file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
explicit-self.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; static tau: f64 = 2.0*3.14159265358979323; struct Point {x: f64, y: f64} struct Size {w: f64, h: f64} enum shape { circle(Point, f64), rectangle(Point, Size) } fn compute_area(shape: &shape) -> f64 { match *shape { circle(_, radius) => 0.5 * tau * radius * radius, rectangle(_, ref size) => size.w * size.h } } impl shape { // self is in the implicit self region pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T) -> &'r T { if compute_area(self) > threshold {a} else {b} } } fn select_based_on_unit_circle<'r, T>( threshold: f64, a: &'r T, b: &'r T) -> &'r T { let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0); shape.select(threshold, a, b) } #[deriving(Clone)] struct thing { x: A } #[deriving(Clone)] struct A { a: @int } fn thing(x: A) -> thing { thing { x: x } } impl thing {
pub fn quux(&self) -> int { *self.x.a } pub fn baz<'a>(&'a self) -> &'a A { &self.x } pub fn spam(self) -> int { *self.x.a } } trait Nus { fn f(&self); } impl Nus for thing { fn f(&self) {} } pub fn main() { let x = @thing(A {a: @10}); assert_eq!(x.foo(), 10); assert_eq!(x.quux(), 10); let y = ~thing(A {a: @10}); assert_eq!(y.clone().bar(), 10); assert_eq!(y.quux(), 10); let z = thing(A {a: @11}); assert_eq!(z.spam(), 11); }
pub fn foo(@self) -> int { *self.x.a } pub fn bar(~self) -> int { *self.x.a }
random_line_split
explicit-self.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; static tau: f64 = 2.0*3.14159265358979323; struct Point {x: f64, y: f64} struct Size {w: f64, h: f64} enum shape { circle(Point, f64), rectangle(Point, Size) } fn
(shape: &shape) -> f64 { match *shape { circle(_, radius) => 0.5 * tau * radius * radius, rectangle(_, ref size) => size.w * size.h } } impl shape { // self is in the implicit self region pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T) -> &'r T { if compute_area(self) > threshold {a} else {b} } } fn select_based_on_unit_circle<'r, T>( threshold: f64, a: &'r T, b: &'r T) -> &'r T { let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0); shape.select(threshold, a, b) } #[deriving(Clone)] struct thing { x: A } #[deriving(Clone)] struct A { a: @int } fn thing(x: A) -> thing { thing { x: x } } impl thing { pub fn foo(@self) -> int { *self.x.a } pub fn bar(~self) -> int { *self.x.a } pub fn quux(&self) -> int { *self.x.a } pub fn baz<'a>(&'a self) -> &'a A { &self.x } pub fn spam(self) -> int { *self.x.a } } trait Nus { fn f(&self); } impl Nus for thing { fn f(&self) {} } pub fn main() { let x = @thing(A {a: @10}); assert_eq!(x.foo(), 10); assert_eq!(x.quux(), 10); let y = ~thing(A {a: @10}); assert_eq!(y.clone().bar(), 10); assert_eq!(y.quux(), 10); let z = thing(A {a: @11}); assert_eq!(z.spam(), 11); }
compute_area
identifier_name
explicit-self.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; static tau: f64 = 2.0*3.14159265358979323; struct Point {x: f64, y: f64} struct Size {w: f64, h: f64} enum shape { circle(Point, f64), rectangle(Point, Size) } fn compute_area(shape: &shape) -> f64 { match *shape { circle(_, radius) => 0.5 * tau * radius * radius, rectangle(_, ref size) => size.w * size.h } } impl shape { // self is in the implicit self region pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T) -> &'r T { if compute_area(self) > threshold {a} else {b} } } fn select_based_on_unit_circle<'r, T>( threshold: f64, a: &'r T, b: &'r T) -> &'r T { let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0); shape.select(threshold, a, b) } #[deriving(Clone)] struct thing { x: A } #[deriving(Clone)] struct A { a: @int } fn thing(x: A) -> thing { thing { x: x } } impl thing { pub fn foo(@self) -> int
pub fn bar(~self) -> int { *self.x.a } pub fn quux(&self) -> int { *self.x.a } pub fn baz<'a>(&'a self) -> &'a A { &self.x } pub fn spam(self) -> int { *self.x.a } } trait Nus { fn f(&self); } impl Nus for thing { fn f(&self) {} } pub fn main() { let x = @thing(A {a: @10}); assert_eq!(x.foo(), 10); assert_eq!(x.quux(), 10); let y = ~thing(A {a: @10}); assert_eq!(y.clone().bar(), 10); assert_eq!(y.quux(), 10); let z = thing(A {a: @11}); assert_eq!(z.spam(), 11); }
{ *self.x.a }
identifier_body
credit_seat_spec.js
define([ 'collections/credit_provider_collection', 'ecommerce', 'models/course_seats/credit_seat' ], function (CreditProviderCollection, ecommerce, CreditSeat) { 'use strict'; var model, data = { id: 9, url: 'http://ecommerce.local:8002/api/v2/products/9/', structure: 'child', product_class: 'Seat', title: 'Seat in edX Demonstration Course with honor certificate', price: '0.00', expires: null, attribute_values: [ { name: 'certificate_type', value: 'credit' }, { name: 'course_key', value: 'edX/DemoX/Demo_Course' }, { name: 'id_verification_required', value: false } ], is_available_to_buy: true }; beforeEach(function () { model = CreditSeat.findOrCreate(data, {parse: true}); ecommerce.credit.providers = new CreditProviderCollection([{id: 'harvard', display_name: 'Harvard'}]); }); describe('Credit course seat model', function () { describe('credit provider validation', function () { function
(credit_provider, expected_msg) { model.set('credit_provider', credit_provider); expect(model.validate().credit_provider).toEqual(expected_msg); expect(model.isValid(true)).toBeFalsy(); } it('should do nothing if the credit provider is valid', function () { model.set('credit_provider', ecommerce.credit.providers.at(0).get('id')); expect(model.validate().credit_provider).toBeUndefined(); }); it('should return a message if the credit provider is not set', function () { var msg = 'All credit seats must have a credit provider.', values = [null, undefined, '']; values.forEach(function (value) { assertCreditProviderInvalid(value, msg); }); }); it('should return a message if the credit provider is not a valid credit provider', function () { var msg = 'Please select a valid credit provider.'; assertCreditProviderInvalid('acme', msg); }); }); }); } );
assertCreditProviderInvalid
identifier_name
credit_seat_spec.js
define([ 'collections/credit_provider_collection', 'ecommerce', 'models/course_seats/credit_seat' ], function (CreditProviderCollection, ecommerce, CreditSeat) { 'use strict'; var model, data = { id: 9, url: 'http://ecommerce.local:8002/api/v2/products/9/', structure: 'child', product_class: 'Seat', title: 'Seat in edX Demonstration Course with honor certificate', price: '0.00', expires: null, attribute_values: [ { name: 'certificate_type', value: 'credit' }, { name: 'course_key', value: 'edX/DemoX/Demo_Course' }, { name: 'id_verification_required', value: false } ], is_available_to_buy: true }; beforeEach(function () { model = CreditSeat.findOrCreate(data, {parse: true}); ecommerce.credit.providers = new CreditProviderCollection([{id: 'harvard', display_name: 'Harvard'}]); }); describe('Credit course seat model', function () { describe('credit provider validation', function () { function assertCreditProviderInvalid(credit_provider, expected_msg)
it('should do nothing if the credit provider is valid', function () { model.set('credit_provider', ecommerce.credit.providers.at(0).get('id')); expect(model.validate().credit_provider).toBeUndefined(); }); it('should return a message if the credit provider is not set', function () { var msg = 'All credit seats must have a credit provider.', values = [null, undefined, '']; values.forEach(function (value) { assertCreditProviderInvalid(value, msg); }); }); it('should return a message if the credit provider is not a valid credit provider', function () { var msg = 'Please select a valid credit provider.'; assertCreditProviderInvalid('acme', msg); }); }); }); } );
{ model.set('credit_provider', credit_provider); expect(model.validate().credit_provider).toEqual(expected_msg); expect(model.isValid(true)).toBeFalsy(); }
identifier_body
credit_seat_spec.js
define([ 'collections/credit_provider_collection', 'ecommerce', 'models/course_seats/credit_seat' ], function (CreditProviderCollection, ecommerce, CreditSeat) { 'use strict'; var model, data = { id: 9, url: 'http://ecommerce.local:8002/api/v2/products/9/', structure: 'child', product_class: 'Seat', title: 'Seat in edX Demonstration Course with honor certificate', price: '0.00', expires: null, attribute_values: [ { name: 'certificate_type', value: 'credit' }, { name: 'course_key', value: 'edX/DemoX/Demo_Course' }, { name: 'id_verification_required', value: false } ], is_available_to_buy: true }; beforeEach(function () { model = CreditSeat.findOrCreate(data, {parse: true}); ecommerce.credit.providers = new CreditProviderCollection([{id: 'harvard', display_name: 'Harvard'}]); }); describe('Credit course seat model', function () { describe('credit provider validation', function () { function assertCreditProviderInvalid(credit_provider, expected_msg) { model.set('credit_provider', credit_provider); expect(model.validate().credit_provider).toEqual(expected_msg); expect(model.isValid(true)).toBeFalsy();
}); it('should return a message if the credit provider is not set', function () { var msg = 'All credit seats must have a credit provider.', values = [null, undefined, '']; values.forEach(function (value) { assertCreditProviderInvalid(value, msg); }); }); it('should return a message if the credit provider is not a valid credit provider', function () { var msg = 'Please select a valid credit provider.'; assertCreditProviderInvalid('acme', msg); }); }); }); } );
} it('should do nothing if the credit provider is valid', function () { model.set('credit_provider', ecommerce.credit.providers.at(0).get('id')); expect(model.validate().credit_provider).toBeUndefined();
random_line_split
manageuserdirectories.py
# This file is part of the mantidqt package # # Copyright (C) 2017 mantidproject # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, unicode_literals) from mantidqt.utils.qt import import_qtlib
ManageUserDirectories = import_qtlib('_widgetscore', 'mantidqt.widgets', 'ManageUserDirectories')
random_line_split
chooser_exception_list.ts
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'chooser-exception-list' shows a list of chooser exceptions for a given * chooser type. */ import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import '../settings_shared_css.js'; import '../i18n_setup.js'; import './chooser_exception_list_entry.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {ListPropertyUpdateMixin} from 'chrome://resources/js/list_property_update_mixin.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {PaperTooltipElement} from 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './chooser_exception_list.html.js'; import {ChooserType, ContentSettingsTypes} from './constants.js'; import {SiteSettingsMixin} from './site_settings_mixin.js'; import {ChooserException, RawChooserException, SiteException} from './site_settings_prefs_browser_proxy.js'; export interface ChooserExceptionListElement { $: { tooltip: PaperTooltipElement, }; } const ChooserExceptionListElementBase = ListPropertyUpdateMixin( SiteSettingsMixin(WebUIListenerMixin(I18nMixin(PolymerElement)))); export class ChooserExceptionListElement extends ChooserExceptionListElementBase { static get is() { return 'chooser-exception-list'; } static get template() { return getTemplate(); } static get properties() { return { /** * Array of chooser exceptions to display in the widget. */ chooserExceptions: { type: Array, value()
, }, /** * The string ID of the chooser type that this element is displaying data * for. * See site_settings/constants.js for possible values. */ chooserType: { observer: 'chooserTypeChanged_', type: String, value: ChooserType.NONE, }, emptyListMessage_: { type: String, value: '', }, hasIncognito_: Boolean, tooltipText_: String, }; } chooserExceptions: Array<ChooserException>; chooserType: ChooserType; private emptyListMessage_: string; private hasIncognito_: boolean; private tooltipText_: string; connectedCallback() { super.connectedCallback(); this.addWebUIListener( 'contentSettingChooserPermissionChanged', (category: ContentSettingsTypes, chooserType: ChooserType) => { this.objectWithinChooserTypeChanged_(category, chooserType); }); this.addWebUIListener( 'onIncognitoStatusChanged', (hasIncognito: boolean) => this.onIncognitoStatusChanged_(hasIncognito)); this.browserProxy.updateIncognitoStatus(); } /** * Called when a chooser exception changes permission and updates the element * if |category| is equal to the settings category of this element. * @param category The content settings type that represents this permission * category. * @param chooserType The content settings type that represents the chooser * data for this permission. */ private objectWithinChooserTypeChanged_( category: ContentSettingsTypes, chooserType: ChooserType) { if (category === this.category && chooserType === this.chooserType) { this.chooserTypeChanged_(); } } /** * Called for each chooser-exception-list when incognito is enabled or * disabled. Only called on change (opening N incognito windows only fires one * message). Another message is sent when the *last* incognito window closes. */ private onIncognitoStatusChanged_(hasIncognito: boolean) { this.hasIncognito_ = hasIncognito; this.populateList_(); } /** * Configures the visibility of the widget and shows the list. */ private chooserTypeChanged_() { if (this.chooserType === ChooserType.NONE) { return; } // Set the message to display when the exception list is empty. switch (this.chooserType) { case ChooserType.USB_DEVICES: this.emptyListMessage_ = this.i18n('noUsbDevicesFound'); break; case ChooserType.SERIAL_PORTS: this.emptyListMessage_ = this.i18n('noSerialPortsFound'); break; case ChooserType.HID_DEVICES: this.emptyListMessage_ = this.i18n('noHidDevicesFound'); break; case ChooserType.BLUETOOTH_DEVICES: this.emptyListMessage_ = this.i18n('noBluetoothDevicesFound'); break; default: this.emptyListMessage_ = ''; } this.populateList_(); } /** * @return true if there are any chooser exceptions for this chooser type. */ private hasExceptions_(): boolean { return this.chooserExceptions.length > 0; } /** * Need to use a common tooltip since the tooltip in the entry is cut off from * the iron-list. */ private onShowTooltip_(e: CustomEvent<{target: HTMLElement, text: string}>) { this.tooltipText_ = e.detail.text; const target = e.detail.target; // paper-tooltip normally determines the target from the |for| property, // which is a selector. Here paper-tooltip is being reused by multiple // potential targets. this.$.tooltip.target = target; const hide = () => { this.$.tooltip.hide(); target.removeEventListener('mouseleave', hide); target.removeEventListener('blur', hide); target.removeEventListener('click', hide); this.$.tooltip.removeEventListener('mouseenter', hide); }; target.addEventListener('mouseleave', hide); target.addEventListener('blur', hide); target.addEventListener('click', hide); this.$.tooltip.addEventListener('mouseenter', hide); this.$.tooltip.show(); } /** * Populate the chooser exception list for display. */ private populateList_() { this.browserProxy.getChooserExceptionList(this.chooserType) .then(exceptionList => this.processExceptions_(exceptionList)); } /** * Process the chooser exception list returned from the native layer. */ private processExceptions_(exceptionList: Array<RawChooserException>) { const exceptions = exceptionList.map(exception => { const sites = exception.sites.map(site => this.expandSiteException(site)); return Object.assign(exception, {sites}); }); if (!this.updateList( 'chooserExceptions', x => x.displayName, exceptions, true /* identityBasedUpdate= */)) { // The chooser objects have not been changed, so check if their site // permissions have changed. The |exceptions| and |this.chooserExceptions| // arrays should be the same length. const siteUidGetter = (x: SiteException) => x.origin + x.embeddingOrigin + x.incognito; exceptions.forEach((exception, index) => { const propertyPath = 'chooserExceptions.' + index + '.sites'; this.updateList(propertyPath, siteUidGetter, exception.sites); }, this); } } } declare global { interface HTMLElementTagNameMap { 'chooser-exception-list': ChooserExceptionListElement; } } customElements.define( ChooserExceptionListElement.is, ChooserExceptionListElement);
{ return []; }
identifier_body
chooser_exception_list.ts
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'chooser-exception-list' shows a list of chooser exceptions for a given * chooser type. */ import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import '../settings_shared_css.js'; import '../i18n_setup.js'; import './chooser_exception_list_entry.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {ListPropertyUpdateMixin} from 'chrome://resources/js/list_property_update_mixin.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {PaperTooltipElement} from 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './chooser_exception_list.html.js'; import {ChooserType, ContentSettingsTypes} from './constants.js'; import {SiteSettingsMixin} from './site_settings_mixin.js'; import {ChooserException, RawChooserException, SiteException} from './site_settings_prefs_browser_proxy.js'; export interface ChooserExceptionListElement { $: { tooltip: PaperTooltipElement, }; } const ChooserExceptionListElementBase = ListPropertyUpdateMixin( SiteSettingsMixin(WebUIListenerMixin(I18nMixin(PolymerElement)))); export class ChooserExceptionListElement extends ChooserExceptionListElementBase { static get is() { return 'chooser-exception-list'; } static get template() { return getTemplate(); } static get properties() { return { /** * Array of chooser exceptions to display in the widget. */ chooserExceptions: { type: Array,
() { return []; }, }, /** * The string ID of the chooser type that this element is displaying data * for. * See site_settings/constants.js for possible values. */ chooserType: { observer: 'chooserTypeChanged_', type: String, value: ChooserType.NONE, }, emptyListMessage_: { type: String, value: '', }, hasIncognito_: Boolean, tooltipText_: String, }; } chooserExceptions: Array<ChooserException>; chooserType: ChooserType; private emptyListMessage_: string; private hasIncognito_: boolean; private tooltipText_: string; connectedCallback() { super.connectedCallback(); this.addWebUIListener( 'contentSettingChooserPermissionChanged', (category: ContentSettingsTypes, chooserType: ChooserType) => { this.objectWithinChooserTypeChanged_(category, chooserType); }); this.addWebUIListener( 'onIncognitoStatusChanged', (hasIncognito: boolean) => this.onIncognitoStatusChanged_(hasIncognito)); this.browserProxy.updateIncognitoStatus(); } /** * Called when a chooser exception changes permission and updates the element * if |category| is equal to the settings category of this element. * @param category The content settings type that represents this permission * category. * @param chooserType The content settings type that represents the chooser * data for this permission. */ private objectWithinChooserTypeChanged_( category: ContentSettingsTypes, chooserType: ChooserType) { if (category === this.category && chooserType === this.chooserType) { this.chooserTypeChanged_(); } } /** * Called for each chooser-exception-list when incognito is enabled or * disabled. Only called on change (opening N incognito windows only fires one * message). Another message is sent when the *last* incognito window closes. */ private onIncognitoStatusChanged_(hasIncognito: boolean) { this.hasIncognito_ = hasIncognito; this.populateList_(); } /** * Configures the visibility of the widget and shows the list. */ private chooserTypeChanged_() { if (this.chooserType === ChooserType.NONE) { return; } // Set the message to display when the exception list is empty. switch (this.chooserType) { case ChooserType.USB_DEVICES: this.emptyListMessage_ = this.i18n('noUsbDevicesFound'); break; case ChooserType.SERIAL_PORTS: this.emptyListMessage_ = this.i18n('noSerialPortsFound'); break; case ChooserType.HID_DEVICES: this.emptyListMessage_ = this.i18n('noHidDevicesFound'); break; case ChooserType.BLUETOOTH_DEVICES: this.emptyListMessage_ = this.i18n('noBluetoothDevicesFound'); break; default: this.emptyListMessage_ = ''; } this.populateList_(); } /** * @return true if there are any chooser exceptions for this chooser type. */ private hasExceptions_(): boolean { return this.chooserExceptions.length > 0; } /** * Need to use a common tooltip since the tooltip in the entry is cut off from * the iron-list. */ private onShowTooltip_(e: CustomEvent<{target: HTMLElement, text: string}>) { this.tooltipText_ = e.detail.text; const target = e.detail.target; // paper-tooltip normally determines the target from the |for| property, // which is a selector. Here paper-tooltip is being reused by multiple // potential targets. this.$.tooltip.target = target; const hide = () => { this.$.tooltip.hide(); target.removeEventListener('mouseleave', hide); target.removeEventListener('blur', hide); target.removeEventListener('click', hide); this.$.tooltip.removeEventListener('mouseenter', hide); }; target.addEventListener('mouseleave', hide); target.addEventListener('blur', hide); target.addEventListener('click', hide); this.$.tooltip.addEventListener('mouseenter', hide); this.$.tooltip.show(); } /** * Populate the chooser exception list for display. */ private populateList_() { this.browserProxy.getChooserExceptionList(this.chooserType) .then(exceptionList => this.processExceptions_(exceptionList)); } /** * Process the chooser exception list returned from the native layer. */ private processExceptions_(exceptionList: Array<RawChooserException>) { const exceptions = exceptionList.map(exception => { const sites = exception.sites.map(site => this.expandSiteException(site)); return Object.assign(exception, {sites}); }); if (!this.updateList( 'chooserExceptions', x => x.displayName, exceptions, true /* identityBasedUpdate= */)) { // The chooser objects have not been changed, so check if their site // permissions have changed. The |exceptions| and |this.chooserExceptions| // arrays should be the same length. const siteUidGetter = (x: SiteException) => x.origin + x.embeddingOrigin + x.incognito; exceptions.forEach((exception, index) => { const propertyPath = 'chooserExceptions.' + index + '.sites'; this.updateList(propertyPath, siteUidGetter, exception.sites); }, this); } } } declare global { interface HTMLElementTagNameMap { 'chooser-exception-list': ChooserExceptionListElement; } } customElements.define( ChooserExceptionListElement.is, ChooserExceptionListElement);
value
identifier_name
chooser_exception_list.ts
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'chooser-exception-list' shows a list of chooser exceptions for a given * chooser type. */ import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import '../settings_shared_css.js'; import '../i18n_setup.js'; import './chooser_exception_list_entry.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {ListPropertyUpdateMixin} from 'chrome://resources/js/list_property_update_mixin.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {PaperTooltipElement} from 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './chooser_exception_list.html.js'; import {ChooserType, ContentSettingsTypes} from './constants.js'; import {SiteSettingsMixin} from './site_settings_mixin.js'; import {ChooserException, RawChooserException, SiteException} from './site_settings_prefs_browser_proxy.js'; export interface ChooserExceptionListElement { $: { tooltip: PaperTooltipElement, }; } const ChooserExceptionListElementBase = ListPropertyUpdateMixin( SiteSettingsMixin(WebUIListenerMixin(I18nMixin(PolymerElement)))); export class ChooserExceptionListElement extends ChooserExceptionListElementBase { static get is() { return 'chooser-exception-list'; } static get template() { return getTemplate(); } static get properties() { return { /** * Array of chooser exceptions to display in the widget. */ chooserExceptions: { type: Array, value() { return []; }, }, /** * The string ID of the chooser type that this element is displaying data * for. * See site_settings/constants.js for possible values. */ chooserType: { observer: 'chooserTypeChanged_', type: String, value: ChooserType.NONE, }, emptyListMessage_: { type: String, value: '', }, hasIncognito_: Boolean, tooltipText_: String, }; } chooserExceptions: Array<ChooserException>; chooserType: ChooserType; private emptyListMessage_: string; private hasIncognito_: boolean; private tooltipText_: string; connectedCallback() { super.connectedCallback(); this.addWebUIListener( 'contentSettingChooserPermissionChanged', (category: ContentSettingsTypes, chooserType: ChooserType) => { this.objectWithinChooserTypeChanged_(category, chooserType); }); this.addWebUIListener( 'onIncognitoStatusChanged', (hasIncognito: boolean) => this.onIncognitoStatusChanged_(hasIncognito)); this.browserProxy.updateIncognitoStatus(); } /** * Called when a chooser exception changes permission and updates the element * if |category| is equal to the settings category of this element. * @param category The content settings type that represents this permission * category. * @param chooserType The content settings type that represents the chooser * data for this permission. */ private objectWithinChooserTypeChanged_( category: ContentSettingsTypes, chooserType: ChooserType) { if (category === this.category && chooserType === this.chooserType) { this.chooserTypeChanged_(); } } /** * Called for each chooser-exception-list when incognito is enabled or * disabled. Only called on change (opening N incognito windows only fires one * message). Another message is sent when the *last* incognito window closes. */ private onIncognitoStatusChanged_(hasIncognito: boolean) { this.hasIncognito_ = hasIncognito; this.populateList_(); } /** * Configures the visibility of the widget and shows the list. */ private chooserTypeChanged_() { if (this.chooserType === ChooserType.NONE) { return; } // Set the message to display when the exception list is empty. switch (this.chooserType) { case ChooserType.USB_DEVICES: this.emptyListMessage_ = this.i18n('noUsbDevicesFound'); break; case ChooserType.SERIAL_PORTS: this.emptyListMessage_ = this.i18n('noSerialPortsFound'); break; case ChooserType.HID_DEVICES: this.emptyListMessage_ = this.i18n('noHidDevicesFound'); break; case ChooserType.BLUETOOTH_DEVICES: this.emptyListMessage_ = this.i18n('noBluetoothDevicesFound'); break; default: this.emptyListMessage_ = ''; } this.populateList_(); } /** * @return true if there are any chooser exceptions for this chooser type. */ private hasExceptions_(): boolean { return this.chooserExceptions.length > 0; } /** * Need to use a common tooltip since the tooltip in the entry is cut off from * the iron-list. */ private onShowTooltip_(e: CustomEvent<{target: HTMLElement, text: string}>) { this.tooltipText_ = e.detail.text; const target = e.detail.target; // paper-tooltip normally determines the target from the |for| property, // which is a selector. Here paper-tooltip is being reused by multiple // potential targets. this.$.tooltip.target = target; const hide = () => { this.$.tooltip.hide(); target.removeEventListener('mouseleave', hide); target.removeEventListener('blur', hide); target.removeEventListener('click', hide); this.$.tooltip.removeEventListener('mouseenter', hide); }; target.addEventListener('mouseleave', hide); target.addEventListener('blur', hide); target.addEventListener('click', hide); this.$.tooltip.addEventListener('mouseenter', hide); this.$.tooltip.show(); } /** * Populate the chooser exception list for display. */ private populateList_() { this.browserProxy.getChooserExceptionList(this.chooserType) .then(exceptionList => this.processExceptions_(exceptionList)); } /** * Process the chooser exception list returned from the native layer. */ private processExceptions_(exceptionList: Array<RawChooserException>) { const exceptions = exceptionList.map(exception => { const sites = exception.sites.map(site => this.expandSiteException(site)); return Object.assign(exception, {sites}); }); if (!this.updateList( 'chooserExceptions', x => x.displayName, exceptions, true /* identityBasedUpdate= */))
} } declare global { interface HTMLElementTagNameMap { 'chooser-exception-list': ChooserExceptionListElement; } } customElements.define( ChooserExceptionListElement.is, ChooserExceptionListElement);
{ // The chooser objects have not been changed, so check if their site // permissions have changed. The |exceptions| and |this.chooserExceptions| // arrays should be the same length. const siteUidGetter = (x: SiteException) => x.origin + x.embeddingOrigin + x.incognito; exceptions.forEach((exception, index) => { const propertyPath = 'chooserExceptions.' + index + '.sites'; this.updateList(propertyPath, siteUidGetter, exception.sites); }, this); }
conditional_block
chooser_exception_list.ts
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'chooser-exception-list' shows a list of chooser exceptions for a given * chooser type. */ import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import '../settings_shared_css.js'; import '../i18n_setup.js'; import './chooser_exception_list_entry.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {ListPropertyUpdateMixin} from 'chrome://resources/js/list_property_update_mixin.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {PaperTooltipElement} from 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './chooser_exception_list.html.js'; import {ChooserType, ContentSettingsTypes} from './constants.js'; import {SiteSettingsMixin} from './site_settings_mixin.js'; import {ChooserException, RawChooserException, SiteException} from './site_settings_prefs_browser_proxy.js'; export interface ChooserExceptionListElement { $: { tooltip: PaperTooltipElement, }; } const ChooserExceptionListElementBase = ListPropertyUpdateMixin( SiteSettingsMixin(WebUIListenerMixin(I18nMixin(PolymerElement)))); export class ChooserExceptionListElement extends ChooserExceptionListElementBase { static get is() { return 'chooser-exception-list'; } static get template() { return getTemplate(); } static get properties() { return { /** * Array of chooser exceptions to display in the widget. */ chooserExceptions: { type: Array, value() { return []; }, }, /** * The string ID of the chooser type that this element is displaying data * for. * See site_settings/constants.js for possible values. */ chooserType: { observer: 'chooserTypeChanged_', type: String, value: ChooserType.NONE, }, emptyListMessage_: { type: String, value: '', }, hasIncognito_: Boolean, tooltipText_: String, }; } chooserExceptions: Array<ChooserException>; chooserType: ChooserType; private emptyListMessage_: string; private hasIncognito_: boolean; private tooltipText_: string; connectedCallback() { super.connectedCallback(); this.addWebUIListener( 'contentSettingChooserPermissionChanged', (category: ContentSettingsTypes, chooserType: ChooserType) => { this.objectWithinChooserTypeChanged_(category, chooserType); }); this.addWebUIListener( 'onIncognitoStatusChanged', (hasIncognito: boolean) => this.onIncognitoStatusChanged_(hasIncognito)); this.browserProxy.updateIncognitoStatus(); } /** * Called when a chooser exception changes permission and updates the element * if |category| is equal to the settings category of this element. * @param category The content settings type that represents this permission * category. * @param chooserType The content settings type that represents the chooser * data for this permission. */ private objectWithinChooserTypeChanged_( category: ContentSettingsTypes, chooserType: ChooserType) { if (category === this.category && chooserType === this.chooserType) { this.chooserTypeChanged_(); } } /** * Called for each chooser-exception-list when incognito is enabled or * disabled. Only called on change (opening N incognito windows only fires one * message). Another message is sent when the *last* incognito window closes. */ private onIncognitoStatusChanged_(hasIncognito: boolean) { this.hasIncognito_ = hasIncognito; this.populateList_(); } /** * Configures the visibility of the widget and shows the list. */ private chooserTypeChanged_() { if (this.chooserType === ChooserType.NONE) { return; } // Set the message to display when the exception list is empty. switch (this.chooserType) { case ChooserType.USB_DEVICES: this.emptyListMessage_ = this.i18n('noUsbDevicesFound'); break; case ChooserType.SERIAL_PORTS: this.emptyListMessage_ = this.i18n('noSerialPortsFound'); break;
this.emptyListMessage_ = this.i18n('noHidDevicesFound'); break; case ChooserType.BLUETOOTH_DEVICES: this.emptyListMessage_ = this.i18n('noBluetoothDevicesFound'); break; default: this.emptyListMessage_ = ''; } this.populateList_(); } /** * @return true if there are any chooser exceptions for this chooser type. */ private hasExceptions_(): boolean { return this.chooserExceptions.length > 0; } /** * Need to use a common tooltip since the tooltip in the entry is cut off from * the iron-list. */ private onShowTooltip_(e: CustomEvent<{target: HTMLElement, text: string}>) { this.tooltipText_ = e.detail.text; const target = e.detail.target; // paper-tooltip normally determines the target from the |for| property, // which is a selector. Here paper-tooltip is being reused by multiple // potential targets. this.$.tooltip.target = target; const hide = () => { this.$.tooltip.hide(); target.removeEventListener('mouseleave', hide); target.removeEventListener('blur', hide); target.removeEventListener('click', hide); this.$.tooltip.removeEventListener('mouseenter', hide); }; target.addEventListener('mouseleave', hide); target.addEventListener('blur', hide); target.addEventListener('click', hide); this.$.tooltip.addEventListener('mouseenter', hide); this.$.tooltip.show(); } /** * Populate the chooser exception list for display. */ private populateList_() { this.browserProxy.getChooserExceptionList(this.chooserType) .then(exceptionList => this.processExceptions_(exceptionList)); } /** * Process the chooser exception list returned from the native layer. */ private processExceptions_(exceptionList: Array<RawChooserException>) { const exceptions = exceptionList.map(exception => { const sites = exception.sites.map(site => this.expandSiteException(site)); return Object.assign(exception, {sites}); }); if (!this.updateList( 'chooserExceptions', x => x.displayName, exceptions, true /* identityBasedUpdate= */)) { // The chooser objects have not been changed, so check if their site // permissions have changed. The |exceptions| and |this.chooserExceptions| // arrays should be the same length. const siteUidGetter = (x: SiteException) => x.origin + x.embeddingOrigin + x.incognito; exceptions.forEach((exception, index) => { const propertyPath = 'chooserExceptions.' + index + '.sites'; this.updateList(propertyPath, siteUidGetter, exception.sites); }, this); } } } declare global { interface HTMLElementTagNameMap { 'chooser-exception-list': ChooserExceptionListElement; } } customElements.define( ChooserExceptionListElement.is, ChooserExceptionListElement);
case ChooserType.HID_DEVICES:
random_line_split
restaurant.js
1) { return dishes[xx]; } } } } self.deliveryDiff = function(total) { var diff = parseFloat(self.delivery_min - total).toFixed(2); return diff; } self.meetDeliveryMin = function(total) { return total < parseFloat(self.delivery_min) ? true : false; } self.dateFromItem = function(item, offset) { var theTime = item.split(':'), theDate = new Date(); theDate.setHours(theTime[0]); theDate.setMinutes(theTime[1] + offset); return theDate; } self.deliveryHere = function( distance ){ return ( distance <= this.delivery_radius ) } self.closedMessage = function(){ if( self.closed_message != '' ){ return self.closed_message; } else { if( self._closedDueTo != '' ){ return self._closedDueTo; } return 'Temporarily Unavailable'; } } self.preset = function() { return self['_preset']; } self.finished = function(data) { for (x in data) { self[x] = data[x]; } if (App.minimalMode) { self.img = null; self.image = null; self.img64 = null; } self.categories(); if (App.isCordova) { // this shouldnt be used anymore, but old apps will still be pulling from this url // self.img = App.imgServer + '596x596/' + img + '.jpg'; } if (typeof complete == 'function') { complete.call(self); } } self.tagfy = function( tag, force ){ // driver's restaurant should be always open if( self.driver_restaurant ){ self._tag = ''; return; } if( tag ){ self._tag = tag; if( tag == 'opening' ){ if( ( self._opensIn && self._opensIn_formatted != '' ) || force ){ self._tag = tag; self._nextOpenTag(); } else { self._tag = 'closed'; if( !self.hours || self.hours.length == 0 ){ self._tag = 'force_close'; } self._nextOpenTag(); } } else { self._tag = tag; } return; } self._tag = ''; // Add the tags if( !self._open ){ self._tag = 'closed'; self._nextOpenTag(); if( self._closedDueTo ){ self._tag = 'force_close'; self._nextOpenTag(); } } if( self._open && self._closesIn !== 'false' && self._closesIn !== false && self._closesIn <= 15 ){ self._tag = 'closing'; } // if the restaurant does not have a closed message it has no hours for the week if( self.closed_message == '' ){ self._tag = 'force_close'; self._nextOpenTag(); } // if it has not tag, check if it is takeout only if( self._tag == '' ){ if( self.takeout == '1' && self.delivery != '1' ){ self._tag = 'takeout'; } } } self._nextOpenTag = function(){ if( self.next_open_time_message && self.next_open_time_message.message && self._opensIn_formatted == '' ){ self._tag = 'next_open'; } } self.getNow = function( now ){ if( now && now.getTime ){ return now; } return dateTime.getNow(); } self.openRestaurantPage = function( now ){ // See 2662 now = self.getNow( now ); if( self.open( now, true ) ){ return true; } self.opensIn( now ); if( self._opensIn && self._opensIn < ( 3600 ) ){ return true; } return false; } /* ** Open/Close check methods */ // return true if the restaurant is open self.open = function( now, ignoreOpensClosesInCalc ) { if( !ignoreOpensClosesInCalc ){ self.tagfy( 'opening', true ); } // if the restaurant has no hours it probably will not be opened for the next 24 hours self._hasHours = false; now = self.getNow( now ); self.processHours(); var now_time = now.getTime(); // loop to verify if it is open self._open = false; if( self.hours && self.hours.length > 0 ){ for( x in self.hours ){ self._hasHours = true; if( now_time >= self.hours[ x ]._from_time && now_time <= self.hours[ x ]._to_time ){ if( self.hours[ x ].status == 'open' ){ self._open = true; if( ignoreOpensClosesInCalc ){ return self._open; } // if it is open calc closes in self.closesIn( now ); self.tagfy(); return self._open; } else if( self.hours[ x ].status == 'close' ){ self._closedDueTo = ( self.hours[ x ].notes ) ? self.hours[ x ].notes : false; if( ignoreOpensClosesInCalc ){ return self._open; } // If it is closed calc opens in self.opensIn( now ); self.tagfy(); return self._open; } } } // If it is closed calc opens in self.opensIn( now ); self.tagfy(); if( !self._hasHours ){ self._closedDueTo = ( self._community_closed ? self._community_closed : ' ' ); // There is no reason, leave it blank } return self._open; } else { // if it doesn't have hours it is forced to be closed self._tag = 'force_close'; self._nextOpenTag(); self._closedDueTo = ( self._community_closed ? self._community_closed : ' ' ); // There is no reason, leave it blank } } self.closesIn = function( now ){ now = self.getNow( now ); self._closesIn = false; self._closesIn_formatted = ''; self.processHours(); var force_close = true; var now_time = now.getTime(); if( self.hours ){ for( x in self.hours ){ if( self.hours[ x ].status == 'close' ){ if( now_time <= self.hours[ x ]._from_time ){ self._closesIn = timestampDiff( self.hours[ x ]._from_time, now_time ); self._closesIn_formatted = formatTime( self._closesIn ); return; } } else { if( self.hours[ x ].status == 'open' ){ force_close = false; } } } } if( !self._open && force_close && ( self._closesIn == 0 || self._closesIn === false ) ){ self._open = false; } } self.opensIn = function( now ){ now = self.getNow( now ); self._opensIn = false; self._opensIn_formatted = ''; self.processHours(); var now_time = now.getTime(); for( x in self.hours ){ if( self.hours[ x ].status == 'open' ){ if( now_time <= self.hours[ x ]._from_time )
} } // it means the restaurant will not be opened for the next 24 hours if( self.next_open_time ){ self._opensIn = timestampDiff( Date.parse( self.next_open_time ), now_time ); if( self._opensIn <= 60 * 60 ){ self._opensIn_formatted = formatTime( self._opensIn, self.next_open_time_message ); } } } // Create javascript date objects to faster comparision self.processHours = function(){ if( !self._hours_processed ){ for( x in self.hours ){ self.hours[ x ]._from = Date.parse( self.hours[ x ].from ); self.hours[ x ]._from_time = self.hours[ x ]._from.getTime(); self.hours[ x ]._to = Date.parse( self.hours[ x ].to ); self.hours[ x ]._to_time = self.hours[ x ]._to.getTime(); } self._hours_processed = true; } } self.isActive = function( callback ){ var url = App.service + 'restaurant/active/' + self.id_restaurant; App.http.get
{ self._opensIn = timestampDiff( self.hours[ x ]._from_time, now_time ); if( self._opensIn <= 60 * 60 ){ self._opensIn_formatted = formatTime( self._opensIn ); return; } }
conditional_block
restaurant.js
1) { return dishes[xx]; } } } } self.deliveryDiff = function(total) { var diff = parseFloat(self.delivery_min - total).toFixed(2); return diff; } self.meetDeliveryMin = function(total) { return total < parseFloat(self.delivery_min) ? true : false; } self.dateFromItem = function(item, offset) { var theTime = item.split(':'), theDate = new Date(); theDate.setHours(theTime[0]); theDate.setMinutes(theTime[1] + offset); return theDate; } self.deliveryHere = function( distance ){ return ( distance <= this.delivery_radius ) } self.closedMessage = function(){ if( self.closed_message != '' ){ return self.closed_message; } else { if( self._closedDueTo != '' ){ return self._closedDueTo; } return 'Temporarily Unavailable'; } } self.preset = function() { return self['_preset']; } self.finished = function(data) { for (x in data) { self[x] = data[x]; } if (App.minimalMode) { self.img = null; self.image = null; self.img64 = null; } self.categories(); if (App.isCordova) { // this shouldnt be used anymore, but old apps will still be pulling from this url // self.img = App.imgServer + '596x596/' + img + '.jpg'; } if (typeof complete == 'function') { complete.call(self); } } self.tagfy = function( tag, force ){ // driver's restaurant should be always open if( self.driver_restaurant ){ self._tag = ''; return; } if( tag ){ self._tag = tag; if( tag == 'opening' ){ if( ( self._opensIn && self._opensIn_formatted != '' ) || force ){ self._tag = tag; self._nextOpenTag(); } else { self._tag = 'closed'; if( !self.hours || self.hours.length == 0 ){ self._tag = 'force_close'; } self._nextOpenTag(); } } else { self._tag = tag; } return; } self._tag = ''; // Add the tags if( !self._open ){ self._tag = 'closed'; self._nextOpenTag(); if( self._closedDueTo ){ self._tag = 'force_close'; self._nextOpenTag(); } } if( self._open && self._closesIn !== 'false' && self._closesIn !== false && self._closesIn <= 15 ){ self._tag = 'closing'; } // if the restaurant does not have a closed message it has no hours for the week if( self.closed_message == '' ){ self._tag = 'force_close'; self._nextOpenTag(); } // if it has not tag, check if it is takeout only if( self._tag == '' ){ if( self.takeout == '1' && self.delivery != '1' ){ self._tag = 'takeout'; } } } self._nextOpenTag = function(){ if( self.next_open_time_message && self.next_open_time_message.message && self._opensIn_formatted == '' ){ self._tag = 'next_open'; } } self.getNow = function( now ){ if( now && now.getTime ){ return now; } return dateTime.getNow(); }
return true; } self.opensIn( now ); if( self._opensIn && self._opensIn < ( 3600 ) ){ return true; } return false; } /* ** Open/Close check methods */ // return true if the restaurant is open self.open = function( now, ignoreOpensClosesInCalc ) { if( !ignoreOpensClosesInCalc ){ self.tagfy( 'opening', true ); } // if the restaurant has no hours it probably will not be opened for the next 24 hours self._hasHours = false; now = self.getNow( now ); self.processHours(); var now_time = now.getTime(); // loop to verify if it is open self._open = false; if( self.hours && self.hours.length > 0 ){ for( x in self.hours ){ self._hasHours = true; if( now_time >= self.hours[ x ]._from_time && now_time <= self.hours[ x ]._to_time ){ if( self.hours[ x ].status == 'open' ){ self._open = true; if( ignoreOpensClosesInCalc ){ return self._open; } // if it is open calc closes in self.closesIn( now ); self.tagfy(); return self._open; } else if( self.hours[ x ].status == 'close' ){ self._closedDueTo = ( self.hours[ x ].notes ) ? self.hours[ x ].notes : false; if( ignoreOpensClosesInCalc ){ return self._open; } // If it is closed calc opens in self.opensIn( now ); self.tagfy(); return self._open; } } } // If it is closed calc opens in self.opensIn( now ); self.tagfy(); if( !self._hasHours ){ self._closedDueTo = ( self._community_closed ? self._community_closed : ' ' ); // There is no reason, leave it blank } return self._open; } else { // if it doesn't have hours it is forced to be closed self._tag = 'force_close'; self._nextOpenTag(); self._closedDueTo = ( self._community_closed ? self._community_closed : ' ' ); // There is no reason, leave it blank } } self.closesIn = function( now ){ now = self.getNow( now ); self._closesIn = false; self._closesIn_formatted = ''; self.processHours(); var force_close = true; var now_time = now.getTime(); if( self.hours ){ for( x in self.hours ){ if( self.hours[ x ].status == 'close' ){ if( now_time <= self.hours[ x ]._from_time ){ self._closesIn = timestampDiff( self.hours[ x ]._from_time, now_time ); self._closesIn_formatted = formatTime( self._closesIn ); return; } } else { if( self.hours[ x ].status == 'open' ){ force_close = false; } } } } if( !self._open && force_close && ( self._closesIn == 0 || self._closesIn === false ) ){ self._open = false; } } self.opensIn = function( now ){ now = self.getNow( now ); self._opensIn = false; self._opensIn_formatted = ''; self.processHours(); var now_time = now.getTime(); for( x in self.hours ){ if( self.hours[ x ].status == 'open' ){ if( now_time <= self.hours[ x ]._from_time ){ self._opensIn = timestampDiff( self.hours[ x ]._from_time, now_time ); if( self._opensIn <= 60 * 60 ){ self._opensIn_formatted = formatTime( self._opensIn ); return; } } } } // it means the restaurant will not be opened for the next 24 hours if( self.next_open_time ){ self._opensIn = timestampDiff( Date.parse( self.next_open_time ), now_time ); if( self._opensIn <= 60 * 60 ){ self._opensIn_formatted = formatTime( self._opensIn, self.next_open_time_message ); } } } // Create javascript date objects to faster comparision self.processHours = function(){ if( !self._hours_processed ){ for( x in self.hours ){ self.hours[ x ]._from = Date.parse( self.hours[ x ].from ); self.hours[ x ]._from_time = self.hours[ x ]._from.getTime(); self.hours[ x ]._to = Date.parse( self.hours[ x ].to ); self.hours[ x ]._to_time = self.hours[ x ]._to.getTime(); } self._hours_processed = true; } } self.isActive = function( callback ){ var url = App.service + 'restaurant/active/' + self.id_restaurant; App.http.get( url
self.openRestaurantPage = function( now ){ // See 2662 now = self.getNow( now ); if( self.open( now, true ) ){
random_line_split
backbone.states.js
var State = Backbone.State = function(options) { options || (options = {}); }; _.extend(State.prototype, Backbone.Events, { classes: [], before: null, on: null, after: null, events: {}, triggers: [], multistate: [], _isStateDescribedInSet: function( set, state ) { var isDescribed = false; _.each( set, function( entry ) { if( state.match( entry ) ) { isDescribed = true; } }); return isDescribed; },
isStateDescribedInAllowed: function( state ) { return _isStateDescribedInSet( this.multistate.allow, state ); }, isStateDescribedInDisallowed: function( state ) { return _isStateDescribedInSet( this.multistate.disallow, state ); }, isStatePermitted: function( state ) { var allowed = false; if (this.multistate == "any" || this.multistate == "all") { return true; } if(this.isStateDescribedInAllowed( state )) return true; if(this.isStateDescribedInDisallowed( state )) return false; }, }); // Generic State Machine var StateMachine = Backbone.StateMachine = function(options) { options || (options = {}); if( options.el ) { this.setElement( options.el ); } } _.extend(StateMachine.prototype, Backbone.Events, { states: {}, state: null, el: null, $el: null, setElement: function( el ) { this.el = el; this.$el = this.el ? $(this.el) : null; }, get classes( ) { if(this.$el) { return _.toArray( this.$el.attr('class').split(/\s+/) ); } else { return null; } }, set classes( newClasses ) { if( !$this.el) if( typeof newClasses === 'string' ) { this.$el.attr('class', newClasses); } else { this.$el.attr('class', newClasses.join(' ')); } }, createState: function( name, state ) { state = (typeof state === State) ? state : new State( state ); this.states[name] = state; return this; }, // Private method for applying a state _applyState: function( state ) { this.events = _.union( this.events, state.events); this.classes = _.union( this.classes, state.classes); this.state = state; }, // Private method for cleaning up the previous state _removeState: function( state ) { this.events = _.difference( this.events, state.events ); this.classes = _.difference( this.classes, state.classes ); this.state = null; }, //Public method for changing the state pushState: function( name ) { var oldState = this.state, newState = this.states[name]; // Old State if(oldState) { this._removeState( state ); if(oldState.after) oldState.after( name ); } // New State if(newState && newState.before) { newState.before(); } this._applyState( newState ); if(this.state && this.state.on) { this.state.on(); } this.trigger("stateChanged", { oldState: oldState, newState: newState }); } });
random_line_split
backbone.states.js
var State = Backbone.State = function(options) { options || (options = {}); }; _.extend(State.prototype, Backbone.Events, { classes: [], before: null, on: null, after: null, events: {}, triggers: [], multistate: [], _isStateDescribedInSet: function( set, state ) { var isDescribed = false; _.each( set, function( entry ) { if( state.match( entry ) ) { isDescribed = true; } }); return isDescribed; }, isStateDescribedInAllowed: function( state ) { return _isStateDescribedInSet( this.multistate.allow, state ); }, isStateDescribedInDisallowed: function( state ) { return _isStateDescribedInSet( this.multistate.disallow, state ); }, isStatePermitted: function( state ) { var allowed = false; if (this.multistate == "any" || this.multistate == "all") { return true; } if(this.isStateDescribedInAllowed( state )) return true; if(this.isStateDescribedInDisallowed( state )) return false; }, }); // Generic State Machine var StateMachine = Backbone.StateMachine = function(options) { options || (options = {}); if( options.el ) { this.setElement( options.el ); } } _.extend(StateMachine.prototype, Backbone.Events, { states: {}, state: null, el: null, $el: null, setElement: function( el ) { this.el = el; this.$el = this.el ? $(this.el) : null; }, get classes( ) { if(this.$el)
else { return null; } }, set classes( newClasses ) { if( !$this.el) if( typeof newClasses === 'string' ) { this.$el.attr('class', newClasses); } else { this.$el.attr('class', newClasses.join(' ')); } }, createState: function( name, state ) { state = (typeof state === State) ? state : new State( state ); this.states[name] = state; return this; }, // Private method for applying a state _applyState: function( state ) { this.events = _.union( this.events, state.events); this.classes = _.union( this.classes, state.classes); this.state = state; }, // Private method for cleaning up the previous state _removeState: function( state ) { this.events = _.difference( this.events, state.events ); this.classes = _.difference( this.classes, state.classes ); this.state = null; }, //Public method for changing the state pushState: function( name ) { var oldState = this.state, newState = this.states[name]; // Old State if(oldState) { this._removeState( state ); if(oldState.after) oldState.after( name ); } // New State if(newState && newState.before) { newState.before(); } this._applyState( newState ); if(this.state && this.state.on) { this.state.on(); } this.trigger("stateChanged", { oldState: oldState, newState: newState }); } });
{ return _.toArray( this.$el.attr('class').split(/\s+/) ); }
conditional_block
backbone.states.js
var State = Backbone.State = function(options) { options || (options = {}); }; _.extend(State.prototype, Backbone.Events, { classes: [], before: null, on: null, after: null, events: {}, triggers: [], multistate: [], _isStateDescribedInSet: function( set, state ) { var isDescribed = false; _.each( set, function( entry ) { if( state.match( entry ) ) { isDescribed = true; } }); return isDescribed; }, isStateDescribedInAllowed: function( state ) { return _isStateDescribedInSet( this.multistate.allow, state ); }, isStateDescribedInDisallowed: function( state ) { return _isStateDescribedInSet( this.multistate.disallow, state ); }, isStatePermitted: function( state ) { var allowed = false; if (this.multistate == "any" || this.multistate == "all") { return true; } if(this.isStateDescribedInAllowed( state )) return true; if(this.isStateDescribedInDisallowed( state )) return false; }, }); // Generic State Machine var StateMachine = Backbone.StateMachine = function(options) { options || (options = {}); if( options.el ) { this.setElement( options.el ); } } _.extend(StateMachine.prototype, Backbone.Events, { states: {}, state: null, el: null, $el: null, setElement: function( el ) { this.el = el; this.$el = this.el ? $(this.el) : null; }, get
( ) { if(this.$el) { return _.toArray( this.$el.attr('class').split(/\s+/) ); } else { return null; } }, set classes( newClasses ) { if( !$this.el) if( typeof newClasses === 'string' ) { this.$el.attr('class', newClasses); } else { this.$el.attr('class', newClasses.join(' ')); } }, createState: function( name, state ) { state = (typeof state === State) ? state : new State( state ); this.states[name] = state; return this; }, // Private method for applying a state _applyState: function( state ) { this.events = _.union( this.events, state.events); this.classes = _.union( this.classes, state.classes); this.state = state; }, // Private method for cleaning up the previous state _removeState: function( state ) { this.events = _.difference( this.events, state.events ); this.classes = _.difference( this.classes, state.classes ); this.state = null; }, //Public method for changing the state pushState: function( name ) { var oldState = this.state, newState = this.states[name]; // Old State if(oldState) { this._removeState( state ); if(oldState.after) oldState.after( name ); } // New State if(newState && newState.before) { newState.before(); } this._applyState( newState ); if(this.state && this.state.on) { this.state.on(); } this.trigger("stateChanged", { oldState: oldState, newState: newState }); } });
classes
identifier_name
backbone.states.js
var State = Backbone.State = function(options) { options || (options = {}); }; _.extend(State.prototype, Backbone.Events, { classes: [], before: null, on: null, after: null, events: {}, triggers: [], multistate: [], _isStateDescribedInSet: function( set, state ) { var isDescribed = false; _.each( set, function( entry ) { if( state.match( entry ) ) { isDescribed = true; } }); return isDescribed; }, isStateDescribedInAllowed: function( state ) { return _isStateDescribedInSet( this.multistate.allow, state ); }, isStateDescribedInDisallowed: function( state ) { return _isStateDescribedInSet( this.multistate.disallow, state ); }, isStatePermitted: function( state ) { var allowed = false; if (this.multistate == "any" || this.multistate == "all") { return true; } if(this.isStateDescribedInAllowed( state )) return true; if(this.isStateDescribedInDisallowed( state )) return false; }, }); // Generic State Machine var StateMachine = Backbone.StateMachine = function(options) { options || (options = {}); if( options.el ) { this.setElement( options.el ); } } _.extend(StateMachine.prototype, Backbone.Events, { states: {}, state: null, el: null, $el: null, setElement: function( el ) { this.el = el; this.$el = this.el ? $(this.el) : null; }, get classes( )
, set classes( newClasses ) { if( !$this.el) if( typeof newClasses === 'string' ) { this.$el.attr('class', newClasses); } else { this.$el.attr('class', newClasses.join(' ')); } }, createState: function( name, state ) { state = (typeof state === State) ? state : new State( state ); this.states[name] = state; return this; }, // Private method for applying a state _applyState: function( state ) { this.events = _.union( this.events, state.events); this.classes = _.union( this.classes, state.classes); this.state = state; }, // Private method for cleaning up the previous state _removeState: function( state ) { this.events = _.difference( this.events, state.events ); this.classes = _.difference( this.classes, state.classes ); this.state = null; }, //Public method for changing the state pushState: function( name ) { var oldState = this.state, newState = this.states[name]; // Old State if(oldState) { this._removeState( state ); if(oldState.after) oldState.after( name ); } // New State if(newState && newState.before) { newState.before(); } this._applyState( newState ); if(this.state && this.state.on) { this.state.on(); } this.trigger("stateChanged", { oldState: oldState, newState: newState }); } });
{ if(this.$el) { return _.toArray( this.$el.attr('class').split(/\s+/) ); } else { return null; } }
identifier_body
sweep.py
# coding=utf-8 # Copyright 2018 The DisentanglementLib Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Hyperparameter sweeps and configs for stage 1 of "abstract_reasoning_study". Are Disentangled Representations Helpful for Abstract Visual Reasoning? Sjoerd van Steenkiste, Francesco Locatello, Juergen Schmidhuber, Olivier Bachem. NeurIPS, 2019. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.config import study from disentanglement_lib.utils import resources import disentanglement_lib.utils.hyperparams as h from six.moves import range def get_datasets(): """Returns all the data sets.""" return h.sweep( "dataset.name", h.categorical(["shapes3d", "abstract_dsprites"])) def get_num_latent(sweep): return h.sweep("encoder.num_latent", h.discrete(sweep)) def get_seeds(num): """Returns random seeds.""" return h.sweep("model.random_seed", h.categorical(list(range(num)))) def get_default_models(): """Our default set of models (6 model * 6 hyperparameters=36 models).""" # BetaVAE config. model_name = h.fixed("model.name", "beta_vae") model_fn = h.fixed("model.model", "@vae()") betas = h.sweep("vae.beta", h.discrete([1., 2., 4., 6., 8., 16.])) config_beta_vae = h.zipit([model_name, betas, model_fn]) # AnnealedVAE config. model_name = h.fixed("model.name", "annealed_vae") model_fn = h.fixed("model.model", "@annealed_vae()") iteration_threshold = h.fixed("annealed_vae.iteration_threshold", 100000) c = h.sweep("annealed_vae.c_max", h.discrete([5., 10., 25., 50., 75., 100.])) gamma = h.fixed("annealed_vae.gamma", 1000) config_annealed_beta_vae = h.zipit( [model_name, c, iteration_threshold, gamma, model_fn]) # FactorVAE config. model_name = h.fixed("model.name", "factor_vae") model_fn = h.fixed("model.model", "@factor_vae()") discr_fn = h.fixed("discriminator.discriminator_fn", "@fc_discriminator") gammas = h.sweep("factor_vae.gamma", h.discrete([10., 20., 30., 40., 50., 100.])) config_factor_vae = h.zipit([model_name, gammas, model_fn, discr_fn]) # DIP-VAE-I config. model_name = h.fixed("model.name", "dip_vae_i") model_fn = h.fixed("model.model", "@dip_vae()") lambda_od = h.sweep("dip_vae.lambda_od", h.discrete([1., 2., 5., 10., 20., 50.])) lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 10.) dip_type = h.fixed("dip_vae.dip_type", "i") config_dip_vae_i = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # DIP-VAE-II config. model_name = h.fixed("model.name", "dip_vae_ii") model_fn = h.fixed("model.model", "@dip_vae()") lambda_od = h.sweep("dip_vae.lambda_od", h.discrete([1., 2., 5., 10., 20., 50.])) lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 1.) dip_type = h.fixed("dip_vae.dip_type", "ii") config_dip_vae_ii = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # BetaTCVAE config. model_name = h.fixed("model.name", "beta_tc_vae") model_fn = h.fixed("model.model", "@beta_tc_vae()") betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.])) config_beta_tc_vae = h.zipit([model_name, model_fn, betas]) all_models = h.chainit([ config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii, config_beta_tc_vae, config_annealed_beta_vae ]) return all_models def get_config():
class AbstractReasoningStudyV1(study.Study): """Defines the study for the paper.""" def get_model_config(self, model_num=0): """Returns model bindings and config file.""" config = get_config()[model_num] model_bindings = h.to_bindings(config) model_config_file = resources.get_file( "config/abstract_reasoning_study_v1/stage1/model_configs/shared.gin") return model_bindings, model_config_file def get_postprocess_config_files(self): """Returns postprocessing config files.""" return list( resources.get_files_in_folder( "config/abstract_reasoning_study_v1/stage1/postprocess_configs/")) def get_eval_config_files(self): """Returns evaluation config files.""" return list( resources.get_files_in_folder( "config/abstract_reasoning_study_v1/stage1/metric_configs/"))
"""Returns the hyperparameter configs for different experiments.""" arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1) arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1) architecture = h.zipit([arch_enc, arch_dec]) return h.product([ get_datasets(), architecture, get_default_models(), get_seeds(5), ])
identifier_body
sweep.py
# coding=utf-8 # Copyright 2018 The DisentanglementLib Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Hyperparameter sweeps and configs for stage 1 of "abstract_reasoning_study". Are Disentangled Representations Helpful for Abstract Visual Reasoning? Sjoerd van Steenkiste, Francesco Locatello, Juergen Schmidhuber, Olivier Bachem. NeurIPS, 2019. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.config import study from disentanglement_lib.utils import resources import disentanglement_lib.utils.hyperparams as h from six.moves import range def get_datasets(): """Returns all the data sets.""" return h.sweep( "dataset.name", h.categorical(["shapes3d", "abstract_dsprites"])) def get_num_latent(sweep): return h.sweep("encoder.num_latent", h.discrete(sweep)) def get_seeds(num): """Returns random seeds.""" return h.sweep("model.random_seed", h.categorical(list(range(num)))) def get_default_models(): """Our default set of models (6 model * 6 hyperparameters=36 models).""" # BetaVAE config. model_name = h.fixed("model.name", "beta_vae") model_fn = h.fixed("model.model", "@vae()") betas = h.sweep("vae.beta", h.discrete([1., 2., 4., 6., 8., 16.])) config_beta_vae = h.zipit([model_name, betas, model_fn]) # AnnealedVAE config. model_name = h.fixed("model.name", "annealed_vae") model_fn = h.fixed("model.model", "@annealed_vae()") iteration_threshold = h.fixed("annealed_vae.iteration_threshold", 100000) c = h.sweep("annealed_vae.c_max", h.discrete([5., 10., 25., 50., 75., 100.])) gamma = h.fixed("annealed_vae.gamma", 1000) config_annealed_beta_vae = h.zipit( [model_name, c, iteration_threshold, gamma, model_fn])
gammas = h.sweep("factor_vae.gamma", h.discrete([10., 20., 30., 40., 50., 100.])) config_factor_vae = h.zipit([model_name, gammas, model_fn, discr_fn]) # DIP-VAE-I config. model_name = h.fixed("model.name", "dip_vae_i") model_fn = h.fixed("model.model", "@dip_vae()") lambda_od = h.sweep("dip_vae.lambda_od", h.discrete([1., 2., 5., 10., 20., 50.])) lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 10.) dip_type = h.fixed("dip_vae.dip_type", "i") config_dip_vae_i = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # DIP-VAE-II config. model_name = h.fixed("model.name", "dip_vae_ii") model_fn = h.fixed("model.model", "@dip_vae()") lambda_od = h.sweep("dip_vae.lambda_od", h.discrete([1., 2., 5., 10., 20., 50.])) lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 1.) dip_type = h.fixed("dip_vae.dip_type", "ii") config_dip_vae_ii = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # BetaTCVAE config. model_name = h.fixed("model.name", "beta_tc_vae") model_fn = h.fixed("model.model", "@beta_tc_vae()") betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.])) config_beta_tc_vae = h.zipit([model_name, model_fn, betas]) all_models = h.chainit([ config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii, config_beta_tc_vae, config_annealed_beta_vae ]) return all_models def get_config(): """Returns the hyperparameter configs for different experiments.""" arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1) arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1) architecture = h.zipit([arch_enc, arch_dec]) return h.product([ get_datasets(), architecture, get_default_models(), get_seeds(5), ]) class AbstractReasoningStudyV1(study.Study): """Defines the study for the paper.""" def get_model_config(self, model_num=0): """Returns model bindings and config file.""" config = get_config()[model_num] model_bindings = h.to_bindings(config) model_config_file = resources.get_file( "config/abstract_reasoning_study_v1/stage1/model_configs/shared.gin") return model_bindings, model_config_file def get_postprocess_config_files(self): """Returns postprocessing config files.""" return list( resources.get_files_in_folder( "config/abstract_reasoning_study_v1/stage1/postprocess_configs/")) def get_eval_config_files(self): """Returns evaluation config files.""" return list( resources.get_files_in_folder( "config/abstract_reasoning_study_v1/stage1/metric_configs/"))
# FactorVAE config. model_name = h.fixed("model.name", "factor_vae") model_fn = h.fixed("model.model", "@factor_vae()") discr_fn = h.fixed("discriminator.discriminator_fn", "@fc_discriminator")
random_line_split
sweep.py
# coding=utf-8 # Copyright 2018 The DisentanglementLib Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Hyperparameter sweeps and configs for stage 1 of "abstract_reasoning_study". Are Disentangled Representations Helpful for Abstract Visual Reasoning? Sjoerd van Steenkiste, Francesco Locatello, Juergen Schmidhuber, Olivier Bachem. NeurIPS, 2019. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.config import study from disentanglement_lib.utils import resources import disentanglement_lib.utils.hyperparams as h from six.moves import range def get_datasets(): """Returns all the data sets.""" return h.sweep( "dataset.name", h.categorical(["shapes3d", "abstract_dsprites"])) def get_num_latent(sweep): return h.sweep("encoder.num_latent", h.discrete(sweep)) def
(num): """Returns random seeds.""" return h.sweep("model.random_seed", h.categorical(list(range(num)))) def get_default_models(): """Our default set of models (6 model * 6 hyperparameters=36 models).""" # BetaVAE config. model_name = h.fixed("model.name", "beta_vae") model_fn = h.fixed("model.model", "@vae()") betas = h.sweep("vae.beta", h.discrete([1., 2., 4., 6., 8., 16.])) config_beta_vae = h.zipit([model_name, betas, model_fn]) # AnnealedVAE config. model_name = h.fixed("model.name", "annealed_vae") model_fn = h.fixed("model.model", "@annealed_vae()") iteration_threshold = h.fixed("annealed_vae.iteration_threshold", 100000) c = h.sweep("annealed_vae.c_max", h.discrete([5., 10., 25., 50., 75., 100.])) gamma = h.fixed("annealed_vae.gamma", 1000) config_annealed_beta_vae = h.zipit( [model_name, c, iteration_threshold, gamma, model_fn]) # FactorVAE config. model_name = h.fixed("model.name", "factor_vae") model_fn = h.fixed("model.model", "@factor_vae()") discr_fn = h.fixed("discriminator.discriminator_fn", "@fc_discriminator") gammas = h.sweep("factor_vae.gamma", h.discrete([10., 20., 30., 40., 50., 100.])) config_factor_vae = h.zipit([model_name, gammas, model_fn, discr_fn]) # DIP-VAE-I config. model_name = h.fixed("model.name", "dip_vae_i") model_fn = h.fixed("model.model", "@dip_vae()") lambda_od = h.sweep("dip_vae.lambda_od", h.discrete([1., 2., 5., 10., 20., 50.])) lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 10.) dip_type = h.fixed("dip_vae.dip_type", "i") config_dip_vae_i = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # DIP-VAE-II config. model_name = h.fixed("model.name", "dip_vae_ii") model_fn = h.fixed("model.model", "@dip_vae()") lambda_od = h.sweep("dip_vae.lambda_od", h.discrete([1., 2., 5., 10., 20., 50.])) lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 1.) dip_type = h.fixed("dip_vae.dip_type", "ii") config_dip_vae_ii = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # BetaTCVAE config. model_name = h.fixed("model.name", "beta_tc_vae") model_fn = h.fixed("model.model", "@beta_tc_vae()") betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.])) config_beta_tc_vae = h.zipit([model_name, model_fn, betas]) all_models = h.chainit([ config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii, config_beta_tc_vae, config_annealed_beta_vae ]) return all_models def get_config(): """Returns the hyperparameter configs for different experiments.""" arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1) arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1) architecture = h.zipit([arch_enc, arch_dec]) return h.product([ get_datasets(), architecture, get_default_models(), get_seeds(5), ]) class AbstractReasoningStudyV1(study.Study): """Defines the study for the paper.""" def get_model_config(self, model_num=0): """Returns model bindings and config file.""" config = get_config()[model_num] model_bindings = h.to_bindings(config) model_config_file = resources.get_file( "config/abstract_reasoning_study_v1/stage1/model_configs/shared.gin") return model_bindings, model_config_file def get_postprocess_config_files(self): """Returns postprocessing config files.""" return list( resources.get_files_in_folder( "config/abstract_reasoning_study_v1/stage1/postprocess_configs/")) def get_eval_config_files(self): """Returns evaluation config files.""" return list( resources.get_files_in_folder( "config/abstract_reasoning_study_v1/stage1/metric_configs/"))
get_seeds
identifier_name
main.py
''' Controller for the application ''' import logging import sys import traceback import forms from models import Settings from flask import Flask, render_template from google.appengine.api import app_identity # pylint: disable=E0401 from google.appengine.api import mail # pylint: disable=E0401 from google.appengine.api import users import pdb # Initialize the application with CSRF app = Flask(__name__) # pylint: disable=invalid-name # Set the Flask debug to false so you can use GAE debug app.config.update(DEBUG=False) app.secret_key = Settings.get('SECRET_KEY') app.config['RECAPTCHA_USE_SSL'] = False app.config['RECAPTCHA_PUBLIC_KEY'] = Settings.get('RECAPTCHA_PUBLIC_KEY') app.config['RECAPTCHA_PRIVATE_KEY'] = Settings.get('RECAPTCHA_PRIVATE_KEY') app.config['RECAPTCHA_OPTIONS'] = {'theme': 'white'} @app.before_request def enable_local_error_handling(): ''' test of log ''' app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) @app.route('/', methods=['GET', 'POST']) def form(): ''' Show the message form for the user to fill in ''' message_form = forms.MessageForm() if message_form.validate_on_submit():
return render_template('form.html', title="Message", form=message_form) def send_mail(their_email, their_message): ''' Send an email message to me ''' message = mail.EmailMessage(sender=app_identity.get_application_id() + '@appspot.gserviceaccount.com>') message.subject = 'Message from Bagbatch Website' message.to = Settings.get('EMAIL') message.body = """From: {}\n\n<<BEGINS>>\n\n{}\n\n<<ENDS>>""".format(their_email, their_message) message.send() @app.errorhandler(500) def server_error(error): ''' Log any errors to the browser because you are too lazy to look at the console The Flask DEBUG setting must the set to false for this to work ''' exception_type, exception_value, trace_back = sys.exc_info() no_limit = None exception = ''.join(traceback.format_exception(exception_type, exception_value, trace_back, no_limit)) logging.exception('An error occurred during a request. ' + str(error)) return render_template('500.html', title=error, exception=exception) @app.route('/admin', methods=['GET']) def admin_page(): ''' Authentication required page ''' user = users.get_current_user() return render_template('admin.html', email=user.email())
send_mail(message_form.email.data, message_form.message.data) return render_template('submitted_form.html', title="Thanks", form=message_form)
conditional_block
main.py
''' Controller for the application ''' import logging import sys import traceback import forms from models import Settings from flask import Flask, render_template from google.appengine.api import app_identity # pylint: disable=E0401 from google.appengine.api import mail # pylint: disable=E0401 from google.appengine.api import users import pdb # Initialize the application with CSRF app = Flask(__name__) # pylint: disable=invalid-name # Set the Flask debug to false so you can use GAE debug app.config.update(DEBUG=False) app.secret_key = Settings.get('SECRET_KEY') app.config['RECAPTCHA_USE_SSL'] = False app.config['RECAPTCHA_PUBLIC_KEY'] = Settings.get('RECAPTCHA_PUBLIC_KEY') app.config['RECAPTCHA_PRIVATE_KEY'] = Settings.get('RECAPTCHA_PRIVATE_KEY') app.config['RECAPTCHA_OPTIONS'] = {'theme': 'white'} @app.before_request def enable_local_error_handling(): ''' test of log ''' app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) @app.route('/', methods=['GET', 'POST']) def form():
def send_mail(their_email, their_message): ''' Send an email message to me ''' message = mail.EmailMessage(sender=app_identity.get_application_id() + '@appspot.gserviceaccount.com>') message.subject = 'Message from Bagbatch Website' message.to = Settings.get('EMAIL') message.body = """From: {}\n\n<<BEGINS>>\n\n{}\n\n<<ENDS>>""".format(their_email, their_message) message.send() @app.errorhandler(500) def server_error(error): ''' Log any errors to the browser because you are too lazy to look at the console The Flask DEBUG setting must the set to false for this to work ''' exception_type, exception_value, trace_back = sys.exc_info() no_limit = None exception = ''.join(traceback.format_exception(exception_type, exception_value, trace_back, no_limit)) logging.exception('An error occurred during a request. ' + str(error)) return render_template('500.html', title=error, exception=exception) @app.route('/admin', methods=['GET']) def admin_page(): ''' Authentication required page ''' user = users.get_current_user() return render_template('admin.html', email=user.email())
''' Show the message form for the user to fill in ''' message_form = forms.MessageForm() if message_form.validate_on_submit(): send_mail(message_form.email.data, message_form.message.data) return render_template('submitted_form.html', title="Thanks", form=message_form) return render_template('form.html', title="Message", form=message_form)
identifier_body
main.py
''' Controller for the application ''' import logging import sys import traceback import forms from models import Settings from flask import Flask, render_template from google.appengine.api import app_identity # pylint: disable=E0401 from google.appengine.api import mail # pylint: disable=E0401 from google.appengine.api import users import pdb # Initialize the application with CSRF app = Flask(__name__) # pylint: disable=invalid-name # Set the Flask debug to false so you can use GAE debug app.config.update(DEBUG=False) app.secret_key = Settings.get('SECRET_KEY') app.config['RECAPTCHA_USE_SSL'] = False app.config['RECAPTCHA_PUBLIC_KEY'] = Settings.get('RECAPTCHA_PUBLIC_KEY') app.config['RECAPTCHA_PRIVATE_KEY'] = Settings.get('RECAPTCHA_PRIVATE_KEY') app.config['RECAPTCHA_OPTIONS'] = {'theme': 'white'} @app.before_request def enable_local_error_handling(): ''' test of log '''
''' Show the message form for the user to fill in ''' message_form = forms.MessageForm() if message_form.validate_on_submit(): send_mail(message_form.email.data, message_form.message.data) return render_template('submitted_form.html', title="Thanks", form=message_form) return render_template('form.html', title="Message", form=message_form) def send_mail(their_email, their_message): ''' Send an email message to me ''' message = mail.EmailMessage(sender=app_identity.get_application_id() + '@appspot.gserviceaccount.com>') message.subject = 'Message from Bagbatch Website' message.to = Settings.get('EMAIL') message.body = """From: {}\n\n<<BEGINS>>\n\n{}\n\n<<ENDS>>""".format(their_email, their_message) message.send() @app.errorhandler(500) def server_error(error): ''' Log any errors to the browser because you are too lazy to look at the console The Flask DEBUG setting must the set to false for this to work ''' exception_type, exception_value, trace_back = sys.exc_info() no_limit = None exception = ''.join(traceback.format_exception(exception_type, exception_value, trace_back, no_limit)) logging.exception('An error occurred during a request. ' + str(error)) return render_template('500.html', title=error, exception=exception) @app.route('/admin', methods=['GET']) def admin_page(): ''' Authentication required page ''' user = users.get_current_user() return render_template('admin.html', email=user.email())
app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) @app.route('/', methods=['GET', 'POST']) def form():
random_line_split
main.py
''' Controller for the application ''' import logging import sys import traceback import forms from models import Settings from flask import Flask, render_template from google.appengine.api import app_identity # pylint: disable=E0401 from google.appengine.api import mail # pylint: disable=E0401 from google.appengine.api import users import pdb # Initialize the application with CSRF app = Flask(__name__) # pylint: disable=invalid-name # Set the Flask debug to false so you can use GAE debug app.config.update(DEBUG=False) app.secret_key = Settings.get('SECRET_KEY') app.config['RECAPTCHA_USE_SSL'] = False app.config['RECAPTCHA_PUBLIC_KEY'] = Settings.get('RECAPTCHA_PUBLIC_KEY') app.config['RECAPTCHA_PRIVATE_KEY'] = Settings.get('RECAPTCHA_PRIVATE_KEY') app.config['RECAPTCHA_OPTIONS'] = {'theme': 'white'} @app.before_request def enable_local_error_handling(): ''' test of log ''' app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) @app.route('/', methods=['GET', 'POST']) def form(): ''' Show the message form for the user to fill in ''' message_form = forms.MessageForm() if message_form.validate_on_submit(): send_mail(message_form.email.data, message_form.message.data) return render_template('submitted_form.html', title="Thanks", form=message_form) return render_template('form.html', title="Message", form=message_form) def
(their_email, their_message): ''' Send an email message to me ''' message = mail.EmailMessage(sender=app_identity.get_application_id() + '@appspot.gserviceaccount.com>') message.subject = 'Message from Bagbatch Website' message.to = Settings.get('EMAIL') message.body = """From: {}\n\n<<BEGINS>>\n\n{}\n\n<<ENDS>>""".format(their_email, their_message) message.send() @app.errorhandler(500) def server_error(error): ''' Log any errors to the browser because you are too lazy to look at the console The Flask DEBUG setting must the set to false for this to work ''' exception_type, exception_value, trace_back = sys.exc_info() no_limit = None exception = ''.join(traceback.format_exception(exception_type, exception_value, trace_back, no_limit)) logging.exception('An error occurred during a request. ' + str(error)) return render_template('500.html', title=error, exception=exception) @app.route('/admin', methods=['GET']) def admin_page(): ''' Authentication required page ''' user = users.get_current_user() return render_template('admin.html', email=user.email())
send_mail
identifier_name
server.js
var eio = require('engine.io'), HashMap = require('hashmap').HashMap; function
() { var self = this; self.endpoint = { port: 44444, host: 'localhost' }; self.server = eio.listen(self.endpoint.port, self.endpoint.host); self.server.on('connection', function(socket){ console.log('Server :: Connection from socket: ' + socket.id); socket.on('message', function(msg){ console.log('Server :: Message event from socket: ' + socket.id + ', with message: ' + msg); // echo message back socket.send('echoed back: ' + msg); }); socket.on('close', function(){ console.log('Server :: Close event from socket: ' + socket.id); }); socket.on('disconnect', function(){ console.log('Server :: Disconnect event from socket: ' + socket.id); }); }); } var server = new Server();
Server
identifier_name
server.js
var eio = require('engine.io'), HashMap = require('hashmap').HashMap; function Server()
}); socket.on('disconnect', function(){ console.log('Server :: Disconnect event from socket: ' + socket.id); }); }); } var server = new Server();
{ var self = this; self.endpoint = { port: 44444, host: 'localhost' }; self.server = eio.listen(self.endpoint.port, self.endpoint.host); self.server.on('connection', function(socket){ console.log('Server :: Connection from socket: ' + socket.id); socket.on('message', function(msg){ console.log('Server :: Message event from socket: ' + socket.id + ', with message: ' + msg); // echo message back socket.send('echoed back: ' + msg); }); socket.on('close', function(){ console.log('Server :: Close event from socket: ' + socket.id);
identifier_body
server.js
var eio = require('engine.io'), HashMap = require('hashmap').HashMap; function Server() { var self = this; self.endpoint = { port: 44444,
host: 'localhost' }; self.server = eio.listen(self.endpoint.port, self.endpoint.host); self.server.on('connection', function(socket){ console.log('Server :: Connection from socket: ' + socket.id); socket.on('message', function(msg){ console.log('Server :: Message event from socket: ' + socket.id + ', with message: ' + msg); // echo message back socket.send('echoed back: ' + msg); }); socket.on('close', function(){ console.log('Server :: Close event from socket: ' + socket.id); }); socket.on('disconnect', function(){ console.log('Server :: Disconnect event from socket: ' + socket.id); }); }); } var server = new Server();
random_line_split
main.rs
extern crate getopts; extern crate librespot; extern crate rpassword; use std::clone::Clone; use std::fs::File; use std::io::{stdout, Read, Write}; use std::path::Path; use std::thread; use std::path::PathBuf; use getopts::Options; use rpassword::read_password; use librespot::session::{Config, Session}; use librespot::util::version::version_string; use librespot::player::Player; use librespot::spirc::SpircManager; fn usage(program: &str, opts: &Options) -> String { let brief = format!("Usage: {} [options]", program); format!("{}", opts.usage(&brief)) } fn
() { let args: Vec<String> = std::env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY"); opts.reqopt("u", "username", "Username to sign in with", "USERNAME"); opts.optopt("p", "password", "Password (optional)", "PASSWORD"); opts.reqopt("c", "cache", "Path to a directory where files will be cached.", "CACHE"); opts.reqopt("n", "name", "Device name", "NAME"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m }, Err(f) => { print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts)); return; } }; let mut appkey_file = File::open( Path::new(&*matches.opt_str("a").unwrap()) ).expect("Could not open app key."); let username = matches.opt_str("u").unwrap(); let cache_location = matches.opt_str("c").unwrap(); let name = matches.opt_str("n").unwrap(); let password = matches.opt_str("p").unwrap_or_else(|| { print!("Password: "); stdout().flush().unwrap(); read_password().unwrap() }); let mut appkey = Vec::new(); appkey_file.read_to_end(&mut appkey).unwrap(); let config = Config { application_key: appkey, user_agent: version_string(), device_id: name.clone(), cache_location: PathBuf::from(cache_location) }; let session = Session::new(config); session.login(username.clone(), password); session.poll(); let _session = session.clone(); thread::spawn(move || { loop { _session.poll(); } }); let player = Player::new(&session); let mut spirc_manager = SpircManager::new(&session, player, name); spirc_manager.run(); }
main
identifier_name
main.rs
extern crate getopts; extern crate librespot; extern crate rpassword; use std::clone::Clone; use std::fs::File; use std::io::{stdout, Read, Write}; use std::path::Path; use std::thread; use std::path::PathBuf; use getopts::Options; use rpassword::read_password; use librespot::session::{Config, Session}; use librespot::util::version::version_string; use librespot::player::Player; use librespot::spirc::SpircManager; fn usage(program: &str, opts: &Options) -> String { let brief = format!("Usage: {} [options]", program); format!("{}", opts.usage(&brief)) } fn main() { let args: Vec<String> = std::env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY"); opts.reqopt("u", "username", "Username to sign in with", "USERNAME"); opts.optopt("p", "password", "Password (optional)", "PASSWORD"); opts.reqopt("c", "cache", "Path to a directory where files will be cached.", "CACHE"); opts.reqopt("n", "name", "Device name", "NAME"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m }, Err(f) =>
}; let mut appkey_file = File::open( Path::new(&*matches.opt_str("a").unwrap()) ).expect("Could not open app key."); let username = matches.opt_str("u").unwrap(); let cache_location = matches.opt_str("c").unwrap(); let name = matches.opt_str("n").unwrap(); let password = matches.opt_str("p").unwrap_or_else(|| { print!("Password: "); stdout().flush().unwrap(); read_password().unwrap() }); let mut appkey = Vec::new(); appkey_file.read_to_end(&mut appkey).unwrap(); let config = Config { application_key: appkey, user_agent: version_string(), device_id: name.clone(), cache_location: PathBuf::from(cache_location) }; let session = Session::new(config); session.login(username.clone(), password); session.poll(); let _session = session.clone(); thread::spawn(move || { loop { _session.poll(); } }); let player = Player::new(&session); let mut spirc_manager = SpircManager::new(&session, player, name); spirc_manager.run(); }
{ print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts)); return; }
conditional_block
main.rs
extern crate getopts; extern crate librespot; extern crate rpassword; use std::clone::Clone; use std::fs::File; use std::io::{stdout, Read, Write}; use std::path::Path; use std::thread; use std::path::PathBuf; use getopts::Options; use rpassword::read_password; use librespot::session::{Config, Session}; use librespot::util::version::version_string; use librespot::player::Player; use librespot::spirc::SpircManager; fn usage(program: &str, opts: &Options) -> String { let brief = format!("Usage: {} [options]", program); format!("{}", opts.usage(&brief)) } fn main() { let args: Vec<String> = std::env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY"); opts.reqopt("u", "username", "Username to sign in with", "USERNAME"); opts.optopt("p", "password", "Password (optional)", "PASSWORD"); opts.reqopt("c", "cache", "Path to a directory where files will be cached.", "CACHE"); opts.reqopt("n", "name", "Device name", "NAME"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m }, Err(f) => { print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts)); return; } }; let mut appkey_file = File::open( Path::new(&*matches.opt_str("a").unwrap()) ).expect("Could not open app key."); let username = matches.opt_str("u").unwrap(); let cache_location = matches.opt_str("c").unwrap(); let name = matches.opt_str("n").unwrap(); let password = matches.opt_str("p").unwrap_or_else(|| { print!("Password: "); stdout().flush().unwrap(); read_password().unwrap() }); let mut appkey = Vec::new(); appkey_file.read_to_end(&mut appkey).unwrap(); let config = Config { application_key: appkey, user_agent: version_string(), device_id: name.clone(), cache_location: PathBuf::from(cache_location) }; let session = Session::new(config); session.login(username.clone(), password); session.poll(); let _session = session.clone(); thread::spawn(move || { loop { _session.poll(); }
let mut spirc_manager = SpircManager::new(&session, player, name); spirc_manager.run(); }
}); let player = Player::new(&session);
random_line_split
main.rs
extern crate getopts; extern crate librespot; extern crate rpassword; use std::clone::Clone; use std::fs::File; use std::io::{stdout, Read, Write}; use std::path::Path; use std::thread; use std::path::PathBuf; use getopts::Options; use rpassword::read_password; use librespot::session::{Config, Session}; use librespot::util::version::version_string; use librespot::player::Player; use librespot::spirc::SpircManager; fn usage(program: &str, opts: &Options) -> String
fn main() { let args: Vec<String> = std::env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.reqopt("a", "appkey", "Path to a spotify appkey", "APPKEY"); opts.reqopt("u", "username", "Username to sign in with", "USERNAME"); opts.optopt("p", "password", "Password (optional)", "PASSWORD"); opts.reqopt("c", "cache", "Path to a directory where files will be cached.", "CACHE"); opts.reqopt("n", "name", "Device name", "NAME"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m }, Err(f) => { print!("Error: {}\n{}", f.to_string(), usage(&*program, &opts)); return; } }; let mut appkey_file = File::open( Path::new(&*matches.opt_str("a").unwrap()) ).expect("Could not open app key."); let username = matches.opt_str("u").unwrap(); let cache_location = matches.opt_str("c").unwrap(); let name = matches.opt_str("n").unwrap(); let password = matches.opt_str("p").unwrap_or_else(|| { print!("Password: "); stdout().flush().unwrap(); read_password().unwrap() }); let mut appkey = Vec::new(); appkey_file.read_to_end(&mut appkey).unwrap(); let config = Config { application_key: appkey, user_agent: version_string(), device_id: name.clone(), cache_location: PathBuf::from(cache_location) }; let session = Session::new(config); session.login(username.clone(), password); session.poll(); let _session = session.clone(); thread::spawn(move || { loop { _session.poll(); } }); let player = Player::new(&session); let mut spirc_manager = SpircManager::new(&session, player, name); spirc_manager.run(); }
{ let brief = format!("Usage: {} [options]", program); format!("{}", opts.usage(&brief)) }
identifier_body
sys.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::ffi::c_void; use std::fmt::{self, Debug}; use std::marker::PhantomData; use std::slice; use libc::iovec; /// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with /// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical /// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the /// guest, so another mutable borrow would violate Rust assumptions about references.) #[derive(Copy, Clone)] #[repr(transparent)] pub struct IoBufMut<'a> { iov: iovec, phantom: PhantomData<&'a mut [u8]>, } impl<'a> IoBufMut<'a> { pub fn new(buf: &mut [u8]) -> IoBufMut<'a> { // Safe because buf's memory is of the supplied length, and // guaranteed to exist for the lifetime of the returned value. unsafe { Self::from_raw_parts(buf.as_mut_ptr(), buf.len()) } } /// Creates a `IoBufMut` from a pointer and a length. /// /// # Safety /// /// In order to use this method safely, `addr` must be valid for reads and writes of `len` bytes /// and should live for the entire duration of lifetime `'a`. pub unsafe fn from_raw_parts(addr: *mut u8, len: usize) -> IoBufMut<'a> { IoBufMut { iov: iovec { iov_base: addr as *mut c_void, iov_len: len, }, phantom: PhantomData, } } /// Advance the internal position of the buffer. /// /// Panics if `count > self.len()`. pub fn advance(&mut self, count: usize) { assert!(count <= self.len()); self.iov.iov_len -= count; // Safe because we've checked that `count <= self.len()` so both the starting and resulting // pointer are within the bounds of the allocation. self.iov.iov_base = unsafe { self.iov.iov_base.add(count) }; } /// Shorten the length of the buffer. /// /// Has no effect if `len > self.len()`. pub fn truncate(&mut self, len: usize) { if len < self.len() { self.iov.iov_len = len; } } #[inline] pub fn len(&self) -> usize { self.iov.iov_len as usize } #[inline] pub fn is_empty(&self) -> bool { self.iov.iov_len == 0 } /// Gets a const pointer to this slice's memory. #[inline] pub fn as_ptr(&self) -> *const u8 { self.iov.iov_base as *const u8 } /// Gets a mutable pointer to this slice's memory. #[inline] pub fn as_mut_ptr(&self) -> *mut u8 { self.iov.iov_base as *mut u8 } /// Converts a slice of `IoBufMut`s into a slice of `iovec`s. #[allow(clippy::wrong_self_convention)] #[inline] pub fn as_iobufs<'slice>(iovs: &'slice [IoBufMut<'_>]) -> &'slice [iovec]
} impl<'a> AsRef<libc::iovec> for IoBufMut<'a> { fn as_ref(&self) -> &libc::iovec { &self.iov } } impl<'a> AsMut<libc::iovec> for IoBufMut<'a> { fn as_mut(&mut self) -> &mut libc::iovec { &mut self.iov } } // It's safe to implement Send + Sync for this type for the same reason that `std::io::IoBufMut` // is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send // + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the // pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342. unsafe impl<'a> Send for IoBufMut<'a> {} unsafe impl<'a> Sync for IoBufMut<'a> {} struct DebugIovec(iovec); impl Debug for DebugIovec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("iovec") .field("iov_base", &self.0.iov_base) .field("iov_len", &self.0.iov_len) .finish() } } impl<'a> Debug for IoBufMut<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("IoBufMut") .field("iov", &DebugIovec(self.iov)) .field("phantom", &self.phantom) .finish() } }
{ // Safe because `IoBufMut` is ABI-compatible with `iovec`. unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) } }
identifier_body
sys.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::ffi::c_void; use std::fmt::{self, Debug}; use std::marker::PhantomData; use std::slice; use libc::iovec; /// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with /// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical /// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the /// guest, so another mutable borrow would violate Rust assumptions about references.) #[derive(Copy, Clone)] #[repr(transparent)] pub struct IoBufMut<'a> { iov: iovec, phantom: PhantomData<&'a mut [u8]>, } impl<'a> IoBufMut<'a> { pub fn new(buf: &mut [u8]) -> IoBufMut<'a> { // Safe because buf's memory is of the supplied length, and // guaranteed to exist for the lifetime of the returned value. unsafe { Self::from_raw_parts(buf.as_mut_ptr(), buf.len()) } } /// Creates a `IoBufMut` from a pointer and a length. /// /// # Safety /// /// In order to use this method safely, `addr` must be valid for reads and writes of `len` bytes /// and should live for the entire duration of lifetime `'a`. pub unsafe fn from_raw_parts(addr: *mut u8, len: usize) -> IoBufMut<'a> { IoBufMut { iov: iovec { iov_base: addr as *mut c_void, iov_len: len, }, phantom: PhantomData, } } /// Advance the internal position of the buffer. /// /// Panics if `count > self.len()`. pub fn advance(&mut self, count: usize) { assert!(count <= self.len()); self.iov.iov_len -= count; // Safe because we've checked that `count <= self.len()` so both the starting and resulting // pointer are within the bounds of the allocation. self.iov.iov_base = unsafe { self.iov.iov_base.add(count) }; } /// Shorten the length of the buffer. /// /// Has no effect if `len > self.len()`. pub fn truncate(&mut self, len: usize) { if len < self.len()
} #[inline] pub fn len(&self) -> usize { self.iov.iov_len as usize } #[inline] pub fn is_empty(&self) -> bool { self.iov.iov_len == 0 } /// Gets a const pointer to this slice's memory. #[inline] pub fn as_ptr(&self) -> *const u8 { self.iov.iov_base as *const u8 } /// Gets a mutable pointer to this slice's memory. #[inline] pub fn as_mut_ptr(&self) -> *mut u8 { self.iov.iov_base as *mut u8 } /// Converts a slice of `IoBufMut`s into a slice of `iovec`s. #[allow(clippy::wrong_self_convention)] #[inline] pub fn as_iobufs<'slice>(iovs: &'slice [IoBufMut<'_>]) -> &'slice [iovec] { // Safe because `IoBufMut` is ABI-compatible with `iovec`. unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) } } } impl<'a> AsRef<libc::iovec> for IoBufMut<'a> { fn as_ref(&self) -> &libc::iovec { &self.iov } } impl<'a> AsMut<libc::iovec> for IoBufMut<'a> { fn as_mut(&mut self) -> &mut libc::iovec { &mut self.iov } } // It's safe to implement Send + Sync for this type for the same reason that `std::io::IoBufMut` // is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send // + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the // pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342. unsafe impl<'a> Send for IoBufMut<'a> {} unsafe impl<'a> Sync for IoBufMut<'a> {} struct DebugIovec(iovec); impl Debug for DebugIovec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("iovec") .field("iov_base", &self.0.iov_base) .field("iov_len", &self.0.iov_len) .finish() } } impl<'a> Debug for IoBufMut<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("IoBufMut") .field("iov", &DebugIovec(self.iov)) .field("phantom", &self.phantom) .finish() } }
{ self.iov.iov_len = len; }
conditional_block
sys.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::ffi::c_void; use std::fmt::{self, Debug}; use std::marker::PhantomData; use std::slice; use libc::iovec; /// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with /// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical /// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the /// guest, so another mutable borrow would violate Rust assumptions about references.) #[derive(Copy, Clone)] #[repr(transparent)] pub struct IoBufMut<'a> { iov: iovec, phantom: PhantomData<&'a mut [u8]>, } impl<'a> IoBufMut<'a> { pub fn new(buf: &mut [u8]) -> IoBufMut<'a> { // Safe because buf's memory is of the supplied length, and // guaranteed to exist for the lifetime of the returned value. unsafe { Self::from_raw_parts(buf.as_mut_ptr(), buf.len()) } } /// Creates a `IoBufMut` from a pointer and a length. /// /// # Safety /// /// In order to use this method safely, `addr` must be valid for reads and writes of `len` bytes /// and should live for the entire duration of lifetime `'a`. pub unsafe fn from_raw_parts(addr: *mut u8, len: usize) -> IoBufMut<'a> { IoBufMut { iov: iovec { iov_base: addr as *mut c_void, iov_len: len, },
} /// Advance the internal position of the buffer. /// /// Panics if `count > self.len()`. pub fn advance(&mut self, count: usize) { assert!(count <= self.len()); self.iov.iov_len -= count; // Safe because we've checked that `count <= self.len()` so both the starting and resulting // pointer are within the bounds of the allocation. self.iov.iov_base = unsafe { self.iov.iov_base.add(count) }; } /// Shorten the length of the buffer. /// /// Has no effect if `len > self.len()`. pub fn truncate(&mut self, len: usize) { if len < self.len() { self.iov.iov_len = len; } } #[inline] pub fn len(&self) -> usize { self.iov.iov_len as usize } #[inline] pub fn is_empty(&self) -> bool { self.iov.iov_len == 0 } /// Gets a const pointer to this slice's memory. #[inline] pub fn as_ptr(&self) -> *const u8 { self.iov.iov_base as *const u8 } /// Gets a mutable pointer to this slice's memory. #[inline] pub fn as_mut_ptr(&self) -> *mut u8 { self.iov.iov_base as *mut u8 } /// Converts a slice of `IoBufMut`s into a slice of `iovec`s. #[allow(clippy::wrong_self_convention)] #[inline] pub fn as_iobufs<'slice>(iovs: &'slice [IoBufMut<'_>]) -> &'slice [iovec] { // Safe because `IoBufMut` is ABI-compatible with `iovec`. unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) } } } impl<'a> AsRef<libc::iovec> for IoBufMut<'a> { fn as_ref(&self) -> &libc::iovec { &self.iov } } impl<'a> AsMut<libc::iovec> for IoBufMut<'a> { fn as_mut(&mut self) -> &mut libc::iovec { &mut self.iov } } // It's safe to implement Send + Sync for this type for the same reason that `std::io::IoBufMut` // is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send // + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the // pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342. unsafe impl<'a> Send for IoBufMut<'a> {} unsafe impl<'a> Sync for IoBufMut<'a> {} struct DebugIovec(iovec); impl Debug for DebugIovec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("iovec") .field("iov_base", &self.0.iov_base) .field("iov_len", &self.0.iov_len) .finish() } } impl<'a> Debug for IoBufMut<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("IoBufMut") .field("iov", &DebugIovec(self.iov)) .field("phantom", &self.phantom) .finish() } }
phantom: PhantomData, }
random_line_split
sys.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::ffi::c_void; use std::fmt::{self, Debug}; use std::marker::PhantomData; use std::slice; use libc::iovec; /// This type is essentialy `std::io::IoBufMut`, and guaranteed to be ABI-compatible with /// `libc::iovec`; however, it does NOT automatically deref to `&mut [u8]`, which is critical /// because it can point to guest memory. (Guest memory is implicitly mutably borrowed by the /// guest, so another mutable borrow would violate Rust assumptions about references.) #[derive(Copy, Clone)] #[repr(transparent)] pub struct
<'a> { iov: iovec, phantom: PhantomData<&'a mut [u8]>, } impl<'a> IoBufMut<'a> { pub fn new(buf: &mut [u8]) -> IoBufMut<'a> { // Safe because buf's memory is of the supplied length, and // guaranteed to exist for the lifetime of the returned value. unsafe { Self::from_raw_parts(buf.as_mut_ptr(), buf.len()) } } /// Creates a `IoBufMut` from a pointer and a length. /// /// # Safety /// /// In order to use this method safely, `addr` must be valid for reads and writes of `len` bytes /// and should live for the entire duration of lifetime `'a`. pub unsafe fn from_raw_parts(addr: *mut u8, len: usize) -> IoBufMut<'a> { IoBufMut { iov: iovec { iov_base: addr as *mut c_void, iov_len: len, }, phantom: PhantomData, } } /// Advance the internal position of the buffer. /// /// Panics if `count > self.len()`. pub fn advance(&mut self, count: usize) { assert!(count <= self.len()); self.iov.iov_len -= count; // Safe because we've checked that `count <= self.len()` so both the starting and resulting // pointer are within the bounds of the allocation. self.iov.iov_base = unsafe { self.iov.iov_base.add(count) }; } /// Shorten the length of the buffer. /// /// Has no effect if `len > self.len()`. pub fn truncate(&mut self, len: usize) { if len < self.len() { self.iov.iov_len = len; } } #[inline] pub fn len(&self) -> usize { self.iov.iov_len as usize } #[inline] pub fn is_empty(&self) -> bool { self.iov.iov_len == 0 } /// Gets a const pointer to this slice's memory. #[inline] pub fn as_ptr(&self) -> *const u8 { self.iov.iov_base as *const u8 } /// Gets a mutable pointer to this slice's memory. #[inline] pub fn as_mut_ptr(&self) -> *mut u8 { self.iov.iov_base as *mut u8 } /// Converts a slice of `IoBufMut`s into a slice of `iovec`s. #[allow(clippy::wrong_self_convention)] #[inline] pub fn as_iobufs<'slice>(iovs: &'slice [IoBufMut<'_>]) -> &'slice [iovec] { // Safe because `IoBufMut` is ABI-compatible with `iovec`. unsafe { slice::from_raw_parts(iovs.as_ptr() as *const libc::iovec, iovs.len()) } } } impl<'a> AsRef<libc::iovec> for IoBufMut<'a> { fn as_ref(&self) -> &libc::iovec { &self.iov } } impl<'a> AsMut<libc::iovec> for IoBufMut<'a> { fn as_mut(&mut self) -> &mut libc::iovec { &mut self.iov } } // It's safe to implement Send + Sync for this type for the same reason that `std::io::IoBufMut` // is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send // + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the // pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342. unsafe impl<'a> Send for IoBufMut<'a> {} unsafe impl<'a> Sync for IoBufMut<'a> {} struct DebugIovec(iovec); impl Debug for DebugIovec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("iovec") .field("iov_base", &self.0.iov_base) .field("iov_len", &self.0.iov_len) .finish() } } impl<'a> Debug for IoBufMut<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("IoBufMut") .field("iov", &DebugIovec(self.iov)) .field("phantom", &self.phantom) .finish() } }
IoBufMut
identifier_name
person.rs
use super::Point; use super::terrain::Terrain; use std::fmt; // formatting for console display use std::cmp; use std::cmp::Ordering::Equal; // ****** // PERSON // ****** #[derive(Debug)] pub struct Person { pub id: usize, pub position : Point, pub has_escaped : bool, } impl Person { pub fn new_placed(terrain : &mut Terrain, id: usize, position : Point) -> Person { terrain.set_pt_val(&position, id as isize); Person {id, position, has_escaped :false} } pub fn new_unplaced(id: usize) -> Person { Person { id, position: Point { x: 0, y: 0 }, has_escaped : true } } pub fn new(id : usize, position : Point) -> Person { Person { id, position, has_escaped : false } } // Select the best available move that reduces most the distance to the azimuth point // or stay where you are. pub fn choose_best_move (&self, possible_moves: &Vec<Point>) -> Point { let azimuth: Point = Point{x: -2, y: 130}; #[derive(Debug)] // to allow println for debugging purposes. let mut moves_and_dist: Vec<(&Point, f32)> = possible_moves.iter() .map(|x| (x, x.square_distance_to( &azimuth))) .collect(); moves_and_dist.sort_by( |x, y| { x.1.partial_cmp((&y.1)) .unwrap_or(Equal) } ); debug!("debug sort :{:?}",moves_and_dist); // debug match moves_and_dist.first() { Some(&(ref point, _)) => Point{x:point.x, y:point.y}, None => Point{x: self.position.x, y: self.position.y}, // todo : stay where you are for now... } } pub fn place_on_terrain(&mut self, terrain: &mut Terrain){ terrain.set_pt_val(&self.position, self.id as isize); self.has_escaped = false; } pub fn remove_from_terrain(&mut self, terrain: &mut Terrain){ terrain.set_pt_val(&self.position, 0 as isize); self.has_escaped = true; } pub fn move_to(&mut self, terrain: &mut Terrain, new_point: &Point) { if self.has_escaped == true { } else if terrain.get_exit_points().contains(new_point)
else { terrain.move_src_to_dst(&self.position, new_point); self.position.x = new_point.x; // change internal position (copy of x and y) self.position.y = new_point.y; } } /// This function encapulates a complete move for a person : /// from looking around to actually moving to another place /// (and mutating the Person and the Terrain). pub fn look_and_move(&mut self, terrain : &mut Terrain) { //println!("Dealing with : {}", self); // look around let moves = terrain.list_possible_moves(&self.position); // select the best point (hope that no-one took it while thinking) //println!("Possible moves : {:?}", moves); #[derive(Debug)] let good_point = self.choose_best_move(&moves); // move to the best point if good_point != self.position { trace!("Moving to : {}", good_point); self.move_to(terrain, &good_point); } else { trace!("I, {} am staying here : {}", self.id, good_point); } } } impl cmp::PartialEq for Person { fn eq(&self, other: &Person) -> bool { (self.id == other.id) } fn ne(&self, other: &Person) -> bool { !self.eq(other) } } impl fmt::Display for Person { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position) } }
{ terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts trace!("I escaped : {}", self.id); self.has_escaped = true; self.remove_from_terrain(terrain); }
conditional_block
person.rs
use super::Point; use super::terrain::Terrain; use std::fmt; // formatting for console display use std::cmp; use std::cmp::Ordering::Equal; // ****** // PERSON // ****** #[derive(Debug)] pub struct Person { pub id: usize, pub position : Point, pub has_escaped : bool, } impl Person { pub fn new_placed(terrain : &mut Terrain, id: usize, position : Point) -> Person { terrain.set_pt_val(&position, id as isize); Person {id, position, has_escaped :false} } pub fn new_unplaced(id: usize) -> Person { Person { id, position: Point { x: 0, y: 0 }, has_escaped : true } } pub fn new(id : usize, position : Point) -> Person { Person { id, position, has_escaped : false } } // Select the best available move that reduces most the distance to the azimuth point // or stay where you are. pub fn choose_best_move (&self, possible_moves: &Vec<Point>) -> Point { let azimuth: Point = Point{x: -2, y: 130}; #[derive(Debug)] // to allow println for debugging purposes. let mut moves_and_dist: Vec<(&Point, f32)> = possible_moves.iter() .map(|x| (x, x.square_distance_to( &azimuth))) .collect(); moves_and_dist.sort_by( |x, y| { x.1.partial_cmp((&y.1)) .unwrap_or(Equal) } ); debug!("debug sort :{:?}",moves_and_dist); // debug match moves_and_dist.first() { Some(&(ref point, _)) => Point{x:point.x, y:point.y}, None => Point{x: self.position.x, y: self.position.y}, // todo : stay where you are for now... } } pub fn place_on_terrain(&mut self, terrain: &mut Terrain){ terrain.set_pt_val(&self.position, self.id as isize); self.has_escaped = false; } pub fn remove_from_terrain(&mut self, terrain: &mut Terrain){ terrain.set_pt_val(&self.position, 0 as isize); self.has_escaped = true; } pub fn move_to(&mut self, terrain: &mut Terrain, new_point: &Point)
/// This function encapulates a complete move for a person : /// from looking around to actually moving to another place /// (and mutating the Person and the Terrain). pub fn look_and_move(&mut self, terrain : &mut Terrain) { //println!("Dealing with : {}", self); // look around let moves = terrain.list_possible_moves(&self.position); // select the best point (hope that no-one took it while thinking) //println!("Possible moves : {:?}", moves); #[derive(Debug)] let good_point = self.choose_best_move(&moves); // move to the best point if good_point != self.position { trace!("Moving to : {}", good_point); self.move_to(terrain, &good_point); } else { trace!("I, {} am staying here : {}", self.id, good_point); } } } impl cmp::PartialEq for Person { fn eq(&self, other: &Person) -> bool { (self.id == other.id) } fn ne(&self, other: &Person) -> bool { !self.eq(other) } } impl fmt::Display for Person { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position) } }
{ if self.has_escaped == true { } else if terrain.get_exit_points().contains(new_point) { terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts trace!("I escaped : {}", self.id); self.has_escaped = true; self.remove_from_terrain(terrain); } else { terrain.move_src_to_dst(&self.position, new_point); self.position.x = new_point.x; // change internal position (copy of x and y) self.position.y = new_point.y; } }
identifier_body
person.rs
use super::Point; use super::terrain::Terrain; use std::fmt; // formatting for console display use std::cmp; use std::cmp::Ordering::Equal; // ****** // PERSON // ****** #[derive(Debug)] pub struct Person { pub id: usize, pub position : Point, pub has_escaped : bool, } impl Person { pub fn new_placed(terrain : &mut Terrain, id: usize, position : Point) -> Person { terrain.set_pt_val(&position, id as isize); Person {id, position, has_escaped :false} } pub fn new_unplaced(id: usize) -> Person { Person { id, position: Point { x: 0, y: 0 }, has_escaped : true } } pub fn new(id : usize, position : Point) -> Person { Person { id, position, has_escaped : false } } // Select the best available move that reduces most the distance to the azimuth point // or stay where you are. pub fn choose_best_move (&self, possible_moves: &Vec<Point>) -> Point { let azimuth: Point = Point{x: -2, y: 130}; #[derive(Debug)] // to allow println for debugging purposes. let mut moves_and_dist: Vec<(&Point, f32)> = possible_moves.iter() .map(|x| (x, x.square_distance_to( &azimuth))) .collect(); moves_and_dist.sort_by( |x, y| { x.1.partial_cmp((&y.1)) .unwrap_or(Equal) } ); debug!("debug sort :{:?}",moves_and_dist); // debug match moves_and_dist.first() { Some(&(ref point, _)) => Point{x:point.x, y:point.y}, None => Point{x: self.position.x, y: self.position.y}, // todo : stay where you are for now... } } pub fn place_on_terrain(&mut self, terrain: &mut Terrain){ terrain.set_pt_val(&self.position, self.id as isize); self.has_escaped = false; } pub fn remove_from_terrain(&mut self, terrain: &mut Terrain){ terrain.set_pt_val(&self.position, 0 as isize); self.has_escaped = true; } pub fn move_to(&mut self, terrain: &mut Terrain, new_point: &Point) { if self.has_escaped == true { } else if terrain.get_exit_points().contains(new_point) { terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts trace!("I escaped : {}", self.id); self.has_escaped = true; self.remove_from_terrain(terrain); } else { terrain.move_src_to_dst(&self.position, new_point); self.position.x = new_point.x; // change internal position (copy of x and y) self.position.y = new_point.y; } } /// This function encapulates a complete move for a person : /// from looking around to actually moving to another place /// (and mutating the Person and the Terrain). pub fn look_and_move(&mut self, terrain : &mut Terrain) { //println!("Dealing with : {}", self); // look around let moves = terrain.list_possible_moves(&self.position); // select the best point (hope that no-one took it while thinking) //println!("Possible moves : {:?}", moves); #[derive(Debug)] let good_point = self.choose_best_move(&moves); // move to the best point if good_point != self.position { trace!("Moving to : {}", good_point); self.move_to(terrain, &good_point); } else { trace!("I, {} am staying here : {}", self.id, good_point); } } } impl cmp::PartialEq for Person { fn eq(&self, other: &Person) -> bool { (self.id == other.id) } fn ne(&self, other: &Person) -> bool { !self.eq(other) } }
impl fmt::Display for Person { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position) } }
random_line_split
person.rs
use super::Point; use super::terrain::Terrain; use std::fmt; // formatting for console display use std::cmp; use std::cmp::Ordering::Equal; // ****** // PERSON // ****** #[derive(Debug)] pub struct Person { pub id: usize, pub position : Point, pub has_escaped : bool, } impl Person { pub fn new_placed(terrain : &mut Terrain, id: usize, position : Point) -> Person { terrain.set_pt_val(&position, id as isize); Person {id, position, has_escaped :false} } pub fn new_unplaced(id: usize) -> Person { Person { id, position: Point { x: 0, y: 0 }, has_escaped : true } } pub fn new(id : usize, position : Point) -> Person { Person { id, position, has_escaped : false } } // Select the best available move that reduces most the distance to the azimuth point // or stay where you are. pub fn choose_best_move (&self, possible_moves: &Vec<Point>) -> Point { let azimuth: Point = Point{x: -2, y: 130}; #[derive(Debug)] // to allow println for debugging purposes. let mut moves_and_dist: Vec<(&Point, f32)> = possible_moves.iter() .map(|x| (x, x.square_distance_to( &azimuth))) .collect(); moves_and_dist.sort_by( |x, y| { x.1.partial_cmp((&y.1)) .unwrap_or(Equal) } ); debug!("debug sort :{:?}",moves_and_dist); // debug match moves_and_dist.first() { Some(&(ref point, _)) => Point{x:point.x, y:point.y}, None => Point{x: self.position.x, y: self.position.y}, // todo : stay where you are for now... } } pub fn place_on_terrain(&mut self, terrain: &mut Terrain){ terrain.set_pt_val(&self.position, self.id as isize); self.has_escaped = false; } pub fn remove_from_terrain(&mut self, terrain: &mut Terrain){ terrain.set_pt_val(&self.position, 0 as isize); self.has_escaped = true; } pub fn move_to(&mut self, terrain: &mut Terrain, new_point: &Point) { if self.has_escaped == true { } else if terrain.get_exit_points().contains(new_point) { terrain.move_src_to_dst(&self.position, new_point); // should just increase exit counts trace!("I escaped : {}", self.id); self.has_escaped = true; self.remove_from_terrain(terrain); } else { terrain.move_src_to_dst(&self.position, new_point); self.position.x = new_point.x; // change internal position (copy of x and y) self.position.y = new_point.y; } } /// This function encapulates a complete move for a person : /// from looking around to actually moving to another place /// (and mutating the Person and the Terrain). pub fn look_and_move(&mut self, terrain : &mut Terrain) { //println!("Dealing with : {}", self); // look around let moves = terrain.list_possible_moves(&self.position); // select the best point (hope that no-one took it while thinking) //println!("Possible moves : {:?}", moves); #[derive(Debug)] let good_point = self.choose_best_move(&moves); // move to the best point if good_point != self.position { trace!("Moving to : {}", good_point); self.move_to(terrain, &good_point); } else { trace!("I, {} am staying here : {}", self.id, good_point); } } } impl cmp::PartialEq for Person { fn eq(&self, other: &Person) -> bool { (self.id == other.id) } fn ne(&self, other: &Person) -> bool { !self.eq(other) } } impl fmt::Display for Person { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Person : {{ id : {}, position : {} }}", self.id, self.position) } }
fmt
identifier_name
rich-textarea-field-response.js
import React from "react"; import PropTypes from "prop-types"; import styled from "@emotion/styled"; import { insertEmbeddedImages } from "../../../utils/embedded-images"; const RichTextareaFieldResponseWrapper = styled("div")(props => ({ // TODO: fluid video lineHeight: "1.3rem", "& img": { maxWidth: "100%", margin: "16px 0 0 0", }, "& ul": { marginTop: 0, marginBottom: "16px", fontWeight: "normal", }, "& p": { fontFamily: props.theme.text.bodyFontFamily, marginTop: 0, marginBottom: "16px", fontWeight: "normal", }, "& li": { fontFamily: props.theme.text.bodyFontFamily, fontWeight: "normal", }, "& a": { textDectoration: "none", fontWeight: "normal", }, "& h1,h2,h3,h4,h5,h6": { fontFamily: props.theme.text.titleFontFamily, margin: "16px 0 8px 0", }, })); const RichTextareaFieldResponse = props => { return ( <RichTextareaFieldResponseWrapper> <div className="rich-textarea-field-response" dangerouslySetInnerHTML={{ __html: insertEmbeddedImages(props.value, props.attachments), }} /> </RichTextareaFieldResponseWrapper> );
RichTextareaFieldResponse.propTypes = { attachments: PropTypes.array, value: PropTypes.string.isRequired, }; export default RichTextareaFieldResponse;
};
random_line_split
backtrace.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 https://mozilla.org/MPL/2.0/. */ //! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate. //! //! Seems to fix some deadlocks: https://github.com/servo/servo/issues/24881 //! //! FIXME: if/when a future version of the `backtrace` crate has //! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead. use std::fmt::{self, Write}; use backtrace::{BytesOrWideString, PrintFmt}; #[inline(never)] pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> { write!(w, "{:?}", Print { print_fn_address: print as usize, }) } struct Print { print_fn_address: usize, } impl fmt::Debug for Print { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Safety: we’re in a signal handler that is about to call `libc::_exit`. // Potential data races from using `*_unsynchronized` functions are perhaps // less bad than potential deadlocks? unsafe { let mut print_fn_frame = 0; let mut frame_count = 0; backtrace::trace_unsynchronized(|frame| { let found = frame.symbol_address() as usize == self.print_fn_address; if found { print_fn_frame = frame_count; } frame_count += 1; !found }); let mode = PrintFmt::Short; let mut p = print_path; let mut f = backtrace::BacktraceFmt::new(fmt, mode, &mut p); f.add_context()?; let mut result = Ok(()); let mut frame_count = 0; backtrace::trace_unsynchronized(|frame| { let skip = frame_count < print_fn_frame; frame_count += 1; if skip { return true } let mut frame_fmt = f.frame(); let mut any_symbol = false; backtrace::resolve_frame_unsynchronized(frame, |symbol| { any_symbol = true; if let Err(e) = frame_fmt.symbol(frame, symbol) { result = Err(e) } }); if !any_symbol { if let Err(e) = frame_fmt.print_raw(frame.ip(), None, None, None) { result = Err(e) } } result.is_ok() }); result?; f.finish() } } }
loop { match std::str::from_utf8(bytes) { Ok(s) => { fmt.write_str(s)?; break; } Err(err) => { fmt.write_char(std::char::REPLACEMENT_CHARACTER)?; match err.error_len() { Some(len) => bytes = &bytes[err.valid_up_to() + len..], None => break, } } } } } BytesOrWideString::Wide(wide) => { for c in std::char::decode_utf16(wide.iter().cloned()) { fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))? } } } Ok(()) }
fn print_path(fmt: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result { match path { BytesOrWideString::Bytes(mut bytes) => {
random_line_split
backtrace.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 https://mozilla.org/MPL/2.0/. */ //! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate. //! //! Seems to fix some deadlocks: https://github.com/servo/servo/issues/24881 //! //! FIXME: if/when a future version of the `backtrace` crate has //! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead. use std::fmt::{self, Write}; use backtrace::{BytesOrWideString, PrintFmt}; #[inline(never)] pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> { write!(w, "{:?}", Print { print_fn_address: print as usize, }) } struct Print { print_fn_address: usize, } impl fmt::Debug for Print { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Safety: we’re in a signal handler that is about to call `libc::_exit`. // Potential data races from using `*_unsynchronized` functions are perhaps // less bad than potential deadlocks? unsafe { let mut print_fn_frame = 0; let mut frame_count = 0; backtrace::trace_unsynchronized(|frame| { let found = frame.symbol_address() as usize == self.print_fn_address; if found { print_fn_frame = frame_count; } frame_count += 1; !found }); let mode = PrintFmt::Short; let mut p = print_path; let mut f = backtrace::BacktraceFmt::new(fmt, mode, &mut p); f.add_context()?; let mut result = Ok(()); let mut frame_count = 0; backtrace::trace_unsynchronized(|frame| { let skip = frame_count < print_fn_frame; frame_count += 1; if skip { return true } let mut frame_fmt = f.frame(); let mut any_symbol = false; backtrace::resolve_frame_unsynchronized(frame, |symbol| { any_symbol = true; if let Err(e) = frame_fmt.symbol(frame, symbol) { result = Err(e) } }); if !any_symbol { if let Err(e) = frame_fmt.print_raw(frame.ip(), None, None, None) { result = Err(e) } } result.is_ok() }); result?; f.finish() } } } fn print_path(fmt: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))? } } } Ok(()) }
match path { BytesOrWideString::Bytes(mut bytes) => { loop { match std::str::from_utf8(bytes) { Ok(s) => { fmt.write_str(s)?; break; } Err(err) => { fmt.write_char(std::char::REPLACEMENT_CHARACTER)?; match err.error_len() { Some(len) => bytes = &bytes[err.valid_up_to() + len..], None => break, } } } } } BytesOrWideString::Wide(wide) => { for c in std::char::decode_utf16(wide.iter().cloned()) {
identifier_body
backtrace.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 https://mozilla.org/MPL/2.0/. */ //! Similar to `println!("{:?}", Backtrace::new())`, but doesn’t allocate. //! //! Seems to fix some deadlocks: https://github.com/servo/servo/issues/24881 //! //! FIXME: if/when a future version of the `backtrace` crate has //! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead. use std::fmt::{self, Write}; use backtrace::{BytesOrWideString, PrintFmt}; #[inline(never)] pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> { write!(w, "{:?}", Print { print_fn_address: print as usize, }) } struct Print { print_fn_address: usize, } impl fmt::Debug for Print { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Safety: we’re in a signal handler that is about to call `libc::_exit`. // Potential data races from using `*_unsynchronized` functions are perhaps // less bad than potential deadlocks? unsafe { let mut print_fn_frame = 0; let mut frame_count = 0; backtrace::trace_unsynchronized(|frame| { let found = frame.symbol_address() as usize == self.print_fn_address; if found { print_fn_frame = frame_count; } frame_count += 1; !found }); let mode = PrintFmt::Short; let mut p = print_path; let mut f = backtrace::BacktraceFmt::new(fmt, mode, &mut p); f.add_context()?; let mut result = Ok(()); let mut frame_count = 0; backtrace::trace_unsynchronized(|frame| { let skip = frame_count < print_fn_frame; frame_count += 1; if skip { return true } let mut frame_fmt = f.frame(); let mut any_symbol = false; backtrace::resolve_frame_unsynchronized(frame, |symbol| { any_symbol = true; if let Err(e) = frame_fmt.symbol(frame, symbol) { result = Err(e) } }); if !any_symbol { if let Err(e) = frame_fmt.print_raw(frame.ip(), None, None, None) { result = Err(e) } } result.is_ok() }); result?; f.finish() } } } fn prin
: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result { match path { BytesOrWideString::Bytes(mut bytes) => { loop { match std::str::from_utf8(bytes) { Ok(s) => { fmt.write_str(s)?; break; } Err(err) => { fmt.write_char(std::char::REPLACEMENT_CHARACTER)?; match err.error_len() { Some(len) => bytes = &bytes[err.valid_up_to() + len..], None => break, } } } } } BytesOrWideString::Wide(wide) => { for c in std::char::decode_utf16(wide.iter().cloned()) { fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))? } } } Ok(()) }
t_path(fmt
identifier_name
calc.js
/** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var isNumeric = require('fast-isnumeric'); var calcColorscale = require('../scatter/colorscale_calc'); var arraysToCalcdata = require('../scatter/arrays_to_calcdata'); var calcSelection = require('../scatter/calc_selection'); var calcMarkerSize = require('../scatter/calc').calcMarkerSize; var lookupCarpet = require('../carpet/lookup_carpetid'); module.exports = function calc(gd, trace) { var carpet = trace._carpetTrace = lookupCarpet(gd, trace); if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return; var i; // Transfer this over from carpet before plotting since this is a necessary // condition in order for cartesian to actually plot this trace: trace.xaxis = carpet.xaxis; trace.yaxis = carpet.yaxis; // make the calcdata array var serieslen = trace._length; var cd = new Array(serieslen); var a, b; var needsCull = false; for(i = 0; i < serieslen; i++)
trace._needsCull = needsCull; cd[0].carpet = carpet; cd[0].trace = trace; calcMarkerSize(trace, serieslen); calcColorscale(gd, trace); arraysToCalcdata(cd, trace); calcSelection(cd, trace); return cd; };
{ a = trace.a[i]; b = trace.b[i]; if(isNumeric(a) && isNumeric(b)) { var xy = carpet.ab2xy(+a, +b, true); var visible = carpet.isVisible(+a, +b); if(!visible) needsCull = true; cd[i] = {x: xy[0], y: xy[1], a: a, b: b, vis: visible}; } else cd[i] = {x: false, y: false}; }
conditional_block
calc.js
/** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var isNumeric = require('fast-isnumeric'); var calcColorscale = require('../scatter/colorscale_calc'); var arraysToCalcdata = require('../scatter/arrays_to_calcdata'); var calcSelection = require('../scatter/calc_selection'); var calcMarkerSize = require('../scatter/calc').calcMarkerSize; var lookupCarpet = require('../carpet/lookup_carpetid'); module.exports = function calc(gd, trace) { var carpet = trace._carpetTrace = lookupCarpet(gd, trace); if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return; var i; // Transfer this over from carpet before plotting since this is a necessary // condition in order for cartesian to actually plot this trace: trace.xaxis = carpet.xaxis; trace.yaxis = carpet.yaxis; // make the calcdata array var serieslen = trace._length; var cd = new Array(serieslen); var a, b; var needsCull = false; for(i = 0; i < serieslen; i++) { a = trace.a[i]; b = trace.b[i]; if(isNumeric(a) && isNumeric(b)) { var xy = carpet.ab2xy(+a, +b, true);
} else cd[i] = {x: false, y: false}; } trace._needsCull = needsCull; cd[0].carpet = carpet; cd[0].trace = trace; calcMarkerSize(trace, serieslen); calcColorscale(gd, trace); arraysToCalcdata(cd, trace); calcSelection(cd, trace); return cd; };
var visible = carpet.isVisible(+a, +b); if(!visible) needsCull = true; cd[i] = {x: xy[0], y: xy[1], a: a, b: b, vis: visible};
random_line_split
linkedList.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v18.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedList = (function () { function LinkedList() { this.first = null; this.last = null; } LinkedList.prototype.add = function (item) { var entry = { item: item, next: null }; if (this.last)
else { this.first = entry; } this.last = entry; }; LinkedList.prototype.remove = function () { var result = this.first; if (result) { this.first = result.next; if (!this.first) { this.last = null; } } return result.item; }; LinkedList.prototype.isEmpty = function () { return !this.first; }; return LinkedList; }()); exports.LinkedList = LinkedList; var LinkedListItem = (function () { function LinkedListItem() { } return LinkedListItem; }());
{ this.last.next = entry; }
conditional_block
linkedList.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v18.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedList = (function () { function LinkedList() { this.first = null; this.last = null; } LinkedList.prototype.add = function (item) { var entry = { item: item, next: null }; if (this.last) { this.last.next = entry; } else { this.first = entry; } this.last = entry; }; LinkedList.prototype.remove = function () { var result = this.first; if (result) { this.first = result.next; if (!this.first) {
LinkedList.prototype.isEmpty = function () { return !this.first; }; return LinkedList; }()); exports.LinkedList = LinkedList; var LinkedListItem = (function () { function LinkedListItem() { } return LinkedListItem; }());
this.last = null; } } return result.item; };
random_line_split
linkedList.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v18.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedList = (function () { function LinkedList() { this.first = null; this.last = null; } LinkedList.prototype.add = function (item) { var entry = { item: item, next: null }; if (this.last) { this.last.next = entry; } else { this.first = entry; } this.last = entry; }; LinkedList.prototype.remove = function () { var result = this.first; if (result) { this.first = result.next; if (!this.first) { this.last = null; } } return result.item; }; LinkedList.prototype.isEmpty = function () { return !this.first; }; return LinkedList; }()); exports.LinkedList = LinkedList; var LinkedListItem = (function () { function
() { } return LinkedListItem; }());
LinkedListItem
identifier_name
linkedList.js
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v18.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedList = (function () { function LinkedList() { this.first = null; this.last = null; } LinkedList.prototype.add = function (item) { var entry = { item: item, next: null }; if (this.last) { this.last.next = entry; } else { this.first = entry; } this.last = entry; }; LinkedList.prototype.remove = function () { var result = this.first; if (result) { this.first = result.next; if (!this.first) { this.last = null; } } return result.item; }; LinkedList.prototype.isEmpty = function () { return !this.first; }; return LinkedList; }()); exports.LinkedList = LinkedList; var LinkedListItem = (function () { function LinkedListItem()
return LinkedListItem; }());
{ }
identifier_body
perfect.rs
use super::lookups; use cards::card::{Card}; use super::{HandRank}; use super::utils::{card_to_deck_number}; fn simulate_32bit_precision(u: usize) -> usize { let mask = 0xffffffff; u & mask } // don't use this. pub fn find_fast(something: usize) -> usize { let mut u = simulate_32bit_precision(something); //well, this is awkward. The logic in this function relies on arithmetic overflows u = simulate_32bit_precision(u + 0xe91aaa35); u = simulate_32bit_precision(u ^ (u >> 16)); u = simulate_32bit_precision(u + (u << 8)); u = simulate_32bit_precision(u ^ (u >> 4)); let b = simulate_32bit_precision((u >> 8) & 0x1ff); let a = simulate_32bit_precision((u + (u << 2)) >> 19); simulate_32bit_precision(a ^ (lookups::HASH_ADJUST[b] as usize)) } pub fn eval_5cards(cards: [&Card; 5]) -> HandRank { let c1 = card_to_deck_number(cards[0]); let c2 = card_to_deck_number(cards[1]); let c3 = card_to_deck_number(cards[2]); let c4 = card_to_deck_number(cards[3]); let c5 = card_to_deck_number(cards[4]); let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16; if (c1 & c2 & c3 & c4 & c5 & 0xf000) != 0 { return lookups::FLUSHES[q] as HandRank; } let s = lookups::UNIQUE_5[q] as HandRank; if s != 0
//TODO: FIXME // version: perfect hash. Not working currently let lookup = find_fast( ((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize ); HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank) } // don't use this. pub fn eval_7cards(cards: [&Card; 7]) -> HandRank { let mut tmp; let mut best = 0; for ids in lookups::PERM_7.iter() { let subhand : [&Card; 5] = [ cards[ids[0] as usize], cards[ids[1] as usize], cards[ids[2] as usize], cards[ids[3] as usize], cards[ids[4] as usize] ]; tmp = eval_5cards(subhand); if tmp > best { best = tmp; } } best } // these two guys only work by accident /* #[test] fn get_rank_of_5_perfect() { let c1 = Card(Value::Two, Suit::Spades); let c2 = Card(Value::Two, Suit::Hearts); let c3 = Card(Value::Two, Suit::Diamonds); let c4 = Card(Value::Two, Suit::Clubs); let c5 = Card(Value::Three, Suit::Hearts); let cards = [&c1, &c2, &c3, &c4, &c5]; let rank = perfect::eval_5cards(cards); assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind); } #[test] fn get_rank_of_7_perfect() { let c1 = Card(Value::Two, Suit::Spades); let c2 = Card(Value::Two, Suit::Hearts); let c3 = Card(Value::Two, Suit::Diamonds); let c4 = Card(Value::Two, Suit::Clubs); let c5 = Card(Value::Three, Suit::Hearts); let c6 = Card(Value::Three, Suit::Diamonds); let c7 = Card(Value::Three, Suit::Clubs); let cards = [&c1, &c2, &c3, &c4, &c5, &c6, &c7]; let rank = perfect::eval_7cards(cards); assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind); } */
{ return s; }
conditional_block
perfect.rs
use super::lookups; use cards::card::{Card}; use super::{HandRank}; use super::utils::{card_to_deck_number}; fn simulate_32bit_precision(u: usize) -> usize { let mask = 0xffffffff; u & mask } // don't use this. pub fn find_fast(something: usize) -> usize { let mut u = simulate_32bit_precision(something); //well, this is awkward. The logic in this function relies on arithmetic overflows u = simulate_32bit_precision(u + 0xe91aaa35); u = simulate_32bit_precision(u ^ (u >> 16)); u = simulate_32bit_precision(u + (u << 8)); u = simulate_32bit_precision(u ^ (u >> 4)); let b = simulate_32bit_precision((u >> 8) & 0x1ff); let a = simulate_32bit_precision((u + (u << 2)) >> 19); simulate_32bit_precision(a ^ (lookups::HASH_ADJUST[b] as usize)) } pub fn
(cards: [&Card; 5]) -> HandRank { let c1 = card_to_deck_number(cards[0]); let c2 = card_to_deck_number(cards[1]); let c3 = card_to_deck_number(cards[2]); let c4 = card_to_deck_number(cards[3]); let c5 = card_to_deck_number(cards[4]); let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16; if (c1 & c2 & c3 & c4 & c5 & 0xf000) != 0 { return lookups::FLUSHES[q] as HandRank; } let s = lookups::UNIQUE_5[q] as HandRank; if s != 0 { return s; } //TODO: FIXME // version: perfect hash. Not working currently let lookup = find_fast( ((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize ); HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank) } // don't use this. pub fn eval_7cards(cards: [&Card; 7]) -> HandRank { let mut tmp; let mut best = 0; for ids in lookups::PERM_7.iter() { let subhand : [&Card; 5] = [ cards[ids[0] as usize], cards[ids[1] as usize], cards[ids[2] as usize], cards[ids[3] as usize], cards[ids[4] as usize] ]; tmp = eval_5cards(subhand); if tmp > best { best = tmp; } } best } // these two guys only work by accident /* #[test] fn get_rank_of_5_perfect() { let c1 = Card(Value::Two, Suit::Spades); let c2 = Card(Value::Two, Suit::Hearts); let c3 = Card(Value::Two, Suit::Diamonds); let c4 = Card(Value::Two, Suit::Clubs); let c5 = Card(Value::Three, Suit::Hearts); let cards = [&c1, &c2, &c3, &c4, &c5]; let rank = perfect::eval_5cards(cards); assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind); } #[test] fn get_rank_of_7_perfect() { let c1 = Card(Value::Two, Suit::Spades); let c2 = Card(Value::Two, Suit::Hearts); let c3 = Card(Value::Two, Suit::Diamonds); let c4 = Card(Value::Two, Suit::Clubs); let c5 = Card(Value::Three, Suit::Hearts); let c6 = Card(Value::Three, Suit::Diamonds); let c7 = Card(Value::Three, Suit::Clubs); let cards = [&c1, &c2, &c3, &c4, &c5, &c6, &c7]; let rank = perfect::eval_7cards(cards); assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind); } */
eval_5cards
identifier_name
perfect.rs
use super::lookups; use cards::card::{Card}; use super::{HandRank}; use super::utils::{card_to_deck_number}; fn simulate_32bit_precision(u: usize) -> usize { let mask = 0xffffffff; u & mask } // don't use this. pub fn find_fast(something: usize) -> usize { let mut u = simulate_32bit_precision(something); //well, this is awkward. The logic in this function relies on arithmetic overflows u = simulate_32bit_precision(u + 0xe91aaa35); u = simulate_32bit_precision(u ^ (u >> 16)); u = simulate_32bit_precision(u + (u << 8)); u = simulate_32bit_precision(u ^ (u >> 4)); let b = simulate_32bit_precision((u >> 8) & 0x1ff); let a = simulate_32bit_precision((u + (u << 2)) >> 19); simulate_32bit_precision(a ^ (lookups::HASH_ADJUST[b] as usize)) } pub fn eval_5cards(cards: [&Card; 5]) -> HandRank { let c1 = card_to_deck_number(cards[0]); let c2 = card_to_deck_number(cards[1]); let c3 = card_to_deck_number(cards[2]); let c4 = card_to_deck_number(cards[3]); let c5 = card_to_deck_number(cards[4]); let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16; if (c1 & c2 & c3 & c4 & c5 & 0xf000) != 0 { return lookups::FLUSHES[q] as HandRank; } let s = lookups::UNIQUE_5[q] as HandRank; if s != 0 { return s; } //TODO: FIXME // version: perfect hash. Not working currently let lookup = find_fast( ((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize ); HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank) } // don't use this. pub fn eval_7cards(cards: [&Card; 7]) -> HandRank
// these two guys only work by accident /* #[test] fn get_rank_of_5_perfect() { let c1 = Card(Value::Two, Suit::Spades); let c2 = Card(Value::Two, Suit::Hearts); let c3 = Card(Value::Two, Suit::Diamonds); let c4 = Card(Value::Two, Suit::Clubs); let c5 = Card(Value::Three, Suit::Hearts); let cards = [&c1, &c2, &c3, &c4, &c5]; let rank = perfect::eval_5cards(cards); assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind); } #[test] fn get_rank_of_7_perfect() { let c1 = Card(Value::Two, Suit::Spades); let c2 = Card(Value::Two, Suit::Hearts); let c3 = Card(Value::Two, Suit::Diamonds); let c4 = Card(Value::Two, Suit::Clubs); let c5 = Card(Value::Three, Suit::Hearts); let c6 = Card(Value::Three, Suit::Diamonds); let c7 = Card(Value::Three, Suit::Clubs); let cards = [&c1, &c2, &c3, &c4, &c5, &c6, &c7]; let rank = perfect::eval_7cards(cards); assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind); } */
{ let mut tmp; let mut best = 0; for ids in lookups::PERM_7.iter() { let subhand : [&Card; 5] = [ cards[ids[0] as usize], cards[ids[1] as usize], cards[ids[2] as usize], cards[ids[3] as usize], cards[ids[4] as usize] ]; tmp = eval_5cards(subhand); if tmp > best { best = tmp; } } best }
identifier_body
perfect.rs
use super::lookups; use cards::card::{Card}; use super::{HandRank}; use super::utils::{card_to_deck_number}; fn simulate_32bit_precision(u: usize) -> usize { let mask = 0xffffffff; u & mask } // don't use this. pub fn find_fast(something: usize) -> usize { let mut u = simulate_32bit_precision(something); //well, this is awkward. The logic in this function relies on arithmetic overflows u = simulate_32bit_precision(u + 0xe91aaa35); u = simulate_32bit_precision(u ^ (u >> 16)); u = simulate_32bit_precision(u + (u << 8)); u = simulate_32bit_precision(u ^ (u >> 4)); let b = simulate_32bit_precision((u >> 8) & 0x1ff); let a = simulate_32bit_precision((u + (u << 2)) >> 19); simulate_32bit_precision(a ^ (lookups::HASH_ADJUST[b] as usize)) } pub fn eval_5cards(cards: [&Card; 5]) -> HandRank { let c1 = card_to_deck_number(cards[0]); let c2 = card_to_deck_number(cards[1]); let c3 = card_to_deck_number(cards[2]); let c4 = card_to_deck_number(cards[3]); let c5 = card_to_deck_number(cards[4]); let q : usize = ((c1 | c2 | c3 | c4 | c5) as usize) >> 16; if (c1 & c2 & c3 & c4 & c5 & 0xf000) != 0 { return lookups::FLUSHES[q] as HandRank; } let s = lookups::UNIQUE_5[q] as HandRank; if s != 0 { return s; } //TODO: FIXME // version: perfect hash. Not working currently let lookup = find_fast( ((c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff)) as usize ); HAND_RANK_COUNT - (lookups::HASH_VALUES[lookup] as HandRank) } // don't use this. pub fn eval_7cards(cards: [&Card; 7]) -> HandRank { let mut tmp; let mut best = 0; for ids in lookups::PERM_7.iter() { let subhand : [&Card; 5] = [ cards[ids[0] as usize], cards[ids[1] as usize], cards[ids[2] as usize], cards[ids[3] as usize], cards[ids[4] as usize] ]; tmp = eval_5cards(subhand); if tmp > best { best = tmp; } } best } // these two guys only work by accident /* #[test] fn get_rank_of_5_perfect() { let c1 = Card(Value::Two, Suit::Spades); let c2 = Card(Value::Two, Suit::Hearts); let c3 = Card(Value::Two, Suit::Diamonds); let c4 = Card(Value::Two, Suit::Clubs); let c5 = Card(Value::Three, Suit::Hearts); let cards = [&c1, &c2, &c3, &c4, &c5]; let rank = perfect::eval_5cards(cards); assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind); }
let c1 = Card(Value::Two, Suit::Spades); let c2 = Card(Value::Two, Suit::Hearts); let c3 = Card(Value::Two, Suit::Diamonds); let c4 = Card(Value::Two, Suit::Clubs); let c5 = Card(Value::Three, Suit::Hearts); let c6 = Card(Value::Three, Suit::Diamonds); let c7 = Card(Value::Three, Suit::Clubs); let cards = [&c1, &c2, &c3, &c4, &c5, &c6, &c7]; let rank = perfect::eval_7cards(cards); assert_eq!(hand_rank(rank), HandRankClass::FourOfAKind); } */
#[test] fn get_rank_of_7_perfect() {
random_line_split
test_base.py
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') import numpy as np # noqa import pandas as pd # noqa import pandas_ml as pdml # noqa import pandas_ml.util.testing as tm # noqa import sklearn.datasets as datasets # noqa import xgboost as xgb # noqa class TestXGBoost(tm.TestCase): def test_objectmapper(self):
def test_XGBClassifier(self): iris = datasets.load_iris() df = pdml.ModelFrame(iris) models = ['XGBClassifier'] for model in models: mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(iris.data, iris.target) result = df.predict(mod1) expected = mod2.predict(iris.data) self.assertIsInstance(result, pdml.ModelSeries) self.assert_numpy_array_almost_equal(result.values, expected) def test_XGBRegressor(self): # http://scikit-learn.org/stable/auto_examples/plot_kernel_ridge_regression.html X = 5 * np.random.rand(1000, 1) y = np.sin(X).ravel() # Add noise to targets y[::5] += 3 * (0.5 - np.random.rand(X.shape[0] // 5)) df = pdml.ModelFrame(data=X, target=y) models = ['XGBRegressor'] for model in models: mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(X, y) result = df.predict(mod1) expected = mod2.predict(X) self.assertIsInstance(result, pdml.ModelSeries) self.assert_numpy_array_almost_equal(result.values, expected) self.assertIsInstance(df.predicted, pdml.ModelSeries) self.assert_numpy_array_almost_equal(df.predicted.values, expected) def test_grid_search(self): tuned_parameters = [{'max_depth': [3, 4], 'n_estimators': [50, 100]}] df = pdml.ModelFrame(datasets.load_digits()) cv = df.grid_search.GridSearchCV(df.xgb.XGBClassifier(), tuned_parameters, cv=5) with tm.RNGContext(1): df.fit(cv) result = df.grid_search.describe(cv) expected = pd.DataFrame({'mean': [0.89705064, 0.91764051, 0.91263216, 0.91930996], 'std': [0.03244061, 0.03259985, 0.02764891, 0.0266436], 'max_depth': [3, 3, 4, 4], 'n_estimators': [50, 100, 50, 100]}, columns=['mean', 'std', 'max_depth', 'n_estimators']) self.assertIsInstance(result, pdml.ModelFrame) tm.assert_frame_equal(result, expected) def test_plotting(self): iris = datasets.load_iris() df = pdml.ModelFrame(iris) df.fit(df.svm.SVC()) # raises if df.estimator is not XGBModel with self.assertRaises(ValueError): df.xgb.plot_importance() with self.assertRaises(ValueError): df.xgb.to_graphviz() with self.assertRaises(ValueError): df.xgb.plot_tree() df.fit(df.xgb.XGBClassifier()) from matplotlib.axes import Axes from graphviz import Digraph try: ax = df.xgb.plot_importance() except ImportError: import nose # matplotlib.use doesn't work on Travis # PYTHON=3.4 PANDAS=0.17.1 SKLEARN=0.16.1 raise nose.SkipTest() self.assertIsInstance(ax, Axes) assert ax.get_title() == 'Feature importance' assert ax.get_xlabel() == 'F score' assert ax.get_ylabel() == 'Features' assert len(ax.patches) == 4 g = df.xgb.to_graphviz(num_trees=0) self.assertIsInstance(g, Digraph) ax = df.xgb.plot_tree(num_trees=0) self.assertIsInstance(ax, Axes) if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
df = pdml.ModelFrame([]) self.assertIs(df.xgboost.XGBRegressor, xgb.XGBRegressor) self.assertIs(df.xgboost.XGBClassifier, xgb.XGBClassifier)
identifier_body
test_base.py
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') import numpy as np # noqa import pandas as pd # noqa import pandas_ml as pdml # noqa import pandas_ml.util.testing as tm # noqa import sklearn.datasets as datasets # noqa import xgboost as xgb # noqa class TestXGBoost(tm.TestCase): def test_objectmapper(self): df = pdml.ModelFrame([]) self.assertIs(df.xgboost.XGBRegressor, xgb.XGBRegressor) self.assertIs(df.xgboost.XGBClassifier, xgb.XGBClassifier) def test_XGBClassifier(self): iris = datasets.load_iris() df = pdml.ModelFrame(iris) models = ['XGBClassifier'] for model in models: mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(iris.data, iris.target) result = df.predict(mod1) expected = mod2.predict(iris.data) self.assertIsInstance(result, pdml.ModelSeries) self.assert_numpy_array_almost_equal(result.values, expected) def test_XGBRegressor(self): # http://scikit-learn.org/stable/auto_examples/plot_kernel_ridge_regression.html X = 5 * np.random.rand(1000, 1) y = np.sin(X).ravel() # Add noise to targets y[::5] += 3 * (0.5 - np.random.rand(X.shape[0] // 5)) df = pdml.ModelFrame(data=X, target=y) models = ['XGBRegressor'] for model in models: mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(X, y) result = df.predict(mod1) expected = mod2.predict(X) self.assertIsInstance(result, pdml.ModelSeries) self.assert_numpy_array_almost_equal(result.values, expected) self.assertIsInstance(df.predicted, pdml.ModelSeries) self.assert_numpy_array_almost_equal(df.predicted.values, expected) def test_grid_search(self): tuned_parameters = [{'max_depth': [3, 4], 'n_estimators': [50, 100]}] df = pdml.ModelFrame(datasets.load_digits()) cv = df.grid_search.GridSearchCV(df.xgb.XGBClassifier(), tuned_parameters, cv=5) with tm.RNGContext(1): df.fit(cv) result = df.grid_search.describe(cv) expected = pd.DataFrame({'mean': [0.89705064, 0.91764051, 0.91263216, 0.91930996], 'std': [0.03244061, 0.03259985, 0.02764891, 0.0266436], 'max_depth': [3, 3, 4, 4], 'n_estimators': [50, 100, 50, 100]}, columns=['mean', 'std', 'max_depth', 'n_estimators']) self.assertIsInstance(result, pdml.ModelFrame) tm.assert_frame_equal(result, expected) def
(self): iris = datasets.load_iris() df = pdml.ModelFrame(iris) df.fit(df.svm.SVC()) # raises if df.estimator is not XGBModel with self.assertRaises(ValueError): df.xgb.plot_importance() with self.assertRaises(ValueError): df.xgb.to_graphviz() with self.assertRaises(ValueError): df.xgb.plot_tree() df.fit(df.xgb.XGBClassifier()) from matplotlib.axes import Axes from graphviz import Digraph try: ax = df.xgb.plot_importance() except ImportError: import nose # matplotlib.use doesn't work on Travis # PYTHON=3.4 PANDAS=0.17.1 SKLEARN=0.16.1 raise nose.SkipTest() self.assertIsInstance(ax, Axes) assert ax.get_title() == 'Feature importance' assert ax.get_xlabel() == 'F score' assert ax.get_ylabel() == 'Features' assert len(ax.patches) == 4 g = df.xgb.to_graphviz(num_trees=0) self.assertIsInstance(g, Digraph) ax = df.xgb.plot_tree(num_trees=0) self.assertIsInstance(ax, Axes) if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
test_plotting
identifier_name
test_base.py
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') import numpy as np # noqa import pandas as pd # noqa import pandas_ml as pdml # noqa import pandas_ml.util.testing as tm # noqa import sklearn.datasets as datasets # noqa import xgboost as xgb # noqa class TestXGBoost(tm.TestCase): def test_objectmapper(self): df = pdml.ModelFrame([]) self.assertIs(df.xgboost.XGBRegressor, xgb.XGBRegressor) self.assertIs(df.xgboost.XGBClassifier, xgb.XGBClassifier) def test_XGBClassifier(self): iris = datasets.load_iris() df = pdml.ModelFrame(iris) models = ['XGBClassifier'] for model in models: mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(iris.data, iris.target) result = df.predict(mod1) expected = mod2.predict(iris.data) self.assertIsInstance(result, pdml.ModelSeries) self.assert_numpy_array_almost_equal(result.values, expected) def test_XGBRegressor(self): # http://scikit-learn.org/stable/auto_examples/plot_kernel_ridge_regression.html X = 5 * np.random.rand(1000, 1) y = np.sin(X).ravel() # Add noise to targets y[::5] += 3 * (0.5 - np.random.rand(X.shape[0] // 5)) df = pdml.ModelFrame(data=X, target=y) models = ['XGBRegressor'] for model in models:
def test_grid_search(self): tuned_parameters = [{'max_depth': [3, 4], 'n_estimators': [50, 100]}] df = pdml.ModelFrame(datasets.load_digits()) cv = df.grid_search.GridSearchCV(df.xgb.XGBClassifier(), tuned_parameters, cv=5) with tm.RNGContext(1): df.fit(cv) result = df.grid_search.describe(cv) expected = pd.DataFrame({'mean': [0.89705064, 0.91764051, 0.91263216, 0.91930996], 'std': [0.03244061, 0.03259985, 0.02764891, 0.0266436], 'max_depth': [3, 3, 4, 4], 'n_estimators': [50, 100, 50, 100]}, columns=['mean', 'std', 'max_depth', 'n_estimators']) self.assertIsInstance(result, pdml.ModelFrame) tm.assert_frame_equal(result, expected) def test_plotting(self): iris = datasets.load_iris() df = pdml.ModelFrame(iris) df.fit(df.svm.SVC()) # raises if df.estimator is not XGBModel with self.assertRaises(ValueError): df.xgb.plot_importance() with self.assertRaises(ValueError): df.xgb.to_graphviz() with self.assertRaises(ValueError): df.xgb.plot_tree() df.fit(df.xgb.XGBClassifier()) from matplotlib.axes import Axes from graphviz import Digraph try: ax = df.xgb.plot_importance() except ImportError: import nose # matplotlib.use doesn't work on Travis # PYTHON=3.4 PANDAS=0.17.1 SKLEARN=0.16.1 raise nose.SkipTest() self.assertIsInstance(ax, Axes) assert ax.get_title() == 'Feature importance' assert ax.get_xlabel() == 'F score' assert ax.get_ylabel() == 'Features' assert len(ax.patches) == 4 g = df.xgb.to_graphviz(num_trees=0) self.assertIsInstance(g, Digraph) ax = df.xgb.plot_tree(num_trees=0) self.assertIsInstance(ax, Axes) if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(X, y) result = df.predict(mod1) expected = mod2.predict(X) self.assertIsInstance(result, pdml.ModelSeries) self.assert_numpy_array_almost_equal(result.values, expected) self.assertIsInstance(df.predicted, pdml.ModelSeries) self.assert_numpy_array_almost_equal(df.predicted.values, expected)
conditional_block
test_base.py
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') import numpy as np # noqa import pandas as pd # noqa import pandas_ml as pdml # noqa import pandas_ml.util.testing as tm # noqa import sklearn.datasets as datasets # noqa import xgboost as xgb # noqa class TestXGBoost(tm.TestCase): def test_objectmapper(self): df = pdml.ModelFrame([]) self.assertIs(df.xgboost.XGBRegressor, xgb.XGBRegressor) self.assertIs(df.xgboost.XGBClassifier, xgb.XGBClassifier) def test_XGBClassifier(self): iris = datasets.load_iris() df = pdml.ModelFrame(iris) models = ['XGBClassifier'] for model in models: mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(iris.data, iris.target) result = df.predict(mod1) expected = mod2.predict(iris.data) self.assertIsInstance(result, pdml.ModelSeries) self.assert_numpy_array_almost_equal(result.values, expected) def test_XGBRegressor(self): # http://scikit-learn.org/stable/auto_examples/plot_kernel_ridge_regression.html X = 5 * np.random.rand(1000, 1) y = np.sin(X).ravel() # Add noise to targets y[::5] += 3 * (0.5 - np.random.rand(X.shape[0] // 5)) df = pdml.ModelFrame(data=X, target=y) models = ['XGBRegressor'] for model in models: mod1 = getattr(df.xgboost, model)() mod2 = getattr(xgb, model)() df.fit(mod1) mod2.fit(X, y) result = df.predict(mod1) expected = mod2.predict(X) self.assertIsInstance(result, pdml.ModelSeries) self.assert_numpy_array_almost_equal(result.values, expected) self.assertIsInstance(df.predicted, pdml.ModelSeries) self.assert_numpy_array_almost_equal(df.predicted.values, expected) def test_grid_search(self): tuned_parameters = [{'max_depth': [3, 4], 'n_estimators': [50, 100]}] df = pdml.ModelFrame(datasets.load_digits()) cv = df.grid_search.GridSearchCV(df.xgb.XGBClassifier(), tuned_parameters, cv=5) with tm.RNGContext(1): df.fit(cv) result = df.grid_search.describe(cv) expected = pd.DataFrame({'mean': [0.89705064, 0.91764051, 0.91263216, 0.91930996], 'std': [0.03244061, 0.03259985, 0.02764891, 0.0266436], 'max_depth': [3, 3, 4, 4], 'n_estimators': [50, 100, 50, 100]}, columns=['mean', 'std', 'max_depth', 'n_estimators']) self.assertIsInstance(result, pdml.ModelFrame) tm.assert_frame_equal(result, expected) def test_plotting(self): iris = datasets.load_iris() df = pdml.ModelFrame(iris) df.fit(df.svm.SVC()) # raises if df.estimator is not XGBModel with self.assertRaises(ValueError): df.xgb.plot_importance() with self.assertRaises(ValueError): df.xgb.to_graphviz() with self.assertRaises(ValueError): df.xgb.plot_tree() df.fit(df.xgb.XGBClassifier()) from matplotlib.axes import Axes from graphviz import Digraph try: ax = df.xgb.plot_importance() except ImportError: import nose # matplotlib.use doesn't work on Travis
# PYTHON=3.4 PANDAS=0.17.1 SKLEARN=0.16.1 raise nose.SkipTest() self.assertIsInstance(ax, Axes) assert ax.get_title() == 'Feature importance' assert ax.get_xlabel() == 'F score' assert ax.get_ylabel() == 'Features' assert len(ax.patches) == 4 g = df.xgb.to_graphviz(num_trees=0) self.assertIsInstance(g, Digraph) ax = df.xgb.plot_tree(num_trees=0) self.assertIsInstance(ax, Axes) if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
random_line_split
backtrace.rs
1::*; use io::prelude::*; use ffi::CStr; use io; use libc; use str; use sync::StaticMutex; use sys_common::backtrace::*; /// As always - iOS on arm uses SjLj exceptions and /// _Unwind_Backtrace is even not available there. Still, /// backtraces could be extracted using a backtrace function, /// which thanks god is public /// /// As mentioned in a huge comment block above, backtrace doesn't /// play well with green threads, so while it is extremely nice /// and simple to use it should be used only on iOS devices as the /// only viable option. #[cfg(all(target_os = "ios", target_arch = "arm"))] #[inline(never)] pub fn write(w: &mut Write) -> io::Result<()> { extern { fn backtrace(buf: *mut *mut libc::c_void, sz: libc::c_int) -> libc::c_int; } // while it doesn't requires lock for work as everything is // local, it still displays much nicer backtraces when a // couple of threads panic simultaneously static LOCK: StaticMutex = StaticMutex::new(); let _g = LOCK.lock(); try!(writeln!(w, "stack backtrace:")); // 100 lines should be enough const SIZE: usize = 100; let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()}; let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as usize}; // skipping the first one as it is write itself for i in 1..cnt { try!(print(w, i as isize, buf[i], buf[i])) } Ok(()) } #[cfg(not(all(target_os = "ios", target_arch = "arm")))] #[inline(never)] // if we know this is a function call, we can skip it when // tracing pub fn write(w: &mut Write) -> io::Result<()>
&mut cx as *mut Context as *mut libc::c_void) } { uw::_URC_NO_REASON => { match cx.last_error { Some(err) => Err(err), None => Ok(()) } } _ => Ok(()), }; extern fn trace_fn(ctx: *mut uw::_Unwind_Context, arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code { let cx: &mut Context = unsafe { &mut *(arg as *mut Context) }; let mut ip_before_insn = 0; let mut ip = unsafe { uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void }; if !ip.is_null() && ip_before_insn == 0 { // this is a non-signaling frame, so `ip` refers to the address // after the calling instruction. account for that. ip = (ip as usize - 1) as *mut _; } // dladdr() on osx gets whiny when we use FindEnclosingFunction, and // it appears to work fine without it, so we only use // FindEnclosingFunction on non-osx platforms. In doing so, we get a // slightly more accurate stack trace in the process. // // This is often because panic involves the last instruction of a // function being "call std::rt::begin_unwind", with no ret // instructions after it. This means that the return instruction // pointer points *outside* of the calling function, and by // unwinding it we go back to the original function. let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") { ip } else { unsafe { uw::_Unwind_FindEnclosingFunction(ip) } }; // Don't print out the first few frames (they're not user frames) cx.idx += 1; if cx.idx <= 0 { return uw::_URC_NO_REASON } // Don't print ginormous backtraces if cx.idx > 100 { match write!(cx.writer, " ... <frames omitted>\n") { Ok(()) => {} Err(e) => { cx.last_error = Some(e); } } return uw::_URC_FAILURE } // Once we hit an error, stop trying to print more frames if cx.last_error.is_some() { return uw::_URC_FAILURE } match print(cx.writer, cx.idx, ip, symaddr) { Ok(()) => {} Err(e) => { cx.last_error = Some(e); } } // keep going return uw::_URC_NO_REASON } } #[cfg(any(target_os = "macos", target_os = "ios"))] fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void, _symaddr: *mut libc::c_void) -> io::Result<()> { use intrinsics; #[repr(C)] struct Dl_info { dli_fname: *const libc::c_char, dli_fbase: *mut libc::c_void, dli_sname: *const libc::c_char, dli_saddr: *mut libc::c_void, } extern { fn dladdr(addr: *const libc::c_void, info: *mut Dl_info) -> libc::c_int; } let mut info: Dl_info = unsafe { intrinsics::init() }; if unsafe { dladdr(addr, &mut info) == 0 } { output(w, idx,addr, None) } else { output(w, idx, addr, Some(unsafe { CStr::from_ptr(info.dli_sname).to_bytes() })) } } #[cfg(not(any(target_os = "macos", target_os = "ios")))] fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void, symaddr: *mut libc::c_void) -> io::Result<()> { use env; use os::unix::prelude::*; use ptr; //////////////////////////////////////////////////////////////////////// // libbacktrace.h API //////////////////////////////////////////////////////////////////////// type backtrace_syminfo_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, symname: *const libc::c_char, symval: libc::uintptr_t, symsize: libc::uintptr_t); type backtrace_full_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, filename: *const libc::c_char, lineno: libc::c_int, function: *const libc::c_char) -> libc::c_int; type backtrace_error_callback = extern "C" fn(data: *mut libc::c_void, msg: *const libc::c_char, errnum: libc::c_int); enum backtrace_state {} #[link(name = "backtrace", kind = "static")] #[cfg(not(test))] extern {} extern { fn backtrace_create_state(filename: *const libc::c_char, threaded: libc::c_int, error: backtrace_error_callback, data: *mut libc::c_void) -> *mut backtrace_state; fn backtrace_syminfo(state: *mut backtrace_state, addr: libc::uintptr_t, cb: backtrace_syminfo_callback, error: backtrace_error_callback, data: *mut libc::c_void) -> libc::c_int; fn backtrace_pcinfo(state: *mut backtrace_state, addr: libc::uintptr_t, cb: backtrace_full_callback, error: backtrace_error_callback, data: *mut libc::c_void) -> libc::c_int; } //////////////////////////////////////////////////////////////////////// // helper callbacks //////////////////////////////////////////////////////////////////////// type FileLine = (*const libc::c_char, libc::c_int); extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char, _errnum: libc::c_int) { // do nothing for now } extern fn syminfo_cb(data: *mut libc::c_void, _pc: libc::uintptr_t, symname: *const libc::c_char, _symval: libc::uintptr_t, _sy
{ struct Context<'a> { idx: isize, writer: &'a mut (Write+'a), last_error: Option<io::Error>, } // When using libbacktrace, we use some necessary global state, so we // need to prevent more than one thread from entering this block. This // is semi-reasonable in terms of printing anyway, and we know that all // I/O done here is blocking I/O, not green I/O, so we don't have to // worry about this being a native vs green mutex. static LOCK: StaticMutex = StaticMutex::new(); let _g = LOCK.lock(); try!(writeln!(w, "stack backtrace:")); let mut cx = Context { writer: w, last_error: None, idx: 0 }; return match unsafe { uw::_Unwind_Backtrace(trace_fn,
identifier_body
backtrace.rs
1::*; use io::prelude::*; use ffi::CStr; use io; use libc; use str; use sync::StaticMutex; use sys_common::backtrace::*; /// As always - iOS on arm uses SjLj exceptions and /// _Unwind_Backtrace is even not available there. Still, /// backtraces could be extracted using a backtrace function, /// which thanks god is public /// /// As mentioned in a huge comment block above, backtrace doesn't /// play well with green threads, so while it is extremely nice /// and simple to use it should be used only on iOS devices as the /// only viable option. #[cfg(all(target_os = "ios", target_arch = "arm"))] #[inline(never)] pub fn write(w: &mut Write) -> io::Result<()> { extern { fn backtrace(buf: *mut *mut libc::c_void, sz: libc::c_int) -> libc::c_int; } // while it doesn't requires lock for work as everything is // local, it still displays much nicer backtraces when a // couple of threads panic simultaneously static LOCK: StaticMutex = StaticMutex::new(); let _g = LOCK.lock(); try!(writeln!(w, "stack backtrace:")); // 100 lines should be enough const SIZE: usize = 100; let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()}; let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as usize}; // skipping the first one as it is write itself for i in 1..cnt { try!(print(w, i as isize, buf[i], buf[i])) } Ok(()) } #[cfg(not(all(target_os = "ios", target_arch = "arm")))] #[inline(never)] // if we know this is a function call, we can skip it when // tracing pub fn write(w: &mut Write) -> io::Result<()> { struct Context<'a> { idx: isize, writer: &'a mut (Write+'a), last_error: Option<io::Error>, } // When using libbacktrace, we use some necessary global state, so we // need to prevent more than one thread from entering this block. This // is semi-reasonable in terms of printing anyway, and we know that all // I/O done here is blocking I/O, not green I/O, so we don't have to // worry about this being a native vs green mutex. static LOCK: StaticMutex = StaticMutex::new(); let _g = LOCK.lock(); try!(writeln!(w, "stack backtrace:")); let mut cx = Context { writer: w, last_error: None, idx: 0 }; return match unsafe { uw::_Unwind_Backtrace(trace_fn, &mut cx as *mut Context as *mut libc::c_void) } { uw::_URC_NO_REASON => { match cx.last_error { Some(err) => Err(err), None => Ok(()) } } _ => Ok(()), }; extern fn trace_fn(ctx: *mut uw::_Unwind_Context, arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code { let cx: &mut Context = unsafe { &mut *(arg as *mut Context) }; let mut ip_before_insn = 0; let mut ip = unsafe { uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void }; if !ip.is_null() && ip_before_insn == 0 { // this is a non-signaling frame, so `ip` refers to the address // after the calling instruction. account for that. ip = (ip as usize - 1) as *mut _; } // dladdr() on osx gets whiny when we use FindEnclosingFunction, and // it appears to work fine without it, so we only use // FindEnclosingFunction on non-osx platforms. In doing so, we get a // slightly more accurate stack trace in the process. // // This is often because panic involves the last instruction of a // function being "call std::rt::begin_unwind", with no ret // instructions after it. This means that the return instruction // pointer points *outside* of the calling function, and by // unwinding it we go back to the original function. let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") { ip } else { unsafe { uw::_Unwind_FindEnclosingFunction(ip) } }; // Don't print out the first few frames (they're not user frames) cx.idx += 1; if cx.idx <= 0 { return uw::_URC_NO_REASON } // Don't print ginormous backtraces if cx.idx > 100 { match write!(cx.writer, " ... <frames omitted>\n") { Ok(()) => {} Err(e) => { cx.last_error = Some(e); } } return uw::_URC_FAILURE } // Once we hit an error, stop trying to print more frames if cx.last_error.is_some() { return uw::_URC_FAILURE } match print(cx.writer, cx.idx, ip, symaddr) { Ok(()) => {} Err(e) => { cx.last_error = Some(e); } } // keep going return uw::_URC_NO_REASON } } #[cfg(any(target_os = "macos", target_os = "ios"))] fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void, _symaddr: *mut libc::c_void) -> io::Result<()> { use intrinsics; #[repr(C)] struct Dl_info { dli_fname: *const libc::c_char, dli_fbase: *mut libc::c_void, dli_sname: *const libc::c_char, dli_saddr: *mut libc::c_void, } extern { fn dladdr(addr: *const libc::c_void, info: *mut Dl_info) -> libc::c_int; } let mut info: Dl_info = unsafe { intrinsics::init() }; if unsafe { dladdr(addr, &mut info) == 0 } { output(w, idx,addr, None) } else { output(w, idx, addr, Some(unsafe { CStr::from_ptr(info.dli_sname).to_bytes() })) } } #[cfg(not(any(target_os = "macos", target_os = "ios")))] fn
(w: &mut Write, idx: isize, addr: *mut libc::c_void, symaddr: *mut libc::c_void) -> io::Result<()> { use env; use os::unix::prelude::*; use ptr; //////////////////////////////////////////////////////////////////////// // libbacktrace.h API //////////////////////////////////////////////////////////////////////// type backtrace_syminfo_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, symname: *const libc::c_char, symval: libc::uintptr_t, symsize: libc::uintptr_t); type backtrace_full_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, filename: *const libc::c_char, lineno: libc::c_int, function: *const libc::c_char) -> libc::c_int; type backtrace_error_callback = extern "C" fn(data: *mut libc::c_void, msg: *const libc::c_char, errnum: libc::c_int); enum backtrace_state {} #[link(name = "backtrace", kind = "static")] #[cfg(not(test))] extern {} extern { fn backtrace_create_state(filename: *const libc::c_char, threaded: libc::c_int, error: backtrace_error_callback, data: *mut libc::c_void) -> *mut backtrace_state; fn backtrace_syminfo(state: *mut backtrace_state, addr: libc::uintptr_t, cb: backtrace_syminfo_callback, error: backtrace_error_callback, data: *mut libc::c_void) -> libc::c_int; fn backtrace_pcinfo(state: *mut backtrace_state, addr: libc::uintptr_t, cb: backtrace_full_callback, error: backtrace_error_callback, data: *mut libc::c_void) -> libc::c_int; } //////////////////////////////////////////////////////////////////////// // helper callbacks //////////////////////////////////////////////////////////////////////// type FileLine = (*const libc::c_char, libc::c_int); extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char, _errnum: libc::c_int) { // do nothing for now } extern fn syminfo_cb(data: *mut libc::c_void, _pc: libc::uintptr_t, symname: *const libc::c_char, _symval: libc::uintptr_t, _sy
print
identifier_name
backtrace.rs
ip_before_insn) as *mut libc::c_void }; if !ip.is_null() && ip_before_insn == 0 { // this is a non-signaling frame, so `ip` refers to the address // after the calling instruction. account for that. ip = (ip as usize - 1) as *mut _; } // dladdr() on osx gets whiny when we use FindEnclosingFunction, and // it appears to work fine without it, so we only use // FindEnclosingFunction on non-osx platforms. In doing so, we get a // slightly more accurate stack trace in the process. // // This is often because panic involves the last instruction of a // function being "call std::rt::begin_unwind", with no ret // instructions after it. This means that the return instruction // pointer points *outside* of the calling function, and by // unwinding it we go back to the original function. let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") { ip } else { unsafe { uw::_Unwind_FindEnclosingFunction(ip) } }; // Don't print out the first few frames (they're not user frames) cx.idx += 1; if cx.idx <= 0 { return uw::_URC_NO_REASON } // Don't print ginormous backtraces if cx.idx > 100 { match write!(cx.writer, " ... <frames omitted>\n") { Ok(()) => {} Err(e) => { cx.last_error = Some(e); } } return uw::_URC_FAILURE } // Once we hit an error, stop trying to print more frames if cx.last_error.is_some() { return uw::_URC_FAILURE } match print(cx.writer, cx.idx, ip, symaddr) { Ok(()) => {} Err(e) => { cx.last_error = Some(e); } } // keep going return uw::_URC_NO_REASON } } #[cfg(any(target_os = "macos", target_os = "ios"))] fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void, _symaddr: *mut libc::c_void) -> io::Result<()> { use intrinsics; #[repr(C)] struct Dl_info { dli_fname: *const libc::c_char, dli_fbase: *mut libc::c_void, dli_sname: *const libc::c_char, dli_saddr: *mut libc::c_void, } extern { fn dladdr(addr: *const libc::c_void, info: *mut Dl_info) -> libc::c_int; } let mut info: Dl_info = unsafe { intrinsics::init() }; if unsafe { dladdr(addr, &mut info) == 0 } { output(w, idx,addr, None) } else { output(w, idx, addr, Some(unsafe { CStr::from_ptr(info.dli_sname).to_bytes() })) } } #[cfg(not(any(target_os = "macos", target_os = "ios")))] fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void, symaddr: *mut libc::c_void) -> io::Result<()> { use env; use os::unix::prelude::*; use ptr; //////////////////////////////////////////////////////////////////////// // libbacktrace.h API //////////////////////////////////////////////////////////////////////// type backtrace_syminfo_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, symname: *const libc::c_char, symval: libc::uintptr_t, symsize: libc::uintptr_t); type backtrace_full_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, filename: *const libc::c_char, lineno: libc::c_int, function: *const libc::c_char) -> libc::c_int; type backtrace_error_callback = extern "C" fn(data: *mut libc::c_void, msg: *const libc::c_char, errnum: libc::c_int); enum backtrace_state {} #[link(name = "backtrace", kind = "static")] #[cfg(not(test))] extern {} extern { fn backtrace_create_state(filename: *const libc::c_char, threaded: libc::c_int, error: backtrace_error_callback, data: *mut libc::c_void) -> *mut backtrace_state; fn backtrace_syminfo(state: *mut backtrace_state, addr: libc::uintptr_t, cb: backtrace_syminfo_callback, error: backtrace_error_callback, data: *mut libc::c_void) -> libc::c_int; fn backtrace_pcinfo(state: *mut backtrace_state, addr: libc::uintptr_t, cb: backtrace_full_callback, error: backtrace_error_callback, data: *mut libc::c_void) -> libc::c_int; } //////////////////////////////////////////////////////////////////////// // helper callbacks //////////////////////////////////////////////////////////////////////// type FileLine = (*const libc::c_char, libc::c_int); extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char, _errnum: libc::c_int) { // do nothing for now } extern fn syminfo_cb(data: *mut libc::c_void, _pc: libc::uintptr_t, symname: *const libc::c_char, _symval: libc::uintptr_t, _symsize: libc::uintptr_t) { let slot = data as *mut *const libc::c_char; unsafe { *slot = symname; } } extern fn pcinfo_cb(data: *mut libc::c_void, _pc: libc::uintptr_t, filename: *const libc::c_char, lineno: libc::c_int, _function: *const libc::c_char) -> libc::c_int { if !filename.is_null() { let slot = data as *mut &mut [FileLine]; let buffer = unsafe {ptr::read(slot)}; // if the buffer is not full, add file:line to the buffer // and adjust the buffer for next possible calls to pcinfo_cb. if !buffer.is_empty() { buffer[0] = (filename, lineno); unsafe { ptr::write(slot, &mut buffer[1..]); } } } 0 } // The libbacktrace API supports creating a state, but it does not // support destroying a state. I personally take this to mean that a // state is meant to be created and then live forever. // // I would love to register an at_exit() handler which cleans up this // state, but libbacktrace provides no way to do so. // // With these constraints, this function has a statically cached state // that is calculated the first time this is requested. Remember that // backtracing all happens serially (one global lock). // // An additionally oddity in this function is that we initialize the // filename via self_exe_name() to pass to libbacktrace. It turns out // that on Linux libbacktrace seamlessly gets the filename of the // current executable, but this fails on freebsd. by always providing // it, we make sure that libbacktrace never has a reason to not look up // the symbols. The libbacktrace API also states that the filename must // be in "permanent memory", so we copy it to a static and then use the // static as the pointer. // // FIXME: We also call self_exe_name() on DragonFly BSD. I haven't // tested if this is required or not. unsafe fn init_state() -> *mut backtrace_state { static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state; static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256]; if !STATE.is_null() { return STATE } let selfname = if cfg!(target_os = "freebsd") || cfg!(target_os = "dragonfly") || cfg!(target_os = "bitrig") || cfg!(target_os = "netbsd") || cfg!(target_os = "openbsd") { env::current_exe().ok() } else { None }; let filename = match selfname { Some(path) => { let bytes = path.as_os_str().as_bytes(); if bytes.len() < LAST_FILENAME.len() { let i = bytes.iter(); for (slot, val) in LAST_FILENAME.iter_mut().zip(i) { *slot = *val as libc::c_char; } LAST_FILENAME.as_ptr() } else { ptr::null() } } None => ptr::null(), }; STATE = backtrace_create_state(filename, 0, error_cb, ptr::null_mut()); return STATE }
//////////////////////////////////////////////////////////////////////// // translation
random_line_split
backtrace.rs
::*; use io::prelude::*; use ffi::CStr; use io; use libc; use str; use sync::StaticMutex; use sys_common::backtrace::*; /// As always - iOS on arm uses SjLj exceptions and /// _Unwind_Backtrace is even not available there. Still, /// backtraces could be extracted using a backtrace function, /// which thanks god is public /// /// As mentioned in a huge comment block above, backtrace doesn't /// play well with green threads, so while it is extremely nice /// and simple to use it should be used only on iOS devices as the /// only viable option. #[cfg(all(target_os = "ios", target_arch = "arm"))] #[inline(never)] pub fn write(w: &mut Write) -> io::Result<()> { extern { fn backtrace(buf: *mut *mut libc::c_void, sz: libc::c_int) -> libc::c_int; } // while it doesn't requires lock for work as everything is // local, it still displays much nicer backtraces when a // couple of threads panic simultaneously static LOCK: StaticMutex = StaticMutex::new(); let _g = LOCK.lock(); try!(writeln!(w, "stack backtrace:")); // 100 lines should be enough const SIZE: usize = 100; let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()}; let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as usize}; // skipping the first one as it is write itself for i in 1..cnt { try!(print(w, i as isize, buf[i], buf[i])) } Ok(()) } #[cfg(not(all(target_os = "ios", target_arch = "arm")))] #[inline(never)] // if we know this is a function call, we can skip it when // tracing pub fn write(w: &mut Write) -> io::Result<()> { struct Context<'a> { idx: isize, writer: &'a mut (Write+'a), last_error: Option<io::Error>, } // When using libbacktrace, we use some necessary global state, so we // need to prevent more than one thread from entering this block. This // is semi-reasonable in terms of printing anyway, and we know that all // I/O done here is blocking I/O, not green I/O, so we don't have to // worry about this being a native vs green mutex. static LOCK: StaticMutex = StaticMutex::new(); let _g = LOCK.lock(); try!(writeln!(w, "stack backtrace:")); let mut cx = Context { writer: w, last_error: None, idx: 0 }; return match unsafe { uw::_Unwind_Backtrace(trace_fn, &mut cx as *mut Context as *mut libc::c_void) } { uw::_URC_NO_REASON => { match cx.last_error { Some(err) => Err(err), None => Ok(()) } } _ => Ok(()), }; extern fn trace_fn(ctx: *mut uw::_Unwind_Context, arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code { let cx: &mut Context = unsafe { &mut *(arg as *mut Context) }; let mut ip_before_insn = 0; let mut ip = unsafe { uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void }; if !ip.is_null() && ip_before_insn == 0
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and // it appears to work fine without it, so we only use // FindEnclosingFunction on non-osx platforms. In doing so, we get a // slightly more accurate stack trace in the process. // // This is often because panic involves the last instruction of a // function being "call std::rt::begin_unwind", with no ret // instructions after it. This means that the return instruction // pointer points *outside* of the calling function, and by // unwinding it we go back to the original function. let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") { ip } else { unsafe { uw::_Unwind_FindEnclosingFunction(ip) } }; // Don't print out the first few frames (they're not user frames) cx.idx += 1; if cx.idx <= 0 { return uw::_URC_NO_REASON } // Don't print ginormous backtraces if cx.idx > 100 { match write!(cx.writer, " ... <frames omitted>\n") { Ok(()) => {} Err(e) => { cx.last_error = Some(e); } } return uw::_URC_FAILURE } // Once we hit an error, stop trying to print more frames if cx.last_error.is_some() { return uw::_URC_FAILURE } match print(cx.writer, cx.idx, ip, symaddr) { Ok(()) => {} Err(e) => { cx.last_error = Some(e); } } // keep going return uw::_URC_NO_REASON } } #[cfg(any(target_os = "macos", target_os = "ios"))] fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void, _symaddr: *mut libc::c_void) -> io::Result<()> { use intrinsics; #[repr(C)] struct Dl_info { dli_fname: *const libc::c_char, dli_fbase: *mut libc::c_void, dli_sname: *const libc::c_char, dli_saddr: *mut libc::c_void, } extern { fn dladdr(addr: *const libc::c_void, info: *mut Dl_info) -> libc::c_int; } let mut info: Dl_info = unsafe { intrinsics::init() }; if unsafe { dladdr(addr, &mut info) == 0 } { output(w, idx,addr, None) } else { output(w, idx, addr, Some(unsafe { CStr::from_ptr(info.dli_sname).to_bytes() })) } } #[cfg(not(any(target_os = "macos", target_os = "ios")))] fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void, symaddr: *mut libc::c_void) -> io::Result<()> { use env; use os::unix::prelude::*; use ptr; //////////////////////////////////////////////////////////////////////// // libbacktrace.h API //////////////////////////////////////////////////////////////////////// type backtrace_syminfo_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, symname: *const libc::c_char, symval: libc::uintptr_t, symsize: libc::uintptr_t); type backtrace_full_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, filename: *const libc::c_char, lineno: libc::c_int, function: *const libc::c_char) -> libc::c_int; type backtrace_error_callback = extern "C" fn(data: *mut libc::c_void, msg: *const libc::c_char, errnum: libc::c_int); enum backtrace_state {} #[link(name = "backtrace", kind = "static")] #[cfg(not(test))] extern {} extern { fn backtrace_create_state(filename: *const libc::c_char, threaded: libc::c_int, error: backtrace_error_callback, data: *mut libc::c_void) -> *mut backtrace_state; fn backtrace_syminfo(state: *mut backtrace_state, addr: libc::uintptr_t, cb: backtrace_syminfo_callback, error: backtrace_error_callback, data: *mut libc::c_void) -> libc::c_int; fn backtrace_pcinfo(state: *mut backtrace_state, addr: libc::uintptr_t, cb: backtrace_full_callback, error: backtrace_error_callback, data: *mut libc::c_void) -> libc::c_int; } //////////////////////////////////////////////////////////////////////// // helper callbacks //////////////////////////////////////////////////////////////////////// type FileLine = (*const libc::c_char, libc::c_int); extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char, _errnum: libc::c_int) { // do nothing for now } extern fn syminfo_cb(data: *mut libc::c_void, _pc: libc::uintptr_t, symname: *const libc::c_char, _symval: libc::uintptr_t, _sy
{ // this is a non-signaling frame, so `ip` refers to the address // after the calling instruction. account for that. ip = (ip as usize - 1) as *mut _; }
conditional_block
mod.rs
//! Two sample Kolmogorov-Smirnov test. /// Two sample test result. pub struct TestResult { pub is_rejected: bool, pub statistic: f64, pub reject_probability: f64, pub critical_value: f64, pub confidence: f64, } /// Perform a two sample Kolmogorov-Smirnov test on given samples. /// /// The samples must have length > 7 elements for the test to be valid. /// /// # Panics /// /// There are assertion panics if either sequence has <= 7 elements or /// if the requested confidence level is not between 0 and 1. /// /// # Examples /// /// ``` /// extern crate kernel_density; /// /// let xs = vec!(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0); /// let ys = vec!(12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0); /// let confidence = 0.95; /// /// let result = kernel_density::kolmogorov_smirnov::test(&xs, &ys, confidence); /// /// if result.is_rejected { /// println!("{:?} and {:?} are not from the same distribution with probability {}.", /// xs, ys, result.reject_probability); /// } /// ``` pub fn test(xs: &[f64], ys: &[f64], confidence: f64) -> TestResult { assert!(0.0 < confidence && confidence < 1.0); // Only supports samples of size > 7. assert!(xs.len() > 7 && ys.len() > 7); let statistic = calculate_statistic(xs, ys); let critical_value = calculate_critical_value(xs.len(), ys.len(), confidence); let reject_probability = calculate_reject_probability(statistic, xs.len(), ys.len()); let is_rejected = reject_probability > confidence; TestResult { is_rejected: is_rejected, statistic: statistic, reject_probability: reject_probability, critical_value: critical_value, confidence: confidence, } } /// Calculate the test statistic for the two sample Kolmogorov-Smirnov test. /// /// The test statistic is the maximum vertical distance between the ECDFs of /// the two samples. fn calculate_statistic(xs: &[f64], ys: &[f64]) -> f64 { let n = xs.len(); let m = ys.len(); assert!(n > 0 && m > 0); let mut xs = xs.to_vec(); let mut ys = ys.to_vec(); // xs and ys must be sorted for the stepwise ECDF calculations to work. xs.sort_by(|x_1, x_2| x_1.partial_cmp(x_2).unwrap()); ys.sort_by(|y_1, y_2| y_1.partial_cmp(y_2).unwrap()); // The current value testing for ECDF difference. Sweeps up through elements // present in xs and ys. let mut current: f64; // i, j index the first values in xs and ys that are greater than current. let mut i = 0; let mut j = 0; // ecdf_xs, ecdf_ys always hold the ECDF(current) of xs and ys. let mut ecdf_xs = 0.0; let mut ecdf_ys = 0.0; // The test statistic value computed over values <= current. let mut statistic = 0.0; while i < n && j < m { // Advance i through duplicate samples in xs. let x_i = xs[i]; while i + 1 < n && x_i == xs[i + 1] { i += 1; } // Advance j through duplicate samples in ys. let y_j = ys[j]; while j + 1 < m && y_j == ys[j + 1] { j += 1; } // Step to the next sample value in the ECDF sweep from low to high. current = x_i.min(y_j); // Update invariant conditions for i, j, ecdf_xs, and ecdf_ys. if current == x_i { ecdf_xs = (i + 1) as f64 / n as f64; i += 1; } if current == y_j { ecdf_ys = (j + 1) as f64 / m as f64; j += 1; } // Update invariant conditions for the test statistic. let diff = (ecdf_xs - ecdf_ys).abs(); if diff > statistic { statistic = diff; } } // Don't need to walk the rest of the samples because one of the ecdfs is // already one and the other will be increasing up to one. This means the // difference will be monotonically decreasing, so we have our test // statistic value already. statistic } /// Calculate the probability that the null hypothesis is false for a two sample /// Kolmogorov-Smirnov test. Can only reject the null hypothesis if this /// evidence exceeds the confidence level required. fn calculate_reject_probability(statistic: f64, n1: usize, n2: usize) -> f64 { // Only supports samples of size > 7. assert!(n1 > 7 && n2 > 7); let n1 = n1 as f64; let n2 = n2 as f64; let factor = ((n1 * n2) / (n1 + n2)).sqrt(); let term = (factor + 0.12 + 0.11 / factor) * statistic; let reject_probability = 1.0 - probability_kolmogorov_smirnov(term); assert!(0.0 <= reject_probability && reject_probability <= 1.0); reject_probability } /// Calculate the critical value for the two sample Kolmogorov-Smirnov test. /// /// # Panics /// /// There are assertion panics if either sequence size is <= 7 or if the /// requested confidence level is not between 0 and 1. /// /// No convergence panic if the binary search does not locate the critical /// value in less than 200 iterations. /// /// # Examples /// /// ``` /// extern crate kernel_density; /// /// let critical_value = kernel_density::kolmogorov_smirnov::calculate_critical_value( /// 256, 256, 0.95); /// println!("Critical value at 95% confidence for samples of size 256 is {}", /// critical_value); /// ``` pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 { assert!(0.0 < confidence && confidence < 1.0); // Only supports samples of size > 7. assert!(n1 > 7 && n2 > 7); // The test statistic is between zero and one so can binary search quickly // for the critical value. let mut low = 0.0; let mut high = 1.0; for _ in 1..200 { if low + 1e-8 >= high { return high; } let mid = low + (high - low) / 2.0; let reject_probability = calculate_reject_probability(mid, n1, n2); if reject_probability > confidence
else { // Maintain invariant that reject_probability(low) <= confidence. low = mid; } } panic!("No convergence in calculate_critical_value({}, {}, {}).", n1, n2, confidence); } /// Calculate the Kolmogorov-Smirnov probability function. fn probability_kolmogorov_smirnov(lambda: f64) -> f64 { if lambda == 0.0 { return 1.0; } let minus_two_lambda_squared = -2.0 * lambda * lambda; let mut q_ks = 0.0; for j in 1..200 { let sign = if j % 2 == 1 { 1.0 } else { -1.0 }; let j = j as f64; let term = sign * 2.0 * (minus_two_lambda_squared * j * j).exp(); q_ks += term; if term.abs() < 1e-8 { // Trim results that exceed 1. return q_ks.min(1.0); } } panic!("No convergence in probability_kolmogorov_smirnov({}).", lambda); }
{ // Maintain invariant that reject_probability(high) > confidence. high = mid; }
conditional_block
mod.rs
//! Two sample Kolmogorov-Smirnov test. /// Two sample test result. pub struct TestResult { pub is_rejected: bool, pub statistic: f64, pub reject_probability: f64, pub critical_value: f64, pub confidence: f64, } /// Perform a two sample Kolmogorov-Smirnov test on given samples. /// /// The samples must have length > 7 elements for the test to be valid. /// /// # Panics /// /// There are assertion panics if either sequence has <= 7 elements or /// if the requested confidence level is not between 0 and 1. /// /// # Examples /// /// ``` /// extern crate kernel_density; /// /// let xs = vec!(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0); /// let ys = vec!(12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0); /// let confidence = 0.95; /// /// let result = kernel_density::kolmogorov_smirnov::test(&xs, &ys, confidence); /// /// if result.is_rejected { /// println!("{:?} and {:?} are not from the same distribution with probability {}.", /// xs, ys, result.reject_probability); /// } /// ``` pub fn test(xs: &[f64], ys: &[f64], confidence: f64) -> TestResult { assert!(0.0 < confidence && confidence < 1.0); // Only supports samples of size > 7. assert!(xs.len() > 7 && ys.len() > 7); let statistic = calculate_statistic(xs, ys); let critical_value = calculate_critical_value(xs.len(), ys.len(), confidence); let reject_probability = calculate_reject_probability(statistic, xs.len(), ys.len()); let is_rejected = reject_probability > confidence; TestResult { is_rejected: is_rejected, statistic: statistic, reject_probability: reject_probability, critical_value: critical_value, confidence: confidence, } } /// Calculate the test statistic for the two sample Kolmogorov-Smirnov test. /// /// The test statistic is the maximum vertical distance between the ECDFs of /// the two samples. fn calculate_statistic(xs: &[f64], ys: &[f64]) -> f64 { let n = xs.len(); let m = ys.len(); assert!(n > 0 && m > 0); let mut xs = xs.to_vec(); let mut ys = ys.to_vec(); // xs and ys must be sorted for the stepwise ECDF calculations to work. xs.sort_by(|x_1, x_2| x_1.partial_cmp(x_2).unwrap()); ys.sort_by(|y_1, y_2| y_1.partial_cmp(y_2).unwrap()); // The current value testing for ECDF difference. Sweeps up through elements // present in xs and ys. let mut current: f64; // i, j index the first values in xs and ys that are greater than current. let mut i = 0; let mut j = 0; // ecdf_xs, ecdf_ys always hold the ECDF(current) of xs and ys. let mut ecdf_xs = 0.0; let mut ecdf_ys = 0.0; // The test statistic value computed over values <= current. let mut statistic = 0.0; while i < n && j < m { // Advance i through duplicate samples in xs. let x_i = xs[i]; while i + 1 < n && x_i == xs[i + 1] { i += 1; } // Advance j through duplicate samples in ys. let y_j = ys[j]; while j + 1 < m && y_j == ys[j + 1] { j += 1; } // Step to the next sample value in the ECDF sweep from low to high. current = x_i.min(y_j); // Update invariant conditions for i, j, ecdf_xs, and ecdf_ys. if current == x_i { ecdf_xs = (i + 1) as f64 / n as f64; i += 1; } if current == y_j { ecdf_ys = (j + 1) as f64 / m as f64; j += 1; } // Update invariant conditions for the test statistic. let diff = (ecdf_xs - ecdf_ys).abs(); if diff > statistic { statistic = diff; } } // Don't need to walk the rest of the samples because one of the ecdfs is // already one and the other will be increasing up to one. This means the // difference will be monotonically decreasing, so we have our test // statistic value already. statistic } /// Calculate the probability that the null hypothesis is false for a two sample /// Kolmogorov-Smirnov test. Can only reject the null hypothesis if this /// evidence exceeds the confidence level required. fn calculate_reject_probability(statistic: f64, n1: usize, n2: usize) -> f64 { // Only supports samples of size > 7. assert!(n1 > 7 && n2 > 7); let n1 = n1 as f64; let n2 = n2 as f64; let factor = ((n1 * n2) / (n1 + n2)).sqrt(); let term = (factor + 0.12 + 0.11 / factor) * statistic; let reject_probability = 1.0 - probability_kolmogorov_smirnov(term); assert!(0.0 <= reject_probability && reject_probability <= 1.0); reject_probability } /// Calculate the critical value for the two sample Kolmogorov-Smirnov test. /// /// # Panics /// /// There are assertion panics if either sequence size is <= 7 or if the /// requested confidence level is not between 0 and 1. /// /// No convergence panic if the binary search does not locate the critical /// value in less than 200 iterations. /// /// # Examples /// /// ``` /// extern crate kernel_density; /// /// let critical_value = kernel_density::kolmogorov_smirnov::calculate_critical_value( /// 256, 256, 0.95); /// println!("Critical value at 95% confidence for samples of size 256 is {}", /// critical_value); /// ``` pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64
// Maintain invariant that reject_probability(high) > confidence. high = mid; } else { // Maintain invariant that reject_probability(low) <= confidence. low = mid; } } panic!("No convergence in calculate_critical_value({}, {}, {}).", n1, n2, confidence); } /// Calculate the Kolmogorov-Smirnov probability function. fn probability_kolmogorov_smirnov(lambda: f64) -> f64 { if lambda == 0.0 { return 1.0; } let minus_two_lambda_squared = -2.0 * lambda * lambda; let mut q_ks = 0.0; for j in 1..200 { let sign = if j % 2 == 1 { 1.0 } else { -1.0 }; let j = j as f64; let term = sign * 2.0 * (minus_two_lambda_squared * j * j).exp(); q_ks += term; if term.abs() < 1e-8 { // Trim results that exceed 1. return q_ks.min(1.0); } } panic!("No convergence in probability_kolmogorov_smirnov({}).", lambda); }
{ assert!(0.0 < confidence && confidence < 1.0); // Only supports samples of size > 7. assert!(n1 > 7 && n2 > 7); // The test statistic is between zero and one so can binary search quickly // for the critical value. let mut low = 0.0; let mut high = 1.0; for _ in 1..200 { if low + 1e-8 >= high { return high; } let mid = low + (high - low) / 2.0; let reject_probability = calculate_reject_probability(mid, n1, n2); if reject_probability > confidence {
identifier_body
mod.rs
//! Two sample Kolmogorov-Smirnov test. /// Two sample test result. pub struct TestResult { pub is_rejected: bool, pub statistic: f64, pub reject_probability: f64, pub critical_value: f64, pub confidence: f64, } /// Perform a two sample Kolmogorov-Smirnov test on given samples. /// /// The samples must have length > 7 elements for the test to be valid. /// /// # Panics /// /// There are assertion panics if either sequence has <= 7 elements or /// if the requested confidence level is not between 0 and 1. /// /// # Examples /// /// ``` /// extern crate kernel_density; /// /// let xs = vec!(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0); /// let ys = vec!(12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0); /// let confidence = 0.95; /// /// let result = kernel_density::kolmogorov_smirnov::test(&xs, &ys, confidence); /// /// if result.is_rejected { /// println!("{:?} and {:?} are not from the same distribution with probability {}.", /// xs, ys, result.reject_probability); /// } /// ``` pub fn test(xs: &[f64], ys: &[f64], confidence: f64) -> TestResult { assert!(0.0 < confidence && confidence < 1.0); // Only supports samples of size > 7. assert!(xs.len() > 7 && ys.len() > 7); let statistic = calculate_statistic(xs, ys); let critical_value = calculate_critical_value(xs.len(), ys.len(), confidence); let reject_probability = calculate_reject_probability(statistic, xs.len(), ys.len()); let is_rejected = reject_probability > confidence; TestResult { is_rejected: is_rejected, statistic: statistic, reject_probability: reject_probability, critical_value: critical_value, confidence: confidence, } } /// Calculate the test statistic for the two sample Kolmogorov-Smirnov test. /// /// The test statistic is the maximum vertical distance between the ECDFs of /// the two samples. fn calculate_statistic(xs: &[f64], ys: &[f64]) -> f64 { let n = xs.len(); let m = ys.len(); assert!(n > 0 && m > 0); let mut xs = xs.to_vec(); let mut ys = ys.to_vec(); // xs and ys must be sorted for the stepwise ECDF calculations to work. xs.sort_by(|x_1, x_2| x_1.partial_cmp(x_2).unwrap()); ys.sort_by(|y_1, y_2| y_1.partial_cmp(y_2).unwrap()); // The current value testing for ECDF difference. Sweeps up through elements // present in xs and ys. let mut current: f64; // i, j index the first values in xs and ys that are greater than current. let mut i = 0; let mut j = 0; // ecdf_xs, ecdf_ys always hold the ECDF(current) of xs and ys. let mut ecdf_xs = 0.0; let mut ecdf_ys = 0.0; // The test statistic value computed over values <= current. let mut statistic = 0.0; while i < n && j < m { // Advance i through duplicate samples in xs. let x_i = xs[i]; while i + 1 < n && x_i == xs[i + 1] { i += 1; } // Advance j through duplicate samples in ys. let y_j = ys[j]; while j + 1 < m && y_j == ys[j + 1] { j += 1; } // Step to the next sample value in the ECDF sweep from low to high. current = x_i.min(y_j); // Update invariant conditions for i, j, ecdf_xs, and ecdf_ys. if current == x_i { ecdf_xs = (i + 1) as f64 / n as f64; i += 1; } if current == y_j { ecdf_ys = (j + 1) as f64 / m as f64; j += 1; } // Update invariant conditions for the test statistic. let diff = (ecdf_xs - ecdf_ys).abs(); if diff > statistic { statistic = diff; } } // Don't need to walk the rest of the samples because one of the ecdfs is // already one and the other will be increasing up to one. This means the // difference will be monotonically decreasing, so we have our test // statistic value already. statistic } /// Calculate the probability that the null hypothesis is false for a two sample /// Kolmogorov-Smirnov test. Can only reject the null hypothesis if this /// evidence exceeds the confidence level required. fn
(statistic: f64, n1: usize, n2: usize) -> f64 { // Only supports samples of size > 7. assert!(n1 > 7 && n2 > 7); let n1 = n1 as f64; let n2 = n2 as f64; let factor = ((n1 * n2) / (n1 + n2)).sqrt(); let term = (factor + 0.12 + 0.11 / factor) * statistic; let reject_probability = 1.0 - probability_kolmogorov_smirnov(term); assert!(0.0 <= reject_probability && reject_probability <= 1.0); reject_probability } /// Calculate the critical value for the two sample Kolmogorov-Smirnov test. /// /// # Panics /// /// There are assertion panics if either sequence size is <= 7 or if the /// requested confidence level is not between 0 and 1. /// /// No convergence panic if the binary search does not locate the critical /// value in less than 200 iterations. /// /// # Examples /// /// ``` /// extern crate kernel_density; /// /// let critical_value = kernel_density::kolmogorov_smirnov::calculate_critical_value( /// 256, 256, 0.95); /// println!("Critical value at 95% confidence for samples of size 256 is {}", /// critical_value); /// ``` pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 { assert!(0.0 < confidence && confidence < 1.0); // Only supports samples of size > 7. assert!(n1 > 7 && n2 > 7); // The test statistic is between zero and one so can binary search quickly // for the critical value. let mut low = 0.0; let mut high = 1.0; for _ in 1..200 { if low + 1e-8 >= high { return high; } let mid = low + (high - low) / 2.0; let reject_probability = calculate_reject_probability(mid, n1, n2); if reject_probability > confidence { // Maintain invariant that reject_probability(high) > confidence. high = mid; } else { // Maintain invariant that reject_probability(low) <= confidence. low = mid; } } panic!("No convergence in calculate_critical_value({}, {}, {}).", n1, n2, confidence); } /// Calculate the Kolmogorov-Smirnov probability function. fn probability_kolmogorov_smirnov(lambda: f64) -> f64 { if lambda == 0.0 { return 1.0; } let minus_two_lambda_squared = -2.0 * lambda * lambda; let mut q_ks = 0.0; for j in 1..200 { let sign = if j % 2 == 1 { 1.0 } else { -1.0 }; let j = j as f64; let term = sign * 2.0 * (minus_two_lambda_squared * j * j).exp(); q_ks += term; if term.abs() < 1e-8 { // Trim results that exceed 1. return q_ks.min(1.0); } } panic!("No convergence in probability_kolmogorov_smirnov({}).", lambda); }
calculate_reject_probability
identifier_name
mod.rs
//! Two sample Kolmogorov-Smirnov test. /// Two sample test result. pub struct TestResult { pub is_rejected: bool, pub statistic: f64, pub reject_probability: f64, pub critical_value: f64, pub confidence: f64, } /// Perform a two sample Kolmogorov-Smirnov test on given samples. /// /// The samples must have length > 7 elements for the test to be valid. /// /// # Panics /// /// There are assertion panics if either sequence has <= 7 elements or /// if the requested confidence level is not between 0 and 1. /// /// # Examples /// /// ``` /// extern crate kernel_density; /// /// let xs = vec!(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0); /// let ys = vec!(12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0); /// let confidence = 0.95; /// /// let result = kernel_density::kolmogorov_smirnov::test(&xs, &ys, confidence); /// /// if result.is_rejected { /// println!("{:?} and {:?} are not from the same distribution with probability {}.", /// xs, ys, result.reject_probability); /// } /// ``` pub fn test(xs: &[f64], ys: &[f64], confidence: f64) -> TestResult { assert!(0.0 < confidence && confidence < 1.0); // Only supports samples of size > 7. assert!(xs.len() > 7 && ys.len() > 7); let statistic = calculate_statistic(xs, ys); let critical_value = calculate_critical_value(xs.len(), ys.len(), confidence); let reject_probability = calculate_reject_probability(statistic, xs.len(), ys.len()); let is_rejected = reject_probability > confidence; TestResult { is_rejected: is_rejected, statistic: statistic, reject_probability: reject_probability, critical_value: critical_value, confidence: confidence, } } /// Calculate the test statistic for the two sample Kolmogorov-Smirnov test. /// /// The test statistic is the maximum vertical distance between the ECDFs of /// the two samples. fn calculate_statistic(xs: &[f64], ys: &[f64]) -> f64 { let n = xs.len(); let m = ys.len(); assert!(n > 0 && m > 0); let mut xs = xs.to_vec(); let mut ys = ys.to_vec(); // xs and ys must be sorted for the stepwise ECDF calculations to work. xs.sort_by(|x_1, x_2| x_1.partial_cmp(x_2).unwrap()); ys.sort_by(|y_1, y_2| y_1.partial_cmp(y_2).unwrap()); // The current value testing for ECDF difference. Sweeps up through elements // present in xs and ys. let mut current: f64; // i, j index the first values in xs and ys that are greater than current. let mut i = 0; let mut j = 0; // ecdf_xs, ecdf_ys always hold the ECDF(current) of xs and ys. let mut ecdf_xs = 0.0; let mut ecdf_ys = 0.0; // The test statistic value computed over values <= current. let mut statistic = 0.0; while i < n && j < m { // Advance i through duplicate samples in xs. let x_i = xs[i]; while i + 1 < n && x_i == xs[i + 1] { i += 1; } // Advance j through duplicate samples in ys. let y_j = ys[j]; while j + 1 < m && y_j == ys[j + 1] { j += 1; } // Step to the next sample value in the ECDF sweep from low to high. current = x_i.min(y_j); // Update invariant conditions for i, j, ecdf_xs, and ecdf_ys. if current == x_i { ecdf_xs = (i + 1) as f64 / n as f64; i += 1; } if current == y_j { ecdf_ys = (j + 1) as f64 / m as f64; j += 1; } // Update invariant conditions for the test statistic. let diff = (ecdf_xs - ecdf_ys).abs(); if diff > statistic { statistic = diff; } } // Don't need to walk the rest of the samples because one of the ecdfs is // already one and the other will be increasing up to one. This means the // difference will be monotonically decreasing, so we have our test // statistic value already. statistic } /// Calculate the probability that the null hypothesis is false for a two sample /// Kolmogorov-Smirnov test. Can only reject the null hypothesis if this /// evidence exceeds the confidence level required. fn calculate_reject_probability(statistic: f64, n1: usize, n2: usize) -> f64 { // Only supports samples of size > 7. assert!(n1 > 7 && n2 > 7); let n1 = n1 as f64; let n2 = n2 as f64; let factor = ((n1 * n2) / (n1 + n2)).sqrt(); let term = (factor + 0.12 + 0.11 / factor) * statistic; let reject_probability = 1.0 - probability_kolmogorov_smirnov(term); assert!(0.0 <= reject_probability && reject_probability <= 1.0); reject_probability } /// Calculate the critical value for the two sample Kolmogorov-Smirnov test. /// /// # Panics /// /// There are assertion panics if either sequence size is <= 7 or if the /// requested confidence level is not between 0 and 1. /// /// No convergence panic if the binary search does not locate the critical /// value in less than 200 iterations. /// /// # Examples /// /// ``` /// extern crate kernel_density; /// /// let critical_value = kernel_density::kolmogorov_smirnov::calculate_critical_value( /// 256, 256, 0.95); /// println!("Critical value at 95% confidence for samples of size 256 is {}", /// critical_value);
assert!(n1 > 7 && n2 > 7); // The test statistic is between zero and one so can binary search quickly // for the critical value. let mut low = 0.0; let mut high = 1.0; for _ in 1..200 { if low + 1e-8 >= high { return high; } let mid = low + (high - low) / 2.0; let reject_probability = calculate_reject_probability(mid, n1, n2); if reject_probability > confidence { // Maintain invariant that reject_probability(high) > confidence. high = mid; } else { // Maintain invariant that reject_probability(low) <= confidence. low = mid; } } panic!("No convergence in calculate_critical_value({}, {}, {}).", n1, n2, confidence); } /// Calculate the Kolmogorov-Smirnov probability function. fn probability_kolmogorov_smirnov(lambda: f64) -> f64 { if lambda == 0.0 { return 1.0; } let minus_two_lambda_squared = -2.0 * lambda * lambda; let mut q_ks = 0.0; for j in 1..200 { let sign = if j % 2 == 1 { 1.0 } else { -1.0 }; let j = j as f64; let term = sign * 2.0 * (minus_two_lambda_squared * j * j).exp(); q_ks += term; if term.abs() < 1e-8 { // Trim results that exceed 1. return q_ks.min(1.0); } } panic!("No convergence in probability_kolmogorov_smirnov({}).", lambda); }
/// ``` pub fn calculate_critical_value(n1: usize, n2: usize, confidence: f64) -> f64 { assert!(0.0 < confidence && confidence < 1.0); // Only supports samples of size > 7.
random_line_split
GenomeAFS.py
''' Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: [email protected] ''' import numpy as np; np.set_printoptions(linewidth=200, precision=5, suppress=True) import pandas as pd; pd.options.display.max_rows = 20; pd.options.display.expand_frame_repr = False import pylab as plt; import os; home = os.path.expanduser('~') + '/' import Utils.Estimate as est import Utils.Plots as pplt import Scripts.KyrgysHAPH.Utils as kutl import Scripts.KyrgysHAPH.Plot as kplt kplt.savefig() reload(est) a=pd.read_pickle(kutl.path+'/data/freq.df') def
(chrom=None): f=est.Estimate.getSAFS a=pd.read_pickle(kutl.path+'/data/freq.df') if chrom is not None: suff='.chr{}'.format(chrom) a=a.loc[[chrom]] kplt.plotSFSold2(a, fold=False, fname='AFS' + suff); kplt.plotSFSold2(a, fold=False, fname='Scaled-AFS' + suff, f=f) kplt.plotSFSold2(a, fold=True, fname='AFS' + suff, ); kplt.plotSFSold2(a, fold=True, fname='Scaled-AFS' + suff, f=f) def plotChromAll(): a.apply(lambda x: kplt.SFSChromosomwise(x, False, False)) a.apply(lambda x: kplt.SFSChromosomwise(x, False, True)) a.apply(lambda x: kplt.SFSChromosomwise(x, True, False)) a.apply(lambda x: kplt.SFSChromosomwise(x, True, True)) def SFS(): plotSFSall() plotSFSall('X') plotSFSall('Y') plotChromAll()
plotSFSall
identifier_name
GenomeAFS.py
''' Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: [email protected] ''' import numpy as np; np.set_printoptions(linewidth=200, precision=5, suppress=True) import pandas as pd; pd.options.display.max_rows = 20; pd.options.display.expand_frame_repr = False
home = os.path.expanduser('~') + '/' import Utils.Estimate as est import Utils.Plots as pplt import Scripts.KyrgysHAPH.Utils as kutl import Scripts.KyrgysHAPH.Plot as kplt kplt.savefig() reload(est) a=pd.read_pickle(kutl.path+'/data/freq.df') def plotSFSall(chrom=None): f=est.Estimate.getSAFS a=pd.read_pickle(kutl.path+'/data/freq.df') if chrom is not None: suff='.chr{}'.format(chrom) a=a.loc[[chrom]] kplt.plotSFSold2(a, fold=False, fname='AFS' + suff); kplt.plotSFSold2(a, fold=False, fname='Scaled-AFS' + suff, f=f) kplt.plotSFSold2(a, fold=True, fname='AFS' + suff, ); kplt.plotSFSold2(a, fold=True, fname='Scaled-AFS' + suff, f=f) def plotChromAll(): a.apply(lambda x: kplt.SFSChromosomwise(x, False, False)) a.apply(lambda x: kplt.SFSChromosomwise(x, False, True)) a.apply(lambda x: kplt.SFSChromosomwise(x, True, False)) a.apply(lambda x: kplt.SFSChromosomwise(x, True, True)) def SFS(): plotSFSall() plotSFSall('X') plotSFSall('Y') plotChromAll()
import pylab as plt; import os;
random_line_split
GenomeAFS.py
''' Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: [email protected] ''' import numpy as np; np.set_printoptions(linewidth=200, precision=5, suppress=True) import pandas as pd; pd.options.display.max_rows = 20; pd.options.display.expand_frame_repr = False import pylab as plt; import os; home = os.path.expanduser('~') + '/' import Utils.Estimate as est import Utils.Plots as pplt import Scripts.KyrgysHAPH.Utils as kutl import Scripts.KyrgysHAPH.Plot as kplt kplt.savefig() reload(est) a=pd.read_pickle(kutl.path+'/data/freq.df') def plotSFSall(chrom=None):
def plotChromAll(): a.apply(lambda x: kplt.SFSChromosomwise(x, False, False)) a.apply(lambda x: kplt.SFSChromosomwise(x, False, True)) a.apply(lambda x: kplt.SFSChromosomwise(x, True, False)) a.apply(lambda x: kplt.SFSChromosomwise(x, True, True)) def SFS(): plotSFSall() plotSFSall('X') plotSFSall('Y') plotChromAll()
f=est.Estimate.getSAFS a=pd.read_pickle(kutl.path+'/data/freq.df') if chrom is not None: suff='.chr{}'.format(chrom) a=a.loc[[chrom]] kplt.plotSFSold2(a, fold=False, fname='AFS' + suff); kplt.plotSFSold2(a, fold=False, fname='Scaled-AFS' + suff, f=f) kplt.plotSFSold2(a, fold=True, fname='AFS' + suff, ); kplt.plotSFSold2(a, fold=True, fname='Scaled-AFS' + suff, f=f)
identifier_body
GenomeAFS.py
''' Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: [email protected] ''' import numpy as np; np.set_printoptions(linewidth=200, precision=5, suppress=True) import pandas as pd; pd.options.display.max_rows = 20; pd.options.display.expand_frame_repr = False import pylab as plt; import os; home = os.path.expanduser('~') + '/' import Utils.Estimate as est import Utils.Plots as pplt import Scripts.KyrgysHAPH.Utils as kutl import Scripts.KyrgysHAPH.Plot as kplt kplt.savefig() reload(est) a=pd.read_pickle(kutl.path+'/data/freq.df') def plotSFSall(chrom=None): f=est.Estimate.getSAFS a=pd.read_pickle(kutl.path+'/data/freq.df') if chrom is not None:
kplt.plotSFSold2(a, fold=False, fname='AFS' + suff); kplt.plotSFSold2(a, fold=False, fname='Scaled-AFS' + suff, f=f) kplt.plotSFSold2(a, fold=True, fname='AFS' + suff, ); kplt.plotSFSold2(a, fold=True, fname='Scaled-AFS' + suff, f=f) def plotChromAll(): a.apply(lambda x: kplt.SFSChromosomwise(x, False, False)) a.apply(lambda x: kplt.SFSChromosomwise(x, False, True)) a.apply(lambda x: kplt.SFSChromosomwise(x, True, False)) a.apply(lambda x: kplt.SFSChromosomwise(x, True, True)) def SFS(): plotSFSall() plotSFSall('X') plotSFSall('Y') plotChromAll()
suff='.chr{}'.format(chrom) a=a.loc[[chrom]]
conditional_block
Cert_5_1_06_RemoveRouterId.py
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # 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. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. # import unittest import command import mle import thread_cert from command import CheckType LEADER = 1 ROUTER1 = 2 class
(thread_cert.TestCase): TOPOLOGY = { LEADER: { 'mode': 'rsdn', 'panid': 0xface, 'whitelist': [ROUTER1] }, ROUTER1: { 'mode': 'rsdn', 'panid': 0xface, 'router_selection_jitter': 1, 'whitelist': [LEADER] }, } def test(self): self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[ROUTER1].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') rloc16 = self.nodes[ROUTER1].get_addr16() for addr in self.nodes[ROUTER1].get_addrs(): self.assertTrue(self.nodes[LEADER].ping(addr)) self.nodes[LEADER].release_router_id(rloc16 >> 10) self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') leader_messages = self.simulator.get_messages_sent_by(LEADER) router1_messages = self.simulator.get_messages_sent_by(ROUTER1) # 1 - All leader_messages.next_mle_message(mle.CommandType.ADVERTISEMENT) router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) leader_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) router1_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg = router1_messages.next_coap_message("0.02") msg.assertCoapMessageRequestUriPath("/a/as") leader_messages.next_coap_message("2.04") # 2 - N/A # 3 - Router1 msg = router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) command.check_parent_request(msg, is_first_request=True) msg = router1_messages.next_mle_message( mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[LEADER]) command.check_child_id_request( msg, tlv_request=CheckType.CONTAIN, mle_frame_counter=CheckType.OPTIONAL, address_registration=CheckType.NOT_CONTAIN, active_timestamp=CheckType.OPTIONAL, pending_timestamp=CheckType.OPTIONAL, ) msg = router1_messages.next_coap_message(code="0.02") command.check_address_solicit(msg, was_router=True) # 4 - Router1 for addr in self.nodes[ROUTER1].get_addrs(): self.assertTrue(self.nodes[LEADER].ping(addr)) if __name__ == '__main__': unittest.main()
Cert_5_1_06_RemoveRouterId
identifier_name
Cert_5_1_06_RemoveRouterId.py
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # 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. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. # import unittest import command import mle import thread_cert from command import CheckType LEADER = 1 ROUTER1 = 2 class Cert_5_1_06_RemoveRouterId(thread_cert.TestCase): TOPOLOGY = { LEADER: { 'mode': 'rsdn', 'panid': 0xface, 'whitelist': [ROUTER1] }, ROUTER1: { 'mode': 'rsdn', 'panid': 0xface, 'router_selection_jitter': 1, 'whitelist': [LEADER] }, } def test(self): self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[ROUTER1].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') rloc16 = self.nodes[ROUTER1].get_addr16() for addr in self.nodes[ROUTER1].get_addrs(): self.assertTrue(self.nodes[LEADER].ping(addr)) self.nodes[LEADER].release_router_id(rloc16 >> 10) self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') leader_messages = self.simulator.get_messages_sent_by(LEADER) router1_messages = self.simulator.get_messages_sent_by(ROUTER1) # 1 - All leader_messages.next_mle_message(mle.CommandType.ADVERTISEMENT) router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) leader_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) router1_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg = router1_messages.next_coap_message("0.02") msg.assertCoapMessageRequestUriPath("/a/as") leader_messages.next_coap_message("2.04") # 2 - N/A # 3 - Router1 msg = router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) command.check_parent_request(msg, is_first_request=True) msg = router1_messages.next_mle_message( mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[LEADER]) command.check_child_id_request( msg, tlv_request=CheckType.CONTAIN, mle_frame_counter=CheckType.OPTIONAL, address_registration=CheckType.NOT_CONTAIN, active_timestamp=CheckType.OPTIONAL, pending_timestamp=CheckType.OPTIONAL, )
msg = router1_messages.next_coap_message(code="0.02") command.check_address_solicit(msg, was_router=True) # 4 - Router1 for addr in self.nodes[ROUTER1].get_addrs(): self.assertTrue(self.nodes[LEADER].ping(addr)) if __name__ == '__main__': unittest.main()
random_line_split
Cert_5_1_06_RemoveRouterId.py
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # 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. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. # import unittest import command import mle import thread_cert from command import CheckType LEADER = 1 ROUTER1 = 2 class Cert_5_1_06_RemoveRouterId(thread_cert.TestCase): TOPOLOGY = { LEADER: { 'mode': 'rsdn', 'panid': 0xface, 'whitelist': [ROUTER1] }, ROUTER1: { 'mode': 'rsdn', 'panid': 0xface, 'router_selection_jitter': 1, 'whitelist': [LEADER] }, } def test(self): self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[ROUTER1].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') rloc16 = self.nodes[ROUTER1].get_addr16() for addr in self.nodes[ROUTER1].get_addrs(): self.assertTrue(self.nodes[LEADER].ping(addr)) self.nodes[LEADER].release_router_id(rloc16 >> 10) self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') leader_messages = self.simulator.get_messages_sent_by(LEADER) router1_messages = self.simulator.get_messages_sent_by(ROUTER1) # 1 - All leader_messages.next_mle_message(mle.CommandType.ADVERTISEMENT) router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) leader_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) router1_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg = router1_messages.next_coap_message("0.02") msg.assertCoapMessageRequestUriPath("/a/as") leader_messages.next_coap_message("2.04") # 2 - N/A # 3 - Router1 msg = router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) command.check_parent_request(msg, is_first_request=True) msg = router1_messages.next_mle_message( mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[LEADER]) command.check_child_id_request( msg, tlv_request=CheckType.CONTAIN, mle_frame_counter=CheckType.OPTIONAL, address_registration=CheckType.NOT_CONTAIN, active_timestamp=CheckType.OPTIONAL, pending_timestamp=CheckType.OPTIONAL, ) msg = router1_messages.next_coap_message(code="0.02") command.check_address_solicit(msg, was_router=True) # 4 - Router1 for addr in self.nodes[ROUTER1].get_addrs():
if __name__ == '__main__': unittest.main()
self.assertTrue(self.nodes[LEADER].ping(addr))
conditional_block
Cert_5_1_06_RemoveRouterId.py
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # 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. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. # import unittest import command import mle import thread_cert from command import CheckType LEADER = 1 ROUTER1 = 2 class Cert_5_1_06_RemoveRouterId(thread_cert.TestCase): TOPOLOGY = { LEADER: { 'mode': 'rsdn', 'panid': 0xface, 'whitelist': [ROUTER1] }, ROUTER1: { 'mode': 'rsdn', 'panid': 0xface, 'router_selection_jitter': 1, 'whitelist': [LEADER] }, } def test(self):
leader_messages.next_mle_message(mle.CommandType.ADVERTISEMENT) router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) leader_messages.next_mle_message(mle.CommandType.PARENT_RESPONSE) router1_messages.next_mle_message(mle.CommandType.CHILD_ID_REQUEST) leader_messages.next_mle_message(mle.CommandType.CHILD_ID_RESPONSE) msg = router1_messages.next_coap_message("0.02") msg.assertCoapMessageRequestUriPath("/a/as") leader_messages.next_coap_message("2.04") # 2 - N/A # 3 - Router1 msg = router1_messages.next_mle_message(mle.CommandType.PARENT_REQUEST) command.check_parent_request(msg, is_first_request=True) msg = router1_messages.next_mle_message( mle.CommandType.CHILD_ID_REQUEST, sent_to_node=self.nodes[LEADER]) command.check_child_id_request( msg, tlv_request=CheckType.CONTAIN, mle_frame_counter=CheckType.OPTIONAL, address_registration=CheckType.NOT_CONTAIN, active_timestamp=CheckType.OPTIONAL, pending_timestamp=CheckType.OPTIONAL, ) msg = router1_messages.next_coap_message(code="0.02") command.check_address_solicit(msg, was_router=True) # 4 - Router1 for addr in self.nodes[ROUTER1].get_addrs(): self.assertTrue(self.nodes[LEADER].ping(addr)) if __name__ == '__main__': unittest.main()
self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[ROUTER1].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') rloc16 = self.nodes[ROUTER1].get_addr16() for addr in self.nodes[ROUTER1].get_addrs(): self.assertTrue(self.nodes[LEADER].ping(addr)) self.nodes[LEADER].release_router_id(rloc16 >> 10) self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') leader_messages = self.simulator.get_messages_sent_by(LEADER) router1_messages = self.simulator.get_messages_sent_by(ROUTER1) # 1 - All
identifier_body
types.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants; use canvas_traits::gl_enums; gl_enums! { pub enum TexImageTarget { Texture2D = WebGLRenderingContextConstants::TEXTURE_2D, CubeMapPositiveX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_X, CubeMapNegativeX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_X, CubeMapPositiveY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Y, CubeMapNegativeY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Y, CubeMapPositiveZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Z, CubeMapNegativeZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Z, } } impl TexImageTarget { pub fn
(&self) -> bool { match *self { TexImageTarget::Texture2D => false, _ => true, } } }
is_cubic
identifier_name
types.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants; use canvas_traits::gl_enums; gl_enums! { pub enum TexImageTarget { Texture2D = WebGLRenderingContextConstants::TEXTURE_2D, CubeMapPositiveX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_X, CubeMapNegativeX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_X, CubeMapPositiveY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Y, CubeMapNegativeY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Y, CubeMapPositiveZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Z, CubeMapNegativeZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Z, } } impl TexImageTarget { pub fn is_cubic(&self) -> bool
}
{ match *self { TexImageTarget::Texture2D => false, _ => true, } }
identifier_body
types.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants; use canvas_traits::gl_enums; gl_enums! { pub enum TexImageTarget { Texture2D = WebGLRenderingContextConstants::TEXTURE_2D, CubeMapPositiveX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_X, CubeMapNegativeX = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_X, CubeMapPositiveY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Y, CubeMapNegativeY = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Y, CubeMapPositiveZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_POSITIVE_Z, CubeMapNegativeZ = WebGLRenderingContextConstants::TEXTURE_CUBE_MAP_NEGATIVE_Z, } } impl TexImageTarget {
TexImageTarget::Texture2D => false, _ => true, } } }
pub fn is_cubic(&self) -> bool { match *self {
random_line_split
hdfs_command.py
pyox hdfs ls',description="ls") lsparser.add_argument( '-b', action='store_true', dest='reportbytes', default=False, help="Report sizes in bytes") lsparser.add_argument( '-l', action='store_true', dest='detailed', default=False, help="List details") lsparser.add_argument( 'paths', nargs='*', help='a list of paths') lsargs = lsparser.parse_args(argv) if len(lsargs.paths)==0: lsargs.paths = ['/'] for path in lsargs.paths: listing = client.list_directory(path) max = 0; for name in sorted(listing): if len(name)>max: max = len(name) for name in sorted(listing): if not lsargs.detailed: print(name) continue info = listing[name] if name=='': name = path[path.rfind('/')+1:] max = len(name) ftype = info['type'] size = int(info['length']) modtime = datetime.fromtimestamp(int(info['modificationTime'])/1e3) fspec = '{:'+str(max)+'}\t{}\t{}' fsize = '0' if ftype=='DIRECTORY': name = name + '/' else: if lsargs.reportbytes or size<1024: fsize = str(size)+'B' elif size<1048576: fsize = '{:0.1f}KB'.format(size/1024) elif size<1073741824: fsize = '{:0.1f}MB'.format(size/1024/1024) else: fsize = '{:0.1f}GB'.format(size/1024/1024/1024) print(fspec.format(name,fsize,modtime.isoformat())) def hdfs_cat_command(client,argv): catparser = argparse.ArgumentParser(prog='pyox hdfs cat',description="cat") catparser.add_argument( '--offset', type=int, metavar=('int'), help="a byte offset for the file") catparser.add_argument( '--length', type=int, metavar=('int'), help="the byte length to retrieve") catparser.add_argument( 'paths', nargs='*', help='a list of paths') args = catparser.parse_args(argv) for path in args.paths: input = client.open(path,offset=args.offset,length=args.length) for chunk in input: sys.stdout.buffer.write(chunk) def hdfs_download_command(client,argv): dlparser = argparse.ArgumentParser(prog='pyox hdfs download',description="download") dlparser.add_argument( '--chunk-size', dest='chunk_size', type=int, metavar=('int'), help="The chunk size for the download") dlparser.add_argument( '-o','--output', dest='output', metavar=('file'), help="the output file") dlparser.add_argument( '-v', action='store_true', dest='verbose', default=False, help="Verbose") dlparser.add_argument( 'source', help='the remote source') args = dlparser.parse_args(argv) destination = args.output if destination is None: last = args.source.rfind('/') destination = args.source[last+1:] if last>=0 else args.source if args.chunk_size is not None: info = client.status(args.source) remaining = info['length'] offset = 0 chunk = 0 chunks = ceil(remaining/args.chunk_size) if args.verbose: sys.stderr.write('File size: {}\n'.format(remaining)) with open(destination,'wb') as output: while remaining>0: chunk += 1 if args.verbose: sys.stderr.write('Downloading chunk {}/{} '.format(chunk,chunks)) sys.stderr.flush() length = args.chunk_size if remaining>args.chunk_size else remaining input = client.open(args.source,offset=offset,length=length) for data in input: output.write(data) if args.verbose: sys.stderr.write('.') sys.stderr.flush() output.flush() if args.verbose: sys.stderr.write('\n') sys.stderr.flush() remaining -= length offset += length else: input = client.open(args.source) with open(destination,'wb') as output: for chunk in input: output.write(chunk) def hdfs_mkdir_command(client,argv): for path in argv: if not client.make_directory(path): raise ServiceError(403,'mkdir failed: {}'.format(path)) def hdfs_mv_command(client,argv): if len(argv)!=3: sys.stderr.write('Invalid number of arguments: {}'.format(len(args.command)-1)) if not client.mv(argv[0],argv[1]): raise ServiceError(403,'Move failed: {} → {}'.format(argv[0],argv[1])) def hd
lient,argv): rmparser = argparse.ArgumentParser(prog='pyox hdfs rm',description="rm") rmparser.add_argument( '-r', action='store_true', dest='recursive', default=False, help="Recursively remove files/directories") rmparser.add_argument( 'paths', nargs='*', help='a list of paths') rmargs = rmparser.parse_args(argv) for path in rmargs.paths: if not client.remove(path,recursive=rmargs.recursive): raise ServiceError(403,'Cannot remove: {}'.format(path)) def copy_to_destination(client,source,destpath,verbose=False,force=False): size = os.path.getsize(source) targetpath = source slash = source.rfind('/') if source[0]=='/': targetpath = source[slash+1:] elif source[0:3]=='../': targetpath = source[slash+1:] elif slash > 0 : dirpath = source[0:slash] if dirpath not in mkdirs.values: if cpargs.verbose: sys.stderr.write(dirpath+'/\n') if client.make_directory(destpath+dirpath): mkdirs.add(dirpath) else: raise ServiceError(403,'Cannot make target directory: {}'.format(dirpath)) target = destpath + targetpath if verbose: sys.stderr.write(source+' → '+target+'\n') with open(source,'rb') as input: def chunker(): sent =0 while True: b = input.read(32768) sent += len(b) if not b: if cpargs.verbose: sys.stderr.write('Sent {} bytes\n'.format(sent)) break yield b if not client.copy(chunker() if size<0 else input,target,size=size,overwrite=force): raise ServiceError(403,'Move failed: {} → {}'.format(source,target)) def hdfs_cp_command(client,argv): cpparser = argparse.ArgumentParser(prog='pyox hdfs cp',description="cp") cpparser.add_argument( '-f', action='store_true', dest='force', default=False, help="Force an overwrite") cpparser.add_argument( '-v', action='store_true', dest='verbose', default=False, help="Verbose") cpparser.add_argument( '-r', action='store_true', dest='recursive', default=False, help="Recursively apply wildcards") cpparser.add_argument( '-s', action='store_true', dest='sendsize', default=False, help="Send the file size") cpparser.add_argument( 'paths', nargs='*', help='a list of paths') cpargs = cpparser.parse_args(argv) if len(cpargs.paths)<2: sys.stderr.write('At least two paths must be specified.\n') sys.exit(1) destpath = cpargs.paths[-1] if destpath[-1]=='/': # directory copy, glob files mkdirs = tracker() for pattern in cpargs.paths[:-1]: if isfile(pattern): copy_to_destination(client,pattern,destpath,verbose=cpargs.verbose,force=cpargs.force) else: files = glob(pattern,recursive=cpargs.recursive) if len(files)==0 and cpargs.verbose: sys.stderr.write('Nothing matched {}\n'.format(pattern)) for source in files: copy_to_destination(client,source,destpath,verbose=cpargs.verbose,force=cpargs.force) elif len(cpargs.paths)==2: source = cpargs.paths[0] size = os.path.getsize(source) if cpargs.sendsize else -1 with open(source,'rb') as input: if cpargs.verbose: sys.stderr.write(source+' → '+destpath+'\n') if not client.copy(input,destpath,size=size,overwrite=cpargs.force): raise ServiceError(403,'Move failed: {} → {}'.format(source,destpath)) else: raise ServiceError(400,'Target is not a directory.') hdfs_commands = { 'ls
fs_rm_command(c
identifier_name
hdfs_command.py
='pyox hdfs ls',description="ls") lsparser.add_argument( '-b', action='store_true', dest='reportbytes', default=False, help="Report sizes in bytes") lsparser.add_argument( '-l', action='store_true', dest='detailed', default=False, help="List details") lsparser.add_argument( 'paths', nargs='*', help='a list of paths') lsargs = lsparser.parse_args(argv) if len(lsargs.paths)==0: lsargs.paths = ['/'] for path in lsargs.paths: listing = client.list_directory(path) max = 0; for name in sorted(listing): if len(name)>max: max = len(name) for name in sorted(listing): if not lsargs.detailed: print(name) continue info = listing[name] if name=='': name = path[path.rfind('/')+1:] max = len(name) ftype = info['type'] size = int(info['length']) modtime = datetime.fromtimestamp(int(info['modificationTime'])/1e3) fspec = '{:'+str(max)+'}\t{}\t{}' fsize = '0' if ftype=='DIRECTORY': name = name + '/' else: if lsargs.reportbytes or size<1024: fsize = str(size)+'B' elif size<1048576: fsize = '{:0.1f}KB'.format(size/1024) elif size<1073741824: fsize = '{:0.1f}MB'.format(size/1024/1024) else: fsize = '{:0.1f}GB'.format(size/1024/1024/1024) print(fspec.format(name,fsize,modtime.isoformat())) def hdfs_cat_command(client,argv): catparser = argparse.ArgumentParser(prog='pyox hdfs cat',description="cat") catparser.add_argument( '--offset', type=int, metavar=('int'), help="a byte offset for the file") catparser.add_argument( '--length', type=int, metavar=('int'),
help='a list of paths') args = catparser.parse_args(argv) for path in args.paths: input = client.open(path,offset=args.offset,length=args.length) for chunk in input: sys.stdout.buffer.write(chunk) def hdfs_download_command(client,argv): dlparser = argparse.ArgumentParser(prog='pyox hdfs download',description="download") dlparser.add_argument( '--chunk-size', dest='chunk_size', type=int, metavar=('int'), help="The chunk size for the download") dlparser.add_argument( '-o','--output', dest='output', metavar=('file'), help="the output file") dlparser.add_argument( '-v', action='store_true', dest='verbose', default=False, help="Verbose") dlparser.add_argument( 'source', help='the remote source') args = dlparser.parse_args(argv) destination = args.output if destination is None: last = args.source.rfind('/') destination = args.source[last+1:] if last>=0 else args.source if args.chunk_size is not None: info = client.status(args.source) remaining = info['length'] offset = 0 chunk = 0 chunks = ceil(remaining/args.chunk_size) if args.verbose: sys.stderr.write('File size: {}\n'.format(remaining)) with open(destination,'wb') as output: while remaining>0: chunk += 1 if args.verbose: sys.stderr.write('Downloading chunk {}/{} '.format(chunk,chunks)) sys.stderr.flush() length = args.chunk_size if remaining>args.chunk_size else remaining input = client.open(args.source,offset=offset,length=length) for data in input: output.write(data) if args.verbose: sys.stderr.write('.') sys.stderr.flush() output.flush() if args.verbose: sys.stderr.write('\n') sys.stderr.flush() remaining -= length offset += length else: input = client.open(args.source) with open(destination,'wb') as output: for chunk in input: output.write(chunk) def hdfs_mkdir_command(client,argv): for path in argv: if not client.make_directory(path): raise ServiceError(403,'mkdir failed: {}'.format(path)) def hdfs_mv_command(client,argv): if len(argv)!=3: sys.stderr.write('Invalid number of arguments: {}'.format(len(args.command)-1)) if not client.mv(argv[0],argv[1]): raise ServiceError(403,'Move failed: {} → {}'.format(argv[0],argv[1])) def hdfs_rm_command(client,argv): rmparser = argparse.ArgumentParser(prog='pyox hdfs rm',description="rm") rmparser.add_argument( '-r', action='store_true', dest='recursive', default=False, help="Recursively remove files/directories") rmparser.add_argument( 'paths', nargs='*', help='a list of paths') rmargs = rmparser.parse_args(argv) for path in rmargs.paths: if not client.remove(path,recursive=rmargs.recursive): raise ServiceError(403,'Cannot remove: {}'.format(path)) def copy_to_destination(client,source,destpath,verbose=False,force=False): size = os.path.getsize(source) targetpath = source slash = source.rfind('/') if source[0]=='/': targetpath = source[slash+1:] elif source[0:3]=='../': targetpath = source[slash+1:] elif slash > 0 : dirpath = source[0:slash] if dirpath not in mkdirs.values: if cpargs.verbose: sys.stderr.write(dirpath+'/\n') if client.make_directory(destpath+dirpath): mkdirs.add(dirpath) else: raise ServiceError(403,'Cannot make target directory: {}'.format(dirpath)) target = destpath + targetpath if verbose: sys.stderr.write(source+' → '+target+'\n') with open(source,'rb') as input: def chunker(): sent =0 while True: b = input.read(32768) sent += len(b) if not b: if cpargs.verbose: sys.stderr.write('Sent {} bytes\n'.format(sent)) break yield b if not client.copy(chunker() if size<0 else input,target,size=size,overwrite=force): raise ServiceError(403,'Move failed: {} → {}'.format(source,target)) def hdfs_cp_command(client,argv): cpparser = argparse.ArgumentParser(prog='pyox hdfs cp',description="cp") cpparser.add_argument( '-f', action='store_true', dest='force', default=False, help="Force an overwrite") cpparser.add_argument( '-v', action='store_true', dest='verbose', default=False, help="Verbose") cpparser.add_argument( '-r', action='store_true', dest='recursive', default=False, help="Recursively apply wildcards") cpparser.add_argument( '-s', action='store_true', dest='sendsize', default=False, help="Send the file size") cpparser.add_argument( 'paths', nargs='*', help='a list of paths') cpargs = cpparser.parse_args(argv) if len(cpargs.paths)<2: sys.stderr.write('At least two paths must be specified.\n') sys.exit(1) destpath = cpargs.paths[-1] if destpath[-1]=='/': # directory copy, glob files mkdirs = tracker() for pattern in cpargs.paths[:-1]: if isfile(pattern): copy_to_destination(client,pattern,destpath,verbose=cpargs.verbose,force=cpargs.force) else: files = glob(pattern,recursive=cpargs.recursive) if len(files)==0 and cpargs.verbose: sys.stderr.write('Nothing matched {}\n'.format(pattern)) for source in files: copy_to_destination(client,source,destpath,verbose=cpargs.verbose,force=cpargs.force) elif len(cpargs.paths)==2: source = cpargs.paths[0] size = os.path.getsize(source) if cpargs.sendsize else -1 with open(source,'rb') as input: if cpargs.verbose: sys.stderr.write(source+' → '+destpath+'\n') if not client.copy(input,destpath,size=size,overwrite=cpargs.force): raise ServiceError(403,'Move failed: {} → {}'.format(source,destpath)) else: raise ServiceError(400,'Target is not a directory.') hdfs_commands = { 'ls'
help="the byte length to retrieve") catparser.add_argument( 'paths', nargs='*',
random_line_split
hdfs_command.py
lsargs.paths = ['/'] for path in lsargs.paths: listing = client.list_directory(path) max = 0; for name in sorted(listing): if len(name)>max: max = len(name) for name in sorted(listing): if not lsargs.detailed: print(name) continue info = listing[name] if name=='': name = path[path.rfind('/')+1:] max = len(name) ftype = info['type'] size = int(info['length']) modtime = datetime.fromtimestamp(int(info['modificationTime'])/1e3) fspec = '{:'+str(max)+'}\t{}\t{}' fsize = '0' if ftype=='DIRECTORY': name = name + '/' else: if lsargs.reportbytes or size<1024: fsize = str(size)+'B' elif size<1048576: fsize = '{:0.1f}KB'.format(size/1024) elif size<1073741824: fsize = '{:0.1f}MB'.format(size/1024/1024) else: fsize = '{:0.1f}GB'.format(size/1024/1024/1024) print(fspec.format(name,fsize,modtime.isoformat())) def hdfs_cat_command(client,argv): catparser = argparse.ArgumentParser(prog='pyox hdfs cat',description="cat") catparser.add_argument( '--offset', type=int, metavar=('int'), help="a byte offset for the file") catparser.add_argument( '--length', type=int, metavar=('int'), help="the byte length to retrieve") catparser.add_argument( 'paths', nargs='*', help='a list of paths') args = catparser.parse_args(argv) for path in args.paths: input = client.open(path,offset=args.offset,length=args.length) for chunk in input: sys.stdout.buffer.write(chunk) def hdfs_download_command(client,argv): dlparser = argparse.ArgumentParser(prog='pyox hdfs download',description="download") dlparser.add_argument( '--chunk-size', dest='chunk_size', type=int, metavar=('int'), help="The chunk size for the download") dlparser.add_argument( '-o','--output', dest='output', metavar=('file'), help="the output file") dlparser.add_argument( '-v', action='store_true', dest='verbose', default=False, help="Verbose") dlparser.add_argument( 'source', help='the remote source') args = dlparser.parse_args(argv) destination = args.output if destination is None: last = args.source.rfind('/') destination = args.source[last+1:] if last>=0 else args.source if args.chunk_size is not None: info = client.status(args.source) remaining = info['length'] offset = 0 chunk = 0 chunks = ceil(remaining/args.chunk_size) if args.verbose: sys.stderr.write('File size: {}\n'.format(remaining)) with open(destination,'wb') as output: while remaining>0: chunk += 1 if args.verbose: sys.stderr.write('Downloading chunk {}/{} '.format(chunk,chunks)) sys.stderr.flush() length = args.chunk_size if remaining>args.chunk_size else remaining input = client.open(args.source,offset=offset,length=length) for data in input: output.write(data) if args.verbose: sys.stderr.write('.') sys.stderr.flush() output.flush() if args.verbose: sys.stderr.write('\n') sys.stderr.flush() remaining -= length offset += length else: input = client.open(args.source) with open(destination,'wb') as output: for chunk in input: output.write(chunk) def hdfs_mkdir_command(client,argv): for path in argv: if not client.make_directory(path): raise ServiceError(403,'mkdir failed: {}'.format(path)) def hdfs_mv_command(client,argv): if len(argv)!=3: sys.stderr.write('Invalid number of arguments: {}'.format(len(args.command)-1)) if not client.mv(argv[0],argv[1]): raise ServiceError(403,'Move failed: {} → {}'.format(argv[0],argv[1])) def hdfs_rm_command(client,argv): rmparser = argparse.ArgumentParser(prog='pyox hdfs rm',description="rm") rmparser.add_argument( '-r', action='store_true', dest='recursive', default=False, help="Recursively remove files/directories") rmparser.add_argument( 'paths', nargs='*', help='a list of paths') rmargs = rmparser.parse_args(argv) for path in rmargs.paths: if not client.remove(path,recursive=rmargs.recursive): raise ServiceError(403,'Cannot remove: {}'.format(path)) def copy_to_destination(client,source,destpath,verbose=False,force=False): size = os.path.getsize(source) targetpath = source slash = source.rfind('/') if source[0]=='/': targetpath = source[slash+1:] elif source[0:3]=='../': targetpath = source[slash+1:] elif slash > 0 : dirpath = source[0:slash] if dirpath not in mkdirs.values: if cpargs.verbose: sys.stderr.write(dirpath+'/\n') if client.make_directory(destpath+dirpath): mkdirs.add(dirpath) else: raise ServiceError(403,'Cannot make target directory: {}'.format(dirpath)) target = destpath + targetpath if verbose: sys.stderr.write(source+' → '+target+'\n') with open(source,'rb') as input: def chunker(): sent =0 while True: b = input.read(32768) sent += len(b) if not b: if cpargs.verbose: sys.stderr.write('Sent {} bytes\n'.format(sent)) break yield b if not client.copy(chunker() if size<0 else input,target,size=size,overwrite=force): raise ServiceError(403,'Move failed: {} → {}'.format(source,target)) def hdfs_cp_command(client,argv): cpparser = argparse.ArgumentParser(prog='pyox hdfs cp',description="cp") cpparser.add_argument( '-f', action='store_true', dest='force', default=False, help="Force an overwrite") cpparser.add_argument( '-v', action='store_true', dest='verbose', default=False, help="Verbose") cpparser.add_argument( '-r', action='store_true', dest='recursive', default=False, help="Recursively apply wildcards") cpparser.add_argument( '-s', action='store_true', dest='sendsize', default=False, help="Send the file size") cpparser.add_argument( 'paths', nargs='*', help='a list of paths') cpargs = cpparser.parse_args(argv) if len(cpargs.paths)<2: sys.stderr.write('At least two paths must be specified.\n') sys.exit(1) destpath = cpargs.paths[-1] if destpath[-1]=='/': # directory copy, glob files mkdirs = tracker() for pattern in cpargs.paths[:-1]: if isfile(pattern): copy_to_destination(client,pattern,destpath,verbose=cpargs.verbose,force=cpargs.force) else: files = glob(pattern,recursive=cpargs.recursive) if len(files)==0 and cpargs.verbose: sys.stderr.write('Nothing matched {}\n'.format(pattern)) for source in files: copy_to_destination(client,source,destpath,verbose=cpargs.verbose,force=cpargs.force) elif len(cpargs.paths)==2: source = cpargs.paths[0] size = os.path.getsize(source) if cpargs.sendsize else -1 with open(source,'rb') as input: if cpargs.verbose: sys.stderr.write(source+' → '+destpath+'\n') if not client.copy(input,destpath,size=size,overwrite=cpargs.force): raise ServiceError(403,'Move failed: {} → {}'.format(source,destpath)) else: raise ServiceError(400,'Target is not a directory.') h
lsparser = argparse.ArgumentParser(prog='pyox hdfs ls',description="ls") lsparser.add_argument( '-b', action='store_true', dest='reportbytes', default=False, help="Report sizes in bytes") lsparser.add_argument( '-l', action='store_true', dest='detailed', default=False, help="List details") lsparser.add_argument( 'paths', nargs='*', help='a list of paths') lsargs = lsparser.parse_args(argv) if len(lsargs.paths)==0:
identifier_body
hdfs_command.py
='pyox hdfs ls',description="ls") lsparser.add_argument( '-b', action='store_true', dest='reportbytes', default=False, help="Report sizes in bytes") lsparser.add_argument( '-l', action='store_true', dest='detailed', default=False, help="List details") lsparser.add_argument( 'paths', nargs='*', help='a list of paths') lsargs = lsparser.parse_args(argv) if len(lsargs.paths)==0: lsargs.paths = ['/'] for path in lsargs.paths: listing = client.list_directory(path) max = 0; for name in sorted(listing): if len(name)>max: max = len(name) for name in sorted(listing): if not lsargs.detailed: print(name) continue info = listing[name] if name=='': name = path[path.rfind('/')+1:] max = len(name) ftype = info['type'] size = int(info['length']) modtime = datetime.fromtimestamp(int(info['modificationTime'])/1e3) fspec = '{:'+str(max)+'}\t{}\t{}' fsize = '0' if ftype=='DIRECTORY': name = name + '/' else: if lsargs.reportbytes or size<1024: fsize = str(size)+'B' elif size<1048576: fsize = '{:0.1f}KB'.format(size/1024) elif size<1073741824: fsize = '{:0.1f}MB'.format(size/1024/1024) else: fsize = '{:0.1f}GB'.format(size/1024/1024/1024) print(fspec.format(name,fsize,modtime.isoformat())) def hdfs_cat_command(client,argv): catparser = argparse.ArgumentParser(prog='pyox hdfs cat',description="cat") catparser.add_argument( '--offset', type=int, metavar=('int'), help="a byte offset for the file") catparser.add_argument( '--length', type=int, metavar=('int'), help="the byte length to retrieve") catparser.add_argument( 'paths', nargs='*', help='a list of paths') args = catparser.parse_args(argv) for path in args.paths: input = client.open(path,offset=args.offset,length=args.length) for chunk in input: sys.stdout.buffer.write(chunk) def hdfs_download_command(client,argv): dlparser = argparse.ArgumentParser(prog='pyox hdfs download',description="download") dlparser.add_argument( '--chunk-size', dest='chunk_size', type=int, metavar=('int'), help="The chunk size for the download") dlparser.add_argument( '-o','--output', dest='output', metavar=('file'), help="the output file") dlparser.add_argument( '-v', action='store_true', dest='verbose', default=False, help="Verbose") dlparser.add_argument( 'source', help='the remote source') args = dlparser.parse_args(argv) destination = args.output if destination is None: last = args.source.rfind('/') destination = args.source[last+1:] if last>=0 else args.source if args.chunk_size is not None:
output.flush() if args.verbose: sys.stderr.write('\n') sys.stderr.flush() remaining -= length offset += length else: input = client.open(args.source) with open(destination,'wb') as output: for chunk in input: output.write(chunk) def hdfs_mkdir_command(client,argv): for path in argv: if not client.make_directory(path): raise ServiceError(403,'mkdir failed: {}'.format(path)) def hdfs_mv_command(client,argv): if len(argv)!=3: sys.stderr.write('Invalid number of arguments: {}'.format(len(args.command)-1)) if not client.mv(argv[0],argv[1]): raise ServiceError(403,'Move failed: {} → {}'.format(argv[0],argv[1])) def hdfs_rm_command(client,argv): rmparser = argparse.ArgumentParser(prog='pyox hdfs rm',description="rm") rmparser.add_argument( '-r', action='store_true', dest='recursive', default=False, help="Recursively remove files/directories") rmparser.add_argument( 'paths', nargs='*', help='a list of paths') rmargs = rmparser.parse_args(argv) for path in rmargs.paths: if not client.remove(path,recursive=rmargs.recursive): raise ServiceError(403,'Cannot remove: {}'.format(path)) def copy_to_destination(client,source,destpath,verbose=False,force=False): size = os.path.getsize(source) targetpath = source slash = source.rfind('/') if source[0]=='/': targetpath = source[slash+1:] elif source[0:3]=='../': targetpath = source[slash+1:] elif slash > 0 : dirpath = source[0:slash] if dirpath not in mkdirs.values: if cpargs.verbose: sys.stderr.write(dirpath+'/\n') if client.make_directory(destpath+dirpath): mkdirs.add(dirpath) else: raise ServiceError(403,'Cannot make target directory: {}'.format(dirpath)) target = destpath + targetpath if verbose: sys.stderr.write(source+' → '+target+'\n') with open(source,'rb') as input: def chunker(): sent =0 while True: b = input.read(32768) sent += len(b) if not b: if cpargs.verbose: sys.stderr.write('Sent {} bytes\n'.format(sent)) break yield b if not client.copy(chunker() if size<0 else input,target,size=size,overwrite=force): raise ServiceError(403,'Move failed: {} → {}'.format(source,target)) def hdfs_cp_command(client,argv): cpparser = argparse.ArgumentParser(prog='pyox hdfs cp',description="cp") cpparser.add_argument( '-f', action='store_true', dest='force', default=False, help="Force an overwrite") cpparser.add_argument( '-v', action='store_true', dest='verbose', default=False, help="Verbose") cpparser.add_argument( '-r', action='store_true', dest='recursive', default=False, help="Recursively apply wildcards") cpparser.add_argument( '-s', action='store_true', dest='sendsize', default=False, help="Send the file size") cpparser.add_argument( 'paths', nargs='*', help='a list of paths') cpargs = cpparser.parse_args(argv) if len(cpargs.paths)<2: sys.stderr.write('At least two paths must be specified.\n') sys.exit(1) destpath = cpargs.paths[-1] if destpath[-1]=='/': # directory copy, glob files mkdirs = tracker() for pattern in cpargs.paths[:-1]: if isfile(pattern): copy_to_destination(client,pattern,destpath,verbose=cpargs.verbose,force=cpargs.force) else: files = glob(pattern,recursive=cpargs.recursive) if len(files)==0 and cpargs.verbose: sys.stderr.write('Nothing matched {}\n'.format(pattern)) for source in files: copy_to_destination(client,source,destpath,verbose=cpargs.verbose,force=cpargs.force) elif len(cpargs.paths)==2: source = cpargs.paths[0] size = os.path.getsize(source) if cpargs.sendsize else -1 with open(source,'rb') as input: if cpargs.verbose: sys.stderr.write(source+' → '+destpath+'\n') if not client.copy(input,destpath,size=size,overwrite=cpargs.force): raise ServiceError(403,'Move failed: {} → {}'.format(source,destpath)) else: raise ServiceError(400,'Target is not a directory.') hdfs_commands = { 'ls
info = client.status(args.source) remaining = info['length'] offset = 0 chunk = 0 chunks = ceil(remaining/args.chunk_size) if args.verbose: sys.stderr.write('File size: {}\n'.format(remaining)) with open(destination,'wb') as output: while remaining>0: chunk += 1 if args.verbose: sys.stderr.write('Downloading chunk {}/{} '.format(chunk,chunks)) sys.stderr.flush() length = args.chunk_size if remaining>args.chunk_size else remaining input = client.open(args.source,offset=offset,length=length) for data in input: output.write(data) if args.verbose: sys.stderr.write('.') sys.stderr.flush()
conditional_block
load3_db_weather.py
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Cloudant のデータベース作成 # # Copyright (C) 2016 International Business Machines Corporation # and others. All Rights Reserved. # # # https://github.com/cloudant/python-cloudant # pip install cloudant # # API Document # http://python-cloudant.readthedocs.io/en/latest/cloudant.html # import json import csv import codecs import uuid from cloudant.client import Cloudant from cloudant.result import Result, ResultByKey, QueryResult
# Cloudant認証情報の取得 f = open('cloudant_credentials_id.json', 'r') cred = json.load(f) f.close() print cred # データベース名の取得 f = open('database_name.json', 'r') dbn = json.load(f) f.close() print dbn['name'] client = Cloudant(cred['credentials']['username'], cred['credentials']['password'], url=cred['credentials']['url']) # Connect to the server client.connect() # DB選択 db = client[dbn['name']] # CSVを読んでループを回す fn = 'weather_code.csv'; reader = csv.reader(codecs.open(fn),delimiter=',',quoting=csv.QUOTE_NONE) for id, e_description,j_description in reader: print id, e_description,j_description data = { "_id": id, "e_description": e_description, "j_description": j_description } print data rx = db.create_document(data) if rx.exists(): print "SUCCESS!!" # Disconnect from the server client.disconnect()
from cloudant.query import Query #import cloudant
random_line_split
load3_db_weather.py
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Cloudant のデータベース作成 # # Copyright (C) 2016 International Business Machines Corporation # and others. All Rights Reserved. # # # https://github.com/cloudant/python-cloudant # pip install cloudant # # API Document # http://python-cloudant.readthedocs.io/en/latest/cloudant.html # import json import csv import codecs import uuid from cloudant.client import Cloudant from cloudant.result import Result, ResultByKey, QueryResult from cloudant.query import Query #import cloudant # Cloudant認証情報の取得 f = open('cloudant_credentials_id.json', 'r') cred = json.load(f) f.close() print cred # データベース名の取得 f = open('database_name.json', 'r') dbn = json.load(f) f.close() print dbn['name'] client = Cloudant(cred['credentials']['username'], cred['credentials']['password'], url=cred['credentials']['url']) # Connect to the server client.connect() # DB選択 db = client[dbn['name']] # CSVを読んでループを回す fn = 'weather_code.csv'; reader = csv.reader(codecs.open(fn),delimiter=',',quoting=csv.QUOTE_NONE) for id, e_description,j_description in reader: print id, e_description,j_description data = { "_id": id,
"e_description": e_description, "j_description": j_description } print data rx = db.create_document(data) if rx.exists(): print "SUCCESS!!" # Disconnect from the server client.disconnect()
conditional_block
SetCompareAndRetainAllCodec.ts
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable max-len */ import {BitsUtil} from '../util/BitsUtil'; import {FixSizedTypesCodec} from './builtin/FixSizedTypesCodec'; import {ClientMessage, Frame, RESPONSE_BACKUP_ACKS_OFFSET, PARTITION_ID_OFFSET} from '../protocol/ClientMessage'; import {StringCodec} from './builtin/StringCodec'; import {Data} from '../serialization/Data'; import {ListMultiFrameCodec} from './builtin/ListMultiFrameCodec'; import {DataCodec} from './builtin/DataCodec'; // hex: 0x060800 const REQUEST_MESSAGE_TYPE = 395264; // hex: 0x060801 // RESPONSE_MESSAGE_TYPE = 395265 const REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_OFFSET + BitsUtil.INT_SIZE_IN_BYTES; const RESPONSE_RESPONSE_OFFSET = RESPONSE_BACKUP_ACKS_OFFSET + BitsUtil.BYTE_SIZE_IN_BYTES; /** @internal */ export class SetCompareAndRetainAllCodec { static
(name: string, values: Data[]): ClientMessage { const clientMessage = ClientMessage.createForEncode(); clientMessage.setRetryable(false); const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE); clientMessage.addFrame(initialFrame); clientMessage.setMessageType(REQUEST_MESSAGE_TYPE); clientMessage.setPartitionId(-1); StringCodec.encode(clientMessage, name); ListMultiFrameCodec.encode(clientMessage, values, DataCodec.encode); return clientMessage; } static decodeResponse(clientMessage: ClientMessage): boolean { const initialFrame = clientMessage.nextFrame(); return FixSizedTypesCodec.decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_OFFSET); } }
encodeRequest
identifier_name
SetCompareAndRetainAllCodec.ts
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
* * 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. */ /* eslint-disable max-len */ import {BitsUtil} from '../util/BitsUtil'; import {FixSizedTypesCodec} from './builtin/FixSizedTypesCodec'; import {ClientMessage, Frame, RESPONSE_BACKUP_ACKS_OFFSET, PARTITION_ID_OFFSET} from '../protocol/ClientMessage'; import {StringCodec} from './builtin/StringCodec'; import {Data} from '../serialization/Data'; import {ListMultiFrameCodec} from './builtin/ListMultiFrameCodec'; import {DataCodec} from './builtin/DataCodec'; // hex: 0x060800 const REQUEST_MESSAGE_TYPE = 395264; // hex: 0x060801 // RESPONSE_MESSAGE_TYPE = 395265 const REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_OFFSET + BitsUtil.INT_SIZE_IN_BYTES; const RESPONSE_RESPONSE_OFFSET = RESPONSE_BACKUP_ACKS_OFFSET + BitsUtil.BYTE_SIZE_IN_BYTES; /** @internal */ export class SetCompareAndRetainAllCodec { static encodeRequest(name: string, values: Data[]): ClientMessage { const clientMessage = ClientMessage.createForEncode(); clientMessage.setRetryable(false); const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE); clientMessage.addFrame(initialFrame); clientMessage.setMessageType(REQUEST_MESSAGE_TYPE); clientMessage.setPartitionId(-1); StringCodec.encode(clientMessage, name); ListMultiFrameCodec.encode(clientMessage, values, DataCodec.encode); return clientMessage; } static decodeResponse(clientMessage: ClientMessage): boolean { const initialFrame = clientMessage.nextFrame(); return FixSizedTypesCodec.decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_OFFSET); } }
* You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0
random_line_split
SetCompareAndRetainAllCodec.ts
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable max-len */ import {BitsUtil} from '../util/BitsUtil'; import {FixSizedTypesCodec} from './builtin/FixSizedTypesCodec'; import {ClientMessage, Frame, RESPONSE_BACKUP_ACKS_OFFSET, PARTITION_ID_OFFSET} from '../protocol/ClientMessage'; import {StringCodec} from './builtin/StringCodec'; import {Data} from '../serialization/Data'; import {ListMultiFrameCodec} from './builtin/ListMultiFrameCodec'; import {DataCodec} from './builtin/DataCodec'; // hex: 0x060800 const REQUEST_MESSAGE_TYPE = 395264; // hex: 0x060801 // RESPONSE_MESSAGE_TYPE = 395265 const REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_OFFSET + BitsUtil.INT_SIZE_IN_BYTES; const RESPONSE_RESPONSE_OFFSET = RESPONSE_BACKUP_ACKS_OFFSET + BitsUtil.BYTE_SIZE_IN_BYTES; /** @internal */ export class SetCompareAndRetainAllCodec { static encodeRequest(name: string, values: Data[]): ClientMessage
static decodeResponse(clientMessage: ClientMessage): boolean { const initialFrame = clientMessage.nextFrame(); return FixSizedTypesCodec.decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_OFFSET); } }
{ const clientMessage = ClientMessage.createForEncode(); clientMessage.setRetryable(false); const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE); clientMessage.addFrame(initialFrame); clientMessage.setMessageType(REQUEST_MESSAGE_TYPE); clientMessage.setPartitionId(-1); StringCodec.encode(clientMessage, name); ListMultiFrameCodec.encode(clientMessage, values, DataCodec.encode); return clientMessage; }
identifier_body
fakes.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 //! Fakes for filling-in hardware functionality from `manticore::hardware`. use std::collections::HashMap; use std::convert::TryInto as _; use std::time::Duration; use std::time::Instant; /// A fake `Identity` that returns fixed values. pub struct Identity { firmware_version: Vec<u8>, vendor_firmware_versions: HashMap<u8, Vec<u8>>, unique_id: Vec<u8>, } impl Identity { /// Creates a new `Identity`. pub fn new<'a>( firmware_version: &[u8], vendor_firmware_versions: impl Iterator<Item = (u8, &'a [u8])>, unique_id: &[u8], ) -> Self { fn pad_to_32(data: &[u8]) -> Vec<u8> { let mut vec = data.to_vec(); while vec.len() < 32 { vec.push(0); } vec.truncate(32); vec } Self { firmware_version: pad_to_32(firmware_version), vendor_firmware_versions: vendor_firmware_versions .map(|(key, value)| (key, pad_to_32(value))) .collect(), unique_id: unique_id.to_vec(), } } } impl manticore::hardware::Identity for Identity { fn firmware_version(&self) -> &[u8; 32] { self.firmware_version[..32].try_into().unwrap() } fn vendor_firmware_version(&self, slot: u8) -> Option<&[u8; 32]> { self.vendor_firmware_versions .get(&slot) .map(|data| data[..32].try_into().unwrap()) } fn unique_device_identity(&self) -> &[u8] { &self.unique_id[..] } } /// A fake `Reset` that returns fixed values. pub struct Reset { startup_time: Instant, resets_since_power_on: u32, } impl Reset { /// Creates a new `Reset`. pub fn new(resets_since_power_on: u32) -> Self { Self { startup_time: Instant::now(), resets_since_power_on, } } } impl manticore::hardware::Reset for Reset { fn resets_since_power_on(&self) -> u32 { self.resets_since_power_on } fn
(&self) -> Duration { self.startup_time.elapsed() } }
uptime
identifier_name
fakes.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 //! Fakes for filling-in hardware functionality from `manticore::hardware`. use std::collections::HashMap; use std::convert::TryInto as _; use std::time::Duration; use std::time::Instant; /// A fake `Identity` that returns fixed values. pub struct Identity { firmware_version: Vec<u8>, vendor_firmware_versions: HashMap<u8, Vec<u8>>, unique_id: Vec<u8>, } impl Identity { /// Creates a new `Identity`. pub fn new<'a>( firmware_version: &[u8], vendor_firmware_versions: impl Iterator<Item = (u8, &'a [u8])>, unique_id: &[u8], ) -> Self { fn pad_to_32(data: &[u8]) -> Vec<u8> { let mut vec = data.to_vec(); while vec.len() < 32 { vec.push(0); } vec.truncate(32); vec } Self { firmware_version: pad_to_32(firmware_version), vendor_firmware_versions: vendor_firmware_versions .map(|(key, value)| (key, pad_to_32(value))) .collect(), unique_id: unique_id.to_vec(), } } } impl manticore::hardware::Identity for Identity { fn firmware_version(&self) -> &[u8; 32] { self.firmware_version[..32].try_into().unwrap() } fn vendor_firmware_version(&self, slot: u8) -> Option<&[u8; 32]> { self.vendor_firmware_versions .get(&slot) .map(|data| data[..32].try_into().unwrap()) } fn unique_device_identity(&self) -> &[u8] { &self.unique_id[..] } } /// A fake `Reset` that returns fixed values. pub struct Reset { startup_time: Instant, resets_since_power_on: u32, }
impl Reset { /// Creates a new `Reset`. pub fn new(resets_since_power_on: u32) -> Self { Self { startup_time: Instant::now(), resets_since_power_on, } } } impl manticore::hardware::Reset for Reset { fn resets_since_power_on(&self) -> u32 { self.resets_since_power_on } fn uptime(&self) -> Duration { self.startup_time.elapsed() } }
random_line_split
fakes.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 //! Fakes for filling-in hardware functionality from `manticore::hardware`. use std::collections::HashMap; use std::convert::TryInto as _; use std::time::Duration; use std::time::Instant; /// A fake `Identity` that returns fixed values. pub struct Identity { firmware_version: Vec<u8>, vendor_firmware_versions: HashMap<u8, Vec<u8>>, unique_id: Vec<u8>, } impl Identity { /// Creates a new `Identity`. pub fn new<'a>( firmware_version: &[u8], vendor_firmware_versions: impl Iterator<Item = (u8, &'a [u8])>, unique_id: &[u8], ) -> Self { fn pad_to_32(data: &[u8]) -> Vec<u8> { let mut vec = data.to_vec(); while vec.len() < 32 { vec.push(0); } vec.truncate(32); vec } Self { firmware_version: pad_to_32(firmware_version), vendor_firmware_versions: vendor_firmware_versions .map(|(key, value)| (key, pad_to_32(value))) .collect(), unique_id: unique_id.to_vec(), } } } impl manticore::hardware::Identity for Identity { fn firmware_version(&self) -> &[u8; 32] { self.firmware_version[..32].try_into().unwrap() } fn vendor_firmware_version(&self, slot: u8) -> Option<&[u8; 32]> { self.vendor_firmware_versions .get(&slot) .map(|data| data[..32].try_into().unwrap()) } fn unique_device_identity(&self) -> &[u8] { &self.unique_id[..] } } /// A fake `Reset` that returns fixed values. pub struct Reset { startup_time: Instant, resets_since_power_on: u32, } impl Reset { /// Creates a new `Reset`. pub fn new(resets_since_power_on: u32) -> Self { Self { startup_time: Instant::now(), resets_since_power_on, } } } impl manticore::hardware::Reset for Reset { fn resets_since_power_on(&self) -> u32
fn uptime(&self) -> Duration { self.startup_time.elapsed() } }
{ self.resets_since_power_on }
identifier_body
__init__.py
import warnings import sqlalchemy as sa from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base, synonym_for from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_utils import ( InstrumentedList, coercion_listener, aggregates, i18n ) @sa.event.listens_for(sa.engine.Engine, 'before_cursor_execute') def count_sql_calls(conn, cursor, statement, parameters, context, executemany): try: conn.query_count += 1 except AttributeError: conn.query_count = 0 warnings.simplefilter('error', sa.exc.SAWarning) sa.event.listen(sa.orm.mapper, 'mapper_configured', coercion_listener) def get_locale(): class Locale(): territories = {'fi': 'Finland'} return Locale() class TestCase(object): dns = 'sqlite:///:memory:' create_tables = True def setup_method(self, method): self.engine = create_engine(self.dns) # self.engine.echo = True self.connection = self.engine.connect() self.Base = declarative_base()
Session = sessionmaker(bind=self.connection) self.session = Session() i18n.get_locale = get_locale def teardown_method(self, method): aggregates.manager.reset() self.session.close_all() if self.create_tables: self.Base.metadata.drop_all(self.connection) self.connection.close() self.engine.dispose() def create_models(self): class User(self.Base): __tablename__ = 'user' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255)) class Category(self.Base): __tablename__ = 'category' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255)) @hybrid_property def articles_count(self): return len(self.articles) @articles_count.expression def articles_count(cls): return ( sa.select([sa.func.count(self.Article.id)]) .where(self.Article.category_id == self.Category.id) .correlate(self.Article.__table__) .label('article_count') ) @property def name_alias(self): return self.name @synonym_for('name') @property def name_synonym(self): return self.name class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255), index=True) category_id = sa.Column(sa.Integer, sa.ForeignKey(Category.id)) category = sa.orm.relationship( Category, primaryjoin=category_id == Category.id, backref=sa.orm.backref( 'articles', collection_class=InstrumentedList ) ) self.User = User self.Category = Category self.Article = Article def assert_contains(clause, query): # Test that query executes query.all() assert clause in str(query)
self.create_models() sa.orm.configure_mappers() if self.create_tables: self.Base.metadata.create_all(self.connection)
random_line_split
__init__.py
import warnings import sqlalchemy as sa from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base, synonym_for from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_utils import ( InstrumentedList, coercion_listener, aggregates, i18n ) @sa.event.listens_for(sa.engine.Engine, 'before_cursor_execute') def count_sql_calls(conn, cursor, statement, parameters, context, executemany):
warnings.simplefilter('error', sa.exc.SAWarning) sa.event.listen(sa.orm.mapper, 'mapper_configured', coercion_listener) def get_locale(): class Locale(): territories = {'fi': 'Finland'} return Locale() class TestCase(object): dns = 'sqlite:///:memory:' create_tables = True def setup_method(self, method): self.engine = create_engine(self.dns) # self.engine.echo = True self.connection = self.engine.connect() self.Base = declarative_base() self.create_models() sa.orm.configure_mappers() if self.create_tables: self.Base.metadata.create_all(self.connection) Session = sessionmaker(bind=self.connection) self.session = Session() i18n.get_locale = get_locale def teardown_method(self, method): aggregates.manager.reset() self.session.close_all() if self.create_tables: self.Base.metadata.drop_all(self.connection) self.connection.close() self.engine.dispose() def create_models(self): class User(self.Base): __tablename__ = 'user' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255)) class Category(self.Base): __tablename__ = 'category' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255)) @hybrid_property def articles_count(self): return len(self.articles) @articles_count.expression def articles_count(cls): return ( sa.select([sa.func.count(self.Article.id)]) .where(self.Article.category_id == self.Category.id) .correlate(self.Article.__table__) .label('article_count') ) @property def name_alias(self): return self.name @synonym_for('name') @property def name_synonym(self): return self.name class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255), index=True) category_id = sa.Column(sa.Integer, sa.ForeignKey(Category.id)) category = sa.orm.relationship( Category, primaryjoin=category_id == Category.id, backref=sa.orm.backref( 'articles', collection_class=InstrumentedList ) ) self.User = User self.Category = Category self.Article = Article def assert_contains(clause, query): # Test that query executes query.all() assert clause in str(query)
try: conn.query_count += 1 except AttributeError: conn.query_count = 0
identifier_body
__init__.py
import warnings import sqlalchemy as sa from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base, synonym_for from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_utils import ( InstrumentedList, coercion_listener, aggregates, i18n ) @sa.event.listens_for(sa.engine.Engine, 'before_cursor_execute') def count_sql_calls(conn, cursor, statement, parameters, context, executemany): try: conn.query_count += 1 except AttributeError: conn.query_count = 0 warnings.simplefilter('error', sa.exc.SAWarning) sa.event.listen(sa.orm.mapper, 'mapper_configured', coercion_listener) def get_locale(): class Locale(): territories = {'fi': 'Finland'} return Locale() class TestCase(object): dns = 'sqlite:///:memory:' create_tables = True def setup_method(self, method): self.engine = create_engine(self.dns) # self.engine.echo = True self.connection = self.engine.connect() self.Base = declarative_base() self.create_models() sa.orm.configure_mappers() if self.create_tables: self.Base.metadata.create_all(self.connection) Session = sessionmaker(bind=self.connection) self.session = Session() i18n.get_locale = get_locale def teardown_method(self, method): aggregates.manager.reset() self.session.close_all() if self.create_tables: self.Base.metadata.drop_all(self.connection) self.connection.close() self.engine.dispose() def create_models(self): class User(self.Base): __tablename__ = 'user' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255)) class Category(self.Base): __tablename__ = 'category' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255)) @hybrid_property def articles_count(self): return len(self.articles) @articles_count.expression def articles_count(cls): return ( sa.select([sa.func.count(self.Article.id)]) .where(self.Article.category_id == self.Category.id) .correlate(self.Article.__table__) .label('article_count') ) @property def name_alias(self): return self.name @synonym_for('name') @property def name_synonym(self): return self.name class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255), index=True) category_id = sa.Column(sa.Integer, sa.ForeignKey(Category.id)) category = sa.orm.relationship( Category, primaryjoin=category_id == Category.id, backref=sa.orm.backref( 'articles', collection_class=InstrumentedList ) ) self.User = User self.Category = Category self.Article = Article def
(clause, query): # Test that query executes query.all() assert clause in str(query)
assert_contains
identifier_name
__init__.py
import warnings import sqlalchemy as sa from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base, synonym_for from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_utils import ( InstrumentedList, coercion_listener, aggregates, i18n ) @sa.event.listens_for(sa.engine.Engine, 'before_cursor_execute') def count_sql_calls(conn, cursor, statement, parameters, context, executemany): try: conn.query_count += 1 except AttributeError: conn.query_count = 0 warnings.simplefilter('error', sa.exc.SAWarning) sa.event.listen(sa.orm.mapper, 'mapper_configured', coercion_listener) def get_locale(): class Locale(): territories = {'fi': 'Finland'} return Locale() class TestCase(object): dns = 'sqlite:///:memory:' create_tables = True def setup_method(self, method): self.engine = create_engine(self.dns) # self.engine.echo = True self.connection = self.engine.connect() self.Base = declarative_base() self.create_models() sa.orm.configure_mappers() if self.create_tables:
Session = sessionmaker(bind=self.connection) self.session = Session() i18n.get_locale = get_locale def teardown_method(self, method): aggregates.manager.reset() self.session.close_all() if self.create_tables: self.Base.metadata.drop_all(self.connection) self.connection.close() self.engine.dispose() def create_models(self): class User(self.Base): __tablename__ = 'user' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255)) class Category(self.Base): __tablename__ = 'category' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255)) @hybrid_property def articles_count(self): return len(self.articles) @articles_count.expression def articles_count(cls): return ( sa.select([sa.func.count(self.Article.id)]) .where(self.Article.category_id == self.Category.id) .correlate(self.Article.__table__) .label('article_count') ) @property def name_alias(self): return self.name @synonym_for('name') @property def name_synonym(self): return self.name class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255), index=True) category_id = sa.Column(sa.Integer, sa.ForeignKey(Category.id)) category = sa.orm.relationship( Category, primaryjoin=category_id == Category.id, backref=sa.orm.backref( 'articles', collection_class=InstrumentedList ) ) self.User = User self.Category = Category self.Article = Article def assert_contains(clause, query): # Test that query executes query.all() assert clause in str(query)
self.Base.metadata.create_all(self.connection)
conditional_block
app.component.ts
import { Component, ViewChild } from '@angular/core'; import { /*Events, MenuController, */ Nav, Platform, MenuController, Events } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { UserData } from "../providers/user-data"; import { LoginPage } from '../pages/login/login'; import { SignupPage } from '../pages/signup/signup'; import { HomePage } from '../pages/home/home'; import { ProfilePage } from '../pages/profile/profile'; import { CreateProjectPage } from '../pages/create-project/create-project'; import { EditProfilePage } from '../pages/edit-profile/edit-profile'; import { LogoutPage } from '../pages/logout/logout'; import { SearchPage } from '../pages/search/search'; import { BookmarksPage } from '../pages/bookmarks/bookmarks'; import { TutorialPage } from '../pages/tutorial/tutorial'; export interface PageInterface { title: string; component: any; icon: string; logsOut?: boolean; index?: number; tabComponent?: any; param?: String; } @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any; loggedOutPages: PageInterface[] = [ { title: 'Log In', component: LoginPage, icon: 'log-in' }, { title: 'Sign Up', component: SignupPage, icon: 'person-add' } ]; loggedInPages: PageInterface[] = [ { title: 'Home', component: HomePage, icon: 'home' }, { title: 'New Project', component: CreateProjectPage, icon: 'create' }, { title: 'Search', component: SearchPage, icon: 'search'} ]; accountPages: PageInterface[] = [ { title: 'Profile', component: ProfilePage, icon: 'person', param:'username' }, { title: 'Favourites', component: BookmarksPage, icon: 'star' }, { title: 'Edit Account', component: EditProfilePage, icon: 'contact' }, { title: 'Log out', component: LogoutPage, icon: 'log-out' } ]; aboutPages: PageInterface[] = [ { title: 'Tutorial', component: TutorialPage, icon: 'information' } ]; username: String = ""; occupation: String = ""; email: String = ""; directory: string = "assets/img/profile/"; chosenPicture: string = ""; constructor(public menu: MenuController, public events: Events, public userData: UserData, public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) { this.initializeApp(); // decide which menu items should be hidden by current login status stored in local storage this.userData.checkHasSeenTutorial().then((hasSeenTutorial) => { if(!hasSeenTutorial){ //set the root to Tutorial on the first opening of app this.rootPage = TutorialPage; //set menu to logged out menu as the user cannot be logged in yet this.enableMenu(false); //set the has seen tutorial to true this.userData.setHasSeenTutorial(); }else{ this.userData.hasLoggedIn().then((hasLoggedIn) => { this.enableMenu(hasLoggedIn); if(hasLoggedIn){this.rootPage = HomePage;} else
}); } }); this.startEvents(); } initializeApp() { this.platform.ready().then(() => { // The platform is ready and our plugins are available. this.statusBar.styleDefault(); this.splashScreen.hide(); }); } openPage(page) { //if has param (the profile page) //set root and pass in param if(page.hasOwnProperty('param')){ this.nav.setRoot(page.component, { param1: page.param }); } else{ //set root without param this.nav.setRoot(page.component); } } //set the color of the active page to be red isActive(page: PageInterface) { if (this.nav.getActive() && this.nav.getActive().component === page.component) { return 'danger'; } return; } //toggle logged in/out menu enableMenu(loggedIn: boolean) { this.menu.enable(loggedIn, 'loggedInMenu'); this.menu.enable(!loggedIn, 'loggedOutMenu'); } //get user data for profile param, and any user data shown in the side menu getUserDetails() { this.userData.getCurrentUser().then((user) => { console.log("In get user details - app component"); console.log(user); this.username = user.username; this.occupation = user.occupation; this.email = user.email; this.chosenPicture= this.directory + user.gender + ".jpg"; this.accountPages.forEach(function(p){if (p.title === 'Profile') p.param=user.username;} ); }).catch(()=>{}); } //get user data for profile param, any user data shown in the side menu, //and trigger getLoginDetails() { this.userData.getCurrentUser().then((user) => { console.log("In get user details - app component"); console.log(user); this.username = user.username; this.occupation = user.occupation; this.email = user.email; this.chosenPicture= this.directory + user.gender + ".jpg"; this.accountPages.forEach(function(p){if (p.title === 'Profile') p.param=user.username;} ); }).then((user) => { console.log("Triggering login event"); this.events.publish('user:loggedin'); }).catch(()=>{}); } //start listening for events startEvents(){ this.events.subscribe('user:login', () => { this.getLoginDetails(); console.log("Logged in event triggered"); }); this.events.subscribe('user:loggedin', () => { this.enableMenu(true); this.nav.setRoot(HomePage); console.log("Logged in event triggered"); }); this.events.subscribe('user:changed', () => { this.getUserDetails(); console.log("User changed event triggered"); }); this.events.subscribe('user:logout', () => { this.enableMenu(false); this.nav.setRoot(LoginPage); }); } }
{this.rootPage = LoginPage;}
conditional_block
app.component.ts
import { Component, ViewChild } from '@angular/core'; import { /*Events, MenuController, */ Nav, Platform, MenuController, Events } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { UserData } from "../providers/user-data"; import { LoginPage } from '../pages/login/login'; import { SignupPage } from '../pages/signup/signup'; import { HomePage } from '../pages/home/home'; import { ProfilePage } from '../pages/profile/profile'; import { CreateProjectPage } from '../pages/create-project/create-project'; import { EditProfilePage } from '../pages/edit-profile/edit-profile'; import { LogoutPage } from '../pages/logout/logout'; import { SearchPage } from '../pages/search/search'; import { BookmarksPage } from '../pages/bookmarks/bookmarks'; import { TutorialPage } from '../pages/tutorial/tutorial'; export interface PageInterface { title: string; component: any; icon: string; logsOut?: boolean; index?: number; tabComponent?: any; param?: String; } @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any; loggedOutPages: PageInterface[] = [ { title: 'Log In', component: LoginPage, icon: 'log-in' }, { title: 'Sign Up', component: SignupPage, icon: 'person-add' } ]; loggedInPages: PageInterface[] = [ { title: 'Home', component: HomePage, icon: 'home' }, { title: 'New Project', component: CreateProjectPage, icon: 'create' }, { title: 'Search', component: SearchPage, icon: 'search'} ]; accountPages: PageInterface[] = [ { title: 'Profile', component: ProfilePage, icon: 'person', param:'username' }, { title: 'Favourites', component: BookmarksPage, icon: 'star' }, { title: 'Edit Account', component: EditProfilePage, icon: 'contact' }, { title: 'Log out', component: LogoutPage, icon: 'log-out' } ]; aboutPages: PageInterface[] = [ { title: 'Tutorial', component: TutorialPage, icon: 'information' } ]; username: String = ""; occupation: String = ""; email: String = ""; directory: string = "assets/img/profile/"; chosenPicture: string = ""; constructor(public menu: MenuController, public events: Events, public userData: UserData, public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) { this.initializeApp(); // decide which menu items should be hidden by current login status stored in local storage this.userData.checkHasSeenTutorial().then((hasSeenTutorial) => { if(!hasSeenTutorial){ //set the root to Tutorial on the first opening of app this.rootPage = TutorialPage; //set menu to logged out menu as the user cannot be logged in yet this.enableMenu(false); //set the has seen tutorial to true this.userData.setHasSeenTutorial(); }else{ this.userData.hasLoggedIn().then((hasLoggedIn) => { this.enableMenu(hasLoggedIn); if(hasLoggedIn){this.rootPage = HomePage;} else{this.rootPage = LoginPage;} }); } }); this.startEvents(); } initializeApp() { this.platform.ready().then(() => { // The platform is ready and our plugins are available. this.statusBar.styleDefault(); this.splashScreen.hide(); }); } openPage(page)
//set the color of the active page to be red isActive(page: PageInterface) { if (this.nav.getActive() && this.nav.getActive().component === page.component) { return 'danger'; } return; } //toggle logged in/out menu enableMenu(loggedIn: boolean) { this.menu.enable(loggedIn, 'loggedInMenu'); this.menu.enable(!loggedIn, 'loggedOutMenu'); } //get user data for profile param, and any user data shown in the side menu getUserDetails() { this.userData.getCurrentUser().then((user) => { console.log("In get user details - app component"); console.log(user); this.username = user.username; this.occupation = user.occupation; this.email = user.email; this.chosenPicture= this.directory + user.gender + ".jpg"; this.accountPages.forEach(function(p){if (p.title === 'Profile') p.param=user.username;} ); }).catch(()=>{}); } //get user data for profile param, any user data shown in the side menu, //and trigger getLoginDetails() { this.userData.getCurrentUser().then((user) => { console.log("In get user details - app component"); console.log(user); this.username = user.username; this.occupation = user.occupation; this.email = user.email; this.chosenPicture= this.directory + user.gender + ".jpg"; this.accountPages.forEach(function(p){if (p.title === 'Profile') p.param=user.username;} ); }).then((user) => { console.log("Triggering login event"); this.events.publish('user:loggedin'); }).catch(()=>{}); } //start listening for events startEvents(){ this.events.subscribe('user:login', () => { this.getLoginDetails(); console.log("Logged in event triggered"); }); this.events.subscribe('user:loggedin', () => { this.enableMenu(true); this.nav.setRoot(HomePage); console.log("Logged in event triggered"); }); this.events.subscribe('user:changed', () => { this.getUserDetails(); console.log("User changed event triggered"); }); this.events.subscribe('user:logout', () => { this.enableMenu(false); this.nav.setRoot(LoginPage); }); } }
{ //if has param (the profile page) //set root and pass in param if(page.hasOwnProperty('param')){ this.nav.setRoot(page.component, { param1: page.param }); } else{ //set root without param this.nav.setRoot(page.component); } }
identifier_body
app.component.ts
import { Component, ViewChild } from '@angular/core'; import { /*Events, MenuController, */ Nav, Platform, MenuController, Events } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { UserData } from "../providers/user-data"; import { LoginPage } from '../pages/login/login'; import { SignupPage } from '../pages/signup/signup'; import { HomePage } from '../pages/home/home'; import { ProfilePage } from '../pages/profile/profile'; import { CreateProjectPage } from '../pages/create-project/create-project'; import { EditProfilePage } from '../pages/edit-profile/edit-profile'; import { LogoutPage } from '../pages/logout/logout'; import { SearchPage } from '../pages/search/search'; import { BookmarksPage } from '../pages/bookmarks/bookmarks'; import { TutorialPage } from '../pages/tutorial/tutorial'; export interface PageInterface { title: string; component: any; icon: string; logsOut?: boolean; index?: number; tabComponent?: any; param?: String; } @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any; loggedOutPages: PageInterface[] = [ { title: 'Log In', component: LoginPage, icon: 'log-in' }, { title: 'Sign Up', component: SignupPage, icon: 'person-add' } ]; loggedInPages: PageInterface[] = [ { title: 'Home', component: HomePage, icon: 'home' }, { title: 'New Project', component: CreateProjectPage, icon: 'create' }, { title: 'Search', component: SearchPage, icon: 'search'} ]; accountPages: PageInterface[] = [ { title: 'Profile', component: ProfilePage, icon: 'person', param:'username' }, { title: 'Favourites', component: BookmarksPage, icon: 'star' }, { title: 'Edit Account', component: EditProfilePage, icon: 'contact' }, { title: 'Log out', component: LogoutPage, icon: 'log-out' } ]; aboutPages: PageInterface[] = [ { title: 'Tutorial', component: TutorialPage, icon: 'information' } ]; username: String = ""; occupation: String = ""; email: String = ""; directory: string = "assets/img/profile/"; chosenPicture: string = ""; constructor(public menu: MenuController, public events: Events, public userData: UserData, public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) { this.initializeApp(); // decide which menu items should be hidden by current login status stored in local storage this.userData.checkHasSeenTutorial().then((hasSeenTutorial) => { if(!hasSeenTutorial){ //set the root to Tutorial on the first opening of app this.rootPage = TutorialPage; //set menu to logged out menu as the user cannot be logged in yet this.enableMenu(false); //set the has seen tutorial to true this.userData.setHasSeenTutorial(); }else{ this.userData.hasLoggedIn().then((hasLoggedIn) => { this.enableMenu(hasLoggedIn); if(hasLoggedIn){this.rootPage = HomePage;} else{this.rootPage = LoginPage;} }); } }); this.startEvents(); }
() { this.platform.ready().then(() => { // The platform is ready and our plugins are available. this.statusBar.styleDefault(); this.splashScreen.hide(); }); } openPage(page) { //if has param (the profile page) //set root and pass in param if(page.hasOwnProperty('param')){ this.nav.setRoot(page.component, { param1: page.param }); } else{ //set root without param this.nav.setRoot(page.component); } } //set the color of the active page to be red isActive(page: PageInterface) { if (this.nav.getActive() && this.nav.getActive().component === page.component) { return 'danger'; } return; } //toggle logged in/out menu enableMenu(loggedIn: boolean) { this.menu.enable(loggedIn, 'loggedInMenu'); this.menu.enable(!loggedIn, 'loggedOutMenu'); } //get user data for profile param, and any user data shown in the side menu getUserDetails() { this.userData.getCurrentUser().then((user) => { console.log("In get user details - app component"); console.log(user); this.username = user.username; this.occupation = user.occupation; this.email = user.email; this.chosenPicture= this.directory + user.gender + ".jpg"; this.accountPages.forEach(function(p){if (p.title === 'Profile') p.param=user.username;} ); }).catch(()=>{}); } //get user data for profile param, any user data shown in the side menu, //and trigger getLoginDetails() { this.userData.getCurrentUser().then((user) => { console.log("In get user details - app component"); console.log(user); this.username = user.username; this.occupation = user.occupation; this.email = user.email; this.chosenPicture= this.directory + user.gender + ".jpg"; this.accountPages.forEach(function(p){if (p.title === 'Profile') p.param=user.username;} ); }).then((user) => { console.log("Triggering login event"); this.events.publish('user:loggedin'); }).catch(()=>{}); } //start listening for events startEvents(){ this.events.subscribe('user:login', () => { this.getLoginDetails(); console.log("Logged in event triggered"); }); this.events.subscribe('user:loggedin', () => { this.enableMenu(true); this.nav.setRoot(HomePage); console.log("Logged in event triggered"); }); this.events.subscribe('user:changed', () => { this.getUserDetails(); console.log("User changed event triggered"); }); this.events.subscribe('user:logout', () => { this.enableMenu(false); this.nav.setRoot(LoginPage); }); } }
initializeApp
identifier_name
app.component.ts
import { Component, ViewChild } from '@angular/core'; import { /*Events, MenuController, */ Nav, Platform, MenuController, Events } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { UserData } from "../providers/user-data"; import { LoginPage } from '../pages/login/login'; import { SignupPage } from '../pages/signup/signup'; import { HomePage } from '../pages/home/home'; import { ProfilePage } from '../pages/profile/profile'; import { CreateProjectPage } from '../pages/create-project/create-project'; import { EditProfilePage } from '../pages/edit-profile/edit-profile'; import { LogoutPage } from '../pages/logout/logout'; import { SearchPage } from '../pages/search/search'; import { BookmarksPage } from '../pages/bookmarks/bookmarks'; import { TutorialPage } from '../pages/tutorial/tutorial'; export interface PageInterface { title: string; component: any; icon: string; logsOut?: boolean; index?: number; tabComponent?: any; param?: String; } @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any; loggedOutPages: PageInterface[] = [ { title: 'Log In', component: LoginPage, icon: 'log-in' }, { title: 'Sign Up', component: SignupPage, icon: 'person-add' } ]; loggedInPages: PageInterface[] = [ { title: 'Home', component: HomePage, icon: 'home' }, { title: 'New Project', component: CreateProjectPage, icon: 'create' }, { title: 'Search', component: SearchPage, icon: 'search'} ]; accountPages: PageInterface[] = [ { title: 'Profile', component: ProfilePage, icon: 'person', param:'username' }, { title: 'Favourites', component: BookmarksPage, icon: 'star' }, { title: 'Edit Account', component: EditProfilePage, icon: 'contact' }, { title: 'Log out', component: LogoutPage, icon: 'log-out' } ]; aboutPages: PageInterface[] = [ { title: 'Tutorial', component: TutorialPage, icon: 'information' } ]; username: String = ""; occupation: String = ""; email: String = ""; directory: string = "assets/img/profile/"; chosenPicture: string = ""; constructor(public menu: MenuController, public events: Events, public userData: UserData, public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) { this.initializeApp(); // decide which menu items should be hidden by current login status stored in local storage this.userData.checkHasSeenTutorial().then((hasSeenTutorial) => { if(!hasSeenTutorial){ //set the root to Tutorial on the first opening of app
//set the has seen tutorial to true this.userData.setHasSeenTutorial(); }else{ this.userData.hasLoggedIn().then((hasLoggedIn) => { this.enableMenu(hasLoggedIn); if(hasLoggedIn){this.rootPage = HomePage;} else{this.rootPage = LoginPage;} }); } }); this.startEvents(); } initializeApp() { this.platform.ready().then(() => { // The platform is ready and our plugins are available. this.statusBar.styleDefault(); this.splashScreen.hide(); }); } openPage(page) { //if has param (the profile page) //set root and pass in param if(page.hasOwnProperty('param')){ this.nav.setRoot(page.component, { param1: page.param }); } else{ //set root without param this.nav.setRoot(page.component); } } //set the color of the active page to be red isActive(page: PageInterface) { if (this.nav.getActive() && this.nav.getActive().component === page.component) { return 'danger'; } return; } //toggle logged in/out menu enableMenu(loggedIn: boolean) { this.menu.enable(loggedIn, 'loggedInMenu'); this.menu.enable(!loggedIn, 'loggedOutMenu'); } //get user data for profile param, and any user data shown in the side menu getUserDetails() { this.userData.getCurrentUser().then((user) => { console.log("In get user details - app component"); console.log(user); this.username = user.username; this.occupation = user.occupation; this.email = user.email; this.chosenPicture= this.directory + user.gender + ".jpg"; this.accountPages.forEach(function(p){if (p.title === 'Profile') p.param=user.username;} ); }).catch(()=>{}); } //get user data for profile param, any user data shown in the side menu, //and trigger getLoginDetails() { this.userData.getCurrentUser().then((user) => { console.log("In get user details - app component"); console.log(user); this.username = user.username; this.occupation = user.occupation; this.email = user.email; this.chosenPicture= this.directory + user.gender + ".jpg"; this.accountPages.forEach(function(p){if (p.title === 'Profile') p.param=user.username;} ); }).then((user) => { console.log("Triggering login event"); this.events.publish('user:loggedin'); }).catch(()=>{}); } //start listening for events startEvents(){ this.events.subscribe('user:login', () => { this.getLoginDetails(); console.log("Logged in event triggered"); }); this.events.subscribe('user:loggedin', () => { this.enableMenu(true); this.nav.setRoot(HomePage); console.log("Logged in event triggered"); }); this.events.subscribe('user:changed', () => { this.getUserDetails(); console.log("User changed event triggered"); }); this.events.subscribe('user:logout', () => { this.enableMenu(false); this.nav.setRoot(LoginPage); }); } }
this.rootPage = TutorialPage; //set menu to logged out menu as the user cannot be logged in yet this.enableMenu(false);
random_line_split
horizon.py
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from horizon.contrib import bootstrap_datepicker from django.conf import settings from django import template from django.utils.datastructures import SortedDict from django.utils.encoding import force_text from django.utils import translation from django.utils.translation import ugettext_lazy as _ from horizon.base import Horizon # noqa from horizon import conf register = template.Library() @register.filter def has_permissions(user, component): """Checks if the given user meets the permissions requirements for the component. """ return user.has_perms(getattr(component, 'permissions', set())) @register.filter def has_permissions_on_list(components, user): return [component for component in components if has_permissions(user, component)] @register.inclusion_tag('horizon/_accordion_nav.html', takes_context=True) def horizon_nav(context): if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) current_panel = context['request'].horizon.get('panel', None) dashboards = [] for dash in Horizon.get_dashboards(): panel_groups = dash.get_panel_groups() non_empty_groups = [] for group in panel_groups.values(): allowed_panels = [] for panel in group: if (callable(panel.nav) and panel.nav(context) and panel.can_access(context)): allowed_panels.append(panel) elif (not callable(panel.nav) and panel.nav and panel.can_access(context)): allowed_panels.append(panel) if allowed_panels: non_empty_groups.append((group.name, allowed_panels)) if (callable(dash.nav) and dash.nav(context) and dash.can_access(context)): dashboards.append((dash, SortedDict(non_empty_groups))) elif (not callable(dash.nav) and dash.nav and dash.can_access(context)): dashboards.append((dash, SortedDict(non_empty_groups))) return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'current_panel': current_panel.slug if current_panel else '', 'request': context['request']} @register.inclusion_tag('horizon/_nav_list.html', takes_context=True) def horizon_main_nav(context): """Generates top-level dashboard navigation entries.""" if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if dash.can_access(context):
return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'request': context['request']} @register.inclusion_tag('horizon/_subnav_list.html', takes_context=True) def horizon_dashboard_nav(context): """Generates sub-navigation entries for the current dashboard.""" if 'request' not in context: return {} dashboard = context['request'].horizon['dashboard'] panel_groups = dashboard.get_panel_groups() non_empty_groups = [] for group in panel_groups.values(): allowed_panels = [] for panel in group: if (callable(panel.nav) and panel.nav(context) and panel.can_access(context)): allowed_panels.append(panel) elif (not callable(panel.nav) and panel.nav and panel.can_access(context)): allowed_panels.append(panel) if allowed_panels: if group.name is None: non_empty_groups.append((dashboard.name, allowed_panels)) else: non_empty_groups.append((group.name, allowed_panels)) return {'components': SortedDict(non_empty_groups), 'user': context['request'].user, 'current': context['request'].horizon['panel'].slug, 'request': context['request']} @register.filter def quota(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s %s" % (val, force_text(units), force_text(_("Available"))) else: return "%s %s" % (val, force_text(_("Available"))) @register.filter def quotainf(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s" % (val, units) else: return val class JSTemplateNode(template.Node): """Helper node for the ``jstemplate`` template tag.""" def __init__(self, nodelist): self.nodelist = nodelist def render(self, context,): output = self.nodelist.render(context) output = output.replace('[[[', '{{{').replace(']]]', '}}}') output = output.replace('[[', '{{').replace(']]', '}}') output = output.replace('[%', '{%').replace('%]', '%}') return output @register.tag def jstemplate(parser, token): """Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``, ``[[`` and ``]]`` with ``{{`` and ``}}`` and ``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts with Django's template engine when using any of the Mustache-based templating libraries. """ nodelist = parser.parse(('endjstemplate',)) parser.delete_first_token() return JSTemplateNode(nodelist) @register.assignment_tag def load_config(): return conf.HORIZON_CONFIG @register.assignment_tag def datepicker_locale(): locale_mapping = getattr(settings, 'DATEPICKER_LOCALES', bootstrap_datepicker.LOCALE_MAPPING) return locale_mapping.get(translation.get_language(), 'en')
if callable(dash.nav) and dash.nav(context): dashboards.append(dash) elif dash.nav: dashboards.append(dash)
conditional_block
horizon.py
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from horizon.contrib import bootstrap_datepicker from django.conf import settings from django import template from django.utils.datastructures import SortedDict from django.utils.encoding import force_text from django.utils import translation from django.utils.translation import ugettext_lazy as _ from horizon.base import Horizon # noqa from horizon import conf register = template.Library() @register.filter def has_permissions(user, component): """Checks if the given user meets the permissions requirements for the component. """ return user.has_perms(getattr(component, 'permissions', set())) @register.filter def has_permissions_on_list(components, user): return [component for component in components if has_permissions(user, component)] @register.inclusion_tag('horizon/_accordion_nav.html', takes_context=True) def horizon_nav(context): if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) current_panel = context['request'].horizon.get('panel', None) dashboards = [] for dash in Horizon.get_dashboards(): panel_groups = dash.get_panel_groups() non_empty_groups = [] for group in panel_groups.values(): allowed_panels = [] for panel in group: if (callable(panel.nav) and panel.nav(context) and panel.can_access(context)): allowed_panels.append(panel) elif (not callable(panel.nav) and panel.nav and panel.can_access(context)): allowed_panels.append(panel) if allowed_panels: non_empty_groups.append((group.name, allowed_panels)) if (callable(dash.nav) and dash.nav(context) and dash.can_access(context)): dashboards.append((dash, SortedDict(non_empty_groups))) elif (not callable(dash.nav) and dash.nav and dash.can_access(context)): dashboards.append((dash, SortedDict(non_empty_groups))) return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'current_panel': current_panel.slug if current_panel else '', 'request': context['request']} @register.inclusion_tag('horizon/_nav_list.html', takes_context=True) def horizon_main_nav(context): """Generates top-level dashboard navigation entries.""" if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if dash.can_access(context): if callable(dash.nav) and dash.nav(context): dashboards.append(dash) elif dash.nav: dashboards.append(dash) return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'request': context['request']} @register.inclusion_tag('horizon/_subnav_list.html', takes_context=True) def horizon_dashboard_nav(context): """Generates sub-navigation entries for the current dashboard.""" if 'request' not in context: return {} dashboard = context['request'].horizon['dashboard'] panel_groups = dashboard.get_panel_groups() non_empty_groups = [] for group in panel_groups.values(): allowed_panels = [] for panel in group: if (callable(panel.nav) and panel.nav(context) and panel.can_access(context)): allowed_panels.append(panel) elif (not callable(panel.nav) and panel.nav and panel.can_access(context)): allowed_panels.append(panel) if allowed_panels: if group.name is None: non_empty_groups.append((dashboard.name, allowed_panels)) else: non_empty_groups.append((group.name, allowed_panels)) return {'components': SortedDict(non_empty_groups), 'user': context['request'].user, 'current': context['request'].horizon['panel'].slug, 'request': context['request']} @register.filter def quota(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s %s" % (val, force_text(units), force_text(_("Available"))) else: return "%s %s" % (val, force_text(_("Available"))) @register.filter def quotainf(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s" % (val, units) else: return val class JSTemplateNode(template.Node): """Helper node for the ``jstemplate`` template tag.""" def __init__(self, nodelist): self.nodelist = nodelist
def render(self, context,): output = self.nodelist.render(context) output = output.replace('[[[', '{{{').replace(']]]', '}}}') output = output.replace('[[', '{{').replace(']]', '}}') output = output.replace('[%', '{%').replace('%]', '%}') return output @register.tag def jstemplate(parser, token): """Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``, ``[[`` and ``]]`` with ``{{`` and ``}}`` and ``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts with Django's template engine when using any of the Mustache-based templating libraries. """ nodelist = parser.parse(('endjstemplate',)) parser.delete_first_token() return JSTemplateNode(nodelist) @register.assignment_tag def load_config(): return conf.HORIZON_CONFIG @register.assignment_tag def datepicker_locale(): locale_mapping = getattr(settings, 'DATEPICKER_LOCALES', bootstrap_datepicker.LOCALE_MAPPING) return locale_mapping.get(translation.get_language(), 'en')
random_line_split
horizon.py
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from horizon.contrib import bootstrap_datepicker from django.conf import settings from django import template from django.utils.datastructures import SortedDict from django.utils.encoding import force_text from django.utils import translation from django.utils.translation import ugettext_lazy as _ from horizon.base import Horizon # noqa from horizon import conf register = template.Library() @register.filter def has_permissions(user, component): """Checks if the given user meets the permissions requirements for the component. """ return user.has_perms(getattr(component, 'permissions', set())) @register.filter def has_permissions_on_list(components, user): return [component for component in components if has_permissions(user, component)] @register.inclusion_tag('horizon/_accordion_nav.html', takes_context=True) def horizon_nav(context): if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) current_panel = context['request'].horizon.get('panel', None) dashboards = [] for dash in Horizon.get_dashboards(): panel_groups = dash.get_panel_groups() non_empty_groups = [] for group in panel_groups.values(): allowed_panels = [] for panel in group: if (callable(panel.nav) and panel.nav(context) and panel.can_access(context)): allowed_panels.append(panel) elif (not callable(panel.nav) and panel.nav and panel.can_access(context)): allowed_panels.append(panel) if allowed_panels: non_empty_groups.append((group.name, allowed_panels)) if (callable(dash.nav) and dash.nav(context) and dash.can_access(context)): dashboards.append((dash, SortedDict(non_empty_groups))) elif (not callable(dash.nav) and dash.nav and dash.can_access(context)): dashboards.append((dash, SortedDict(non_empty_groups))) return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'current_panel': current_panel.slug if current_panel else '', 'request': context['request']} @register.inclusion_tag('horizon/_nav_list.html', takes_context=True) def horizon_main_nav(context): """Generates top-level dashboard navigation entries.""" if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if dash.can_access(context): if callable(dash.nav) and dash.nav(context): dashboards.append(dash) elif dash.nav: dashboards.append(dash) return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'request': context['request']} @register.inclusion_tag('horizon/_subnav_list.html', takes_context=True) def
(context): """Generates sub-navigation entries for the current dashboard.""" if 'request' not in context: return {} dashboard = context['request'].horizon['dashboard'] panel_groups = dashboard.get_panel_groups() non_empty_groups = [] for group in panel_groups.values(): allowed_panels = [] for panel in group: if (callable(panel.nav) and panel.nav(context) and panel.can_access(context)): allowed_panels.append(panel) elif (not callable(panel.nav) and panel.nav and panel.can_access(context)): allowed_panels.append(panel) if allowed_panels: if group.name is None: non_empty_groups.append((dashboard.name, allowed_panels)) else: non_empty_groups.append((group.name, allowed_panels)) return {'components': SortedDict(non_empty_groups), 'user': context['request'].user, 'current': context['request'].horizon['panel'].slug, 'request': context['request']} @register.filter def quota(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s %s" % (val, force_text(units), force_text(_("Available"))) else: return "%s %s" % (val, force_text(_("Available"))) @register.filter def quotainf(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s" % (val, units) else: return val class JSTemplateNode(template.Node): """Helper node for the ``jstemplate`` template tag.""" def __init__(self, nodelist): self.nodelist = nodelist def render(self, context,): output = self.nodelist.render(context) output = output.replace('[[[', '{{{').replace(']]]', '}}}') output = output.replace('[[', '{{').replace(']]', '}}') output = output.replace('[%', '{%').replace('%]', '%}') return output @register.tag def jstemplate(parser, token): """Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``, ``[[`` and ``]]`` with ``{{`` and ``}}`` and ``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts with Django's template engine when using any of the Mustache-based templating libraries. """ nodelist = parser.parse(('endjstemplate',)) parser.delete_first_token() return JSTemplateNode(nodelist) @register.assignment_tag def load_config(): return conf.HORIZON_CONFIG @register.assignment_tag def datepicker_locale(): locale_mapping = getattr(settings, 'DATEPICKER_LOCALES', bootstrap_datepicker.LOCALE_MAPPING) return locale_mapping.get(translation.get_language(), 'en')
horizon_dashboard_nav
identifier_name
horizon.py
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from horizon.contrib import bootstrap_datepicker from django.conf import settings from django import template from django.utils.datastructures import SortedDict from django.utils.encoding import force_text from django.utils import translation from django.utils.translation import ugettext_lazy as _ from horizon.base import Horizon # noqa from horizon import conf register = template.Library() @register.filter def has_permissions(user, component): """Checks if the given user meets the permissions requirements for the component. """ return user.has_perms(getattr(component, 'permissions', set())) @register.filter def has_permissions_on_list(components, user): return [component for component in components if has_permissions(user, component)] @register.inclusion_tag('horizon/_accordion_nav.html', takes_context=True) def horizon_nav(context): if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) current_panel = context['request'].horizon.get('panel', None) dashboards = [] for dash in Horizon.get_dashboards(): panel_groups = dash.get_panel_groups() non_empty_groups = [] for group in panel_groups.values(): allowed_panels = [] for panel in group: if (callable(panel.nav) and panel.nav(context) and panel.can_access(context)): allowed_panels.append(panel) elif (not callable(panel.nav) and panel.nav and panel.can_access(context)): allowed_panels.append(panel) if allowed_panels: non_empty_groups.append((group.name, allowed_panels)) if (callable(dash.nav) and dash.nav(context) and dash.can_access(context)): dashboards.append((dash, SortedDict(non_empty_groups))) elif (not callable(dash.nav) and dash.nav and dash.can_access(context)): dashboards.append((dash, SortedDict(non_empty_groups))) return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'current_panel': current_panel.slug if current_panel else '', 'request': context['request']} @register.inclusion_tag('horizon/_nav_list.html', takes_context=True) def horizon_main_nav(context): """Generates top-level dashboard navigation entries.""" if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if dash.can_access(context): if callable(dash.nav) and dash.nav(context): dashboards.append(dash) elif dash.nav: dashboards.append(dash) return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'request': context['request']} @register.inclusion_tag('horizon/_subnav_list.html', takes_context=True) def horizon_dashboard_nav(context): """Generates sub-navigation entries for the current dashboard.""" if 'request' not in context: return {} dashboard = context['request'].horizon['dashboard'] panel_groups = dashboard.get_panel_groups() non_empty_groups = [] for group in panel_groups.values(): allowed_panels = [] for panel in group: if (callable(panel.nav) and panel.nav(context) and panel.can_access(context)): allowed_panels.append(panel) elif (not callable(panel.nav) and panel.nav and panel.can_access(context)): allowed_panels.append(panel) if allowed_panels: if group.name is None: non_empty_groups.append((dashboard.name, allowed_panels)) else: non_empty_groups.append((group.name, allowed_panels)) return {'components': SortedDict(non_empty_groups), 'user': context['request'].user, 'current': context['request'].horizon['panel'].slug, 'request': context['request']} @register.filter def quota(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s %s" % (val, force_text(units), force_text(_("Available"))) else: return "%s %s" % (val, force_text(_("Available"))) @register.filter def quotainf(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s" % (val, units) else: return val class JSTemplateNode(template.Node):
@register.tag def jstemplate(parser, token): """Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``, ``[[`` and ``]]`` with ``{{`` and ``}}`` and ``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts with Django's template engine when using any of the Mustache-based templating libraries. """ nodelist = parser.parse(('endjstemplate',)) parser.delete_first_token() return JSTemplateNode(nodelist) @register.assignment_tag def load_config(): return conf.HORIZON_CONFIG @register.assignment_tag def datepicker_locale(): locale_mapping = getattr(settings, 'DATEPICKER_LOCALES', bootstrap_datepicker.LOCALE_MAPPING) return locale_mapping.get(translation.get_language(), 'en')
"""Helper node for the ``jstemplate`` template tag.""" def __init__(self, nodelist): self.nodelist = nodelist def render(self, context,): output = self.nodelist.render(context) output = output.replace('[[[', '{{{').replace(']]]', '}}}') output = output.replace('[[', '{{').replace(']]', '}}') output = output.replace('[%', '{%').replace('%]', '%}') return output
identifier_body