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 |
|---|---|---|---|---|
game.ts | }
const gameDebugger = new GameDebugger(true);
interface FlyingProperties {
gravity: number;
jumpVelocity: number;
flightAreaBox: BoundingBox;
}
interface BoundingBox {
x: number;
y: number;
width: number;
height: number;
}
interface GameHtmlElements {
bird: HTMLElement;
land: HT... | console.log(`[${shortTime}]`, ...args);
this.domLogs.innerText += `[${shortTime}] ${args.map(a => a?.toString()).join(' ')}\n`;
} | random_line_split | |
game.ts | boudingBox.style.left = `${box.x}px`;
boudingBox.style.width = `${box.width}px`;
boudingBox.style.height = `${box.height}px`;
}
public resetBoxes() {
if (!this.enabled) {
return;
}
// Only pipes need resetting. Land and bird are recycled. The debugg... | {
if (!this.enabled) {
return;
}
if (!this.domBoxes.has(key)) {
const newDebugBox = document.createElement('div');
newDebugBox.className = 'boundingbox';
this.domBoxContainer.appendChild(newDebugBox);
this.domBoxes.set(key, newDebugBox... | identifier_body | |
game.ts | shortTime}] ${args.map(a => a?.toString()).join(' ')}\n`;
}
}
const gameDebugger = new GameDebugger(true);
interface FlyingProperties {
gravity: number;
jumpVelocity: number;
flightAreaBox: BoundingBox;
}
interface BoundingBox {
x: number;
y: number;
width: number;
height: number;
}
... |
if (this.position > this.flyingProperties.flightAreaBox.height) {
this.position = this.flyingProperties.flightAreaBox.height;
}
// We draw our bounding box around the bird through | {
this.position = 0;
} | conditional_block |
game.ts | (oldState: GameState, newState: GameState) {
if (!this.enabled) {
return;
}
this.log('Changing state', GameState[oldState], GameState[newState]);
this.domState.innerText = GameState[newState];
}
public log(...args: any[]) {
if (!this.enabled) {
r... | logStateChange | identifier_name | |
navbar-item.component.view.spec.ts | import { async, TestBed } from '@angular/core/testing';
import { buildComponent, MzTestWrapperComponent } from '../../shared/test-wrapper';
import { MzNavbarItemComponent } from './navbar-item.component';
describe('MzNavbarItemComponent:view', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
... | fixture.detectChanges();
expect(item().classList).toContain('active');
});
}));
it('should not have active class when active prop is not provided', async(() => {
buildComponent<MzNavbarItemComponent>(`<mz-navbar-item></mz-navbar-item>`).then((fixture) => {
nativeElement =... |
buildComponent<MzNavbarItemComponent>(`<mz-navbar-item [active]="'true'"></mz-navbar-item>`).then((fixture) => {
nativeElement = fixture.nativeElement; | random_line_split |
navbar-item.component.view.spec.ts | import { async, TestBed } from '@angular/core/testing';
import { buildComponent, MzTestWrapperComponent } from '../../shared/test-wrapper';
import { MzNavbarItemComponent } from './navbar-item.component';
describe('MzNavbarItemComponent:view', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
... |
it('should display a navbar item', async(() => {
buildComponent<MzNavbarItemComponent>(`<mz-navbar-item></mz-navbar-item>`).then((fixture) => {
nativeElement = fixture.nativeElement;
fixture.detectChanges();
expect(item()).toBeTruthy();
});
}));
it('should have cust... | {
return nativeElement.querySelector('li');
} | identifier_body |
navbar-item.component.view.spec.ts | import { async, TestBed } from '@angular/core/testing';
import { buildComponent, MzTestWrapperComponent } from '../../shared/test-wrapper';
import { MzNavbarItemComponent } from './navbar-item.component';
describe('MzNavbarItemComponent:view', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
... | (): HTMLElement {
return nativeElement.querySelector('li');
}
it('should display a navbar item', async(() => {
buildComponent<MzNavbarItemComponent>(`<mz-navbar-item></mz-navbar-item>`).then((fixture) => {
nativeElement = fixture.nativeElement;
fixture.detectChanges();
ex... | item | identifier_name |
localization.py | import pytz
from django.conf import settings
from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR
from django.utils.translation import gettext as _
# Wagtail languages with >=90% coverage
# This list is manually maintained
WAGTAILADMIN_PROVIDED_LANGUAGES = [
('ar', 'Arabic'),
('ca', 'Catalan'),
... | ):
return {
'DELETE': _('Delete'),
'EDIT': _('Edit'),
'PAGE': _('Page'),
'PAGES': _('Pages'),
'LOADING': _('Loading…'),
'NO_RESULTS': _('No results'),
'SERVER_ERROR': _('Server Error'),
'SEE_ALL': _('See all'),
'CLOSE_EXPLORER': _('Close explor... | et_js_translation_strings( | identifier_name |
localization.py | import pytz
from django.conf import settings
from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR
from django.utils.translation import gettext as _
# Wagtail languages with >=90% coverage
# This list is manually maintained
WAGTAILADMIN_PROVIDED_LANGUAGES = [
('ar', 'Arabic'),
('ca', 'Catalan'),
... | return getattr(settings, 'WAGTAIL_USER_TIME_ZONES', pytz.common_timezones)
| n []
| conditional_block |
localization.py | import pytz
from django.conf import settings
from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR
from django.utils.translation import gettext as _
# Wagtail languages with >=90% coverage
# This list is manually maintained
WAGTAILADMIN_PROVIDED_LANGUAGES = [
('ar', 'Arabic'),
('ca', 'Catalan'),
... | 'SHOW_ERROR': _('Show error'),
'EDITOR_CRASH': _('The editor just crashed. Content has been reset to the last saved version.'),
'BROKEN_LINK': _('Broken link'),
'MISSING_DOCUMENT': _('Missing document'),
'CLOSE': _('Close'),
'EDIT_PAGE': _('Edit \'{title}\''),
'VI... | eturn {
'DELETE': _('Delete'),
'EDIT': _('Edit'),
'PAGE': _('Page'),
'PAGES': _('Pages'),
'LOADING': _('Loading…'),
'NO_RESULTS': _('No results'),
'SERVER_ERROR': _('Server Error'),
'SEE_ALL': _('See all'),
'CLOSE_EXPLORER': _('Close explorer'),
... | identifier_body |
localization.py | import pytz
from django.conf import settings
from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR
from django.utils.translation import gettext as _
# Wagtail languages with >=90% coverage
# This list is manually maintained
WAGTAILADMIN_PROVIDED_LANGUAGES = [
('ar', 'Arabic'),
('ca', 'Catalan'),
... | def get_available_admin_time_zones():
if not settings.USE_TZ:
return []
return getattr(settings, 'WAGTAIL_USER_TIME_ZONES', pytz.common_timezones) | def get_available_admin_languages():
return getattr(settings, 'WAGTAILADMIN_PERMITTED_LANGUAGES', WAGTAILADMIN_PROVIDED_LANGUAGES)
| random_line_split |
viewer.js | (marker, numPhotos) {
var zIndex = 0;
if (selected_marker) {
zIndex = selected_marker.getZIndex();
selected_marker.setIcon(selected_icon);
}
if (marker) {
selected_marker = marker;
selected_icon = marker.getIcon();
marker.setIcon(selected_marker_icons[numPhotos > 100 ? 100 : numPhotos]);
... | selectMarker | identifier_name | |
viewer.js | panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
},
styles: MAP_STYLE
};
map = new google.maps.Map($('#map').get(0), opts);
// This shoves the navigation bits down by a CSS-specified amount
// (see the .spacer rule). This is surprisingly hard to d... | $btn.css({width: $btn.get(0).offsetWidth}).addClass('clicked').text('Copied!');
});
});
twttr.widgets.createShareButton(
document.location.href,
$pane.find('.tweet').get(0), {
count: 'none',
text: (info.original_title || info.title) + ' - ' + info.date,
via: 'Old_NY... | clipboard.setData('text/plain', window.location.href);
});
client.on( 'aftercopy', function( event ) {
var $btn = $(event.target); | random_line_split |
viewer.js | amount
// (see the .spacer rule). This is surprisingly hard to do.
var map_spacer = $('<div/>').append($('<div/>').addClass('spacer')).get(0);
map_spacer.index = -1;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(map_spacer);
// The OldSF UI just gets in the way of Street View.
// Even worse, it ... | {
var $img = $(img);
if ($img.attr('src')) return;
$(img)
.attr('src', $(img).attr('data-src'))
.removeAttr('data-src');
} | identifier_body | |
viewer.js | .find('.share'));
client.on('ready', function() {
client.on('copy', function(event) {
var clipboard = event.clipboardData;
clipboard.setData('text/plain', window.location.href);
});
client.on( 'aftercopy', function( event ) {
var $btn = $(event.target);
$btn.css({width: $btn.get(0)... | {
var $input = $button.siblings('input, textarea');
value = $input.val();
if (value == '') return;
$input.prop('disabled', true);
} | conditional_block | |
base.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
define(
[
'underscore',
'backbone',
'lib/localizer'
],
function (_, Backbone, Localizer) {
'... |
return context;
},
/**
* Localizes English input text.
*
* @method localize
* @return {String} localized text
*/
localize: function (text) {
return Localizer.localize(text);
},
/**
* Renders by combining template and context and inser... | {
context = {};
} | conditional_block |
base.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
define(
[
'underscore',
'backbone',
'lib/localizer'
],
function (_, Backbone, Localizer) {
'... | } else {
context = {};
}
return context;
},
/**
* Localizes English input text.
*
* @method localize
* @return {String} localized text
*/
localize: function (text) {
return Localizer.localize(text);
},
/**
* R... | context = this.model.attributes; | random_line_split |
browser.js | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... | * @module mm.core
* @ngdoc directive
* @name mmBrowser
*
* @param {Boolean} [captureLink=false] If the link needs to be captured by the app.
*/
.directive('mmBrowser', function($mmUtil, $mmContentLinksHelper) {
/**
* Convenience function to open file or url in the browser.
*
* @param {String}... | * Directive to open a link in external browser.
* | random_line_split |
browser.js | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... | else {
openInBrowser(href);
}
}
});
}
};
});
| {
$mmContentLinksHelper.handleLink(href).then(function(treated) {
if (!treated) {
openInBrowser(href);
}
});
} | conditional_block |
browser.js | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... |
return {
restrict: 'A',
priority: 100,
link: function(scope, element, attrs) {
element.on('click', function(event) {
var href = element[0].getAttribute('href');
if (href) {
event.preventDefault();
event.sto... | {
if (href.indexOf('cdvfile://') === 0 || href.indexOf('file://') === 0) {
// We have a local file.
$mmUtil.openFile(href).catch(function(error) {
$mmUtil.showErrorModal(error);
});
} else {
// It's an external link, we will open with brows... | identifier_body |
browser.js | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... | (href) {
if (href.indexOf('cdvfile://') === 0 || href.indexOf('file://') === 0) {
// We have a local file.
$mmUtil.openFile(href).catch(function(error) {
$mmUtil.showErrorModal(error);
});
} else {
// It's an external link, we will open wit... | openInBrowser | identifier_name |
constant.rs | // Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/license/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 distri... |
fn find_case<'a>(&'a self, expected: bool, variable: &Item) -> Option<reflection::Case<'a>> {
utils::default_find_case(self, expected, variable)
}
}
impl reflection::PredicateReflection for BooleanPredicate {
fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> ... | {
self.retval
} | identifier_body |
constant.rs | // Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/license/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 distri... | use crate::utils;
use crate::Predicate;
/// Predicate that always returns a constant (boolean) result.
///
/// This is created by the `predicate::always` and `predicate::never` functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BooleanPredicate {
retval: bool,
}
impl<Item: ?Sized> Predicate<Item> ... | use crate::reflection; | random_line_split |
constant.rs | // Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/license/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 distri... | () -> BooleanPredicate {
BooleanPredicate { retval: false }
}
| never | identifier_name |
objc_interface_type.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#![cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
#[allow(non_camel_case_types)]
pub type id = *mut objc::runtime::Object;
#[repr(transparent)]
#[derive(Clone)]
pub struct Foo(pub id);
impl std::ops::Deref f... | {
pub foo: Foo,
}
#[test]
fn bindgen_test_layout_FooStruct() {
assert_eq!(
::std::mem::size_of::<FooStruct>(),
8usize,
concat!("Size of: ", stringify!(FooStruct))
);
assert_eq!(
::std::mem::align_of::<FooStruct>(),
8usize,
concat!("Alignment of ", stringi... | FooStruct | identifier_name |
objc_interface_type.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#![cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
#[allow(non_camel_case_types)]
pub type id = *mut objc::runtime::Object;
#[repr(transparent)]
#[derive(Clone)]
pub struct Foo(pub id);
impl std::ops::Deref f... | );
}
impl Default for FooStruct {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
extern "C" {
pub fn fooFunc(foo: Foo);
}
extern "C" {
pub stat... | random_line_split | |
od.rs | // Copyright 2016-2020 James Bostock. See the LICENSE file at the top-level
// directory of this distribution.
// An implementation of the od(1) command in Rust.
// See http://man.cat-v.org/unix-6th/1/od
use std::env;
use std::io;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Read;
use std::io::Seek;
us... | (out: &mut BufWriter<Stdout>, data: &[u8])
-> io::Result<usize> {
for byte in data {
write!(out, " {:03o}", byte)?;
}
writeln!(out)?;
Ok(data.len())
}
/// Writes a chunk of output data as octal (16 bit) word values. Words are
/// assumed to be little endian.
fn write_oct_word... | write_oct_bytes | identifier_name |
od.rs | // Copyright 2016-2020 James Bostock. See the LICENSE file at the top-level
// directory of this distribution.
// An implementation of the od(1) command in Rust.
// See http://man.cat-v.org/unix-6th/1/od
use std::env;
use std::io;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Read;
use std::io::Seek;
us... |
/// Writes a chunk of output data as octal (16 bit) word values. Words are
/// assumed to be little endian.
fn write_oct_words(out: &mut BufWriter<Stdout>, data: &[u8])
-> io::Result<usize> {
for word in data.chunks(2) {
write!(out, " {:06o}", u16::from(word[1]) << 8 | u16::from(word[0... | {
for byte in data {
write!(out, " {:03o}", byte)?;
}
writeln!(out)?;
Ok(data.len())
} | identifier_body |
od.rs | // Copyright 2016-2020 James Bostock. See the LICENSE file at the top-level
// directory of this distribution.
// An implementation of the od(1) command in Rust.
// See http://man.cat-v.org/unix-6th/1/od
use std::env;
use std::io;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Read;
use std::io::Seek;
us... | Ok(data.len())
}
/// Writes a chunk of data as ASCII, reverting to octal byte values for
/// non-printable characters. Standard escape sequences are supported.
fn write_ascii_chars(out: &mut BufWriter<Stdout>, data: &[u8])
-> io::Result<usize> {
for byte in data {
match *byte {
... | for word in data.chunks(2) {
write!(out, " {:06x}", u16::from(word[1]) << 8 | u16::from(word[0]))?;
}
writeln!(out)?; | random_line_split |
test_cp2_creturn_trap.py | #-
# Copyright (c) 2013 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BER... | (self):
'''Test that creturn sets the cap cause register'''
self.assertRegisterEqual(self.MIPS.a3, 0x06ff,
"creturn did not set capability cause correctly")
@attr('capabilities')
def test_cp_creturn3(self):
'''Test that $kcc is copied to $pcc when trap handler runs'''
... | test_cp_creturn2 | identifier_name |
test_cp2_creturn_trap.py | #-
# Copyright (c) 2013 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BER... | @attr('capabilities')
def test_cp_creturn2(self):
'''Test that creturn sets the cap cause register'''
self.assertRegisterEqual(self.MIPS.a3, 0x06ff,
"creturn did not set capability cause correctly")
@attr('capabilities')
def test_cp_creturn3(self):
'''Test that $kcc ... | random_line_split | |
test_cp2_creturn_trap.py | #-
# Copyright (c) 2013 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BER... | '''Test that creturn restored full perms to $pcc'''
self.assertRegisterEqual(self.MIPS.a6, 0x7fffffff,
"creturn did not restore full perms to $pcc") | identifier_body | |
mod.rs | LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOF... | &mut self, msg_times: [Duration; 2], update: EntityUpdate) {
// enable lerping
self.force_link = false;
if update.no_lerp || self.msg_time != msg_times[1] {
self.force_link = true;
}
self.msg_time = msg_times[0];
// fill in missing values from baseline
... | pdate( | identifier_name |
mod.rs | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE... | }
}
pub fn uninitialized() -> ClientEntity {
ClientEntity {
force_link: false,
baseline: EntityState::uninitialized(),
msg_time: Duration::zero(),
msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)],
origin: Vector3... |
ClientEntity {
force_link: false,
baseline: baseline.clone(),
msg_time: Duration::zero(),
msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)],
origin: baseline.origin,
msg_angles: [
Vector3::new(Deg(0.0)... | identifier_body |
mod.rs | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE... | pub fn from_baseline(baseline: EntityState) -> ClientEntity {
ClientEntity {
force_link: false,
baseline: baseline.clone(),
msg_time: Duration::zero(),
msg_origins: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)],
origin: baseline.origin... | }
impl ClientEntity { | random_line_split |
mod.rs | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE... | }
radius
}
/// Returns `true` if the light should be retained at the specified time.
pub fn retain(&mut self, time: Duration) -> bool {
self.spawned + self.ttl > time
}
}
/// A set of active dynamic lights.
pub struct Lights {
slab: LinkedSlab<Light>,
}
impl Lights {
... |
return 0.0;
}
| conditional_block |
CurrentCourseStore.spec.js | 'use strict';
var CurrentCourseStore = require('../../../js/stores/CurrentCourseStore');
var CourseActions = require('../../../js/actions/CourseActions');
require('../../../utils/createAuthenticatedSuite')('Store: CurrentCourse', function() {
it('should be empty on init', function(done) {
(CurrentCourseSt... | CurrentCourseStore.course.id.should.equal(1);
done();
});
});
it('should load a course on action', function(done) {
CourseActions.openCourse(1, function(err) {
(err === null).should.be.true; // jshint ignore:line
CurrentCourseStore.course.should.be.instanceOf(Object);
CurrentC... |
CourseActions.setCourse(course, function(err) {
(err === null).should.be.true; // jshint ignore:line
CurrentCourseStore.course.should.be.instanceOf(Object); | random_line_split |
index.d.ts | // Type definitions for @webpack-blocks/assets 2.0
// Project: https://github.com/andywer/webpack-blocks/tree/master/packages/assets
// Definitions by: Max Boguslavskiy <https://github.com/maxbogus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.7
import { Block } from 'web... | type ImportFilter = (parseImport: ParseImportOptions, resourcePath: string) => boolean;
type GetLocalIdent = (context: any, localIdentName: any, localName: any, options: any) => string;
type NameFunction = (file: string) => any;
type PathFunction = (url: string, resourcePath: string, context: string) =>... |
export namespace css {
type UrlFilter = (url: string, resourcePath: string) => boolean; | random_line_split |
app.js | // Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
/*jslint browser: true, continue: true, plusplus: true */
/*global $... |
function isEmptyObject(obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
function debounce(func, wait) {
var timeout, args, context, timestamp, result, again;
var later = function () {
var last = Date.now() - timestamp;
if (last < wait) {
... | {
var result = '';
for (var i = 0; i < len; i++) {
result += charset[Math.round(Math.random() * (charset.length - 1))];
}
return result;
} | identifier_body |
app.js | // Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
/*jslint browser: true, continue: true, plusplus: true */
/*global $... | (obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
function debounce(func, wait) {
var timeout, args, context, timestamp, result, again;
var later = function () {
var last = Date.now() - timestamp;
if (last < wait) {
timeout = setTimeout(la... | isEmptyObject | identifier_name |
app.js | // Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
/*jslint browser: true, continue: true, plusplus: true */
/*global $... | }
return result;
};
} | result = func.apply(context, args);
context = args = null;
} else {
again = true; | random_line_split |
app.js | // Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
/*jslint browser: true, continue: true, plusplus: true */
/*global $... |
};
return function () {
context = this;
args = arguments;
timestamp = Date.now();
if (!timeout) {
timeout = setTimeout(later, wait);
result = func.apply(context, args);
context = args = null;
} else {
again = true;
... | {
timeout = null;
if (again) {
again = false;
result = func.apply(context, args);
context = args = null;
}
} | conditional_block |
arcvec.rs | use std::sync::Arc;
use std::fmt;
use std::ops::Deref;
#[derive(Clone)]
pub struct ArcVec<T> {
data: Arc<Vec<T>>,
offset: usize,
length: usize,
}
impl <T> ArcVec<T> {
pub fn new(data: Vec<T>) -> ArcVec<T> { | ArcVec {
data: Arc::new(data),
offset: 0,
length: length
}
}
pub fn offset(mut self, offset: usize) -> ArcVec<T> {
assert!(offset <= self.length);
self.offset += offset;
self.length -= offset;
self
}
pub fn limit(mut... | let length = data.len(); | random_line_split |
arcvec.rs | use std::sync::Arc;
use std::fmt;
use std::ops::Deref;
#[derive(Clone)]
pub struct | <T> {
data: Arc<Vec<T>>,
offset: usize,
length: usize,
}
impl <T> ArcVec<T> {
pub fn new(data: Vec<T>) -> ArcVec<T> {
let length = data.len();
ArcVec {
data: Arc::new(data),
offset: 0,
length: length
}
}
pub fn offset(mut self, offset... | ArcVec | identifier_name |
test.py | #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
import argparse
import os
import re
import subprocess
import sys
import traceback
import json
def main():
|
if __name__ ==
"__main__":
try:
main()
except Exception, ex:
traceback.print_exc(file=sys.stdout)
exit(1)
exit(0)
| parser = argparse.ArgumentParser(description='Test discovery for Zabbix',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--discovery", dest="discovery", action='store_true', help="Режим обнаружения")
parser.add_argument('integers', metavar='N', type=int, nargs='*',
... | identifier_body |
test.py | #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
import argparse
import os
import re
import subprocess
import sys
import traceback
import json
def main():
parser = argparse.ArgumentParser(description='Test discovery for Zabbix',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argumen... | "__main__":
try:
main()
except Exception, ex:
traceback.print_exc(file=sys.stdout)
exit(1)
exit(0)
| ntegers[0] + args.integers[1])
if __name__ == | conditional_block |
test.py | #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
import argparse
import os
import re
import subprocess
import sys
import traceback
import json
def main():
parser = argparse.ArgumentParser(description='Test discovery for Zabbix', |
args = parser.parse_args()
if args.discovery:
data = [
{"{#T1}": "1","{#T2}": "1"},
{"{#T1}": "1","{#T2}": "2"},
{"{#T1}": "2","{#T2}": "1"},
{"{#T1}": "2","{#T2}": "2"}
]
result = json.dumps({"data": data})
print result
e... | formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--discovery", dest="discovery", action='store_true', help="Режим обнаружения")
parser.add_argument('integers', metavar='N', type=int, nargs='*',
help='an integer for the accumulator') | random_line_split |
test.py | #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
import argparse
import os
import re
import subprocess
import sys
import traceback
import json
def | ():
parser = argparse.ArgumentParser(description='Test discovery for Zabbix',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--discovery", dest="discovery", action='store_true', help="Режим обнаружения")
parser.add_argument('integers', metavar='N', type=int, nargs='*',... | main | identifier_name |
test_io_ilg.py | import pytest
import os
import sys
from polyglotdb.io import inspect_ilg
from polyglotdb.io.helper import guess_type
from polyglotdb.exceptions import DelimiterError, ILGWordMismatchError
from polyglotdb import CorpusContext
def | (ilg_test_dir):
basic_path = os.path.join(ilg_test_dir, 'basic.txt')
parser = inspect_ilg(basic_path)
assert (len(parser.annotation_tiers) == 2)
assert (parser.annotation_tiers[1].trans_delimiter == '.')
def test_inspect_ilg_directory(ilg_test_dir):
parser = inspect_ilg(ilg_test_dir)
assert (l... | test_inspect_ilg | identifier_name |
test_io_ilg.py | import pytest
import os
import sys
from polyglotdb.io import inspect_ilg
from polyglotdb.io.helper import guess_type
from polyglotdb.exceptions import DelimiterError, ILGWordMismatchError
from polyglotdb import CorpusContext
def test_inspect_ilg(ilg_test_dir):
basic_path = os.path.join(ilg_test_dir, 'basic.tx... |
def test_ilg_mismatched(graph_db, ilg_test_dir):
mismatched_path = os.path.join(ilg_test_dir, 'mismatched.txt')
basic_path = os.path.join(ilg_test_dir, 'basic.txt')
parser = inspect_ilg(basic_path)
with CorpusContext('mismatch', **graph_db) as c:
c.reset()
with pytest.raises(ILGWord... | basic_path = os.path.join(ilg_test_dir, 'basic.txt')
parser = inspect_ilg(basic_path)
with CorpusContext('basic_ilg', **graph_db) as c:
c.reset()
c.load(parser, basic_path)
# assert(c.lexicon['a'].frequency == 2) | identifier_body |
test_io_ilg.py | import pytest
import os
import sys
from polyglotdb.io import inspect_ilg
from polyglotdb.io.helper import guess_type
from polyglotdb.exceptions import DelimiterError, ILGWordMismatchError
from polyglotdb import CorpusContext
def test_inspect_ilg(ilg_test_dir):
basic_path = os.path.join(ilg_test_dir, 'basic.tx... |
def test_ilg_basic(graph_db, ilg_test_dir):
basic_path = os.path.join(ilg_test_dir, 'basic.txt')
parser = inspect_ilg(basic_path)
with CorpusContext('basic_ilg', **graph_db) as c:
c.reset()
c.load(parser, basic_path)
# assert(c.lexicon['a'].frequency == 2)
def test_ilg_mismatch... | assert (line.strip() == expected_lines[i]) | conditional_block |
test_io_ilg.py | import pytest
import os
import sys
from polyglotdb.io import inspect_ilg
from polyglotdb.io.helper import guess_type
from polyglotdb.exceptions import DelimiterError, ILGWordMismatchError
from polyglotdb import CorpusContext
def test_inspect_ilg(ilg_test_dir):
basic_path = os.path.join(ilg_test_dir, 'basic.tx... | def test_export_ilg(graph_db, export_test_dir):
export_path = os.path.join(export_test_dir, 'export_ilg.txt')
with CorpusContext('untimed', **graph_db) as c:
export_discourse_ilg(c, 'test', export_path,
annotations=['label', 'transcription'], words_per_line=3)
expected_l... | random_line_split | |
oeq_AHDE.py | # -*- coding: utf-8 -*-
import os,math
from qgis.core import NULL
from mole import oeq_global
from mole.project import config
from mole.extensions import OeQExtension
from mole.stat_corr import rb_contemporary_base_uvalue_by_building_age_lookup
def | (self=None, parameters={},feature = None):
from math import floor, ceil
from PyQt4.QtCore import QVariant
ahde = NULL
if not oeq_global.isnull([parameters['HLAE']]):
ahde=float(parameters['HLAE']) + 40.0 * 0.8
# Air Change Heatloss for standard Rooms 40kWh/m2a nach Geiger Lüftung im Woh... | calculation | identifier_name |
oeq_AHDE.py | # -*- coding: utf-8 -*-
import os,math
from qgis.core import NULL
from mole import oeq_global
from mole.project import config
from mole.extensions import OeQExtension
from mole.stat_corr import rb_contemporary_base_uvalue_by_building_age_lookup
def calculation(self=None, parameters={},feature = None):
from math i... | extension.registerExtension(default=True) | evaluation_method=calculation)
| random_line_split |
oeq_AHDE.py | # -*- coding: utf-8 -*-
import os,math
from qgis.core import NULL
from mole import oeq_global
from mole.project import config
from mole.extensions import OeQExtension
from mole.stat_corr import rb_contemporary_base_uvalue_by_building_age_lookup
def calculation(self=None, parameters={},feature = None):
|
extension = OeQExtension(
extension_id=__name__,
category='Evaluation',
subcategory='Building',
extension_name='AHD Building per Livig Area EnEV',
layer_name= 'Annual Heat Demand (per Living Area, EnEV)',
extension_filepath=os.path.join(__file__),
colortable = os.path.join(os.path.splitex... | from math import floor, ceil
from PyQt4.QtCore import QVariant
ahde = NULL
if not oeq_global.isnull([parameters['HLAE']]):
ahde=float(parameters['HLAE']) + 40.0 * 0.8
# Air Change Heatloss for standard Rooms 40kWh/m2a nach Geiger Lüftung im Wohnungsbau
# 20% of the Total Area are us... | identifier_body |
oeq_AHDE.py | # -*- coding: utf-8 -*-
import os,math
from qgis.core import NULL
from mole import oeq_global
from mole.project import config
from mole.extensions import OeQExtension
from mole.stat_corr import rb_contemporary_base_uvalue_by_building_age_lookup
def calculation(self=None, parameters={},feature = None):
from math i... | return {'AHDE': {'type': QVariant.Double, 'value': ahde}}
extension = OeQExtension(
extension_id=__name__,
category='Evaluation',
subcategory='Building',
extension_name='AHD Building per Livig Area EnEV',
layer_name= 'Annual Heat Demand (per Living Area, EnEV)',
extension_filepath=os.path... | ahde=float(parameters['HLAE']) + 40.0 * 0.8
# Air Change Heatloss for standard Rooms 40kWh/m2a nach Geiger Lüftung im Wohnungsbau
# 20% of the Total Area are used for stairs and floors
| conditional_block |
capitalize.filter.spec.js | beforeEach(function() {
module('impactApp');
inject(function(_$filter_) {
this.$filter = _$filter_;
});
});
describe('capitalize', function() {
it('should capitalize first letter of a word, after a \' but not after an accent', function() {
//given
var text = 'type d\'hébergemen... | 'use strict';
describe('Capitalize.filter', function() {
| random_line_split | |
sieve.rs | extern crate sieve;
#[test]
fn limit_lower_than_the_first_prime() {
assert_eq!(sieve::primes_up_to(1), []);
}
#[test]
fn limit_is_the_first_prime() {
assert_eq!(sieve::primes_up_to(2), [2]);
}
#[test]
fn primes_up_to_10() {
assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]);
}
#[test]
fn limit_of_1000()... | 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,
911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
assert_eq!(sieve::primes_up_... | random_line_split | |
sieve.rs | extern crate sieve;
#[test]
fn limit_lower_than_the_first_prime() {
assert_eq!(sieve::primes_up_to(1), []);
}
#[test]
fn limit_is_the_first_prime() |
#[test]
fn primes_up_to_10() {
assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]);
}
#[test]
fn limit_of_1000() {
let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,
... | {
assert_eq!(sieve::primes_up_to(2), [2]);
} | identifier_body |
sieve.rs | extern crate sieve;
#[test]
fn | () {
assert_eq!(sieve::primes_up_to(1), []);
}
#[test]
fn limit_is_the_first_prime() {
assert_eq!(sieve::primes_up_to(2), [2]);
}
#[test]
fn primes_up_to_10() {
assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]);
}
#[test]
fn limit_of_1000() {
let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 3... | limit_lower_than_the_first_prime | identifier_name |
Utilities.js | /*
Copyright - 2016 - Christian Guyette - Contact: http//www.ouaie.be/
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 any later version.
This program is distribu... | ( ) { return _pageId; },
/*
--- storageAvailable function ------------------------------------------------------------------------------------------
This function test if the storage API is available ( the API can be deactived by user....)
Adapted from MDN :-)
---------------------------------... | pageId | identifier_name |
Utilities.js | /*
Copyright - 2016 - Christian Guyette - Contact: http//www.ouaie.be/
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 any later version.
This program is distribu... | ,
/*
--- pageId getter ------------------------------------------------------------------------------------------------------
*/
get pageId ( ) { return _pageId; },
/*
--- storageAvailable function ------------------------------------------------------------------------------------------
... | { return getUUID ( ); } | identifier_body |
Utilities.js | /*
Copyright - 2016 - Christian Guyette - Contact: http//www.ouaie.be/
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 any later version.
This program is distribu... |
} ) ( );
/* --- End of Utilities.js file --- */ | {
module.exports = getUtilities ( );
} | conditional_block |
Utilities.js | /*
Copyright - 2016 - Christian Guyette - Contact: http//www.ouaie.be/
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 any later version.
This program is distribu... | }
}
}
};
};
/* --- End of getUtilities function --- */
/*
--- Exports ------------------------------------------------------------------------------------------------------------
*/
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = getUtilities ( );
}
} ... | random_line_split | |
notices.js | /**
Copyright 2011 Red Hat, Inc.
This software is licensed to you under the GNU General Public
License as published by the Free Software Foundation; either version
2 of the License (GPLv2) or (at your option) any later version.
There is NO WARRANTY for this software, express or implied,
including the implied war... | else if( level === "message" ) {
options["sticky"] = true;
options["fadeSpeed"] = 600;
} else {
options["sticky"] = false;
options["fadeSpeed"] = 600;
}
if( noticesParsed['validation_errors'] !== undefined ){
... | {
options["sticky"] = true;
options["fadeSpeed"] = 600;
} | conditional_block |
notices.js | /**
Copyright 2011 Red Hat, Inc.
This software is licensed to you under the GNU General Public
License as published by the Free Software Foundation; either version
2 of the License (GPLv2) or (at your option) any later version.
There is NO WARRANTY for this software, express or implied,
including the implied war... | notices_list += '</ul>';
return notices_list;
};
if (level === 'success') {
notices.clearPreviousFailures(requestType);
}
if ((level === "error") || (level === "warning")) {
options["sticky"] =... | random_line_split | |
edits-reducer.js | /** @format */
/**
* External dependencies
*/
import { compact, isEqual } from 'lodash';
/**
* Internal dependencies
*/
import { createReducer } from 'state/utils';
import {
WOOCOMMERCE_PRODUCT_CATEGORY_CREATE,
WOOCOMMERCE_PRODUCT_CATEGORY_UPDATE,
WOOCOMMERCE_PRODUCT_CATEGORY_EDIT,
WOOCOMMERCE_PRODUCT_CATEGO... | newArray.push( { id: category.id, ...data } );
}
return newArray;
}
| {
const prevArray = array || [];
let found = false;
// Look for this object in the appropriate create or edit array first.
const newArray = compact(
prevArray.map( c => {
if ( isEqual( category.id, c.id ) ) {
found = true;
// If data is null, remove this edit, otherwise update the edit data.
ret... | identifier_body |
edits-reducer.js | /** @format */
/**
* External dependencies
*/
import { compact, isEqual } from 'lodash';
/**
* Internal dependencies
*/
import { createReducer } from 'state/utils';
import {
WOOCOMMERCE_PRODUCT_CATEGORY_CREATE,
WOOCOMMERCE_PRODUCT_CATEGORY_UPDATE,
WOOCOMMERCE_PRODUCT_CATEGORY_EDIT,
WOOCOMMERCE_PRODUCT_CATEGO... |
return c;
} )
);
if ( ! found ) {
// update or create not already in edit state, so add it now.
newArray.push( { id: category.id, ...data } );
}
return newArray;
}
| {
found = true;
// If data is null, remove this edit, otherwise update the edit data.
return data ? { ...c, ...data } : undefined;
} | conditional_block |
edits-reducer.js | /** @format */
/**
* External dependencies
*/
import { compact, isEqual } from 'lodash';
/**
* Internal dependencies
*/
import { createReducer } from 'state/utils';
import {
WOOCOMMERCE_PRODUCT_CATEGORY_CREATE,
WOOCOMMERCE_PRODUCT_CATEGORY_UPDATE,
WOOCOMMERCE_PRODUCT_CATEGORY_EDIT,
WOOCOMMERCE_PRODUCT_CATEGO... | return newArray;
} | }
| random_line_split |
edits-reducer.js | /** @format */
/**
* External dependencies
*/
import { compact, isEqual } from 'lodash';
/**
* Internal dependencies
*/
import { createReducer } from 'state/utils';
import {
WOOCOMMERCE_PRODUCT_CATEGORY_CREATE,
WOOCOMMERCE_PRODUCT_CATEGORY_UPDATE,
WOOCOMMERCE_PRODUCT_CATEGORY_EDIT,
WOOCOMMERCE_PRODUCT_CATEGO... | ( edits, action ) {
const { category, data } = action;
const prevEdits = edits || {};
const bucket = getBucket( category );
const newArray = editProductCategory( prevEdits[ bucket ], category, data );
return {
...prevEdits,
[ bucket ]: newArray,
currentlyEditingId: category.id,
};
}
function editProductCa... | editProductCategoryAction | identifier_name |
shim.rs | use std::marker::PhantomData;
// FIXME: remove this and use std::ptr::NonNull when Firefox requires Rust 1.25+
pub struct NonZeroPtr<T: 'static>(&'static T);
impl<T: 'static> NonZeroPtr<T> {
pub unsafe fn new_unchecked(ptr: *mut T) -> Self {
NonZeroPtr(&*ptr)
}
pub fn as_ptr(&self) -> *mut T {
... | (&self) -> &mut T {
&mut *self.ptr.as_ptr()
}
}
impl<'a, T> From<&'a mut T> for Shared<T> {
fn from(reference: &'a mut T) -> Self {
unsafe { Shared::new_unchecked(reference) }
}
}
| as_mut | identifier_name |
shim.rs | use std::marker::PhantomData; | impl<T: 'static> NonZeroPtr<T> {
pub unsafe fn new_unchecked(ptr: *mut T) -> Self {
NonZeroPtr(&*ptr)
}
pub fn as_ptr(&self) -> *mut T {
self.0 as *const T as *mut T
}
}
pub struct Unique<T: 'static> {
ptr: NonZeroPtr<T>,
_marker: PhantomData<T>,
}
impl<T: 'static> Unique<T> {
... |
// FIXME: remove this and use std::ptr::NonNull when Firefox requires Rust 1.25+
pub struct NonZeroPtr<T: 'static>(&'static T);
| random_line_split |
app.js | const AppError = require('../../../lib/errors/app')
const assert = require('assert')
function | () {
throw new AppError('app error message')
}
it('Error details', function () {
try {
doSomethingBad()
} catch (err) {
assert.strictEqual(
err.name,
'AppError',
"Name property set to error's name"
)
assert(
err instanceof AppError,
'Is an instance of its class'
... | doSomethingBad | identifier_name |
app.js | const AppError = require('../../../lib/errors/app')
const assert = require('assert')
function doSomethingBad () |
it('Error details', function () {
try {
doSomethingBad()
} catch (err) {
assert.strictEqual(
err.name,
'AppError',
"Name property set to error's name"
)
assert(
err instanceof AppError,
'Is an instance of its class'
)
assert(
err instanceof Error,
... | {
throw new AppError('app error message')
} | identifier_body |
app.js | const AppError = require('../../../lib/errors/app')
const assert = require('assert')
function doSomethingBad () {
throw new AppError('app error message')
}
it('Error details', function () {
try {
doSomethingBad()
} catch (err) {
assert.strictEqual(
err.name,
'AppError',
"Name property ... | err.stack,
'Should have recorded a stack'
)
assert.strictEqual(
err.toString(),
'AppError: app error message',
'toString should return the default error message formatting'
)
assert.strictEqual(
err.stack.split('\n')[0],
'AppError: app error message',
'S... | )
assert( | random_line_split |
wrong-mul-method-signature.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (self, s: &f64) -> Vec1 {
//~^ ERROR method `mul` has an incompatible type for trait
Vec1 {
x: self.x * *s
}
}
}
struct Vec2 {
x: f64,
y: f64
}
// Wrong type parameter ordering
impl Mul<Vec2> for Vec2 {
type Output = f64;
fn mul(self, s: f64) -> Vec2 {
//~^ ERR... | mul | identifier_name |
wrong-mul-method-signature.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
struct Vec1 {
x: f64
}
// Expecting value in input signature
impl Mul<f64> for Vec1 {
type Output = Vec1;
fn mul(self, s: &f64) -> Vec1 {
//~^ ERROR method `mul` has an incompatible type for trait
Vec1 {
x: self.x * *s
}
}
}
struct Vec2 {
x: f64,
y: f64
}
// ... | // method for an operator is not implemented properly.
// (In this case the mul method should take &f64 and not f64)
// See: #11450
use std::ops::Mul; | random_line_split |
wrong-mul-method-signature.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
struct Vec3 {
x: f64,
y: f64,
z: f64
}
// Unexpected return type
impl Mul<f64> for Vec3 {
type Output = i32;
fn mul(self, s: f64) -> f64 {
//~^ ERROR method `mul` has an incompatible type for trait
s
}
}
pub fn main() {
// Check that the usage goes from the trait declarati... | {
//~^ ERROR method `mul` has an incompatible type for trait
Vec2 {
x: self.x * s,
y: self.y * s
}
} | identifier_body |
car_factory.rs | use super::car_type::{Body, CarType, Colour};
pub struct | {
car_types: Vec<CarType>,
}
impl CarFactory {
pub fn new() -> CarFactory {
CarFactory {
car_types: Vec::new(),
}
}
pub fn get_car_type_id(&mut self, body: Body, colour: Colour) -> u8 {
let position = self.car_types
.iter()
.position(|ref r|... | CarFactory | identifier_name |
car_factory.rs | use super::car_type::{Body, CarType, Colour};
pub struct CarFactory {
car_types: Vec<CarType>,
}
impl CarFactory {
pub fn new() -> CarFactory {
CarFactory {
car_types: Vec::new(),
}
}
pub fn get_car_type_id(&mut self, body: Body, colour: Colour) -> u8 {
let positio... | println!("Number of car types: {}", self.car_types.len());
}
} |
pub fn print(&self) { | random_line_split |
car_factory.rs | use super::car_type::{Body, CarType, Colour};
pub struct CarFactory {
car_types: Vec<CarType>,
}
impl CarFactory {
pub fn new() -> CarFactory {
CarFactory {
car_types: Vec::new(),
}
}
pub fn get_car_type_id(&mut self, body: Body, colour: Colour) -> u8 {
let positio... |
pub fn print(&self) {
println!("Number of car types: {}", self.car_types.len());
}
}
| {
self.car_types.get(id as usize)
} | identifier_body |
Boot.Server.ts | import { DotNet } from '@microsoft/dotnet-js-interop';
import { Blazor } from './GlobalExports';
import { HubConnectionBuilder, HubConnection, HttpTransportType } from '@microsoft/signalr';
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack';
import { showErrorNotification } from './BootErrors'... | connection.on('JS.ReceiveByteArray', DotNet.jsCallDispatcher.receiveByteArray);
connection.on('JS.BeginTransmitStream', (streamId: number) => {
const readableStream = new ReadableStream({
start(controller) {
connection.stream('SendDotNetStreamToJS', streamId).subscribe({
next: (chunk: U... | {
const hubProtocol = new MessagePackHubProtocol();
(hubProtocol as unknown as { name: string }).name = 'blazorpack';
const connectionBuilder = new HubConnectionBuilder()
.withUrl('_blazor')
.withHubProtocol(hubProtocol);
options.configureSignalR(connectionBuilder);
const connection = connectionBui... | identifier_body |
Boot.Server.ts | import { DotNet } from '@microsoft/dotnet-js-interop';
import { Blazor } from './GlobalExports';
import { HubConnectionBuilder, HubConnection, HttpTransportType } from '@microsoft/signalr';
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack';
import { showErrorNotification } from './BootErrors'... | (userOptions?: Partial<CircuitStartOptions>): Promise<void> {
if (started) {
throw new Error('Blazor has already started.');
}
started = true;
// Establish options to be used
const options = resolveOptions(userOptions);
const jsInitializer = await fetchAndInvokeInitializers(options);
const logger = ... | boot | identifier_name |
Boot.Server.ts | import { DotNet } from '@microsoft/dotnet-js-interop';
import { Blazor } from './GlobalExports';
import { HubConnectionBuilder, HubConnection, HttpTransportType } from '@microsoft/signalr';
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack';
import { showErrorNotification } from './BootErrors'... |
let disconnectSent = false;
const cleanup = () => {
if (!disconnectSent) {
const data = new FormData();
const circuitId = circuit.circuitId!;
data.append('circuitId', circuitId);
disconnectSent = navigator.sendBeacon('_blazor/disconnect', data);
}
};
Blazor.disconnect = cleanup... | random_line_split | |
Boot.Server.ts | import { DotNet } from '@microsoft/dotnet-js-interop';
import { Blazor } from './GlobalExports';
import { HubConnectionBuilder, HubConnection, HttpTransportType } from '@microsoft/signalr';
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack';
import { showErrorNotification } from './BootErrors'... |
started = true;
// Establish options to be used
const options = resolveOptions(userOptions);
const jsInitializer = await fetchAndInvokeInitializers(options);
const logger = new ConsoleLogger(options.logLevel);
Blazor.reconnect = async (existingConnection?: HubConnection): Promise<boolean> => {
if (r... | {
throw new Error('Blazor has already started.');
} | conditional_block |
jquery.fitvids.js | /*global jQuery */
/*jshint browser:true */
/*!
* FitVids 1.1
*
* Copyright 2013, Chris Coyier - https://css-tricks.com + Dave Rupert - https://daverupert.com
* Credit to Thierry Koblentz - https://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - https://sam.zoy... | // Works with either jQuery or Zepto
})(window.jQuery || window.Zepto); | $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100) + "%");
$this.removeAttr('height').removeAttr('width');
});
});
}; | random_line_split |
jquery.fitvids.js | /*global jQuery */
/*jshint browser:true */
/*!
* FitVids 1.1
*
* Copyright 2013, Chris Coyier - https://css-tricks.com + Dave Rupert - https://daverupert.com
* Credit to Thierry Koblentz - https://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - https://sam.zoy... |
var $allVideos = $(this).find(selectors.join(','));
$allVideos = $allVideos.not("object object"); // SwfObj conflict patch
$allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video.
$allVideos.each(function() {
var $this = $(this);
... | {
ignoreList = ignoreList + ', ' + settings.ignore;
} | conditional_block |
testf0seqnrcalculation.py | """
Example usage:
python3 testf0seqnrcalculation.py 548659 \
../testdata/sample_data_548659/L548659.parset \
../testdata/sample_data_548659/file-sizes.txt \
../testdata/sample_data_548659/f0seqnr-sizes.txt
"""
import os
import sys
sys.path.append("../scripts")
import create_html
def test... |
print('\n'.join(['%s: %dMB (%0.f%%)' % (name, size, f0seqnr_completeness_dict.get(name, -1)) for (name, size) in sorted(analysed_file_sizes_dict['odd_sized_data_sets'])]))
open("./index.html", 'w').write('''
<html>
<head>
<meta http-equiv="refresh" content="60">
... | print("Dataset: ", data_product_folder, " Size: ", file_size_in_mb, "MB ", "(%0.f%%)" % (100*file_size_in_mb/highest_file_size_mb)) | conditional_block |
testf0seqnrcalculation.py | """
Example usage:
python3 testf0seqnrcalculation.py 548659 \
../testdata/sample_data_548659/L548659.parset \
../testdata/sample_data_548659/file-sizes.txt \
../testdata/sample_data_548659/f0seqnr-sizes.txt
"""
import os
import sys
sys.path.append("../scripts")
import create_html
def test... | print("Correlator locations: ", "\n".join(parset['correlator_locations']))
print("Beamformer locations: ", "\n".join(parset['beamformer_locations']))
print("\nContent of [file_sizes_dict]:")
for data_product_folder, (_, _, file_size_in_mb) in file_sizes_dict.items():
print(data... | result = True
parset = create_html.parset_summary(in_sas_id, in_parset_path)
file_sizes_dict = create_html.parse_file_sizes(in_file_sizes_path)
analysed_file_sizes_dict = create_html.file_size_analysis(parset, file_sizes_dict)
highest_file_size_mb = analysed_file_sizes_dict['max_ms_size_mb'].... | identifier_body |
testf0seqnrcalculation.py | """
Example usage:
python3 testf0seqnrcalculation.py 548659 \
../testdata/sample_data_548659/L548659.parset \
../testdata/sample_data_548659/file-sizes.txt \
../testdata/sample_data_548659/f0seqnr-sizes.txt
"""
import os
import sys
sys.path.append("../scripts")
import create_html
def | (in_sas_id, in_parset_path, in_file_sizes_path, in_f0seqnr_sizes_path):
result = True
parset = create_html.parset_summary(in_sas_id, in_parset_path)
file_sizes_dict = create_html.parse_file_sizes(in_file_sizes_path)
analysed_file_sizes_dict = create_html.file_size_analysis(parset, file_sizes_... | test_main | identifier_name |
testf0seqnrcalculation.py | """
Example usage:
python3 testf0seqnrcalculation.py 548659 \
../testdata/sample_data_548659/L548659.parset \
../testdata/sample_data_548659/file-sizes.txt \
../testdata/sample_data_548659/f0seqnr-sizes.txt
"""
import os
import sys
sys.path.append("../scripts")
import create_html
def test... | <title>LOFAR Inspection plots</title>
</head>
<body>
<h1>LOFAR inspection plots</h1>
<table>
<tr><th>SAS ID</th> <th>Campaign</th> <th>Target</th> <th>DynSpec</th> <th title="Percentage of odd sized data products per project\n\nWhere 'odd sized' is defined as:\nData products with... | open("./index.html", 'w').write('''
<html>
<head>
<meta http-equiv="refresh" content="60"> | random_line_split |
read-json.js | var _require = require('zoroaster/assert'),
deepEqual = _require.deepEqual,
throws = _require.throws;
var context = require('../context/WroteContext');
var readJSON = require('../../src/read-json');
var readJSONTestSuite = {
context,
'should read a JSON file'(_ref) {
return new Promise(functio... | try {
return $return();
} catch ($boundEx) {
return $error($boundEx);
}
}.bind(this), $error);
}.bind(this));
},
'should throw an error if cannot parse JSON'(_ref3) {
return new Promise(function (... | args: [tempFile],
code: 'ENOENT'
})).then(function ($await_2) { | random_line_split |
read-json.js | var _require = require('zoroaster/assert'),
deepEqual = _require.deepEqual,
throws = _require.throws;
var context = require('../context/WroteContext');
var readJSON = require('../../src/read-json');
var readJSONTestSuite = {
context,
'should read a JSON file'(_ref) {
return new Promise(functio... | (_ref2) {
return new Promise(function ($return, $error) {
var tempFile;
tempFile = _ref2.tempFile;
return Promise.resolve(throws({
fn: readJSON,
args: [tempFile],
code: 'ENOENT'
})).then(function ($await_2) {
... | 'should throw an error if file is not found' | identifier_name |
read-json.js | var _require = require('zoroaster/assert'),
deepEqual = _require.deepEqual,
throws = _require.throws;
var context = require('../context/WroteContext');
var readJSON = require('../../src/read-json');
var readJSONTestSuite = {
context,
'should read a JSON file'(_ref) {
return new Promise(functio... |
};
module.exports = readJSONTestSuite; | {
return new Promise(function ($return, $error) {
var invalidJSONpath;
invalidJSONpath = _ref3.invalidJSONpath;
return Promise.resolve(throws({
fn: readJSON,
args: [invalidJSONpath],
message: /Unexpected token h/
}))... | identifier_body |
test.rs | use std::path::PathBuf;
use crate::app::{config, ddns, index::Index, lastfm, playlist, settings, thumbnail, user, vfs};
use crate::db::DB;
use crate::test::*;
pub struct Context {
pub db: DB,
pub index: Index,
pub config_manager: config::Manager,
pub ddns_manager: ddns::Manager,
pub lastfm_manager: lastfm::Manag... | (mut self, name: &str, source: &str) -> Self {
self.config
.mount_dirs
.get_or_insert(Vec::new())
.push(vfs::MountDir {
name: name.to_owned(),
source: source.to_owned(),
});
self
}
pub fn build(self) -> Context {
let cache_output_dir = self.test_directory.join("cache");
let db_path = self... | mount | identifier_name |
test.rs | use std::path::PathBuf;
use crate::app::{config, ddns, index::Index, lastfm, playlist, settings, thumbnail, user, vfs};
use crate::db::DB;
use crate::test::*;
pub struct Context {
pub db: DB,
pub index: Index,
pub config_manager: config::Manager,
pub ddns_manager: ddns::Manager,
pub lastfm_manager: lastfm::Manag... | let user_manager = user::Manager::new(db.clone(), auth_secret);
let vfs_manager = vfs::Manager::new(db.clone());
let ddns_manager = ddns::Manager::new(db.clone());
let config_manager = config::Manager::new(
settings_manager.clone(),
user_manager.clone(),
vfs_manager.clone(),
ddns_manager.clone(),
... | let auth_secret = settings_manager.get_auth_secret().unwrap(); | random_line_split |
test.rs | use std::path::PathBuf;
use crate::app::{config, ddns, index::Index, lastfm, playlist, settings, thumbnail, user, vfs};
use crate::db::DB;
use crate::test::*;
pub struct Context {
pub db: DB,
pub index: Index,
pub config_manager: config::Manager,
pub ddns_manager: ddns::Manager,
pub lastfm_manager: lastfm::Manag... |
config_manager.apply(&self.config).unwrap();
Context {
db,
index,
config_manager,
ddns_manager,
lastfm_manager,
playlist_manager,
settings_manager,
thumbnail_manager,
user_manager,
vfs_manager,
test_directory: self.test_directory,
}
}
}
| {
let cache_output_dir = self.test_directory.join("cache");
let db_path = self.test_directory.join("db.sqlite");
let db = DB::new(&db_path).unwrap();
let settings_manager = settings::Manager::new(db.clone());
let auth_secret = settings_manager.get_auth_secret().unwrap();
let user_manager = user::Manager::n... | identifier_body |
list_and_dump.py | # Copyright 2015 Spotify AB
#
# 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, so... | """
with open(out_file, "w") as f:
s = socket.socket(socket.AF_UNIX)
s.connect(os.getenv("SSH_AUTH_SOCK"))
s.send("\x00\x00\x00\x01\x0b")
data = s.recv(8192)
f.write(data)
print "read and wrote %d bytes of data" % len(data)
if __name__ == '__main__':
list_k... | """
Connects to the ssh agent on localhost and requests a key listing, dumping
what gets sent as a response to a file. Useful for constructing test data
:param out_file: the filename to write to | random_line_split |
list_and_dump.py | # Copyright 2015 Spotify AB
#
# 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, so... |
if __name__ == '__main__':
list_keys_dump_raw_data(sys.argv[1])
| """
Connects to the ssh agent on localhost and requests a key listing, dumping
what gets sent as a response to a file. Useful for constructing test data
:param out_file: the filename to write to
"""
with open(out_file, "w") as f:
s = socket.socket(socket.AF_UNIX)
s.connect(os.gete... | identifier_body |
list_and_dump.py | # Copyright 2015 Spotify AB
#
# 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, so... | list_keys_dump_raw_data(sys.argv[1]) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.