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 |
|---|---|---|---|---|
main.rs | #[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate chrono;
extern crate responder;
use std::env::{self, VarError};
use std::io::{self, Write};
use std::net::SocketAddr;
use std::path::Path;
use std::process;
use clap::{App, Arg, Format};
use log::{LogRecord, LogLeve... |
fn run_server(address: Option<&str>, config_file: &Path, reload: bool)
-> Result<(), String>
{
let context = try!(Context::from_config_file(config_file, reload));
let address = address.or(Some(context.address()))
.unwrap_or(DEFAULT_ADDR)
.to_owned();
info!("Starting http server at ht... | {
arg.parse::<SocketAddr>()
.map(|_| ())
.map_err(|_| String::from("invalid adrress"))
} | identifier_body |
main.rs | #[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate chrono;
extern crate responder;
use std::env::{self, VarError};
use std::io::{self, Write};
use std::net::SocketAddr;
use std::path::Path;
use std::process;
use clap::{App, Arg, Format};
use log::{LogRecord, LogLeve... | -> Result<(), String>
{
let context = try!(Context::from_config_file(config_file, reload));
let address = address.or(Some(context.address()))
.unwrap_or(DEFAULT_ADDR)
.to_owned();
info!("Starting http server at http://{}/", &address);
try!(server::run(context, &address));
Ok((... | }
fn run_server(address: Option<&str>, config_file: &Path, reload: bool) | random_line_split |
index.js | 'use strict';
var mongoose = require('mongoose'),
async = require('async');
var DeleteChildrenPlugin = function(schema, options) {
schema.pre('remove', function(done) {
var parentField = options.parentField;
var childModel = options.childModel;
if (!parentField) {
var err = new Error('parentField not def... | });
});
};
exports.parentAttach = ParentAttachPlugin;
exports.deleteChildren = DeleteChildrenPlugin; | console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::exit');
doneRemoving();
| random_line_split |
index.js | 'use strict';
var mongoose = require('mongoose'),
async = require('async');
var DeleteChildrenPlugin = function(schema, options) {
schema.pre('remove', function(done) {
var parentField = options.parentField;
var childModel = options.childModel;
if (!parentField) |
if (!childModel) {
var err = new Error('childModel not defined');
return done(err);
}
// must delete all campuses
console.log('model::', parentField, '>', childModel, '::pre::remove::enter');
var Model = mongoose.model(childModel);
var conditions = {};
conditions[parentField] = this._id;
Model... | {
var err = new Error('parentField not defined');
return done(err);
} | conditional_block |
variance-types.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <A> { //~ ERROR [o]
t: InvariantCell<A>
}
#[rustc_variance]
struct Covariant<A> { //~ ERROR [+]
t: A, u: fn() -> A
}
#[rustc_variance]
struct Contravariant<A> { //~ ERROR [-]
t: fn(A)
}
#[rustc_variance]
enum Enum<A,B,C> { //~ ERROR [+, -, o]
Foo(Covariant<A>),
Bar(Contravariant<B>),
Zed(Cova... | InvariantIndirect | identifier_name |
variance-types.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)... | // | random_line_split |
protocolClient.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | request.arguments = args;
}
// store callback for this request
this.pendingRequests[request.seq] = clb;
var json = JSON.stringify(request);
var length = Buffer.byteLength(json, 'utf8');
this.outputStream.write('Content-Length: ' + length.toString() + ProtocolClient.TWO_CRLF, 'utf8');
this.outputStre... | random_line_split | |
protocolClient.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
super();
this.sequence = 1;
this.contentLength = -1;
this.pendingRequests = {};
this.rawData = new Buffer(0);
}
protected connect(readable: stream.Readable, writable: stream.Writable): void {
this.outputStream = writable;
readable.on('data', (data: Buffer) => {
this.rawData = Buffer.concat([t... | constructor | identifier_name |
protocolClient.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
} | {
var rawData = JSON.parse(body);
if (typeof rawData.event !== 'undefined') {
var event = <DebugProtocol.Event> rawData;
this.emit(event.event, event);
} else {
var response = <DebugProtocol.Response> rawData;
var clb = this.pendingRequests[response.request_seq];
if (clb) {
delete this.pending... | identifier_body |
protocolClient.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
// store callback for this request
this.pendingRequests[request.seq] = clb;
var json = JSON.stringify(request);
var length = Buffer.byteLength(json, 'utf8');
this.outputStream.write('Content-Length: ' + length.toString() + ProtocolClient.TWO_CRLF, 'utf8');
this.outputStream.write(json, 'utf8');
}
pri... | {
request.arguments = args;
} | conditional_block |
popstateevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::PopStateEv... | {
event: Event,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
state: MutHeapJSVal,
}
impl PopStateEvent {
fn new_inherited() -> PopStateEvent {
PopStateEvent {
event: Event::new_inherited(),
state: MutHeapJSVal::new(),
}
}
pub fn new_uninitialized(wi... | PopStateEvent | identifier_name |
popstateevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::PopStateEv... |
}
impl PopStateEventMethods for PopStateEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-popstateevent-state
unsafe fn State(&self, _cx: *mut JSContext) -> JSVal {
self.state.get()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) ->... | {
Ok(PopStateEvent::new(window,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
unsafe { HandleValue::from_marked_location(&init.state) }))
} | identifier_body |
popstateevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::PopStateEv... |
pub fn new_uninitialized(window: &Window) -> Root<PopStateEvent> {
reflect_dom_object(box PopStateEvent::new_inherited(),
window,
PopStateEventBinding::Wrap)
}
pub fn new(window: &Window,
type_: Atom,
bubbles: bool... | state: MutHeapJSVal::new(),
}
} | random_line_split |
issue-2631-a.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 ... | <T>(req: &header_map) {
let _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow()
.clone()
.get(0)).clone();
}
| request | identifier_name |
issue-2631-a.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 ... | .clone()
.get(0)).clone();
} | let _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow() | random_line_split |
issue-2631-a.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 _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow()
.clone()
.get(0)).clone();
} | identifier_body | |
dir_reg.rs | use std::io::{self, Read, Write};
use std::fmt;
use instruction::parameter::{Direct, Register, RegisterError, InvalidRegister};
use instruction::parameter::{ParamType, ParamTypeOf};
use instruction::parameter::InvalidParamType;
use instruction::mem_size::MemSize;
use instruction::write_to::WriteTo;
use instruction::get... | DirReg::Register(_) => ParamType::Register,
}
}
}
impl WriteTo for DirReg {
fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> {
match *self {
DirReg::Direct(direct) => direct.write_to(writer),
DirReg::Register(register) => register.write_to(write... | impl ParamTypeOf for DirReg {
fn param_type(&self) -> ParamType {
match *self {
DirReg::Direct(_) => ParamType::Direct, | random_line_split |
dir_reg.rs | use std::io::{self, Read, Write};
use std::fmt;
use instruction::parameter::{Direct, Register, RegisterError, InvalidRegister};
use instruction::parameter::{ParamType, ParamTypeOf};
use instruction::parameter::InvalidParamType;
use instruction::mem_size::MemSize;
use instruction::write_to::WriteTo;
use instruction::get... | (&self) -> ParamType {
match *self {
DirReg::Direct(_) => ParamType::Direct,
DirReg::Register(_) => ParamType::Register,
}
}
}
impl WriteTo for DirReg {
fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> {
match *self {
DirReg::Direct(dire... | param_type | identifier_name |
plot_capecod_onlevel.py | """
=====================================
Include On-leveling into Cape Cod
=====================================
This example demonstrates how to incorporate on-leveling into the `CapeCod`
estimator. The on-level approach emulates the approach taken by Friedland in
"Estimating Unpaid Claims Using Basic Techniques" C... | ('olf', cl.ParallelogramOLF(tort_reform, change_col='rate_change', date_col='date', vertical_line=True)),
('dev', cl.Development(n_periods=2)),
('model', cl.CapeCod(trend=0.034))
])
# Define X
X = cl.load_sample('xyz')['Incurred']
# Separately apply on-level factors for premium
sample_weight = cl.Parallel... | 'rate_change': [-0.1067, -.25]
})
# In addition to development, include onlevel estimator in pipeline for loss
pipe = cl.Pipeline(steps=[ | random_line_split |
test.js | var assert = require("should");
var exec = require('child_process').exec;
var restify = require('restify');
var boplishHost = exec(__dirname + '/../run.js --bootstrap ws://chris.ac:5000 --port 10000',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !... | });
});
});
});
it('should get Host status', function(done) {
restClient.get('/status', function(err, req, res, obj) {
assert.ifError(err);
obj.startDate.should.not.be.empty;
obj.bootstrapNode.should.not.be.empty;
obj.numberOfPeers.should.equal(0);
done();
});
});
it('should request log ... | assert.ifError(err);
obj.should.be.empty;
done();
}); | random_line_split |
test.js | var assert = require("should");
var exec = require('child_process').exec;
var restify = require('restify');
var boplishHost = exec(__dirname + '/../run.js --bootstrap ws://chris.ac:5000 --port 10000',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !... |
});
describe('BOPlish Emulation Host test', function() {
this.timeout(5000);
var restClient;
it('should create client', function() {
restClient = restify.createJsonClient({
url: 'http://localhost:10000',
version: '*'
});
});
var peerId;
it('should start Peer', function(done) {
restClient.post('/pee... | {
console.log('exec error: ' + error);
} | conditional_block |
test_SMBSR.py | import unittest
import mock
import SMBSR
import xs_errors
import XenAPI
import vhdutil
import util
import errno
class FakeSMBSR(SMBSR.SMBSR):
uuid = None
sr_ref = None
mountpoint = None
linkpath = None
path = None
session = None
remoteserver = None
def __init__(self, srcmd, none):
... | def create_smbsr(self, sr_uuid='asr_uuid', server='\\aServer', serverpath = '/aServerpath', username = 'aUsername', password = 'aPassword'):
srcmd = mock.Mock()
srcmd.dconf = {
'server': server,
'serverpath': serverpath,
'username': username,
'password': p... | identifier_body | |
test_SMBSR.py | import unittest
import mock
import SMBSR
import xs_errors
import XenAPI
import vhdutil
import util
import errno
class FakeSMBSR(SMBSR.SMBSR):
uuid = None
sr_ref = None
mountpoint = None
linkpath = None
path = None
session = None
remoteserver = None
def __init__(self, srcmd, none):
... | (unittest.TestCase):
def create_smbsr(self, sr_uuid='asr_uuid', server='\\aServer', serverpath = '/aServerpath', username = 'aUsername', password = 'aPassword'):
srcmd = mock.Mock()
srcmd.dconf = {
'server': server,
'serverpath': serverpath,
'username': username,... | Test_SMBSR | identifier_name |
test_SMBSR.py | import unittest
import mock
import SMBSR
import xs_errors
import XenAPI
import vhdutil
import util
import errno
class FakeSMBSR(SMBSR.SMBSR):
uuid = None
sr_ref = None
mountpoint = None
linkpath = None
path = None
session = None
remoteserver = None
def __init__(self, srcmd, none):
... |
#Attach
@mock.patch('SMBSR.SMBSR.checkmount')
@mock.patch('SMBSR.SMBSR.mount')
def test_attach_smbexception_raises_xenerror(self, mock_mount, mock_checkmount):
smbsr = self.create_smbsr()
mock_mount = mock.Mock(side_effect=SMBSR.SMBException("mount raised SMBException"))
mock_ch... | smbsr.load(sr_uuid)
return smbsr | random_line_split |
core.js | 'use strict';
const Twitter = require('twit'),
q = require('q');
module.exports = {
getDirectMessages,
getMentions
};
/////
function getMentions(config, options) {
return q.ninvoke(new Twitter(config), 'get', '/statuses/mentions_timeline', options).then(data => _formatTweets(data[0]));
}
function getDi... | avatar: object.profile_image_url_https,
screenName: '@' + object.screen_name
};
}
}
function _formatTweets(tweets) {
return tweets.map(tweet => ({
id: tweet.id,
author: _formatTwitterUser(tweet.user || tweet.sender),
rcpt: _formatTwitterUser(tweet.recipient),
date: new Date(tweet.cr... | return {
id: object.id,
displayName: object.name, | random_line_split |
core.js | 'use strict';
const Twitter = require('twit'),
q = require('q');
module.exports = {
getDirectMessages,
getMentions
};
/////
function getMentions(config, options) {
return q.ninvoke(new Twitter(config), 'get', '/statuses/mentions_timeline', options).then(data => _formatTweets(data[0]));
}
function getDi... | (object) {
if (object) {
return {
id: object.id,
displayName: object.name,
avatar: object.profile_image_url_https,
screenName: '@' + object.screen_name
};
}
}
function _formatTweets(tweets) {
return tweets.map(tweet => ({
id: tweet.id,
author: _formatTwitterUser(tweet.user... | _formatTwitterUser | identifier_name |
core.js | 'use strict';
const Twitter = require('twit'),
q = require('q');
module.exports = {
getDirectMessages,
getMentions
};
/////
function getMentions(config, options) {
return q.ninvoke(new Twitter(config), 'get', '/statuses/mentions_timeline', options).then(data => _formatTweets(data[0]));
}
function getDi... |
}
function _formatTweets(tweets) {
return tweets.map(tweet => ({
id: tweet.id,
author: _formatTwitterUser(tweet.user || tweet.sender),
rcpt: _formatTwitterUser(tweet.recipient),
date: new Date(tweet.created_at),
text: tweet.text
}));
}
| {
return {
id: object.id,
displayName: object.name,
avatar: object.profile_image_url_https,
screenName: '@' + object.screen_name
};
} | conditional_block |
core.js | 'use strict';
const Twitter = require('twit'),
q = require('q');
module.exports = {
getDirectMessages,
getMentions
};
/////
function getMentions(config, options) {
return q.ninvoke(new Twitter(config), 'get', '/statuses/mentions_timeline', options).then(data => _formatTweets(data[0]));
}
function getDi... | {
return tweets.map(tweet => ({
id: tweet.id,
author: _formatTwitterUser(tweet.user || tweet.sender),
rcpt: _formatTwitterUser(tweet.recipient),
date: new Date(tweet.created_at),
text: tweet.text
}));
} | identifier_body | |
test_migration_volume_manager_extension_001_add_volumes_table.py | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | @classmethod
def setUpClass(cls):
setup_module()
def test_add_volumes_table(self):
result = db.execute(
sa.select([
self.meta.tables['volume_manager_node_volumes'].c.node_id,
self.meta.tables['volume_manager_node_volumes'].c.volumes]))
rec... |
class TestVolumeManagerExtensionAddVolumesTable(base.BaseAlembicMigrationTest):
| random_line_split |
test_migration_volume_manager_extension_001_add_volumes_table.py | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | result = db.execute(
sa.select([
self.meta.tables['volume_manager_node_volumes'].c.node_id,
self.meta.tables['volume_manager_node_volumes'].c.volumes]))
records = list(result)
node_ids = [r[0] for r in records]
self.assertItemsEqual(node_ids, [1, 2])
... | identifier_body | |
test_migration_volume_manager_extension_001_add_volumes_table.py | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | ():
meta = base.reflect_db_metadata()
# Fill in migration table with data
db.execute(
meta.tables[extensions_migration_buffer_table_name].insert(),
[{'extension_name': 'volume_manager',
'data': jsonutils.dumps({'node_id': 1, 'volumes': [{'volume': 1}]})},
{'extension_name... | prepare | identifier_name |
group_quota.py | import squeakspace.common.util as ut
import squeakspace.common.util_http as ht
import squeakspace.proxy.server.db_sqlite3 as db
import squeakspace.common.squeak_ex as ex
import config
def post_handler(environ):
|
def get_handler(environ):
query = ht.parse_get_request(environ)
cookies = ht.parse_cookies(environ)
user_id = ht.get_required_cookie(cookies, 'user_id')
session_id = ht.get_required_cookie(cookies, 'session_id')
node_name = ht.get_required(query, 'node_name')
group_id = ht.get_required(que... | query = ht.parse_post_request(environ)
cookies = ht.parse_cookies(environ)
user_id = ht.get_required_cookie(cookies, 'user_id')
session_id = ht.get_required_cookie(cookies, 'session_id')
node_name = ht.get_required(query, 'node_name')
group_id = ht.get_required(query, 'group_id')
new_size = ht... | identifier_body |
group_quota.py | import squeakspace.common.util as ut
import squeakspace.common.util_http as ht
import squeakspace.proxy.server.db_sqlite3 as db
import squeakspace.common.squeak_ex as ex
import config
def | (environ):
query = ht.parse_post_request(environ)
cookies = ht.parse_cookies(environ)
user_id = ht.get_required_cookie(cookies, 'user_id')
session_id = ht.get_required_cookie(cookies, 'session_id')
node_name = ht.get_required(query, 'node_name')
group_id = ht.get_required(query, 'group_id')
... | post_handler | identifier_name |
group_quota.py | import squeakspace.common.util as ut
import squeakspace.common.util_http as ht
import squeakspace.proxy.server.db_sqlite3 as db
import squeakspace.common.squeak_ex as ex
import config
def post_handler(environ):
query = ht.parse_post_request(environ)
cookies = ht.parse_cookies(environ)
user_id = ht.get_re... | resp = db.read_group_quota(c, user_id, session_id, node_name, group_id, owner_id, passphrase)
raise ht.ok_json({'status' : 'ok', 'resp' : resp})
except ex.SqueakException as e:
raise ht.convert_squeak_exception(e)
finally:
db.close(conn)
def main_handler(environ):
... | c = db.cursor(conn) | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | runfile = glob(join_path(self.stage.path, 'cuda*_linux*'))[0]
chmod = which('chmod')
chmod('+x', runfile)
runfile = which(runfile)
# Note: NVIDIA does not officially support many newer versions of
# compilers. For example, on CentOS 6, you must use GCC 4.4.7 or
# older.... | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | class Cuda(Package):
"""CUDA is a parallel computing platform and programming model invented
by NVIDIA. It enables dramatic increases in computing performance by
harnessing the power of the graphics processing unit (GPU).
Note: This package does not currently install the drivers necessary
to run CU... | from glob import glob
| random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (Package):
"""CUDA is a parallel computing platform and programming model invented
by NVIDIA. It enables dramatic increases in computing performance by
harnessing the power of the graphics processing unit (GPU).
Note: This package does not currently install the drivers necessary
to run CUDA. These ... | Cuda | identifier_name |
mod.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
|
// Modules --------------------------------------------------------------------
pub mod alias;
pub mod ban;
//pub mod debug;
pub mod effect;
pub mod greeting;
pub mod message;
pub mod recording;
pub mod server;
pub mod uploader;
pub mod timed;
pub mod twitch;
// Re-Exports ------------------------------------------... |
// Internal Dependencies ------------------------------------------------------
use ::core::EventQueue;
use ::bot::{Bot, BotConfig}; | random_line_split |
mod.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Internal Dependencies ------------------------------------------------------
use ::core::EventQueue;
use ::bot::{Bot, BotConfig};
// Modules --------------------------------------------------------------------
pub mod a... | (&self) -> bool {
true
}
fn run(&mut self, &mut Bot, &BotConfig, &mut EventQueue) -> ActionGroup;
}
| ready | identifier_name |
mod.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Internal Dependencies ------------------------------------------------------
use ::core::EventQueue;
use ::bot::{Bot, BotConfig};
// Modules --------------------------------------------------------------------
pub mod a... |
fn run(&mut self, &mut Bot, &BotConfig, &mut EventQueue) -> ActionGroup;
}
| {
true
} | identifier_body |
App.tsx | /// <reference path="../refs.d.ts" />
/// <reference path="../localtypings/blockly.d.ts" />
import * as React from 'react';
import { CSSTransitionGroup } from 'react-transition-group';
import '../App.css';
import { AppModel } from '../models/AppModel';
import { TabbedArea, TabPane } from './TabbedArea';
import { Targ... | (ev: Event) {
this.forceUpdate();
}
render() {
let width = window.innerWidth;
let divider = width * 2 / 3;
let headerHeight = 60;
let footerHeight = 60;
let modelData = this.props.model.data;
let pairLink = `${constants.serverHost}/pair.html?pairingCode=${modelData.pairingCode}`;
re... | onResize | identifier_name |
App.tsx | /// <reference path="../refs.d.ts" />
/// <reference path="../localtypings/blockly.d.ts" />
import * as React from 'react';
import { CSSTransitionGroup } from 'react-transition-group';
import '../App.css';
import { AppModel } from '../models/AppModel';
import { TabbedArea, TabPane } from './TabbedArea';
import { Targ... | Reset Application
</button>
<CSSTransitionGroup
transitionName='statusMessage'
transitionEnterTimeout={0}
transitionLeaveTimeout={0}>
{modelData.statusMessage && <span>{modelData.statusMessage}</span>}
</CSSTrans... | <button type='button' className='btn btn-primary' onClick={() => this.props.model.redo()}>Redo</button>
<button type='button' className='btn btn-primary' onClick={() => this.props.model.resetApplication()}>
<img src='/icons/dark/appbar.flag.wavy.png' style={{ width: 20, height: 20 ... | random_line_split |
App.tsx | /// <reference path="../refs.d.ts" />
/// <reference path="../localtypings/blockly.d.ts" />
import * as React from 'react';
import { CSSTransitionGroup } from 'react-transition-group';
import '../App.css';
import { AppModel } from '../models/AppModel';
import { TabbedArea, TabPane } from './TabbedArea';
import { Targ... |
componentDidMount() {
this.props.model.initializeBlockly(this.blocksArea);
this.props.model.on('change', prop => {
this.forceUpdate();
});
window.addEventListener('resize', this.onResize.bind(this), false);
}
onResize(ev: Event) {
this.forceUpdate();
}
render() {
let width = w... | {
super(props);
this.state = {};
} | identifier_body |
RightPanelCard.js | const React = require('react')
import TeamCard from './TeamCard'
import UserCard from './UserCard'
const {Paper} = require('material-ui')
/**
* Container for UserCard or TeamCard
*/
class RightPanelCard extends React.Component{
render() |
}
RightPanelCard.propTypes = {
/**
* Pydio instance
*/
pydio: React.PropTypes.instanceOf(Pydio),
/**
* Selected item
*/
item: React.PropTypes.object,
/**
* Applies to root container
*/
style: React.PropTypes.object,
/**
* Forwarded to child
*/
o... | {
let content;
const item = this.props.item || {};
if(item.type === 'user'){
content = <UserCard {...this.props}/>
}else if(item.type === 'group' && item.id.indexOf('/AJXP_TEAM/') === 0){
content = <TeamCard {...this.props}/>
}
return (
... | identifier_body |
RightPanelCard.js | const React = require('react')
import TeamCard from './TeamCard'
import UserCard from './UserCard'
const {Paper} = require('material-ui')
/**
* Container for UserCard or TeamCard
*/
class RightPanelCard extends React.Component{
render(){
let content;
const item = this.props.item || {};
... | <Paper zDepth={2} style={{position:'relative', ...this.props.style}}>{content}</Paper>
);
}
}
RightPanelCard.propTypes = {
/**
* Pydio instance
*/
pydio: React.PropTypes.instanceOf(Pydio),
/**
* Selected item
*/
item: React.PropTypes.object,
/**
* A... | content = <TeamCard {...this.props}/>
}
return ( | random_line_split |
RightPanelCard.js | const React = require('react')
import TeamCard from './TeamCard'
import UserCard from './UserCard'
const {Paper} = require('material-ui')
/**
* Container for UserCard or TeamCard
*/
class | extends React.Component{
render(){
let content;
const item = this.props.item || {};
if(item.type === 'user'){
content = <UserCard {...this.props}/>
}else if(item.type === 'group' && item.id.indexOf('/AJXP_TEAM/') === 0){
content = <TeamCard {...this.props}/... | RightPanelCard | identifier_name |
RightPanelCard.js | const React = require('react')
import TeamCard from './TeamCard'
import UserCard from './UserCard'
const {Paper} = require('material-ui')
/**
* Container for UserCard or TeamCard
*/
class RightPanelCard extends React.Component{
render(){
let content;
const item = this.props.item || {};
... |
return (
<Paper zDepth={2} style={{position:'relative', ...this.props.style}}>{content}</Paper>
);
}
}
RightPanelCard.propTypes = {
/**
* Pydio instance
*/
pydio: React.PropTypes.instanceOf(Pydio),
/**
* Selected item
*/
item: React.PropTypes.objec... | {
content = <TeamCard {...this.props}/>
} | conditional_block |
db_log_parser.py | # Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
# This source code is licensed under both the GPLv2 (found in the
# COPYING file in the root directory) and Apache 2.0 License
# (found in the LICENSE.Apache file in the root directory).
from abc import ABC, abstractmethod
from calendar import timeg... |
def get_human_readable_time(self):
# example from a log line: '2018/07/25-11:25:45.782710'
return self.time
def get_column_family(self):
return self.column_family
def get_context(self):
return self.context
def get_message(self):
return self.message
def a... | token_list = log_line.strip().split()
self.time = token_list[0]
self.context = token_list[1]
self.message = " ".join(token_list[2:])
self.column_family = None
# example log for 'default' column family:
# "2018/07/25-17:29:05.176080 7f969de68700 [db/compaction_job.cc:1634]... | identifier_body |
db_log_parser.py | # Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
# This source code is licensed under both the GPLv2 (found in the
# COPYING file in the root directory) and Apache 2.0 License
# (found in the LICENSE.Apache file in the root directory).
from abc import ABC, abstractmethod
from calendar import timeg... | (self):
return (
'time: ' + self.time + '; context: ' + self.context +
'; col_fam: ' + self.column_family +
'; message: ' + self.message
)
class DatabaseLogs(DataSource):
def __init__(self, logs_path_prefix, column_families):
super().__init__(DataSource.... | __repr__ | identifier_name |
db_log_parser.py | # Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
# This source code is licensed under both the GPLv2 (found in the
# COPYING file in the root directory) and Apache 2.0 License
# (found in the LICENSE.Apache file in the root directory).
from abc import ABC, abstractmethod
from calendar import timeg... | if re.search('old', file_name, re.IGNORECASE):
continue
with open(file_name, 'r') as db_logs:
new_log = None
for line in db_logs:
if Log.is_new_log(line):
if new_log:
self.trigger_conditio... | conditional_block | |
db_log_parser.py | # Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
# This source code is licensed under both the GPLv2 (found in the
# COPYING file in the root directory) and Apache 2.0 License
# (found in the LICENSE.Apache file in the root directory).
from abc import ABC, abstractmethod
from calendar import timeg... | self.trigger_conditions_for_log(conditions, new_log) | if new_log: | random_line_split |
borrowingmutsource0.rs | #[allow(dead_code)]
#[derive(Clone, Copy)]
struct Book {
// `&'static str` est une référence d'une chaîne de caractères allouée
// dans un bloc mémoire qui ne peut être accédé qu'en lecture.
author: &'static str,
title: &'static str,
year: u32,
}
// Cette fonction prend une référence d'une instanc... | let mut mutabook = immutabook;
// Emprunte un objet en lecture seule.
borrow_book(&immutabook);
// Emprunte un objet en lecture seule.
borrow_book(&mutabook);
// Récupère une référence mutable d'un objet mutable.
new_edition(&mut mutabook);
// Erreur! Vous ne pouvez pas récupérer une... | random_line_split | |
borrowingmutsource0.rs | #[allow(dead_code)]
#[derive(Clone, Copy)]
struct Book {
// `&'static str` est une référence d'une chaîne de caractères allouée
// dans un bloc mémoire qui ne peut être accédé qu'en lecture.
author: &'static str,
title: &'static str,
year: u32,
}
// Cette fonction prend une référence d'une instanc... | ) {
println!("I immutably borrowed {} - {} edition", book.title, book.year);
}
// Cette fonction prend une référence mutable d'une instance de la
// structure `Book` en paramètre, et initialise sa date de publication
// à 2014.
fn new_edition(book: &mut Book) {
book.year = 2014;
println!("I mutably borro... | book: &Book | identifier_name |
run_command_document_base.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | (Model):
"""Describes the properties of a Run Command metadata.
:param schema: The VM run command schema.
:type schema: str
:param id: The VM run command id.
:type id: str
:param os_type: The Operating System type. Possible values include:
'Windows', 'Linux'
:type os_type: str or
... | RunCommandDocumentBase | identifier_name |
run_command_document_base.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | def __init__(self, schema, id, os_type, label, description):
super(RunCommandDocumentBase, self).__init__()
self.schema = schema
self.id = id
self.os_type = os_type
self.label = label
self.description = description | }
| random_line_split |
run_command_document_base.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | """Describes the properties of a Run Command metadata.
:param schema: The VM run command schema.
:type schema: str
:param id: The VM run command id.
:type id: str
:param os_type: The Operating System type. Possible values include:
'Windows', 'Linux'
:type os_type: str or
~azure.mgmt.c... | identifier_body | |
wpf_preformatter.js | function wpf_preformatter_batch_request(reset, iteration, num) {
iteration++;
var params = {action:'wpf_preformatter_batch', security:wpf_nonce};
if (reset)
params['reset'] = 1;
jQuery.ajax({
type: 'POST',
url: ajaxurl,
async: true,
data... |
// wpf_preformatter_batch
function wpf_preformatter_batch() {
jQuery('#wpf_preformatter_batch_start').unbind('click').click(function() { alert('Please wait for batch preformatting to complete'); });
wpf_indicator_on('#wpf_preformatter_batch_start');
wpf_preformatter_batch_request(true, 0, 0);
}
... | random_line_split | |
wpf_preformatter.js | function wpf_preformatter_batch_request(reset, iteration, num) {
iteration++;
var params = {action:'wpf_preformatter_batch', security:wpf_nonce};
if (reset)
params['reset'] = 1;
jQuery.ajax({
type: 'POST',
url: ajaxurl,
async: true,
data... | () {
jQuery('#wpf_preformatter_batch_start').unbind('click').click(function() { alert('Please wait for batch preformatting to complete'); });
wpf_indicator_on('#wpf_preformatter_batch_start');
wpf_preformatter_batch_request(true, 0, 0);
}
jQuery(document).ready(function($) {
$('#wpf_preformatt... | wpf_preformatter_batch | identifier_name |
wpf_preformatter.js | function wpf_preformatter_batch_request(reset, iteration, num) |
// wpf_preformatter_batch
function wpf_preformatter_batch() {
jQuery('#wpf_preformatter_batch_start').unbind('click').click(function() { alert('Please wait for batch preformatting to complete'); });
wpf_indicator_on('#wpf_preformatter_batch_start');
wpf_preformatter_batch_request(true, 0, 0);
}
... | {
iteration++;
var params = {action:'wpf_preformatter_batch', security:wpf_nonce};
if (reset)
params['reset'] = 1;
jQuery.ajax({
type: 'POST',
url: ajaxurl,
async: true,
data: params,
complete: function (xhr, text) {
... | identifier_body |
wpf_preformatter.js | function wpf_preformatter_batch_request(reset, iteration, num) {
iteration++;
var params = {action:'wpf_preformatter_batch', security:wpf_nonce};
if (reset)
params['reset'] = 1;
jQuery.ajax({
type: 'POST',
url: ajaxurl,
async: true,
data... |
if (!error) {
try {
var data = jQuery.parseJSON(xhr.responseText);
} catch(e) {
error = 'Error decoding response: ' + e;
}
}
if (!error && data['error'])
error = 'Server... | {
error = 'Response error, no data';
} | conditional_block |
csjson.py | import os
import binascii
import json
from txjsonrpc.web.jsonrpc import Proxy
from txjsonrpc.web import jsonrpc
from twisted.web import server
from twisted.internet import reactor
try:
from OpenSSL import SSL
from twisted.internet import ssl
except:
pass
from .base import (get_current_blockheight, CoinSwap... | def send_poll_unsigned(self, method, callback, *args):
"""Stateless queries outside of a coinswap run use
this query method; no nonce, sessionid or signature needed.
"""
d = self.proxy.callRemote(method, *args)
d.addCallback(callback).addErrback(self.error)
def send(self... | """
d = self.proxy.callRemote("coinswap", sessionid, noncesig, method, *args)
d.addCallback(callback).addErrback(self.error)
| random_line_split |
csjson.py | import os
import binascii
import json
from txjsonrpc.web.jsonrpc import Proxy
from txjsonrpc.web import jsonrpc
from twisted.web import server
from twisted.internet import reactor
try:
from OpenSSL import SSL
from twisted.internet import ssl
except:
pass
from .base import (get_current_blockheight, CoinSwap... |
def refresh_carols(self):
"""Remove CoinSwapCarol instances that are flagged complete from
the running dict."""
to_remove = []
for k, v in self.carols.iteritems():
if v.completed:
to_remove.append(k)
for x in to_remove:
self.carols.po... | """In order to respond appropriately to ill formed requests (no content,
or ill-formed content), we return a null response early in this class,
overriding render() from the base class, which unfortunately does not
correctly handle e.g. browser GET requests.
"""
request.content.se... | identifier_body |
csjson.py | import os
import binascii
import json
from txjsonrpc.web.jsonrpc import Proxy
from txjsonrpc.web import jsonrpc
from twisted.web import server
from twisted.internet import reactor
try:
from OpenSSL import SSL
from twisted.internet import ssl
except:
pass
from .base import (get_current_blockheight, CoinSwap... | (self):
#initialise status variables from config; some are updated dynamically
c = cs_single().config
source_chain = c.get("SERVER", "source_chain")
destination_chain = c.get("SERVER", "destination_chain")
minimum_amount = c.getint("SERVER", "minimum_amount")
maximum_amou... | update_status | identifier_name |
csjson.py | import os
import binascii
import json
from txjsonrpc.web.jsonrpc import Proxy
from txjsonrpc.web import jsonrpc
from twisted.web import server
from twisted.internet import reactor
try:
from OpenSSL import SSL
from twisted.internet import ssl
except:
pass
from .base import (get_current_blockheight, CoinSwap... |
#paramlist[1] is method name, the remaining are the args
msg_to_verify = prepare_ecdsa_msg(nonce, paramlist[1], *paramlist[2:])
if not carol.validate_alice_sig(sig, msg_to_verify):
return (False, "ECDSA message signature verification failed")
return (True, "Nonce and signatu... | return (False, "Nonce invalid, probably a repeat") | conditional_block |
downgrade_component.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentFactory, ComponentFactoryResolver, Injector, NgZone, Type} from '@angular/core';
import {IAnnotate... | extends SyncPromise<Injector> {
private injectorKey: string = controllerKey(INJECTOR_KEY);
constructor(private element: IAugmentedJQuery) {
super();
// Store the promise on the element.
element.data !(this.injectorKey, this);
}
resolve(injector: Injector): void {
// Store the real injector o... | ParentInjectorPromise | identifier_name |
downgrade_component.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentFactory, ComponentFactoryResolver, Injector, NgZone, Type} from '@angular/core';
import {IAnnotate... |
if (!parentInjector || hasMultipleDowngradedModules) {
const downgradedModule = info.downgradedModule || '';
const lazyModuleRefKey = `${LAZY_MODULE_REF}${downgradedModule}`;
const attemptedAction = `instantiating component '${getTypeName(info.component)}'`;
validateInj... | const ngModel: INgModelController = required[1];
const parentInjector: Injector|Thenable<Injector>|undefined = required[0];
let moduleInjector: Injector|Thenable<Injector>|undefined = undefined;
let ranAsync = false; | random_line_split |
downgrade_component.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentFactory, ComponentFactoryResolver, Injector, NgZone, Type} from '@angular/core';
import {IAnnotate... |
resolve(injector: Injector): void {
// Store the real injector on the element.
this.element.data !(this.injectorKey, injector);
// Release the element to prevent memory leaks.
this.element = null !;
// Resolve the promise.
super.resolve(injector);
}
}
| {
super();
// Store the promise on the element.
element.data !(this.injectorKey, this);
} | identifier_body |
downgrade_component.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentFactory, ComponentFactoryResolver, Injector, NgZone, Type} from '@angular/core';
import {IAnnotate... |
const injectorPromise = new ParentInjectorPromise(element);
const facade = new DowngradeComponentAdapter(
element, attrs, scope, ngModel, injector, $injector, $compile, $parse,
componentFactory, wrapCallback);
const projectableNodes = facade.compileContents()... | {
throw new Error(`Expecting ComponentFactory for: ${getTypeName(info.component)}`);
} | conditional_block |
common_utils.py | # coding=utf-8 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | # Copyright 2018 The Google AI Language Team Authors.
# | random_line_split |
__init__.py | ###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## ... | pipeline, change its parameters based on aliases, and execute them on
the spreadsheet."""
from __future__ import division
identifier = 'org.vistrails.vistrails.pipelineedit'
name = 'Pipeline Editor'
version = '0.0.2'
old_identifiers = ['edu.utah.sci.vistrails.pipelineedit'] | random_line_split | |
functions4.rs | // Make me compile! Scroll down for hints :)
// This store is having a sale where if the price is an even number, you get
// 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less.
fn main() |
fn sale_price(price: i32) -> i32 {
if is_even(price) {
price - 10
} else {
price - 3
}
}
fn is_even(num: i32) -> bool {
num % 2 == 0
}
// The error message points to line 10 and says it expects a type after the
// `->`. This is where the function's return type shoul... | {
let original_price: i32 = 51;
println!("Your sale price is {}", sale_price(original_price));
} | identifier_body |
functions4.rs | // Make me compile! Scroll down for hints :)
// This store is having a sale where if the price is an even number, you get
// 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less.
fn main() {
let original_price: i32 = 51;
println!("Your sale price is {}", sale_price(original_price));
}
fn ... | else {
price - 3
}
}
fn is_even(num: i32) -> bool {
num % 2 == 0
}
// The error message points to line 10 and says it expects a type after the
// `->`. This is where the function's return type should be-- take a look at
// the `is_even` function for an example!
| {
price - 10
} | conditional_block |
functions4.rs | // Make me compile! Scroll down for hints :)
// This store is having a sale where if the price is an even number, you get
// 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less.
fn main() {
let original_price: i32 = 51;
println!("Your sale price is {}", sale_price(original_price));
}
fn ... | // The error message points to line 10 and says it expects a type after the
// `->`. This is where the function's return type should be-- take a look at
// the `is_even` function for an example! | random_line_split | |
functions4.rs | // Make me compile! Scroll down for hints :)
// This store is having a sale where if the price is an even number, you get
// 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less.
fn | () {
let original_price: i32 = 51;
println!("Your sale price is {}", sale_price(original_price));
}
fn sale_price(price: i32) -> i32 {
if is_even(price) {
price - 10
} else {
price - 3
}
}
fn is_even(num: i32) -> bool {
num % 2 == 0
}
// The error message poi... | main | identifier_name |
mime.rs | use std::io::{Write, BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
use std::borrow::Cow;
macro_rules! or_continue {
($e: expr) => (if let Some(v) = $e {
v
} else {
continue;
})
}
pub fn gen() | {
let input = File::open("build/apache/mime.types").unwrap_or_else(|e| {
panic!("could not open 'build/apache/mime.types': {}", e);
});
let out_path = format!("{}/mime.rs", env!("OUT_DIR"));
let mut output = File::create(&out_path).unwrap_or_else(|e| {
panic!("could not create '{}': {}"... | identifier_body | |
mime.rs | use std::io::{Write, BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
use std::borrow::Cow;
macro_rules! or_continue {
($e: expr) => (if let Some(v) = $e {
v
} else {
continue;
})
}
pub fn | () {
let input = File::open("build/apache/mime.types").unwrap_or_else(|e| {
panic!("could not open 'build/apache/mime.types': {}", e);
});
let out_path = format!("{}/mime.rs", env!("OUT_DIR"));
let mut output = File::create(&out_path).unwrap_or_else(|e| {
panic!("could not create '{}': ... | gen | identifier_name |
mime.rs | use std::io::{Write, BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
use std::borrow::Cow;
macro_rules! or_continue {
($e: expr) => (if let Some(v) = $e {
v
} else {
continue;
})
}
pub fn gen() {
let input = File::open("build/apache/mime.types").unwrap_or_else(|e... | panic!("could not create '{}': {}", out_path, e);
});
let mut types = HashMap::new();
for line in BufReader::new(input).lines().filter_map(Result::ok) {
if let Some('#') = line.chars().next() {
continue;
}
let mut parts = line.split('\t').filter(|v| v.len() > 0... | let out_path = format!("{}/mime.rs", env!("OUT_DIR"));
let mut output = File::create(&out_path).unwrap_or_else(|e| { | random_line_split |
cleanup.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/.
// Code to handle cleanup after a failed operation.
use crate::stratis::{ErrorEnum, StratisError, StratisResult};
u... | else {
let err_msg = format!(
"Failed to teardown already set up pools: {:?}",
untorndown_pools
);
Err(StratisError::Engine(ErrorEnum::Error, err_msg))
}
}
| {
Ok(())
} | conditional_block |
cleanup.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/.
// Code to handle cleanup after a failed operation.
use crate::stratis::{ErrorEnum, StratisError, StratisResult};
u... | (pools: Table<StratPool>) -> StratisResult<()> {
let mut untorndown_pools = Vec::new();
for (_, uuid, mut pool) in pools {
pool.teardown()
.unwrap_or_else(|_| untorndown_pools.push(uuid));
}
if untorndown_pools.is_empty() {
Ok(())
} else {
let err_msg = format!(
... | teardown_pools | identifier_name |
cleanup.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/.
// Code to handle cleanup after a failed operation.
use crate::stratis::{ErrorEnum, StratisError, StratisResult};
u... | );
Err(StratisError::Engine(ErrorEnum::Error, err_msg))
}
} | random_line_split | |
cleanup.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/.
// Code to handle cleanup after a failed operation.
use crate::stratis::{ErrorEnum, StratisError, StratisResult};
u... | {
let mut untorndown_pools = Vec::new();
for (_, uuid, mut pool) in pools {
pool.teardown()
.unwrap_or_else(|_| untorndown_pools.push(uuid));
}
if untorndown_pools.is_empty() {
Ok(())
} else {
let err_msg = format!(
"Failed to teardown already set up p... | identifier_body | |
getAccuracy.py | # -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | params_dict.update(kwargs)
return Matrix(y.sds_context,
'getAccuracy',
named_input_nodes=params_dict) | params_dict = {'y': y, 'yhat': yhat} | random_line_split |
getAccuracy.py | # -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | (y: Matrix,
yhat: Matrix,
**kwargs: Dict[str, VALID_INPUT_TYPES]):
params_dict = {'y': y, 'yhat': yhat}
params_dict.update(kwargs)
return Matrix(y.sds_context,
'getAccuracy',
named_input_nodes=params_dict)
| getAccuracy | identifier_name |
getAccuracy.py | # -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | params_dict = {'y': y, 'yhat': yhat}
params_dict.update(kwargs)
return Matrix(y.sds_context,
'getAccuracy',
named_input_nodes=params_dict) | identifier_body | |
v1.ts | // Copyright 2020 Google LLC
// 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 writi... | {
context: APIRequestContext;
activityTypes: Resource$Projects$Locations$Activitytypes;
constructor(context: APIRequestContext) {
this.context = context;
this.activityTypes = new Resource$Projects$Locations$Activitytypes(
this.context
);
}
}
export class Resource$Projects... | Resource$Projects$Locations | identifier_name |
v1.ts | // Copyright 2020 Google LLC
// 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 writi... |
}
}
export interface Params$Resource$Projects$Locations$Activitytypes$Activities$Query
extends StandardParameters {
/**
* Optional. Filter expression to restrict the activities returned. For serviceAccountLastAuthentication activities, supported filters are: - `activities.full_resource_name {=\} ... | {
return createAPIRequest<Schema$GoogleCloudPolicyanalyzerV1QueryActivityResponse>(
parameters
);
} | conditional_block |
v1.ts | // Copyright 2020 Google LLC
// 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 writi... |
}
export class Resource$Projects$Locations$Activitytypes$Activities {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Queries policy activities on Google Cloud resources.
* @example
* ```js
* // Before running the sam... | {
this.context = context;
this.activities =
new Resource$Projects$Locations$Activitytypes$Activities(this.context);
} | identifier_body |
v1.ts | // Copyright 2020 Google LLC
// 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 writi... | constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Queries policy activities on Google Cloud resources.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/policyanalyze... | }
}
export class Resource$Projects$Locations$Activitytypes$Activities {
context: APIRequestContext; | random_line_split |
spi_master.rs | //! Traits and parameters for SPI master communication.
use core::option::Option;
/// Values for the ordering of bits
#[derive(Copy, Clone)]
pub enum DataOrder {MSBFirst, LSBFirst}
/// Values for the clock polarity (idle state or CPOL)
#[derive(Copy, Clone)]
pub enum ClockPolarity {IdleHigh, IdleLow}
/// Which cloc... | {SampleLeading, SampleTrailing}
pub trait SpiCallback {
/// Called when a read/write operation finishes
fn read_write_done(&'static self);
}
/// The `SpiMaster` trait for interacting with SPI slave
/// devices at a byte or buffer level.
///
/// Using SpiMaster normally involves three steps:
///
/// 1. Configu... | ClockPhase | identifier_name |
spi_master.rs | //! Traits and parameters for SPI master communication.
use core::option::Option;
/// Values for the ordering of bits
#[derive(Copy, Clone)]
pub enum DataOrder {MSBFirst, LSBFirst}
/// Values for the clock polarity (idle state or CPOL)
#[derive(Copy, Clone)]
pub enum ClockPolarity {IdleHigh, IdleLow}
/// Which cloc... | /// Returns whether this chip select is valid and was
/// applied, 0 is always valid.
fn set_chip_select(&self, cs: u8) -> bool;
fn clear_chip_select(&self);
/// Returns the actual rate set
fn set_rate(&self, rate: u32) -> u32;
fn set_clock(&self, polarity: ClockPolarity);
fn set_phase(&... | random_line_split | |
MapCircle.js | var React = require('react');
var {
PropTypes,
} = React;
var ReactNative = require('react-native');
var {
View,
NativeMethodsMixin,
requireNativeComponent,
StyleSheet,
} = ReactNative;
var MapCircle = React.createClass({
mixins: [NativeMethodsMixin],
propTypes: {
...View.propTypes,
/**
*... |
module.exports = MapCircle; | },
});
var AIRMapCircle = requireNativeComponent('AIRMapCircle', MapCircle); | random_line_split |
main.rs | extern crate term_size;
extern crate getch;
extern crate doh;
use getch::Getch;
use std::process::exit;
use std::io::{Write, stdout, stderr};
fn main() {
let ec = handler_main();
exit(ec);
}
fn handler_main() -> i32 {
if let Err((msg, errc)) = real_main() {
let _ = writeln!(stderr(), "{}", msg);... |
}
fn real_main() -> Result<(), (String, i32)> {
let opts = doh::Options::parse();
let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensions.".to_string(), 1)));
let _cursor = doh::util::RaiiGuard::new(|| print!("{}", doh::ops::term::show_cursor(false)),
... | {
0
} | conditional_block |
main.rs | extern crate term_size;
extern crate getch;
extern crate doh;
use getch::Getch;
use std::process::exit;
use std::io::{Write, stdout, stderr};
fn main() |
fn handler_main() -> i32 {
if let Err((msg, errc)) = real_main() {
let _ = writeln!(stderr(), "{}", msg);
errc
} else {
0
}
}
fn real_main() -> Result<(), (String, i32)> {
let opts = doh::Options::parse();
let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown... | {
let ec = handler_main();
exit(ec);
} | identifier_body |
main.rs | extern crate term_size;
extern crate getch;
extern crate doh;
use getch::Getch;
use std::process::exit;
use std::io::{Write, stdout, stderr};
fn main() {
let ec = handler_main();
exit(ec); | if let Err((msg, errc)) = real_main() {
let _ = writeln!(stderr(), "{}", msg);
errc
} else {
0
}
}
fn real_main() -> Result<(), (String, i32)> {
let opts = doh::Options::parse();
let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensions.".to_str... | }
fn handler_main() -> i32 { | random_line_split |
main.rs | extern crate term_size;
extern crate getch;
extern crate doh;
use getch::Getch;
use std::process::exit;
use std::io::{Write, stdout, stderr};
fn main() {
let ec = handler_main();
exit(ec);
}
fn | () -> i32 {
if let Err((msg, errc)) = real_main() {
let _ = writeln!(stderr(), "{}", msg);
errc
} else {
0
}
}
fn real_main() -> Result<(), (String, i32)> {
let opts = doh::Options::parse();
let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensi... | handler_main | identifier_name |
rfc2045.rs | //! Module for dealing with RFC2045 style headers.
use super::rfc5322::Rfc5322Parser;
use std::collections::HashMap;
/// Parser over RFC 2045 style headers.
///
/// Things of the style `value; param1=foo; param2="bar"`
pub struct Rfc2045Parser<'s> {
parser: Rfc5322Parser<'s>,
}
impl<'s> Rfc2045Parser<'s> {
/... | () {
let tests = vec![
ParserTestCase {
input: "foo/bar",
output: ("foo/bar", vec![]),
name: "Basic value",
},
ParserTestCase {
input: "foo/bar; foo=bar",
output: ("foo/bar", vec![
... | test_foo | identifier_name |
rfc2045.rs | //! Module for dealing with RFC2045 style headers.
use super::rfc5322::Rfc5322Parser;
use std::collections::HashMap;
/// Parser over RFC 2045 style headers.
///
/// Things of the style `value; param1=foo; param2="bar"`
pub struct Rfc2045Parser<'s> {
parser: Rfc5322Parser<'s>,
}
impl<'s> Rfc2045Parser<'s> {
/... | (Some(attrib), Some(val)) => {
params.insert(attrib, val);
},
_ => {}
}
}
(value, params)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
struct ParserTestCase<'s> {
inpu... | self.consume_token()
};
match (attribute, value) { | random_line_split |
rfc2045.rs | //! Module for dealing with RFC2045 style headers.
use super::rfc5322::Rfc5322Parser;
use std::collections::HashMap;
/// Parser over RFC 2045 style headers.
///
/// Things of the style `value; param1=foo; param2="bar"`
pub struct Rfc2045Parser<'s> {
parser: Rfc5322Parser<'s>,
}
impl<'s> Rfc2045Parser<'s> {
/... | ,
_ => {}
}
}
(value, params)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
struct ParserTestCase<'s> {
input: &'s str,
output: (&'s str, Vec<(&'s str, &'s str)>),
name: &'s str,
}
#[test]
pu... | {
params.insert(attrib, val);
} | conditional_block |
speed.py | # -*- coding: utf-8 -*-
#
# This file is part of Linux Show Player
#
# Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 ... |
return {}
def load_settings(self, settings):
self.speedSlider.setValue(settings.get('speed', 1) * 100)
def speedChanged(self, value):
self.speedLabel.setText(str(value / 100.0))
| return {'speed': self.speedSlider.value() / 100} | conditional_block |
speed.py | # -*- coding: utf-8 -*-
#
# This file is part of Linux Show Player
#
# Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 ... | (self, enable):
self.groupBox.setCheckable(enable)
self.groupBox.setChecked(False)
def get_settings(self):
if not (self.groupBox.isCheckable() and not self.groupBox.isChecked()):
return {'speed': self.speedSlider.value() / 100}
return {}
def load_settings(self, set... | enable_check | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.