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
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class OclIcd(AutotoolsPackage): """This package aims at creating an Open Source alternative to vendor specific OpenCL ICD loaders.""" homepage = "https://github.com/OCL-dev/ocl-icd" url = "https://github.com/OCL-dev/ocl-icd/archive/v2.2.12.tar.gz" version('2.2.13', sha256='f85d59f3e8327f15637b91e4ae8df0829e94daeff68c647b2927b8376b1f8d92') version('2.2.12', sha256='17500e5788304eef5b52dbe784cec197bdae64e05eecf38317840d2d05484272') version('2.2.11', sha256='c1865ef7701b8201ebc6930ed3ac757c7e5cb30f3aa4c1e742a6bc022f4f2292') version('2.2.10', sha256='d0459fa1421e8d86aaf0a4df092185ea63bc4e1a7682d3af261ae5d3fae063c7') version('2.2.9', sha256='88da749bc2bd75149f0bb6e72eb4a9d74401a54f4508bc730f13cc03c57a17ed') version('2.2.8', sha256='8a8a405c7d659b905757a358dc467f4aa3d7e4dff1d1624779065764d962a246') version('2.2.7', sha256='b8e68435904e1a95661c385f24d6924ed28f416985c6db5a3c7448698ad5fea2') version('2.2.6', sha256='4567cae92f58c1d6ecfc771c456fa95f206d8a5c7c5d6c9010ec688a9fd83750') version('2.2.5', sha256='50bf51f4544f83e69a5a2f564732a2adca63fbe9511430aba12f8d6f3a53ae59') version('2.2.4', sha256='92853137ffff393cc74f829357fdd80ac46a82b46c970e80195db86164cca316') version('2.2.3', sha256='46b8355d90f8cc240555e4e077f223c47b950abeadf3e1af52d6e68d2efc2ff3') variant("headers", default=False, description="Install also OpenCL headers to use this as OpenCL provider") depends_on('autoconf', type='build') depends_on('automake', type='build') depends_on('libtool', type='build') depends_on('m4', type='build') depends_on('ruby', type='build') depends_on('asciidoc-py3', type='build') depends_on('xmlto', type='build') depends_on('[email protected]:', when='+headers') provides('opencl@:2.2', when='@2.2.12:+headers') provides('opencl@:2.1', when='@2.2.8:2.2.11+headers') provides('opencl@:2.0', when='@2.2.3:2.2.7+headers') def flag_handler(self, name, flags): if name == 'cflags' and self.spec.satisfies('@:2.2.12'): # https://github.com/OCL-dev/ocl-icd/issues/8 # this is fixed in version grater than 2.2.12 flags.append('-O2') # gcc-10 change the default from -fcommon to fno-common # This is fixed in versions greater than 2.2.12: # https://github.com/OCL-dev/ocl-icd/commit/4667bddd365bcc1dc66c483835971f0083b44b1d if self.spec.satisfies('%gcc@10:'):
return (flags, None, None)
flags.append('-fcommon')
conditional_block
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class OclIcd(AutotoolsPackage): """This package aims at creating an Open Source alternative to vendor specific OpenCL ICD loaders.""" homepage = "https://github.com/OCL-dev/ocl-icd" url = "https://github.com/OCL-dev/ocl-icd/archive/v2.2.12.tar.gz" version('2.2.13', sha256='f85d59f3e8327f15637b91e4ae8df0829e94daeff68c647b2927b8376b1f8d92') version('2.2.12', sha256='17500e5788304eef5b52dbe784cec197bdae64e05eecf38317840d2d05484272') version('2.2.11', sha256='c1865ef7701b8201ebc6930ed3ac757c7e5cb30f3aa4c1e742a6bc022f4f2292') version('2.2.10', sha256='d0459fa1421e8d86aaf0a4df092185ea63bc4e1a7682d3af261ae5d3fae063c7') version('2.2.9', sha256='88da749bc2bd75149f0bb6e72eb4a9d74401a54f4508bc730f13cc03c57a17ed') version('2.2.8', sha256='8a8a405c7d659b905757a358dc467f4aa3d7e4dff1d1624779065764d962a246') version('2.2.7', sha256='b8e68435904e1a95661c385f24d6924ed28f416985c6db5a3c7448698ad5fea2') version('2.2.6', sha256='4567cae92f58c1d6ecfc771c456fa95f206d8a5c7c5d6c9010ec688a9fd83750') version('2.2.5', sha256='50bf51f4544f83e69a5a2f564732a2adca63fbe9511430aba12f8d6f3a53ae59') version('2.2.4', sha256='92853137ffff393cc74f829357fdd80ac46a82b46c970e80195db86164cca316') version('2.2.3', sha256='46b8355d90f8cc240555e4e077f223c47b950abeadf3e1af52d6e68d2efc2ff3') variant("headers", default=False, description="Install also OpenCL headers to use this as OpenCL provider") depends_on('autoconf', type='build') depends_on('automake', type='build') depends_on('libtool', type='build') depends_on('m4', type='build') depends_on('ruby', type='build') depends_on('asciidoc-py3', type='build') depends_on('xmlto', type='build') depends_on('[email protected]:', when='+headers') provides('opencl@:2.2', when='@2.2.12:+headers') provides('opencl@:2.1', when='@2.2.8:2.2.11+headers') provides('opencl@:2.0', when='@2.2.3:2.2.7+headers') def flag_handler(self, name, flags):
if name == 'cflags' and self.spec.satisfies('@:2.2.12'): # https://github.com/OCL-dev/ocl-icd/issues/8 # this is fixed in version grater than 2.2.12 flags.append('-O2') # gcc-10 change the default from -fcommon to fno-common # This is fixed in versions greater than 2.2.12: # https://github.com/OCL-dev/ocl-icd/commit/4667bddd365bcc1dc66c483835971f0083b44b1d if self.spec.satisfies('%gcc@10:'): flags.append('-fcommon') return (flags, None, None)
identifier_body
QuerySubject.ts
import {Subject} from "rxjs"; import {IEntity, IEntityQuery} from "querydsl-typescript"; import {Subscribable} from "rxjs/Observable"; import {Subscription, ISubscription, TeardownLogic} from "rxjs/Subscription"; import {PartialObserver} from "rxjs/Observer"; /** * Created by shamsutdinov.artem on 8/8/2016. */ export class QuerySubject<E, IE extends IEntity> implements Subscribable<E[]> { querySubject: Subject<IEntityQuery<IE>> = new Subject<IEntityQuery<IE>>(); resultsSubject: Subject<E[]> = new Subject<E[]>(); constructor( private resultsUnsubscribeCallback: () => void ) { } next(ieq: IEntityQuery<IE>) { this.querySubject.next(ieq); } subscribe( observerOrNext?: PartialObserver<E[]> | ((value: E[]) => void), error?: (error: any) => void, complete?: () => void ): ISubscription { let subscription = this.resultsSubject.subscribe(observerOrNext); let resultsSubscription = new ResultsSubscription(subscription, this.resultsUnsubscribeCallback); return resultsSubscription; } } export class QueryOneSubject<E, IE extends IEntity> implements Subscribable<E> { querySubject: Subject<IEntityQuery<IE>> = new Subject<IEntityQuery<IE>>(); resultsSubject: Subject<E> = new Subject<E>(); constructor( private resultsUnsubscribeCallback: () => void ) { } next(ieq: IEntityQuery<IE>) { this.querySubject.next(ieq); }
let subscription = this.resultsSubject.subscribe(observerOrNext); let resultsSubscription = new ResultsSubscription(subscription, this.resultsUnsubscribeCallback); return resultsSubscription; } } export class ResultsSubscription implements Subscription { constructor( public subscription: Subscription, private onUnsubscribe: ()=>void ) { } unsubscribe(): void { this.subscription.unsubscribe(); this.onUnsubscribe(); } get closed(): boolean { return this.subscription.closed; } set closed(newClosed: boolean) { this.subscription.closed = newClosed; } add(teardown: TeardownLogic): Subscription { return this.subscription.add(teardown); } remove(sub: Subscription): void { this.subscription.remove(sub); } }
subscribe(observerOrNext?: PartialObserver<E> | ((value: E) => void), error?: (error: any) => void, complete?: () => void): ISubscription {
random_line_split
QuerySubject.ts
import {Subject} from "rxjs"; import {IEntity, IEntityQuery} from "querydsl-typescript"; import {Subscribable} from "rxjs/Observable"; import {Subscription, ISubscription, TeardownLogic} from "rxjs/Subscription"; import {PartialObserver} from "rxjs/Observer"; /** * Created by shamsutdinov.artem on 8/8/2016. */ export class QuerySubject<E, IE extends IEntity> implements Subscribable<E[]> { querySubject: Subject<IEntityQuery<IE>> = new Subject<IEntityQuery<IE>>(); resultsSubject: Subject<E[]> = new Subject<E[]>(); constructor( private resultsUnsubscribeCallback: () => void )
next(ieq: IEntityQuery<IE>) { this.querySubject.next(ieq); } subscribe( observerOrNext?: PartialObserver<E[]> | ((value: E[]) => void), error?: (error: any) => void, complete?: () => void ): ISubscription { let subscription = this.resultsSubject.subscribe(observerOrNext); let resultsSubscription = new ResultsSubscription(subscription, this.resultsUnsubscribeCallback); return resultsSubscription; } } export class QueryOneSubject<E, IE extends IEntity> implements Subscribable<E> { querySubject: Subject<IEntityQuery<IE>> = new Subject<IEntityQuery<IE>>(); resultsSubject: Subject<E> = new Subject<E>(); constructor( private resultsUnsubscribeCallback: () => void ) { } next(ieq: IEntityQuery<IE>) { this.querySubject.next(ieq); } subscribe(observerOrNext?: PartialObserver<E> | ((value: E) => void), error?: (error: any) => void, complete?: () => void): ISubscription { let subscription = this.resultsSubject.subscribe(observerOrNext); let resultsSubscription = new ResultsSubscription(subscription, this.resultsUnsubscribeCallback); return resultsSubscription; } } export class ResultsSubscription implements Subscription { constructor( public subscription: Subscription, private onUnsubscribe: ()=>void ) { } unsubscribe(): void { this.subscription.unsubscribe(); this.onUnsubscribe(); } get closed(): boolean { return this.subscription.closed; } set closed(newClosed: boolean) { this.subscription.closed = newClosed; } add(teardown: TeardownLogic): Subscription { return this.subscription.add(teardown); } remove(sub: Subscription): void { this.subscription.remove(sub); } }
{ }
identifier_body
QuerySubject.ts
import {Subject} from "rxjs"; import {IEntity, IEntityQuery} from "querydsl-typescript"; import {Subscribable} from "rxjs/Observable"; import {Subscription, ISubscription, TeardownLogic} from "rxjs/Subscription"; import {PartialObserver} from "rxjs/Observer"; /** * Created by shamsutdinov.artem on 8/8/2016. */ export class QuerySubject<E, IE extends IEntity> implements Subscribable<E[]> { querySubject: Subject<IEntityQuery<IE>> = new Subject<IEntityQuery<IE>>(); resultsSubject: Subject<E[]> = new Subject<E[]>(); constructor( private resultsUnsubscribeCallback: () => void ) { } next(ieq: IEntityQuery<IE>) { this.querySubject.next(ieq); } subscribe( observerOrNext?: PartialObserver<E[]> | ((value: E[]) => void), error?: (error: any) => void, complete?: () => void ): ISubscription { let subscription = this.resultsSubject.subscribe(observerOrNext); let resultsSubscription = new ResultsSubscription(subscription, this.resultsUnsubscribeCallback); return resultsSubscription; } } export class QueryOneSubject<E, IE extends IEntity> implements Subscribable<E> { querySubject: Subject<IEntityQuery<IE>> = new Subject<IEntityQuery<IE>>(); resultsSubject: Subject<E> = new Subject<E>(); constructor( private resultsUnsubscribeCallback: () => void ) { } next(ieq: IEntityQuery<IE>) { this.querySubject.next(ieq); } subscribe(observerOrNext?: PartialObserver<E> | ((value: E) => void), error?: (error: any) => void, complete?: () => void): ISubscription { let subscription = this.resultsSubject.subscribe(observerOrNext); let resultsSubscription = new ResultsSubscription(subscription, this.resultsUnsubscribeCallback); return resultsSubscription; } } export class ResultsSubscription implements Subscription {
( public subscription: Subscription, private onUnsubscribe: ()=>void ) { } unsubscribe(): void { this.subscription.unsubscribe(); this.onUnsubscribe(); } get closed(): boolean { return this.subscription.closed; } set closed(newClosed: boolean) { this.subscription.closed = newClosed; } add(teardown: TeardownLogic): Subscription { return this.subscription.add(teardown); } remove(sub: Subscription): void { this.subscription.remove(sub); } }
constructor
identifier_name
GeometryFactory.js
/* Copyright (c) 2011 by The Authors. * Published under the LGPL 2.1 license. * See /license-notice.txt for the full text of the license notice. * See /license.txt for the full text of the license. */ /** * Supplies a set of utility methods for building Geometry objects from lists * of Coordinates. * * Note that the factory constructor methods do <b>not</b> change the input * coordinates in any way. * * In particular, they are not rounded to the supplied <tt>PrecisionModel</tt>. * It is assumed that input Coordinates meet the given precision. */ /** * @requires jsts/geom/PrecisionModel.js */ /** * Constructs a GeometryFactory that generates Geometries having a floating * PrecisionModel and a spatial-reference ID of 0. * * @constructor */ jsts.geom.GeometryFactory = function(precisionModel) { this.precisionModel = precisionModel || new jsts.geom.PrecisionModel(); }; jsts.geom.GeometryFactory.prototype.precisionModel = null; jsts.geom.GeometryFactory.prototype.getPrecisionModel = function() { return this.precisionModel; }; /** * Creates a Point using the given Coordinate; a null Coordinate will create an * empty Geometry. * * @param {Coordinate} * coordinate Coordinate to base this Point on. * @return {Point} A new Point. */ jsts.geom.GeometryFactory.prototype.createPoint = function(coordinate) { var point = new jsts.geom.Point(coordinate, this); return point; }; /** * Creates a LineString using the given Coordinates; a null or empty array will * create an empty LineString. Consecutive points must not be equal. * * @param {Coordinate[]} * coordinates an array without null elements, or an empty array, or * null. * @return {LineString} A new LineString. */ jsts.geom.GeometryFactory.prototype.createLineString = function(coordinates) { var lineString = new jsts.geom.LineString(coordinates, this); return lineString; }; /** * Creates a LinearRing using the given Coordinates; a null or empty array will * create an empty LinearRing. The points must form a closed and simple * linestring. Consecutive points must not be equal. * * @param {Coordinate[]} * coordinates an array without null elements, or an empty array, or * null. * @return {LinearRing} A new LinearRing. */ jsts.geom.GeometryFactory.prototype.createLinearRing = function(coordinates) { var linearRing = new jsts.geom.LinearRing(coordinates, this); return linearRing; }; /** * Constructs a <code>Polygon</code> with the given exterior boundary and * interior boundaries. * * @param {LinearRing} * shell the outer boundary of the new <code>Polygon</code>, or * <code>null</code> or an empty <code>LinearRing</code> if the * empty geometry is to be created. * @param {LinearRing[]} * holes the inner boundaries of the new <code>Polygon</code>, or * <code>null</code> or empty <code>LinearRing</code> s if the * empty geometry is to be created. * @return {Polygon} A new Polygon. */ jsts.geom.GeometryFactory.prototype.createPolygon = function(shell, holes) { var polygon = new jsts.geom.Polygon(shell, holes, this); return polygon; }; jsts.geom.GeometryFactory.prototype.createMultiPoint = function(points) { if (points && points[0] instanceof jsts.geom.Coordinate) { var converted = []; var i; for (i = 0; i < points.length; i++) { converted.push(this.createPoint(points[i])); } points = converted; } return new jsts.geom.MultiPoint(points, this); }; jsts.geom.GeometryFactory.prototype.createMultiLineString = function( lineStrings) { return new jsts.geom.MultiLineString(lineStrings, this); }; jsts.geom.GeometryFactory.prototype.createMultiPolygon = function(polygons) { return new jsts.geom.MultiPolygon(polygons, this); }; /** * Build an appropriate <code>Geometry</code>, <code>MultiGeometry</code>, * or <code>GeometryCollection</code> to contain the <code>Geometry</code>s * in it. For example:<br> * * <ul> * <li> If <code>geomList</code> contains a single <code>Polygon</code>, * the <code>Polygon</code> is returned. * <li> If <code>geomList</code> contains several <code>Polygon</code>s, a * <code>MultiPolygon</code> is returned. * <li> If <code>geomList</code> contains some <code>Polygon</code>s and * some <code>LineString</code>s, a <code>GeometryCollection</code> is * returned. * <li> If <code>geomList</code> is empty, an empty * <code>GeometryCollection</code> is returned * </ul> * * Note that this method does not "flatten" Geometries in the input, and hence
* containing them will be returned. * * @param geomList * the <code>Geometry</code>s to combine. * @return {Geometry} a <code>Geometry</code> of the "smallest", "most * type-specific" class that can contain the elements of * <code>geomList</code> . */ jsts.geom.GeometryFactory.prototype.buildGeometry = function(geomList) { /** * Determine some facts about the geometries in the list */ var geomClass = null; var isHeterogeneous = false; var hasGeometryCollection = false; for (var i = geomList.iterator(); i.hasNext();) { var geom = i.next(); var partClass = geom.CLASS_NAME; if (geomClass === null) { geomClass = partClass; } if (!(partClass === geomClass)) { isHeterogeneous = true; } if (geom.isGeometryCollectionBase()) hasGeometryCollection = true; } /** * Now construct an appropriate geometry to return */ // for the empty geometry, return an empty GeometryCollection if (geomClass === null) { return this.createGeometryCollection(null); } if (isHeterogeneous || hasGeometryCollection) { return this.createGeometryCollection(geomList.toArray()); } // at this point we know the collection is hetereogenous. // Determine the type of the result from the first Geometry in the list // this should always return a geometry, since otherwise an empty collection // would have already been returned var geom0 = geomList.get(0); var isCollection = geomList.size() > 1; if (isCollection) { if (geom0 instanceof jsts.geom.Polygon) { return this.createMultiPolygon(geomList.toArray()); } else if (geom0 instanceof jsts.geom.LineString) { return this.createMultiLineString(geomList.toArray()); } else if (geom0 instanceof jsts.geom.Point) { return this.createMultiPoint(geomList.toArray()); } jsts.util.Assert.shouldNeverReachHere('Unhandled class: ' + geom0); } return geom0; }; jsts.geom.GeometryFactory.prototype.createGeometryCollection = function( geometries) { return new jsts.geom.GeometryCollection(geometries, this); }; /** * Creates a {@link Geometry} with the same extent as the given envelope. The * Geometry returned is guaranteed to be valid. To provide this behaviour, the * following cases occur: * <p> * If the <code>Envelope</code> is: * <ul> * <li>null : returns an empty {@link Point} * <li>a point : returns a non-empty {@link Point} * <li>a line : returns a two-point {@link LineString} * <li>a rectangle : returns a {@link Polygon}> whose points are (minx, miny), * (minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny). * </ul> * * @param {jsts.geom.Envelope} * envelope the <code>Envelope</code> to convert. * @return {jsts.geom.Geometry} an empty <code>Point</code> (for null * <code>Envelope</code>s), a <code>Point</code> (when min x = max * x and min y = max y) or a <code>Polygon</code> (in all other cases). */ jsts.geom.GeometryFactory.prototype.toGeometry = function(envelope) { // null envelope - return empty point geometry if (envelope.isNull()) { return this.createPoint(null); } // point? if (envelope.getMinX() === envelope.getMaxX() && envelope.getMinY() === envelope.getMaxY()) { return this.createPoint(new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY())); } // vertical or horizontal line? if (envelope.getMinX() === envelope.getMaxX() || envelope.getMinY() === envelope.getMaxY()) { return this.createLineString([ new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMaxY())]); } // create a CW ring for the polygon return this.createPolygon(this.createLinearRing([ new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMaxY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMaxY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY())]), null); };
* if any MultiGeometries are contained in the input a GeometryCollection
random_line_split
actionCell.js
/** * Created by Daniel on 9/12/2016. */ //Template events Template.payslipActionCell.events({ "click .send-email-button": function (event, temp) { Meteor.call("sendPayslip",$(event.currentTarget).attr("data-payslip-id"), function(err,res){ if(!err){ // Payslips.update({_id:res},{$set: { status: 'SENT' }}); Payslips.remove({_id:res}); FlashMessages.sendSuccess("The Payslip has been sent successfully.", {autoHide: true, hideDelay: 5000}); } }); }, "click .resend-email-button": function (event, temp) { Meteor.call("sendPayslip",$(event.currentTarget).attr("data-payslip-id"), function(err,res){ if(!err){ Payslips.remove({_id:res}); FlashMessages.sendSuccess("The Payslip has been re-sent successfully.", {autoHide: true, hideDelay: 5000}); } }); }, }); Template.payslipActionCell.helpers({ payslip: function () { return this; }, isNewPayslip: function(){ return (this.status === 'NEW')?true:false; }, onError: function () { return function (error) { alert("Error on deleting!"); console.log(error); }; }, onSuccess: function () { return function (result) { alert("Deleted!"); }; }, beforeRemove: function () { return function (collection, id) { var doc = collection.findOne(id); if (confirm('Really delete question "' + doc.name + '"?')) {
});
this.remove(); } }; }
random_line_split
actionCell.js
/** * Created by Daniel on 9/12/2016. */ //Template events Template.payslipActionCell.events({ "click .send-email-button": function (event, temp) { Meteor.call("sendPayslip",$(event.currentTarget).attr("data-payslip-id"), function(err,res){ if(!err){ // Payslips.update({_id:res},{$set: { status: 'SENT' }}); Payslips.remove({_id:res}); FlashMessages.sendSuccess("The Payslip has been sent successfully.", {autoHide: true, hideDelay: 5000}); } }); }, "click .resend-email-button": function (event, temp) { Meteor.call("sendPayslip",$(event.currentTarget).attr("data-payslip-id"), function(err,res){ if(!err){ Payslips.remove({_id:res}); FlashMessages.sendSuccess("The Payslip has been re-sent successfully.", {autoHide: true, hideDelay: 5000}); } }); }, }); Template.payslipActionCell.helpers({ payslip: function () { return this; }, isNewPayslip: function(){ return (this.status === 'NEW')?true:false; }, onError: function () { return function (error) { alert("Error on deleting!"); console.log(error); }; }, onSuccess: function () { return function (result) { alert("Deleted!"); }; }, beforeRemove: function () { return function (collection, id) { var doc = collection.findOne(id); if (confirm('Really delete question "' + doc.name + '"?'))
}; } });
{ this.remove(); }
conditional_block
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().parse::<i32>().unwrap(), parts.get(1).unwrap().parse::<i32>().unwrap(), ) }) .collect() } fn find_bounds(points: &Vec<Point>) -> ((i32, i32), (i32, i32)) { let min_x = points.into_iter().map(|x| x.0).min().unwrap(); let max_x = points.into_iter().map(|x| x.0).max().unwrap(); let min_y = points.into_iter().map(|x| x.1).min().unwrap(); let max_y = points.into_iter().map(|x| x.1).max().unwrap(); ((min_x, min_y), (max_x, max_y)) } fn region_within(input: String, n: i32) -> i32 { let points = &input_points(input); let ((min_x, min_y), (max_x, max_y)) = find_bounds(points); let mut count = 0; for x in min_x..=max_x { for y in min_y..=max_y { let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n { count += 1; } } } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn test_06b()
{ let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
identifier_body
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().parse::<i32>().unwrap(), parts.get(1).unwrap().parse::<i32>().unwrap(), ) }) .collect() } fn find_bounds(points: &Vec<Point>) -> ((i32, i32), (i32, i32)) { let min_x = points.into_iter().map(|x| x.0).min().unwrap(); let max_x = points.into_iter().map(|x| x.0).max().unwrap(); let min_y = points.into_iter().map(|x| x.1).min().unwrap(); let max_y = points.into_iter().map(|x| x.1).max().unwrap(); ((min_x, min_y), (max_x, max_y)) } fn region_within(input: String, n: i32) -> i32 { let points = &input_points(input); let ((min_x, min_y), (max_x, max_y)) = find_bounds(points); let mut count = 0; for x in min_x..=max_x { for y in min_y..=max_y { let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n
} } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn test_06b() { let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
{ count += 1; }
conditional_block
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().parse::<i32>().unwrap(), parts.get(1).unwrap().parse::<i32>().unwrap(), ) }) .collect() } fn find_bounds(points: &Vec<Point>) -> ((i32, i32), (i32, i32)) { let min_x = points.into_iter().map(|x| x.0).min().unwrap(); let max_x = points.into_iter().map(|x| x.0).max().unwrap(); let min_y = points.into_iter().map(|x| x.1).min().unwrap(); let max_y = points.into_iter().map(|x| x.1).max().unwrap(); ((min_x, min_y), (max_x, max_y)) } fn region_within(input: String, n: i32) -> i32 { let points = &input_points(input); let ((min_x, min_y), (max_x, max_y)) = find_bounds(points); let mut count = 0;
let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n { count += 1; } } } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn test_06b() { let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
for x in min_x..=max_x { for y in min_y..=max_y {
random_line_split
06b.rs
type Point = (i32, i32); fn distance(a: Point, b: Point) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn input_points(input: String) -> Vec<Point> { input .split("\n") .map(|x| { let parts: Vec<_> = x.split(", ").collect(); ( parts.get(0).unwrap().parse::<i32>().unwrap(), parts.get(1).unwrap().parse::<i32>().unwrap(), ) }) .collect() } fn find_bounds(points: &Vec<Point>) -> ((i32, i32), (i32, i32)) { let min_x = points.into_iter().map(|x| x.0).min().unwrap(); let max_x = points.into_iter().map(|x| x.0).max().unwrap(); let min_y = points.into_iter().map(|x| x.1).min().unwrap(); let max_y = points.into_iter().map(|x| x.1).max().unwrap(); ((min_x, min_y), (max_x, max_y)) } fn region_within(input: String, n: i32) -> i32 { let points = &input_points(input); let ((min_x, min_y), (max_x, max_y)) = find_bounds(points); let mut count = 0; for x in min_x..=max_x { for y in min_y..=max_y { let total_distance: i32 = points.into_iter().map(|p| distance((x, y), *p)).sum(); if total_distance < n { count += 1; } } } count } fn main() { println!("{}", region_within(include_str!("input.txt").into(), 10000)); } #[test] fn
() { let input = vec!["1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9"]; let result = region_within(input.join("\n").into(), 32); assert_eq!(result, 16); }
test_06b
identifier_name
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) } ClusterBootstrapped(cluster_id: u64) { display("cluster {} is already bootstrapped", cluster_id) } ClusterNotBootstrapped(cluster_id: u64) { display("cluster {} is not bootstrapped", cluster_id) } Incompatible { display("feature is not supported in other cluster components") } Grpc(err: grpcio::Error) { from() cause(err) display("{}", err) } Other(err: Box<dyn error::Error + Sync + Send>) { from() cause(err.as_ref()) display("unknown error {:?}", err) } RegionNotFound(key: Vec<u8>) { display("region is not found for key {}", &log_wrappers::Value::key(key)) } StoreTombstone(msg: String) { display("store is tombstone {:?}", msg) } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn error_code(&self) -> ErrorCode
}
{ match self { Error::Io(_) => error_code::pd::IO, Error::ClusterBootstrapped(_) => error_code::pd::CLUSTER_BOOTSTRAPPED, Error::ClusterNotBootstrapped(_) => error_code::pd::CLUSTER_NOT_BOOTSTRAPPED, Error::Incompatible => error_code::pd::INCOMPATIBLE, Error::Grpc(_) => error_code::pd::GRPC, Error::RegionNotFound(_) => error_code::pd::REGION_NOT_FOUND, Error::StoreTombstone(_) => error_code::pd::STORE_TOMBSTONE, Error::Other(_) => error_code::pd::UNKNOWN, } }
identifier_body
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) } ClusterBootstrapped(cluster_id: u64) { display("cluster {} is already bootstrapped", cluster_id) } ClusterNotBootstrapped(cluster_id: u64) { display("cluster {} is not bootstrapped", cluster_id) } Incompatible { display("feature is not supported in other cluster components") } Grpc(err: grpcio::Error) { from() cause(err) display("{}", err) } Other(err: Box<dyn error::Error + Sync + Send>) { from() cause(err.as_ref()) display("unknown error {:?}", err) } RegionNotFound(key: Vec<u8>) { display("region is not found for key {}", &log_wrappers::Value::key(key)) } StoreTombstone(msg: String) { display("store is tombstone {:?}", msg) } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn
(&self) -> ErrorCode { match self { Error::Io(_) => error_code::pd::IO, Error::ClusterBootstrapped(_) => error_code::pd::CLUSTER_BOOTSTRAPPED, Error::ClusterNotBootstrapped(_) => error_code::pd::CLUSTER_NOT_BOOTSTRAPPED, Error::Incompatible => error_code::pd::INCOMPATIBLE, Error::Grpc(_) => error_code::pd::GRPC, Error::RegionNotFound(_) => error_code::pd::REGION_NOT_FOUND, Error::StoreTombstone(_) => error_code::pd::STORE_TOMBSTONE, Error::Other(_) => error_code::pd::UNKNOWN, } } }
error_code
identifier_name
errors.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use std::error; use std::result; quick_error! { #[derive(Debug)] pub enum Error { Io(err: std::io::Error) { from() cause(err) display("{}", err) } ClusterBootstrapped(cluster_id: u64) { display("cluster {} is already bootstrapped", cluster_id) } ClusterNotBootstrapped(cluster_id: u64) { display("cluster {} is not bootstrapped", cluster_id) } Incompatible { display("feature is not supported in other cluster components") } Grpc(err: grpcio::Error) { from() cause(err) display("{}", err) }
display("unknown error {:?}", err) } RegionNotFound(key: Vec<u8>) { display("region is not found for key {}", &log_wrappers::Value::key(key)) } StoreTombstone(msg: String) { display("store is tombstone {:?}", msg) } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn error_code(&self) -> ErrorCode { match self { Error::Io(_) => error_code::pd::IO, Error::ClusterBootstrapped(_) => error_code::pd::CLUSTER_BOOTSTRAPPED, Error::ClusterNotBootstrapped(_) => error_code::pd::CLUSTER_NOT_BOOTSTRAPPED, Error::Incompatible => error_code::pd::INCOMPATIBLE, Error::Grpc(_) => error_code::pd::GRPC, Error::RegionNotFound(_) => error_code::pd::REGION_NOT_FOUND, Error::StoreTombstone(_) => error_code::pd::STORE_TOMBSTONE, Error::Other(_) => error_code::pd::UNKNOWN, } } }
Other(err: Box<dyn error::Error + Sync + Send>) { from() cause(err.as_ref())
random_line_split
environment-list.js
/*! * Copyright 2017, Digital Reasoning
* * 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. * */ define([ 'jquery', 'generics/pagination', 'models/environment' ], function ($, Pagination, Environment) { 'use strict'; return Pagination.extend({ breadcrumbs: [ { active: true, title: 'Environments' } ], model: Environment, baseUrl: '/environments/', initialUrl: '/api/environments/', detailRequiresAdvanced: true, sortableFields: [ {name: 'name', displayName: 'Name', width: '20%'}, {name: 'description', displayName: 'Description', width: '35%'}, {name: 'labelList', displayName: 'Labels', width: '15%'}, {name: 'activity', displayName: 'Activity', width: '10%'}, {name: 'health', displayName: 'Health', width: '10%'} ], openActionEnvironmentId: null, actionMap: {}, reset: function() { this.openActionEnvironmentId = null; this.actionMap = {}; this._super(); }, processObject: function (environment) { if (this.actionMap.hasOwnProperty(environment.id)) { environment.availableActions(this.actionMap[environment.id]); } }, extraReloadSteps: function () { // Add the dropdown events. This must happen AFTER we set the environments observable // in the previous statement. var actionElement = $('.action-dropdown'); var self = this; // React to an open-dropdown event actionElement.on('show.bs.dropdown', function (evt) { // Grab the ID of the open element var id = evt.target.id; // Set the ID of the currently open action dropdown self.openActionEnvironmentId = id; // Freeze a copy of the current environments var environments = self.objects(); // Find the current environment with the correct ID, and load the actions for (var i = 0, length = environments.length; i < length; ++i) { if (environments[i].id === id) { environments[i].loadAvailableActions(); break; } } }); // React to a close dropdown event (this one is pretty simple) actionElement.on('hide.bs.dropdown', function () { // Make sure that we know nothing is open self.openActionEnvironmentId = null; }); } }); });
* * 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
random_line_split
environment-list.js
/*! * Copyright 2017, Digital Reasoning * * 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. * */ define([ 'jquery', 'generics/pagination', 'models/environment' ], function ($, Pagination, Environment) { 'use strict'; return Pagination.extend({ breadcrumbs: [ { active: true, title: 'Environments' } ], model: Environment, baseUrl: '/environments/', initialUrl: '/api/environments/', detailRequiresAdvanced: true, sortableFields: [ {name: 'name', displayName: 'Name', width: '20%'}, {name: 'description', displayName: 'Description', width: '35%'}, {name: 'labelList', displayName: 'Labels', width: '15%'}, {name: 'activity', displayName: 'Activity', width: '10%'}, {name: 'health', displayName: 'Health', width: '10%'} ], openActionEnvironmentId: null, actionMap: {}, reset: function() { this.openActionEnvironmentId = null; this.actionMap = {}; this._super(); }, processObject: function (environment) { if (this.actionMap.hasOwnProperty(environment.id)) { environment.availableActions(this.actionMap[environment.id]); } }, extraReloadSteps: function () { // Add the dropdown events. This must happen AFTER we set the environments observable // in the previous statement. var actionElement = $('.action-dropdown'); var self = this; // React to an open-dropdown event actionElement.on('show.bs.dropdown', function (evt) { // Grab the ID of the open element var id = evt.target.id; // Set the ID of the currently open action dropdown self.openActionEnvironmentId = id; // Freeze a copy of the current environments var environments = self.objects(); // Find the current environment with the correct ID, and load the actions for (var i = 0, length = environments.length; i < length; ++i)
}); // React to a close dropdown event (this one is pretty simple) actionElement.on('hide.bs.dropdown', function () { // Make sure that we know nothing is open self.openActionEnvironmentId = null; }); } }); });
{ if (environments[i].id === id) { environments[i].loadAvailableActions(); break; } }
conditional_block
bs-lessdoc-parser.js
/*! * Bootstrap Grunt task for parsing Less docstrings * http://getbootstrap.com * Copyright 2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ 'use strict'; var Markdown = require('markdown-it'); function markdown2html(markdownString) { var md = new Markdown(); // the slice removes the <p>...</p> wrapper output by Markdown processor return md.render(markdownString.trim()).slice(3, -5); } /* Mini-language: //== This is a normal heading, which starts a section. Sections group variables together. //## Optional description for the heading //=== This is a subheading. //** Optional description for the following variable. You **can** use Markdown in descriptions to discuss `<html>` stuff. @foo: #fff; //-- This is a heading for a section whose variables shouldn't be customizable All other lines are ignored completely. */ var CUSTOMIZABLE_HEADING = /^[/]{2}={2}(.*)$/; var UNCUSTOMIZABLE_HEADING = /^[/]{2}-{2}(.*)$/; var SUBSECTION_HEADING = /^[/]{2}={3}(.*)$/; var SECTION_DOCSTRING = /^[/]{2}#{2}(.+)$/; var VAR_ASSIGNMENT = /^(@[a-zA-Z0-9_-]+):[ ]*([^ ;][^;]*);[ ]*$/; var VAR_DOCSTRING = /^[/]{2}[*]{2}(.+)$/; function Section(heading, customizable) { this.heading = heading.trim(); this.id = this.heading.replace(/\s+/g, '-').toLowerCase(); this.customizable = customizable; this.docstring = null; this.subsections = []; } Section.prototype.addSubSection = function (subsection) { this.subsections.push(subsection); }; function SubSection(heading) { this.heading = heading.trim(); this.id = this.heading.replace(/\s+/g, '-').toLowerCase(); this.variables = []; } SubSection.prototype.addVar = function (variable) { this.variables.push(variable); }; function VarDocstring(markdownString)
function SectionDocstring(markdownString) { this.php = markdown2html(markdownString); } function Variable(name, defaultValue) { this.name = name; this.defaultValue = defaultValue; this.docstring = null; } function Tokenizer(fileContent) { this._lines = fileContent.split('\n'); this._next = undefined; } Tokenizer.prototype.unshift = function (token) { if (this._next !== undefined) { throw new Error('Attempted to unshift twice!'); } this._next = token; }; Tokenizer.prototype._shift = function () { // returning null signals EOF // returning undefined means the line was ignored if (this._next !== undefined) { var result = this._next; this._next = undefined; return result; } if (this._lines.length <= 0) { return null; } var line = this._lines.shift(); var match = null; match = SUBSECTION_HEADING.exec(line); if (match !== null) { return new SubSection(match[1]); } match = CUSTOMIZABLE_HEADING.exec(line); if (match !== null) { return new Section(match[1], true); } match = UNCUSTOMIZABLE_HEADING.exec(line); if (match !== null) { return new Section(match[1], false); } match = SECTION_DOCSTRING.exec(line); if (match !== null) { return new SectionDocstring(match[1]); } match = VAR_DOCSTRING.exec(line); if (match !== null) { return new VarDocstring(match[1]); } var commentStart = line.lastIndexOf('//'); var varLine = (commentStart === -1) ? line : line.slice(0, commentStart); match = VAR_ASSIGNMENT.exec(varLine); if (match !== null) { return new Variable(match[1], match[2]); } return undefined; }; Tokenizer.prototype.shift = function () { while (true) { var result = this._shift(); if (result === undefined) { continue; } return result; } }; function Parser(fileContent) { this._tokenizer = new Tokenizer(fileContent); } Parser.prototype.parseFile = function () { var sections = []; while (true) { var section = this.parseSection(); if (section === null) { if (this._tokenizer.shift() !== null) { throw new Error('Unexpected unparsed section of file remains!'); } return sections; } sections.push(section); } }; Parser.prototype.parseSection = function () { var section = this._tokenizer.shift(); if (section === null) { return null; } if (!(section instanceof Section)) { throw new Error('Expected section heading; got: ' + JSON.stringify(section)); } var docstring = this._tokenizer.shift(); if (docstring instanceof SectionDocstring) { section.docstring = docstring; } else { this._tokenizer.unshift(docstring); } this.parseSubSections(section); return section; }; Parser.prototype.parseSubSections = function (section) { while (true) { var subsection = this.parseSubSection(); if (subsection === null) { if (section.subsections.length === 0) { // Presume an implicit initial subsection subsection = new SubSection(''); this.parseVars(subsection); } else { break; } } section.addSubSection(subsection); } if (section.subsections.length === 1 && !(section.subsections[0].heading) && section.subsections[0].variables.length === 0) { // Ignore lone empty implicit subsection section.subsections = []; } }; Parser.prototype.parseSubSection = function () { var subsection = this._tokenizer.shift(); if (subsection instanceof SubSection) { this.parseVars(subsection); return subsection; } this._tokenizer.unshift(subsection); return null; }; Parser.prototype.parseVars = function (subsection) { while (true) { var variable = this.parseVar(); if (variable === null) { return; } subsection.addVar(variable); } }; Parser.prototype.parseVar = function () { var docstring = this._tokenizer.shift(); if (!(docstring instanceof VarDocstring)) { this._tokenizer.unshift(docstring); docstring = null; } var variable = this._tokenizer.shift(); if (variable instanceof Variable) { variable.docstring = docstring; return variable; } this._tokenizer.unshift(variable); return null; }; module.exports = Parser;
{ this.php = markdown2html(markdownString); }
identifier_body
bs-lessdoc-parser.js
/*! * Bootstrap Grunt task for parsing Less docstrings * http://getbootstrap.com * Copyright 2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ 'use strict'; var Markdown = require('markdown-it'); function markdown2html(markdownString) { var md = new Markdown(); // the slice removes the <p>...</p> wrapper output by Markdown processor return md.render(markdownString.trim()).slice(3, -5); } /* Mini-language: //== This is a normal heading, which starts a section. Sections group variables together. //## Optional description for the heading //=== This is a subheading. //** Optional description for the following variable. You **can** use Markdown in descriptions to discuss `<html>` stuff. @foo: #fff; //-- This is a heading for a section whose variables shouldn't be customizable All other lines are ignored completely. */ var CUSTOMIZABLE_HEADING = /^[/]{2}={2}(.*)$/; var UNCUSTOMIZABLE_HEADING = /^[/]{2}-{2}(.*)$/; var SUBSECTION_HEADING = /^[/]{2}={3}(.*)$/; var SECTION_DOCSTRING = /^[/]{2}#{2}(.+)$/; var VAR_ASSIGNMENT = /^(@[a-zA-Z0-9_-]+):[ ]*([^ ;][^;]*);[ ]*$/; var VAR_DOCSTRING = /^[/]{2}[*]{2}(.+)$/; function Section(heading, customizable) { this.heading = heading.trim(); this.id = this.heading.replace(/\s+/g, '-').toLowerCase(); this.customizable = customizable; this.docstring = null; this.subsections = []; } Section.prototype.addSubSection = function (subsection) { this.subsections.push(subsection); }; function SubSection(heading) { this.heading = heading.trim(); this.id = this.heading.replace(/\s+/g, '-').toLowerCase(); this.variables = []; } SubSection.prototype.addVar = function (variable) { this.variables.push(variable); }; function VarDocstring(markdownString) { this.php = markdown2html(markdownString); } function SectionDocstring(markdownString) { this.php = markdown2html(markdownString); } function Variable(name, defaultValue) { this.name = name; this.defaultValue = defaultValue; this.docstring = null; } function Tokenizer(fileContent) { this._lines = fileContent.split('\n'); this._next = undefined; } Tokenizer.prototype.unshift = function (token) { if (this._next !== undefined) { throw new Error('Attempted to unshift twice!'); } this._next = token; }; Tokenizer.prototype._shift = function () { // returning null signals EOF // returning undefined means the line was ignored if (this._next !== undefined) { var result = this._next; this._next = undefined; return result; } if (this._lines.length <= 0) { return null; } var line = this._lines.shift(); var match = null; match = SUBSECTION_HEADING.exec(line); if (match !== null) { return new SubSection(match[1]); } match = CUSTOMIZABLE_HEADING.exec(line); if (match !== null) { return new Section(match[1], true); } match = UNCUSTOMIZABLE_HEADING.exec(line); if (match !== null) { return new Section(match[1], false); } match = SECTION_DOCSTRING.exec(line); if (match !== null) { return new SectionDocstring(match[1]); } match = VAR_DOCSTRING.exec(line); if (match !== null) { return new VarDocstring(match[1]); } var commentStart = line.lastIndexOf('//'); var varLine = (commentStart === -1) ? line : line.slice(0, commentStart); match = VAR_ASSIGNMENT.exec(varLine); if (match !== null) { return new Variable(match[1], match[2]); } return undefined; }; Tokenizer.prototype.shift = function () { while (true) { var result = this._shift(); if (result === undefined) { continue; } return result; } }; function Parser(fileContent) { this._tokenizer = new Tokenizer(fileContent); } Parser.prototype.parseFile = function () { var sections = []; while (true) { var section = this.parseSection(); if (section === null) { if (this._tokenizer.shift() !== null) { throw new Error('Unexpected unparsed section of file remains!'); } return sections; } sections.push(section); } }; Parser.prototype.parseSection = function () { var section = this._tokenizer.shift(); if (section === null) { return null; } if (!(section instanceof Section)) { throw new Error('Expected section heading; got: ' + JSON.stringify(section)); } var docstring = this._tokenizer.shift(); if (docstring instanceof SectionDocstring) { section.docstring = docstring; } else { this._tokenizer.unshift(docstring); } this.parseSubSections(section); return section; }; Parser.prototype.parseSubSections = function (section) { while (true) { var subsection = this.parseSubSection(); if (subsection === null) { if (section.subsections.length === 0) { // Presume an implicit initial subsection subsection = new SubSection(''); this.parseVars(subsection); } else { break; } } section.addSubSection(subsection); } if (section.subsections.length === 1 && !(section.subsections[0].heading) && section.subsections[0].variables.length === 0) { // Ignore lone empty implicit subsection section.subsections = []; } }; Parser.prototype.parseSubSection = function () { var subsection = this._tokenizer.shift(); if (subsection instanceof SubSection) { this.parseVars(subsection);
return subsection; } this._tokenizer.unshift(subsection); return null; }; Parser.prototype.parseVars = function (subsection) { while (true) { var variable = this.parseVar(); if (variable === null) { return; } subsection.addVar(variable); } }; Parser.prototype.parseVar = function () { var docstring = this._tokenizer.shift(); if (!(docstring instanceof VarDocstring)) { this._tokenizer.unshift(docstring); docstring = null; } var variable = this._tokenizer.shift(); if (variable instanceof Variable) { variable.docstring = docstring; return variable; } this._tokenizer.unshift(variable); return null; }; module.exports = Parser;
random_line_split
bs-lessdoc-parser.js
/*! * Bootstrap Grunt task for parsing Less docstrings * http://getbootstrap.com * Copyright 2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ 'use strict'; var Markdown = require('markdown-it'); function markdown2html(markdownString) { var md = new Markdown(); // the slice removes the <p>...</p> wrapper output by Markdown processor return md.render(markdownString.trim()).slice(3, -5); } /* Mini-language: //== This is a normal heading, which starts a section. Sections group variables together. //## Optional description for the heading //=== This is a subheading. //** Optional description for the following variable. You **can** use Markdown in descriptions to discuss `<html>` stuff. @foo: #fff; //-- This is a heading for a section whose variables shouldn't be customizable All other lines are ignored completely. */ var CUSTOMIZABLE_HEADING = /^[/]{2}={2}(.*)$/; var UNCUSTOMIZABLE_HEADING = /^[/]{2}-{2}(.*)$/; var SUBSECTION_HEADING = /^[/]{2}={3}(.*)$/; var SECTION_DOCSTRING = /^[/]{2}#{2}(.+)$/; var VAR_ASSIGNMENT = /^(@[a-zA-Z0-9_-]+):[ ]*([^ ;][^;]*);[ ]*$/; var VAR_DOCSTRING = /^[/]{2}[*]{2}(.+)$/; function Section(heading, customizable) { this.heading = heading.trim(); this.id = this.heading.replace(/\s+/g, '-').toLowerCase(); this.customizable = customizable; this.docstring = null; this.subsections = []; } Section.prototype.addSubSection = function (subsection) { this.subsections.push(subsection); }; function SubSection(heading) { this.heading = heading.trim(); this.id = this.heading.replace(/\s+/g, '-').toLowerCase(); this.variables = []; } SubSection.prototype.addVar = function (variable) { this.variables.push(variable); }; function VarDocstring(markdownString) { this.php = markdown2html(markdownString); } function SectionDocstring(markdownString) { this.php = markdown2html(markdownString); } function Variable(name, defaultValue) { this.name = name; this.defaultValue = defaultValue; this.docstring = null; } function Tokenizer(fileContent) { this._lines = fileContent.split('\n'); this._next = undefined; } Tokenizer.prototype.unshift = function (token) { if (this._next !== undefined) { throw new Error('Attempted to unshift twice!'); } this._next = token; }; Tokenizer.prototype._shift = function () { // returning null signals EOF // returning undefined means the line was ignored if (this._next !== undefined) { var result = this._next; this._next = undefined; return result; } if (this._lines.length <= 0)
var line = this._lines.shift(); var match = null; match = SUBSECTION_HEADING.exec(line); if (match !== null) { return new SubSection(match[1]); } match = CUSTOMIZABLE_HEADING.exec(line); if (match !== null) { return new Section(match[1], true); } match = UNCUSTOMIZABLE_HEADING.exec(line); if (match !== null) { return new Section(match[1], false); } match = SECTION_DOCSTRING.exec(line); if (match !== null) { return new SectionDocstring(match[1]); } match = VAR_DOCSTRING.exec(line); if (match !== null) { return new VarDocstring(match[1]); } var commentStart = line.lastIndexOf('//'); var varLine = (commentStart === -1) ? line : line.slice(0, commentStart); match = VAR_ASSIGNMENT.exec(varLine); if (match !== null) { return new Variable(match[1], match[2]); } return undefined; }; Tokenizer.prototype.shift = function () { while (true) { var result = this._shift(); if (result === undefined) { continue; } return result; } }; function Parser(fileContent) { this._tokenizer = new Tokenizer(fileContent); } Parser.prototype.parseFile = function () { var sections = []; while (true) { var section = this.parseSection(); if (section === null) { if (this._tokenizer.shift() !== null) { throw new Error('Unexpected unparsed section of file remains!'); } return sections; } sections.push(section); } }; Parser.prototype.parseSection = function () { var section = this._tokenizer.shift(); if (section === null) { return null; } if (!(section instanceof Section)) { throw new Error('Expected section heading; got: ' + JSON.stringify(section)); } var docstring = this._tokenizer.shift(); if (docstring instanceof SectionDocstring) { section.docstring = docstring; } else { this._tokenizer.unshift(docstring); } this.parseSubSections(section); return section; }; Parser.prototype.parseSubSections = function (section) { while (true) { var subsection = this.parseSubSection(); if (subsection === null) { if (section.subsections.length === 0) { // Presume an implicit initial subsection subsection = new SubSection(''); this.parseVars(subsection); } else { break; } } section.addSubSection(subsection); } if (section.subsections.length === 1 && !(section.subsections[0].heading) && section.subsections[0].variables.length === 0) { // Ignore lone empty implicit subsection section.subsections = []; } }; Parser.prototype.parseSubSection = function () { var subsection = this._tokenizer.shift(); if (subsection instanceof SubSection) { this.parseVars(subsection); return subsection; } this._tokenizer.unshift(subsection); return null; }; Parser.prototype.parseVars = function (subsection) { while (true) { var variable = this.parseVar(); if (variable === null) { return; } subsection.addVar(variable); } }; Parser.prototype.parseVar = function () { var docstring = this._tokenizer.shift(); if (!(docstring instanceof VarDocstring)) { this._tokenizer.unshift(docstring); docstring = null; } var variable = this._tokenizer.shift(); if (variable instanceof Variable) { variable.docstring = docstring; return variable; } this._tokenizer.unshift(variable); return null; }; module.exports = Parser;
{ return null; }
conditional_block
bs-lessdoc-parser.js
/*! * Bootstrap Grunt task for parsing Less docstrings * http://getbootstrap.com * Copyright 2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ 'use strict'; var Markdown = require('markdown-it'); function markdown2html(markdownString) { var md = new Markdown(); // the slice removes the <p>...</p> wrapper output by Markdown processor return md.render(markdownString.trim()).slice(3, -5); } /* Mini-language: //== This is a normal heading, which starts a section. Sections group variables together. //## Optional description for the heading //=== This is a subheading. //** Optional description for the following variable. You **can** use Markdown in descriptions to discuss `<html>` stuff. @foo: #fff; //-- This is a heading for a section whose variables shouldn't be customizable All other lines are ignored completely. */ var CUSTOMIZABLE_HEADING = /^[/]{2}={2}(.*)$/; var UNCUSTOMIZABLE_HEADING = /^[/]{2}-{2}(.*)$/; var SUBSECTION_HEADING = /^[/]{2}={3}(.*)$/; var SECTION_DOCSTRING = /^[/]{2}#{2}(.+)$/; var VAR_ASSIGNMENT = /^(@[a-zA-Z0-9_-]+):[ ]*([^ ;][^;]*);[ ]*$/; var VAR_DOCSTRING = /^[/]{2}[*]{2}(.+)$/; function
(heading, customizable) { this.heading = heading.trim(); this.id = this.heading.replace(/\s+/g, '-').toLowerCase(); this.customizable = customizable; this.docstring = null; this.subsections = []; } Section.prototype.addSubSection = function (subsection) { this.subsections.push(subsection); }; function SubSection(heading) { this.heading = heading.trim(); this.id = this.heading.replace(/\s+/g, '-').toLowerCase(); this.variables = []; } SubSection.prototype.addVar = function (variable) { this.variables.push(variable); }; function VarDocstring(markdownString) { this.php = markdown2html(markdownString); } function SectionDocstring(markdownString) { this.php = markdown2html(markdownString); } function Variable(name, defaultValue) { this.name = name; this.defaultValue = defaultValue; this.docstring = null; } function Tokenizer(fileContent) { this._lines = fileContent.split('\n'); this._next = undefined; } Tokenizer.prototype.unshift = function (token) { if (this._next !== undefined) { throw new Error('Attempted to unshift twice!'); } this._next = token; }; Tokenizer.prototype._shift = function () { // returning null signals EOF // returning undefined means the line was ignored if (this._next !== undefined) { var result = this._next; this._next = undefined; return result; } if (this._lines.length <= 0) { return null; } var line = this._lines.shift(); var match = null; match = SUBSECTION_HEADING.exec(line); if (match !== null) { return new SubSection(match[1]); } match = CUSTOMIZABLE_HEADING.exec(line); if (match !== null) { return new Section(match[1], true); } match = UNCUSTOMIZABLE_HEADING.exec(line); if (match !== null) { return new Section(match[1], false); } match = SECTION_DOCSTRING.exec(line); if (match !== null) { return new SectionDocstring(match[1]); } match = VAR_DOCSTRING.exec(line); if (match !== null) { return new VarDocstring(match[1]); } var commentStart = line.lastIndexOf('//'); var varLine = (commentStart === -1) ? line : line.slice(0, commentStart); match = VAR_ASSIGNMENT.exec(varLine); if (match !== null) { return new Variable(match[1], match[2]); } return undefined; }; Tokenizer.prototype.shift = function () { while (true) { var result = this._shift(); if (result === undefined) { continue; } return result; } }; function Parser(fileContent) { this._tokenizer = new Tokenizer(fileContent); } Parser.prototype.parseFile = function () { var sections = []; while (true) { var section = this.parseSection(); if (section === null) { if (this._tokenizer.shift() !== null) { throw new Error('Unexpected unparsed section of file remains!'); } return sections; } sections.push(section); } }; Parser.prototype.parseSection = function () { var section = this._tokenizer.shift(); if (section === null) { return null; } if (!(section instanceof Section)) { throw new Error('Expected section heading; got: ' + JSON.stringify(section)); } var docstring = this._tokenizer.shift(); if (docstring instanceof SectionDocstring) { section.docstring = docstring; } else { this._tokenizer.unshift(docstring); } this.parseSubSections(section); return section; }; Parser.prototype.parseSubSections = function (section) { while (true) { var subsection = this.parseSubSection(); if (subsection === null) { if (section.subsections.length === 0) { // Presume an implicit initial subsection subsection = new SubSection(''); this.parseVars(subsection); } else { break; } } section.addSubSection(subsection); } if (section.subsections.length === 1 && !(section.subsections[0].heading) && section.subsections[0].variables.length === 0) { // Ignore lone empty implicit subsection section.subsections = []; } }; Parser.prototype.parseSubSection = function () { var subsection = this._tokenizer.shift(); if (subsection instanceof SubSection) { this.parseVars(subsection); return subsection; } this._tokenizer.unshift(subsection); return null; }; Parser.prototype.parseVars = function (subsection) { while (true) { var variable = this.parseVar(); if (variable === null) { return; } subsection.addVar(variable); } }; Parser.prototype.parseVar = function () { var docstring = this._tokenizer.shift(); if (!(docstring instanceof VarDocstring)) { this._tokenizer.unshift(docstring); docstring = null; } var variable = this._tokenizer.shift(); if (variable instanceof Variable) { variable.docstring = docstring; return variable; } this._tokenizer.unshift(variable); return null; }; module.exports = Parser;
Section
identifier_name
constant.js
angular.module('material.core') .factory('$mdConstant', MdConstantFactory); /** * Factory function that creates the grab-bag $mdConstant service. * @ngInject */ function
($sniffer) { var webkit = /webkit/i.test($sniffer.vendorPrefix); function vendorProperty(name) { return webkit ? ('webkit' + name.charAt(0).toUpperCase() + name.substring(1)) : name; } return { KEY_CODE: { COMMA: 188, SEMICOLON : 186, ENTER: 13, ESCAPE: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT_ARROW : 37, UP_ARROW : 38, RIGHT_ARROW : 39, DOWN_ARROW : 40, TAB : 9, BACKSPACE: 8, DELETE: 46 }, CSS: { /* Constants */ TRANSITIONEND: 'transitionend' + (webkit ? ' webkitTransitionEnd' : ''), ANIMATIONEND: 'animationend' + (webkit ? ' webkitAnimationEnd' : ''), TRANSFORM: vendorProperty('transform'), TRANSFORM_ORIGIN: vendorProperty('transformOrigin'), TRANSITION: vendorProperty('transition'), TRANSITION_DURATION: vendorProperty('transitionDuration'), ANIMATION_PLAY_STATE: vendorProperty('animationPlayState'), ANIMATION_DURATION: vendorProperty('animationDuration'), ANIMATION_NAME: vendorProperty('animationName'), ANIMATION_TIMING: vendorProperty('animationTimingFunction'), ANIMATION_DIRECTION: vendorProperty('animationDirection') }, /** * As defined in core/style/variables.scss * * $layout-breakpoint-xs: 600px !default; * $layout-breakpoint-sm: 960px !default; * $layout-breakpoint-md: 1280px !default; * $layout-breakpoint-lg: 1920px !default; * */ MEDIA: { 'xs' : '(max-width: 599px)' , 'gt-xs' : '(min-width: 600px)' , 'sm' : '(min-width: 600px) and (max-width: 959px)' , 'gt-sm' : '(min-width: 960px)' , 'md' : '(min-width: 960px) and (max-width: 1279px)' , 'gt-md' : '(min-width: 1280px)' , 'lg' : '(min-width: 1280px) and (max-width: 1919px)', 'gt-lg' : '(min-width: 1920px)' , 'xl' : '(min-width: 1920px)' , 'print' : 'print' }, MEDIA_PRIORITY: [ 'xl', 'gt-lg', 'lg', 'gt-md', 'md', 'gt-sm', 'sm', 'gt-xs', 'xs', 'print' ] }; }
MdConstantFactory
identifier_name
constant.js
angular.module('material.core') .factory('$mdConstant', MdConstantFactory); /** * Factory function that creates the grab-bag $mdConstant service. * @ngInject */ function MdConstantFactory($sniffer)
{ var webkit = /webkit/i.test($sniffer.vendorPrefix); function vendorProperty(name) { return webkit ? ('webkit' + name.charAt(0).toUpperCase() + name.substring(1)) : name; } return { KEY_CODE: { COMMA: 188, SEMICOLON : 186, ENTER: 13, ESCAPE: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT_ARROW : 37, UP_ARROW : 38, RIGHT_ARROW : 39, DOWN_ARROW : 40, TAB : 9, BACKSPACE: 8, DELETE: 46 }, CSS: { /* Constants */ TRANSITIONEND: 'transitionend' + (webkit ? ' webkitTransitionEnd' : ''), ANIMATIONEND: 'animationend' + (webkit ? ' webkitAnimationEnd' : ''), TRANSFORM: vendorProperty('transform'), TRANSFORM_ORIGIN: vendorProperty('transformOrigin'), TRANSITION: vendorProperty('transition'), TRANSITION_DURATION: vendorProperty('transitionDuration'), ANIMATION_PLAY_STATE: vendorProperty('animationPlayState'), ANIMATION_DURATION: vendorProperty('animationDuration'), ANIMATION_NAME: vendorProperty('animationName'), ANIMATION_TIMING: vendorProperty('animationTimingFunction'), ANIMATION_DIRECTION: vendorProperty('animationDirection') }, /** * As defined in core/style/variables.scss * * $layout-breakpoint-xs: 600px !default; * $layout-breakpoint-sm: 960px !default; * $layout-breakpoint-md: 1280px !default; * $layout-breakpoint-lg: 1920px !default; * */ MEDIA: { 'xs' : '(max-width: 599px)' , 'gt-xs' : '(min-width: 600px)' , 'sm' : '(min-width: 600px) and (max-width: 959px)' , 'gt-sm' : '(min-width: 960px)' , 'md' : '(min-width: 960px) and (max-width: 1279px)' , 'gt-md' : '(min-width: 1280px)' , 'lg' : '(min-width: 1280px) and (max-width: 1919px)', 'gt-lg' : '(min-width: 1920px)' , 'xl' : '(min-width: 1920px)' , 'print' : 'print' }, MEDIA_PRIORITY: [ 'xl', 'gt-lg', 'lg', 'gt-md', 'md', 'gt-sm', 'sm', 'gt-xs', 'xs', 'print' ] }; }
identifier_body
constant.js
angular.module('material.core') .factory('$mdConstant', MdConstantFactory);
*/ function MdConstantFactory($sniffer) { var webkit = /webkit/i.test($sniffer.vendorPrefix); function vendorProperty(name) { return webkit ? ('webkit' + name.charAt(0).toUpperCase() + name.substring(1)) : name; } return { KEY_CODE: { COMMA: 188, SEMICOLON : 186, ENTER: 13, ESCAPE: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT_ARROW : 37, UP_ARROW : 38, RIGHT_ARROW : 39, DOWN_ARROW : 40, TAB : 9, BACKSPACE: 8, DELETE: 46 }, CSS: { /* Constants */ TRANSITIONEND: 'transitionend' + (webkit ? ' webkitTransitionEnd' : ''), ANIMATIONEND: 'animationend' + (webkit ? ' webkitAnimationEnd' : ''), TRANSFORM: vendorProperty('transform'), TRANSFORM_ORIGIN: vendorProperty('transformOrigin'), TRANSITION: vendorProperty('transition'), TRANSITION_DURATION: vendorProperty('transitionDuration'), ANIMATION_PLAY_STATE: vendorProperty('animationPlayState'), ANIMATION_DURATION: vendorProperty('animationDuration'), ANIMATION_NAME: vendorProperty('animationName'), ANIMATION_TIMING: vendorProperty('animationTimingFunction'), ANIMATION_DIRECTION: vendorProperty('animationDirection') }, /** * As defined in core/style/variables.scss * * $layout-breakpoint-xs: 600px !default; * $layout-breakpoint-sm: 960px !default; * $layout-breakpoint-md: 1280px !default; * $layout-breakpoint-lg: 1920px !default; * */ MEDIA: { 'xs' : '(max-width: 599px)' , 'gt-xs' : '(min-width: 600px)' , 'sm' : '(min-width: 600px) and (max-width: 959px)' , 'gt-sm' : '(min-width: 960px)' , 'md' : '(min-width: 960px) and (max-width: 1279px)' , 'gt-md' : '(min-width: 1280px)' , 'lg' : '(min-width: 1280px) and (max-width: 1919px)', 'gt-lg' : '(min-width: 1920px)' , 'xl' : '(min-width: 1920px)' , 'print' : 'print' }, MEDIA_PRIORITY: [ 'xl', 'gt-lg', 'lg', 'gt-md', 'md', 'gt-sm', 'sm', 'gt-xs', 'xs', 'print' ] }; }
/** * Factory function that creates the grab-bag $mdConstant service. * @ngInject
random_line_split
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0x05; const AUDIOSYNC_REGISTER: u8 = 0x06; const BREATH1_REGISTER: u8 = 0x08; const BREATH2_REGISTER: u8 = 0x09; const SHUTDOWN_REGISTER: u8 = 0x0A; const GAIN_REGISTER: u8 = 0x0B; const ADC_REGISTER: u8 = 0x0C; const CONFIG_BANK: u8 = 0x0B; const BANK_ADDRESS: u8 = 0xFD; const PICTURE_MODE: u8 = 0x00; const AUTOPLAY_MODE: u8 = 0x08; const AUDIOPLAY_MODE: u8 = 0x18; const ENABLE_OFFSET: u8 = 0x00; const BLINK_OFFSET: u8 = 0x12; const COLOR_OFFSET: u8 = 0x24; const ADDRESS: u16 = 0x74; /// A Scroll pHAT HD device connected over I2C bus (e.g. on a Raspberry Pi). pub struct I2CDisplay { device: LinuxI2CDevice, frame: u8, } impl I2CDisplay { /// Creates a new I2CDisplay device using the I2C device identified by the provided /// `device_id` (normally 1 or 2). pub fn new(device_id: u8) -> I2CDisplay { let device_path = format!("/dev/i2c-{}", device_id); let d = LinuxI2CDevice::new(device_path, ADDRESS).unwrap(); let mut display = I2CDisplay { device: d, frame: 0, }; display.init_display().unwrap(); display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> { self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, FRAME_REGISTER, frame) } fn write_data(&mut self, base_address: u8, data: &[u8]) -> Result<(), LinuxI2CError> { const CHUNK_SIZE: usize = 32; for (i, chunk) in data.chunks(CHUNK_SIZE).enumerate() { self.device .smbus_process_block(base_address + (i * CHUNK_SIZE) as u8, chunk)?; } Ok(()) } fn reset_display(&mut self) -> Result<(), LinuxI2CError> { self.sleep(true)?; std::thread::sleep(std::time::Duration::from_millis(10)); self.sleep(false)?; Ok(()) } fn
(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for frame in 0..2 { self.write_data(BANK_ADDRESS, &[frame])?; // Turn off blinking for all LEDs. self.write_data(BLINK_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Set the PWM duty cycle for all LEDs to 0%. self.write_data(COLOR_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Turn all LEDs "on". self.write_data(ENABLE_OFFSET, &[127; LED_COLUMNS * LED_ROWS])?; } Ok(()) } fn sleep(&mut self, value: bool) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, SHUTDOWN_REGISTER, if value { 0 } else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error> { // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { (8 - x) * 16 - (y + 2) }; let value = match buffer.get(x as usize) { Some(column) => column[y as usize], None => 0, }; self.write_data(COLOR_OFFSET + offset as u8, &[value])?; } } self.frame(new_frame)?; self.frame = new_frame; Ok(()) } }
init_display
identifier_name
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0x05; const AUDIOSYNC_REGISTER: u8 = 0x06; const BREATH1_REGISTER: u8 = 0x08; const BREATH2_REGISTER: u8 = 0x09; const SHUTDOWN_REGISTER: u8 = 0x0A; const GAIN_REGISTER: u8 = 0x0B; const ADC_REGISTER: u8 = 0x0C; const CONFIG_BANK: u8 = 0x0B; const BANK_ADDRESS: u8 = 0xFD; const PICTURE_MODE: u8 = 0x00; const AUTOPLAY_MODE: u8 = 0x08; const AUDIOPLAY_MODE: u8 = 0x18; const ENABLE_OFFSET: u8 = 0x00; const BLINK_OFFSET: u8 = 0x12; const COLOR_OFFSET: u8 = 0x24; const ADDRESS: u16 = 0x74; /// A Scroll pHAT HD device connected over I2C bus (e.g. on a Raspberry Pi). pub struct I2CDisplay { device: LinuxI2CDevice, frame: u8, } impl I2CDisplay { /// Creates a new I2CDisplay device using the I2C device identified by the provided /// `device_id` (normally 1 or 2). pub fn new(device_id: u8) -> I2CDisplay { let device_path = format!("/dev/i2c-{}", device_id); let d = LinuxI2CDevice::new(device_path, ADDRESS).unwrap(); let mut display = I2CDisplay { device: d, frame: 0, }; display.init_display().unwrap();
self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, FRAME_REGISTER, frame) } fn write_data(&mut self, base_address: u8, data: &[u8]) -> Result<(), LinuxI2CError> { const CHUNK_SIZE: usize = 32; for (i, chunk) in data.chunks(CHUNK_SIZE).enumerate() { self.device .smbus_process_block(base_address + (i * CHUNK_SIZE) as u8, chunk)?; } Ok(()) } fn reset_display(&mut self) -> Result<(), LinuxI2CError> { self.sleep(true)?; std::thread::sleep(std::time::Duration::from_millis(10)); self.sleep(false)?; Ok(()) } fn init_display(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for frame in 0..2 { self.write_data(BANK_ADDRESS, &[frame])?; // Turn off blinking for all LEDs. self.write_data(BLINK_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Set the PWM duty cycle for all LEDs to 0%. self.write_data(COLOR_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Turn all LEDs "on". self.write_data(ENABLE_OFFSET, &[127; LED_COLUMNS * LED_ROWS])?; } Ok(()) } fn sleep(&mut self, value: bool) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, SHUTDOWN_REGISTER, if value { 0 } else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error> { // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { (8 - x) * 16 - (y + 2) }; let value = match buffer.get(x as usize) { Some(column) => column[y as usize], None => 0, }; self.write_data(COLOR_OFFSET + offset as u8, &[value])?; } } self.frame(new_frame)?; self.frame = new_frame; Ok(()) } }
display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> {
random_line_split
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0x05; const AUDIOSYNC_REGISTER: u8 = 0x06; const BREATH1_REGISTER: u8 = 0x08; const BREATH2_REGISTER: u8 = 0x09; const SHUTDOWN_REGISTER: u8 = 0x0A; const GAIN_REGISTER: u8 = 0x0B; const ADC_REGISTER: u8 = 0x0C; const CONFIG_BANK: u8 = 0x0B; const BANK_ADDRESS: u8 = 0xFD; const PICTURE_MODE: u8 = 0x00; const AUTOPLAY_MODE: u8 = 0x08; const AUDIOPLAY_MODE: u8 = 0x18; const ENABLE_OFFSET: u8 = 0x00; const BLINK_OFFSET: u8 = 0x12; const COLOR_OFFSET: u8 = 0x24; const ADDRESS: u16 = 0x74; /// A Scroll pHAT HD device connected over I2C bus (e.g. on a Raspberry Pi). pub struct I2CDisplay { device: LinuxI2CDevice, frame: u8, } impl I2CDisplay { /// Creates a new I2CDisplay device using the I2C device identified by the provided /// `device_id` (normally 1 or 2). pub fn new(device_id: u8) -> I2CDisplay { let device_path = format!("/dev/i2c-{}", device_id); let d = LinuxI2CDevice::new(device_path, ADDRESS).unwrap(); let mut display = I2CDisplay { device: d, frame: 0, }; display.init_display().unwrap(); display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> { self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, FRAME_REGISTER, frame) } fn write_data(&mut self, base_address: u8, data: &[u8]) -> Result<(), LinuxI2CError> { const CHUNK_SIZE: usize = 32; for (i, chunk) in data.chunks(CHUNK_SIZE).enumerate() { self.device .smbus_process_block(base_address + (i * CHUNK_SIZE) as u8, chunk)?; } Ok(()) } fn reset_display(&mut self) -> Result<(), LinuxI2CError> { self.sleep(true)?; std::thread::sleep(std::time::Duration::from_millis(10)); self.sleep(false)?; Ok(()) } fn init_display(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for frame in 0..2 { self.write_data(BANK_ADDRESS, &[frame])?; // Turn off blinking for all LEDs. self.write_data(BLINK_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Set the PWM duty cycle for all LEDs to 0%. self.write_data(COLOR_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Turn all LEDs "on". self.write_data(ENABLE_OFFSET, &[127; LED_COLUMNS * LED_ROWS])?; } Ok(()) } fn sleep(&mut self, value: bool) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, SHUTDOWN_REGISTER, if value { 0 } else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error>
}
{ // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { (8 - x) * 16 - (y + 2) }; let value = match buffer.get(x as usize) { Some(column) => column[y as usize], None => 0, }; self.write_data(COLOR_OFFSET + offset as u8, &[value])?; } } self.frame(new_frame)?; self.frame = new_frame; Ok(()) }
identifier_body
i2c_display.rs
#![allow(dead_code)] extern crate i2cdev; use super::*; use self::i2cdev::core::I2CDevice; use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError}; const MODE_REGISTER: u8 = 0x00; const FRAME_REGISTER: u8 = 0x01; const AUTOPLAY1_REGISTER: u8 = 0x02; const AUTOPLAY2_REGISTER: u8 = 0x03; const BLINK_REGISTER: u8 = 0x05; const AUDIOSYNC_REGISTER: u8 = 0x06; const BREATH1_REGISTER: u8 = 0x08; const BREATH2_REGISTER: u8 = 0x09; const SHUTDOWN_REGISTER: u8 = 0x0A; const GAIN_REGISTER: u8 = 0x0B; const ADC_REGISTER: u8 = 0x0C; const CONFIG_BANK: u8 = 0x0B; const BANK_ADDRESS: u8 = 0xFD; const PICTURE_MODE: u8 = 0x00; const AUTOPLAY_MODE: u8 = 0x08; const AUDIOPLAY_MODE: u8 = 0x18; const ENABLE_OFFSET: u8 = 0x00; const BLINK_OFFSET: u8 = 0x12; const COLOR_OFFSET: u8 = 0x24; const ADDRESS: u16 = 0x74; /// A Scroll pHAT HD device connected over I2C bus (e.g. on a Raspberry Pi). pub struct I2CDisplay { device: LinuxI2CDevice, frame: u8, } impl I2CDisplay { /// Creates a new I2CDisplay device using the I2C device identified by the provided /// `device_id` (normally 1 or 2). pub fn new(device_id: u8) -> I2CDisplay { let device_path = format!("/dev/i2c-{}", device_id); let d = LinuxI2CDevice::new(device_path, ADDRESS).unwrap(); let mut display = I2CDisplay { device: d, frame: 0, }; display.init_display().unwrap(); display } fn bank(&mut self, bank: u8) -> Result<(), LinuxI2CError> { self.write_data(BANK_ADDRESS, &[bank]) } fn register(&mut self, bank: u8, register: u8, value: u8) -> Result<(), LinuxI2CError> { self.bank(bank)?; self.write_data(register, &[value]) } fn frame(&mut self, frame: u8) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, FRAME_REGISTER, frame) } fn write_data(&mut self, base_address: u8, data: &[u8]) -> Result<(), LinuxI2CError> { const CHUNK_SIZE: usize = 32; for (i, chunk) in data.chunks(CHUNK_SIZE).enumerate() { self.device .smbus_process_block(base_address + (i * CHUNK_SIZE) as u8, chunk)?; } Ok(()) } fn reset_display(&mut self) -> Result<(), LinuxI2CError> { self.sleep(true)?; std::thread::sleep(std::time::Duration::from_millis(10)); self.sleep(false)?; Ok(()) } fn init_display(&mut self) -> Result<(), LinuxI2CError> { self.reset_display()?; // Switch to Picture Mode. self.register(CONFIG_BANK, MODE_REGISTER, PICTURE_MODE)?; // Disable audio sync. self.register(CONFIG_BANK, AUDIOSYNC_REGISTER, 0)?; // Initialize frames 0 and 1. for frame in 0..2 { self.write_data(BANK_ADDRESS, &[frame])?; // Turn off blinking for all LEDs. self.write_data(BLINK_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Set the PWM duty cycle for all LEDs to 0%. self.write_data(COLOR_OFFSET, &[0; LED_COLUMNS * LED_ROWS])?; // Turn all LEDs "on". self.write_data(ENABLE_OFFSET, &[127; LED_COLUMNS * LED_ROWS])?; } Ok(()) } fn sleep(&mut self, value: bool) -> Result<(), LinuxI2CError> { self.register(CONFIG_BANK, SHUTDOWN_REGISTER, if value
else { 1 }) } } impl Display for I2CDisplay { fn show(&mut self, buffer: &[Column]) -> Result<(), Error> { // Double buffering with frames 0 and 1. let new_frame = (self.frame + 1) % 2; self.bank(new_frame)?; for y in 0..DISPLAY_HEIGHT { for x in 0..DISPLAY_WIDTH { let offset = if x >= 8 { (x - 8) * 16 + y } else { (8 - x) * 16 - (y + 2) }; let value = match buffer.get(x as usize) { Some(column) => column[y as usize], None => 0, }; self.write_data(COLOR_OFFSET + offset as u8, &[value])?; } } self.frame(new_frame)?; self.frame = new_frame; Ok(()) } }
{ 0 }
conditional_block
bundle.js
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function
(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /*! no static exports found */ /***/ (function(module, exports) { eval("throw new Error(\"Module parse failed: Unexpected token (2:1)/nYou may need an appropriate loader to handle this file type./n| var a;/n| == 0;/n| \");\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }) /******/ });
__webpack_require__
identifier_name
bundle.js
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId)
/******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /*! no static exports found */ /***/ (function(module, exports) { eval("throw new Error(\"Module parse failed: Unexpected token (2:1)/nYou may need an appropriate loader to handle this file type./n| var a;/n| == 0;/n| \");\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }) /******/ });
{ /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ }
identifier_body
bundle.js
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {}
/******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /*! no static exports found */ /***/ (function(module, exports) { eval("throw new Error(\"Module parse failed: Unexpected token (2:1)/nYou may need an appropriate loader to handle this file type./n| var a;/n| == 0;/n| \");\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }) /******/ });
/******/ }; /******/
random_line_split
todo.js
const ADD_TODO = 'ADD_TODO'; const TOGGLE_TODO = 'TOGGLE_TODO'; const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; const SHOW_ALL = 'SHOW_ALL'; const todo = (state = {}, action) => { switch (action.type) { case ADD_TODO: return { id: action.id, text: action.text, completed: false }; case TOGGLE_TODO: if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const initialState = { todos: [], filter: SHOW_ALL }; export default function reducer(state = initialState, action) { let todos; switch (action.type) { case ADD_TODO: todos = [todo(undefined, action), ...state.todos]; return { ...state, filter: SHOW_ALL, todos }; case TOGGLE_TODO: todos = state.todos.map(td => todo(td, action) ); return { ...state, todos }; case SET_VISIBILITY_FILTER: return { ...state, filter: action.filter, todos: [...state.todos] }; default: return state; } } export function addTodo(id, text) { return { type: ADD_TODO, id, text }; } export function
(id) { return { type: TOGGLE_TODO, id }; } export function setVisibilityFilter(filter) { return { type: SET_VISIBILITY_FILTER, filter }; }
toggleTodo
identifier_name
todo.js
const ADD_TODO = 'ADD_TODO'; const TOGGLE_TODO = 'TOGGLE_TODO'; const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; const SHOW_ALL = 'SHOW_ALL'; const todo = (state = {}, action) => { switch (action.type) { case ADD_TODO: return { id: action.id, text: action.text, completed: false }; case TOGGLE_TODO: if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const initialState = { todos: [], filter: SHOW_ALL }; export default function reducer(state = initialState, action) { let todos; switch (action.type) { case ADD_TODO: todos = [todo(undefined, action), ...state.todos]; return { ...state, filter: SHOW_ALL, todos }; case TOGGLE_TODO: todos = state.todos.map(td => todo(td, action) ); return { ...state, todos }; case SET_VISIBILITY_FILTER: return { ...state, filter: action.filter, todos: [...state.todos] }; default: return state; } } export function addTodo(id, text)
export function toggleTodo(id) { return { type: TOGGLE_TODO, id }; } export function setVisibilityFilter(filter) { return { type: SET_VISIBILITY_FILTER, filter }; }
{ return { type: ADD_TODO, id, text }; }
identifier_body
todo.js
const ADD_TODO = 'ADD_TODO'; const TOGGLE_TODO = 'TOGGLE_TODO'; const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; const SHOW_ALL = 'SHOW_ALL'; const todo = (state = {}, action) => { switch (action.type) { case ADD_TODO: return { id: action.id, text: action.text, completed: false }; case TOGGLE_TODO: if (state.id !== action.id) { return state; } return { ...state,
}; default: return state; } }; const initialState = { todos: [], filter: SHOW_ALL }; export default function reducer(state = initialState, action) { let todos; switch (action.type) { case ADD_TODO: todos = [todo(undefined, action), ...state.todos]; return { ...state, filter: SHOW_ALL, todos }; case TOGGLE_TODO: todos = state.todos.map(td => todo(td, action) ); return { ...state, todos }; case SET_VISIBILITY_FILTER: return { ...state, filter: action.filter, todos: [...state.todos] }; default: return state; } } export function addTodo(id, text) { return { type: ADD_TODO, id, text }; } export function toggleTodo(id) { return { type: TOGGLE_TODO, id }; } export function setVisibilityFilter(filter) { return { type: SET_VISIBILITY_FILTER, filter }; }
completed: !state.completed
random_line_split
todo.js
const ADD_TODO = 'ADD_TODO'; const TOGGLE_TODO = 'TOGGLE_TODO'; const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; const SHOW_ALL = 'SHOW_ALL'; const todo = (state = {}, action) => { switch (action.type) { case ADD_TODO: return { id: action.id, text: action.text, completed: false }; case TOGGLE_TODO: if (state.id !== action.id)
return { ...state, completed: !state.completed }; default: return state; } }; const initialState = { todos: [], filter: SHOW_ALL }; export default function reducer(state = initialState, action) { let todos; switch (action.type) { case ADD_TODO: todos = [todo(undefined, action), ...state.todos]; return { ...state, filter: SHOW_ALL, todos }; case TOGGLE_TODO: todos = state.todos.map(td => todo(td, action) ); return { ...state, todos }; case SET_VISIBILITY_FILTER: return { ...state, filter: action.filter, todos: [...state.todos] }; default: return state; } } export function addTodo(id, text) { return { type: ADD_TODO, id, text }; } export function toggleTodo(id) { return { type: TOGGLE_TODO, id }; } export function setVisibilityFilter(filter) { return { type: SET_VISIBILITY_FILTER, filter }; }
{ return state; }
conditional_block
GroupsViewController.ts
/** * Created by kalle on 3.6.2014. */ /// <reference path="../require.d.ts" /> /// <reference path="../dustjs-linkedin.d.ts" /> /// <reference path="../lodash.d.ts" /> import ViewControllerBase = require("../ViewControllerBase"); class GroupsViewController extends ViewControllerBase { ControllerInitialize():void { var me = this; require(["GroupsView/Groups_dust", "lib/dusts/command_button_begin_dust", "lib/dusts/command_button_end_dust", "lib/dusts/command_button_dust", "lib/dusts/modal_begin_dust", "lib/dusts/textinput_singleline_dust", "lib/dusts/modal_end_dust", "lib/dusts/hiddeninput_dust", "lib/dusts/openmodal_button_dust", "lib/dusts/insidemodal_button_dust" ], (template) => { this.currUDG.GetData(this.dataUrl, myData => { me.currentData = myData; dust.render("Groups.dust", myData, (error, output) => { if(error) alert("Dust error: " + error); var $hostDiv = $("#" + me.divID); $hostDiv.empty(); $hostDiv.html(output); me.ControllerInitializeDone(); }); }); }); } // Instead of hidden fields in "form", we can store the last fetched data as current currentData:any; public VisibleTemplateRender():void { } public
():void { } SetAsDefaultGroup($source) { var me = this; var groupURL = $source.attr("data-groupurl"); var groupID = groupURL.substr(10,36); var wnd:any = window; this.CommonWaitForOperation("Making group as default..."); this.currOPM.ExecuteOperationWithForm("SetGroupAsDefaultForAccount", {"GroupID": groupID}, function() { me.CommonSuccessHandler(); me.ReInitialize(); }, this.CommonErrorHandler); } ClearDefaultGroup($source) { var me = this; var wnd:any = window; this.CommonWaitForOperation("Clearing account's default group setting..."); this.currOPM.ExecuteOperationWithForm("ClearDefaultGroupFromAccount", { }, function() { me.CommonSuccessHandler(); me.ReInitialize(); }, this.CommonErrorHandler); } OpenCreateNewGroupModal($source) { var me = this; var $modal:any = me.$getNamedFieldWithin("CreateNewGroupModal"); me.$getNamedFieldWithinModal($modal, "GroupName").val(""); $modal.foundation("reveal", "open"); } Modal_CreateNewGroup($modal) { var redirectUrlAfterCreation = "cpanel/html/cpanel.html"; var templateNameList = "cpanel,categoriesandcontent"; var me = this; var groupName = me.$getNamedFieldWithinModal($modal, "GroupName").val(); var jq:any = $; jq.blockUI({ message: '<h2>Creating new group...</h2>' }); me.currOPM.ExecuteOperationWithForm("CreateGroupWithTemplates", { GroupName: groupName, TemplateNameList: templateNameList }, function(responseData) { setTimeout(function() { jq.unblockUI(); $modal.foundation("reveal", "close"); me.ReInitialize(); }, 2500); }, me.CommonErrorHandler); } } export = GroupsViewController;
InvisibleTemplateRender
identifier_name
GroupsViewController.ts
/** * Created by kalle on 3.6.2014. */ /// <reference path="../require.d.ts" /> /// <reference path="../dustjs-linkedin.d.ts" /> /// <reference path="../lodash.d.ts" /> import ViewControllerBase = require("../ViewControllerBase"); class GroupsViewController extends ViewControllerBase { ControllerInitialize():void { var me = this; require(["GroupsView/Groups_dust", "lib/dusts/command_button_begin_dust", "lib/dusts/command_button_end_dust", "lib/dusts/command_button_dust", "lib/dusts/modal_begin_dust", "lib/dusts/textinput_singleline_dust", "lib/dusts/modal_end_dust", "lib/dusts/hiddeninput_dust", "lib/dusts/openmodal_button_dust", "lib/dusts/insidemodal_button_dust" ], (template) => { this.currUDG.GetData(this.dataUrl, myData => { me.currentData = myData; dust.render("Groups.dust", myData, (error, output) => { if(error) alert("Dust error: " + error); var $hostDiv = $("#" + me.divID); $hostDiv.empty(); $hostDiv.html(output); me.ControllerInitializeDone(); }); }); }); } // Instead of hidden fields in "form", we can store the last fetched data as current currentData:any; public VisibleTemplateRender():void { } public InvisibleTemplateRender():void { } SetAsDefaultGroup($source) { var me = this; var groupURL = $source.attr("data-groupurl"); var groupID = groupURL.substr(10,36); var wnd:any = window; this.CommonWaitForOperation("Making group as default..."); this.currOPM.ExecuteOperationWithForm("SetGroupAsDefaultForAccount", {"GroupID": groupID}, function() { me.CommonSuccessHandler(); me.ReInitialize(); }, this.CommonErrorHandler); } ClearDefaultGroup($source) { var me = this; var wnd:any = window; this.CommonWaitForOperation("Clearing account's default group setting..."); this.currOPM.ExecuteOperationWithForm("ClearDefaultGroupFromAccount", { }, function() { me.CommonSuccessHandler(); me.ReInitialize(); }, this.CommonErrorHandler); } OpenCreateNewGroupModal($source) { var me = this; var $modal:any = me.$getNamedFieldWithin("CreateNewGroupModal");
Modal_CreateNewGroup($modal) { var redirectUrlAfterCreation = "cpanel/html/cpanel.html"; var templateNameList = "cpanel,categoriesandcontent"; var me = this; var groupName = me.$getNamedFieldWithinModal($modal, "GroupName").val(); var jq:any = $; jq.blockUI({ message: '<h2>Creating new group...</h2>' }); me.currOPM.ExecuteOperationWithForm("CreateGroupWithTemplates", { GroupName: groupName, TemplateNameList: templateNameList }, function(responseData) { setTimeout(function() { jq.unblockUI(); $modal.foundation("reveal", "close"); me.ReInitialize(); }, 2500); }, me.CommonErrorHandler); } } export = GroupsViewController;
me.$getNamedFieldWithinModal($modal, "GroupName").val(""); $modal.foundation("reveal", "open"); }
random_line_split
GroupsViewController.ts
/** * Created by kalle on 3.6.2014. */ /// <reference path="../require.d.ts" /> /// <reference path="../dustjs-linkedin.d.ts" /> /// <reference path="../lodash.d.ts" /> import ViewControllerBase = require("../ViewControllerBase"); class GroupsViewController extends ViewControllerBase { ControllerInitialize():void { var me = this; require(["GroupsView/Groups_dust", "lib/dusts/command_button_begin_dust", "lib/dusts/command_button_end_dust", "lib/dusts/command_button_dust", "lib/dusts/modal_begin_dust", "lib/dusts/textinput_singleline_dust", "lib/dusts/modal_end_dust", "lib/dusts/hiddeninput_dust", "lib/dusts/openmodal_button_dust", "lib/dusts/insidemodal_button_dust" ], (template) => { this.currUDG.GetData(this.dataUrl, myData => { me.currentData = myData; dust.render("Groups.dust", myData, (error, output) => { if(error) alert("Dust error: " + error); var $hostDiv = $("#" + me.divID); $hostDiv.empty(); $hostDiv.html(output); me.ControllerInitializeDone(); }); }); }); } // Instead of hidden fields in "form", we can store the last fetched data as current currentData:any; public VisibleTemplateRender():void
public InvisibleTemplateRender():void { } SetAsDefaultGroup($source) { var me = this; var groupURL = $source.attr("data-groupurl"); var groupID = groupURL.substr(10,36); var wnd:any = window; this.CommonWaitForOperation("Making group as default..."); this.currOPM.ExecuteOperationWithForm("SetGroupAsDefaultForAccount", {"GroupID": groupID}, function() { me.CommonSuccessHandler(); me.ReInitialize(); }, this.CommonErrorHandler); } ClearDefaultGroup($source) { var me = this; var wnd:any = window; this.CommonWaitForOperation("Clearing account's default group setting..."); this.currOPM.ExecuteOperationWithForm("ClearDefaultGroupFromAccount", { }, function() { me.CommonSuccessHandler(); me.ReInitialize(); }, this.CommonErrorHandler); } OpenCreateNewGroupModal($source) { var me = this; var $modal:any = me.$getNamedFieldWithin("CreateNewGroupModal"); me.$getNamedFieldWithinModal($modal, "GroupName").val(""); $modal.foundation("reveal", "open"); } Modal_CreateNewGroup($modal) { var redirectUrlAfterCreation = "cpanel/html/cpanel.html"; var templateNameList = "cpanel,categoriesandcontent"; var me = this; var groupName = me.$getNamedFieldWithinModal($modal, "GroupName").val(); var jq:any = $; jq.blockUI({ message: '<h2>Creating new group...</h2>' }); me.currOPM.ExecuteOperationWithForm("CreateGroupWithTemplates", { GroupName: groupName, TemplateNameList: templateNameList }, function(responseData) { setTimeout(function() { jq.unblockUI(); $modal.foundation("reveal", "close"); me.ReInitialize(); }, 2500); }, me.CommonErrorHandler); } } export = GroupsViewController;
{ }
identifier_body
clientChat.js
"use strict"; exports.__esModule = true; var vueClient_1 = require("../../bibliotheque/vueClient"); console.log("* Chargement du script"); /* Test - déclaration d'une variable externe - Possible cf. declare */ function centreNoeud() { return JSON.parse(vueClient_1.contenuBalise(document, 'centre')); } function voisinsNoeud() { var v = JSON.parse(vueClient_1.contenuBalise(document, 'voisins')); var r = []; var id; for (id in v) { r.push(v[id]); } return r; } function a
) { return vueClient_1.contenuBalise(document, 'adresseServeur'); } /* type CanalChat = CanalClient<FormatMessageTchat>; // A initialiser var canal: CanalChat; var noeud: Noeud<FormatSommetTchat>; function envoyerMessage(texte: string, destinataire: Identifiant) { let msg: MessageTchat = creerMessageCommunication(noeud.centre().enJSON().id, destinataire, texte); console.log("- Envoi du message brut : " + msg.brut()); console.log("- Envoi du message net : " + msg.net()); canal.envoyerMessage(msg); initialiserEntree('message_' + destinataire, ""); } // A exécuter après chargement de la page function initialisation(): void { console.log("* Initialisation après chargement du DOM ...") noeud = creerNoeud<FormatSommetTchat>(centreNoeud(), voisinsNoeud(), creerSommetTchat); canal = new CanalClient<FormatMessageTchat>(adresseServeur()); canal.enregistrerTraitementAReception((m: FormatMessageTchat) => { let msg = new MessageTchat(m); console.log("- Réception du message brut : " + msg.brut()); console.log("- Réception du message net : " + msg.net()); posterNL('logChats', msg.net()); }); console.log("* ... du noeud et du canal côté client en liaison avec le serveur : " + adresseServeur()); // Gestion des événements pour les éléments du document. //document.getElementById("boutonEnvoi").addEventListener("click", <EventListenerOrEventListenerObject>(e => {alert("click!");}), true); let id: Identifiant; let v = noeud.voisins(); for (id in v) { console.log("id : " +id); let idVal = id; gererEvenementElement("boutonEnvoi_" + idVal, "click", e => { console.log("id message_" + idVal); console.log("entree : " + recupererEntree("message_" + idVal)); envoyerMessage(recupererEntree("message_" + idVal), idVal); }); } <form id="envoi"> <input type="text" id="message_id1"> <input class="button" type="button" id="boutonEnvoi_id1" value="Envoyer un message à {{nom id1}}." onClick="envoyerMessage(this.form.message.value, "id1")"> </form> console.log("* ... et des gestionnaires d'événements sur des éléments du document."); } // Gestion des événements pour le document console.log("* Enregistrement de l'initialisation"); gererEvenementDocument('DOMContentLoaded', initialisation); <script type="text/javascript"> document.addEventListener('DOMContentLoaded', initialisation()); </script> */ //# sourceMappingURL=clientChat.js.map
dresseServeur(
identifier_name
clientChat.js
"use strict"; exports.__esModule = true; var vueClient_1 = require("../../bibliotheque/vueClient"); console.log("* Chargement du script"); /* Test - déclaration d'une variable externe - Possible cf. declare */ function centreNoeud() {
function voisinsNoeud() { var v = JSON.parse(vueClient_1.contenuBalise(document, 'voisins')); var r = []; var id; for (id in v) { r.push(v[id]); } return r; } function adresseServeur() { return vueClient_1.contenuBalise(document, 'adresseServeur'); } /* type CanalChat = CanalClient<FormatMessageTchat>; // A initialiser var canal: CanalChat; var noeud: Noeud<FormatSommetTchat>; function envoyerMessage(texte: string, destinataire: Identifiant) { let msg: MessageTchat = creerMessageCommunication(noeud.centre().enJSON().id, destinataire, texte); console.log("- Envoi du message brut : " + msg.brut()); console.log("- Envoi du message net : " + msg.net()); canal.envoyerMessage(msg); initialiserEntree('message_' + destinataire, ""); } // A exécuter après chargement de la page function initialisation(): void { console.log("* Initialisation après chargement du DOM ...") noeud = creerNoeud<FormatSommetTchat>(centreNoeud(), voisinsNoeud(), creerSommetTchat); canal = new CanalClient<FormatMessageTchat>(adresseServeur()); canal.enregistrerTraitementAReception((m: FormatMessageTchat) => { let msg = new MessageTchat(m); console.log("- Réception du message brut : " + msg.brut()); console.log("- Réception du message net : " + msg.net()); posterNL('logChats', msg.net()); }); console.log("* ... du noeud et du canal côté client en liaison avec le serveur : " + adresseServeur()); // Gestion des événements pour les éléments du document. //document.getElementById("boutonEnvoi").addEventListener("click", <EventListenerOrEventListenerObject>(e => {alert("click!");}), true); let id: Identifiant; let v = noeud.voisins(); for (id in v) { console.log("id : " +id); let idVal = id; gererEvenementElement("boutonEnvoi_" + idVal, "click", e => { console.log("id message_" + idVal); console.log("entree : " + recupererEntree("message_" + idVal)); envoyerMessage(recupererEntree("message_" + idVal), idVal); }); } <form id="envoi"> <input type="text" id="message_id1"> <input class="button" type="button" id="boutonEnvoi_id1" value="Envoyer un message à {{nom id1}}." onClick="envoyerMessage(this.form.message.value, "id1")"> </form> console.log("* ... et des gestionnaires d'événements sur des éléments du document."); } // Gestion des événements pour le document console.log("* Enregistrement de l'initialisation"); gererEvenementDocument('DOMContentLoaded', initialisation); <script type="text/javascript"> document.addEventListener('DOMContentLoaded', initialisation()); </script> */ //# sourceMappingURL=clientChat.js.map
return JSON.parse(vueClient_1.contenuBalise(document, 'centre')); }
identifier_body
clientChat.js
"use strict"; exports.__esModule = true; var vueClient_1 = require("../../bibliotheque/vueClient"); console.log("* Chargement du script"); /* Test - déclaration d'une variable externe - Possible cf. declare */ function centreNoeud() { return JSON.parse(vueClient_1.contenuBalise(document, 'centre')); } function voisinsNoeud() { var v = JSON.parse(vueClient_1.contenuBalise(document, 'voisins')); var r = [];
return r; } function adresseServeur() { return vueClient_1.contenuBalise(document, 'adresseServeur'); } /* type CanalChat = CanalClient<FormatMessageTchat>; // A initialiser var canal: CanalChat; var noeud: Noeud<FormatSommetTchat>; function envoyerMessage(texte: string, destinataire: Identifiant) { let msg: MessageTchat = creerMessageCommunication(noeud.centre().enJSON().id, destinataire, texte); console.log("- Envoi du message brut : " + msg.brut()); console.log("- Envoi du message net : " + msg.net()); canal.envoyerMessage(msg); initialiserEntree('message_' + destinataire, ""); } // A exécuter après chargement de la page function initialisation(): void { console.log("* Initialisation après chargement du DOM ...") noeud = creerNoeud<FormatSommetTchat>(centreNoeud(), voisinsNoeud(), creerSommetTchat); canal = new CanalClient<FormatMessageTchat>(adresseServeur()); canal.enregistrerTraitementAReception((m: FormatMessageTchat) => { let msg = new MessageTchat(m); console.log("- Réception du message brut : " + msg.brut()); console.log("- Réception du message net : " + msg.net()); posterNL('logChats', msg.net()); }); console.log("* ... du noeud et du canal côté client en liaison avec le serveur : " + adresseServeur()); // Gestion des événements pour les éléments du document. //document.getElementById("boutonEnvoi").addEventListener("click", <EventListenerOrEventListenerObject>(e => {alert("click!");}), true); let id: Identifiant; let v = noeud.voisins(); for (id in v) { console.log("id : " +id); let idVal = id; gererEvenementElement("boutonEnvoi_" + idVal, "click", e => { console.log("id message_" + idVal); console.log("entree : " + recupererEntree("message_" + idVal)); envoyerMessage(recupererEntree("message_" + idVal), idVal); }); } <form id="envoi"> <input type="text" id="message_id1"> <input class="button" type="button" id="boutonEnvoi_id1" value="Envoyer un message à {{nom id1}}." onClick="envoyerMessage(this.form.message.value, "id1")"> </form> console.log("* ... et des gestionnaires d'événements sur des éléments du document."); } // Gestion des événements pour le document console.log("* Enregistrement de l'initialisation"); gererEvenementDocument('DOMContentLoaded', initialisation); <script type="text/javascript"> document.addEventListener('DOMContentLoaded', initialisation()); </script> */ //# sourceMappingURL=clientChat.js.map
var id; for (id in v) { r.push(v[id]); }
random_line_split
hops_velocity.py
# coding: utf-8 # ## Plot velocity from non-CF HOPS dataset # In[5]: get_ipython().magic(u'matplotlib inline') import netCDF4 import matplotlib.pyplot as plt # In[6]: url='http://geoport.whoi.edu/thredds/dodsC/usgs/data2/rsignell/gdrive/nsf-alpha/Data/MIT_MSEAS/MSEAS_Tides_20160317/mseas_tides_2015071612_2015081612_01h.nc' # In[8]: nc = netCDF4.Dataset(url) # In[9]: ncv = nc.variables # In[ ]: # extract lon,lat variables from vgrid2 variable lon = ncv['vgrid2'][:,:,0] lat = ncv['vgrid2'][:,:,1] # In[20]: # extract u,v variables from vbaro variable itime = -1 u = ncv['vbaro'][itime,:,:,0] v = ncv['vbaro'][itime,:,:,1]
# In[30]: n=10 fig = plt.figure(figsize=(12,8)) plt.quiver(lon[::n,::n],lat[::n,::n],u[::n,::n],v[::n,::n]) #plt.axis([-70.6,-70.4,41.2,41.4]) # In[ ]: # In[ ]: # In[ ]:
random_line_split
all.js
'use strict'; module.exports = { app: { title: 'Surf Around The Corner', description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js', keywords: 'MongoDB, Express, AngularJS, Node.js' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/components-font-awesome/css/font-awesome.css', 'public/lib/angular-ui-select/dist/select.css', 'http://fonts.googleapis.com/css?family=Bree+Serif', 'http://fonts.googleapis.com/css?family=Open+Sans', 'http://fonts.googleapis.com/css?family=Playfair+Display', 'http://fonts.googleapis.com/css?family=Dancing+Script', 'http://fonts.googleapis.com/css?family=Nunito' //'http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css' ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/jquery/dist/jquery.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'public/lib/angular-ui-select/dist/select.js', 'public/lib/ng-lodash/build/ng-lodash.js', 'public/lib/ng-backstretch/dist/ng-backstretch.js', 'public/lib/ngFitText/src/ng-FitText.js' ] }, css: [
], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
'public/less/*.css', 'public/modules/**/css/*.css'
random_line_split
test.py
# # Copyright 2013 eNovance # # 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. """Test alarm notifier.""" from ceilometer.alarm import notifier class TestAlarmNotifier(notifier.AlarmNotifier): "Test alarm notifier.""" def __init__(self): self.notifications = [] def notify(self, action, alarm_id, alarm_name, severity, previous, current, reason, reason_data):
self.notifications.append((action, alarm_id, alarm_name, severity, previous, current, reason, reason_data))
identifier_body
test.py
# # Copyright 2013 eNovance # # 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. """Test alarm notifier.""" from ceilometer.alarm import notifier class TestAlarmNotifier(notifier.AlarmNotifier): "Test alarm notifier.""" def
(self): self.notifications = [] def notify(self, action, alarm_id, alarm_name, severity, previous, current, reason, reason_data): self.notifications.append((action, alarm_id, alarm_name, severity, previous, current, reason, reason_data))
__init__
identifier_name
test.py
# # Copyright 2013 eNovance # # 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 #
# 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. """Test alarm notifier.""" from ceilometer.alarm import notifier class TestAlarmNotifier(notifier.AlarmNotifier): "Test alarm notifier.""" def __init__(self): self.notifications = [] def notify(self, action, alarm_id, alarm_name, severity, previous, current, reason, reason_data): self.notifications.append((action, alarm_id, alarm_name, severity, previous, current, reason, reason_data))
# Unless required by applicable law or agreed to in writing, software
random_line_split
hark.py
# -*- coding: latin-1 -*- import re import json from .common import InfoExtractor from ..utils import determine_ext class
(InfoExtractor): _VALID_URL = r'https?://www\.hark\.com/clips/(.+?)-.+' _TEST = { u'url': u'http://www.hark.com/clips/mmbzyhkgny-obama-beyond-the-afghan-theater-we-only-target-al-qaeda-on-may-23-2013', u'file': u'mmbzyhkgny.mp3', u'md5': u'6783a58491b47b92c7c1af5a77d4cbee', u'info_dict': { u'title': u"Obama: 'Beyond The Afghan Theater, We Only Target Al Qaeda' on May 23, 2013", u'description': u'President Barack Obama addressed the nation live on May 23, 2013 in a speech aimed at addressing counter-terrorism policies including the use of drone strikes, detainees at Guantanamo Bay prison facility, and American citizens who are terrorists.', u'duration': 11, } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group(1) json_url = "http://www.hark.com/clips/%s.json" %(video_id) info_json = self._download_webpage(json_url, video_id) info = json.loads(info_json) final_url = info['url'] return {'id': video_id, 'url' : final_url, 'title': info['name'], 'ext': determine_ext(final_url), 'description': info['description'], 'thumbnail': info['image_original'], 'duration': info['duration'], }
HarkIE
identifier_name
hark.py
# -*- coding: latin-1 -*-
from .common import InfoExtractor from ..utils import determine_ext class HarkIE(InfoExtractor): _VALID_URL = r'https?://www\.hark\.com/clips/(.+?)-.+' _TEST = { u'url': u'http://www.hark.com/clips/mmbzyhkgny-obama-beyond-the-afghan-theater-we-only-target-al-qaeda-on-may-23-2013', u'file': u'mmbzyhkgny.mp3', u'md5': u'6783a58491b47b92c7c1af5a77d4cbee', u'info_dict': { u'title': u"Obama: 'Beyond The Afghan Theater, We Only Target Al Qaeda' on May 23, 2013", u'description': u'President Barack Obama addressed the nation live on May 23, 2013 in a speech aimed at addressing counter-terrorism policies including the use of drone strikes, detainees at Guantanamo Bay prison facility, and American citizens who are terrorists.', u'duration': 11, } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group(1) json_url = "http://www.hark.com/clips/%s.json" %(video_id) info_json = self._download_webpage(json_url, video_id) info = json.loads(info_json) final_url = info['url'] return {'id': video_id, 'url' : final_url, 'title': info['name'], 'ext': determine_ext(final_url), 'description': info['description'], 'thumbnail': info['image_original'], 'duration': info['duration'], }
import re import json
random_line_split
hark.py
# -*- coding: latin-1 -*- import re import json from .common import InfoExtractor from ..utils import determine_ext class HarkIE(InfoExtractor): _VALID_URL = r'https?://www\.hark\.com/clips/(.+?)-.+' _TEST = { u'url': u'http://www.hark.com/clips/mmbzyhkgny-obama-beyond-the-afghan-theater-we-only-target-al-qaeda-on-may-23-2013', u'file': u'mmbzyhkgny.mp3', u'md5': u'6783a58491b47b92c7c1af5a77d4cbee', u'info_dict': { u'title': u"Obama: 'Beyond The Afghan Theater, We Only Target Al Qaeda' on May 23, 2013", u'description': u'President Barack Obama addressed the nation live on May 23, 2013 in a speech aimed at addressing counter-terrorism policies including the use of drone strikes, detainees at Guantanamo Bay prison facility, and American citizens who are terrorists.', u'duration': 11, } } def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url) video_id = mobj.group(1) json_url = "http://www.hark.com/clips/%s.json" %(video_id) info_json = self._download_webpage(json_url, video_id) info = json.loads(info_json) final_url = info['url'] return {'id': video_id, 'url' : final_url, 'title': info['name'], 'ext': determine_ext(final_url), 'description': info['description'], 'thumbnail': info['image_original'], 'duration': info['duration'], }
identifier_body
msp.py
import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def
(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec
rec
identifier_name
msp.py
import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max:
return rec
tmp_max, rec = tmp, label
conditional_block
msp.py
import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir)
return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec
self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num":
random_line_split
msp.py
import sys import cv2 import helper as hp class MSP():
name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec
identifier_body
config.spec.js
'use strict'; var Config = require('../src/config'); var fs = require('fs'); var sh = require('shelljs'); describe('Config', function() { var config = new Config(); afterEach(function() { sh.rm('-rf', './config/'); }); describe('Create config', function() { it('should call init and isExistOrCreate the methods when creating', function() { Config.prototype.init = function() { }; Config.prototype.isExistOrCreate = function() { }; spyOn(Config.prototype, 'init').and.callThrough(); spyOn(Config.prototype, 'isExistOrCreate').and.callThrough(); var config = new Config(); expect(Config.prototype.init).toHaveBeenCalled(); expect(Config.prototype.isExistOrCreate).toHaveBeenCalled(); }); }); it('should create config data and fs when initing', function() { expect(config.fs).toBeDefined(); expect(config.config.dirName).toEqual('config/'); expect(config.config.fileName).toEqual('config-manager.json'); }); it('should get path', function() { var expected = 'config/config-manager.json'; var path = config.getPath(); expect(path).toEqual(expected); }); it('should create', function() { config.craeteDir = function() { }; config.save = function() { }; spyOn(config, 'craeteDir').and.callThrough(); spyOn(config, 'save').and.callThrough();
expect(config.craeteDir).toHaveBeenCalled(); expect(config.save).toHaveBeenCalled(); }); });
config.create();
random_line_split
scancode.rs
// Copyright 2014 The sdl2-rs Developers. // // 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. // SDL_scancode.h #[repr(C)] pub enum SDL_Scancode { SDL_SCANCODE_UNKNOWN = 0, SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, SDL_SCANCODE_NONUSHASH = 50, SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68,
SDL_SCANCODE_INSERT = 73, SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, SDL_SCANCODE_APPLICATION = 101, SDL_SCANCODE_POWER = 102, SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, SDL_SCANCODE_MENU = 118, SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, SDL_SCANCODE_AGAIN = 121, SDL_SCANCODE_UNDO = 122, SDL_SCANCODE_CUT = 123, SDL_SCANCODE_COPY = 124, SDL_SCANCODE_PASTE = 125, SDL_SCANCODE_FIND = 126, SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, SDL_SCANCODE_LANG2 = 145, SDL_SCANCODE_LANG3 = 146, SDL_SCANCODE_LANG4 = 147, SDL_SCANCODE_LANG5 = 148, SDL_SCANCODE_LANG6 = 149, SDL_SCANCODE_LANG7 = 150, SDL_SCANCODE_LANG8 = 151, SDL_SCANCODE_LANG9 = 152, SDL_SCANCODE_ALTERASE = 153, SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, SDL_SCANCODE_LGUI = 227, SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, SDL_SCANCODE_RGUI = 231, SDL_SCANCODE_MODE = 257, SDL_SCANCODE_AUDIONEXT = 258, SDL_SCANCODE_AUDIOPREV = 259, SDL_SCANCODE_AUDIOSTOP = 260, SDL_SCANCODE_AUDIOPLAY = 261, SDL_SCANCODE_AUDIOMUTE = 262, SDL_SCANCODE_MEDIASELECT = 263, SDL_SCANCODE_WWW = 264, SDL_SCANCODE_MAIL = 265, SDL_SCANCODE_CALCULATOR = 266, SDL_SCANCODE_COMPUTER = 267, SDL_SCANCODE_AC_SEARCH = 268, SDL_SCANCODE_AC_HOME = 269, SDL_SCANCODE_AC_BACK = 270, SDL_SCANCODE_AC_FORWARD = 271, SDL_SCANCODE_AC_STOP = 272, SDL_SCANCODE_AC_REFRESH = 273, SDL_SCANCODE_AC_BOOKMARKS = 274, SDL_SCANCODE_BRIGHTNESSDOWN = 275, SDL_SCANCODE_BRIGHTNESSUP = 276, SDL_SCANCODE_DISPLAYSWITCH = 277, SDL_SCANCODE_KBDILLUMTOGGLE = 278, SDL_SCANCODE_KBDILLUMDOWN = 279, SDL_SCANCODE_KBDILLUMUP = 280, SDL_SCANCODE_EJECT = 281, SDL_SCANCODE_SLEEP = 282, SDL_SCANCODE_APP1 = 283, SDL_SCANCODE_APP2 = 284, SDL_NUM_SCANCODES = 512, }
SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72,
random_line_split
scancode.rs
// Copyright 2014 The sdl2-rs Developers. // // 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. // SDL_scancode.h #[repr(C)] pub enum
{ SDL_SCANCODE_UNKNOWN = 0, SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, SDL_SCANCODE_NONUSHASH = 50, SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68, SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72, SDL_SCANCODE_INSERT = 73, SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, SDL_SCANCODE_APPLICATION = 101, SDL_SCANCODE_POWER = 102, SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, SDL_SCANCODE_MENU = 118, SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, SDL_SCANCODE_AGAIN = 121, SDL_SCANCODE_UNDO = 122, SDL_SCANCODE_CUT = 123, SDL_SCANCODE_COPY = 124, SDL_SCANCODE_PASTE = 125, SDL_SCANCODE_FIND = 126, SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, SDL_SCANCODE_LANG2 = 145, SDL_SCANCODE_LANG3 = 146, SDL_SCANCODE_LANG4 = 147, SDL_SCANCODE_LANG5 = 148, SDL_SCANCODE_LANG6 = 149, SDL_SCANCODE_LANG7 = 150, SDL_SCANCODE_LANG8 = 151, SDL_SCANCODE_LANG9 = 152, SDL_SCANCODE_ALTERASE = 153, SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, SDL_SCANCODE_LGUI = 227, SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, SDL_SCANCODE_RGUI = 231, SDL_SCANCODE_MODE = 257, SDL_SCANCODE_AUDIONEXT = 258, SDL_SCANCODE_AUDIOPREV = 259, SDL_SCANCODE_AUDIOSTOP = 260, SDL_SCANCODE_AUDIOPLAY = 261, SDL_SCANCODE_AUDIOMUTE = 262, SDL_SCANCODE_MEDIASELECT = 263, SDL_SCANCODE_WWW = 264, SDL_SCANCODE_MAIL = 265, SDL_SCANCODE_CALCULATOR = 266, SDL_SCANCODE_COMPUTER = 267, SDL_SCANCODE_AC_SEARCH = 268, SDL_SCANCODE_AC_HOME = 269, SDL_SCANCODE_AC_BACK = 270, SDL_SCANCODE_AC_FORWARD = 271, SDL_SCANCODE_AC_STOP = 272, SDL_SCANCODE_AC_REFRESH = 273, SDL_SCANCODE_AC_BOOKMARKS = 274, SDL_SCANCODE_BRIGHTNESSDOWN = 275, SDL_SCANCODE_BRIGHTNESSUP = 276, SDL_SCANCODE_DISPLAYSWITCH = 277, SDL_SCANCODE_KBDILLUMTOGGLE = 278, SDL_SCANCODE_KBDILLUMDOWN = 279, SDL_SCANCODE_KBDILLUMUP = 280, SDL_SCANCODE_EJECT = 281, SDL_SCANCODE_SLEEP = 282, SDL_SCANCODE_APP1 = 283, SDL_SCANCODE_APP2 = 284, SDL_NUM_SCANCODES = 512, }
SDL_Scancode
identifier_name
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import os import curses import cumodoro.config as config import cumodoro.interface as interface import cumodoro.globals as globals from cumodoro.cursest import Refresher import logging log = logging.getLogger('cumodoro') def set_title(msg):
def get_title(): print("\x1B[23t") return sys.stdin.read() def save_title(): print("\x1B[22t") def restore_title(): print("\x1B[23t") def main(): globals.refresher = Refresher() globals.refresher.start() globals.database.create() globals.database.load_tasks() os.environ["ESCDELAY"] = "25" save_title() set_title("Cumodoro") curses.wrapper(interface.main) restore_title()
print("\x1B]0;%s\x07" % msg)
identifier_body
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import os import curses import cumodoro.config as config import cumodoro.interface as interface import cumodoro.globals as globals from cumodoro.cursest import Refresher import logging log = logging.getLogger('cumodoro') def set_title(msg): print("\x1B]0;%s\x07" % msg) def get_title(): print("\x1B[23t") return sys.stdin.read() def save_title(): print("\x1B[22t") def
(): print("\x1B[23t") def main(): globals.refresher = Refresher() globals.refresher.start() globals.database.create() globals.database.load_tasks() os.environ["ESCDELAY"] = "25" save_title() set_title("Cumodoro") curses.wrapper(interface.main) restore_title()
restore_title
identifier_name
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import os import curses import cumodoro.config as config import cumodoro.interface as interface import cumodoro.globals as globals from cumodoro.cursest import Refresher import logging log = logging.getLogger('cumodoro') def set_title(msg): print("\x1B]0;%s\x07" % msg) def get_title(): print("\x1B[23t") return sys.stdin.read() def save_title(): print("\x1B[22t") def restore_title(): print("\x1B[23t") def main(): globals.refresher = Refresher() globals.refresher.start() globals.database.create() globals.database.load_tasks() os.environ["ESCDELAY"] = "25" save_title() set_title("Cumodoro")
curses.wrapper(interface.main) restore_title()
random_line_split
main.py
# -*- coding: utf-8 -*- """ syslog2irc.main ~~~~~~~~~~~~~~~ :Copyright: 2007-2015 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from itertools import chain from .announcer import create_announcer from .processor import Processor from .router import replace_channels_with_channel_names, Router from .signals import irc_channel_joined, message_approved from .syslog import start_syslog_message_receivers from .util import log # A note on threads (implementation detail): # # This tool uses threads. Besides the main thread, there are two # additional threads: one for the syslog message receiver and one for # the IRC bot. Both are configured to be daemon threads. # # A Python application exits if no more non-daemon threads are running. # # In order to exit syslog2IRC when shutdown is requested on IRC, the IRC # bot will call `die()`, which will join the IRC bot thread. The main # thread and the (daemonized) syslog message receiver thread remain. # # Additionally, a dedicated signal is sent that sets a flag that causes # the main loop to stop. As the syslog message receiver thread is the # only one left, but runs as a daemon, the application exits. # # The STDOUT announcer, on the other hand, does not run in a thread. The # user has to manually interrupt the application to exit. # # For details, see the documentation on the `threading` module that is # part of Python's standard library. def start(irc_server, irc_nickname, irc_realname, routes, **options): """Start the IRC bot and the syslog listen server.""" try: irc_channels = frozenset(chain(*routes.values())) ports = routes.keys() ports_to_channel_names = replace_channels_with_channel_names(routes) announcer = create_announcer(irc_server, irc_nickname, irc_realname, irc_channels, **options) message_approved.connect(announcer.announce) router = Router(ports_to_channel_names) processor = Processor(router) # Up to this point, no signals must have been sent. processor.connect_to_signals() # Signals are allowed be sent from here on. start_syslog_message_receivers(ports) announcer.start() if not irc_server: fake_channel_joins(router) processor.run() except KeyboardInterrupt: log('<Ctrl-C> pressed, aborting.') def fake_channel_joins(router): for channel_name in router.get_channel_names():
irc_channel_joined.send(channel=channel_name)
random_line_split
main.py
# -*- coding: utf-8 -*- """ syslog2irc.main ~~~~~~~~~~~~~~~ :Copyright: 2007-2015 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from itertools import chain from .announcer import create_announcer from .processor import Processor from .router import replace_channels_with_channel_names, Router from .signals import irc_channel_joined, message_approved from .syslog import start_syslog_message_receivers from .util import log # A note on threads (implementation detail): # # This tool uses threads. Besides the main thread, there are two # additional threads: one for the syslog message receiver and one for # the IRC bot. Both are configured to be daemon threads. # # A Python application exits if no more non-daemon threads are running. # # In order to exit syslog2IRC when shutdown is requested on IRC, the IRC # bot will call `die()`, which will join the IRC bot thread. The main # thread and the (daemonized) syslog message receiver thread remain. # # Additionally, a dedicated signal is sent that sets a flag that causes # the main loop to stop. As the syslog message receiver thread is the # only one left, but runs as a daemon, the application exits. # # The STDOUT announcer, on the other hand, does not run in a thread. The # user has to manually interrupt the application to exit. # # For details, see the documentation on the `threading` module that is # part of Python's standard library. def start(irc_server, irc_nickname, irc_realname, routes, **options): """Start the IRC bot and the syslog listen server.""" try: irc_channels = frozenset(chain(*routes.values())) ports = routes.keys() ports_to_channel_names = replace_channels_with_channel_names(routes) announcer = create_announcer(irc_server, irc_nickname, irc_realname, irc_channels, **options) message_approved.connect(announcer.announce) router = Router(ports_to_channel_names) processor = Processor(router) # Up to this point, no signals must have been sent. processor.connect_to_signals() # Signals are allowed be sent from here on. start_syslog_message_receivers(ports) announcer.start() if not irc_server: fake_channel_joins(router) processor.run() except KeyboardInterrupt: log('<Ctrl-C> pressed, aborting.') def
(router): for channel_name in router.get_channel_names(): irc_channel_joined.send(channel=channel_name)
fake_channel_joins
identifier_name
main.py
# -*- coding: utf-8 -*- """ syslog2irc.main ~~~~~~~~~~~~~~~ :Copyright: 2007-2015 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from itertools import chain from .announcer import create_announcer from .processor import Processor from .router import replace_channels_with_channel_names, Router from .signals import irc_channel_joined, message_approved from .syslog import start_syslog_message_receivers from .util import log # A note on threads (implementation detail): # # This tool uses threads. Besides the main thread, there are two # additional threads: one for the syslog message receiver and one for # the IRC bot. Both are configured to be daemon threads. # # A Python application exits if no more non-daemon threads are running. # # In order to exit syslog2IRC when shutdown is requested on IRC, the IRC # bot will call `die()`, which will join the IRC bot thread. The main # thread and the (daemonized) syslog message receiver thread remain. # # Additionally, a dedicated signal is sent that sets a flag that causes # the main loop to stop. As the syslog message receiver thread is the # only one left, but runs as a daemon, the application exits. # # The STDOUT announcer, on the other hand, does not run in a thread. The # user has to manually interrupt the application to exit. # # For details, see the documentation on the `threading` module that is # part of Python's standard library. def start(irc_server, irc_nickname, irc_realname, routes, **options): """Start the IRC bot and the syslog listen server.""" try: irc_channels = frozenset(chain(*routes.values())) ports = routes.keys() ports_to_channel_names = replace_channels_with_channel_names(routes) announcer = create_announcer(irc_server, irc_nickname, irc_realname, irc_channels, **options) message_approved.connect(announcer.announce) router = Router(ports_to_channel_names) processor = Processor(router) # Up to this point, no signals must have been sent. processor.connect_to_signals() # Signals are allowed be sent from here on. start_syslog_message_receivers(ports) announcer.start() if not irc_server: fake_channel_joins(router) processor.run() except KeyboardInterrupt: log('<Ctrl-C> pressed, aborting.') def fake_channel_joins(router): for channel_name in router.get_channel_names():
irc_channel_joined.send(channel=channel_name)
conditional_block
main.py
# -*- coding: utf-8 -*- """ syslog2irc.main ~~~~~~~~~~~~~~~ :Copyright: 2007-2015 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from itertools import chain from .announcer import create_announcer from .processor import Processor from .router import replace_channels_with_channel_names, Router from .signals import irc_channel_joined, message_approved from .syslog import start_syslog_message_receivers from .util import log # A note on threads (implementation detail): # # This tool uses threads. Besides the main thread, there are two # additional threads: one for the syslog message receiver and one for # the IRC bot. Both are configured to be daemon threads. # # A Python application exits if no more non-daemon threads are running. # # In order to exit syslog2IRC when shutdown is requested on IRC, the IRC # bot will call `die()`, which will join the IRC bot thread. The main # thread and the (daemonized) syslog message receiver thread remain. # # Additionally, a dedicated signal is sent that sets a flag that causes # the main loop to stop. As the syslog message receiver thread is the # only one left, but runs as a daemon, the application exits. # # The STDOUT announcer, on the other hand, does not run in a thread. The # user has to manually interrupt the application to exit. # # For details, see the documentation on the `threading` module that is # part of Python's standard library. def start(irc_server, irc_nickname, irc_realname, routes, **options): """Start the IRC bot and the syslog listen server.""" try: irc_channels = frozenset(chain(*routes.values())) ports = routes.keys() ports_to_channel_names = replace_channels_with_channel_names(routes) announcer = create_announcer(irc_server, irc_nickname, irc_realname, irc_channels, **options) message_approved.connect(announcer.announce) router = Router(ports_to_channel_names) processor = Processor(router) # Up to this point, no signals must have been sent. processor.connect_to_signals() # Signals are allowed be sent from here on. start_syslog_message_receivers(ports) announcer.start() if not irc_server: fake_channel_joins(router) processor.run() except KeyboardInterrupt: log('<Ctrl-C> pressed, aborting.') def fake_channel_joins(router):
for channel_name in router.get_channel_names(): irc_channel_joined.send(channel=channel_name)
identifier_body
APythonTest.py
# # coding=utf-8 # import os # def tree(top): # #path,folder list,file list # for path, names, fnames in os.walk(top): # for fname in fnames: # yield os.path.join(path, fname) # # for name in tree(os.getcwd()): # print name # # import time # from functools import wraps # # def timethis(func): # ''' # Decorator that reports the execution time. # ''' # @wraps(func) # def wrapper(*args, **kwargs): # start = time.time() # result = func(*args, **kwargs) # end = time.time() # print(func.__name__, end-start) # return result # return wrapper # # @timethis # def countdown(n): # while n > 0: # n -= 1 # # countdown(100000) # # class demo(object): # pass # # obj = demo() # # print "Class of obj is {0}".format(obj.__class__) # print "Class of obj is {0}".format(demo.__class__) # # Class of obj is <class '__main__.demo'> # # Class of obj is <type 'type'> # # print(obj.__metaclass__) # # # def temp(x): # return x+2 # # print(temp.func_code) # # import dis # print([ord(b) for b in temp.func_code.co_code]) # dis.dis(temp.func_code) # # #写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”, # #对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。 # for x in range(101): # #4 is string length # print "fizz"[x%3*4::]+"buzz"[x%5*4::] or x # # class decorator(object): # # def __init__(self, f): # print("inside decorator.__init__()") # # f() # Prove that function definition has completed # self.f=f # # def __call__(self): # print("inside decorator.__call__() begin") # self.f() # print("inside decorator.__call__() end") # # @decorator # def function(): # print("inside function()") # # print("Finished decorating function()") # # function() # # # inside decorator.__init__() # # Finished decorating function() # # inside decorator.__call__() begin # # inside function() # # inside decorator.__call__() end import os def tree(top): #path,folder list,file list for path, names, fnames in os.walk(top): for fname in fnames: # yield os.path.join(path,
rint '![image](http://hujiaweibujidao.github.io/images/pics/'+name+')' if __name__ == '__main__': pass
fname) yield fname for name in tree(os.getcwd()): print name for name in tree('/Users/hujiawei/Desktop/csu/'): p
identifier_body
APythonTest.py
# # coding=utf-8 # import os # def tree(top): # #path,folder list,file list # for path, names, fnames in os.walk(top): # for fname in fnames: # yield os.path.join(path, fname) # # for name in tree(os.getcwd()): # print name # # import time # from functools import wraps # # def timethis(func): # ''' # Decorator that reports the execution time. # ''' # @wraps(func) # def wrapper(*args, **kwargs): # start = time.time() # result = func(*args, **kwargs) # end = time.time() # print(func.__name__, end-start) # return result # return wrapper # # @timethis # def countdown(n): # while n > 0: # n -= 1 # # countdown(100000) # # class demo(object): # pass # # obj = demo() # # print "Class of obj is {0}".format(obj.__class__) # print "Class of obj is {0}".format(demo.__class__) # # Class of obj is <class '__main__.demo'> # # Class of obj is <type 'type'> # # print(obj.__metaclass__) # # # def temp(x): # return x+2 # # print(temp.func_code) # # import dis # print([ord(b) for b in temp.func_code.co_code]) # dis.dis(temp.func_code) # # #写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”, # #对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。 # for x in range(101): # #4 is string length # print "fizz"[x%3*4::]+"buzz"[x%5*4::] or x # # class decorator(object): # # def __init__(self, f): # print("inside decorator.__init__()") # # f() # Prove that function definition has completed # self.f=f # # def __call__(self): # print("inside decorator.__call__() begin") # self.f() # print("inside decorator.__call__() end") # # @decorator # def function(): # print("inside function()") # # print("Finished decorating function()") # # function() # # # inside decorator.__init__() # # Finished decorating function() # # inside decorator.__call__() begin # # inside function() # # inside decorator.__call__() end import os def tree(top): #path,folder list,file list for path, names, fnames in os.walk(top): for fname in
mes: # yield os.path.join(path, fname) yield fname for name in tree(os.getcwd()): print name for name in tree('/Users/hujiawei/Desktop/csu/'): print '![image](http://hujiaweibujidao.github.io/images/pics/'+name+')' if __name__ == '__main__': pass
fna
identifier_name
APythonTest.py
# # coding=utf-8 # import os # def tree(top): # #path,folder list,file list # for path, names, fnames in os.walk(top): # for fname in fnames: # yield os.path.join(path, fname) # # for name in tree(os.getcwd()): # print name # # import time # from functools import wraps # # def timethis(func):
# def wrapper(*args, **kwargs): # start = time.time() # result = func(*args, **kwargs) # end = time.time() # print(func.__name__, end-start) # return result # return wrapper # # @timethis # def countdown(n): # while n > 0: # n -= 1 # # countdown(100000) # # class demo(object): # pass # # obj = demo() # # print "Class of obj is {0}".format(obj.__class__) # print "Class of obj is {0}".format(demo.__class__) # # Class of obj is <class '__main__.demo'> # # Class of obj is <type 'type'> # # print(obj.__metaclass__) # # # def temp(x): # return x+2 # # print(temp.func_code) # # import dis # print([ord(b) for b in temp.func_code.co_code]) # dis.dis(temp.func_code) # # #写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”, # #对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。 # for x in range(101): # #4 is string length # print "fizz"[x%3*4::]+"buzz"[x%5*4::] or x # # class decorator(object): # # def __init__(self, f): # print("inside decorator.__init__()") # # f() # Prove that function definition has completed # self.f=f # # def __call__(self): # print("inside decorator.__call__() begin") # self.f() # print("inside decorator.__call__() end") # # @decorator # def function(): # print("inside function()") # # print("Finished decorating function()") # # function() # # # inside decorator.__init__() # # Finished decorating function() # # inside decorator.__call__() begin # # inside function() # # inside decorator.__call__() end import os def tree(top): #path,folder list,file list for path, names, fnames in os.walk(top): for fname in fnames: # yield os.path.join(path, fname) yield fname for name in tree(os.getcwd()): print name for name in tree('/Users/hujiawei/Desktop/csu/'): print '![image](http://hujiaweibujidao.github.io/images/pics/'+name+')' if __name__ == '__main__': pass
# ''' # Decorator that reports the execution time. # ''' # @wraps(func)
random_line_split
APythonTest.py
# # coding=utf-8 # import os # def tree(top): # #path,folder list,file list # for path, names, fnames in os.walk(top): # for fname in fnames: # yield os.path.join(path, fname) # # for name in tree(os.getcwd()): # print name # # import time # from functools import wraps # # def timethis(func): # ''' # Decorator that reports the execution time. # ''' # @wraps(func) # def wrapper(*args, **kwargs): # start = time.time() # result = func(*args, **kwargs) # end = time.time() # print(func.__name__, end-start) # return result # return wrapper # # @timethis # def countdown(n): # while n > 0: # n -= 1 # # countdown(100000) # # class demo(object): # pass # # obj = demo() # # print "Class of obj is {0}".format(obj.__class__) # print "Class of obj is {0}".format(demo.__class__) # # Class of obj is <class '__main__.demo'> # # Class of obj is <type 'type'> # # print(obj.__metaclass__) # # # def temp(x): # return x+2 # # print(temp.func_code) # # import dis # print([ord(b) for b in temp.func_code.co_code]) # dis.dis(temp.func_code) # # #写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”, # #对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。 # for x in range(101): # #4 is string length # print "fizz"[x%3*4::]+"buzz"[x%5*4::] or x # # class decorator(object): # # def __init__(self, f): # print("inside decorator.__init__()") # # f() # Prove that function definition has completed # self.f=f # # def __call__(self): # print("inside decorator.__call__() begin") # self.f() # print("inside decorator.__call__() end") # # @decorator # def function(): # print("inside function()") # # print("Finished decorating function()") # # function() # # # inside decorator.__init__() # # Finished decorating function() # # inside decorator.__call__() begin # # inside function() # # inside decorator.__call__() end import os def tree(top): #path,folder list,file list for path, names, fnames in os.walk(top): for fname in fnames: # yield os.path.join(path, fname) yield fname for name in tree(os.getcwd()): print name for name in tree('/Users/hujiawei/Desktop/csu/'): print '![image](http://hujiaweibujidao.github.io/images/pics/'+name+')' if __name__ == '__main__': pas
s
conditional_block
aggregate_work_time.py
#!/usr/bin/env python # coding: UTF-8 # The MIT License # # Copyright (c) 2011 Keita Kita # # 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. import argparse import os import os.path import sqlite3 import sys import work_recorder # Name of column that represents month. Format is YYYY-MM. COLUMN_MONTH = u'month' # Name of column that represents hours. COLUMN_HOURS = u'hours' # Key of time that represents a month. TIME_KEY_MONTH = COLUMN_MONTH # Key of time that represents a project. TIME_KEY_PROJECT = work_recorder.COLUMN_PROJECT # Key of time that represents hours a project. TIME_KEY_HOURS = COLUMN_HOURS def aggregate_work_time(start_day, end_day, conn):
def print_result(times): previous_month = None for a_time in times: month = a_time[TIME_KEY_MONTH] if month != previous_month: if previous_month != None: print print month previous_month = month print u'\t%s: %s hours' % (a_time[TIME_KEY_PROJECT], a_time[TIME_KEY_HOURS]) def main(): u""" Aggregate work time a project. Command line arguments: <start day> : Day of start, format : YYYYMMDD or MMDD, MDD (required) <end day> : Day of end, format : YYYYMMDD or MMDD, MDD (required) """ parser = argparse.ArgumentParser(description = u'Aggregate work time a project.') parser.add_argument(u'start_day', help = u'Day of start. Format is YYYYMMDD or MMDD, MDD') parser.add_argument(u'end_day', help = u'Day of end. Format is YYYYMMDD or MMDD, MDD') args = parser.parse_args() try: start_day = work_recorder.convert_day(args.start_day) end_day = work_recorder.convert_day(args.end_day) except work_recorder.InvalidArgumentFormatException: print u'Your arguments discords with formats.' sys.exit(1) database = os.path.join(os.getcwdu(), work_recorder.DATABASE_FILE_NAME) with sqlite3.connect(database) as conn: times = aggregate_work_time(start_day, end_day, conn) print_result(times) if __name__ == '__main__': main()
u""" Aggregate work times a project. Parameters: start_day : Day of start. Format is YYYY-MM-DD. end_day : Day of end. Format is YYYY-MM-DD. conn : Connection of database. Return: A list of dictionary. Key is a name of project. Value is its work time. """ cursor = conn.execute(u""" select strftime('%Y-%m', {day}) as {month}, {project}, round(sum(strftime('%s', {day} || ' ' || {end}) - strftime('%s', {day} || ' ' || {start})) / 60.0 / 60.0, 2) as {hours} from {work_time} where {day} between :start and :end group by {month}, {project} order by {month} asc, {hours} desc """.format(month = COLUMN_MONTH, project = work_recorder.COLUMN_PROJECT, day = work_recorder.COLUMN_DAY, end = work_recorder.COLUMN_END, hours = COLUMN_HOURS, start = work_recorder.COLUMN_START, work_time = work_recorder.TABLE_WORK_TIME), {u'start': start_day, u'end': end_day}) return [ {TIME_KEY_MONTH: a_row[0], TIME_KEY_PROJECT: a_row[1], TIME_KEY_HOURS: a_row[2]} for a_row in cursor]
identifier_body
aggregate_work_time.py
#!/usr/bin/env python # coding: UTF-8 # The MIT License # # Copyright (c) 2011 Keita Kita # # 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. import argparse import os import os.path import sqlite3 import sys import work_recorder # Name of column that represents month. Format is YYYY-MM. COLUMN_MONTH = u'month' # Name of column that represents hours. COLUMN_HOURS = u'hours' # Key of time that represents a month. TIME_KEY_MONTH = COLUMN_MONTH # Key of time that represents a project. TIME_KEY_PROJECT = work_recorder.COLUMN_PROJECT # Key of time that represents hours a project. TIME_KEY_HOURS = COLUMN_HOURS def aggregate_work_time(start_day, end_day, conn): u""" Aggregate work times a project. Parameters: start_day : Day of start. Format is YYYY-MM-DD. end_day : Day of end. Format is YYYY-MM-DD. conn : Connection of database. Return: A list of dictionary. Key is a name of project. Value is its work time. """ cursor = conn.execute(u""" select strftime('%Y-%m', {day}) as {month}, {project}, round(sum(strftime('%s', {day} || ' ' || {end}) - strftime('%s', {day} || ' ' || {start})) / 60.0 / 60.0, 2) as {hours} from {work_time} where {day} between :start and :end group by {month}, {project} order by {month} asc, {hours} desc """.format(month = COLUMN_MONTH, project = work_recorder.COLUMN_PROJECT, day = work_recorder.COLUMN_DAY, end = work_recorder.COLUMN_END, hours = COLUMN_HOURS, start = work_recorder.COLUMN_START, work_time = work_recorder.TABLE_WORK_TIME), {u'start': start_day, u'end': end_day}) return [ {TIME_KEY_MONTH: a_row[0], TIME_KEY_PROJECT: a_row[1], TIME_KEY_HOURS: a_row[2]} for a_row in cursor] def print_result(times): previous_month = None for a_time in times: month = a_time[TIME_KEY_MONTH] if month != previous_month:
print u'\t%s: %s hours' % (a_time[TIME_KEY_PROJECT], a_time[TIME_KEY_HOURS]) def main(): u""" Aggregate work time a project. Command line arguments: <start day> : Day of start, format : YYYYMMDD or MMDD, MDD (required) <end day> : Day of end, format : YYYYMMDD or MMDD, MDD (required) """ parser = argparse.ArgumentParser(description = u'Aggregate work time a project.') parser.add_argument(u'start_day', help = u'Day of start. Format is YYYYMMDD or MMDD, MDD') parser.add_argument(u'end_day', help = u'Day of end. Format is YYYYMMDD or MMDD, MDD') args = parser.parse_args() try: start_day = work_recorder.convert_day(args.start_day) end_day = work_recorder.convert_day(args.end_day) except work_recorder.InvalidArgumentFormatException: print u'Your arguments discords with formats.' sys.exit(1) database = os.path.join(os.getcwdu(), work_recorder.DATABASE_FILE_NAME) with sqlite3.connect(database) as conn: times = aggregate_work_time(start_day, end_day, conn) print_result(times) if __name__ == '__main__': main()
if previous_month != None: print print month previous_month = month
conditional_block
aggregate_work_time.py
#!/usr/bin/env python # coding: UTF-8 # The MIT License # # Copyright (c) 2011 Keita Kita # # 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. import argparse import os import os.path import sqlite3 import sys import work_recorder # Name of column that represents month. Format is YYYY-MM. COLUMN_MONTH = u'month' # Name of column that represents hours. COLUMN_HOURS = u'hours' # Key of time that represents a month. TIME_KEY_MONTH = COLUMN_MONTH # Key of time that represents a project. TIME_KEY_PROJECT = work_recorder.COLUMN_PROJECT # Key of time that represents hours a project. TIME_KEY_HOURS = COLUMN_HOURS def aggregate_work_time(start_day, end_day, conn): u""" Aggregate work times a project. Parameters: start_day : Day of start. Format is YYYY-MM-DD. end_day : Day of end. Format is YYYY-MM-DD. conn : Connection of database. Return: A list of dictionary. Key is a name of project. Value is its work time. """ cursor = conn.execute(u""" select strftime('%Y-%m', {day}) as {month}, {project}, round(sum(strftime('%s', {day} || ' ' || {end}) - strftime('%s', {day} || ' ' || {start})) / 60.0 / 60.0, 2) as {hours} from {work_time} where {day} between :start and :end group by {month}, {project} order by {month} asc, {hours} desc """.format(month = COLUMN_MONTH, project = work_recorder.COLUMN_PROJECT, day = work_recorder.COLUMN_DAY, end = work_recorder.COLUMN_END, hours = COLUMN_HOURS, start = work_recorder.COLUMN_START, work_time = work_recorder.TABLE_WORK_TIME), {u'start': start_day, u'end': end_day}) return [ {TIME_KEY_MONTH: a_row[0],
TIME_KEY_PROJECT: a_row[1], TIME_KEY_HOURS: a_row[2]} for a_row in cursor] def print_result(times): previous_month = None for a_time in times: month = a_time[TIME_KEY_MONTH] if month != previous_month: if previous_month != None: print print month previous_month = month print u'\t%s: %s hours' % (a_time[TIME_KEY_PROJECT], a_time[TIME_KEY_HOURS]) def main(): u""" Aggregate work time a project. Command line arguments: <start day> : Day of start, format : YYYYMMDD or MMDD, MDD (required) <end day> : Day of end, format : YYYYMMDD or MMDD, MDD (required) """ parser = argparse.ArgumentParser(description = u'Aggregate work time a project.') parser.add_argument(u'start_day', help = u'Day of start. Format is YYYYMMDD or MMDD, MDD') parser.add_argument(u'end_day', help = u'Day of end. Format is YYYYMMDD or MMDD, MDD') args = parser.parse_args() try: start_day = work_recorder.convert_day(args.start_day) end_day = work_recorder.convert_day(args.end_day) except work_recorder.InvalidArgumentFormatException: print u'Your arguments discords with formats.' sys.exit(1) database = os.path.join(os.getcwdu(), work_recorder.DATABASE_FILE_NAME) with sqlite3.connect(database) as conn: times = aggregate_work_time(start_day, end_day, conn) print_result(times) if __name__ == '__main__': main()
random_line_split
aggregate_work_time.py
#!/usr/bin/env python # coding: UTF-8 # The MIT License # # Copyright (c) 2011 Keita Kita # # 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. import argparse import os import os.path import sqlite3 import sys import work_recorder # Name of column that represents month. Format is YYYY-MM. COLUMN_MONTH = u'month' # Name of column that represents hours. COLUMN_HOURS = u'hours' # Key of time that represents a month. TIME_KEY_MONTH = COLUMN_MONTH # Key of time that represents a project. TIME_KEY_PROJECT = work_recorder.COLUMN_PROJECT # Key of time that represents hours a project. TIME_KEY_HOURS = COLUMN_HOURS def aggregate_work_time(start_day, end_day, conn): u""" Aggregate work times a project. Parameters: start_day : Day of start. Format is YYYY-MM-DD. end_day : Day of end. Format is YYYY-MM-DD. conn : Connection of database. Return: A list of dictionary. Key is a name of project. Value is its work time. """ cursor = conn.execute(u""" select strftime('%Y-%m', {day}) as {month}, {project}, round(sum(strftime('%s', {day} || ' ' || {end}) - strftime('%s', {day} || ' ' || {start})) / 60.0 / 60.0, 2) as {hours} from {work_time} where {day} between :start and :end group by {month}, {project} order by {month} asc, {hours} desc """.format(month = COLUMN_MONTH, project = work_recorder.COLUMN_PROJECT, day = work_recorder.COLUMN_DAY, end = work_recorder.COLUMN_END, hours = COLUMN_HOURS, start = work_recorder.COLUMN_START, work_time = work_recorder.TABLE_WORK_TIME), {u'start': start_day, u'end': end_day}) return [ {TIME_KEY_MONTH: a_row[0], TIME_KEY_PROJECT: a_row[1], TIME_KEY_HOURS: a_row[2]} for a_row in cursor] def
(times): previous_month = None for a_time in times: month = a_time[TIME_KEY_MONTH] if month != previous_month: if previous_month != None: print print month previous_month = month print u'\t%s: %s hours' % (a_time[TIME_KEY_PROJECT], a_time[TIME_KEY_HOURS]) def main(): u""" Aggregate work time a project. Command line arguments: <start day> : Day of start, format : YYYYMMDD or MMDD, MDD (required) <end day> : Day of end, format : YYYYMMDD or MMDD, MDD (required) """ parser = argparse.ArgumentParser(description = u'Aggregate work time a project.') parser.add_argument(u'start_day', help = u'Day of start. Format is YYYYMMDD or MMDD, MDD') parser.add_argument(u'end_day', help = u'Day of end. Format is YYYYMMDD or MMDD, MDD') args = parser.parse_args() try: start_day = work_recorder.convert_day(args.start_day) end_day = work_recorder.convert_day(args.end_day) except work_recorder.InvalidArgumentFormatException: print u'Your arguments discords with formats.' sys.exit(1) database = os.path.join(os.getcwdu(), work_recorder.DATABASE_FILE_NAME) with sqlite3.connect(database) as conn: times = aggregate_work_time(start_day, end_day, conn) print_result(times) if __name__ == '__main__': main()
print_result
identifier_name
modal.component.ts
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import { Modal } from 'ngx-modal'; import { ModalService } from '../../services/modal.service'; @Component({ selector: 'osio-modal',
styleUrls: ['./modal.component.less'] }) export class ModalComponent { @ViewChild('OSIOModal') private modal: Modal; private title: string; private buttonText: string; private message: string; private actionKey: string; constructor(private modalService: ModalService) { this.modalService.getComponentObservable().subscribe((params: string[]) => { this.actionKey = params[3]; this.open(params[0], params[1], params[2]); }) } public open(title: string, message: string, buttonText: string) { this.title = title; this.message = message; this.buttonText = buttonText; this.modal.open(); } public doAction() { this.modalService.doAction(this.actionKey); } }
templateUrl: './modal.component.html',
random_line_split
modal.component.ts
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import { Modal } from 'ngx-modal'; import { ModalService } from '../../services/modal.service'; @Component({ selector: 'osio-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.less'] }) export class ModalComponent { @ViewChild('OSIOModal') private modal: Modal; private title: string; private buttonText: string; private message: string; private actionKey: string; constructor(private modalService: ModalService) { this.modalService.getComponentObservable().subscribe((params: string[]) => { this.actionKey = params[3]; this.open(params[0], params[1], params[2]); }) } public
(title: string, message: string, buttonText: string) { this.title = title; this.message = message; this.buttonText = buttonText; this.modal.open(); } public doAction() { this.modalService.doAction(this.actionKey); } }
open
identifier_name
modal.component.ts
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import { Modal } from 'ngx-modal'; import { ModalService } from '../../services/modal.service'; @Component({ selector: 'osio-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.less'] }) export class ModalComponent { @ViewChild('OSIOModal') private modal: Modal; private title: string; private buttonText: string; private message: string; private actionKey: string; constructor(private modalService: ModalService)
public open(title: string, message: string, buttonText: string) { this.title = title; this.message = message; this.buttonText = buttonText; this.modal.open(); } public doAction() { this.modalService.doAction(this.actionKey); } }
{ this.modalService.getComponentObservable().subscribe((params: string[]) => { this.actionKey = params[3]; this.open(params[0], params[1], params[2]); }) }
identifier_body
hyperopt_search.py
#!/usr/bin/env python from __future__ import print_function import sys import math import hyperopt from hyperopt import fmin, tpe, hp from hyperopt.mongoexp import MongoTrials def
(): space = (hp.quniform('numTrees', 1, 10, 1), hp.quniform('samplesPerImage', 10, 7500, 1), hp.quniform('featureCount', 10, 7500, 1), hp.quniform('minSampleCount', 1, 1000, 1), hp.quniform('maxDepth', 5, 25, 1), hp.quniform('boxRadius', 1, 127, 1), hp.quniform('regionSize', 1, 127, 1), hp.quniform('thresholds', 10, 60, 1), hp.uniform('histogramBias', 0.0, 0.6), ) return space def get_exp(mongodb_url, database, exp_key): trials = MongoTrials('mongo://%s/%s/jobs' % (mongodb_url, database), exp_key=exp_key) space = get_space() return trials, space def show(mongodb_url, db, exp_key): print ("Get trials, space...") trials, space = get_exp(mongodb_url, db, exp_key) print ("Get bandit...") bandit = hyperopt.Bandit(expr=space, do_checks=False) print ("Plotting...") # from IPython.core.debugger import Tracer; Tracer()() best_trial = trials.best_trial values = best_trial['misc']['vals'] loss = best_trial['result']['loss'] true_loss = best_trial['result']['true_loss'] print ("values: ", values) print ("loss: ", loss) print ("true_loss: ", true_loss) hyperopt.plotting.main_plot_history(trials) hyperopt.plotting.main_plot_vars(trials, bandit, colorize_best=3) if __name__ == "__main__": if len(sys.argv) < 4: print("usage: %s <mongodb-url> <database> <experiment> [show]" % sys.argv[0], file=sys.stderr) sys.exit(1) mongodb_url, database, exp_key = sys.argv[1:4] if len(sys.argv) == 5: show(mongodb_url, database, exp_key) sys.exit(0) trials, space = get_exp(mongodb_url, database, exp_key) best = fmin(fn=math.sin, space=space, trials=trials, algo=tpe.suggest, max_evals=1000) print("best: %s" % (repr(best)))
get_space
identifier_name
hyperopt_search.py
#!/usr/bin/env python from __future__ import print_function import sys import math import hyperopt from hyperopt import fmin, tpe, hp from hyperopt.mongoexp import MongoTrials def get_space(): space = (hp.quniform('numTrees', 1, 10, 1), hp.quniform('samplesPerImage', 10, 7500, 1), hp.quniform('featureCount', 10, 7500, 1), hp.quniform('minSampleCount', 1, 1000, 1), hp.quniform('maxDepth', 5, 25, 1), hp.quniform('boxRadius', 1, 127, 1), hp.quniform('regionSize', 1, 127, 1), hp.quniform('thresholds', 10, 60, 1), hp.uniform('histogramBias', 0.0, 0.6), ) return space def get_exp(mongodb_url, database, exp_key): trials = MongoTrials('mongo://%s/%s/jobs' % (mongodb_url, database), exp_key=exp_key) space = get_space() return trials, space def show(mongodb_url, db, exp_key): print ("Get trials, space...") trials, space = get_exp(mongodb_url, db, exp_key) print ("Get bandit...") bandit = hyperopt.Bandit(expr=space, do_checks=False) print ("Plotting...") # from IPython.core.debugger import Tracer; Tracer()() best_trial = trials.best_trial values = best_trial['misc']['vals'] loss = best_trial['result']['loss'] true_loss = best_trial['result']['true_loss'] print ("values: ", values) print ("loss: ", loss) print ("true_loss: ", true_loss) hyperopt.plotting.main_plot_history(trials) hyperopt.plotting.main_plot_vars(trials, bandit, colorize_best=3) if __name__ == "__main__": if len(sys.argv) < 4:
mongodb_url, database, exp_key = sys.argv[1:4] if len(sys.argv) == 5: show(mongodb_url, database, exp_key) sys.exit(0) trials, space = get_exp(mongodb_url, database, exp_key) best = fmin(fn=math.sin, space=space, trials=trials, algo=tpe.suggest, max_evals=1000) print("best: %s" % (repr(best)))
print("usage: %s <mongodb-url> <database> <experiment> [show]" % sys.argv[0], file=sys.stderr) sys.exit(1)
conditional_block
hyperopt_search.py
#!/usr/bin/env python from __future__ import print_function import sys import math import hyperopt from hyperopt import fmin, tpe, hp from hyperopt.mongoexp import MongoTrials def get_space():
def get_exp(mongodb_url, database, exp_key): trials = MongoTrials('mongo://%s/%s/jobs' % (mongodb_url, database), exp_key=exp_key) space = get_space() return trials, space def show(mongodb_url, db, exp_key): print ("Get trials, space...") trials, space = get_exp(mongodb_url, db, exp_key) print ("Get bandit...") bandit = hyperopt.Bandit(expr=space, do_checks=False) print ("Plotting...") # from IPython.core.debugger import Tracer; Tracer()() best_trial = trials.best_trial values = best_trial['misc']['vals'] loss = best_trial['result']['loss'] true_loss = best_trial['result']['true_loss'] print ("values: ", values) print ("loss: ", loss) print ("true_loss: ", true_loss) hyperopt.plotting.main_plot_history(trials) hyperopt.plotting.main_plot_vars(trials, bandit, colorize_best=3) if __name__ == "__main__": if len(sys.argv) < 4: print("usage: %s <mongodb-url> <database> <experiment> [show]" % sys.argv[0], file=sys.stderr) sys.exit(1) mongodb_url, database, exp_key = sys.argv[1:4] if len(sys.argv) == 5: show(mongodb_url, database, exp_key) sys.exit(0) trials, space = get_exp(mongodb_url, database, exp_key) best = fmin(fn=math.sin, space=space, trials=trials, algo=tpe.suggest, max_evals=1000) print("best: %s" % (repr(best)))
space = (hp.quniform('numTrees', 1, 10, 1), hp.quniform('samplesPerImage', 10, 7500, 1), hp.quniform('featureCount', 10, 7500, 1), hp.quniform('minSampleCount', 1, 1000, 1), hp.quniform('maxDepth', 5, 25, 1), hp.quniform('boxRadius', 1, 127, 1), hp.quniform('regionSize', 1, 127, 1), hp.quniform('thresholds', 10, 60, 1), hp.uniform('histogramBias', 0.0, 0.6), ) return space
identifier_body
hyperopt_search.py
#!/usr/bin/env python from __future__ import print_function import sys import math import hyperopt from hyperopt import fmin, tpe, hp from hyperopt.mongoexp import MongoTrials
hp.quniform('samplesPerImage', 10, 7500, 1), hp.quniform('featureCount', 10, 7500, 1), hp.quniform('minSampleCount', 1, 1000, 1), hp.quniform('maxDepth', 5, 25, 1), hp.quniform('boxRadius', 1, 127, 1), hp.quniform('regionSize', 1, 127, 1), hp.quniform('thresholds', 10, 60, 1), hp.uniform('histogramBias', 0.0, 0.6), ) return space def get_exp(mongodb_url, database, exp_key): trials = MongoTrials('mongo://%s/%s/jobs' % (mongodb_url, database), exp_key=exp_key) space = get_space() return trials, space def show(mongodb_url, db, exp_key): print ("Get trials, space...") trials, space = get_exp(mongodb_url, db, exp_key) print ("Get bandit...") bandit = hyperopt.Bandit(expr=space, do_checks=False) print ("Plotting...") # from IPython.core.debugger import Tracer; Tracer()() best_trial = trials.best_trial values = best_trial['misc']['vals'] loss = best_trial['result']['loss'] true_loss = best_trial['result']['true_loss'] print ("values: ", values) print ("loss: ", loss) print ("true_loss: ", true_loss) hyperopt.plotting.main_plot_history(trials) hyperopt.plotting.main_plot_vars(trials, bandit, colorize_best=3) if __name__ == "__main__": if len(sys.argv) < 4: print("usage: %s <mongodb-url> <database> <experiment> [show]" % sys.argv[0], file=sys.stderr) sys.exit(1) mongodb_url, database, exp_key = sys.argv[1:4] if len(sys.argv) == 5: show(mongodb_url, database, exp_key) sys.exit(0) trials, space = get_exp(mongodb_url, database, exp_key) best = fmin(fn=math.sin, space=space, trials=trials, algo=tpe.suggest, max_evals=1000) print("best: %s" % (repr(best)))
def get_space(): space = (hp.quniform('numTrees', 1, 10, 1),
random_line_split
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal` lint detects Unicode codepoints that change the /// visual representation of text on screen in a way that does not correspond to their on /// memory representation. /// /// ### Explanation /// /// The unicode characters `\u{202A}`, `\u{202B}`, `\u{202D}`, `\u{202E}`, `\u{2066}`, /// `\u{2067}`, `\u{2068}`, `\u{202C}` and `\u{2069}` make the flow of text on screen change /// its direction on software that supports these codepoints. This makes the text "abc" display /// as "cba" on screen. By leveraging software that supports these, people can write specially /// crafted literals that make the surrounding code seem like it's performing one action, when /// in reality it is performing another. Because of this, we proactively lint against their /// presence to avoid surprises. /// /// ### Example /// /// ```rust,compile_fail /// #![deny(text_direction_codepoint_in_literal)] /// fn main() { /// println!("{:?}", '‮'); /// } /// ``` /// /// {{produces}} /// pub TEXT_DIRECTION_CODEPOINT_IN_LITERAL, Deny, "detect special Unicode codepoints that affect the visual representation of text on screen, \ changing the direction in which text flows", } declare_lint_pass!(HiddenUnicodeCodepoints => [TEXT_DIRECTION_CODEPOINT_IN_LITERAL]); impl HiddenUnicodeCodepoints { fn li
&self, cx: &EarlyContext<'_>, text: Symbol, span: Span, padding: u32, point_at_inner_spans: bool, label: &str, ) { // Obtain the `Span`s for each of the forbidden chars. let spans: Vec<_> = text .as_str() .char_indices() .filter_map(|(i, c)| { TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| { let lo = span.lo() + BytePos(i as u32 + padding); (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32))) }) }) .collect(); cx.struct_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, |lint| { let mut err = lint.build(&format!( "unicode codepoint changing visible direction of text present in {}", label )); let (an, s) = match spans.len() { 1 => ("an ", ""), _ => ("", "s"), }; err.span_label( span, &format!( "this {} contains {}invisible unicode text flow control codepoint{}", label, an, s, ), ); if point_at_inner_spans { for (c, span) in &spans { err.span_label(*span, format!("{:?}", c)); } } err.note( "these kind of unicode codepoints change the way text flows on applications that \ support them, but can cause confusion because they change the order of \ characters on the screen", ); if point_at_inner_spans && !spans.is_empty() { err.multipart_suggestion_with_style( "if their presence wasn't intentional, you can remove them", spans.iter().map(|(_, span)| (*span, "".to_string())).collect(), Applicability::MachineApplicable, SuggestionStyle::HideCodeAlways, ); err.multipart_suggestion( "if you want to keep them but make them visible in your source code, you can \ escape them", spans .into_iter() .map(|(c, span)| { let c = format!("{:?}", c); (span, c[1..c.len() - 1].to_string()) }) .collect(), Applicability::MachineApplicable, ); } else { // FIXME: in other suggestions we've reversed the inner spans of doc comments. We // should do the same here to provide the same good suggestions as we do for // literals above. err.note("if their presence wasn't intentional, you can remove them"); err.note(&format!( "if you want to keep them but make them visible in your source code, you can \ escape them: {}", spans .into_iter() .map(|(c, _)| { format!("{:?}", c) }) .collect::<Vec<String>>() .join(", "), )); } err.emit(); }); } } impl EarlyLintPass for HiddenUnicodeCodepoints { fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { if let ast::AttrKind::DocComment(_, comment) = attr.kind { if contains_text_flow_control_chars(&comment.as_str()) { self.lint_text_direction_codepoint(cx, comment, attr.span, 0, false, "doc comment"); } } } fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { // byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString` let (text, span, padding) = match &expr.kind { ast::ExprKind::Lit(ast::Lit { token, kind, span }) => { let text = token.symbol; if !contains_text_flow_control_chars(&text.as_str()) { return; } let padding = match kind { // account for `"` or `'` ast::LitKind::Str(_, ast::StrStyle::Cooked) | ast::LitKind::Char(_) => 1, // account for `r###"` ast::LitKind::Str(_, ast::StrStyle::Raw(val)) => *val as u32 + 2, _ => return, }; (text, span, padding) } _ => return, }; self.lint_text_direction_codepoint(cx, text, *span, padding, true, "literal"); } }
nt_text_direction_codepoint(
identifier_name
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal` lint detects Unicode codepoints that change the /// visual representation of text on screen in a way that does not correspond to their on /// memory representation. /// /// ### Explanation /// /// The unicode characters `\u{202A}`, `\u{202B}`, `\u{202D}`, `\u{202E}`, `\u{2066}`, /// `\u{2067}`, `\u{2068}`, `\u{202C}` and `\u{2069}` make the flow of text on screen change /// its direction on software that supports these codepoints. This makes the text "abc" display /// as "cba" on screen. By leveraging software that supports these, people can write specially /// crafted literals that make the surrounding code seem like it's performing one action, when /// in reality it is performing another. Because of this, we proactively lint against their /// presence to avoid surprises. /// /// ### Example /// /// ```rust,compile_fail /// #![deny(text_direction_codepoint_in_literal)] /// fn main() { /// println!("{:?}", '‮'); /// } /// ``` /// /// {{produces}} /// pub TEXT_DIRECTION_CODEPOINT_IN_LITERAL, Deny, "detect special Unicode codepoints that affect the visual representation of text on screen, \ changing the direction in which text flows", } declare_lint_pass!(HiddenUnicodeCodepoints => [TEXT_DIRECTION_CODEPOINT_IN_LITERAL]); impl HiddenUnicodeCodepoints { fn lint_text_direction_codepoint( &self, cx: &EarlyContext<'_>, text: Symbol, span: Span, padding: u32, point_at_inner_spans: bool, label: &str, ) { // Obtain the `Span`s for each of the forbidden chars. let spans: Vec<_> = text .as_str() .char_indices() .filter_map(|(i, c)| { TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| { let lo = span.lo() + BytePos(i as u32 + padding); (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32))) }) }) .collect(); cx.struct_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, |lint| { let mut err = lint.build(&format!( "unicode codepoint changing visible direction of text present in {}", label )); let (an, s) = match spans.len() { 1 => ("an ", ""), _ => ("", "s"), }; err.span_label( span, &format!( "this {} contains {}invisible unicode text flow control codepoint{}", label, an, s, ), ); if point_at_inner_spans { for (c, span) in &spans { err.span_label(*span, format!("{:?}", c)); } } err.note( "these kind of unicode codepoints change the way text flows on applications that \ support them, but can cause confusion because they change the order of \ characters on the screen", ); if point_at_inner_spans && !spans.is_empty() { err.multipart_suggestion_with_style( "if their presence wasn't intentional, you can remove them", spans.iter().map(|(_, span)| (*span, "".to_string())).collect(), Applicability::MachineApplicable, SuggestionStyle::HideCodeAlways, ); err.multipart_suggestion( "if you want to keep them but make them visible in your source code, you can \ escape them", spans .into_iter() .map(|(c, span)| { let c = format!("{:?}", c); (span, c[1..c.len() - 1].to_string()) }) .collect(), Applicability::MachineApplicable, ); } else { // FIXME: in other suggestions we've reversed the inner spans of doc comments. We // should do the same here to provide the same good suggestions as we do for // literals above. err.note("if their presence wasn't intentional, you can remove them"); err.note(&format!( "if you want to keep them but make them visible in your source code, you can \ escape them: {}", spans .into_iter() .map(|(c, _)| { format!("{:?}", c) }) .collect::<Vec<String>>() .join(", "), )); } err.emit(); }); } } impl EarlyLintPass for HiddenUnicodeCodepoints { fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { if let ast::AttrKind::DocComment(_, comment) = attr.kind { if contains_text_flow_control_chars(&comment.as_str()) { self.lint_text_direction_codepoint(cx, comment, attr.span, 0, false, "doc comment"); } } } fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
// byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString` let (text, span, padding) = match &expr.kind { ast::ExprKind::Lit(ast::Lit { token, kind, span }) => { let text = token.symbol; if !contains_text_flow_control_chars(&text.as_str()) { return; } let padding = match kind { // account for `"` or `'` ast::LitKind::Str(_, ast::StrStyle::Cooked) | ast::LitKind::Char(_) => 1, // account for `r###"` ast::LitKind::Str(_, ast::StrStyle::Raw(val)) => *val as u32 + 2, _ => return, }; (text, span, padding) } _ => return, }; self.lint_text_direction_codepoint(cx, text, *span, padding, true, "literal"); } }
identifier_body
hidden_unicode_codepoints.rs
use crate::{EarlyContext, EarlyLintPass, LintContext}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_errors::{Applicability, SuggestionStyle}; use rustc_span::{BytePos, Span, Symbol}; declare_lint! { /// The `text_direction_codepoint_in_literal` lint detects Unicode codepoints that change the /// visual representation of text on screen in a way that does not correspond to their on /// memory representation. /// /// ### Explanation /// /// The unicode characters `\u{202A}`, `\u{202B}`, `\u{202D}`, `\u{202E}`, `\u{2066}`, /// `\u{2067}`, `\u{2068}`, `\u{202C}` and `\u{2069}` make the flow of text on screen change /// its direction on software that supports these codepoints. This makes the text "abc" display /// as "cba" on screen. By leveraging software that supports these, people can write specially /// crafted literals that make the surrounding code seem like it's performing one action, when /// in reality it is performing another. Because of this, we proactively lint against their /// presence to avoid surprises. /// /// ### Example /// /// ```rust,compile_fail /// #![deny(text_direction_codepoint_in_literal)] /// fn main() { /// println!("{:?}", '‮'); /// } /// ``` /// /// {{produces}} /// pub TEXT_DIRECTION_CODEPOINT_IN_LITERAL, Deny, "detect special Unicode codepoints that affect the visual representation of text on screen, \ changing the direction in which text flows", } declare_lint_pass!(HiddenUnicodeCodepoints => [TEXT_DIRECTION_CODEPOINT_IN_LITERAL]); impl HiddenUnicodeCodepoints { fn lint_text_direction_codepoint( &self, cx: &EarlyContext<'_>, text: Symbol, span: Span, padding: u32, point_at_inner_spans: bool, label: &str, ) { // Obtain the `Span`s for each of the forbidden chars. let spans: Vec<_> = text .as_str() .char_indices() .filter_map(|(i, c)| { TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| { let lo = span.lo() + BytePos(i as u32 + padding); (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32))) }) }) .collect(); cx.struct_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, |lint| { let mut err = lint.build(&format!( "unicode codepoint changing visible direction of text present in {}", label )); let (an, s) = match spans.len() { 1 => ("an ", ""), _ => ("", "s"), }; err.span_label( span, &format!( "this {} contains {}invisible unicode text flow control codepoint{}", label, an, s, ), ); if point_at_inner_spans { for (c, span) in &spans { err.span_label(*span, format!("{:?}", c)); } } err.note( "these kind of unicode codepoints change the way text flows on applications that \ support them, but can cause confusion because they change the order of \ characters on the screen", ); if point_at_inner_spans && !spans.is_empty() { err.multipart_suggestion_with_style( "if their presence wasn't intentional, you can remove them",
err.multipart_suggestion( "if you want to keep them but make them visible in your source code, you can \ escape them", spans .into_iter() .map(|(c, span)| { let c = format!("{:?}", c); (span, c[1..c.len() - 1].to_string()) }) .collect(), Applicability::MachineApplicable, ); } else { // FIXME: in other suggestions we've reversed the inner spans of doc comments. We // should do the same here to provide the same good suggestions as we do for // literals above. err.note("if their presence wasn't intentional, you can remove them"); err.note(&format!( "if you want to keep them but make them visible in your source code, you can \ escape them: {}", spans .into_iter() .map(|(c, _)| { format!("{:?}", c) }) .collect::<Vec<String>>() .join(", "), )); } err.emit(); }); } } impl EarlyLintPass for HiddenUnicodeCodepoints { fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { if let ast::AttrKind::DocComment(_, comment) = attr.kind { if contains_text_flow_control_chars(&comment.as_str()) { self.lint_text_direction_codepoint(cx, comment, attr.span, 0, false, "doc comment"); } } } fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { // byte strings are already handled well enough by `EscapeError::NonAsciiCharInByteString` let (text, span, padding) = match &expr.kind { ast::ExprKind::Lit(ast::Lit { token, kind, span }) => { let text = token.symbol; if !contains_text_flow_control_chars(&text.as_str()) { return; } let padding = match kind { // account for `"` or `'` ast::LitKind::Str(_, ast::StrStyle::Cooked) | ast::LitKind::Char(_) => 1, // account for `r###"` ast::LitKind::Str(_, ast::StrStyle::Raw(val)) => *val as u32 + 2, _ => return, }; (text, span, padding) } _ => return, }; self.lint_text_direction_codepoint(cx, text, *span, padding, true, "literal"); } }
spans.iter().map(|(_, span)| (*span, "".to_string())).collect(), Applicability::MachineApplicable, SuggestionStyle::HideCodeAlways, );
random_line_split
status-dialog.spec.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { render } from '@testing-library/react'; import React from 'react'; import { anywhereMatcher, StatusDialog } from './status-dialog'; describe('StatusDialog', () => {
it('matches snapshot', () => { const statusDialog = <StatusDialog onClose={() => {}} />; render(statusDialog); expect(document.body.lastChild).toMatchSnapshot(); }); it('filters data that contains input', () => { const row = [ 'org.apache.druid.common.gcp.GcpModule', 'org.apache.druid.common.aws.AWSModule', 'org.apache.druid.OtherModule', ]; expect(anywhereMatcher({ id: '0', value: 'common' }, row)).toEqual(true); expect(anywhereMatcher({ id: '1', value: 'common' }, row)).toEqual(true); expect(anywhereMatcher({ id: '0', value: 'org' }, row)).toEqual(true); expect(anywhereMatcher({ id: '1', value: 'org' }, row)).toEqual(true); expect(anywhereMatcher({ id: '2', value: 'common' }, row)).toEqual(false); }); });
random_line_split
htmltextareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{AttributeHandlers, HTMLTextAreaElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLTextAreaElement { htmlelement: HTMLElement, } impl HTMLTextAreaElementDerived for EventTarget { fn is_htmltextareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTextAreaElementTypeId)) } } impl HTMLTextAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement { HTMLTextAreaElement { htmlelement: HTMLElement::new_inherited(HTMLTextAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTextAreaElement>
} impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> { // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type fn Type(self) -> DOMString { "textarea".to_string() } } impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLTextAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
{ let element = HTMLTextAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTextAreaElementBinding::Wrap) }
identifier_body
htmltextareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{AttributeHandlers, HTMLTextAreaElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLTextAreaElement { htmlelement: HTMLElement, } impl HTMLTextAreaElementDerived for EventTarget { fn is_htmltextareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTextAreaElementTypeId)) } } impl HTMLTextAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement { HTMLTextAreaElement { htmlelement: HTMLElement::new_inherited(HTMLTextAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTextAreaElement> { let element = HTMLTextAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTextAreaElementBinding::Wrap) } } impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> { // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type fn Type(self) -> DOMString { "textarea".to_string() } } impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn
(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLTextAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
after_set_attr
identifier_name
htmltextareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::{AttributeHandlers, HTMLTextAreaElementTypeId}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLTextAreaElement { htmlelement: HTMLElement, } impl HTMLTextAreaElementDerived for EventTarget { fn is_htmltextareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTextAreaElementTypeId)) } } impl HTMLTextAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement { HTMLTextAreaElement { htmlelement: HTMLElement::new_inherited(HTMLTextAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTextAreaElement> { let element = HTMLTextAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTextAreaElementBinding::Wrap) } } impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> { // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type fn Type(self) -> DOMString { "textarea".to_string() } } impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => {
} } fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); match name.as_slice() { "disabled" => { node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } } impl Reflectable for HTMLTextAreaElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
node.set_disabled_state(true); node.set_enabled_state(false); }, _ => ()
random_line_split
index.ts
// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Optional, Injector, Input } from '@angular/core'; import { Content, ModalController } from 'ionic-angular'; import { CoreAppProvider } from '@providers/app'; import { CoreCourseProvider } from '@core/course/providers/course'; import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component'; import { AddonModBookProvider, AddonModBookContentsMap, AddonModBookTocChapter } from '../../providers/book'; import { AddonModBookPrefetchHandler } from '../../providers/prefetch-handler'; import { CoreTagProvider } from '@core/tag/providers/tag'; /** * Component that displays a book. */ @Component({ selector: 'addon-mod-book-index', templateUrl: 'addon-mod-book-index.html', }) export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComponent { @Input() initialChapterId: string; // The initial chapter ID to load. component = AddonModBookProvider.COMPONENT; chapterContent: string; previousChapter: string; nextChapter: string; tagsEnabled: boolean; protected chapters: AddonModBookTocChapter[]; protected currentChapter: string; protected contentsMap: AddonModBookContentsMap; constructor(injector: Injector, private bookProvider: AddonModBookProvider, private courseProvider: CoreCourseProvider, private appProvider: CoreAppProvider, private prefetchDelegate: AddonModBookPrefetchHandler, private modalCtrl: ModalController, private tagProvider: CoreTagProvider, @Optional() private content: Content) { super(injector); } /** * Component being initialized. */ ngOnInit(): void { super.ngOnInit(); this.tagsEnabled = this.tagProvider.areTagsAvailableInSite(); this.loadContent(); } /** * Show the TOC. * * @param {MouseEvent} event Event. */ showToc(event: MouseEvent): void { // Create the toc modal. const modal = this.modalCtrl.create('AddonModBookTocPage', { chapters: this.chapters, selected: this.currentChapter }, { cssClass: 'core-modal-lateral', showBackdrop: true, enableBackdropDismiss: true, enterAnimation: 'core-modal-lateral-transition', leaveAnimation: 'core-modal-lateral-transition' }); modal.onDidDismiss((chapterId) => { if (chapterId) { this.changeChapter(chapterId); } }); modal.present({ ev: event }); } /** * Change the current chapter. * * @param {string} chapterId Chapter to load. * @return {Promise<void>} Promise resolved when done. */ changeChapter(chapterId: string): void { if (chapterId && chapterId != this.currentChapter) { this.loaded = false; this.refreshIcon = 'spinner'; this.loadChapter(chapterId); } } /** * Perform the invalidate content function. * * @return {Promise<any>} Resolved when done. */ protected invalidateContent(): Promise<any> { return this.bookProvider.invalidateContent(this.module.id, this.courseId); } /** * Download book contents and load the current chapter. * * @param {boolean} [refresh] Whether we're refreshing data. * @return {Promise<any>} Promise resolved when done. */ protected fetchContent(refresh?: boolean): Promise<any> { const promises = []; let downloadFailed = false; // Try to get the book data. promises.push(this.bookProvider.getBook(this.courseId, this.module.id).then((book) => { this.dataRetrieved.emit(book); this.description = book.intro || this.description; }).catch(() => { // Ignore errors since this WS isn't available in some Moodle versions. })); // Download content. This function also loads module contents if needed. promises.push(this.prefetchDelegate.download(this.module, this.courseId).catch(() => { // Mark download as failed but go on since the main files could have been downloaded. downloadFailed = true; if (!this.module.contents.length) { // Try to load module contents for offline usage. return this.courseProvider.loadModuleContents(this.module, this.courseId); } })); return Promise.all(promises).then(() => { this.contentsMap = this.bookProvider.getContentsMap(this.module.contents); this.chapters = this.bookProvider.getTocList(this.module.contents); if (typeof this.currentChapter == 'undefined' && typeof this.initialChapterId != 'undefined' && this.chapters) { // Initial chapter set. Validate that the chapter exists. const chapter = this.chapters.find((chapter) => { return chapter.id == this.initialChapterId; }); if (chapter)
} if (typeof this.currentChapter == 'undefined') { // Load the first chapter. this.currentChapter = this.bookProvider.getFirstChapter(this.chapters); } // Show chapter. return this.loadChapter(this.currentChapter).then(() => { if (downloadFailed && this.appProvider.isOnline()) { // We could load the main file but the download failed. Show error message. this.domUtils.showErrorModal('core.errordownloadingsomefiles', true); } // All data obtained, now fill the context menu. this.fillContextMenu(refresh); }).catch(() => { // Ignore errors, they're handled inside the loadChapter function. }); }); } /** * Load a book chapter. * * @param {string} chapterId Chapter to load. * @return {Promise<void>} Promise resolved when done. */ protected loadChapter(chapterId: string): Promise<void> { this.currentChapter = chapterId; this.domUtils.scrollToTop(this.content); return this.bookProvider.getChapterContent(this.contentsMap, chapterId, this.module.id).then((content) => { this.chapterContent = content; this.previousChapter = this.bookProvider.getPreviousChapter(this.chapters, chapterId); this.nextChapter = this.bookProvider.getNextChapter(this.chapters, chapterId); // Chapter loaded, log view. We don't return the promise because we don't want to block the user for this. this.bookProvider.logView(this.module.instance, chapterId, this.module.name).then(() => { // Module is completed when last chapter is viewed, so we only check completion if the last is reached. if (this.nextChapter == '0') { this.courseProvider.checkModuleCompletion(this.courseId, this.module.completiondata); } }).catch(() => { // Ignore errors. }); }).catch((error) => { this.domUtils.showErrorModalDefault(error, 'addon.mod_book.errorchapter', true); return Promise.reject(null); }).finally(() => { this.loaded = true; this.refreshIcon = 'refresh'; }); } }
{ this.currentChapter = this.initialChapterId; }
conditional_block
index.ts
// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Optional, Injector, Input } from '@angular/core'; import { Content, ModalController } from 'ionic-angular'; import { CoreAppProvider } from '@providers/app'; import { CoreCourseProvider } from '@core/course/providers/course'; import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component'; import { AddonModBookProvider, AddonModBookContentsMap, AddonModBookTocChapter } from '../../providers/book'; import { AddonModBookPrefetchHandler } from '../../providers/prefetch-handler'; import { CoreTagProvider } from '@core/tag/providers/tag';
* Component that displays a book. */ @Component({ selector: 'addon-mod-book-index', templateUrl: 'addon-mod-book-index.html', }) export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComponent { @Input() initialChapterId: string; // The initial chapter ID to load. component = AddonModBookProvider.COMPONENT; chapterContent: string; previousChapter: string; nextChapter: string; tagsEnabled: boolean; protected chapters: AddonModBookTocChapter[]; protected currentChapter: string; protected contentsMap: AddonModBookContentsMap; constructor(injector: Injector, private bookProvider: AddonModBookProvider, private courseProvider: CoreCourseProvider, private appProvider: CoreAppProvider, private prefetchDelegate: AddonModBookPrefetchHandler, private modalCtrl: ModalController, private tagProvider: CoreTagProvider, @Optional() private content: Content) { super(injector); } /** * Component being initialized. */ ngOnInit(): void { super.ngOnInit(); this.tagsEnabled = this.tagProvider.areTagsAvailableInSite(); this.loadContent(); } /** * Show the TOC. * * @param {MouseEvent} event Event. */ showToc(event: MouseEvent): void { // Create the toc modal. const modal = this.modalCtrl.create('AddonModBookTocPage', { chapters: this.chapters, selected: this.currentChapter }, { cssClass: 'core-modal-lateral', showBackdrop: true, enableBackdropDismiss: true, enterAnimation: 'core-modal-lateral-transition', leaveAnimation: 'core-modal-lateral-transition' }); modal.onDidDismiss((chapterId) => { if (chapterId) { this.changeChapter(chapterId); } }); modal.present({ ev: event }); } /** * Change the current chapter. * * @param {string} chapterId Chapter to load. * @return {Promise<void>} Promise resolved when done. */ changeChapter(chapterId: string): void { if (chapterId && chapterId != this.currentChapter) { this.loaded = false; this.refreshIcon = 'spinner'; this.loadChapter(chapterId); } } /** * Perform the invalidate content function. * * @return {Promise<any>} Resolved when done. */ protected invalidateContent(): Promise<any> { return this.bookProvider.invalidateContent(this.module.id, this.courseId); } /** * Download book contents and load the current chapter. * * @param {boolean} [refresh] Whether we're refreshing data. * @return {Promise<any>} Promise resolved when done. */ protected fetchContent(refresh?: boolean): Promise<any> { const promises = []; let downloadFailed = false; // Try to get the book data. promises.push(this.bookProvider.getBook(this.courseId, this.module.id).then((book) => { this.dataRetrieved.emit(book); this.description = book.intro || this.description; }).catch(() => { // Ignore errors since this WS isn't available in some Moodle versions. })); // Download content. This function also loads module contents if needed. promises.push(this.prefetchDelegate.download(this.module, this.courseId).catch(() => { // Mark download as failed but go on since the main files could have been downloaded. downloadFailed = true; if (!this.module.contents.length) { // Try to load module contents for offline usage. return this.courseProvider.loadModuleContents(this.module, this.courseId); } })); return Promise.all(promises).then(() => { this.contentsMap = this.bookProvider.getContentsMap(this.module.contents); this.chapters = this.bookProvider.getTocList(this.module.contents); if (typeof this.currentChapter == 'undefined' && typeof this.initialChapterId != 'undefined' && this.chapters) { // Initial chapter set. Validate that the chapter exists. const chapter = this.chapters.find((chapter) => { return chapter.id == this.initialChapterId; }); if (chapter) { this.currentChapter = this.initialChapterId; } } if (typeof this.currentChapter == 'undefined') { // Load the first chapter. this.currentChapter = this.bookProvider.getFirstChapter(this.chapters); } // Show chapter. return this.loadChapter(this.currentChapter).then(() => { if (downloadFailed && this.appProvider.isOnline()) { // We could load the main file but the download failed. Show error message. this.domUtils.showErrorModal('core.errordownloadingsomefiles', true); } // All data obtained, now fill the context menu. this.fillContextMenu(refresh); }).catch(() => { // Ignore errors, they're handled inside the loadChapter function. }); }); } /** * Load a book chapter. * * @param {string} chapterId Chapter to load. * @return {Promise<void>} Promise resolved when done. */ protected loadChapter(chapterId: string): Promise<void> { this.currentChapter = chapterId; this.domUtils.scrollToTop(this.content); return this.bookProvider.getChapterContent(this.contentsMap, chapterId, this.module.id).then((content) => { this.chapterContent = content; this.previousChapter = this.bookProvider.getPreviousChapter(this.chapters, chapterId); this.nextChapter = this.bookProvider.getNextChapter(this.chapters, chapterId); // Chapter loaded, log view. We don't return the promise because we don't want to block the user for this. this.bookProvider.logView(this.module.instance, chapterId, this.module.name).then(() => { // Module is completed when last chapter is viewed, so we only check completion if the last is reached. if (this.nextChapter == '0') { this.courseProvider.checkModuleCompletion(this.courseId, this.module.completiondata); } }).catch(() => { // Ignore errors. }); }).catch((error) => { this.domUtils.showErrorModalDefault(error, 'addon.mod_book.errorchapter', true); return Promise.reject(null); }).finally(() => { this.loaded = true; this.refreshIcon = 'refresh'; }); } }
/**
random_line_split
index.ts
// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Optional, Injector, Input } from '@angular/core'; import { Content, ModalController } from 'ionic-angular'; import { CoreAppProvider } from '@providers/app'; import { CoreCourseProvider } from '@core/course/providers/course'; import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component'; import { AddonModBookProvider, AddonModBookContentsMap, AddonModBookTocChapter } from '../../providers/book'; import { AddonModBookPrefetchHandler } from '../../providers/prefetch-handler'; import { CoreTagProvider } from '@core/tag/providers/tag'; /** * Component that displays a book. */ @Component({ selector: 'addon-mod-book-index', templateUrl: 'addon-mod-book-index.html', }) export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComponent { @Input() initialChapterId: string; // The initial chapter ID to load. component = AddonModBookProvider.COMPONENT; chapterContent: string; previousChapter: string; nextChapter: string; tagsEnabled: boolean; protected chapters: AddonModBookTocChapter[]; protected currentChapter: string; protected contentsMap: AddonModBookContentsMap; constructor(injector: Injector, private bookProvider: AddonModBookProvider, private courseProvider: CoreCourseProvider, private appProvider: CoreAppProvider, private prefetchDelegate: AddonModBookPrefetchHandler, private modalCtrl: ModalController, private tagProvider: CoreTagProvider, @Optional() private content: Content) { super(injector); } /** * Component being initialized. */ ngOnInit(): void { super.ngOnInit(); this.tagsEnabled = this.tagProvider.areTagsAvailableInSite(); this.loadContent(); } /** * Show the TOC. * * @param {MouseEvent} event Event. */ showToc(event: MouseEvent): void { // Create the toc modal. const modal = this.modalCtrl.create('AddonModBookTocPage', { chapters: this.chapters, selected: this.currentChapter }, { cssClass: 'core-modal-lateral', showBackdrop: true, enableBackdropDismiss: true, enterAnimation: 'core-modal-lateral-transition', leaveAnimation: 'core-modal-lateral-transition' }); modal.onDidDismiss((chapterId) => { if (chapterId) { this.changeChapter(chapterId); } }); modal.present({ ev: event }); } /** * Change the current chapter. * * @param {string} chapterId Chapter to load. * @return {Promise<void>} Promise resolved when done. */ changeChapter(chapterId: string): void
/** * Perform the invalidate content function. * * @return {Promise<any>} Resolved when done. */ protected invalidateContent(): Promise<any> { return this.bookProvider.invalidateContent(this.module.id, this.courseId); } /** * Download book contents and load the current chapter. * * @param {boolean} [refresh] Whether we're refreshing data. * @return {Promise<any>} Promise resolved when done. */ protected fetchContent(refresh?: boolean): Promise<any> { const promises = []; let downloadFailed = false; // Try to get the book data. promises.push(this.bookProvider.getBook(this.courseId, this.module.id).then((book) => { this.dataRetrieved.emit(book); this.description = book.intro || this.description; }).catch(() => { // Ignore errors since this WS isn't available in some Moodle versions. })); // Download content. This function also loads module contents if needed. promises.push(this.prefetchDelegate.download(this.module, this.courseId).catch(() => { // Mark download as failed but go on since the main files could have been downloaded. downloadFailed = true; if (!this.module.contents.length) { // Try to load module contents for offline usage. return this.courseProvider.loadModuleContents(this.module, this.courseId); } })); return Promise.all(promises).then(() => { this.contentsMap = this.bookProvider.getContentsMap(this.module.contents); this.chapters = this.bookProvider.getTocList(this.module.contents); if (typeof this.currentChapter == 'undefined' && typeof this.initialChapterId != 'undefined' && this.chapters) { // Initial chapter set. Validate that the chapter exists. const chapter = this.chapters.find((chapter) => { return chapter.id == this.initialChapterId; }); if (chapter) { this.currentChapter = this.initialChapterId; } } if (typeof this.currentChapter == 'undefined') { // Load the first chapter. this.currentChapter = this.bookProvider.getFirstChapter(this.chapters); } // Show chapter. return this.loadChapter(this.currentChapter).then(() => { if (downloadFailed && this.appProvider.isOnline()) { // We could load the main file but the download failed. Show error message. this.domUtils.showErrorModal('core.errordownloadingsomefiles', true); } // All data obtained, now fill the context menu. this.fillContextMenu(refresh); }).catch(() => { // Ignore errors, they're handled inside the loadChapter function. }); }); } /** * Load a book chapter. * * @param {string} chapterId Chapter to load. * @return {Promise<void>} Promise resolved when done. */ protected loadChapter(chapterId: string): Promise<void> { this.currentChapter = chapterId; this.domUtils.scrollToTop(this.content); return this.bookProvider.getChapterContent(this.contentsMap, chapterId, this.module.id).then((content) => { this.chapterContent = content; this.previousChapter = this.bookProvider.getPreviousChapter(this.chapters, chapterId); this.nextChapter = this.bookProvider.getNextChapter(this.chapters, chapterId); // Chapter loaded, log view. We don't return the promise because we don't want to block the user for this. this.bookProvider.logView(this.module.instance, chapterId, this.module.name).then(() => { // Module is completed when last chapter is viewed, so we only check completion if the last is reached. if (this.nextChapter == '0') { this.courseProvider.checkModuleCompletion(this.courseId, this.module.completiondata); } }).catch(() => { // Ignore errors. }); }).catch((error) => { this.domUtils.showErrorModalDefault(error, 'addon.mod_book.errorchapter', true); return Promise.reject(null); }).finally(() => { this.loaded = true; this.refreshIcon = 'refresh'; }); } }
{ if (chapterId && chapterId != this.currentChapter) { this.loaded = false; this.refreshIcon = 'spinner'; this.loadChapter(chapterId); } }
identifier_body
index.ts
// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Optional, Injector, Input } from '@angular/core'; import { Content, ModalController } from 'ionic-angular'; import { CoreAppProvider } from '@providers/app'; import { CoreCourseProvider } from '@core/course/providers/course'; import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component'; import { AddonModBookProvider, AddonModBookContentsMap, AddonModBookTocChapter } from '../../providers/book'; import { AddonModBookPrefetchHandler } from '../../providers/prefetch-handler'; import { CoreTagProvider } from '@core/tag/providers/tag'; /** * Component that displays a book. */ @Component({ selector: 'addon-mod-book-index', templateUrl: 'addon-mod-book-index.html', }) export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComponent { @Input() initialChapterId: string; // The initial chapter ID to load. component = AddonModBookProvider.COMPONENT; chapterContent: string; previousChapter: string; nextChapter: string; tagsEnabled: boolean; protected chapters: AddonModBookTocChapter[]; protected currentChapter: string; protected contentsMap: AddonModBookContentsMap; constructor(injector: Injector, private bookProvider: AddonModBookProvider, private courseProvider: CoreCourseProvider, private appProvider: CoreAppProvider, private prefetchDelegate: AddonModBookPrefetchHandler, private modalCtrl: ModalController, private tagProvider: CoreTagProvider, @Optional() private content: Content) { super(injector); } /** * Component being initialized. */ ngOnInit(): void { super.ngOnInit(); this.tagsEnabled = this.tagProvider.areTagsAvailableInSite(); this.loadContent(); } /** * Show the TOC. * * @param {MouseEvent} event Event. */ showToc(event: MouseEvent): void { // Create the toc modal. const modal = this.modalCtrl.create('AddonModBookTocPage', { chapters: this.chapters, selected: this.currentChapter }, { cssClass: 'core-modal-lateral', showBackdrop: true, enableBackdropDismiss: true, enterAnimation: 'core-modal-lateral-transition', leaveAnimation: 'core-modal-lateral-transition' }); modal.onDidDismiss((chapterId) => { if (chapterId) { this.changeChapter(chapterId); } }); modal.present({ ev: event }); } /** * Change the current chapter. * * @param {string} chapterId Chapter to load. * @return {Promise<void>} Promise resolved when done. */ changeChapter(chapterId: string): void { if (chapterId && chapterId != this.currentChapter) { this.loaded = false; this.refreshIcon = 'spinner'; this.loadChapter(chapterId); } } /** * Perform the invalidate content function. * * @return {Promise<any>} Resolved when done. */ protected invalidateContent(): Promise<any> { return this.bookProvider.invalidateContent(this.module.id, this.courseId); } /** * Download book contents and load the current chapter. * * @param {boolean} [refresh] Whether we're refreshing data. * @return {Promise<any>} Promise resolved when done. */ protected
(refresh?: boolean): Promise<any> { const promises = []; let downloadFailed = false; // Try to get the book data. promises.push(this.bookProvider.getBook(this.courseId, this.module.id).then((book) => { this.dataRetrieved.emit(book); this.description = book.intro || this.description; }).catch(() => { // Ignore errors since this WS isn't available in some Moodle versions. })); // Download content. This function also loads module contents if needed. promises.push(this.prefetchDelegate.download(this.module, this.courseId).catch(() => { // Mark download as failed but go on since the main files could have been downloaded. downloadFailed = true; if (!this.module.contents.length) { // Try to load module contents for offline usage. return this.courseProvider.loadModuleContents(this.module, this.courseId); } })); return Promise.all(promises).then(() => { this.contentsMap = this.bookProvider.getContentsMap(this.module.contents); this.chapters = this.bookProvider.getTocList(this.module.contents); if (typeof this.currentChapter == 'undefined' && typeof this.initialChapterId != 'undefined' && this.chapters) { // Initial chapter set. Validate that the chapter exists. const chapter = this.chapters.find((chapter) => { return chapter.id == this.initialChapterId; }); if (chapter) { this.currentChapter = this.initialChapterId; } } if (typeof this.currentChapter == 'undefined') { // Load the first chapter. this.currentChapter = this.bookProvider.getFirstChapter(this.chapters); } // Show chapter. return this.loadChapter(this.currentChapter).then(() => { if (downloadFailed && this.appProvider.isOnline()) { // We could load the main file but the download failed. Show error message. this.domUtils.showErrorModal('core.errordownloadingsomefiles', true); } // All data obtained, now fill the context menu. this.fillContextMenu(refresh); }).catch(() => { // Ignore errors, they're handled inside the loadChapter function. }); }); } /** * Load a book chapter. * * @param {string} chapterId Chapter to load. * @return {Promise<void>} Promise resolved when done. */ protected loadChapter(chapterId: string): Promise<void> { this.currentChapter = chapterId; this.domUtils.scrollToTop(this.content); return this.bookProvider.getChapterContent(this.contentsMap, chapterId, this.module.id).then((content) => { this.chapterContent = content; this.previousChapter = this.bookProvider.getPreviousChapter(this.chapters, chapterId); this.nextChapter = this.bookProvider.getNextChapter(this.chapters, chapterId); // Chapter loaded, log view. We don't return the promise because we don't want to block the user for this. this.bookProvider.logView(this.module.instance, chapterId, this.module.name).then(() => { // Module is completed when last chapter is viewed, so we only check completion if the last is reached. if (this.nextChapter == '0') { this.courseProvider.checkModuleCompletion(this.courseId, this.module.completiondata); } }).catch(() => { // Ignore errors. }); }).catch((error) => { this.domUtils.showErrorModalDefault(error, 'addon.mod_book.errorchapter', true); return Promise.reject(null); }).finally(() => { this.loaded = true; this.refreshIcon = 'refresh'; }); } }
fetchContent
identifier_name
integration.js
/* jshint indent:4 */ /* * Copyright 2011-2013 Jiří Janoušek <[email protected]> * Copyright 2014 Jan Vlnas <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Anonymous function is used not to pollute environment */ (function(Nuvola) { if (Nuvola.checkFlash) Nuvola.checkFlash(); /** * Generate element selection function */ var elementSelector = function() { var ELEM_IDS = { prev: 'backwards', next: 'forwards', song: 'track-title', artist: 'artist-name', play: 'playPause', thumbsUp: 'controlLike', playAll: 'playAllJams' }; return function(type) { return document.getElementById(ELEM_IDS[type]); }; }; var getElement = elementSelector(); /** * Returns {prev: bool, next: bool} **/ var getPlaylistState = function() { var ret = {}; ['prev', 'next'].forEach(function(type) { ret[type] = !getElement(type).hasAttribute('disabled'); }); return ret; }; /** * Return an URL of the image of (hopefully) currently playing track * TODO: store the first found album art with the currently playing track, * so the visiting the profile page does not replace a correct album art * - OTOH, if I am playing a playlist and I am on the profile page, the incorrect * art will be loaded and stored **/ var getArtLocation = function() { var img = null; // On Playlist page, things are easy img = document.querySelector('.blackHole.playing img'); if (img) { return img.getAttribute('data-thumb'); } // Let's try profile page img = document.querySelector('#jamHolder img'); if (img) { return img.src; } // No can do return null; }; /** * Return state depending on the play button */ var getState = function() { var el = getElement('play'); if (!el) { return Nuvola.STATE_NONE; } if (el.className.match(/playing$/)) { return Nuvola.STATE_PLAYING; } else if (el.className.match(/paused$/)) {
return Nuvola.STATE_NONE; }; var doPlay = function() { var play = getElement('play'); if (play && (getState() != Nuvola.STATE_NONE)) { Nuvola.clickOnElement(play); return true; } var playAll = getElement('playAll'); if (playAll) { Nuvola.clickOnElement(playAll); return true; } return false; }; /** * Creates integration bound to Nuvola JS API */ var Integration = function() { /* Overwrite default commnad function */ Nuvola.onMessageReceived = Nuvola.bind(this, this.messageHandler); /* For debug output */ this.name = "thisismyjam"; /* Let's run */ this.state = Nuvola.STATE_NONE; this.can_thumbs_up = null; this.can_thumbs_down = null; this.can_prev = null; this.can_next = null; this.update(); }; /** * Updates current playback state */ Integration.prototype.update = function() { // Default values var state = Nuvola.STATE_NONE; var can_prev = false; var can_next = false; var can_thumbs_up = false; var can_thumbs_down = false; var album_art = null; var song = null; var artist = null; try { state = getState(); song = getElement('song').textContent; artist = getElement('artist').textContent; album_art = getArtLocation(); can_thumbs_up = (state !== Nuvola.STATE_NONE); var playlist = getPlaylistState(); can_prev = playlist.prev; can_next = playlist.next; // can_thumbs_down = false; } catch (x) { song = artist = null; } // Save state this.state = state; // Submit data to Nuvola backend Nuvola.updateSong(song, artist, null, album_art, state); // Update actions if (this.can_prev !== can_prev) { this.can_prev = can_prev; Nuvola.updateAction(Nuvola.ACTION_PREV_SONG, can_prev); } if (this.can_next !== can_next) { this.can_next = can_next; Nuvola.updateAction(Nuvola.ACTION_NEXT_SONG, can_next); } if (this.can_thumbs_up !== can_thumbs_up) { this.can_thumbs_up = can_thumbs_up; Nuvola.updateAction(Nuvola.ACTION_THUMBS_UP, can_thumbs_up); } if (this.can_thumbs_down !== can_thumbs_down) { this.can_thumbs_down = can_thumbs_down; Nuvola.updateAction(Nuvola.ACTION_THUMBS_DOWN, can_thumbs_down); } // Schedule update setTimeout(Nuvola.bind(this, this.update), 500); }; /** * Message handler * @param cmd command to execute */ Integration.prototype.messageHandler = function(cmd) { /* Respond to user actions */ try { switch (cmd) { case Nuvola.ACTION_PLAY: if (this.state != Nuvola.STATE_PLAYING) doPlay(); break; case Nuvola.ACTION_PAUSE: if (this.state == Nuvola.STATE_PLAYING) Nuvola.clickOnElement(getElement('play')); break; case Nuvola.ACTION_TOGGLE_PLAY: doPlay(); break; case Nuvola.ACTION_PREV_SONG: Nuvola.clickOnElement(getElement('prev')); break; case Nuvola.ACTION_NEXT_SONG: Nuvola.clickOnElement(getElement('next')); break; case Nuvola.ACTION_THUMBS_UP: Nuvola.clickOnElement(getElement('thumbsUp')); break; /*case Nuvola.ACTION_THUMBS_DOWN: break;*/ default: // Other commands are not supported throw { "message": "Not supported." }; } console.log(this.name + ": comand '" + cmd + "' executed."); } catch (e) { // Older API expected exception to be a string. throw (this.name + ": " + e.message); } }; /* Store reference */ Nuvola.integration = new Integration(); // Singleton // Immediately call the anonymous function with Nuvola JS API main object as an argument. // Note that "this" is set to the Nuvola JS API main object. })(this);
return Nuvola.STATE_PAUSED; }
conditional_block
integration.js
/* jshint indent:4 */ /* * Copyright 2011-2013 Jiří Janoušek <[email protected]> * Copyright 2014 Jan Vlnas <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Anonymous function is used not to pollute environment */ (function(Nuvola) { if (Nuvola.checkFlash) Nuvola.checkFlash(); /** * Generate element selection function */ var elementSelector = function() { var ELEM_IDS = { prev: 'backwards', next: 'forwards', song: 'track-title', artist: 'artist-name', play: 'playPause', thumbsUp: 'controlLike', playAll: 'playAllJams' }; return function(type) { return document.getElementById(ELEM_IDS[type]); }; }; var getElement = elementSelector(); /** * Returns {prev: bool, next: bool} **/ var getPlaylistState = function() { var ret = {}; ['prev', 'next'].forEach(function(type) { ret[type] = !getElement(type).hasAttribute('disabled'); }); return ret; }; /** * Return an URL of the image of (hopefully) currently playing track * TODO: store the first found album art with the currently playing track, * so the visiting the profile page does not replace a correct album art * - OTOH, if I am playing a playlist and I am on the profile page, the incorrect * art will be loaded and stored **/ var getArtLocation = function() { var img = null; // On Playlist page, things are easy img = document.querySelector('.blackHole.playing img'); if (img) { return img.getAttribute('data-thumb'); } // Let's try profile page img = document.querySelector('#jamHolder img'); if (img) { return img.src; } // No can do return null; }; /** * Return state depending on the play button */ var getState = function() { var el = getElement('play'); if (!el) { return Nuvola.STATE_NONE; } if (el.className.match(/playing$/)) { return Nuvola.STATE_PLAYING; } else if (el.className.match(/paused$/)) { return Nuvola.STATE_PAUSED; } return Nuvola.STATE_NONE; }; var doPlay = function() { var play = getElement('play'); if (play && (getState() != Nuvola.STATE_NONE)) { Nuvola.clickOnElement(play); return true; } var playAll = getElement('playAll'); if (playAll) { Nuvola.clickOnElement(playAll); return true; } return false; }; /** * Creates integration bound to Nuvola JS API */ var Integration = function() { /* Overwrite default commnad function */ Nuvola.onMessageReceived = Nuvola.bind(this, this.messageHandler); /* For debug output */ this.name = "thisismyjam"; /* Let's run */ this.state = Nuvola.STATE_NONE; this.can_thumbs_up = null; this.can_thumbs_down = null; this.can_prev = null; this.can_next = null; this.update(); }; /** * Updates current playback state */ Integration.prototype.update = function() { // Default values
var can_next = false; var can_thumbs_up = false; var can_thumbs_down = false; var album_art = null; var song = null; var artist = null; try { state = getState(); song = getElement('song').textContent; artist = getElement('artist').textContent; album_art = getArtLocation(); can_thumbs_up = (state !== Nuvola.STATE_NONE); var playlist = getPlaylistState(); can_prev = playlist.prev; can_next = playlist.next; // can_thumbs_down = false; } catch (x) { song = artist = null; } // Save state this.state = state; // Submit data to Nuvola backend Nuvola.updateSong(song, artist, null, album_art, state); // Update actions if (this.can_prev !== can_prev) { this.can_prev = can_prev; Nuvola.updateAction(Nuvola.ACTION_PREV_SONG, can_prev); } if (this.can_next !== can_next) { this.can_next = can_next; Nuvola.updateAction(Nuvola.ACTION_NEXT_SONG, can_next); } if (this.can_thumbs_up !== can_thumbs_up) { this.can_thumbs_up = can_thumbs_up; Nuvola.updateAction(Nuvola.ACTION_THUMBS_UP, can_thumbs_up); } if (this.can_thumbs_down !== can_thumbs_down) { this.can_thumbs_down = can_thumbs_down; Nuvola.updateAction(Nuvola.ACTION_THUMBS_DOWN, can_thumbs_down); } // Schedule update setTimeout(Nuvola.bind(this, this.update), 500); }; /** * Message handler * @param cmd command to execute */ Integration.prototype.messageHandler = function(cmd) { /* Respond to user actions */ try { switch (cmd) { case Nuvola.ACTION_PLAY: if (this.state != Nuvola.STATE_PLAYING) doPlay(); break; case Nuvola.ACTION_PAUSE: if (this.state == Nuvola.STATE_PLAYING) Nuvola.clickOnElement(getElement('play')); break; case Nuvola.ACTION_TOGGLE_PLAY: doPlay(); break; case Nuvola.ACTION_PREV_SONG: Nuvola.clickOnElement(getElement('prev')); break; case Nuvola.ACTION_NEXT_SONG: Nuvola.clickOnElement(getElement('next')); break; case Nuvola.ACTION_THUMBS_UP: Nuvola.clickOnElement(getElement('thumbsUp')); break; /*case Nuvola.ACTION_THUMBS_DOWN: break;*/ default: // Other commands are not supported throw { "message": "Not supported." }; } console.log(this.name + ": comand '" + cmd + "' executed."); } catch (e) { // Older API expected exception to be a string. throw (this.name + ": " + e.message); } }; /* Store reference */ Nuvola.integration = new Integration(); // Singleton // Immediately call the anonymous function with Nuvola JS API main object as an argument. // Note that "this" is set to the Nuvola JS API main object. })(this);
var state = Nuvola.STATE_NONE; var can_prev = false;
random_line_split
es6-promise.d.ts
// Type definitions for es6-promise // Project: https://github.com/jakearchibald/ES6-Promise // Definitions by: François de Campredon <https://github.com/fdecampredon/>, vvakame <https://github.com/vvakame> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Thenable<R> { then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>; then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>; catch<U>(onRejected?: (error: any) => U | Thenable<U>): Thenable<U>; } declare class P
R> implements Thenable<R> { /** * If you call resolve in the body of the callback passed to the constructor, * your promise is fulfilled with result object passed to resolve. * If you call reject your promise is rejected with the object passed to reject. * For consistency and debugging (eg stack traces), obj should be an instanceof Error. * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ constructor(callback: (resolve : (value?: R | Thenable<R>) => void, reject: (error?: any) => void) => void); /** * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * * @param onFulfilled called when/if "promise" resolves * @param onRejected called when/if "promise" rejects */ then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Promise<U>; then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Promise<U>; /** * Sugar for promise.then(undefined, onRejected) * * @param onRejected called when/if "promise" rejects */ catch<U>(onRejected?: (error: any) => U | Thenable<U>): Promise<U>; } declare module Promise { /** * Make a new promise from the thenable. * A thenable is promise-like in as far as it has a "then" method. */ function resolve<R>(value?: R | Thenable<R>): Promise<R>; /** * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error */ function reject(error: any): Promise<any>; /** * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. * the array passed to all can be a mixture of promise-like objects and other objects. * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. */ function all<R>(promises: (R | Thenable<R>)[]): Promise<R[]>; /** * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. */ function race<R>(promises: (R | Thenable<R>)[]): Promise<R>; } declare module 'es6-promise' { var foo: typeof Promise; // Temp variable to reference Promise in local context module rsvp { export var Promise: typeof foo; } export = rsvp; }
romise<
identifier_name
es6-promise.d.ts
// Type definitions for es6-promise // Project: https://github.com/jakearchibald/ES6-Promise // Definitions by: François de Campredon <https://github.com/fdecampredon/>, vvakame <https://github.com/vvakame> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Thenable<R> { then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>; then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>; catch<U>(onRejected?: (error: any) => U | Thenable<U>): Thenable<U>; } declare class Promise<R> implements Thenable<R> { /** * If you call resolve in the body of the callback passed to the constructor, * your promise is fulfilled with result object passed to resolve. * If you call reject your promise is rejected with the object passed to reject. * For consistency and debugging (eg stack traces), obj should be an instanceof Error. * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ constructor(callback: (resolve : (value?: R | Thenable<R>) => void, reject: (error?: any) => void) => void); /** * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * * @param onFulfilled called when/if "promise" resolves * @param onRejected called when/if "promise" rejects */ then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Promise<U>; then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Promise<U>; /** * Sugar for promise.then(undefined, onRejected) * * @param onRejected called when/if "promise" rejects */ catch<U>(onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
* Make a new promise from the thenable. * A thenable is promise-like in as far as it has a "then" method. */ function resolve<R>(value?: R | Thenable<R>): Promise<R>; /** * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error */ function reject(error: any): Promise<any>; /** * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. * the array passed to all can be a mixture of promise-like objects and other objects. * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. */ function all<R>(promises: (R | Thenable<R>)[]): Promise<R[]>; /** * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. */ function race<R>(promises: (R | Thenable<R>)[]): Promise<R>; } declare module 'es6-promise' { var foo: typeof Promise; // Temp variable to reference Promise in local context module rsvp { export var Promise: typeof foo; } export = rsvp; }
} declare module Promise { /**
random_line_split
images.py
# $Id: images.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Directives for figures and simple images. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import Directive from docutils.parsers.rst import directives, states from docutils.nodes import fully_normalize_name, whitespace_normalize_name from docutils.parsers.rst.roles import set_classes try: import Image as PIL # PIL except ImportError: PIL = None class Image(Directive): align_h_values = ('left', 'center', 'right') align_v_values = ('top', 'middle', 'bottom') align_values = align_v_values + align_h_values def align(argument): # This is not callable as self.align. We cannot make it a # staticmethod because we're saving an unbound method in # option_spec below. return directives.choice(argument, Image.align_values) required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.percentage, 'align': align, 'name': directives.unchanged, 'target': directives.unchanged_required, 'class': directives.class_option} def run(self): if 'align' in self.options: if isinstance(self.state, states.SubstitutionDef): # Check for align_v_values. if self.options['align'] not in self.align_v_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value ' 'for the "align" option within a substitution ' 'definition. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_v_values))) elif self.options['align'] not in self.align_h_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_h_values))) messages = [] reference = directives.uri(self.arguments[0]) self.options['uri'] = reference reference_node = None if 'target' in self.options: block = states.escape2null( self.options['target']).splitlines() block = [line for line in block] target_type, data = self.state.parse_target( block, self.block_text, self.lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference( refname=fully_normalize_name(data), name=whitespace_normalize_name(data)) reference_node.indirect_reference_name = data self.state.document.note_refname(reference_node) else: # malformed target messages.append(data) # data is a system message del self.options['target'] set_classes(self.options) image_node = nodes.image(self.block_text, **self.options) self.add_name(image_node) if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node] class Figure(Image): def align(argument): return directives.choice(argument, Figure.align_h_values) def figwidth_value(argument):
option_spec = Image.option_spec.copy() option_spec['figwidth'] = figwidth_value option_spec['figclass'] = directives.class_option option_spec['align'] = align has_content = True def run(self): figwidth = self.options.pop('figwidth', None) figclasses = self.options.pop('figclass', None) align = self.options.pop('align', None) (image_node,) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if PIL and self.state.document.settings.file_insertion_enabled: # PIL doesn't like Unicode paths: try: i = PIL.open(str(image_node['uri'])) except (IOError, UnicodeError): pass else: self.state.document.settings.record_dependencies.add( image_node['uri']) figure_node['width'] = i.size[0] elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if self.content: node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = self.state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node]
if argument.lower() == 'image': return 'image' else: return directives.length_or_percentage_or_unitless(argument, 'px')
identifier_body
images.py
# $Id: images.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Directives for figures and simple images. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import Directive from docutils.parsers.rst import directives, states from docutils.nodes import fully_normalize_name, whitespace_normalize_name from docutils.parsers.rst.roles import set_classes try: import Image as PIL # PIL except ImportError: PIL = None class Image(Directive): align_h_values = ('left', 'center', 'right') align_v_values = ('top', 'middle', 'bottom') align_values = align_v_values + align_h_values def
(argument): # This is not callable as self.align. We cannot make it a # staticmethod because we're saving an unbound method in # option_spec below. return directives.choice(argument, Image.align_values) required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.percentage, 'align': align, 'name': directives.unchanged, 'target': directives.unchanged_required, 'class': directives.class_option} def run(self): if 'align' in self.options: if isinstance(self.state, states.SubstitutionDef): # Check for align_v_values. if self.options['align'] not in self.align_v_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value ' 'for the "align" option within a substitution ' 'definition. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_v_values))) elif self.options['align'] not in self.align_h_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_h_values))) messages = [] reference = directives.uri(self.arguments[0]) self.options['uri'] = reference reference_node = None if 'target' in self.options: block = states.escape2null( self.options['target']).splitlines() block = [line for line in block] target_type, data = self.state.parse_target( block, self.block_text, self.lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference( refname=fully_normalize_name(data), name=whitespace_normalize_name(data)) reference_node.indirect_reference_name = data self.state.document.note_refname(reference_node) else: # malformed target messages.append(data) # data is a system message del self.options['target'] set_classes(self.options) image_node = nodes.image(self.block_text, **self.options) self.add_name(image_node) if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node] class Figure(Image): def align(argument): return directives.choice(argument, Figure.align_h_values) def figwidth_value(argument): if argument.lower() == 'image': return 'image' else: return directives.length_or_percentage_or_unitless(argument, 'px') option_spec = Image.option_spec.copy() option_spec['figwidth'] = figwidth_value option_spec['figclass'] = directives.class_option option_spec['align'] = align has_content = True def run(self): figwidth = self.options.pop('figwidth', None) figclasses = self.options.pop('figclass', None) align = self.options.pop('align', None) (image_node,) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if PIL and self.state.document.settings.file_insertion_enabled: # PIL doesn't like Unicode paths: try: i = PIL.open(str(image_node['uri'])) except (IOError, UnicodeError): pass else: self.state.document.settings.record_dependencies.add( image_node['uri']) figure_node['width'] = i.size[0] elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if self.content: node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = self.state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node]
align
identifier_name
images.py
# $Id: images.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Directives for figures and simple images. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import Directive from docutils.parsers.rst import directives, states from docutils.nodes import fully_normalize_name, whitespace_normalize_name from docutils.parsers.rst.roles import set_classes try: import Image as PIL # PIL except ImportError: PIL = None class Image(Directive): align_h_values = ('left', 'center', 'right') align_v_values = ('top', 'middle', 'bottom') align_values = align_v_values + align_h_values def align(argument): # This is not callable as self.align. We cannot make it a # staticmethod because we're saving an unbound method in # option_spec below. return directives.choice(argument, Image.align_values) required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.percentage, 'align': align, 'name': directives.unchanged, 'target': directives.unchanged_required, 'class': directives.class_option} def run(self): if 'align' in self.options: if isinstance(self.state, states.SubstitutionDef): # Check for align_v_values. if self.options['align'] not in self.align_v_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value ' 'for the "align" option within a substitution ' 'definition. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_v_values))) elif self.options['align'] not in self.align_h_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_h_values))) messages = [] reference = directives.uri(self.arguments[0]) self.options['uri'] = reference reference_node = None if 'target' in self.options: block = states.escape2null( self.options['target']).splitlines() block = [line for line in block] target_type, data = self.state.parse_target( block, self.block_text, self.lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference( refname=fully_normalize_name(data), name=whitespace_normalize_name(data)) reference_node.indirect_reference_name = data self.state.document.note_refname(reference_node) else: # malformed target
del self.options['target'] set_classes(self.options) image_node = nodes.image(self.block_text, **self.options) self.add_name(image_node) if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node] class Figure(Image): def align(argument): return directives.choice(argument, Figure.align_h_values) def figwidth_value(argument): if argument.lower() == 'image': return 'image' else: return directives.length_or_percentage_or_unitless(argument, 'px') option_spec = Image.option_spec.copy() option_spec['figwidth'] = figwidth_value option_spec['figclass'] = directives.class_option option_spec['align'] = align has_content = True def run(self): figwidth = self.options.pop('figwidth', None) figclasses = self.options.pop('figclass', None) align = self.options.pop('align', None) (image_node,) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if PIL and self.state.document.settings.file_insertion_enabled: # PIL doesn't like Unicode paths: try: i = PIL.open(str(image_node['uri'])) except (IOError, UnicodeError): pass else: self.state.document.settings.record_dependencies.add( image_node['uri']) figure_node['width'] = i.size[0] elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if self.content: node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = self.state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node]
messages.append(data) # data is a system message
conditional_block
images.py
# $Id: images.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Directives for figures and simple images. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import Directive from docutils.parsers.rst import directives, states from docutils.nodes import fully_normalize_name, whitespace_normalize_name from docutils.parsers.rst.roles import set_classes try: import Image as PIL # PIL except ImportError: PIL = None class Image(Directive):
align_h_values = ('left', 'center', 'right') align_v_values = ('top', 'middle', 'bottom') align_values = align_v_values + align_h_values def align(argument): # This is not callable as self.align. We cannot make it a # staticmethod because we're saving an unbound method in # option_spec below. return directives.choice(argument, Image.align_values) required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.percentage, 'align': align, 'name': directives.unchanged, 'target': directives.unchanged_required, 'class': directives.class_option} def run(self): if 'align' in self.options: if isinstance(self.state, states.SubstitutionDef): # Check for align_v_values. if self.options['align'] not in self.align_v_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value ' 'for the "align" option within a substitution ' 'definition. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_v_values))) elif self.options['align'] not in self.align_h_values: raise self.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (self.name, self.options['align'], '", "'.join(self.align_h_values))) messages = [] reference = directives.uri(self.arguments[0]) self.options['uri'] = reference reference_node = None if 'target' in self.options: block = states.escape2null( self.options['target']).splitlines() block = [line for line in block] target_type, data = self.state.parse_target( block, self.block_text, self.lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference( refname=fully_normalize_name(data), name=whitespace_normalize_name(data)) reference_node.indirect_reference_name = data self.state.document.note_refname(reference_node) else: # malformed target messages.append(data) # data is a system message del self.options['target'] set_classes(self.options) image_node = nodes.image(self.block_text, **self.options) self.add_name(image_node) if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node] class Figure(Image): def align(argument): return directives.choice(argument, Figure.align_h_values) def figwidth_value(argument): if argument.lower() == 'image': return 'image' else: return directives.length_or_percentage_or_unitless(argument, 'px') option_spec = Image.option_spec.copy() option_spec['figwidth'] = figwidth_value option_spec['figclass'] = directives.class_option option_spec['align'] = align has_content = True def run(self): figwidth = self.options.pop('figwidth', None) figclasses = self.options.pop('figclass', None) align = self.options.pop('align', None) (image_node,) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if PIL and self.state.document.settings.file_insertion_enabled: # PIL doesn't like Unicode paths: try: i = PIL.open(str(image_node['uri'])) except (IOError, UnicodeError): pass else: self.state.document.settings.record_dependencies.add( image_node['uri']) figure_node['width'] = i.size[0] elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if self.content: node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = self.state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node]
random_line_split
shootout-ackermann.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::os; fn ack(m: int, n: int) -> int { if m == 0 { return n + 1 } else { if n == 0 { return ack(m - 1, 1); } else { return ack(m - 1, ack(m, n - 1)); } } } fn
() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); }
main
identifier_name
shootout-ackermann.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::os; fn ack(m: int, n: int) -> int { if m == 0 { return n + 1 } else { if n == 0
else { return ack(m - 1, ack(m, n - 1)); } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); }
{ return ack(m - 1, 1); }
conditional_block
shootout-ackermann.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::os; fn ack(m: int, n: int) -> int {
if m == 0 { return n + 1 } else { if n == 0 { return ack(m - 1, 1); } else { return ack(m - 1, ack(m, n - 1)); } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "12".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "8".to_owned()) } else { args.move_iter().collect() }; let n = from_str::<int>(*args.get(1)).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); }
random_line_split