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 |
|---|---|---|---|---|
windows.rs | use std::ffi::OsStr;
const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
pub trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
pub trait OsStrExt2 {
fn starts_with(&self, s: &[u8]) -> bool;
fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
fn split... | (b: &[u8]) -> &Self {
use std::mem;
unsafe { mem::transmute(b) }
}
fn as_bytes(&self) -> &[u8] { self.to_str().map(str::as_bytes).expect(INVALID_UTF8) }
}
impl OsStrExt2 for OsStr {
fn starts_with(&self, s: &[u8]) -> bool { self.as_bytes().starts_with(s) }
fn is_empty_(&self) -> bool ... | from_bytes | identifier_name |
windows.rs | use std::ffi::OsStr;
const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
pub trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
pub trait OsStrExt2 {
fn starts_with(&self, s: &[u8]) -> bool;
fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
fn split... | fn split(&self, b: u8) -> OsSplit;
}
impl OsStrExt3 for OsStr {
// TODO JB: fix this allow
#[allow(clippy::transmute_ptr_to_ptr)]
fn from_bytes(b: &[u8]) -> &Self {
use std::mem;
unsafe { mem::transmute(b) }
}
fn as_bytes(&self) -> &[u8] { self.to_str().map(str::as_bytes).expec... | fn trim_left_matches(&self, b: u8) -> &OsStr;
fn len_(&self) -> usize;
fn contains_byte(&self, b: u8) -> bool;
fn is_empty_(&self) -> bool; | random_line_split |
windows.rs | use std::ffi::OsStr;
const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
pub trait OsStrExt3 {
fn from_bytes(b: &[u8]) -> &Self;
fn as_bytes(&self) -> &[u8];
}
pub trait OsStrExt2 {
fn starts_with(&self, s: &[u8]) -> bool;
fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
fn split... |
fn len_(&self) -> usize { self.as_bytes().len() }
fn split(&self, b: u8) -> OsSplit {
OsSplit { sep: b,
val: self.as_bytes(),
pos: 0, }
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct OsSplit<'a> {
sep: u8,
val: &'a [u8],
pos: usize,
}
impl<... | {
(&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i..]))
} | identifier_body |
test_volume_quotas_negative.py | # Copyright 2014 OpenStack Foundation
# 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 requ... | (base.BaseVolumeV1AdminTest):
_interface = "json"
force_tenant_isolation = True
@classmethod
@test.safe_setup
def setUpClass(cls):
super(VolumeQuotasNegativeTestJSON, cls).setUpClass()
demo_user = cls.isolated_creds.get_primary_creds()
cls.demo_tenant_id = demo_user.tenant_i... | VolumeQuotasNegativeTestJSON | identifier_name |
test_volume_quotas_negative.py | # Copyright 2014 OpenStack Foundation
# 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 requ... |
@test.attr(type='negative')
def test_quota_volume_gigabytes(self):
# NOTE(gfidente): quota set needs to be changed for this test
# or we may be limited by the volumes or snaps quota number, not by
# actual gigs usage; next line ensures shared set is restored.
self.addCleanup(se... | self.assertRaises(exceptions.OverLimit,
self.snapshots_client.create_snapshot,
self.volume['id']) | identifier_body |
test_volume_quotas_negative.py | # Copyright 2014 OpenStack Foundation
# 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 requ... | self.snapshots_client.create_snapshot,
self.volume['id'])
class VolumeQuotasNegativeTestXML(VolumeQuotasNegativeTestJSON):
_interface = "xml" | resp, quota_set = self.quotas_client.update_quota_set(
self.demo_tenant_id,
**self.shared_quota_set)
self.assertRaises(exceptions.OverLimit, | random_line_split |
picture.js | define([
"jquery",
"require",
"./util",
"./fb",
"./server",
"jquery.ui",
"jquery.jcrop",
"jquery.facedetection",
"jquery.photobooth"
], function($, require) {
var util = require("./util");
var fb = require("./fb");
var server = require("./server");
var jcropApi; /* ... | else {
util.showI18nMessage("info", "take_picture_not_available");
$(".picture-merger").data("photobooth").destroy();
require("./picture").memePicture();
}
}
};
return functions;
}); | {
$("#btn_profile").button("disable");
$("#btn_upload").button("disable");
$("#btn_take").button("disable");
$("#btn_generate").button("disable");
} | conditional_block |
picture.js | define([
"jquery",
"require",
"./util",
"./fb",
"./server",
"jquery.ui",
"jquery.jcrop",
"jquery.facedetection",
"jquery.photobooth"
], function($, require) {
var util = require("./util");
var fb = require("./fb");
var server = require("./server");
var jcropApi; /* ... | onSelect: function(c) {
$("#x1").val(c.x);
$("#x2").val(c.x2);
$("#y1").val(c.y);
$("#y2").val(c.y2);
$("#w").val(c.w);
$("#h").... | aspectRatio: 1,
setSelect: pos,
bgColor: "black",
bgOpacity: .2, | random_line_split |
LoginManagerPrompter.js | N
get _brandBundle() {
if (!this.__brandBundle) {
var bunService = Cc["@mozilla.org/intl/stringbundle;1"].
getService(Ci.nsIStringBundleService);
this.__brandBundle = bunService.createBundle(
"chrome://branding/locale/brand.propert... | _showLoginNotification : function (aName, aText, aButtons) {
this.log("Adding new " + aName + " notification bar");
let notifyWin = this._window.top;
let chromeWin = this._getChromeWindow(notifyWin).wrappedJSObject;
let browser = chromeWin.BrowserApp.getBrowserForWindow(notifyWin);
... | *
*/ | random_line_split |
LoginManagerPrompter.js |
get _brandBundle() {
if (!this.__brandBundle) {
var bunService = Cc["@mozilla.org/intl/stringbundle;1"].
getService(Ci.nsIStringBundleService);
this.__brandBundle = bunService.createBundle(
"chrome://branding/locale/brand.properti... | ,
/*
* log
*
* Internal function for logging debug messages to the Error Console window.
*/
log : function (message) {
if (!this._debug)
return;
dump("Pwmgr Prompter: " + message + "\n");
Services.console.logStringMessage("Pwmgr Prompter: " + message);
... | {
if (!this.__ellipsis) {
this.__ellipsis = "\u2026";
try {
this.__ellipsis = Services.prefs.getComplexValue(
"intl.ellipsis", Ci.nsIPrefLocalizedString).data;
} catch (e) { }
}
return this.__ellipsis;
} | identifier_body |
LoginManagerPrompter.js | () {
if (!this.__promptService)
this.__promptService =
Cc["@mozilla.org/embedcomp/prompt-service;1"].
getService(Ci.nsIPromptService2);
return this.__promptService;
},
__strBundle : null, // String bundle for L10N
get _strBundle() {
if... | _promptService | identifier_name | |
iterator.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
yield 'one';
yield 'two';
yield 'three';
}
};
test('first', function () {
assert.equal(Iterable.first([]), undefined);
assert.equal(Iterable.first([1]), 1);
assert.equal(Iterable.first(customIterable), 'one');
assert.equal(Iterable.first(customIterable), 'one'); // fresh
});
});
| [Symbol.iterator] | identifier_name |
iterator.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | assert.equal(Iterable.first(customIterable), 'one'); // fresh
});
}); | random_line_split | |
iterator.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
};
test('first', function () {
assert.equal(Iterable.first([]), undefined);
assert.equal(Iterable.first([1]), 1);
assert.equal(Iterable.first(customIterable), 'one');
assert.equal(Iterable.first(customIterable), 'one'); // fresh
});
});
| {
yield 'one';
yield 'two';
yield 'three';
} | identifier_body |
LineHeightTest.ts | import { describe, it } from '@ephox/bedrock-client';
import { PlatformDetection } from '@ephox/sand';
import { TinyAssertions, TinyHooks, TinySelections } from '@ephox/wrap-mcagar';
import { assert } from 'chai';
import Editor from 'tinymce/core/api/Editor';
describe('browser.tinymce.core.commands.LineHeightTest', (... | editor.setContent('<p style="line-height: 1.8;">Hello</p>');
TinySelections.setCursor(editor, [ 0, 0 ], 0);
editor.execCommand('LineHeight', false, '2');
TinyAssertions.assertContent(editor, '<p style="line-height: 2;">Hello</p>');
});
it('TINY-4843: Editor command can toggle line-height', () => {
... | random_line_split | |
LineHeightTest.ts | import { describe, it } from '@ephox/bedrock-client';
import { PlatformDetection } from '@ephox/sand';
import { TinyAssertions, TinyHooks, TinySelections } from '@ephox/wrap-mcagar';
import { assert } from 'chai';
import Editor from 'tinymce/core/api/Editor';
describe('browser.tinymce.core.commands.LineHeightTest', (... |
const editor = hook.editor();
editor.setContent('<p>Hello</p>');
TinySelections.setCursor(editor, [ 0, 0 ], 0);
assertHeight(editor, '1.4'); // default content-css line height
});
it('TINY-4843: Specified line-height can be read from element in px', () => {
const editor = hook.editor();
ed... | {
this.skip();
} | conditional_block |
dnd.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
});
$(container).on(['dragleave', 'drop', 'dragend'], () => this.clearDragTimeout());
}
private clearDragTimeout(): void {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
public dispose(): void {
this.clearDragTimeout();
}
}
export interface IDraggedResource {
resourc... | {
this.timeout = setTimeout(() => {
callback();
this.timeout = null;
}, 800);
} | conditional_block |
dnd.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | {
private timeout: number;
constructor(container: HTMLElement, callback: () => void) {
$(container).on('dragover', () => {
if (!this.timeout) {
this.timeout = setTimeout(() => {
callback();
this.timeout = null;
}, 800);
}
});
$(container).on(['dragleave', 'drop', 'dragend'], () => t... | DelayedDragHandler | identifier_name |
dnd.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | public dispose(): void {
this.clearDragTimeout();
}
}
export interface IDraggedResource {
resource: URI;
isExternal: boolean;
}
export function extractResources(e: DragEvent, externalOnly?: boolean): IDraggedResource[] {
const resources: IDraggedResource[] = [];
if (e.dataTransfer.types.length > 0) {
// Ch... | random_line_split | |
strconv.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | let mut rbuf : [u8; 32] = unsafe { uninitialized() };
let mut myval : u32 = val;
let mut idx: isize = 0;
if myval == 0 {
buf[0] = '0' as u8;
return;
}
while myval > 0 {
let digit : u8 = (myval % base) as u8;
myval = myval / base;
rbuf[idx as usize] = digit;
idx += 1;
}
idx -... |
/// Convert an integer to a string.
pub fn itoa(val: u32, buf : &mut [u8], base: u32) { | random_line_split |
strconv.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
let mut ridx = 0;
while idx >= 0 {
let charcode : u8 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'][rbuf[idx as usize] as usize] as u8;
buf[ridx] = charcode;
idx -= 1;
ridx += 1;
}
}
| {
let mut rbuf : [u8; 32] = unsafe { uninitialized() };
let mut myval : u32 = val;
let mut idx: isize = 0;
if myval == 0 {
buf[0] = '0' as u8;
return;
}
while myval > 0 {
let digit : u8 = (myval % base) as u8;
myval = myval / base;
rbuf[idx as usize] = digit;
idx += 1;
}
idx... | identifier_body |
strconv.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
while myval > 0 {
let digit : u8 = (myval % base) as u8;
myval = myval / base;
rbuf[idx as usize] = digit;
idx += 1;
}
idx -= 1;
let mut ridx = 0;
while idx >= 0 {
let charcode : u8 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'][rbuf[idx as usize] as usize] as u... | {
buf[0] = '0' as u8;
return;
} | conditional_block |
strconv.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | (val: u32, buf : &mut [u8], base: u32) {
let mut rbuf : [u8; 32] = unsafe { uninitialized() };
let mut myval : u32 = val;
let mut idx: isize = 0;
if myval == 0 {
buf[0] = '0' as u8;
return;
}
while myval > 0 {
let digit : u8 = (myval % base) as u8;
myval = myval / base;
rbuf[idx as us... | itoa | identifier_name |
generic-struct-style-enum.rs | // Copyright 2013-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-MI... | // 0b0101100101011001 = 22873
// 0b01011001 = 89
let case3: Regular<u16, i32, u64> = Case3 { a: 0, b: 6438275382588823897 };
let univariant = TheOnlyCase { a: -1 };
zzz();
}
fn zzz() {()}
| {
// In order to avoid endianess trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 ... | identifier_body |
generic-struct-style-enum.rs | // Copyright 2013-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-MI... |
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular<T16, T32, T64> {
Case1 { a: T64, b: T16, c: T16, d... | #[feature(struct_variant)];
// NOTE: This is a copy of the non-generic test case. The `Txx` type parameters have to be
// substituted with something of size `xx` bits and the same alignment as an integer type of the
// same size. | random_line_split |
generic-struct-style-enum.rs | // Copyright 2013-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-MI... | () {()}
| zzz | identifier_name |
variance-use-invariant-struct-1.rs | // Copyright 2015 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 ... | { } | identifier_body | |
variance-use-invariant-struct-1.rs | // Copyright 2015 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 ... | <'min,'max>(v: SomeStruct<&'min ()>)
-> SomeStruct<&'max ()>
where 'max : 'min
{
v //~ ERROR mismatched types
}
fn main() { }
| bar | identifier_name |
variance-use-invariant-struct-1.rs | // Copyright 2015 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 ... |
fn main() { } | random_line_split | |
moleculetype.py | """
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
MoleculeType entity classes.
"""
from everest.entities.base import Entity
from everest.entities.utils import slug_from_string
__docformat__ = "reStructured... |
class MoleculeType(Entity):
"""
Instances of this class describe molecule types, such as \'siRna\'.
"""
#: The name of the molecule type.
name = None
#: A more detailed description.
description = None
#: An number indicating the time it takes for molecules of this type to
#: thaw.... | """
Checks whether the given molecule type name is a known one.
"""
return molecule_type_name in cls.__ALL | identifier_body |
moleculetype.py | """
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
MoleculeType entity classes.
"""
from everest.entities.base import Entity
from everest.entities.utils import slug_from_string
__docformat__ = "reStructured... |
Entity.__init__(self, **kw)
self.name = name
self.default_stock_concentration = default_stock_concentration
self.description = description
self.thaw_time = thaw_time
if modifications == None:
self.modifications = []
@property
def slug(self):
... | kw['id'] = name.lower() | conditional_block |
moleculetype.py | """ | from everest.entities.base import Entity
from everest.entities.utils import slug_from_string
__docformat__ = "reStructuredText en"
__all__ = ['MoleculeType',
'MOLECULE_TYPE_IDS']
class MOLECULE_TYPE_IDS(object):
"""
Known molecule types.
"""
# FIXME: reconcile with `thelma.data.moleculety... | This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
MoleculeType entity classes.
""" | random_line_split |
moleculetype.py | """
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
MoleculeType entity classes.
"""
from everest.entities.base import Entity
from everest.entities.utils import slug_from_string
__docformat__ = "reStructured... | (cls, molecule_type_name):
"""
Checks whether the given molecule type name is a known one.
"""
return molecule_type_name in cls.__ALL
class MoleculeType(Entity):
"""
Instances of this class describe molecule types, such as \'siRna\'.
"""
#: The name of the molecule type... | is_known_type | identifier_name |
navigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{WrapperCache, BindingObject, CacheableWrapper};
use dom::bindings::utils::{DOMString, E... |
pub fn GetAppVersion(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetPlatform(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetUserAgent(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn GetLanguage(&self) ... | {
str(~"Mozilla") // Like Gecko/Webkit
} | identifier_body |
navigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{WrapperCache, BindingObject, CacheableWrapper};
use dom::bindings::utils::{DOMString, E... | impl Navigator {
pub fn new() -> @mut Navigator {
@mut Navigator {
wrapper: WrapperCache::new()
}
}
pub fn DoNotTrack(&self) -> DOMString {
str(~"unspecified")
}
pub fn Vendor(&self) -> DOMString {
str(~"") // Like Gecko
}
pub fn VendorSub(&self... | }
| random_line_split |
navigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{WrapperCache, BindingObject, CacheableWrapper};
use dom::bindings::utils::{DOMString, E... | () -> @mut Navigator {
@mut Navigator {
wrapper: WrapperCache::new()
}
}
pub fn DoNotTrack(&self) -> DOMString {
str(~"unspecified")
}
pub fn Vendor(&self) -> DOMString {
str(~"") // Like Gecko
}
pub fn VendorSub(&self) -> DOMString {
str(~"... | new | identifier_name |
Plugin.ts | import * as fs from "fs"
import * as path from "path"
import * as Log from "./../Log"
import * as Capabilities from "./Api/Capabilities"
import { IChannel } from "./Api/Channel"
import { Oni } from "./Api/Oni"
import * as PackageMetadataParser from "./PackageMetadataParser"
export interface IPluginCommandInfo exten... |
}
}
private _onActivate(): void {
const vm = require("vm")
Log.info(`[PLUGIN] Activating: ${this._oniPluginMetadata.name}`)
let moduleEntryPoint = path.normalize(path.join(this._pluginRootDirectory, this._oniPluginMetadata.main))
moduleEntryPoint = moduleEntryPoint.spl... | {
if (this._oniPluginMetadata.main) {
this._oni = new Oni(this._channel.createPluginChannel(this._oniPluginMetadata,
() => this._onActivate()))
this._commands = PackageMetadataParser.getAllCommandsFromMetadata(this._oniPluginMetadata)
... | conditional_block |
Plugin.ts | import * as fs from "fs"
import * as path from "path"
import * as Log from "./../Log"
import * as Capabilities from "./Api/Capabilities"
import { IChannel } from "./Api/Channel"
import { Oni } from "./Api/Oni"
import * as PackageMetadataParser from "./PackageMetadataParser"
export interface IPluginCommandInfo exten... | (): IPluginCommandInfo[] {
return this._commands
}
constructor(
private _pluginRootDirectory: string,
channel: IChannel,
) {
const packageJsonPath = path.join(this._pluginRootDirectory, "package.json")
this._channel = channel
if (fs.existsSync(packageJsonPat... | commands | identifier_name |
Plugin.ts | import * as fs from "fs"
import * as path from "path"
import * as Log from "./../Log"
import * as Capabilities from "./Api/Capabilities"
import { IChannel } from "./Api/Channel"
import { Oni } from "./Api/Oni"
import * as PackageMetadataParser from "./PackageMetadataParser"
export interface IPluginCommandInfo exten... |
public get commands(): IPluginCommandInfo[] {
return this._commands
}
constructor(
private _pluginRootDirectory: string,
channel: IChannel,
) {
const packageJsonPath = path.join(this._pluginRootDirectory, "package.json")
this._channel = channel
if (fs.e... | export class Plugin {
private _oniPluginMetadata: Capabilities.IPluginMetadata
private _channel: IChannel
private _commands: IPluginCommandInfo[]
private _oni: Oni | random_line_split |
Plugin.ts | import * as fs from "fs"
import * as path from "path"
import * as Log from "./../Log"
import * as Capabilities from "./Api/Capabilities"
import { IChannel } from "./Api/Channel"
import { Oni } from "./Api/Oni"
import * as PackageMetadataParser from "./PackageMetadataParser"
export interface IPluginCommandInfo exten... |
constructor(
private _pluginRootDirectory: string,
channel: IChannel,
) {
const packageJsonPath = path.join(this._pluginRootDirectory, "package.json")
this._channel = channel
if (fs.existsSync(packageJsonPath)) {
this._oniPluginMetadata = PackageMetadataPar... | {
return this._commands
} | identifier_body |
markers.py | #Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/markers.py
"""
This modules defines a collection of markers used in charts.
The make* functions return a simple shape or a widget as f... | circle = Circle(x, y, d)
circle.strokeColor = color
circle.fillColor = color
return circle
def makeSmiley(x, y, size, color):
"Make a smiley marker."
d = size
s = SmileyFace()
s.fillColor = color
s.x = x-d
s.y = y-d
s.size = d*2
return s | def makeFilledCircle(x, y, size, color):
"Make a hollow circle marker."
d = size/2.0 | random_line_split |
markers.py | #Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/markers.py
"""
This modules defines a collection of markers used in charts.
The make* functions return a simple shape or a widget as f... | (x, y, size, color):
"Make a filled diamond marker."
d = size/2.0
poly = Polygon((x-d,y, x,y+d, x+d,y, x,y-d))
poly.strokeColor = color
poly.fillColor = color
return poly
def makeEmptyCircle(x, y, size, color):
"Make a hollow circle marker."
d = size/2.0
circle = Circle(x, y, d)... | makeFilledDiamond | identifier_name |
markers.py | #Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/markers.py
"""
This modules defines a collection of markers used in charts.
The make* functions return a simple shape or a widget as f... |
def makeFilledSquare(x, y, size, color):
"Make a filled square marker."
d = size/2.0
rect = Rect(x-d, y-d, 2*d, 2*d)
rect.strokeColor = color
rect.fillColor = color
return rect
def makeFilledDiamond(x, y, size, color):
"Make a filled diamond marker."
d = size/2.0
poly = Polyg... | "Make an empty square marker."
d = size/2.0
rect = Rect(x-d, y-d, 2*d, 2*d)
rect.strokeColor = color
rect.fillColor = None
return rect | identifier_body |
about-handler.js | // Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Name = "Vimperator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/about-... | let channel = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
.newChannel("chrome://" + name + "/content/about.html", null, null);
channel.originalURI = uri;
return channel;
},
getURIFlags: function (uri) Ci.nsIAboutModule.ALLOW_SCRIPT
};
i... | random_line_split | |
about-handler.js | // Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Name = "Vimperator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/about-... |
AboutHandler.prototype = {
classDescription: "About " + Name + " Page",
classID: Components.ID("81495d80-89ee-4c36-a88d-ea7c4e5ac63f"),
contractID: "@mozilla.org/network/protocol/about;1?what=" + name,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
newChannel: function (uri) {
... | {} | identifier_body |
about-handler.js | // Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Name = "Vimperator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/about-... | () {}
AboutHandler.prototype = {
classDescription: "About " + Name + " Page",
classID: Components.ID("81495d80-89ee-4c36-a88d-ea7c4e5ac63f"),
contractID: "@mozilla.org/network/protocol/about;1?what=" + name,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
newChannel: function (uri) ... | AboutHandler | identifier_name |
basic-worker.js | 'use strict'
const getNamespace = require('continuation-local-storage').getNamespace
const Promise = require('bluebird')
const WorkerStopError = require('error-cat/errors/worker-stop-error')
const Ponos = require('../')
/**
* A simple worker that will publish a message to a queue.
* @param {object} job Object desc... |
const server = new Ponos.Server({
tasks: {
'basic-queue-worker': basicWorker
},
events: {
'basic-event-worker': basicWorker
}
})
server.start()
.then(() => { console.log('server started') })
.catch((err) => { console.error('server error:', err.stack || err.message || err) })
process.on('SIGINT',... | {
return Promise.try(() => {
const tid = getNamespace('ponos').get('tid')
if (!job.message) {
throw new WorkerStopError('message is required', { tid: tid })
}
console.log(`hello world: ${job.message}. tid: ${tid}`)
})
} | identifier_body |
basic-worker.js | 'use strict'
const getNamespace = require('continuation-local-storage').getNamespace
const Promise = require('bluebird')
const WorkerStopError = require('error-cat/errors/worker-stop-error')
const Ponos = require('../')
/**
* A simple worker that will publish a message to a queue.
* @param {object} job Object desc... | })
server.start()
.then(() => { console.log('server started') })
.catch((err) => { console.error('server error:', err.stack || err.message || err) })
process.on('SIGINT', () => {
server.stop()
.then(() => { console.log('server stopped') })
.catch((err) => { console.error('server error:', err.stack || er... | random_line_split | |
basic-worker.js | 'use strict'
const getNamespace = require('continuation-local-storage').getNamespace
const Promise = require('bluebird')
const WorkerStopError = require('error-cat/errors/worker-stop-error')
const Ponos = require('../')
/**
* A simple worker that will publish a message to a queue.
* @param {object} job Object desc... | (job) {
return Promise.try(() => {
const tid = getNamespace('ponos').get('tid')
if (!job.message) {
throw new WorkerStopError('message is required', { tid: tid })
}
console.log(`hello world: ${job.message}. tid: ${tid}`)
})
}
const server = new Ponos.Server({
tasks: {
'basic-queue-work... | basicWorker | identifier_name |
basic-worker.js | 'use strict'
const getNamespace = require('continuation-local-storage').getNamespace
const Promise = require('bluebird')
const WorkerStopError = require('error-cat/errors/worker-stop-error')
const Ponos = require('../')
/**
* A simple worker that will publish a message to a queue.
* @param {object} job Object desc... |
console.log(`hello world: ${job.message}. tid: ${tid}`)
})
}
const server = new Ponos.Server({
tasks: {
'basic-queue-worker': basicWorker
},
events: {
'basic-event-worker': basicWorker
}
})
server.start()
.then(() => { console.log('server started') })
.catch((err) => { console.error('server... | {
throw new WorkerStopError('message is required', { tid: tid })
} | conditional_block |
transpile.bundles.rollup.aot.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import { join } from 'path';
import Config from '../../config';
import { makeTsProject } from '../../utils';
import { TemplateLocalsBuilder } from '../../utils/seed/template_locals';
const plugins = <any>gulpLoadPlugins();
/**
* Exe... | {
allowJs: true,
noFallthroughCasesInSwitch: false
},
Config.TMP_DIR
);
const src = [ join(Config.TMP_DIR, 'bundle.js') ];
const result = gulp
.src(src)
.pipe(plugins.plumber())
.pipe(
Config.PRESERVE_SOURCE_MAPS
? plugins.sourcemaps.init({ loadMaps: true, largeFi... | random_line_split | |
packet_handler.rs | extern crate netfilter_queue as nfq;
use std::ptr::null;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{CopyMode, Verdict, PacketHandler, QueueHandle};
use nfq::message::Message;
use nfq::error::Error;
fn main() {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok(... |
}
| {
match message {
Ok(m) => {
let _ = Verdict::set_verdict(hq, m.header.id(), Verdict::Accept, 0, null());
},
Err(_) => ()
}
0
} | identifier_body |
packet_handler.rs | extern crate netfilter_queue as nfq;
use std::ptr::null;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{CopyMode, Verdict, PacketHandler, QueueHandle};
use nfq::message::Message;
use nfq::error::Error;
fn | () {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok().unwrap();
let mut queue = handle.queue(0, Decider).ok().unwrap();
let _ = queue.set_mode(CopyMode::Metadata).unwrap();
println!("Listening for packets...");
handle.start(4096);
println!("...finished.... | main | identifier_name |
packet_handler.rs | extern crate netfilter_queue as nfq;
use std::ptr::null;
use nfq::handle::{Handle, ProtocolFamily};
use nfq::queue::{CopyMode, Verdict, PacketHandler, QueueHandle};
use nfq::message::Message;
use nfq::error::Error;
fn main() {
let mut handle = Handle::new().ok().unwrap();
handle.bind(ProtocolFamily::INET).ok(... | handle.start(4096);
println!("...finished.");
}
struct Decider;
impl PacketHandler for Decider {
#[allow(non_snake_case)]
fn handle(&mut self, hq: QueueHandle, message: Result<&Message, &Error>) -> i32 {
match message {
Ok(m) => {
let _ = Verdict::set_verdict(hq, m... | random_line_split | |
cluster.py | ch(coord, ref,app):
|
def rmsd(coord, ref):
sd = (coord - ref)**2
ssd = np.mean(sd)
rmsd = np.sqrt(ssd)
return rmsd
#colors = [(1,.4,.4),(.4,.4,1),(.4,1,.4),(1,.4,1),(.4,1,1),(1,.7,.4),(1,.4,.7)]
colors = [(0,.6,.6),(1,0,.5),(1,1,.2),(1,1,.2),(.8,.4,0),(.6,1,1),(.8,0,.8),(0,.9,0),(0,.6,.6),(1,0,.5),(1,1,.2),(1,1,.2),(.8,.4,0),(.6,1,... | C = np.dot(np.transpose(coord), ref)
V, S, W = np.linalg.svd(C)
#print("VSW", V,S,W)
d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0
if d:
S[-1] = -S[-1]
V[:,-1] = -V[:,-1]
# Create Rotation matrix U
U = np.dot(V, W)
# Rotate coord
kcoord = np.dot(app, U)
return kcoord | identifier_body |
cluster.py | absch(coord, ref,app):
C = np.dot(np.transpose(coord), ref)
V, S, W = np.linalg.svd(C)
#print("VSW", V,S,W)
d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0
if d:
S[-1] = -S[-1]
V[:,-1] = -V[:,-1]
# Create Rotation matrix U
U = np.dot(V, W)
# Rotate coord
kcoord = np.dot(app, U)
return kcoord
def rmsd... | for o,st in enumerate(clust):
strmsdlist = []
stCst = st[CCC]
stC = stCst - np.mean(stCst, axis = 0)
st3 = st - np.mean(st, axis = 0)
#ik = i[np.array([2,7,12])]
#ikm = ik - np.mean(ik, axis = 0)
#im = i - np.mean(i, axis = 0)
#print(i)
for st2 in clust:
st2Cst = st2[CCC]
st2C = st2Cst - n... | random_line_split | |
cluster.py | ch(coord, ref,app):
C = np.dot(np.transpose(coord), ref)
V, S, W = np.linalg.svd(C)
#print("VSW", V,S,W)
d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0
if d:
S[-1] = -S[-1]
V[:,-1] = -V[:,-1]
# Create Rotation matrix U
U = np.dot(V, W)
# Rotate coord
kcoord = np.dot(app, U)
return kcoord
def rmsd(co... |
rmsdlist = []
coordlist = []
for clust in clusters:
l = len(clust)
av = round(l / 2, -1)
av = int(av)
crmsdlist = []
alignedcoordlist = []
for o,st in enumerate(clust):
strmsdlist = []
stCst = st[CCC]
stC = stCst - np.mean(stCst, axis = 0)
st3 = st - np.mean(st, axis = 0)
#ik = i[np.array([2,7,12])]... | cluster = ctree[i]
structure = np.load("goodmodels0.npy")[i]
# print(len(clusters))
# print(cluster)
clusters[cluster].append(structure) | conditional_block |
cluster.py | (coord, ref,app):
C = np.dot(np.transpose(coord), ref)
V, S, W = np.linalg.svd(C)
#print("VSW", V,S,W)
d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0
if d:
S[-1] = -S[-1]
V[:,-1] = -V[:,-1]
# Create Rotation matrix U
U = np.dot(V, W)
# Rotate coord
kcoord = np.dot(app, U)
return kcoord
def rmsd(coor... | kabsch | identifier_name | |
factory.py | # -*- coding: utf-8 -*-
#
# This file is part of HEPData.
# Copyright (C) 2016 CERN.
#
# HEPData 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 2 of the
# License, or (at your option) any later... |
create_app = create_app_factory(
'hepdata',
config_loader=conf_loader,
extension_entry_points=['invenio_base.apps'],
blueprint_entry_points=['invenio_base.blueprints'],
wsgi_factory=create_wsgi_factory({'/api': create_api}),
instance_path=instance_path,
static_folder=static_folder,
) | random_line_split | |
response_container_paged_recent_traces_search.py | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | self._response = None
self._status = None
self.discriminator = None
if response is not None:
self.response = response
self.status = status
@property
def response(self):
"""Gets the response of this ResponseContainerPagedRecentTracesSearch. # noqa: E... | random_line_split | |
response_container_paged_recent_traces_search.py | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... |
@response.setter
def response(self, response):
"""Sets the response of this ResponseContainerPagedRecentTracesSearch.
:param response: The response of this ResponseContainerPagedRecentTracesSearch. # noqa: E501
:type: PagedRecentTracesSearch
"""
self._response = res... | """Gets the response of this ResponseContainerPagedRecentTracesSearch. # noqa: E501
:return: The response of this ResponseContainerPagedRecentTracesSearch. # noqa: E501
:rtype: PagedRecentTracesSearch
"""
return self._response | identifier_body |
response_container_paged_recent_traces_search.py | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... |
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
... | result[attr] = value.to_dict() | conditional_block |
response_container_paged_recent_traces_search.py | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | (self, response=None, status=None, _configuration=None): # noqa: E501
"""ResponseContainerPagedRecentTracesSearch - a model defined in Swagger""" # noqa: E501
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._response = ... | __init__ | identifier_name |
posix.rs | use {TryRead, TryWrite};
use io::{self, PipeReader, PipeWriter};
use std::mem;
use std::os::unix::io::{Fd, AsRawFd};
/*
*
* ===== Awakener =====
*
*/
pub struct Awakener {
reader: PipeReader,
writer: PipeWriter,
}
impl Awakener {
pub fn new() -> io::Result<Awakener> {
let (rd, wr) = try!(io::... | // Consume data until all bytes are purged
match rd.read_slice(&mut buf) {
Ok(Some(i)) if i > 0 => {},
_ => return,
}
}
}
}
} | let rd: &mut PipeReader = mem::transmute(&self.reader);
| random_line_split |
posix.rs | use {TryRead, TryWrite};
use io::{self, PipeReader, PipeWriter};
use std::mem;
use std::os::unix::io::{Fd, AsRawFd};
/*
*
* ===== Awakener =====
*
*/
pub struct | {
reader: PipeReader,
writer: PipeWriter,
}
impl Awakener {
pub fn new() -> io::Result<Awakener> {
let (rd, wr) = try!(io::pipe());
Ok(Awakener {
reader: rd,
writer: wr
})
}
pub fn as_raw_fd(&self) -> Fd {
self.reader.as_raw_fd()
}
... | Awakener | identifier_name |
posix.rs | use {TryRead, TryWrite};
use io::{self, PipeReader, PipeWriter};
use std::mem;
use std::os::unix::io::{Fd, AsRawFd};
/*
*
* ===== Awakener =====
*
*/
pub struct Awakener {
reader: PipeReader,
writer: PipeWriter,
}
impl Awakener {
pub fn new() -> io::Result<Awakener> {
let (rd, wr) = try!(io::... |
}
| {
let mut buf = [0; 128];
loop {
// Also a bit hackish. It would be possible to split up the read /
// write sides of the awakener, but that would be a more
// significant refactor. A transmute here is safe.
unsafe {
let rd: &mut PipeReade... | identifier_body |
ws.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | extractors::WsStats::new(stats),
).unwrap());
(res, port, authcodes)
}
/// Test a single request to running server
pub fn request(server: Server<ws::Server>, request: &str) -> http_client::Response {
http_client::request(server.server.addr(), request)
}
#[cfg(test)]
mod testing {
use std::time;
use hash::kecc... | random_line_split | |
ws.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | () {
// given
let (server, port, authcodes) = serve();
let code = "initial";
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
assert!(authcodes.is_empty());
// when
let response1 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Con... | should_allow_initial_connection_but_only_once | identifier_name |
ws.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... |
#[test]
fn should_block_if_authorization_is_incorrect() {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-P... | {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: close\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 200 Ok".to_owned());
} | identifier_body |
RoomRouter.ts | import { Router } from 'express';
import { IRoomInfo, IRoomArgs } from '../services/RoomDataService';
import { RoomManager } from '../room/RoomManager';
export class RoomRouter {
roomMgr: RoomManager
router = Router();
public constructor(roomManager: RoomManager) {
this.roomMgr = roomManager;
... |
this.roomMgr.makeRoom(roomParam).then((result) =>{
response.send({
result: result
});
}).catch((err) => {
next(err);
});
}
} | {
roomParam.password = request.body.password;
} | conditional_block |
RoomRouter.ts | import { Router } from 'express';
import { IRoomInfo, IRoomArgs } from '../services/RoomDataService';
import { RoomManager } from '../room/RoomManager';
export class RoomRouter {
roomMgr: RoomManager
router = Router();
public constructor(roomManager: RoomManager) {
this.roomMgr = roomManager;
... |
} | {
//Gather room information
let roomParam = <IRoomArgs>{
name: request.body.name,
}
if (request.body.password != null) {
roomParam.password = request.body.password;
}
this.roomMgr.makeRoom(roomParam).then((result) =>{
response.send({
... | identifier_body |
RoomRouter.ts | import { Router } from 'express';
import { IRoomInfo, IRoomArgs } from '../services/RoomDataService';
import { RoomManager } from '../room/RoomManager';
export class RoomRouter {
roomMgr: RoomManager
router = Router();
public constructor(roomManager: RoomManager) {
this.roomMgr = roomManager;
... | (request, response, next) {
//Gather room information
let roomParam = <IRoomArgs>{
name: request.body.name,
}
if (request.body.password != null) {
roomParam.password = request.body.password;
}
this.roomMgr.makeRoom(roomParam).then((result) =>{
... | createRoom | identifier_name |
RoomRouter.ts | import { Router } from 'express';
import { IRoomInfo, IRoomArgs } from '../services/RoomDataService';
import { RoomManager } from '../room/RoomManager';
export class RoomRouter {
roomMgr: RoomManager
router = Router();
public constructor(roomManager: RoomManager) {
this.roomMgr = roomManager;
... | next(err);
});
}
/**
*
*/
public createRoom(request, response, next) {
//Gather room information
let roomParam = <IRoomArgs>{
name: request.body.name,
}
if (request.body.password != null) {
roomParam.password = request.b... | response.send({
result: rooms
});
}).catch((err) => { | random_line_split |
unresolved_type_param.rs | // Provoke an unresolved type error (T).
// Error message should pinpoint the type parameter T as needing to be bound
// (rather than give a general error message)
// edition:2018
async fn bar<T>() -> () {}
async fn foo() {
bar().await;
//~^ ERROR type inside `async fn` body must be known in this context
... | () {}
| main | identifier_name |
unresolved_type_param.rs | // Provoke an unresolved type error (T).
// Error message should pinpoint the type parameter T as needing to be bound
// (rather than give a general error message)
// edition:2018 | //~^ ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE cannot infer type for type param... |
async fn bar<T>() -> () {}
async fn foo() {
bar().await; | random_line_split |
unresolved_type_param.rs | // Provoke an unresolved type error (T).
// Error message should pinpoint the type parameter T as needing to be bound
// (rather than give a general error message)
// edition:2018
async fn bar<T>() -> () {}
async fn foo() |
fn main() {}
| {
bar().await;
//~^ ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| ERROR type inside `async fn` body must be known in this context
//~| NOTE cannot infer type for type parameter `T`
//~| NOTE cannot infer ... | identifier_body |
0012_auto_20170620_1435.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-20 18:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('hamask', '0011_auto_20170615_1520'),
]
operations = [
migrations.AddField(
model_name='workout',
name='day_of_week',
field=models.CharField(blank=True, choices=[('1', 'Sunday'), ('2', 'Monday'), ('3', 'Tuesday'), ('4', 'Wednesday'), ('5', '... | identifier_body | |
0012_auto_20170620_1435.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-20 18:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hamask', '0011_auto_20170615_1520'),
]
operations = [
migrations.AddField(
... | ] | ), | random_line_split |
0012_auto_20170620_1435.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-20 18:35
from __future__ import unicode_literals
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
('hamask', '0011_auto_20170615_1520'),
]
operations = [
migrations.AddField(
model_name='workout',
name='day_of_week',
field=models.CharField(blank=True, choices=[('1', 'Sunday'), ('2', 'Monday'), ('3', 'Tuesday')... | Migration | identifier_name |
jquery.sticky.js | aronco)
// Created: 02/14/2011
// Date: 07/20/2015
// Website: http://stickyjs.com/
// Description: Makes an element on the page stick on the screen as you scroll
// It will only set the 'top' and 'position' of your element, you
// might need to adjust the width in some cases.
(function (fact... |
s.currentTop = newTop;
}
// Check if sticky has reached end of container and stop sticking
var stickyWrapperContainer = s.stickyWrapper.parent();
var unstick = (s.stickyElement.offset().top + s.stickyElement.outerHeight() >= stickyWrapperContainer.offset().top + st... | {
// sticky is started && sticked at topSpacing && overflowing from top just finished
s.stickyElement.trigger('sticky-bottom-unreached', [s]);
} | conditional_block |
jquery.sticky.js | aronco)
// Created: 02/14/2011
// Date: 07/20/2015
// Website: http://stickyjs.com/
// Description: Makes an element on the page stick on the screen as you scroll
// It will only set the 'top' and 'position' of your element, you
// might need to adjust the width in some cases.
(function (fact... | var splice = Array.prototype.splice; // save ref to original slice()
var defaults = {
topSpacing: 0,
bottomSpacing: 0,
className: 'is-sticky',
wrapperClassName: 'sticky-wrapper',
center: false,
getWidthFrom: '',
widthFromWrapper: true, // works only when .getWidthFrom is... | }
}(function ($) {
var slice = Array.prototype.slice; // save ref to original slice() | random_line_split |
DatasetActions.tsx | import React, { FC } from 'react';
import styled from 'styled-components';
import { Dataset, DatasetType } from 'typings/dataset';
import GridRow from 'components/_base/GridRow';
import { useTranslation } from 'react-i18next';
import { Button } from 'antd';
import { isImportFailed } from 'shared/dataset';
import { Butt... | 'view-records': t('dataset.btn_view_records'),
'copy-path': t('dataset.btn_copy_path'),
delete: t('delete'),
};
return (
<Container {...{ type }}>
{actions.map((action) => {
return (
<Button
size="small"
type={type}
key={action}
... | const text = {
'add-batch': t('dataset.btn_add_batch'), | random_line_split |
network.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
private toUri(uriOrModule: URI | string, moduleIdToUrl?: { toUrl(moduleId: string): string }): URI {
if (URI.isUri(uriOrModule)) {
return uriOrModule;
}
return URI.parse(moduleIdToUrl!.toUrl(uriOrModule));
}
}
export const FileAccess = new FileAccessImpl();
| {
const uri = this.toUri(uriOrModule, moduleIdToUrl);
// Only convert the URI if it is `vscode-file:` scheme
if (uri.scheme === Schemas.vscodeFileResource) {
return uri.with({
scheme: Schemas.file,
// Only preserve the `authority` if it is different from
// our fallback authority. This ensures we ... | identifier_body |
network.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
const port = this._ports[authority];
const connectionToken = this._connectionTokens[authority];
let query = `path=${encodeURIComponent(uri.path)}`;
if (typeof connectionToken === 'string') {
query += `&tkn=${encodeURIComponent(connectionToken)}`;
}
return URI.from({
scheme: platform.isWeb ? this._pre... | {
host = `[${host}]`;
} | conditional_block |
network.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (schema: 'http' | 'https') {
this._preferredWebSchema = schema;
}
setDelegate(delegate: (uri: URI) => URI): void {
this._delegate = delegate;
}
set(authority: string, host: string, port: number): void {
this._hosts[authority] = host;
this._ports[authority] = port;
}
setConnectionToken(authority: string... | setPreferredWebSchema | identifier_name |
network.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | const connectionToken = this._connectionTokens[authority];
let query = `path=${encodeURIComponent(uri.path)}`;
if (typeof connectionToken === 'string') {
query += `&tkn=${encodeURIComponent(connectionToken)}`;
}
return URI.from({
scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteRe... | const port = this._ports[authority]; | random_line_split |
setup.py | """Setup script of zinnia-twitter"""
from setuptools import setup
from setuptools import find_packages
import zinnia_twitter
| setup(
name='zinnia-twitter',
version=zinnia_twitter.__version__,
description='Twitter plugin for django-blog-zinnia',
long_description=open('README.rst').read(),
keywords='django, zinnia, twitter',
author=zinnia_twitter.__author__,
author_email=zinnia_twitter.__email__,
url=zinnia_tw... | random_line_split | |
flow.py | '''
David Rodriguez
Goal: Continuously looping while to perform valve actions at specified times,
introduce substance at a specific ratio based on flow data, recording
and saving flow data, and actuating a flush at a specified time.
Inputs: A schedule of events based on entered times.
Outputs: Sequence of e... | PWM.set_frequency("P9_16", 250)
time.sleep(90)
PWM.stop("P9_16")
PWM.cleanup()
def toiletTrigger(self, flushType):
if flushType == "Full":
self.toiletFull()
else:
self.toiletUrine()
def toiletUrine(self):
print "Toilet... | GPIO.setup("P8_7", GPIO.OUT) #stepper direction
GPIO.setup("P9_16", GPIO.OUT) #step
GPIO.setup("P8_11", GPIO.OUT) #(0: enabled, 1: disabled)
GPIO.setup("P8_15", GPIO.OUT) #Direction for actuator 1
GPIO.setup("P8_17", GPIO.OUT) #PWM for actuator 1
GPIO.setup("P8_16", GPIO.OUT) #Direction for act... | identifier_body |
flow.py | '''
David Rodriguez
Goal: Continuously looping while to perform valve actions at specified times,
introduce substance at a specific ratio based on flow data, recording
and saving flow data, and actuating a flush at a specified time.
Inputs: A schedule of events based on entered times.
Outputs: Sequence of e... | :
GPIO.setup("P8_7", GPIO.OUT) #stepper direction
GPIO.setup("P9_16", GPIO.OUT) #step
GPIO.setup("P8_11", GPIO.OUT) #(0: enabled, 1: disabled)
GPIO.setup("P8_15", GPIO.OUT) #Direction for actuator 1
GPIO.setup("P8_17", GPIO.OUT) #PWM for actuator 1
GPIO.setup("P8_16", GPIO.OUT) #Direction ... | Flow | identifier_name |
flow.py | '''
David Rodriguez
Goal: Continuously looping while to perform valve actions at specified times,
introduce substance at a specific ratio based on flow data, recording
and saving flow data, and actuating a flush at a specified time.
Inputs: A schedule of events based on entered times.
Outputs: Sequence of e... |
else:
self.toiletUrine()
def toiletUrine(self):
print "Toilet Urine Triggered"
self.enableStepper()
self.triggerStepper()
GPIO.output("P8_17", GPIO.HIGH) #pwm on
GPIO.output("P8_15", GPIO.LOW) #extend actuator
time.sleep(.65)
... | self.toiletFull() | conditional_block |
flow.py | '''
David Rodriguez
Goal: Continuously looping while to perform valve actions at specified times,
introduce substance at a specific ratio based on flow data, recording
and saving flow data, and actuating a flush at a specified time.
Inputs: A schedule of events based on entered times.
Outputs: Sequence of e... | GPIO.output("P8_17", GPIO.HIGH) #pwm on
GPIO.output("P8_15", GPIO.LOW) #extend actuator
time.sleep(.65)
GPIO.output("P8_15", GPIO.HIGH) #retract actuator
time.sleep(2)
GPIO.output("P8_17", GPIO.LOW) #pwn off
self.disableStepper()
def toiletFull(self)... |
def toiletUrine(self):
print "Toilet Urine Triggered"
self.enableStepper()
self.triggerStepper()
| random_line_split |
streamio-consumer.js | var stream = require('getstream');
// Instantiate a new client (server side)
client = stream.connect('9jtyb249ejzp', 'jnbe82eryq4qvquj4wn5dc8nh85bry33jpbmu84jn58xc3uk4y697xke4rcz9kyk', '24985');
// Instantiate a new client (client side)
//client = stream.connect('9jtyb249ejzp', null, '24985');
var p1 = client.feed('pr... | var nextActivityData = results;
console.log('Activity data:', activityData);
});
}); | console.log('Activity data:', activityData);
// Read the next page, using id filtering for optimal performance:
p1.get({ limit: 10, id_lte: activityData[activityData.length-1].id }).then(function(results) { | random_line_split |
websocket.js | /**
* emit events
* websocket-error
* websocket-message
* session-expired
* logined
* error
* connected
*/
/**
* @param {string} sessionId
* @param {string} url
* @constructor
*/
var AppWebSocket = function (sessionId, url) {
this.url = url;
this.websocket = null;
this.sessionId = sessionId;
//wi... |
} else if (data.REP_REQ_ID === this.restoreSessionMsg) {
if (data.REP_STATUS === 'SUCCESS') {
this.logined = true;
this.emit('logined', data.REP);
} else {
//this.win.window.login();
this.logined = false;
this.emit('session-expired');
}
this.restoreSessionMsg = null;
}
//} catch (e) {
// //t... | {
//this.win.window.alert('Wrong email or password');
//this.win.window.document.querySelector('.wkErrorMessage').style.visibility = 'visible';
this.logined = false;
this.emit('error', 'Wrong email or password');
//todo add settimeout hide
} | conditional_block |
websocket.js | /**
* emit events
* websocket-error
* websocket-message
* session-expired
* logined
* error
* connected
*/
/**
* @param {string} sessionId
* @param {string} url
* @constructor
*/
var AppWebSocket = function (sessionId, url) {
this.url = url;
this.websocket = null;
this.sessionId = sessionId;
//wi... | this.websocket.onerror = this.onError.bind(this);
this.websocket.onmessage = this.onMessage.bind(this);
};
AppWebSocket.prototype.reconnect = function () {
if (this.websocket && this.websocket) {
console.log('AppWebSocket.reconnect');
this.websocket.close();
this.connect();
}
};
AppWebSocket.prototype.onOpe... | random_line_split | |
0021_auto_20151008_1526.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def from_election_to_elections(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Election = a... |
class Migration(migrations.Migration):
dependencies = [
('elections', '0020_auto_20150821_2101'),
]
operations = [
migrations.AddField(
model_name='candidate',
name='elections',
field=models.ManyToManyField(related_name='candidates', null=True, to='el... | candidate.elections.add(candidate.election) | conditional_block |
0021_auto_20151008_1526.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def | (apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Election = apps.get_model("elections", "Election")
Candidate = apps.get_model("elections", "Candidate")
for candidate in Candidate.objects.all... | from_election_to_elections | identifier_name |
0021_auto_20151008_1526.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def from_election_to_elections(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Election = a... | migrations.AddField(
model_name='candidate',
name='elections',
field=models.ManyToManyField(related_name='candidates', null=True, to='elections.Election'),
),
migrations.RunPython(from_election_to_elections),
] | dependencies = [
('elections', '0020_auto_20150821_2101'),
]
operations = [ | random_line_split |
0021_auto_20151008_1526.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def from_election_to_elections(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Election = a... | dependencies = [
('elections', '0020_auto_20150821_2101'),
]
operations = [
migrations.AddField(
model_name='candidate',
name='elections',
field=models.ManyToManyField(related_name='candidates', null=True, to='elections.Election'),
),
migratio... | identifier_body | |
views_css_layout.js | window.cls || (window.cls = {});
/**
* @constructor
* @extends ViewBase
*/
cls.CSSLayoutView = function(id, name, container_class)
{
var self = this;
this.createView = function(container)
{
if( !container.getElementsByTagName('layout-container')[0] )
{
container.innerHTML = "<div class='... | var offsets = container.getElementsByTagName('offsets-container')[0];
if (offsets)
offsets.clearAndRender(window.templates.offset_values(offset_values));
}
this.init(id, name, container_class);
var onSettingChange = function(msg)
{
if( msg.id == "dom"
&& ( msg.key == "show-sibling... | { | random_line_split |
views_css_layout.js | window.cls || (window.cls = {});
/**
* @constructor
* @extends ViewBase
*/
cls.CSSLayoutView = function(id, name, container_class)
{
var self = this;
this.createView = function(container)
{
if( !container.getElementsByTagName('layout-container')[0] )
{
container.innerHTML = "<div class='... | }
this.updateLayout({});
window.elementLayout.getOffsetsValues(this.updateOffsets.bind(this, container));
}
this.updateLayout = function(ev)
{
var containers = self.getAllContainers(), c = null , i = 0;
// TODO not good logic
for( ; c = containers[i]; i++)
{
c = c.getElementsByTa... | hostspotlighter.clearMouseHandlerTarget();
layout.addEventListener('mouseover', hostspotlighter.metricsMouseoverHandler, false);
layout.addEventListener('mouseout', hostspotlighter.metricsMouseoutHandler, false);
}
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.