file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
acceptancetest.py | import hashlib
import shutil
import os
from datetime import datetime
list_of_paths_and_strings = [
["assignment1.cpp", "main()"]
]
def main():
if acceptance_test():
make_txt_file()
zip_dir()
def get_md5_hash(file):
# opening file
file_to_hash = open(file)
read_file = file_to_hash.read()
... | ():
# writes a text file with each of the hashes for each of the files using MD5
write_file = open("hash.txt", "w+")
write_file.write("Write time: " + str(get_current_time()) + '\n')
for file in os.listdir(os.getcwd()):
if "." in file:
f_name, file_hash = get_md5_hash(file)
write_file.write(f_name ... | make_txt_file | identifier_name |
acceptancetest.py | import hashlib
import shutil
import os
from datetime import datetime
list_of_paths_and_strings = [
["assignment1.cpp", "main()"]
]
def main():
if acceptance_test():
make_txt_file()
zip_dir()
def get_md5_hash(file):
# opening file
|
def get_current_time():
print "The current time is " + " datetime.today()"
return datetime.today()
def acceptance_test():
# for each list of the list of paths and strings
# make sure that a file with that name exists within the folder
for my_list in list_of_paths_and_strings:
path = my_list[0]
l... | file_to_hash = open(file)
read_file = file_to_hash.read()
# get hash of file
md5_hash = hashlib.md5(read_file)
md5_hash_output = md5_hash.hexdigest()
# print file name and hash
print "File Name: %s" % file
print "MD5 Hash: %r" % md5_hash_output
# return hash
return file, md5_hash_output | identifier_body |
queue.js | "use strict";
var ASSERT = require("./assert");
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) |
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};... | {
this._capacity = capacity;
this._length = 0;
this._front = 0;
} | identifier_body |
queue.js | "use strict";
var ASSERT = require("./assert");
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this... |
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exp... | {
this._resizeTo(this._capacity << 1);
} | conditional_block |
queue.js | "use strict";
var ASSERT = require("./assert");
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function | (capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._fron... | Queue | identifier_name |
queue.js | "use strict";
var ASSERT = require("./assert");
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this... | return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
... |
Queue.prototype.length = function () { | random_line_split |
keytar.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
(async () => {
const keytar = await import('keytar');
const name = `VSCode Test ${Math.floor(Math.random() * 1e9)}`;
try {
await keytar.setPassword(name, 'foo', 'bar');
assert.equal(await keytar.getPassword(name, 'foo'), 'bar');
await keytar.deletePassword(name, 'foo');
assert.equal(await ke... | {
// Skip test due to set up issue with Travis.
this.skip();
return;
} | conditional_block |
keytar.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | if (platform.isLinux) {
// Skip test due to set up issue with Travis.
this.skip();
return;
}
(async () => {
const keytar = await import('keytar');
const name = `VSCode Test ${Math.floor(Math.random() * 1e9)}`;
try {
await keytar.setPassword(name, 'foo', 'bar');
assert.equal(await keytar.... | suite('Keytar', () => {
test('loads and is functional', function (done) { | random_line_split |
TableDialog.js.uncompressed.js | define("dojox/editor/plugins/nls/mk/TableDialog", {
//begin v1.x content
insertTableTitle: "Вметни табела",
modifyTableTitle: "Модифицирај табела",
rows: "Редови",
columns: "Колони",
align: "Порамни:",
cellPadding: "Дополнување на ќелија:",
cellSpacing: "Растојание меѓу ќелии:",
tableWidth: "Ширина на таб... | deleteTableColumnLabel: "Избриши колона",
colorTableCellTitle: "Боја на заднина на ќелија на табела",
tableContextMenuTitle: "Контекстуално мени на табела"
//end v1.x content
}); | insertTableColumnAfterLabel: "Додај колона после",
deleteTableRowLabel: "Избриши ред", | random_line_split |
defaults-fa_IR.min.js | /*! | *
* Copyright 2013-2016 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,functi... | * Bootstrap-select v1.11.0 (http://silviomoreto.github.io/bootstrap-select) | random_line_split |
iterateOverGenerator.es6.js | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed ... |
setTimeout(iterate, 0);
}
| {
let iteration;
if (value) {
iteration = value.next();
} else {
iteration = iterator.next();
}
if (!iteration.done) {
if ('then' in iteration.value) {
iteration.value.then(function iterateGenerator() {
ite... | identifier_body |
iterateOverGenerator.es6.js | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed ... |
if (!iteration.done) {
if ('then' in iteration.value) {
iteration.value.then(function iterateGenerator() {
iterator.next();
});
} else {
iterate(iteration.value);
}
}
}
setTimeout(iterate, ... | {
iteration = iterator.next();
} | conditional_block |
iterateOverGenerator.es6.js | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed ... | (value) {
let iteration;
if (value) {
iteration = value.next();
} else {
iteration = iterator.next();
}
if (!iteration.done) {
if ('then' in iteration.value) {
iteration.value.then(function iterateGenerator() {
... | iterate | identifier_name |
iterateOverGenerator.es6.js | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed ... | } else {
iteration = iterator.next();
}
if (!iteration.done) {
if ('then' in iteration.value) {
iteration.value.then(function iterateGenerator() {
iterator.next();
});
} else {
iterate(iterat... | function iterate(value) {
let iteration;
if (value) {
iteration = value.next(); | random_line_split |
xhr_impl_spec.ts | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit
} from 'angular2/test_lib';
import {XHRImpl} from 'angular2/src/core/render/xhr_impl';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
export function | () {
describe('XHRImpl', () => {
var xhr: XHRImpl;
var url200 = '/base/modules/angular2/test/core/services/static_assets/200.html';
var url404 = '/base/modules/angular2/test/core/services/static_assets/404.html';
beforeEach(() => { xhr = new XHRImpl(); });
it('should resolve the Promise with the... | main | identifier_name |
xhr_impl_spec.ts | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit
} from 'angular2/test_lib';
import {XHRImpl} from 'angular2/src/core/render/xhr_impl';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
export function main() {
describe('XHRImpl', () => {
... | return null;
});
}), 10000);
});
} | random_line_split | |
xhr_impl_spec.ts | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit
} from 'angular2/test_lib';
import {XHRImpl} from 'angular2/src/core/render/xhr_impl';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
export function main() | {
describe('XHRImpl', () => {
var xhr: XHRImpl;
var url200 = '/base/modules/angular2/test/core/services/static_assets/200.html';
var url404 = '/base/modules/angular2/test/core/services/static_assets/404.html';
beforeEach(() => { xhr = new XHRImpl(); });
it('should resolve the Promise with the fi... | identifier_body | |
lib.rs | use std::io::ErrorKind;
use std::net::Ipv4Addr;
use std::net::TcpStream;
use spaceapi_server::api;
use spaceapi_server::{SpaceapiServer, SpaceapiServerBuilder};
/// Create a new status object containing test data.
fn | () -> api::Status {
api::StatusBuilder::new("ourspace")
.logo("https://example.com/logo.png")
.url("https://example.com/")
.location(api::Location {
address: Some("Street 1, Zürich, Switzerland".into()),
lat: 47.123,
lon: 8.88,
})
.contact(... | get_status | identifier_name |
lib.rs | use std::io::ErrorKind;
use std::net::Ipv4Addr;
use std::net::TcpStream;
use spaceapi_server::api;
use spaceapi_server::{SpaceapiServer, SpaceapiServerBuilder};
/// Create a new status object containing test data.
fn get_status() -> api::Status {
api::StatusBuilder::new("ourspace")
.logo("https://example.... |
#[test]
fn server_starts() {
//! Test that the spaceapi server starts at all.
// Ip / port for test server
let ip = Ipv4Addr::new(127, 0, 0, 1);
let port = 3344;
// Test data
let status = get_status();
// Connection to port should fail right now
let connect_result = TcpStream::connec... |
SpaceapiServerBuilder::new(status)
.redis_connection_info("redis://127.0.0.1/")
.build()
.unwrap()
}
| identifier_body |
lib.rs | use std::io::ErrorKind;
use std::net::Ipv4Addr;
use std::net::TcpStream;
use spaceapi_server::api;
use spaceapi_server::{SpaceapiServer, SpaceapiServerBuilder};
/// Create a new status object containing test data.
fn get_status() -> api::Status {
api::StatusBuilder::new("ourspace")
.logo("https://example.... | // Ip / port for test server
let ip = Ipv4Addr::new(127, 0, 0, 1);
let port = 3344;
// Test data
let status = get_status();
// Connection to port should fail right now
let connect_result = TcpStream::connect((ip, port));
assert!(connect_result.is_err());
assert_eq!(connect_result.u... | random_line_split | |
elf64.rs | use core::fmt;
use core::iter::Iterator;
use ::kern::console::LogLevel::*;
pub const SIZEOF_IDENT: usize = 16;
pub const SIZEOF_EHDR: usize = 64;
pub const ELFCLASS: u8 = ELFCLASS64;
#[repr(C)]
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Header {
/// Magic number and other info
pub e_ident: [u8; SIZ... | (bytes: &'a [u8]) -> Elf64<'a> {
let h = &*(bytes.as_ptr() as *const Header);
Elf64 {
data: bytes,
header: h,
}
}
pub fn program_headers(&self) -> ProgramHeaderIter<'a> {
ProgramHeaderIter {
data: self.data,
header: self.header,
... | from | identifier_name |
elf64.rs | use core::fmt;
use core::iter::Iterator;
use ::kern::console::LogLevel::*;
pub const SIZEOF_IDENT: usize = 16;
pub const SIZEOF_EHDR: usize = 64;
pub const ELFCLASS: u8 = ELFCLASS64;
#[repr(C)]
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Header {
/// Magic number and other info
pub e_ident: [u8; SIZ... | pub const PF_X: u32 = 1 << 0;
/// Segment is writable
pub const PF_W: u32 = 1 << 1;
/// Segment is readable
pub const PF_R: u32 = 1 << 2;
pub struct ProgramHeaderIter<'a> {
data: &'a [u8],
header: &'a Header,
next: usize
}
pub struct Elf64<'a> {
pub header: &'a Header,
pub data: &'a [u8]
}
impl<'... | /// Segment is executable | random_line_split |
elf64.rs | use core::fmt;
use core::iter::Iterator;
use ::kern::console::LogLevel::*;
pub const SIZEOF_IDENT: usize = 16;
pub const SIZEOF_EHDR: usize = 64;
pub const ELFCLASS: u8 = ELFCLASS64;
#[repr(C)]
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Header {
/// Magic number and other info
pub e_ident: [u8; SIZ... |
}
/// No file type.
pub const ET_NONE: u16 = 0;
/// Relocatable file.
pub const ET_REL: u16 = 1;
/// Executable file.
pub const ET_EXEC: u16 = 2;
/// Shared object file.
pub const ET_DYN: u16 = 3;
/// Core file.
pub const ET_CORE: u16 = 4;
/// Number of defined types.
pub const ET_NUM: u16 = 5;
/// The ELF magic nu... | {
write!(f, "e_ident: {:?} e_type: {} e_machine: 0x{:x} e_version: 0x{:x} e_entry: 0x{:x} \
e_phoff: 0x{:x} e_shoff: 0x{:x} e_flags: {:x} e_ehsize: {} e_phentsize: {} \
e_phnum: {} e_shentsize: {} e_shnum: {} e_shstrndx: {}",
self.e_ident,
et_to_str(se... | identifier_body |
stream.rs | use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo};
use frame::frame_parser;
use utility::{
ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
many_metadata,
};
use std::io;
use std::usize;
use std::fs::File;
/// FLAC stream that decodes and hold file information.
pub... | (filename: &str) -> Result<StreamReader<File>, ErrorKind> {
File::open(filename).map_err(|e| ErrorKind::IO(e.kind()))
.and_then(|file| {
let producer = ReadStream::new(file);
Stream::from_stream_producer(producer)
})
}
/// Constructs a decoder with the given buffer.
/... | from_file | identifier_name |
stream.rs | use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo};
use frame::frame_parser;
use utility::{
ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
many_metadata,
};
use std::io;
use std::usize;
use std::fs::File;
/// FLAC stream that decodes and hold file information.
pub... |
/// Returns information for the current stream.
#[inline]
pub fn info(&self) -> StreamInfo {
self.info
}
/// Returns a slice of `Metadata`
///
/// This slice excludes `StreamInfo`, which is located in `Stream::info`.
/// Everything else is related to metadata for the FLAC stream is in the
/// s... | {
let producer = ReadStream::new(reader);
Stream::from_stream_producer(producer)
} | identifier_body |
stream.rs | use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo};
use frame::frame_parser;
use utility::{
ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
many_metadata,
};
use std::io;
use std::usize;
use std::fs::File;
/// FLAC stream that decodes and hold file information.
pub... | stream_info = info;
} else {
metadata.push(block);
}
}).map(|_| {
Stream {
info: stream_info,
metadata: metadata,
producer: producer,
}
})
}
/// Returns an iterator over the decoded samples.
#[inline]
pub fn iter<S: SampleSize>(&mut self) ... |
many_metadata(&mut producer, |block| {
if let metadata::Data::StreamInfo(info) = block.data { | random_line_split |
qtserialport_uk.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="uk_UA">
<context>
<name>QSerialPort</name>
<message>
<source>No error</source>
<translation>Немає помилки</translation>
</message>
<message>
<source>Device is already open</source>
<translati... | <translation>Помилка доступу під час створення файлу блокування</translation>
</message>
<message>
<source>Permission error while locking the device</source>
<translation>Помилка доступу під час блокування пристрою</translation>
</message>
<message>
<source>Cannot set cus... | </message>
<message>
<source>Permission error while creating lock file</source> | random_line_split |
glutin.rs | use glium::{
Frame,
IndexBuffer,
Surface,
VertexBuffer,
glutin,
program,
texture,
};
use glium::index::PrimitiveType;
use glium::backend::glutin_backend::GlutinFacade;
use super::super::gamestate::*;
use super::sound::{
Player,
PortAudio,
};
#[derive(Copy, Clone)]
// Non-snake case ... | () -> texture::RawImage2d<'static, (f32, f32, f32)> {
use std::cmp::min;
use std::mem;
use glium::texture::ClientFormat;
const TEXDIMENSION: u32 = 256;
const TEXBUFFSIZE: usize = (TEXDIMENSION*TEXDIMENSION) as usize;
let mut raw_data: Vec<(f32, f32, f32)> = Vec::new();
for i in 0..TEXDIMENSI... | gen_image | identifier_name |
glutin.rs | use glium::{
Frame,
IndexBuffer,
Surface,
VertexBuffer,
glutin,
program,
texture,
};
use glium::index::PrimitiveType;
use glium::backend::glutin_backend::GlutinFacade;
use super::super::gamestate::*;
use super::sound::{
Player,
PortAudio,
};
#[derive(Copy, Clone)]
// Non-snake case ... |
}
assert!(image.data.len() == image.width as usize * image.height as usize * image.format.get_size() / mem::size_of::<(f32, f32, f32)>(),
"size mismatch: len {:?}, width {:?}, height {:?}, get_size() {:?}, size_of {:?}",
image.data.len(), image.width, image.height, image.format.get_size... | {
println!("correcting wrong format: {:?}", image.format);
image.format = ClientFormat::F32F32F32;
} | conditional_block |
glutin.rs | use glium::{
Frame,
IndexBuffer,
Surface,
VertexBuffer,
glutin,
program,
texture,
};
use glium::index::PrimitiveType;
use glium::backend::glutin_backend::GlutinFacade;
use super::super::gamestate::*;
use super::sound::{
Player,
PortAudio,
};
#[derive(Copy, Clone)]
// Non-snake case ... | {
let data_mutex = data_mutex.clone();
let callback = move |field: Ref<field::Field>, current: &piece::Piece, ghost: Option<&piece::Piece>| {
let new_data = RenderData {
current: From::from(current),
field: field.clone(),
ghost: match ghost... | let image = gen_image();
let texture = texture::Texture2d::new(&display, image).unwrap();
let data_mutex: Arc<Mutex<Option<RenderData>>> = Arc::new(Mutex::new(None));
let mut game: game::Game; | random_line_split |
task-comm-11.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
extern mod extra;
use std::comm;
use std::task;
fn start(c: &comm::Chan... | // 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 | random_line_split |
task-comm-11.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let (p, ch) = comm::stream();
let child = task::spawn(|| start(&ch) );
let c = p.recv();
} | identifier_body | |
task-comm-11.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let (p, ch) = comm::stream();
let child = task::spawn(|| start(&ch) );
let c = p.recv();
}
| main | identifier_name |
test_exposed.py | """ Check what the `lambdax` module publicly exposes. """
import builtins
from inspect import isbuiltin, ismodule, isclass
from itertools import chain
import operator
from unittest.mock import patch
import lambdax.builtins_as_lambdas
import lambdax.builtins_overridden
from lambdax import x1, x2, x
def _get_exposed(t... | l = name.split('_', 1)
meth = tail[:-2]
original = _get_method_or_object(getattr(builtins, obj), meth)
as_λ = getattr(lambdax.builtins_as_lambdas, name)
overridden = _get_method_or_object(getattr(lambdax.builtins_overridden, obj), meth)
ref, ref_output = _get_effect(original)
... | conditional_block | |
test_exposed.py | """ Check what the `lambdax` module publicly exposes. """
import builtins
from inspect import isbuiltin, ismodule, isclass
from itertools import chain
import operator
from unittest.mock import patch
import lambdax.builtins_as_lambdas
import lambdax.builtins_overridden
from lambdax import x1, x2, x
def _get_exposed(t... | def test_base_exposed():
variables = {'x'} | {'x%d' % i for i in range(1, 10)}
variables |= {v.upper() for v in variables}
special_functions = {'λ', 'is_λ', 'comp', 'circle', 'chaining', 'and_', 'or_', 'if_'}
to_expose = variables | special_functions
exposed = _get_exposed(lambdax.lambda_calculus)
... | random_line_split | |
test_exposed.py | """ Check what the `lambdax` module publicly exposes. """
import builtins
from inspect import isbuiltin, ismodule, isclass
from itertools import chain
import operator
from unittest.mock import patch
import lambdax.builtins_as_lambdas
import lambdax.builtins_overridden
from lambdax import x1, x2, x
def | (tested_module):
return {name for name, obj in vars(tested_module).items()
if not name.startswith('_') and not ismodule(obj)}
def test_no_builtin_exposed():
for obj in chain(vars(lambdax).values(), vars(lambdax.builtins_overridden).values()):
assert not isbuiltin(obj)
def test_base_expos... | _get_exposed | identifier_name |
test_exposed.py | """ Check what the `lambdax` module publicly exposes. """
import builtins
from inspect import isbuiltin, ismodule, isclass
from itertools import chain
import operator
from unittest.mock import patch
import lambdax.builtins_as_lambdas
import lambdax.builtins_overridden
from lambdax import x1, x2, x
def _get_exposed(t... |
def test_base_exposed():
variables = {'x'} | {'x%d' % i for i in range(1, 10)}
variables |= {v.upper() for v in variables}
special_functions = {'λ', 'is_λ', 'comp', 'circle', 'chaining', 'and_', 'or_', 'if_'}
to_expose = variables | special_functions
exposed = _get_exposed(lambdax.lambda_calculu... | for obj in chain(vars(lambdax).values(), vars(lambdax.builtins_overridden).values()):
assert not isbuiltin(obj) | identifier_body |
app.js | 'use strict';
angular.module('playgroundApp', [
'playgroundApp.filters',
'playgroundApp.services',
'playgroundApp.directives',
'ngRoute',
'ui.bootstrap',
'ui',
])
.config(function($locationProvider, $routeProvider, $httpProvider,
$dialogProvider) { |
$locationProvider.html5Mode(true);
// TODO: add list of promises to be resolved for injection
// TODO: resolved promises are injected into controller
// TODO: see http://www.youtube.com/watch?v=P6KITGRQujQ
$routeProvider
.when('/playground/', {
templateUrl: '/playground/main.html',
controller: M... | random_line_split | |
selections.js | /* globals google: true */
import Ember from 'ember';
const { later } = Ember.run;
const { on, computed, isArray } = Ember;
export default Ember.Mixin.create({
// Stores reference to google DrawingManager instance
_drawingManager: null,
/**
* [selectionsDelay time it takes to remove last selection from th... |
return options;
}
),
/**
* [_syncDrawingMangagerOptions finally sets the options on the drawManager instance]
* [Added via `_initSelections`]
* [Observes ('_drawManagerOptions')]
*/
_syncDrawingMangagerOptions: function() {
return this.get('_drawingManager').setOptions(this.get('_dra... | {
options.rectangleOptions = rectangleOptions;
} | conditional_block |
selections.js | /* globals google: true */
import Ember from 'ember';
const { later } = Ember.run;
const { on, computed, isArray } = Ember;
export default Ember.Mixin.create({
// Stores reference to google DrawingManager instance
_drawingManager: null,
/**
* [selectionsDelay time it takes to remove last selection from th... | this.sendAction('selectionsCircle', {
circle,
radius: circle.getRadius(),
lat: circle.center.lat(),
lng: circle.center.lng()
});
},
selectionsRectangle: function(rectangle) {
const ne = rectangle.bounds.getNorthEast();
const sw = rectangle.bounds.getSouth... |
selectionsCircle: function(circle) { | random_line_split |
test_templates.py | """Test template specific functionality.
Make sure tables expose their functionality to templates right. This
generally about testing "out"-functionality of the tables, whether
via templates or otherwise. Whether a test belongs here or, say, in
``test_basic``, is not always a clear-cut decision.
"""
from django.temp... | Table):
name = tables.TextColumn()
capital = tables.TextColumn()
population = tables.NumberColumn(verbose_name="Population Size")
currency = tables.NumberColumn(visible=False, inaccessible=True)
tld = tables.TextColumn(visible=False, verbose_name="Domain")
calling_code = ... | able(tables. | identifier_name |
test_templates.py | """Test template specific functionality.
Make sure tables expose their functionality to templates right. This
generally about testing "out"-functionality of the tables, whether
via templates or otherwise. Whether a test belongs here or, say, in
``test_basic``, is not always a clear-cut decision.
"""
from django.temp... | certain data is available on columns
assert countries.columns['currency'].sortable == True
assert countries.columns['capital'].sortable == False
assert countries.columns['name'].visible == True
assert countries.columns['tld'].visible == False
def test_render():
"""For good measure, render some actu... | '], row['cc'], row['population']
# | conditional_block |
test_templates.py | """Test template specific functionality.
Make sure tables expose their functionality to templates right. This
generally about testing "out"-functionality of the tables, whether
via templates or otherwise. Whether a test belongs here or, say, in
``test_basic``, is not always a clear-cut decision.
"""
from django.temp... | "Germany Berlin 83 49 France None 64 33 Netherlands Amsterdam None 31 Austria None 8 43 "
print Template("{% for row in countries %}{% if countries.columns.name.visible %}{{ row.name }} {% endif %}{% if countries.columns.tld.visible %}{{ row.tld }} {% endif %}{% endfor %}").\
render(Context({'count... |
assert Template("{% for row in countries %}{% for value in row %}{{ value }} {% endfor %}{% endfor %}").\
render(Context({'countries': countries})) == \ | random_line_split |
test_templates.py | """Test template specific functionality.
Make sure tables expose their functionality to templates right. This
generally about testing "out"-functionality of the tables, whether
via templates or otherwise. Whether a test belongs here or, say, in
``test_basic``, is not always a clear-cut decision.
"""
from django.temp... | books = BookTable([
{'id': 1, 'name': 'Foo: Bar'},
])
# cast to a string we get a value ready to be passed to the querystring
books.order_by = ('name',)
assert str(books.order_by) == 'name'
books.order_by = ('name', '-id')
assert str(books.order_by) == 'name,-id'
def test_columns_an... | = tables.Column()
name = tables.Column()
| identifier_body |
serializer.test.tsx | import * as React from 'react'
import { shallow, mount } from 'enzyme'
import { Editor, EditorState, convertFromRaw } from 'draft-js'
import { Serlizer } from './serializer'
import { getContentState } from './testUtils'
describe('Editor Serilizer', () => {
it('serialize ContentState should get RawContentState', () =... | expect(editor.text()).toEqual(text)
})
}) | onChange={ () => { } }
editorState={ EditorState.createWithContent(c) }>
</Editor >
) | random_line_split |
protoc.py | # Copyright (c) 2009 Scott Stafford
# Copyright 2014 The Ostrich / by Itamar O
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the right... |
if env['PROTOPYOUT']:
target.append('%s_pb2.py' % (proto))
return target, source
def protoc_scanner(node, env, _):
"""Return list of file nodes that `node` imports"""
contents = node.get_text_contents()
# If build location different from sources location,
# get the destination... | target.append('%s.pb.cc' % (proto))
target.append('%s.pb.h' % (proto)) | conditional_block |
protoc.py | # Copyright (c) 2009 Scott Stafford
# Copyright 2014 The Ostrich / by Itamar O
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the right... |
def protoc_scanner(node, env, _):
"""Return list of file nodes that `node` imports"""
contents = node.get_text_contents()
# If build location different from sources location,
# get the destination base dir as the base for imports.
nodepath = str(node.path)
srcnodepath = str(node.srcnode())
... | """Return list of targets generated by Protoc builder for source."""
for src in source:
proto = os.path.splitext(str(src))[0]
if env['PROTOCPPOUT']:
target.append('%s.pb.cc' % (proto))
target.append('%s.pb.h' % (proto))
if env['PROTOPYOUT']:
target.append(... | identifier_body |
protoc.py | # Copyright (c) 2009 Scott Stafford
# Copyright 2014 The Ostrich / by Itamar O
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the right... | env['PROTOPATH'] = ['.']
# Default CPP output in same dir
env['PROTOCPPOUT'] = '.'
# No default Python output
env['PROTOPYOUT'] = ''
proto_cmd = ['$PROTOC']
proto_cmd.append('${["--proto_path=%s"%(x) for x in PROTOPATH]}')
proto_cmd.append('$PROTOCFLAGS')
proto_cmd... | env['PROTOCFLAGS'] = SCons.Util.CLVar('')
env['PROTOCSRCSUFFIX'] = _PROTOSUFFIX
# Default proto search path is same dir | random_line_split |
protoc.py | # Copyright (c) 2009 Scott Stafford
# Copyright 2014 The Ostrich / by Itamar O
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the right... | (node, env, _):
"""Return list of file nodes that `node` imports"""
contents = node.get_text_contents()
# If build location different from sources location,
# get the destination base dir as the base for imports.
nodepath = str(node.path)
srcnodepath = str(node.srcnode())
src_pos = nodepath... | protoc_scanner | identifier_name |
pinger.py | import asyncio
import functools
import logging
from aiohttp import request
from .packet import ControlPacket
PING_TIMEOUT = 10
PING_INTERVAL = 5
class Pinger:
"""
Pinger to send ping packets to an endpoint and inform if the timeout has occurred
"""
def __init__(self, handler, interval, timeout, lo... | (self, payload=None):
try:
res = yield from request('get', self._url)
if res.status == 200:
self.pong_received(payload=payload)
res.close()
except Exception:
self.logger.exception('Error while ping')
def stop(self):
self._p... | ping_coroutine | identifier_name |
pinger.py | import asyncio
import functools
import logging
from aiohttp import request
from .packet import ControlPacket
PING_TIMEOUT = 10
PING_INTERVAL = 5
class Pinger:
"""
Pinger to send ping packets to an endpoint and inform if the timeout has occurred
"""
def __init__(self, handler, interval, timeout, lo... |
class HTTPPinger:
def __init__(self, host, port, node_id, handler):
self._host = host
self._port = port
self._pinger = Pinger(self, PING_INTERVAL, PING_TIMEOUT)
self._node_id = node_id
self._handler = handler
self._url = 'http://{}:{}/ping'.format(host, port)
... | logger = logging.getLogger(__name__)
def __init__(self, host, port, node_id, protocol, handler):
self._host = host
self._port = port
self._pinger = Pinger(self, PING_INTERVAL, PING_TIMEOUT)
self._node_id = node_id
self._protocol = protocol
self._handler = handler
... | identifier_body |
pinger.py | import asyncio
import functools
import logging
from aiohttp import request
from .packet import ControlPacket
PING_TIMEOUT = 10
PING_INTERVAL = 5
class Pinger:
"""
Pinger to send ping packets to an endpoint and inform if the timeout has occurred
"""
def __init__(self, handler, interval, timeout, lo... |
except Exception:
self.logger.exception('Error while ping')
def stop(self):
self._pinger.stop()
def on_timeout(self):
self.logger.warn('%s timed out', self._node_id)
self._handler.on_timeout(self._host, self._port, self._node_id)
def pong_received(self, payloa... | self.pong_received(payload=payload)
res.close() | conditional_block |
pinger.py | import asyncio
import functools
import logging
from aiohttp import request
from .packet import ControlPacket
PING_TIMEOUT = 10
PING_INTERVAL = 5
class Pinger:
"""
Pinger to send ping packets to an endpoint and inform if the timeout has occurred
"""
def __init__(self, handler, interval, timeout, lo... |
def stop(self):
self._pinger.stop()
def on_timeout(self):
self.logger.warn('%s timed out', self._node_id)
self._handler.on_timeout(self._host, self._port, self._node_id)
def pong_received(self, payload=None):
self._pinger.pong_received(payload=payload) | except Exception:
self.logger.exception('Error while ping') | random_line_split |
lib.rs | pub mod car;
use car::car_factory::CarFactory;
use car::car_type::{Body, Colour};
use car::Car;
pub struct | {
cars: Vec<Car>,
car_factory: CarFactory,
}
impl Parking {
pub fn new() -> Parking {
Parking {
cars: Vec::new(),
car_factory: CarFactory::new(),
}
}
pub fn add_car(
&mut self,
license_plate: &str,
parking_place_number: u8,
b... | Parking | identifier_name |
lib.rs | pub mod car;
use car::car_factory::CarFactory;
use car::car_type::{Body, Colour};
use car::Car;
pub struct Parking {
cars: Vec<Car>,
car_factory: CarFactory,
}
impl Parking {
pub fn new() -> Parking {
Parking {
cars: Vec::new(),
car_factory: CarFactory::new(),
}
... | ) {
self.cars.push(Car::new(
license_plate.to_string(),
parking_place_number,
self.car_factory.get_car_type_id(body, colour),
));
}
pub fn print(&mut self) {
for car in &self.cars {
car.print(self.car_factory.get_car_type(car.car_type_... | license_plate: &str,
parking_place_number: u8,
body: Body,
colour: Colour, | random_line_split |
lib.rs | pub mod car;
use car::car_factory::CarFactory;
use car::car_type::{Body, Colour};
use car::Car;
pub struct Parking {
cars: Vec<Car>,
car_factory: CarFactory,
}
impl Parking {
pub fn new() -> Parking {
Parking {
cars: Vec::new(),
car_factory: CarFactory::new(),
}
... |
}
| {
for car in &self.cars {
car.print(self.car_factory.get_car_type(car.car_type_id).unwrap());
}
println!("\nNumber of cars: {}", self.cars.len());
self.car_factory.print();
} | identifier_body |
index.d.ts | // Type definitions for knex-cleaner 1.3
// Project: https://github.com/steven-ferguson/knex-cleaner
// Definitions by: Karol Goraus <https://github.com/Szarlus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped | * Choose between simply deleting all rows from table or truncating it completely. Default is 'truncate'
*/
mode?: 'truncate' | 'delete' | undefined;
/**
* Used to tell PostgresSQL to reset the ID counter, default is true
*/
restartIdentity?: boolean | undefined;
/**
* List of ... | // TypeScript Version: 4.1
import { Knex } from 'knex';
export interface KnexCleanerOptions {
/** | random_line_split |
glcommon.rs | use core::prelude::*;
use opengles::gl2;
use opengles::gl2::{GLuint, GLint};
use core::borrow::{Cow, IntoCow};
use collections::string::String;
pub type GLResult<T> = Result<T, MString>;
pub type MString = Cow<'static, String, str>;
fn get_gl_error_name(error: u32) -> &'static str {
match error {
gl2::NO_... | gl2::glVertexAttribPointer($handle, $count, gl2::FLOAT, false as ::opengles::gl2::GLboolean,
mem::size_of_val(firstref) as i32,
// XXX this actually derefences firstref and is completely unsafe
// is there better way to do offsetof in rust? there ought to be
... | random_line_split | |
glcommon.rs | use core::prelude::*;
use opengles::gl2;
use opengles::gl2::{GLuint, GLint};
use core::borrow::{Cow, IntoCow};
use collections::string::String;
pub type GLResult<T> = Result<T, MString>;
pub type MString = Cow<'static, String, str>;
fn get_gl_error_name(error: u32) -> &'static str {
match error {
gl2::NO_... | <Init> {
pub val: Init
}
pub trait FillDefaults<Init> {
type Unfilled;
fn fill_defaults(unfilled: <Self as FillDefaults<Init>>::Unfilled) -> Defaults<Init>;
}
pub trait UsingDefaults<Init> {
type Defaults;
//fn fill_defaults(Init) -> <Self as UsingDefaults<Init>>::Defaults;
fn maybe_init(Init)... | Defaults | identifier_name |
glcommon.rs | use core::prelude::*;
use opengles::gl2;
use opengles::gl2::{GLuint, GLint};
use core::borrow::{Cow, IntoCow};
use collections::string::String;
pub type GLResult<T> = Result<T, MString>;
pub type MString = Cow<'static, String, str>;
fn get_gl_error_name(error: u32) -> &'static str {
match error {
gl2::NO_... |
pub fn load_shader(shader_type: gl2::GLenum, source: &str) -> GLResult<GLuint> {
let shader = gl2::create_shader(shader_type);
if shader != 0 {
gl2::shader_source(shader, [source.as_bytes()].as_slice());
gl2::compile_shader(shader);
let compiled = gl2::get_shader_iv(shader, gl2::COMPIL... | {
let (err, result) = match gl2::check_framebuffer_status(gl2::FRAMEBUFFER) {
gl2::FRAMEBUFFER_COMPLETE => ("FRAMEBUFFER_COMPLETE", true),
gl2::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => ("FRAMEBUFFER_INCOMPLETE_ATTACHMENT", false),
gl2::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => ("FRAMEBUFFER_I... | identifier_body |
session.rs | use alloc::boxed::Box;
use collections::string::{String, ToString};
use collections::vec::Vec;
use scheduler;
use schemes::KScheme;
use schemes::{Resource, Url, VecResource};
/// A session
pub struct Session {
/// The scheme items
pub items: Vec<Box<KScheme>>,
}
impl Session {
/// Create new session
... | (&mut self, irq: u8) {
let reenable = scheduler::start_no_ints();
for mut item in self.items.iter_mut() {
item.on_irq(irq);
}
scheduler::end_no_ints(reenable);
}
pub unsafe fn on_poll(&mut self) {
let reenable = scheduler::start_no_ints();
for mut ite... | on_irq | identifier_name |
session.rs | use alloc::boxed::Box;
use collections::string::{String, ToString};
use collections::vec::Vec;
use scheduler;
use schemes::KScheme;
use schemes::{Resource, Url, VecResource};
/// A session
pub struct Session {
/// The scheme items
pub items: Vec<Box<KScheme>>,
}
impl Session {
/// Create new session | pub fn new() -> Box<Self> {
box Session {
items: Vec::new(),
}
}
pub unsafe fn on_irq(&mut self, irq: u8) {
let reenable = scheduler::start_no_ints();
for mut item in self.items.iter_mut() {
item.on_irq(irq);
}
scheduler::end_no_ints(r... | random_line_split | |
session.rs | use alloc::boxed::Box;
use collections::string::{String, ToString};
use collections::vec::Vec;
use scheduler;
use schemes::KScheme;
use schemes::{Resource, Url, VecResource};
/// A session
pub struct Session {
/// The scheme items
pub items: Vec<Box<KScheme>>,
}
impl Session {
/// Create new session
... |
}
| {
if url.scheme().len() == 0 {
let mut list = String::new();
for item in self.items.iter() {
let scheme = item.scheme();
if !scheme.is_empty() {
if !list.is_empty() {
list = list + "\n" + scheme;
... | identifier_body |
session.rs | use alloc::boxed::Box;
use collections::string::{String, ToString};
use collections::vec::Vec;
use scheduler;
use schemes::KScheme;
use schemes::{Resource, Url, VecResource};
/// A session
pub struct Session {
/// The scheme items
pub items: Vec<Box<KScheme>>,
}
impl Session {
/// Create new session
... | else {
for mut item in self.items.iter_mut() {
if item.scheme() == url.scheme() {
return item.open(url, flags);
}
}
None
}
}
}
| {
let mut list = String::new();
for item in self.items.iter() {
let scheme = item.scheme();
if !scheme.is_empty() {
if !list.is_empty() {
list = list + "\n" + scheme;
} else {
... | conditional_block |
issue-9446.rs | // Copyright 2013 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 ... | (String);
impl Wrapper {
pub fn new(wrapped: String) -> Wrapper {
Wrapper(wrapped)
}
pub fn say_hi(&self) {
let Wrapper(ref s) = *self;
println!("hello {}", *s);
}
}
impl Drop for Wrapper {
fn drop(&mut self) {}
}
pub fn main() {
{
// This runs without complai... | Wrapper | identifier_name |
issue-9446.rs | // Copyright 2013 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 ... | impl Drop for Wrapper {
fn drop(&mut self) {}
}
pub fn main() {
{
// This runs without complaint.
let x = Wrapper::new("Bob".to_string());
x.say_hi();
}
{
// This fails to compile, circa 0.8-89-gc635fba.
// error: internal compiler error: drop_ty_immediate: non-b... | let Wrapper(ref s) = *self;
println!("hello {}", *s);
}
}
| random_line_split |
issue-9446.rs | // Copyright 2013 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 ... |
}
pub fn main() {
{
// This runs without complaint.
let x = Wrapper::new("Bob".to_string());
x.say_hi();
}
{
// This fails to compile, circa 0.8-89-gc635fba.
// error: internal compiler error: drop_ty_immediate: non-box ty
Wrapper::new("Bob".to_string()).say... | {} | identifier_body |
dragAction.ts | import { GraphType, rootNodeId } from '../../Graph'
import { cutGraph, dropGraph } from '../../Graph/helper/GraphHelper'
import { uimap } from '../../Graph/helper/uimap'
import { DragStartType } from '../types'
import { ActionContextType } from '../../context.type'
import * as check from 'check-types'
const dragp = [ ... |
drag.uigraph = uimap ( drag.dgraph )
state.set ( dragp, drag )
} | , drag.nodeId
)
drag.rgraph = dropGraph ( graph, drag.nodeId )
} | random_line_split |
dragAction.ts | import { GraphType, rootNodeId } from '../../Graph'
import { cutGraph, dropGraph } from '../../Graph/helper/GraphHelper'
import { uimap } from '../../Graph/helper/uimap'
import { DragStartType } from '../types'
import { ActionContextType } from '../../context.type'
import * as check from 'check-types'
const dragp = [ ... |
else {
let graph = state.get ( [ drag.ownerType, 'graph' ] )
const otype = drag.ownerType === 'project' ? 'scene' : 'project'
drag.dgraph = cutGraph
( graph
, drag.nodeId
)
drag.rgraph = dropGraph ( graph, drag.nodeId )
}
drag.uigraph = uimap ( drag.dgraph )
state.set ( dragp, dr... | {
drag.dgraph = state.get ( [ 'data', 'component', drag.componentId, 'graph' ] )
console.log ( state.get ( [ 'data', 'component', drag.componentId ] ) )
} | conditional_block |
app.ts | /// <reference path="../typings/_custom.d.ts" />
/*
* TODO: use the real App component
* change `app-simple.js` to `app.js` in src/public/index.html
*/
/*
* Angular 2 decorators and servces
*/
import {Directive, Component, View} from 'angular2/angular2';
import {RouteConfig, Router} from 'angular2/router';
impor... | () {
// npm install express connect-history-api-fallback morgan body-parser
// npm run express
this.http.
get('/api/todos', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).
toRx().
map(res => res.json()).
su... | getData | identifier_name |
app.ts | /// <reference path="../typings/_custom.d.ts" />
/*
* TODO: use the real App component
* change `app-simple.js` to `app.js` in src/public/index.html
*/
/*
* Angular 2 decorators and servces
*/
import {Directive, Component, View} from 'angular2/angular2';
import {RouteConfig, Router} from 'angular2/router';
impor... |
}
}
| {
console.info(`${'\n'
} // You must run these commands for the Http API to work ${'\n'
} npm install express connect-history-api-fallback morgan body-parser ${'\n'
} npm run express
`);
}//end err.message | conditional_block |
app.ts | /// <reference path="../typings/_custom.d.ts" />
/*
* TODO: use the real App component
* change `app-simple.js` to `app.js` in src/public/index.html
*/
/*
* Angular 2 decorators and servces
*/
import {Directive, Component, View} from 'angular2/angular2';
import {RouteConfig, Router} from 'angular2/router';
impor... | } | } | random_line_split |
app.ts | /// <reference path="../typings/_custom.d.ts" />
/*
* TODO: use the real App component
* change `app-simple.js` to `app.js` in src/public/index.html
*/
/*
* Angular 2 decorators and servces
*/
import {Directive, Component, View} from 'angular2/angular2';
import {RouteConfig, Router} from 'angular2/router';
impor... |
getData() {
// npm install express connect-history-api-fallback morgan body-parser
// npm run express
this.http.
get('/api/todos', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).
toRx().
map(res => res.json())... | {
this.name = 'Angular 2';
this.getData();
} | identifier_body |
jsonmaking.py | import json, random, time, sys
"""
Creating a random JSON object based on lists of info and random numbers
to assign the index
"""
##Directory
input_file = "test.json"
###Success message takes the file_name and operation type (ie. written, closed)
def process_message(outcome, file_name, operation_type):
print "**... | (n):
range_start = 10**(n-1)
range_end = (10**n)-1
return random.randint(range_start, range_end)
##combines a group of random numbers to resemble a phone number
def random_phone_number():
return "%s-%s-%s" %(str(random_number_maker(3)), str(random_number_maker(3)), str(random_number_maker(4)))
##call... | random_number_maker | identifier_name |
jsonmaking.py | import json, random, time, sys
"""
Creating a random JSON object based on lists of info and random numbers
to assign the index
"""
##Directory
input_file = "test.json"
###Success message takes the file_name and operation type (ie. written, closed)
def process_message(outcome, file_name, operation_type):
print "**... |
##Lists of info
doctors_name=["Dr_K", "Dr. Pepper", "Dr. Lector", "Dr. Seus", "Dr Dre", "Dr. Phill", "Dr. Glass"]
special_notes_list=["No more doctors available for the weekend", "All offices closed for Labor Day", "Offices closed till Monday for Christmas",
"No Dr. on call Saturdays", "No Dr. ... | return random.randrange(start,end) | identifier_body |
jsonmaking.py | import json, random, time, sys
"""
Creating a random JSON object based on lists of info and random numbers
to assign the index
"""
##Directory
input_file = "test.json"
###Success message takes the file_name and operation type (ie. written, closed)
def process_message(outcome, file_name, operation_type):
print "**... | print "Error opening "+input_file
##Random chooser-random number picker function to be used over and over, but needs to be created before called
##To keep everything clean it's listed before the others funtions so that they maybe listed in order of the dictionary keys
def random_chooser(start,end):
return ran... | random_line_split | |
jsonmaking.py | import json, random, time, sys
"""
Creating a random JSON object based on lists of info and random numbers
to assign the index
"""
##Directory
input_file = "test.json"
###Success message takes the file_name and operation type (ie. written, closed)
def process_message(outcome, file_name, operation_type):
print "**... |
print "\r"
##Write file
try:
open_file.write(jasoner)
process_message("SUCCESS", input_file, "Written")
except:
process_message("FAILURE" , input_file, "Not Written")
##Close file
try:
open_file.close()
process_message("SUCCESS", input_file, "Closed")
except:
process_message("FAILURE" , input... | print "\r", str(i)+"%"
time.sleep(.025) | conditional_block |
PanoramaPreview.test.tsx | import { rest } from 'msw'
import { render, screen, waitFor } from '@testing-library/react'
import PanoramaPreview from './PanoramaPreview'
import joinUrl from '../../../../shared/utils/joinUrl'
import environment from '../../../../environment'
import { server } from '../../../../../test/server'
import { mapLayersParam... | expect(params.get('someOtherParam')).toContain('1')
expect(params.get(mapLayersParam.name)).toContain('random-layer')
expect(params.get(panoPitchParam.name)).toContain('0')
expect(params.get(panoHeadingParam.name)).toContain('131')
})
})
it('should render PanoAlert when API responses wi... | random_line_split | |
grad_modifiers.py | from __future__ import absolute_import
import numpy as np
from keras import backend as K
from .utils import utils
def negate(grads):
"""Negates the gradients.
Args:
grads: A numpy array of grads to use.
Returns:
The negated gradients.
"""
return -grads
def absolute(grads):
... | The modified gradients that highlight small values.
"""
return absolute(invert(grads))
def get(identifier):
return utils.get_identifier(identifier, globals(), __name__) | random_line_split | |
grad_modifiers.py | from __future__ import absolute_import
import numpy as np
from keras import backend as K
from .utils import utils
def negate(grads):
"""Negates the gradients.
Args:
grads: A numpy array of grads to use.
Returns:
The negated gradients.
"""
return -grads
def absolute(grads):
... | (identifier):
return utils.get_identifier(identifier, globals(), __name__)
| get | identifier_name |
grad_modifiers.py | from __future__ import absolute_import
import numpy as np
from keras import backend as K
from .utils import utils
def negate(grads):
"""Negates the gradients.
Args:
grads: A numpy array of grads to use.
Returns:
The negated gradients.
"""
return -grads
def absolute(grads):
... | return utils.get_identifier(identifier, globals(), __name__) | identifier_body | |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
moduleId: module.id,
selector... | (
private heroSearchService: HeroSearchService,
private router: Router
) { }
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300... | constructor | identifier_name |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
moduleId: module.id,
selector... | }
} | this.router.navigate(link); | random_line_split |
lights.py |
import logging
import requests
HUE_IP = '192.168.86.32'
HUE_USERNAME = '7KcxItfntdF0DuWV9t0GPMeToEBlvHTgqWNZqxu6'
logger = logging.getLogger('hue')
def getLights():
url = 'http://{0}/api/{1}/lights'.format(HUE_IP, HUE_USERNAME)
try:
r = requests.get(url)
except:
logger.error('Failed getting stat... |
def getStatus(id):
url = 'http://{0}/api/{1}/lights/{2}'.format(HUE_IP, HUE_USERNAME, id)
try:
r = requests.get(url)
except:
logger.error('Failed getting status for light {0}'.format (id))
return
if r.status_code == 200:
data = r.json()
return data
| data = r.json()
return data | conditional_block |
lights.py | import logging
import requests
HUE_IP = '192.168.86.32'
HUE_USERNAME = '7KcxItfntdF0DuWV9t0GPMeToEBlvHTgqWNZqxu6'
|
url = 'http://{0}/api/{1}/lights'.format(HUE_IP, HUE_USERNAME)
try:
r = requests.get(url)
except:
logger.error('Failed getting status for all lights')
return
if r.status_code == 200:
data = r.json()
return data
def getStatus(id):
url = 'http://{0}/api/{1}/lights/{2}'.format(HUE... | logger = logging.getLogger('hue')
def getLights(): | random_line_split |
lights.py |
import logging
import requests
HUE_IP = '192.168.86.32'
HUE_USERNAME = '7KcxItfntdF0DuWV9t0GPMeToEBlvHTgqWNZqxu6'
logger = logging.getLogger('hue')
def getLights():
url = 'http://{0}/api/{1}/lights'.format(HUE_IP, HUE_USERNAME)
try:
r = requests.get(url)
except:
logger.error('Failed getting stat... | (id):
url = 'http://{0}/api/{1}/lights/{2}'.format(HUE_IP, HUE_USERNAME, id)
try:
r = requests.get(url)
except:
logger.error('Failed getting status for light {0}'.format (id))
return
if r.status_code == 200:
data = r.json()
return data
| getStatus | identifier_name |
lights.py |
import logging
import requests
HUE_IP = '192.168.86.32'
HUE_USERNAME = '7KcxItfntdF0DuWV9t0GPMeToEBlvHTgqWNZqxu6'
logger = logging.getLogger('hue')
def getLights():
|
def getStatus(id):
url = 'http://{0}/api/{1}/lights/{2}'.format(HUE_IP, HUE_USERNAME, id)
try:
r = requests.get(url)
except:
logger.error('Failed getting status for light {0}'.format (id))
return
if r.status_code == 200:
data = r.json()
return data
| url = 'http://{0}/api/{1}/lights'.format(HUE_IP, HUE_USERNAME)
try:
r = requests.get(url)
except:
logger.error('Failed getting status for all lights')
return
if r.status_code == 200:
data = r.json()
return data | identifier_body |
SetContainsAllCodec.ts | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required ... | (clientMessage: ClientMessage): boolean {
const initialFrame = clientMessage.nextFrame();
return FixSizedTypesCodec.decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_OFFSET);
}
}
| decodeResponse | identifier_name |
SetContainsAllCodec.ts | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable max-len */
import {BitsUtil} from '../util/BitsUtil';
import {FixSizedTypesCodec} from './builtin/FixSizedTypesCodec... | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
output_disposition.py | '''
Created on Sep 14, 2013
@author: paepcke
Modifications:
- Jan 1, 2013: added remove() method to OutputFile
'''
import StringIO
from collections import OrderedDict
import csv
import re
import sys
import os
import tempfile
from col_data_type import ColDataType
class OutputDisposition(object):
'''
Sp... | (self):
pass # don't close stdout
def flush(self):
sys.stdout.flush()
def __str__(self):
return "<OutputPipe:<stdout>"
def writerow(self, colElementArray, tableName=None):
# For CSV: make sure everything is a string:
if self.outputFormat == OutputDispositio... | close | identifier_name |
output_disposition.py | '''
Created on Sep 14, 2013
@author: paepcke
Modifications:
- Jan 1, 2013: added remove() method to OutputFile
'''
import StringIO
from collections import OrderedDict
import csv
import re
import sys
import os
import tempfile
from col_data_type import ColDataType
class OutputDisposition(object):
'''
Sp... | '''
Housekeeping class. Each instance represents the name,
position, and datatype of one column. These instances are
used to generate column name headers, and
SQL insert statements.
'''
def __init__(self, colName, colDataType, jsonToRelationProcessor):
'''
Create a ColumnSpe... |
class ColumnSpec(object): | random_line_split |
output_disposition.py | '''
Created on Sep 14, 2013
@author: paepcke
Modifications:
- Jan 1, 2013: added remove() method to OutputFile
'''
import StringIO
from collections import OrderedDict
import csv
import re
import sys
import os
import tempfile
from col_data_type import ColDataType
class OutputDisposition(object):
'''
Sp... |
# Return False to indicate that if the conversion
# threw an error, the exception should now be re-raised.
# If the conversion worked fine, then this return value
# is ignored.
return False
def flush(self):
self.outputDest.flush()
def getOutputFormat(self):
... | raise IOError("Could not close the output of the conversion: %s" % sys.exc_info()[0]) | conditional_block |
output_disposition.py | '''
Created on Sep 14, 2013
@author: paepcke
Modifications:
- Jan 1, 2013: added remove() method to OutputFile
'''
import StringIO
from collections import OrderedDict
import csv
import re
import sys
import os
import tempfile
from col_data_type import ColDataType
class OutputDisposition(object):
'''
Sp... |
def getSchemaHint(self, colName, tableName):
'''
Given a column name, and a table name, return the ColumnSpec object
that describes that column. If tableName is None, the main (default)
table's schema will be searched for a colName entry
:param colName: name of column whos... | '''
Provide a schema hint dict for the table of the given name.
:param tableName: name of table to which schema applies. The name may be None, in which case it refers to the main (default) table.
:type tableName: String
:param schemaHints: dict mapping column names to SQL types via Colu... | identifier_body |
test-examples.js | const path = require('path')
const execa = require('execa')
const logger = require('./lib/logger')
const { exampleAppsToRun } = require('./lib/paths')
const { createBundle } = require('./lib/bundle')
const bundle = createBundle()
const executeTest = (projectPath) => {
// we change current directory
process.chdi... |
// then we install it in the repo
logger.log('ensuring all dependencies of target project are installed')
logger.log()
execa.sync('npm', ['ci'], { cwd: projectPath })
logger.log()
logger.log('installing bundled version of ts-jest')
logger.log()
execa.sync('npm', ['install', '--no-package-lock', '--n... | random_line_split | |
htmlhrelement.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 crate::dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use crate::dom::b... | }
impl HTMLHRElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> HTMLHRElement {
HTMLHRElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
... | pub struct HTMLHRElement {
htmlelement: HTMLElement, | random_line_split |
htmlhrelement.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 crate::dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use crate::dom::b... | (&self) -> LengthOrPercentageOrAuto {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("width"))
.map(AttrValue::as_dimension)
.cloned()
.unwrap_or(LengthOrPercentageOrAuto::Auto)
}
... | get_width | identifier_name |
BreakfastDiningRounded.js | import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M18 3H6C3.79 3 2 4.79 2 7c0 1.48.81 2.75 2 3.45V19c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-8.55c1.19-.69 2-1.97 2-3.45 0-2.21-1.79-4-4-4zm-2.29 10.7-3 3c-.39.39-1.... | }), 'BreakfastDiningRounded'); | random_line_split | |
query-result-stores.js | /* eslint-disable no-await-in-loop */
const assert = require('assert');
const TestUtils = require('../utils');
const query1 = `SELECT 1 AS id, 'blue' AS color`;
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function testBatchToCompletion(config) {
const utils = new TestUti... |
return testBatchToCompletion({
queryResultStore: 'redis',
redisUri: 'redis://localhost:6379',
});
});
it('database', async function () {
return testBatchToCompletion({
queryResultStore: 'database',
});
});
it('memory', async function () {
return testBatchToCompletion({
... | {
return this.skip();
} | conditional_block |
query-result-stores.js | /* eslint-disable no-await-in-loop */
const assert = require('assert');
const TestUtils = require('../utils');
const query1 = `SELECT 1 AS id, 'blue' AS color`;
function wait(ms) |
async function testBatchToCompletion(config) {
const utils = new TestUtils(config);
await utils.init(true);
const connection = await utils.post('admin', '/api/connections', {
name: 'test connection',
driver: 'sqlite',
data: {
filename: './test/fixtures/sales.sqlite',
},
});
let batch... | {
return new Promise((resolve) => setTimeout(resolve, ms));
} | identifier_body |
query-result-stores.js | /* eslint-disable no-await-in-loop */
const assert = require('assert');
const TestUtils = require('../utils'); |
const query1 = `SELECT 1 AS id, 'blue' AS color`;
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function testBatchToCompletion(config) {
const utils = new TestUtils(config);
await utils.init(true);
const connection = await utils.post('admin', '/api/connections', {
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.