file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
mod.rs | although we handle the invariants in slightly different places to
// get a better iterator interface.
fn next(&mut self) -> Option<ControlMessage<'a>> {
let buf = self.0;
let sizeof_cmsghdr = mem::size_of::<cmsghdr>();
if buf.len() < sizeof_cmsghdr {
return None;
}
... |
}
/// Create an endpoint for communication
///
/// [Further reading](http://man7.org/linux/man-pages/man2/socket.2.html)
pub fn socket(domain: AddressFamily, ty: SockType, flags: SockFlag, protocol: c_int) -> Result<RawFd> {
let mut ty = ty as c_int;
let feat_atomic = features::socket_atomic_cloexec();
... | {
Ok(unsafe { RecvMsg {
bytes: ret as usize,
cmsg_buffer: slice::from_raw_parts(mhdr.msg_control as *const u8,
mhdr.msg_controllen as usize),
address: sockaddr_storage_to_addr(&address,
... | conditional_block |
nixtransport.js | * @return {boolean} Whether window.opener behavior is compatible with NIX.
*/
goog.net.xpc.NixTransport.isNixSupported = function() {
var isSupported = false;
try {
var oldOpener = window.opener;
// The compiler complains (as it should!) if we set window.opener to
// something other than a wind... | {
this.getWindow().setTimeout(goog.bind(this.attemptInnerSetup_, this), 100);
} | conditional_block | |
nixtransport.js | ] || '';
/**
* The authorization token, if any, that must be sent by the other party
* for setup to occur.
* @type {?string}
* @private
*/
this.remoteAuthToken_ =
channel[goog.net.xpc.CfgFields.REMOTE_AUTH_TOKEN] || '';
// Conduct the setup work for NIX in general, if need be.
... |
try {
// Attempt to place the NIX wrapper object into the inner
// frame's opener property.
| random_line_split | |
pat_util.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 ... | (dm: &resolve::DefMap, pat: &Pat) -> bool {
match pat.node {
PatIdent(..) => {
!pat_is_variant_or_struct(dm, pat) &&
!pat_is_const(dm, pat)
}
_ => false
}
}
pub fn pat_is_binding_or_wild(dm: &resolve::DefMap, pat: &Pat) -> bool {
match pat.node {
PatI... | pat_is_binding | identifier_name |
pat_util.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 ... | }
}
_ => false
}
}
pub fn pat_is_const(dm: &resolve::DefMap, pat: &Pat) -> bool {
match pat.node {
PatIdent(_, _, None) | PatEnum(..) => {
match dm.borrow().find(&pat.id) {
Some(&DefStatic(_, false)) => true,
_ => false
... | PatEnum(_, _) | PatIdent(_, _, None) | PatStruct(..) => {
match dm.borrow().find(&pat.id) {
Some(&DefVariant(..)) | Some(&DefStruct(..)) => true,
_ => false | random_line_split |
pat_util.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 ... |
pub fn wild() -> Gc<Pat> {
box (GC) Pat { id: 0, node: PatWild(PatWildSingle), span: DUMMY_SP }
}
pub fn raw_pat(p: Gc<Pat>) -> Gc<Pat> {
match p.node {
PatIdent(_, _, Some(s)) => { raw_pat(s) }
_ => { p }
}
}
pub fn def_to_path(tcx: &ty::ctxt, id: DefId) -> Path {
ty::with_path(tcx,... | {
match pat.node {
PatIdent(BindByValue(_), ref path1, None) => {
Some(&path1.node)
}
_ => {
None
}
}
} | identifier_body |
assert-eq-macro-success.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 ... | () {
assert_eq!(14i,14i);
assert_eq!("abc".to_string(),"abc".to_string());
assert_eq!(box Point{x:34},box Point{x:34});
assert_eq!(&Point{x:34},&Point{x:34});
assert_eq!(box(GC) Point{x:34},box(GC) Point{x:34});
}
| main | identifier_name |
assert-eq-macro-success.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 ... | assert_eq!(&Point{x:34},&Point{x:34});
assert_eq!(box(GC) Point{x:34},box(GC) Point{x:34});
} |
pub fn main() {
assert_eq!(14i,14i);
assert_eq!("abc".to_string(),"abc".to_string());
assert_eq!(box Point{x:34},box Point{x:34}); | random_line_split |
webpack.config.js | var ExtractTextPlugin = require("extract-text-webpack-plugin");
var Webpack = require('webpack');
var path = require('path');
var nodeModulesPath = path.resolve(__dirname, 'node_modules');
var buildPath = path.resolve(__dirname, 'build');
var mainPath = path.resolve(__dirname, 'js', 'app.js');
var config = {
node: {... | exclude: /node_modules/,
loader: "handlebars-loader"
}]
},
plugins: [
new ExtractTextPlugin("style.css"),
new Webpack.HotModuleReplacementPlugin() // we have to manually add the Hot Replacement plugin when running from Node
],
externals: {
'TweenLite': 'TweenLite'
},
resolve: {
... | exclude: /node_modules/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader!sass-loader")
}, {
test: /\.hbs$/, | random_line_split |
container.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 {TNode} from './node';
import {LQueries} from './query';
import {RComment, RElement} from './renderer';
impor... | * it is set to null to identify this scenario, as indices are "absolute" in that case,
* i.e. provided directly by the user of the ViewContainerRef API.
*/
[ACTIVE_INDEX]: number;
/**
* Access to the parent view is necessary so we can propagate back
* up from inside a container to parent[NEXT].
*... | /**
* The next active index in the views array to read or write to. This helps us
* keep track of where we are in the views array.
* In the case the LContainer is created for a ViewContainerRef, | random_line_split |
TaxonomyRouter_spec.js | const should = require('should'),
sinon = require('sinon'),
_ = require('lodash'),
settingsCache = require('../../../../server/services/settings/cache'),
common = require('../../../../server/lib/common'),
controllers = require('../../../../server/services/routing/controllers'),
TaxonomyRouter = ... | sandbox.restore();
});
it('instantiate', function () {
const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/');
should.exist(taxonomyRouter.router);
should.exist(taxonomyRouter.rssRouter);
taxonomyRouter.taxonomyKey.should.eql('tag');
taxonomyRouter.get... | });
afterEach(function () { | random_line_split |
reporter.d.ts | import * as ts from 'typescript';
import { VinylFile } from './types';
export interface TypeScriptError extends Error {
fullFilename?: string;
relativeFilename?: string;
file?: VinylFile;
tsFile?: ts.SourceFile;
diagnostic: ts.Diagnostic; | character: number;
};
endPosition?: {
position: number;
line: number;
character: number;
};
}
export interface CompilationResult {
/**
* Only used when using isolatedModules.
*/
transpileErrors: number;
optionsErrors: number;
syntaxErrors: number;
... | startPosition?: {
position: number;
line: number; | random_line_split |
index.js | 'use strict'
const assert = require('assert')
const test = require('../../lib/test')
const Test = test.Test()
describe('Functional Contract Usage', function () {
before(Test.before())
after(Test.after())
this.timeout(10 * 1000)
it('#Constructor usage', Test.it(function (burrow) {
const source = `
... | const expected2 = [100, A2, 'hello moto', '000000000000000000000000000000000000000000000000DEADBEEFFEEDFACE', 'ABCDEFABCDEFABCDEFABCDEFABCDEFABCDEF0123']
assert.deepEqual(object1, expected1)
assert.deepEqual(object2, expected2)
})
}))
}) | const expected1 = [100, A1, 'hello moto', '000000000000000000000000000000000000000000000000DEADBEEFFEEDFACE', '88977A37D05A4FE86D09E88C88A49C2FCF7D6D8F'] | random_line_split |
bots.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | <R>(
client: &R,
token: &str,
request: &InfoRequest<'_>,
) -> Result<InfoResponse, InfoError<R::Error>>
where
R: SlackWebRequestSender,
{
let params = vec![Some(("token", token)), request.bot.map(|bot| ("bot", bot))];
let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
let... | info | identifier_name |
bots.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | {
let params = vec![Some(("token", token)), request.bot.map(|bot| ("bot", bot))];
let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
let url = crate::get_slack_url_for_method("bots.info");
client
.send(&url, ¶ms[..])
.map_err(InfoError::Client)
.and_then(|... | identifier_body | |
bots.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... |
pub use crate::mod_types::bots_types::*;
use crate::sync::requests::SlackWebRequestSender;
/// Gets information about a bot user.
///
/// Wraps https://api.slack.com/methods/bots.info
pub fn info<R>(
client: &R,
token: &str,
request: &InfoRequest<'_>,
) -> Result<InfoResponse, InfoError<R::Error>>
where
... | random_line_split | |
builtin-superkinds-capabilities.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 ... | <T: Foo + 'static>(val: T, chan: Sender<T>) {
chan.send(val).unwrap();
}
pub fn main() {
let (tx, rx): (Sender<isize>, Receiver<isize>) = channel();
foo(31337, tx);
assert_eq!(rx.recv().unwrap(), 31337);
}
| foo | identifier_name |
builtin-superkinds-capabilities.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 ... | {
let (tx, rx): (Sender<isize>, Receiver<isize>) = channel();
foo(31337, tx);
assert_eq!(rx.recv().unwrap(), 31337);
} | identifier_body | |
builtin-superkinds-capabilities.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() {
let (tx, rx): (Sender<isize>, Receiver<isize>) = channel();
foo(31337, tx);
assert_eq!(rx.recv().unwrap(), 31337);
} | impl <T: Send> Foo for T { }
fn foo<T: Foo + 'static>(val: T, chan: Sender<T>) {
chan.send(val).unwrap();
} | random_line_split |
collinear.rs | // http://coursera.cs.princeton.edu/algs4/assignments/collinear.html
extern crate algs4;
use std::io::prelude::*;
use std::io;
use std::fmt;
use std::cmp::Ordering;
use algs4::sorting::quick_sort;
use algs4::sorting::comparator::Comparator;
use algs4::sorting::comparator::insertion_sort;
#[derive(Copy, Clone)]
pub s... | (&self, other: &Point) -> bool {
self.x == other.x && self.y == other.y
}
}
// is this point lexicographically smaller than that point?
impl PartialOrd<Point> for Point {
fn partial_cmp(&self, other: &Point) -> Option<Ordering> {
if self.y < other.y || (self.y == other.y && self.x < other.x) {... | eq | identifier_name |
collinear.rs | // http://coursera.cs.princeton.edu/algs4/assignments/collinear.html
extern crate algs4;
use std::io::prelude::*;
use std::io;
use std::fmt;
use std::cmp::Ordering;
use algs4::sorting::quick_sort;
use algs4::sorting::comparator::Comparator;
use algs4::sorting::comparator::insertion_sort;
#[derive(Copy, Clone)]
pub s... |
fn main() {
let mut lines = io::BufReader::new(io::stdin()).lines();
let n = lines.next().unwrap().unwrap().parse().unwrap();
let mut points: Vec<Point> = Vec::new();
for _ in 0 .. n {
let segs: Vec<i32> = lines.next().unwrap().unwrap().split(' ').
filter(|s| !s.is_empty()).map(|n|... | random_line_split | |
collinear.rs | // http://coursera.cs.princeton.edu/algs4/assignments/collinear.html
extern crate algs4;
use std::io::prelude::*;
use std::io;
use std::fmt;
use std::cmp::Ordering;
use algs4::sorting::quick_sort;
use algs4::sorting::comparator::Comparator;
use algs4::sorting::comparator::insertion_sort;
#[derive(Copy, Clone)]
pub s... |
for s in points.iter() {
if s == p || s == q || s == r { break }
let slope = p.slope_to(q);
if slope == p.slope_to(r) && slope == p.slope_to(s) {
println!("{} -> {} -> {} -> {}", p, q, r, s);
}
... | { break } | conditional_block |
main.js | define([
'require',
'jquery',
'base/js/namespace',
'base/js/events',
'base/js/utils',
'notebook/js/codecell',
], function (
requirejs,
$,
Jupyter,
events,
utils,
codecell
) {
"use strict";
var CodeCell = codecell.CodeCell;
var Scratchpad = function (nb) {
var scratchpad = this;
th... | this.open_button.click(function () {
scratchpad.expand();
});
this.close_button.click(function () {
scratchpad.collapse();
});
// create my cell
var cell = this.cell = new CodeCell(nb.kernel, {
events: nb.events,
config: nb.config,
keyboard_manager: nb.keyboard_man... | random_line_split | |
main.js | define([
'require',
'jquery',
'base/js/namespace',
'base/js/events',
'base/js/utils',
'notebook/js/codecell',
], function (
requirejs,
$,
Jupyter,
events,
utils,
codecell
) {
"use strict";
var CodeCell = codecell.CodeCell;
var Scratchpad = function (nb) {
var scratchpad = this;
th... | () {
// add css
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = requirejs.toUrl("./scratchpad.css");
document.getElementsByTagName("head")[0].appendChild(link);
// load when the kernel's ready
if (Jupyter.notebook.kernel) {
s... | load_extension | identifier_name |
main.js | define([
'require',
'jquery',
'base/js/namespace',
'base/js/events',
'base/js/utils',
'notebook/js/codecell',
], function (
requirejs,
$,
Jupyter,
events,
utils,
codecell
) {
"use strict";
var CodeCell = codecell.CodeCell;
var Scratchpad = function (nb) {
var scratchpad = this;
th... |
};
Scratchpad.prototype.execute_event = function (evt) {
if (utils.is_focused(this.element)) {
this.cell.execute();
} else {
this.notebook.execute_selected_cells();
}
};
function setup_scratchpad () {
// lazy, hook it up to Jupyter.notebook as the handle on all the singletons
... | {
this.notebook.execute_cell_and_select_below();
} | conditional_block |
main.js | define([
'require',
'jquery',
'base/js/namespace',
'base/js/events',
'base/js/utils',
'notebook/js/codecell',
], function (
requirejs,
$,
Jupyter,
events,
utils,
codecell
) {
"use strict";
var CodeCell = codecell.CodeCell;
var Scratchpad = function (nb) {
var scratchpad = this;
th... |
function load_extension () {
// add css
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = requirejs.toUrl("./scratchpad.css");
document.getElementsByTagName("head")[0].appendChild(link);
// load when the kernel's ready
if (Jupyter... | {
// lazy, hook it up to Jupyter.notebook as the handle on all the singletons
console.log("Setting up scratchpad");
return new Scratchpad(Jupyter.notebook);
} | identifier_body |
brushScript.js | //
// brushScript.js
//
// created by Liv Erickson on 12/04/18
// Copyright 2018 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function () {
var COLOR_NAME = "Paint-Color";
this.collis... |
};
}); | {
if (collisionProperties.name.indexOf('brush') === -1 &&
collisionProperties.name.indexOf('Palette') === -1 &&
collisionProperties.name.indexOf('Parent') === -1) {
Entities.editEntity(theirID, { 'color': Entities.getEntityProperties(myID, 'color').color });
... | conditional_block |
brushScript.js | //
// brushScript.js | //
// created by Liv Erickson on 12/04/18
// Copyright 2018 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function () {
var COLOR_NAME = "Paint-Color";
this.collisionWithEntity = functi... | random_line_split | |
login.js | window.onload=function() {
var start = document.getElementById('start');
start.onclick = function () {
var name = document.getElementById('Name').value;
var id = document.getElementById('Id').value;
var tel = document.getElementById("Tel").value;
if (name == "") {
... | }
if (id =="") {
alert("请输入学号");
return false;
}
if (!isId(id)) {
alert("请输入正确学号");
return false;
}
if (tel == "") {
alert("请输入电话号码");
return false;
}
if (!isTelephone(tel)) {
... | return false;
}
if (!isName(name)) {
alert("请输入正确的姓名")
return false; | random_line_split |
login.js | window.onload=function() {
var start = document.getElementById('start');
start.onclick = function () {
var name = document.getElementById('Name').value;
var id = document.getElementById('Id').value;
var tel = document.getElementById("Tel").value;
if (name == "") {
... | g.test(obj);
}
} | function isTelephone(obj) {
reg = /^1[34578]\d{9}$/;
return re | identifier_body |
login.js | window.onload=function() {
var start = document.getElementById('start');
start.onclick = function () {
var name = document.getElementById('Name').value;
var id = document.getElementById('Id').value;
var tel = document.getElementById("Tel").value;
if (name == "") {
... | }
function isTelephone(obj) {
reg = /^1[34578]\d{9}$/;
return reg.test(obj);
}
} | identifier_name | |
login.js | window.onload=function() {
var start = document.getElementById('start');
start.onclick = function () {
var name = document.getElementById('Name').value;
var id = document.getElementById('Id').value;
var tel = document.getElementById("Tel").value;
if (name == "") {
... | 号码");
return false;
}
if (!isTelephone(tel)) {
alert("请输入正确的手机号码");
return false;
}
else {
start.submit();
// document.getElementById("myform").submit();
// window.open("answer.html","_self");
}
}
f... | return false;
}
if (tel == "") {
alert("请输入电话 | conditional_block |
block_metadata_config_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
config::{
block_metadata::{build_block_metadata, is_new_block, Entry},
global::Config as GlobalConfig,
},
errors::*,
tests::{
global_config_tests::parse_and_build_config as parse_and_... |
fn parse_and_build_config(global_config: &GlobalConfig, s: &str) -> Result<BlockMetadata> {
build_block_metadata(&global_config, &parse_each_line_as::<Entry>(s)?)
}
#[rustfmt::skip]
#[test]
fn build_transaction_config_1() {
let global = parse_and_build_global_config(r"
//! account: alice
").unwra... | {
assert!(is_new_block("//! block-prologue"));
assert!(is_new_block("//!block-prologue "));
assert!(!is_new_block("//"));
assert!(!is_new_block("//! new block"));
assert!(!is_new_block("//! block"));
} | identifier_body |
block_metadata_config_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
config::{
block_metadata::{build_block_metadata, is_new_block, Entry},
global::Config as GlobalConfig,
},
errors::*,
tests::{
global_config_tests::parse_and_build_config as parse_and_... | () {
assert!(is_new_block("//! block-prologue"));
assert!(is_new_block("//!block-prologue "));
assert!(!is_new_block("//"));
assert!(!is_new_block("//! new block"));
assert!(!is_new_block("//! block"));
}
fn parse_and_build_config(global_config: &GlobalConfig, s: &str) -> Result<BlockMetadata> {
... | parse_new_transaction | identifier_name |
block_metadata_config_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
config::{
block_metadata::{build_block_metadata, is_new_block, Entry},
global::Config as GlobalConfig,
},
errors::*,
tests::{
global_config_tests::parse_and_build_config as parse_and_... |
for s in &[
"//!block-time:",
"//!block-time:abc",
"//!block-time: 123, 45",
] {
s.parse::<Entry>().unwrap_err();
}
}
#[test]
fn parse_new_transaction() {
assert!(is_new_block("//! block-prologue"));
assert!(is_new_block("//!block-prologue "));
assert!(!is_new_b... | } | random_line_split |
http-echo-server.rs | extern crate clap;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate simplesched;
use std::io;
use clap::{Arg, App};
use simplesched::Scheduler;
use simplesched::net::http::Server;
use hyper::{Get, Post};
use hyper::server::{Request, Response};
use hyper::uri::RequestUri::Abs... | *res.status_mut() = hyper::NotFound;
return;
}
},
_ => {
return;
}
};
let mut res = try_return!(res.start());
try_return!(io::copy(&mut req, &mut res));
}
fn main() {
env_logger::init().unwrap();
let matches = App::ne... | random_line_split | |
http-echo-server.rs | extern crate clap;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate simplesched;
use std::io;
use clap::{Arg, App};
use simplesched::Scheduler;
use simplesched::net::http::Server;
use hyper::{Get, Post};
use hyper::server::{Request, Response};
use hyper::uri::RequestUri::Abs... | }
| {
env_logger::init().unwrap();
let matches = App::new("http-echo")
.version(env!("CARGO_PKG_VERSION"))
.author("Y. T. Chung <zonyitoo@gmail.com>")
.arg(Arg::with_name("BIND").short("b").long("bind").takes_value(true).required(true)
.help("Listening on thi... | identifier_body |
http-echo-server.rs | extern crate clap;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate simplesched;
use std::io;
use clap::{Arg, App};
use simplesched::Scheduler;
use simplesched::net::http::Server;
use hyper::{Get, Post};
use hyper::server::{Request, Response};
use hyper::uri::RequestUri::Abs... | ,
(&Post, "/echo") => (), // fall through, fighting mutable borrows
_ => {
*res.status_mut() = hyper::NotFound;
return;
}
},
_ => {
return;
}
};
let mut res = try_return!(res.start());
try_return!(io::co... | {
try_return!(res.send(b"Try POST /echo"));
return;
} | conditional_block |
http-echo-server.rs | extern crate clap;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate simplesched;
use std::io;
use clap::{Arg, App};
use simplesched::Scheduler;
use simplesched::net::http::Server;
use hyper::{Get, Post};
use hyper::server::{Request, Response};
use hyper::uri::RequestUri::Abs... | () {
env_logger::init().unwrap();
let matches = App::new("http-echo")
.version(env!("CARGO_PKG_VERSION"))
.author("Y. T. Chung <zonyitoo@gmail.com>")
.arg(Arg::with_name("BIND").short("b").long("bind").takes_value(true).required(true)
.help("Listening on ... | main | identifier_name |
UserBadge.js | import html from 'bel'
import Events from 'plug/core/Events'
import ShowUserRolloverEvent from 'plug/events/ShowUserRolloverEvent'
import users from 'plug/collections/users'
import getUserClasses from 'extplug/util/getUserClasses'
export default function | (uid) {
const user = users.findWhere({ id: uid })
if (user) {
return html`
<div class="extp-UserBadge user ${getUserClasses(uid).join(' ')}"
onclick=${onclick}>
<div class="extp-UserBadge-img">
<div class="thumb small">
<i class="avi avi-${user.get('avatarID')}"><... | UserBadge | identifier_name |
UserBadge.js | import html from 'bel'
import Events from 'plug/core/Events'
import ShowUserRolloverEvent from 'plug/events/ShowUserRolloverEvent'
import users from 'plug/collections/users'
import getUserClasses from 'extplug/util/getUserClasses'
export default function UserBadge (uid) | }
function onclick (event) {
const el = $(event.target).closest('.extp-UserBadge')
Events.dispatch(new ShowUserRolloverEvent(ShowUserRolloverEvent.SHOW, user, {
x: el.offset().left - 6,
y: el.offset().top
}, true))
}
}
| {
const user = users.findWhere({ id: uid })
if (user) {
return html`
<div class="extp-UserBadge user ${getUserClasses(uid).join(' ')}"
onclick=${onclick}>
<div class="extp-UserBadge-img">
<div class="thumb small">
<i class="avi avi-${user.get('avatarID')}"></i>
... | identifier_body |
UserBadge.js | import html from 'bel'
import Events from 'plug/core/Events'
import ShowUserRolloverEvent from 'plug/events/ShowUserRolloverEvent'
import users from 'plug/collections/users'
import getUserClasses from 'extplug/util/getUserClasses'
export default function UserBadge (uid) {
const user = users.findWhere({ id: uid })
... | </div>
`
} else {
// TODO load user using a bulk load action
const placeholder = html`<div />`
return placeholder
}
function onclick (event) {
const el = $(event.target).closest('.extp-UserBadge')
Events.dispatch(new ShowUserRolloverEvent(ShowUserRolloverEvent.SHOW, user, {
x:... | </div>
</div>
<span class="extp-UserBadge-name">
${user.get('username')}
</span> | random_line_split |
UserBadge.js | import html from 'bel'
import Events from 'plug/core/Events'
import ShowUserRolloverEvent from 'plug/events/ShowUserRolloverEvent'
import users from 'plug/collections/users'
import getUserClasses from 'extplug/util/getUserClasses'
export default function UserBadge (uid) {
const user = users.findWhere({ id: uid })
... | else {
// TODO load user using a bulk load action
const placeholder = html`<div />`
return placeholder
}
function onclick (event) {
const el = $(event.target).closest('.extp-UserBadge')
Events.dispatch(new ShowUserRolloverEvent(ShowUserRolloverEvent.SHOW, user, {
x: el.offset().left - 6,... | {
return html`
<div class="extp-UserBadge user ${getUserClasses(uid).join(' ')}"
onclick=${onclick}>
<div class="extp-UserBadge-img">
<div class="thumb small">
<i class="avi avi-${user.get('avatarID')}"></i>
</div>
</div>
<span class="extp-Use... | conditional_block |
str.rs | .spec.whatwg.org/#rules-for-parsing-integers>.
pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> {
do_parse_integer(input).and_then(|result| {
result.to_i32()
})
}
/// Parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers>
pub fn pa... | } | random_line_split | |
str.rs | wg.org/#rules-for-parsing-integers> or
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers>
fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> {
fn is_ascii_digit(c: &char) -> bool {
match *c {
'0'...'9' => true,
_ => false,
}
}
... | from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned()
}
p | identifier_body | |
str.rs | '];
pub fn is_whitespace(s: &str) -> bool {
s.chars().all(char_is_whitespace)
}
#[inline]
pub fn c | c: char) -> bool {
WHITESPACE.contains(&c)
}
/// A "space character" according to:
///
/// https://html.spec.whatwg.org/multipage/#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[
'\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}',
'\u{000d}',
];
pub fn split_html_space_chars<'... | har_is_whitespace( | identifier_name |
str.rs | d'];
pub fn is_whitespace(s: &str) -> bool {
s.chars().all(char_is_whitespace)
}
#[inline]
pub fn char_is_whitespace(c: char) -> bool {
WHITESPACE.contains(&c)
}
/// A "space character" according to:
///
/// https://html.spec.whatwg.org/multipage/#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharV... | let mut end_index = value.len();
let (mut found_full_stop, mut found_percent) = (false, false);
for (i, ch) in value.chars().enumerate() {
match ch {
'0'...'9' => continue,
'%' => {
found_percent = true;
end_index = i;
break
... | return LengthOrPercentageOrAuto::Auto
}
| conditional_block |
PlanUtils.ts | import {ProjectEditor, EditProject} from "@atomist/rug/operations/ProjectEditor"
import {Project} from "@atomist/rug/model/Project"
import {Edit,Instruction,HandleCommand, Respondable, Execute} from "@atomist/rug/operations/Handlers"
/**
* Build a plan instruction for the given decorated
* editor, extracting its pre... |
export function handleCommand(ed: HandleCommand): Instruction<"command"> {
return instruction(ed, "command")
}
/**
* Emit an instruction for the given decorated operation type
* @param op operation to emit instruction for
* @param kind kind of the instruction, such as "edit"
*/
function instruction(op, kind)... | {
let obj = instruction(ed, "edit")
let proj = p as any
obj["project"] = proj.name ? proj.name() : p
return obj as Edit
} | identifier_body |
PlanUtils.ts | import {ProjectEditor, EditProject} from "@atomist/rug/operations/ProjectEditor"
import {Project} from "@atomist/rug/model/Project"
import {Edit,Instruction,HandleCommand, Respondable, Execute} from "@atomist/rug/operations/Handlers"
/**
* Build a plan instruction for the given decorated
* editor, extracting its pre... | (ed: HandleCommand): Instruction<"command"> {
return instruction(ed, "command")
}
/**
* Emit an instruction for the given decorated operation type
* @param op operation to emit instruction for
* @param kind kind of the instruction, such as "edit"
*/
function instruction(op, kind) {
let params = {}
for ... | handleCommand | identifier_name |
PlanUtils.ts | import {ProjectEditor, EditProject} from "@atomist/rug/operations/ProjectEditor"
import {Project} from "@atomist/rug/model/Project"
import {Edit,Instruction,HandleCommand, Respondable, Execute} from "@atomist/rug/operations/Handlers"
| * Build a plan instruction for the given decorated
* editor, extracting its present property values, which
* follow a convention, with names like __name
* @param p project or name of project to edit
* @param ed editor to use
*/
export function editWith(p: Project | string, ed: EditProject | ProjectEditor): Edit {... | /** | random_line_split |
pkgutil.py | exceptions are propagated, terminating the search.
Examples:
# list all modules python can access
walk_packages()
# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__+'.')
"""
def seen(p, m={}):
if p in m:
return True
m[p] = True
... | :
"""PEP 302 Loader that wraps Python's "classic" import algorithm
"""
code = source = None
def __init__(self, fullname, file, filename, etc):
self.file = file
self.filename = filename
self.fullname = fullname
self.etc = etc
def load_module(self, fullname):
... | ImpLoader | identifier_name |
pkgutil.py | exceptions are propagated, terminating the search.
Examples:
# list all modules python can access
walk_packages()
# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__+'.')
"""
def seen(p, m={}):
if p in m:
return True
m[p] = True
... |
def get_data(self, pathname):
f = open(pathname, "rb")
try:
return f.read()
finally:
f.close()
def _reopen(self):
if self.file and self.file.closed:
mod_type = self.etc[2]
if mod_type==imp.PY_SOURCE:
self.file = op... | """PEP 302 Loader that wraps Python's "classic" import algorithm
"""
code = source = None
def __init__(self, fullname, file, filename, etc):
self.file = file
self.filename = filename
self.fullname = fullname
self.etc = etc
def load_module(self, fullname):
self._... | identifier_body |
pkgutil.py | generic(iter_importer_modules)
class ImpImporter:
"""PEP 302 Importer that wraps Python's "classic" import algorithm
ImpImporter(dirname) produces a PEP 302 importer that searches that
directory. ImpImporter(None) produces a PEP 302 importer that searches
the current sys.path, plus any modules that ... | yield ImpImporter() | conditional_block | |
pkgutil.py | .filename[:-1], 'rU')
try:
self.source = f.read()
finally:
f.close()
elif mod_type==imp.PKG_DIRECTORY:
self.source = self._get_delegate().get_source()
return self.source
def _get_delegate(se... | try:
for line in f: | random_line_split | |
sys_stdrhino_locale.js | /*
* Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights
* Reserved.
*
* The contents of this file are subject to the Common Public
* Attribution License Version 1.0 (the “License”); you may not use
* this file except in compliance with the License. You may obtain a
* copy of the License at:
*
*... | },
function testSetLocaleEmptyValue(){
var sys = new StdRhinoTest();
var obj = new CSL.Engine(sys,"<style></style>");
doh.assertEqual("and", obj.locale["en-US"].terms["and"]["long"]);
},
function testLocaleGlobalWorksAtAll(){
try {
var sys = new RhinoTest();
var obj = new CSL.Engine(sys,"<style></styl... | doh.assertEqual("und", obj.locale["de-DE"].terms["and"]["long"]); | random_line_split |
cmath.rs | // Copyright 2017 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 ... | (n: c_float) -> c_float {
f64::asin(n as f64) as c_float
}
#[inline]
pub unsafe fn atan2f(n: c_float, b: c_float) -> c_float {
f64::atan2(n as f64, b as f64) as c_float
}
#[inline]
pub unsafe fn atanf(n: c_float) -> c_float {
f64::atan(n as f64) as c_float
}
#[... | asinf | identifier_name |
cmath.rs | // Copyright 2017 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 coshf(n: c_float) -> c_float;
pub fn sinhf(n: c_float) -> c_float;
pub fn tanf(n: c_float) -> c_float;
pub fn tanhf(n: c_float) -> c_float;
}
}
// On MSVC these functions aren't defined, so we just define shims which promote
// everything fo f64, perform the calculation, and ... | pub fn asinf(n: c_float) -> c_float;
pub fn atan2f(a: c_float, b: c_float) -> c_float;
pub fn atanf(n: c_float) -> c_float; | random_line_split |
cmath.rs | // Copyright 2017 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 ... |
#[inline]
pub unsafe fn atan2f(n: c_float, b: c_float) -> c_float {
f64::atan2(n as f64, b as f64) as c_float
}
#[inline]
pub unsafe fn atanf(n: c_float) -> c_float {
f64::atan(n as f64) as c_float
}
#[inline]
pub unsafe fn coshf(n: c_float) -> c_float {
f64::... | {
f64::asin(n as f64) as c_float
} | identifier_body |
main.rs | Handler, SigSet, Signal},
unistd,
};
use std::{
fs,
io::{stdin, BufReader},
process,
sync::Arc,
};
use crate::binary::MAN_ION;
use std::env;
use thiserror::Error;
mod binary;
struct KeyBindingsWrapper(KeyBindings);
/// The fast, safe, modern rust shell.
/// Ion is a commandline shell created to ... | () -> String { include!(concat!(env!("OUT_DIR"), "/version_string")).to_string() }
fn parse_args() -> Result<CommandLineArgs, ParsingError> {
let mut arg_twice_set = false;
let mut invalid_keybinding = false;
let mut args = env::args().skip(1);
let mut version = false;
let mut help = false;
let... | version | identifier_name |
main.rs | Handler, SigSet, Signal},
unistd,
};
use std::{
fs,
io::{stdin, BufReader},
process,
sync::Arc,
};
use crate::binary::MAN_ION;
use std::env;
use thiserror::Error;
mod binary;
struct KeyBindingsWrapper(KeyBindings);
/// The fast, safe, modern rust shell.
/// Ion is a commandline shell created to ... | return;
}
if command_line_args.command.is_some() && !command_line_args.args.is_empty() {
eprintln!("either execute command or file(s)");
process::exit(1);
}
let mut builtins = BuiltinMap::default();
builtins
.with_unsafe()
.add("debug", &builtins::builtin_deb... | {
let parsedargs = parse_args();
let command_line_args = match parsedargs {
Ok(parsedargs) => parsedargs,
Err(ParsingError::ArgTwiceSet) => {
eprintln!("flag or option set twice, see --help");
process::exit(1);
}
Err(ParsingError::InvalidKeybinding) => {
... | identifier_body |
main.rs | Handler, SigSet, Signal},
unistd,
};
use std::{
fs,
io::{stdin, BufReader},
process,
sync::Arc,
};
use crate::binary::MAN_ION;
use std::env;
use thiserror::Error;
mod binary;
struct KeyBindingsWrapper(KeyBindings);
/// The fast, safe, modern rust shell.
/// Ion is a commandline shell created to ... | }
"-f" | "--fake-interactive" => {
if fake_interactive {
arg_twice_set = true;
}
fake_interactive = true;
}
"-i" | "--interactive" => {
if interactive {
arg_twice_set =... | no_execute = true; | random_line_split |
main.rs | Handler, SigSet, Signal},
unistd,
};
use std::{
fs,
io::{stdin, BufReader},
process,
sync::Arc,
};
use crate::binary::MAN_ION;
use std::env;
use thiserror::Error;
mod binary;
struct KeyBindingsWrapper(KeyBindings);
/// The fast, safe, modern rust shell.
/// Ion is a commandline shell created to ... | else {
shell.execute_command(BufReader::new(stdin()))
}
.and_then(|_| shell.wait_for_background().map_err(Into::into));
| {
let mut reader = BufReader::new(stdin());
loop {
if let Err(err) = shell.execute_command(&mut reader) {
eprintln!("ion: {}", err);
}
}
} | conditional_block |
constants.rs | pub const GET_TXN: &str = "3";
pub const ATTRIB: &str = "100";
pub const SCHEMA: &str = "101";
pub const CRED_DEF: &str = "102";
pub const GET_ATTR: &str = "104";
pub const GET_NYM: &str = "105";
pub const GET_SCHEMA: &str = "107";
pub const GET_CRED_DEF: &str = "108";
pub const POOL_UPGRADE: &str = "109";
pub const PO... | pub const NODE: &str = "0";
pub const NYM: &str = "1"; | random_line_split | |
constants.rs | pub const NODE: &str = "0";
pub const NYM: &str = "1";
pub const GET_TXN: &str = "3";
pub const ATTRIB: &str = "100";
pub const SCHEMA: &str = "101";
pub const CRED_DEF: &str = "102";
pub const GET_ATTR: &str = "104";
pub const GET_NYM: &str = "105";
pub const GET_SCHEMA: &str = "107";
pub const GET_CRED_DEF: &str = "1... | "REVOC_REG_ENTRY" => Some(REVOC_REG_ENTRY),
"GET_REVOC_REG_DEF" => Some(GET_REVOC_REG_DEF),
"GET_REVOC_REG" => Some(GET_REVOC_REG),
"GET_REVOC_REG_DELTA" => Some(GET_REVOC_REG_DELTA),
"GET_VALIDATOR_INFO" => Some(GET_VALIDATOR_INFO),
"AUTH_RULE" => Some(AUTH_RULE),
... | {
if REQUESTS.contains(&txn) {
return Some(txn)
}
match txn {
"NODE" => Some(NODE),
"NYM" => Some(NYM),
"GET_TXN" => Some(GET_TXN),
"ATTRIB" => Some(ATTRIB),
"SCHEMA" => Some(SCHEMA),
"CRED_DEF" | "CLAIM_DEF" => Some(CRED_DEF),
"GET_ATTR" => S... | identifier_body |
constants.rs | pub const NODE: &str = "0";
pub const NYM: &str = "1";
pub const GET_TXN: &str = "3";
pub const ATTRIB: &str = "100";
pub const SCHEMA: &str = "101";
pub const CRED_DEF: &str = "102";
pub const GET_ATTR: &str = "104";
pub const GET_NYM: &str = "105";
pub const GET_SCHEMA: &str = "107";
pub const GET_CRED_DEF: &str = "1... | (txn: &str) -> Option<&str> {
if REQUESTS.contains(&txn) {
return Some(txn)
}
match txn {
"NODE" => Some(NODE),
"NYM" => Some(NYM),
"GET_TXN" => Some(GET_TXN),
"ATTRIB" => Some(ATTRIB),
"SCHEMA" => Some(SCHEMA),
"CRED_DEF" | "CLAIM_DEF" => Some(CRED_D... | txn_name_to_code | identifier_name |
flasher.py | import click
import os
import os.path
import ntpath
import serial
import sys
import prosflasher.ports
import prosflasher.upload
import prosconfig
from proscli.utils import default_cfg, AliasGroup
from proscli.utils import get_version
@click.group(cls=AliasGroup)
def flasher_cli():
pass
@flashe... | click.echo(repr(sys_info))
pass
@flasher_cli.command(short_help='List connected microcontrollers')
@default_cfg
def lsusb(cfg):
if len(prosflasher.ports.list_com_ports()) == 0 or prosflasher.ports.list_com_ports() is None:
click.echo('No serial ports found.')
else:
cli... | if port == 'auto':
ports = prosflasher.ports.list_com_ports()
if len(ports) == 0:
click.echo('No microcontrollers were found. Please plug in a cortex or manually specify a serial port.\n',
err=True)
sys.exit(1)
port = prosflasher.ports.list_co... | identifier_body |
flasher.py | import click
import os
import os.path
import ntpath
import serial
import sys
import prosflasher.ports
import prosflasher.upload
import prosconfig
from proscli.utils import default_cfg, AliasGroup
from proscli.utils import get_version
@click.group(cls=AliasGroup)
def flasher_cli():
pass
@flashe... |
else:
port = [port]
if binary == 'default':
binary = os.getcwd()
if ctx.verbosity > 3:
click.echo('Default binary selected, new directory is {}'.format(binary))
binary = find_binary(binary)
if binary is None:
click.echo('No binary was found! En... | click.confirm('Download to ' + ', '.join(port), default=True, abort=True, prompt_suffix='?') | conditional_block |
flasher.py | import click
import os
import os.path
import ntpath
import serial
import sys
import prosflasher.ports
import prosflasher.upload
import prosconfig
from proscli.utils import default_cfg, AliasGroup
from proscli.utils import get_version
@click.group(cls=AliasGroup)
def flasher_cli():
pass
@flashe... | (cfg, yes, port):
if port == 'auto':
ports = prosflasher.ports.list_com_ports()
if len(ports) == 0:
click.echo('No microcontrollers were found. Please plug in a cortex or manually specify a serial port.\n',
err=True)
sys.exit(1)
port = pr... | get_sys_info | identifier_name |
flasher.py | import click
import os
import os.path
import ntpath
import serial
import sys
import prosflasher.ports
import prosflasher.upload
import prosconfig
from proscli.utils import default_cfg, AliasGroup
from proscli.utils import get_version
@click.group(cls=AliasGroup)
def flasher_cli():
pass
@flashe... | # def dump_cortex(file, verbose):
# pass | random_line_split | |
che-branding.factory.ts | distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
'use strict';
import {CheService} from '../api/che-service.factory';
interface IBranding {
title?: string;
name?: string;
logoFile?: string;
logoTextFile?:... | const DEFAULT_DOCS_WORKSPACE = '/docs/getting-started/intro/index.html';
const DEFAULT_WORKSPACE_PRIORITY_STACKS = ['Java', 'Java-MySQL', 'Blank'];
const DEFAULT_WORKSPACE_DEFAULT_STACK = 'java-mysql';
const DEFAULT_WORKSPACE_CREATION_LINK = '#/create-workspace';
const DEFAULT_WEBSOCKET_CONTEXT = '/api/websocket';
/**... | random_line_split | |
che-branding.factory.ts | distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
'use strict';
import {CheService} from '../api/che-service.factory';
interface IBranding {
title?: string;
name?: string;
logoFile?: string;
logoTextFile?:... | (): void {
this.cheService.fetchServicesInfo().then(() => {
let info = this.cheService.getServicesInfo();
this.$rootScope.productVersion = (info && info.implementationVersion) ? info.implementationVersion : '';
});
}
/**
* Update branding data.
*/
updateData(): void {
this.$http.get... | updateVersion | identifier_name |
che-branding.factory.ts | , and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
'use strict';
import {CheService} from '../api/che-service.factory';
interface IBranding {
title?: string;
name?: string;
logoFile?: string;
logoTextFile?: string;
fa... |
this.callbacks.delete(callbackId);
}
/**
* Gets name.
* @returns {string}
*/
getName(): string {
return this.brandingData.name ? this.brandingData.name : DEFAULT_NAME;
}
/**
* Gets product name.
* @returns {string}
*/
getProductName(): string {
return this.brandingData.titl... | {
return;
} | conditional_block |
lib.rs | //! An wrapper for the RealSense library.
//!
//! # Example
//!
//! ```no_run
//! extern crate realsense; | //!
//! fn main() {
//! let context = rs::Context::new().unwrap();
//! let device = context.get_device(0).unwrap();
//! let property = {
//! rs::Properties {
//! format: rs::Format::Z16,
//! ..Default::default()
//! }
//! };
//! device.enable_stream(rs::Stream... | //! use realsense as rs; | random_line_split |
test_snapshot.py | import shutil
from nose.tools import *
from holland.lib.lvm import LogicalVolume
from holland.lib.lvm.snapshot import *
from tests.constants import *
class TestSnapshot(object):
def setup(self):
self.tmpdir = tempfile.mkdtemp()
def teardown(self):
shutil.rmtree(self.tmpdir)
def test_snap... | snapshot.register(evt, bad_callback)
assert_raises(CallbackFailuresError, snapshot.start, lv)
snapshot.unregister(evt, bad_callback)
if snapshot.sigmgr._handlers:
raise Exception("WTF. sigmgr handlers still exist when checking event => %r", evt) | conditional_block | |
test_snapshot.py | import shutil
from nose.tools import *
from holland.lib.lvm import LogicalVolume
from holland.lib.lvm.snapshot import *
from tests.constants import *
class TestSnapshot(object):
def setup(self):
self.tmpdir = tempfile.mkdtemp()
def | (self):
shutil.rmtree(self.tmpdir)
def test_snapshot_fsm(self):
lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV))
name = lv.lv_name + '_snapshot'
size = 1 # extent
snapshot = Snapshot(name, size, self.tmpdir)
snapshot.start(lv)
def test_snapshot_fsm_with... | teardown | identifier_name |
test_snapshot.py | import shutil
from nose.tools import *
from holland.lib.lvm import LogicalVolume
from holland.lib.lvm.snapshot import *
from tests.constants import *
class TestSnapshot(object):
def setup(self):
self.tmpdir = tempfile.mkdtemp()
def teardown(self):
shutil.rmtree(self.tmpdir)
def test_snap... | raise Exception("Oooh nooo!")
for evt in ('initialize', 'pre-snapshot', 'post-snapshot',
'pre-mount', 'post-mount', 'pre-unmount', 'post-unmount',
'pre-remove', 'post-remove', 'finish'):
snapshot.register(evt, bad_callback)
assert_rai... | random_line_split | |
test_snapshot.py | import shutil
from nose.tools import *
from holland.lib.lvm import LogicalVolume
from holland.lib.lvm.snapshot import *
from tests.constants import *
class TestSnapshot(object):
def setup(self):
self.tmpdir = tempfile.mkdtemp()
def teardown(self):
shutil.rmtree(self.tmpdir)
def test_snap... |
snapshot.register('pre-mount', handle_event)
snapshot.register('post-mount', handle_event)
snapshot.start(lv)
def test_snapshot_fsm_with_failures(self):
lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV))
name = lv.lv_name + '_snapshot'
size = 1 # extent
... | pass | identifier_body |
cli.py | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------------------------------... |
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
class ComplexCLI(AliasedGroup):
'''Custom subclass to load subcommands dynamically from a plugin folder.
It looks in `commands` folder for subcommands.
This is borrowed from `click` examples of complex.
'''
def list_commands(... | return self._get_command(ctx, matches[0]) | conditional_block |
cli.py | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team. | # The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
import click
from os import listdir
from os.path import abspath, join, dirname, splitext
from .config import Configuration
_CONTEXT_SETTINGS = dict(
# allo... | #
# Distributed under the terms of the Modified BSD License.
# | random_line_split |
cli.py | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------------------------------... | (click.Group):
'''Custom subclass of click.Group to enable alias for commands.
This implements a subclass of click.Group that accepts a prefix
for a command. If there were a (sub)command called "push", it would
accept "pus" as an alias (as long as it is unique).
This is borrowed from `click` examp... | AliasedGroup | identifier_name |
cli.py | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------------------------------... |
class ComplexCLI(AliasedGroup):
'''Custom subclass to load subcommands dynamically from a plugin folder.
It looks in `commands` folder for subcommands.
This is borrowed from `click` examples of complex.
'''
def list_commands(self, ctx):
rv = []
cmd_folder = abspath(join(dirname(... | matches = [x for x in self.list_commands(ctx)
if x.lower().startswith(cmd_name.lower())]
if not matches:
return
elif len(matches) == 1:
return self._get_command(ctx, matches[0])
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches))) | identifier_body |
ivec-tag.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 ... | {
let (tx, rx) = channel::<Vec<u8>>();
let _prod = task::spawn(proc() {
producer(&tx)
});
let _data: Vec<u8> = rx.recv();
} | identifier_body | |
ivec-tag.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 ... | tx.send(
vec!(1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8,
13u8));
}
pub fn main() {
let (tx, rx) = channel::<Vec<u8>>();
let _prod = task::spawn(proc() {
producer(&tx)
});
let _data: Vec<u8> = rx.recv();
} | // except according to those terms.
use std::task;
fn producer(tx: &Sender<Vec<u8>>) { | random_line_split |
ivec-tag.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 ... | (tx: &Sender<Vec<u8>>) {
tx.send(
vec!(1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8,
13u8));
}
pub fn main() {
let (tx, rx) = channel::<Vec<u8>>();
let _prod = task::spawn(proc() {
producer(&tx)
});
let _data: Vec<u8> = rx.recv();
}
| producer | identifier_name |
types.service.ts | import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { EVE } from '../../shared/eve.helper';
import { IServerResponse, ITypesData } from '../../shared/interface.helper';
import { BaseService } from './base.service';
@Injectable()
export class TypesService extend... |
return response;
}
}
| {
return undefined;
} | conditional_block |
types.service.ts | import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { EVE } from '../../shared/eve.helper';
import { IServerResponse, ITypesData } from '../../shared/interface.helper';
import { BaseService } from './base.service';
@Injectable()
export class TypesService extend... | this.typesCache = Array.from(new Set(this.typesCache));
}
return response.data;
}
public async getType(typeId: number): Promise<ITypesData | undefined> {
const url = EVE.getUniverseTypesUrl(typeId);
const response = await this.http.get<any>(url).toPromise<ITypesData... | }
if (response.data) {
this.typesCache.push(...response.data); | random_line_split |
types.service.ts | import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { EVE } from '../../shared/eve.helper';
import { IServerResponse, ITypesData } from '../../shared/interface.helper';
import { BaseService } from './base.service';
@Injectable()
export class TypesService extend... | (...typeIds: number[]): Promise<ITypesData[] | undefined> {
const typesFromCache = this.typesCache.filter((type) => typeIds.includes(type.type_id));
if (typesFromCache.length === typeIds.length) {
return typesFromCache;
}
const cachedTypeIds = typesFromCache.map((type) => t... | getTypes | identifier_name |
types.service.ts | import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { EVE } from '../../shared/eve.helper';
import { IServerResponse, ITypesData } from '../../shared/interface.helper';
import { BaseService } from './base.service';
@Injectable()
export class TypesService extend... |
return response.data;
}
public async getType(typeId: number): Promise<ITypesData | undefined> {
const url = EVE.getUniverseTypesUrl(typeId);
const response = await this.http.get<any>(url).toPromise<ITypesData>().catch(this.catchHandler);
if (response instanceof HttpErrorRespon... | {
const typesFromCache = this.typesCache.filter((type) => typeIds.includes(type.type_id));
if (typesFromCache.length === typeIds.length) {
return typesFromCache;
}
const cachedTypeIds = typesFromCache.map((type) => type.type_id);
const missingTypes = typeIds.filter(... | identifier_body |
VariableIdPattern.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is ... | def get_value_pattern(self):
return r'oval:[A-Za-z0-9_\-\.]+:var:[1-9][0-9]*' | identifier_body | |
VariableIdPattern.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is ... |
import logging
from scap.model.xs.StringType import StringType
logger = logging.getLogger(__name__)
class VariableIdPattern(StringType):
# <xsd:pattern value="oval:[A-Za-z0-9_\-\.]+:var:[1-9][0-9]*"/>
def get_value_pattern(self):
return r'oval:[A-Za-z0-9_\-\.]+:var:[1-9][0-9]*' | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PySCAP. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
VariableIdPattern.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is ... | (self):
return r'oval:[A-Za-z0-9_\-\.]+:var:[1-9][0-9]*'
| get_value_pattern | identifier_name |
conf.js | /* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
* Copyright (c) 2010 Mr.doob, rhyolight, bebraw
*/
var DEBUG = true;
var BRUSHES = ["sketchy", "shaded", "chrome", "blur", "fur", "longfur", "web",
"simple", "squares", "ribbon", "circles", "grid", "stringy", "curvy",
"e... | 'decrease': 'w',
'increase': 'e',
'decreaseJitter': 'r',
'increaseJitter': 't'
},
'opacity': {
'toggle': 'a',
'decrease': 's',
'increase': 'd',
'decreaseJitter': 'f',
'increaseJitter': 'g'
... | 'toggle': 'q', | random_line_split |
Medium.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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
# rights to use, copy, modify, merge, publish... | if self in obj._Mediums:
obj._Mediums.remove(self)
self._Assets.remove(obj) | conditional_block | |
Medium.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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
# rights to use, copy, modify, merge, publish... | (self, kind="gas", volumeSpec=0.0, Specification=None, Assets=None, *args, **kw_args):
"""Initialises a new 'Medium' instance.
@param kind: Kind of this medium. Values are: "gas", "liquid", "solid"
@param volumeSpec: The volume of the medium specified for this application. Note that the actual ... | __init__ | identifier_name |
Medium.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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
# rights to use, copy, modify, merge, publish... |
Specification = property(getSpecification, setSpecification)
def getAssets(self):
return self._Assets
def setAssets(self, value):
for p in self._Assets:
filtered = [q for q in p.Mediums if q != self]
self._Assets._Mediums = filtered
for r in value... | if self._Specification is not None:
filtered = [x for x in self.Specification.Mediums if x != self]
self._Specification._Mediums = filtered
self._Specification = value
if self._Specification is not None:
if self not in self._Specification._Mediums:
se... | identifier_body |
Medium.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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
# rights to use, copy, modify, merge, publish... | self._Specification._Mediums = filtered
self._Specification = value
if self._Specification is not None:
if self not in self._Specification._Mediums:
self._Specification._Mediums.append(self)
Specification = property(getSpecification, setSpecification)
d... |
def setSpecification(self, value):
if self._Specification is not None:
filtered = [x for x in self.Specification.Mediums if x != self] | random_line_split |
serverdiscovery-winjs.js | define([], function () {
'use strict';
function listenerSession(resolve, timeoutMs) {
var listenerSocket = null;
var serviceName = "7359";
var servers = [];
var timeout;
var stringToSend = "who is EmbyServer?|emby";
function closeListenerSocket() {
... | ventArguments) {
try {
// Interpret the incoming datagram's entire contents as a string.
var stringLength = eventArguments.getDataReader().unconsumedBufferLength;
var receivedMessage = eventArguments.getDataReader().readString(stringLength);
i... | MessageReceived(e | identifier_name |
serverdiscovery-winjs.js | define([], function () {
'use strict';
function listenerSession(resolve, timeoutMs) {
|
function startListener(eventObject) {
listenerSocket = new Windows.Networking.Sockets.DatagramSocket();
listenerSocket.addEventListener("messagereceived", onMessageReceived);
// Start listen operation.
listenerSocket.bindServiceNameAsync("").done(function () {
... |
var listenerSocket = null;
var serviceName = "7359";
var servers = [];
var timeout;
var stringToSend = "who is EmbyServer?|emby";
function closeListenerSocket() {
if (timeout) {
clearTimeout(timeout);
}
if (listenerS... | identifier_body |
serverdiscovery-winjs.js | define([], function () {
'use strict';
function listenerSession(resolve, timeoutMs) {
var listenerSocket = null;
var serviceName = "7359";
var servers = [];
var timeout;
var stringToSend = "who is EmbyServer?|emby";
function closeListenerSocket() {
... | }
};
}); |
new listenerSession(resolve, timeoutMs);
}); | random_line_split |
serverdiscovery-winjs.js | define([], function () {
'use strict';
function listenerSession(resolve, timeoutMs) {
var listenerSocket = null;
var serviceName = "7359";
var servers = [];
var timeout;
var stringToSend = "who is EmbyServer?|emby";
function closeListenerSocket() {
... | if (listenerSocket !== null) {
// The call below explicitly closes the socket, freeing the UDP port that it is currently bound to.
listenerSocket.close();
listenerSocket = null;
}
resolve(servers);
}
function startListe... | clearTimeout(timeout);
}
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.