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 |
|---|---|---|---|---|
example-uncommented.rs | #![feature(custom_attribute,plugin)]
#![plugin(tag_safe)]
#![allow(dead_code)]
/// RAII primitive spinlock
struct Spinlock;
/// Handle to said spinlock
struct HeldSpinlock(&'static Spinlock);
/// RAII IRQ hold
struct IRQLock;
/// Spinlock that also disables IRQs
struct IrqSpinlock(Spinlock);
static S_NON_IRQ_SPINLOC... |
// vim: ts=4 sw=4 expandtab
| {
irq_handler();
} | identifier_body |
example-uncommented.rs | #![feature(custom_attribute,plugin)]
#![plugin(tag_safe)]
#![allow(dead_code)]
/// RAII primitive spinlock
struct Spinlock;
/// Handle to said spinlock
struct HeldSpinlock(&'static Spinlock);
/// RAII IRQ hold
struct IRQLock;
/// Spinlock that also disables IRQs
struct IrqSpinlock(Spinlock);
static S_NON_IRQ_SPINLOC... | irq_handler();
}
// vim: ts=4 sw=4 expandtab | {
HeldSpinlock(l)
}
fn main() { | random_line_split |
reader.rs | .reader.table_start as u64 {
return None;
}
}
Err(_) => return None,
}
// We're in the Footer/Hash Table of the file, no more items.
let mut buf: [u8; 8] = [0; 8];
{
let mut chunk = self.reader.file.take(8);
... | as_writer | identifier_name | |
reader.rs | _vals = cdb_reader.get(key);
/// assert_eq!(stored_vals.len(), 1);
/// assert_eq!(&stored_vals[0][..], &"value".as_bytes()[..]);
///
/// // The CDB contains only one entry:
/// assert_eq!(cdb_reader.len(), 1);
///
/// // Accessing a key that isn't in the CDB:
/// let non_existing_key = "non_existing_key".as_bytes();
//... | /// # // Do it again to make sure the iterator doesn't consume and lifetimes
/// # // work as expected.
/// # i = 0;
/// # for (_, v) in cdb_reader.into_iter() {
/// # i += 1;
/// # let s = &i.to_string();
/// # let val = s.as_bytes();
/// # assert_eq!(&v[..], &val[..]);
/// # }
/// # assert_eq!(len, i)... | /// # assert_eq!(len, i);
/// # | random_line_split |
reader.rs | = cdb_reader.get(key);
/// assert_eq!(stored_vals.len(), 1);
/// assert_eq!(&stored_vals[0][..], &"value".as_bytes()[..]);
///
/// // The CDB contains only one entry:
/// assert_eq!(cdb_reader.len(), 1);
///
/// // Accessing a key that isn't in the CDB:
/// let non_existing_key = "non_existing_key".as_bytes();
/// let... |
/// Return a `Vec` of all the keys in this Read Only CDB.
///
/// Keep in mind that if there're duplicated keys, they will appear
/// multiple times in the resulting `Vec`.
pub fn keys(&mut self) -> Vec<Vec<u8>> {
let mut keys: Vec<Vec<u8>> = vec![];
for item in self.into_iter() {
... | {
let mut i = 0;
let mut values: Vec<Vec<u8>> = vec![];
loop {
match self.get_from_pos(key, i) {
Ok(v) => values.push(v),
Err(_) => break,
}
i += 1;
}
values
} | identifier_body |
product.js | var express = require('express');
var router = express.Router();
var spider = require("./spider");
router.get("/info",function(req,res,next){
spider(`/product/iteminfo?device=iphone&channel=h5&swidth=375&sheight=667&zoneId=1479&v=2.3.0&terminal=wap&page=https%3A%2F%2Fm.haoshiqi.net%2F%23detail%3Fsid%3D14369%26channel... | res.send(JSON.parse(data).data.graphicDetail); //返回产品的详细图片信息
});
})
module.exports =router; | random_line_split | |
path.rs | use ::inflector::Inflector;
use ::regex::Regex;
use ::syn::Ident;
use ::quote::Tokens;
use ::yaml_rust::Yaml;
use infer::method;
use infer::TokensResult;
fn mod_ident(path: &str) -> Ident {
let rustified = path.replace('/', " ").trim().to_snake_case();
let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap()... | #(#method_impls)*
}
})
}
#[cfg(tests)]
mod tests {
use super::*;
#[test]
fn leading_slash() {
assert_eq!(mod_ident("/foo"), Ident::new("foo"));
}
#[test]
fn both_slash() {
assert_eq!(mod_ident("/foo/"), Ident::new("foo"));
}
#[test]
fn no_s... | random_line_split | |
path.rs | use ::inflector::Inflector;
use ::regex::Regex;
use ::syn::Ident;
use ::quote::Tokens;
use ::yaml_rust::Yaml;
use infer::method;
use infer::TokensResult;
fn mod_ident(path: &str) -> Ident {
let rustified = path.replace('/', " ").trim().to_snake_case();
let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap()... |
}
Ok(quote! {
#[allow(non_snake_case)]
pub mod #path_mod {
#[allow(unused_imports)]
use ::tapioca::Body;
use ::tapioca::Client;
use ::tapioca::Url;
use ::tapioca::header;
use ::tapioca::response::Response;
#[al... | {
path_level_structs = param_structs;
} | conditional_block |
path.rs | use ::inflector::Inflector;
use ::regex::Regex;
use ::syn::Ident;
use ::quote::Tokens;
use ::yaml_rust::Yaml;
use infer::method;
use infer::TokensResult;
fn mod_ident(path: &str) -> Ident {
let rustified = path.replace('/', " ").trim().to_snake_case();
let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap()... |
#[test]
fn multipart_multiresource() {
assert_eq!(mod_ident("/foo/{id}/bar/{bar_id}"), Ident::new("foo__id__bar__bar_id_"));
}
}
| {
assert_eq!(mod_ident("/foo/{id}/bar"), Ident::new("foo__id__bar"));
} | identifier_body |
path.rs | use ::inflector::Inflector;
use ::regex::Regex;
use ::syn::Ident;
use ::quote::Tokens;
use ::yaml_rust::Yaml;
use infer::method;
use infer::TokensResult;
fn mod_ident(path: &str) -> Ident {
let rustified = path.replace('/', " ").trim().to_snake_case();
let re = Regex::new(r"\{(?P<resource>[^}]+)_\}").unwrap()... | () {
assert_eq!(mod_ident("/foo/{id}/bar"), Ident::new("foo__id__bar"));
}
#[test]
fn multipart_multiresource() {
assert_eq!(mod_ident("/foo/{id}/bar/{bar_id}"), Ident::new("foo__id__bar__bar_id_"));
}
}
| multipart_resource | identifier_name |
where-clauses.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, other: &T) -> bool {
self == other
}
fn equals<U,X>(&self, this: &U, other: &U, x: &X, y: &X) -> bool
where U: Eq, X: Eq {
this == other && x == y
}
}
fn equal<T>(x: &T, y: &T) -> bool where T: Eq {
x == y
}
fn main() {
println!("{}", equal(&1, &2));
println... | equal | identifier_name |
where-clauses.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 ... | {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} | identifier_body | |
where-clauses.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 ... |
impl<T> Equal for T where T: Eq {
fn equal(&self, other: &T) -> bool {
self == other
}
fn equals<U,X>(&self, this: &U, other: &U, x: &X, y: &X) -> bool
where U: Eq, X: Eq {
this == other && x == y
}
}
fn equal<T>(x: &T, y: &T) -> bool where T: Eq {
x == y
}
fn main() {... | } | random_line_split |
setup.py | #!/usr/bin/env python
import os
import sys
from setuptools import setup
SETUP_DIR = os.path.dirname(__file__)
README = os.path.join(SETUP_DIR, "README.rst")
NEEDS_PYTEST = {"pytest", "test", "ptr"}.intersection(sys.argv)
PYTEST_RUNNER = ["pytest-runner", "pytest-cov"] if NEEDS_PYTEST else []
setup(
name="cwl-u... | "Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Py... | "License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent", | random_line_split |
completion.rs | str) {
(**self).update(line, start, elected)
}
}
macro_rules! box_completer {
($($id: ident)*) => {
$(
impl<C: ?Sized + Completer> Completer for $id<C> {
type Candidate = C::Candidate;
fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<S... | (
mut input: String,
esc_char: Option<char>,
break_chars: &[u8],
quote: Quote,
) -> String {
if quote == Quote::Single {
return input; // no escape in single quotes
}
let n = input
.bytes()
.filter(|b| memchr(*b, break_chars).is_some())
.count();
if n == 0... | escape | identifier_name |
completion.rs | esc_char: Option<char>,
break_chars: &[u8],
quote: Quote,
) -> Result<Vec<Pair>> {
use dirs::home_dir;
use std::env::current_dir;
let sep = path::MAIN_SEPARATOR;
let (dir_name, file_name) = match path.rfind(sep) {
Some(idx) => path.split_at(idx + sep.len_utf8()),
None => ("", p... | random_line_split | ||
completion.rs |
}
impl<'c, C: ?Sized + Completer> Completer for &'c C {
type Candidate = C::Candidate;
fn complete(&self, line: &str, pos: usize) -> Result<(usize, Vec<Self::Candidate>)> {
(**self).complete(line, pos)
}
fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) {
(**self).... | {
unreachable!()
} | identifier_body | |
completion.rs | _word_break_characters, rl_completer_word_break_characters
#[cfg(unix)]
static DEFAULT_BREAK_CHARS: [u8; 18] = [
b' ', b'\t', b'\n', b'"', b'\\', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&',
b'{', b'(', b'\0',
];
#[cfg(unix)]
static ESCAPE_CHAR: Option<char> = Some('\\');
// Remove \ to make fil... | {
return None;
} | conditional_block | |
app.routing.ts | import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login.component';
import { LoggedInGuard } from './logged-in.guard';
import { TransactionComponent } from './transaction.component';
import { TransactionDetailComponent } from... | {
path: 'dashboard',
component: DashboardComponent,
canActivate: [LoggedInGuard]
},
{
path: 'accounts',
component: AccountComponent,
canActivate: [LoggedInGuard]
},
{
path: 'login',
component: LoginComponent
},
{
path: '... | canActivate: [LoggedInGuard]
}, | random_line_split |
ragged_tensor_value.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self, values, row_splits):
"""Creates a `RaggedTensorValue`.
Args:
values: A numpy array of any type and shape; or a RaggedTensorValue.
row_splits: A 1-D int32 or int64 numpy array.
"""
if not (isinstance(row_splits, (np.ndarray, np.generic)) and
row_splits.dtype in (np.int64, ... | __init__ | identifier_name |
ragged_tensor_value.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
if not isinstance(values, (np.ndarray, np.generic, RaggedTensorValue)):
raise TypeError("values must be a numpy array or a RaggedTensorValue")
if (isinstance(values, RaggedTensorValue) and
row_splits.dtype != values.row_splits.dtype):
raise ValueError("row_splits and values.row_splits must ... | raise TypeError("row_splits must be a 1D int32 or int64 numpy array") | conditional_block |
ragged_tensor_value.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def to_list(self):
"""Returns this ragged tensor value as a nested Python list."""
if isinstance(self._values, RaggedTensorValue):
values_as_list = self._values.to_list()
else:
values_as_list = self._values.tolist()
return [
values_as_list[self._row_splits[i]:self._row_splits[i +... | return "tf.RaggedTensorValue(values=%r, row_splits=%r)" % (self._values,
self._row_splits) | identifier_body |
ragged_tensor_value.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def __repr__(self):
return "tf.RaggedTensorValue(values=%r, row_splits=%r)" % (self._values,
self._row_splits)
def to_list(self):
"""Returns this ragged tensor value as a nested Python list."""
if isinstance(self._values, RaggedTensorValue... | return [RowPartition.from_row_splits(rs) for rs in self.nested_row_splits]
def __str__(self):
return "<tf.RaggedTensorValue %s>" % self.to_list() | random_line_split |
cupshelpers.py | attrs.has_key('requesting-user-name-allowed'):
self.except_users = attrs['requesting-user-name-allowed']
self.default_allow = False
elif attrs.has_key('requesting-user-name-denied'):
self.except_users = attrs['requesting-user-name-denied']
self.except_users_string = ... | result = cups.PPD (self._ppd)
except cups.IPPError, (e, m):
if e == cups.IPP_NOT_FOUND:
result = False
else:
raise
if result == None and self._ppd != None:
result = cups.PPD (self._ppd)
retu... | self._ppd = self.connection.getPPD(self.name) | random_line_split |
cupshelpers.py | printers
def parseDeviceID (id):
"""
Parse an IEEE 1284 Device ID, so that it may be indexed by field name.
@param id: IEEE 1284 Device ID, without the two leading length bytes
@type id: string
@returns: dict indexed by field name
"""
id_dict = {}
pieces = id.split(";")
for piece ... | """
Set the PPD page size according to locale.
@param ppd: PPD
@type ppd: cups.PPD object
@param language: language, as given by the first element of
locale.setlocale
@type language: string
"""
# Just set the page size to A4 or Letter, that's all.
# Use the same method CUPS uses.
... | identifier_body | |
cupshelpers.py |
if attrs.has_key(name+"-supported"):
supported = attrs[name+"-supported"]
self.possible_attributes[name] = (value, supported)
elif (not key.endswith ("-supported") and
key != 'job-sheets-default' and
... | if key.endswith("-default"):
name = key[:-len("-default")]
if name in ["job-sheets", "printer-error-policy",
"printer-op-policy", # handled below
"notify-events", # cannot be set
"document-format", # cann... | conditional_block | |
cupshelpers.py | 'MFG:HEWLETT-PACKARD;MDL:DESKJET 990C;CMD:MLC,PCL,PML;CLS:PRINTER;DES:Hewlett-Packard DeskJet 990C;SN:US05N1J00XLG;S:00808880800010032C1000000C2000000;P:0800,FL,B0;J: ;'
self.id_dict = parseDeviceID (self.id)
s = uri.find("serial=")
if s != -1 and not self.id_dict.get ('SN'... | add_missing | identifier_name | |
event_pad_axis.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use gdk_sys;
use glib::translate::*;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash... |
pub fn get_mode(&self) -> u32 {
self.as_ref().mode
}
pub fn get_value(&self) -> f64 {
self.as_ref().value
}
}
| {
self.as_ref().index
} | identifier_body |
event_pad_axis.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use gdk_sys;
use glib::translate::*;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash... | (&self) -> u32 {
self.as_ref().group
}
pub fn get_index(&self) -> u32 {
self.as_ref().index
}
pub fn get_mode(&self) -> u32 {
self.as_ref().mode
}
pub fn get_value(&self) -> f64 {
self.as_ref().value
}
}
| get_group | identifier_name |
event_pad_axis.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use gdk_sys;
use glib::translate::*;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash... | }
pub fn get_value(&self) -> f64 {
self.as_ref().value
}
} | pub fn get_mode(&self) -> u32 {
self.as_ref().mode | random_line_split |
parameters.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... |
const pack = tar.pack();
async function write(nodes: Node[], regionTag: string) {
const markdown = mdProcessor.stringify(root(nodes));
// write markdown file
pack.entry(
{
name: `documentation/parameters/${regionTag}.md`,
},
`<!--- This is a generated file, do not edit! -->\n... | const main = async (argv: any) => {
const spec = (await $RefParser.dereference(
JSON.parse(readFileSync(argv.spec).toString()) as OpenAPIV3.Document
)) as OpenAPIV3.Document; | random_line_split |
parameters.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... |
}
);
const required = parameters.filter(
(p: OpenAPIV3.ParameterObject) => p.required
);
const optional = parameters.filter(
(p: OpenAPIV3.ParameterObject) => !p.required
);
if (required.length) {
nodes.push(
htmlNode(
`<h2 id="${options.requiredHeading.toLowerCase().replac... | {
return a.name < b.name ? -1 : 1;
} | conditional_block |
parameters.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... | );
}
for (const key in spec.paths!) {
// Custom handling for geocoding and reverse geocoding
if (key === "/maps/api/geocode/json") {
const parameters = spec.paths![key]!.get!
.parameters! as OpenAPIV3.ParameterObject[];
const geocode = {
regionTag: "maps_http_parameters_geo... | {
const markdown = mdProcessor.stringify(root(nodes));
// write markdown file
pack.entry(
{
name: `documentation/parameters/${regionTag}.md`,
},
`<!--- This is a generated file, do not edit! -->\n<!--- [START ${regionTag}] -->\n${markdown}\n<!--- [END ${regionTag}] -->`
);
... | identifier_body |
parameters.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... | (nodes: Node[], regionTag: string) {
const markdown = mdProcessor.stringify(root(nodes));
// write markdown file
pack.entry(
{
name: `documentation/parameters/${regionTag}.md`,
},
`<!--- This is a generated file, do not edit! -->\n<!--- [START ${regionTag}] -->\n${markdown}\n<!--- ... | write | identifier_name |
mod.rs | mod serialize;
/// Handle to a dock
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DockHandle(pub u64);
/// Holds information about the plugin view, data and handle
#[derive(Debug, Clone)]
pub struct Dock {
pub handle: DockHandle,
pub plugin_name: String,
pub plugin_data: Option<Vec<String>>,
}
impl... |
}
#[cfg(test)]
mod test {
extern crate serde_json;
use super::{Dock, DockHandle};
#[test]
fn test_dockhandle_serialize() {
let handle_in = DockHandle(0x1337);
let serialized = serde_json::to_string(&handle_in).unwrap();
let handle_out: DockHandle = serde_json::from_str(&serial... | {
Dock {
handle: dock_handle,
plugin_name: plugin_name.to_owned(),
plugin_data: None,
}
} | identifier_body |
mod.rs | mod serialize;
/// Handle to a dock
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DockHandle(pub u64);
/// Holds information about the plugin view, data and handle
#[derive(Debug, Clone)]
pub struct Dock {
pub handle: DockHandle,
pub plugin_name: String,
pub plugin_data: Option<Vec<String>>,
}
impl... | let dock_in = Dock {
handle: DockHandle(1),
plugin_name: "disassembly".to_owned(),
plugin_data: None,
};
let serialized = serde_json::to_string(&dock_in).unwrap();
let dock_out: Dock = serde_json::from_str(&serialized).unwrap();
assert_eq!(do... | #[test]
fn test_dock_serialize_0() { | random_line_split |
mod.rs | mod serialize;
/// Handle to a dock
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DockHandle(pub u64);
/// Holds information about the plugin view, data and handle
#[derive(Debug, Clone)]
pub struct Dock {
pub handle: DockHandle,
pub plugin_name: String,
pub plugin_data: Option<Vec<String>>,
}
impl... | () {
let dock_in = Dock {
handle: DockHandle(1),
plugin_name: "registers".to_owned(),
plugin_data: Some(vec!["some_data".to_owned(), "more_data".to_owned()]),
};
let serialized = serde_json::to_string(&dock_in).unwrap();
let dock_out: Dock = serde_jso... | test_dock_serialize_1 | identifier_name |
camera.js | var win;
function fireUpTheCamera()
{
Ti.Media.showCamera({
success : function(event){
Ti.API.info(event);
var cropRect = event.cropRect;
var image = event.media;
Ti.API.info("image :"+image);
Ti.API.debug('Our type was: '+event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
... | function call_fun() {
win = Ti.UI.createWindow();
if (Ti.Platform.osname === 'android') {
win.addEventListener('open', function(e) {
fireUpTheCamera();
});
} else {
fireUpTheCamera();
}
return win;
};
module.exports = call_fun; | random_line_split | |
camera.js | var win;
function fireUpTheCamera()
{
Ti.Media.showCamera({
success : function(event){
Ti.API.info(event);
var cropRect = event.cropRect;
var image = event.media;
Ti.API.info("image :"+image);
Ti.API.debug('Our type was: '+event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
... | ;
module.exports = call_fun; | {
win = Ti.UI.createWindow();
if (Ti.Platform.osname === 'android') {
win.addEventListener('open', function(e) {
fireUpTheCamera();
});
} else {
fireUpTheCamera();
}
return win;
} | identifier_body |
camera.js | var win;
function fireUpTheCamera()
{
Ti.Media.showCamera({
success : function(event){
Ti.API.info(event);
var cropRect = event.cropRect;
var image = event.media;
Ti.API.info("image :"+image);
Ti.API.debug('Our type was: '+event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
... |
return win;
};
module.exports = call_fun; | {
fireUpTheCamera();
} | conditional_block |
camera.js | var win;
function | ()
{
Ti.Media.showCamera({
success : function(event){
Ti.API.info(event);
var cropRect = event.cropRect;
var image = event.media;
Ti.API.info("image :"+image);
Ti.API.debug('Our type was: '+event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
var imageView = Ti.UI.createIm... | fireUpTheCamera | identifier_name |
test_joblib_2000fts.py | from joblib import Parallel, delayed
from epac import Methods
import numpy as np
from sklearn import datasets
from sklearn.svm import SVC
X, y = datasets.make_classification(n_samples=500,
n_features=200000,
n_informative=2,
... |
return None
data_list = [data, data, data, data, data, data]
Parallel(n_jobs=4, verbose=100)(delayed(map_func)(d)
for d in data_list)
| data['methods'].run(X=data["X"][train], y=data['y'][train]) | conditional_block |
test_joblib_2000fts.py | from joblib import Parallel, delayed
from epac import Methods
import numpy as np
from sklearn import datasets
from sklearn.svm import SVC
| n_features=200000,
n_informative=2,
random_state=1)
methods = Methods(*[SVC(C=1, kernel='linear'), SVC(C=1, kernel='rbf')])
data = {"X":X, 'y':y, "methods": methods}
# X = np.random.random((500, 200000))
... | X, y = datasets.make_classification(n_samples=500, | random_line_split |
test_joblib_2000fts.py | from joblib import Parallel, delayed
from epac import Methods
import numpy as np
from sklearn import datasets
from sklearn.svm import SVC
X, y = datasets.make_classification(n_samples=500,
n_features=200000,
n_informative=2,
... |
data_list = [data, data, data, data, data, data]
Parallel(n_jobs=4, verbose=100)(delayed(map_func)(d)
for d in data_list)
| from sklearn.cross_validation import StratifiedKFold
from sklearn import svm, cross_validation
kfold = StratifiedKFold(y=data['y'], n_folds=3)
# kfold = cross_validation.KFold(n=data.X.shape[0], n_folds=3)
# svc = SVC(C=1, kernel='linear')
for train, test in kfold:
# svc.fit(data['X'][train], data['y'][... | identifier_body |
test_joblib_2000fts.py | from joblib import Parallel, delayed
from epac import Methods
import numpy as np
from sklearn import datasets
from sklearn.svm import SVC
X, y = datasets.make_classification(n_samples=500,
n_features=200000,
n_informative=2,
... | (data):
from sklearn.cross_validation import StratifiedKFold
from sklearn import svm, cross_validation
kfold = StratifiedKFold(y=data['y'], n_folds=3)
# kfold = cross_validation.KFold(n=data.X.shape[0], n_folds=3)
# svc = SVC(C=1, kernel='linear')
for train, test in kfold:
# svc.fit(data['X'][train], ... | map_func | identifier_name |
overviewCtrl.js | angular.module('app.controllers')
.controller('overviewCtrl', function($scope,$state,$ionicModal,sharedInfo, Auth, User, currentAuth, $window) {
$scope.hasAPlan=false;
$scope.logout = function(){
Auth.$unauth();
}
console.log(currentAuth); |
Auth.$onAuth(function(authData){
if(!authData){
$state.go('login');
}
});
var user = User(currentAuth.uid);
user.$loaded().then(function(){
console.log(user);
if(user.$value === null){
console.log("plan not set");
}else{
$scope.info = user.info;
$scope.hasAPlan = tr... | random_line_split | |
overviewCtrl.js | angular.module('app.controllers')
.controller('overviewCtrl', function($scope,$state,$ionicModal,sharedInfo, Auth, User, currentAuth, $window) {
$scope.hasAPlan=false;
$scope.logout = function(){
Auth.$unauth();
}
console.log(currentAuth);
Auth.$onAuth(function(authData){
if(!authData) |
});
var user = User(currentAuth.uid);
user.$loaded().then(function(){
console.log(user);
if(user.$value === null){
console.log("plan not set");
}else{
$scope.info = user.info;
$scope.hasAPlan = true;
}
});
$ionicModal.fromTemplateUrl('templates/info/modalPreSetPlan.html', ... | {
$state.go('login');
} | conditional_block |
utils.js | import defined from '@xen-orchestra/defined'
import { find, forEach, includes, map } from 'lodash'
export const getDefaultNetworkForVif = (vif, destHost, pifs, networks) => {
const originNetwork = networks[vif.$network]
const originVlans = map(originNetwork.PIFs, pifId => pifs[pifId].vlan)
let destNetworkId = p... |
if (pif.management) {
defaultPif = pif
}
}
}),
intraPool ? {} : defaultPif
).$network
}
| {
return true
} | conditional_block |
utils.js | import defined from '@xen-orchestra/defined'
import { find, forEach, includes, map } from 'lodash'
export const getDefaultNetworkForVif = (vif, destHost, pifs, networks) => {
const originNetwork = networks[vif.$network]
const originVlans = map(originNetwork.PIFs, pifId => pifs[pifId].vlan)
let destNetworkId = p... |
return false
}
if (vlan !== -1 && includes(originVlans, vlan)) {
destNetworkId = $network
}
})
return destNetworkId
}
export const getDefaultMigrationNetwork = (intraPool, destHost, pools, pifs) => {
const migrationNetwork = pools[destHost.$pool].otherConfig['xo:migrationNetwork']
le... | if (networks[$network].name_label === originNetwork.name_label) {
destNetworkId = $network | random_line_split |
Rte.ts | RTE.default {
# Available: https://docs.typo3.org/typo3cms/extensions/rtehtmlarea/Configuration/PageTsconfig/interfaceConfiguration/Index.html
showButtons = bold, italic, underline, orderedlist, unorderedlist, left, center, right, subscript, superscript, insertcharacter, link, undo, redo, chMode, removeformat
... | # media tag
RTE.default.proc.overruleMode = ts_css,txdam_media
RTE.default.FE.proc.overruleMode = ts_css,txdam_media
## Classes for RTE (dropdown with classes)
RTE.classes.highlight {
name = Highlight
value = color:red;
}
RTE.default {
ignoreMainStyleOverride = 1
useCSS = 1
showTagFreeClasses = 1
... | }
| random_line_split |
demo-modal-range.ts | import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { CalendarModal, CalendarModalOptions } from '../ion2-calendar';
@Component({
selector: 'demo-modal-range',
template: `
<ion-button (click)="openCalendar()">
range
</ion-button>
`,
})
export class D... |
const event: any = await myCalendar.onDidDismiss();
const { data: date, role } = event;
if (role === 'done') {
this.dateRange = Object.assign(
{},
{
from: date.from.dateObj,
to: date.to.dateObj,
}
);
}
console.log(date);
console.log('role... | componentProps: { options },
});
myCalendar.present(); | random_line_split |
demo-modal-range.ts | import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { CalendarModal, CalendarModalOptions } from '../ion2-calendar';
@Component({
selector: 'demo-modal-range',
template: `
<ion-button (click)="openCalendar()">
range
</ion-button>
`,
})
export class D... | (public modalCtrl: ModalController) {}
async openCalendar() {
const options: CalendarModalOptions = {
pickMode: 'range',
title: 'RANGE',
defaultDateRange: this.dateRange,
clearLabel: 'CLEAR'
};
const myCalendar = await this.modalCtrl.create({
component: CalendarModal,
... | constructor | identifier_name |
demo-modal-range.ts | import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { CalendarModal, CalendarModalOptions } from '../ion2-calendar';
@Component({
selector: 'demo-modal-range',
template: `
<ion-button (click)="openCalendar()">
range
</ion-button>
`,
})
export class D... |
console.log(date);
console.log('role', role);
}
}
| {
this.dateRange = Object.assign(
{},
{
from: date.from.dateObj,
to: date.to.dateObj,
}
);
} | conditional_block |
demo-modal-range.ts | import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { CalendarModal, CalendarModalOptions } from '../ion2-calendar';
@Component({
selector: 'demo-modal-range',
template: `
<ion-button (click)="openCalendar()">
range
</ion-button>
`,
})
export class D... |
async openCalendar() {
const options: CalendarModalOptions = {
pickMode: 'range',
title: 'RANGE',
defaultDateRange: this.dateRange,
clearLabel: 'CLEAR'
};
const myCalendar = await this.modalCtrl.create({
component: CalendarModal,
componentProps: { options },
});
... | {} | identifier_body |
db_wbx.py | #self._u._write_oe(self._which, 0, 0xffff) # turn off all outputs
self.set_auto_tr(False)
def _lock_detect(self):
"""
@returns: the value of the VCO/PLL lock detect bit.
@rtype: 0 or 1
"""
if self._rx_read_io() & PLL_LOCK_DETECT:
return True
el... | (self, gain):
"""
Set the gain.
@param gain: gain in decibels
@returns True/False
"""
maxgain = self.gain_range()[1] - self._u.pga_max()
mingain = self.gain_range()[0]
if gain > maxgain:
pga_gain = gain-maxgain
assert pga_gain <= ... | set_gain | identifier_name |
db_wbx.py | Offset in Hz
"""
return self._lo_offset
class wbx_base_rx(wbx_base):
def __init__(self, usrp, which):
"""
@param usrp: instance of usrp.source_c
@param which: 0 or 1 corresponding to side RX_A or RX_B respectively.
"""
wbx_base.__init__(self, usrp, which)
... | return 32
elif self.P == 3:
return 64
else:
raise ValueError, "Prescaler out of range" | random_line_split | |
db_wbx.py | self.set_auto_tr(False)
def _lock_detect(self):
"""
@returns: the value of the VCO/PLL lock detect bit.
@rtype: 0 or 1
"""
if self._rx_read_io() & PLL_LOCK_DETECT:
return True
else: # Give it a second chance
if self._rx_read_io() ... | """
Return True if this is a quadrature device and ADC 0 is Q.
"""
return True | identifier_body | |
db_wbx.py | .
@param offset: offset in Hz
"""
self._lo_offset = offset
def lo_offset(self):
"""
Get amount by which LO is offset from requested tuning frequency.
@returns Offset in Hz
"""
return self._lo_offset
class wbx_base_rx(wbx_base):
def __init__(self, usrp, which):
"""
@param usrp: ins... | return 16 | conditional_block | |
index.js | /**
* Dependencies
* @type {exports}
*/
var fs = require('fs')
, q = require('q')
, _ = require('underscore')
, path = require('path')
, natural = require('natural')
, nounInflector = new natural.NounInflector()
, argv = require('optimist').argv
, path = require('path')
, generator = require('./model... | * @returns {boolean|*}
*/
function mkdir(path, root) {
var dirs = path.split('/')
, dir = dirs.shift()
, root = (root || '') + dir + '/';
try {
fs.mkdirSync(root);
}
catch(e) {
if (!fs.statSync(root).isDirectory()) {
throw new Error(e);
}
}
return !dirs.length || mkdir(dirs.join(... | /**
* Make a directory
* @param path
* @param root | random_line_split |
index.js | /**
* Dependencies
* @type {exports}
*/
var fs = require('fs')
, q = require('q')
, _ = require('underscore')
, path = require('path')
, natural = require('natural')
, nounInflector = new natural.NounInflector()
, argv = require('optimist').argv
, path = require('path')
, generator = require('./model... | {
var dirs = path.split('/')
, dir = dirs.shift()
, root = (root || '') + dir + '/';
try {
fs.mkdirSync(root);
}
catch(e) {
if (!fs.statSync(root).isDirectory()) {
throw new Error(e);
}
}
return !dirs.length || mkdir(dirs.join('/'), root);
} | identifier_body | |
index.js | /**
* Dependencies
* @type {exports}
*/
var fs = require('fs')
, q = require('q')
, _ = require('underscore')
, path = require('path')
, natural = require('natural')
, nounInflector = new natural.NounInflector()
, argv = require('optimist').argv
, path = require('path')
, generator = require('./model... | (path, root) {
var dirs = path.split('/')
, dir = dirs.shift()
, root = (root || '') + dir + '/';
try {
fs.mkdirSync(root);
}
catch(e) {
if (!fs.statSync(root).isDirectory()) {
throw new Error(e);
}
}
return !dirs.length || mkdir(dirs.join('/'), root);
} | mkdir | identifier_name |
index.js | /**
* Dependencies
* @type {exports}
*/
var fs = require('fs')
, q = require('q')
, _ = require('underscore')
, path = require('path')
, natural = require('natural')
, nounInflector = new natural.NounInflector()
, argv = require('optimist').argv
, path = require('path')
, generator = require('./model... |
}
return !dirs.length || mkdir(dirs.join('/'), root);
} | {
throw new Error(e);
} | conditional_block |
validation.ts | /*
* Copyright © 2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated... |
if (address.includes('.')) {
throw new Error(
'Address format does not match requirements. Address includes invalid character: `.`.',
);
}
const addressString = address.slice(0, -1);
const addressNumber = new BigNum(addressString);
if (addressNumber.cmp(new BigNum(MAX_EIGHT_BYTE_NUMBER)) > 0) {
throw n... | );
} | random_line_split |
validation.ts | /*
* Copyright © 2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated... |
if (/^[0-9]{1,21}[L|l]$/g.test(username)) {
return false;
}
if (!/^[a-z0-9!@$&_.]+$/g.test(username)) {
return false;
}
return true;
};
export const isSignature = (signature: string): boolean =>
/^[a-f0-9]{128}$/i.test(signature);
export const isGreaterThanZero = (amount: BigNum): boolean => amount.cmp(0... |
return false;
}
| conditional_block |
smoke.rs | use futures::StreamExt;
use opentelemetry::global::shutdown_tracer_provider;
use opentelemetry::trace::{Span, SpanKind, Tracer};
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_proto::tonic::collector::trace::v1::{
trace_service_server::{TraceService, TraceServiceServer},
ExportTraceServiceRequest, ... | () {
println!("Starting server setup...");
let (addr, mut req_rx) = setup().await;
{
println!("Installing tracer...");
let mut metadata = tonic::metadata::MetadataMap::new();
metadata.insert("x-header-key", "header-value".parse().unwrap());
let tracer = opentelemetry_otlp::n... | smoke_tracer | identifier_name |
smoke.rs | use futures::StreamExt;
use opentelemetry::global::shutdown_tracer_provider;
use opentelemetry::trace::{Span, SpanKind, Tracer};
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_proto::tonic::collector::trace::v1::{
trace_service_server::{TraceService, TraceServiceServer},
ExportTraceServiceRequest, ... |
s
});
let (req_tx, req_rx) = mpsc::channel(10);
let service = TraceServiceServer::new(MockServer::new(req_tx));
tokio::task::spawn(async move {
tonic::transport::Server::builder()
.add_service(service)
.serve_with_incoming(stream)
.await
... | {
println!("Got new conn at {}", s.peer_addr().unwrap());
} | conditional_block |
smoke.rs | use futures::StreamExt;
use opentelemetry::global::shutdown_tracer_provider;
use opentelemetry::trace::{Span, SpanKind, Tracer};
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_proto::tonic::collector::trace::v1::{
trace_service_server::{TraceService, TraceServiceServer},
ExportTraceServiceRequest, ... | .with_metadata(metadata),
)
.install_batch(opentelemetry::runtime::Tokio)
.expect("failed to install");
println!("Sending span...");
let mut span = tracer
.span_builder("my-test-span")
.with_kind(SpanKind::Server)
... | random_line_split | |
smoke.rs | use futures::StreamExt;
use opentelemetry::global::shutdown_tracer_provider;
use opentelemetry::trace::{Span, SpanKind, Tracer};
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_proto::tonic::collector::trace::v1::{
trace_service_server::{TraceService, TraceServiceServer},
ExportTraceServiceRequest, ... | let mut span = tracer
.span_builder("my-test-span")
.with_kind(SpanKind::Server)
.start(&tracer);
span.add_event("my-test-event", vec![]);
span.end();
shutdown_tracer_provider();
}
println!("Waiting for request...");
let req = req_rx.recv... | {
println!("Starting server setup...");
let (addr, mut req_rx) = setup().await;
{
println!("Installing tracer...");
let mut metadata = tonic::metadata::MetadataMap::new();
metadata.insert("x-header-key", "header-value".parse().unwrap());
let tracer = opentelemetry_otlp::new_... | identifier_body |
mutation-drift-selection.py | the sequences together will have count *N*.
# <codecell>
pop = {}
# <codecell>
pop["AAAAAAAAAA"] = 40
# <codecell>
pop["AAATAAAAAA"] = 30
# <codecell>
pop["AATTTAAAAA"] = 30
# <markdowncell>
# *Map haplotype string to fitness float.*
# <codecell>
fitness = {}
# <codecell>
fitness["AAAAAAAAAA"] = 1.0
# <... |
return diffs / float(length)
# <codecell>
def get_diversity(population):
haplotypes = population.keys()
haplotype_count = len(haplotypes)
diversity = 0
for i in range(haplotype_count):
for j in range(haplotype_count):
haplotype_a = haplotypes[i]
haplotype_b = haplo... | if chr_a != chr_b:
diffs += 1 | conditional_block |
mutation-drift-selection.py |
# A Wright-Fisher model has a fixed population size *N* and discrete non-overlapping generations. Each generation, each individual has a random number of offspring whose mean is proportional to the individual's fitness. Each generation, mutation may occur. Mutations may increase or decrease individual's fitness, which... |
# Wright-Fisher model of mutation, selection and random genetic drift
# <markdowncell> | random_line_split | |
mutation-drift-selection.py | per individual per site
# <codecell>
def get_mutation_count():
mean = mutation_rate * pop_size * seq_length
return np.random.poisson(mean)
# <codecell>
def get_random_haplotype():
haplotypes = pop.keys()
frequencies = [x/float(pop_size) for x in pop.values()]
total = sum(frequencies)
frequ... | minor_allele_frequency = 0.0
pop_at_generation = history[generation]
for haplotype in pop_at_generation.keys():
allele = haplotype[site]
frequency = pop_at_generation[haplotype] / float(pop_size)
if allele != "A":
minor_allele_frequency += frequency
return minor_allele_fr... | identifier_body | |
mutation-drift-selection.py | the sequences together will have count *N*.
# <codecell>
pop = {}
# <codecell>
pop["AAAAAAAAAA"] = 40
# <codecell>
pop["AAATAAAAAA"] = 30
# <codecell>
pop["AATTTAAAAA"] = 30
# <markdowncell>
# *Map haplotype string to fitness float.*
# <codecell>
fitness = {}
# <codecell>
fitness["AAAAAAAAAA"] = 1.0
# <... | ():
haplotypes = pop.keys()
frequencies = [pop[haplotype]/float(pop_size) for haplotype in haplotypes]
fitnesses = [fitness[haplotype] for haplotype in haplotypes]
weights = [x * y for x,y in zip(frequencies, fitnesses)]
total = sum(weights)
weights = [x / total for x in weights]
return list... | get_offspring_counts | identifier_name |
emulator-cli.py | #!/usr/bin/env python
import socket, struct
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9123))
try:
while True:
line = raw_input( ">" )
parts = line.split()
if parts[0] == "SET":
if parts[1] == "A":
value = int( parts[2] )
s.send( struct.pack( "<BBBBB", 0, valu... |
if parts[1] == "B":
s.send( struct.pack( "<BBBBB", 3, 0, 0, 0, 0 ) )
data = s.recv( 5 )
print struct.unpack( "<BBBBB", data )
except KeyboardInterrupt:
pass
s.close()
| s.send( struct.pack( "<BBBBB", 2, 0, 0, 0, 0 ) )
data = s.recv( 5 )
print struct.unpack( "<BBBBB", data ) | conditional_block |
emulator-cli.py | #!/usr/bin/env python
import socket, struct
|
try:
while True:
line = raw_input( ">" )
parts = line.split()
if parts[0] == "SET":
if parts[1] == "A":
value = int( parts[2] )
s.send( struct.pack( "<BBBBB", 0, value, 0, 0, 0 ) )
if parts[1] == "B":
value = int( parts[2] )
s.send( struct.pack( "<BBBBB", 1, value, 0, 0, 0 ) )
if parts[... |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9123)) | random_line_split |
main.js | var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var chromeArgs = require('./chrome-args.js');
var menu = require('./menu.js');
var settings = require('./settings.js');
var teams = require("./teams.js");
var tray = require("./tray.js");
settings.load();
chromeArgs... | }
});
app.on('before-quit', function(e) {
quitting = true;
});
mainWindow.on('close', function(e) {
settings.set('window:fullscreen', mainWindow.isFullScreen());
if (!mainWindow.isFullScreen()) {
var bounds = mainWindow.getBounds();
settings.set('window:x', bounds.x);
setting... | random_line_split | |
main.js | var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var chromeArgs = require('./chrome-args.js');
var menu = require('./menu.js');
var settings = require('./settings.js');
var teams = require("./teams.js");
var tray = require("./tray.js");
settings.load();
chromeArgs... |
}
});
app.on('before-quit', function(e) {
quitting = true;
});
mainWindow.on('close', function(e) {
settings.set('window:fullscreen', mainWindow.isFullScreen());
if (!mainWindow.isFullScreen()) {
var bounds = mainWindow.getBounds();
settings.set('window:x', bounds.x);
settin... | {
mainWindow.show();
} | conditional_block |
guitester.py | .de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published b... | (self, name):
path = defaults.var_dir + "/guitests/" + name + ".mk"
try:
return eval(file(path).read())
except IOError, e:
raise MKGeneralException(_("Cannot load GUI test file %s: %s") % (self.attrencode(path), e))
def replay_guitest(self):
test_name = self... | load_guitest | identifier_name |
guitester.py | .de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published b... | if self.replayed_guitest_step:
try:
self.end_guitest_replay()
except MKGuitestFailed, e:
self.write("\n[[[GUITEST FAILED]]]\n%s" % ("\n".join(e.errors)))
def end_guitest_replay(self):
if self.replayed_guitest_step and self.guitest_repair_step... |
def finalize_guitests(self):
if self.guitest:
self.end_guitest_recording()
| random_line_split |
guitester.py | You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import re
import defaults
from lib import *
class MKGuitestFailed(MKException):
... | diff_text = guitest_check_text(ref_cell[0], real_cell[0])
if diff_text:
return [ "Row %d, Column %d: %s" % (row_nr, cell_nr, diff_text) ] | conditional_block | |
guitester.py | .de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published b... |
def guitest_check_element_list(reference, reality):
errors = []
one_missing = False
for entry in reference:
if not guitest_entry_in_reference_list(entry, reality):
errors.append("missing entry %r" % (entry,))
one_missing = True
if one_missing:
for entry in real... | if len(reference) > 1:
errors.append("More than one reference value: %s" % ", ".join(reference))
if len(reality) > 1:
errors.append("More than one value: %s" % ", ".join(reality))
diff_text = guitest_check_text(reference[0], reality[0])
if diff_text:
return [ diff_text ]
else:
... | identifier_body |
bitbucketPullRequestUpdated.ts | import R from 'ramda';
import { sendToLagoonLogs } from '@lagoon/commons/dist/logs';
import { createDeployTask } from '@lagoon/commons/dist/tasks';
import { WebhookRequestData, deployData, Project } from '../types';
export async function | (webhook: WebhookRequestData, project: Project) {
const {
webhooktype,
event,
giturl,
uuid,
body,
} = webhook;
const meta = {
projectName: project.name,
pullrequestTitle: body.pullrequest.title,
pullrequestNumber: body.pullrequest.id,
pullrequestUrl: b... | bitbucketPullRequestUpdated | identifier_name |
bitbucketPullRequestUpdated.ts | import R from 'ramda';
import { sendToLagoonLogs } from '@lagoon/commons/dist/logs';
import { createDeployTask } from '@lagoon/commons/dist/tasks';
import { WebhookRequestData, deployData, Project } from '../types';
export async function bitbucketPullRequestUpdated(webhook: WebhookRequestData, project: Project) {
... |
const data: deployData = {
repoName: body.repository.full_name,
repoUrl: body.repository.links.html.href,
pullrequestUrl: body.pullrequest.links.html.href,
pullrequestTitle: body.pullrequest.title,
pullrequestNumber: body.pullrequest.id,
projectName: project.name,
type: '... | {
sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handledButNoTask`, meta,
`*[${project.name}]* PR ${body.number}. No deploy task created, reason: Source/Destination not same repo`
)
return;
} | conditional_block |
bitbucketPullRequestUpdated.ts | import R from 'ramda';
import { sendToLagoonLogs } from '@lagoon/commons/dist/logs';
import { createDeployTask } from '@lagoon/commons/dist/tasks';
import { WebhookRequestData, deployData, Project } from '../types';
export async function bitbucketPullRequestUpdated(webhook: WebhookRequestData, project: Project) {
... |
const meta = {
projectName: project.name,
pullrequestTitle: body.pullrequest.title,
pullrequestNumber: body.pullrequest.id,
pullrequestUrl: body.pullrequest.destination.repository.links.html.href,
repoName: body.repository.full_name,
repoUrl: body.repository.links.html.href,
... | event,
giturl,
uuid,
body,
} = webhook; | random_line_split |
bitbucketPullRequestUpdated.ts | import R from 'ramda';
import { sendToLagoonLogs } from '@lagoon/commons/dist/logs';
import { createDeployTask } from '@lagoon/commons/dist/tasks';
import { WebhookRequestData, deployData, Project } from '../types';
export async function bitbucketPullRequestUpdated(webhook: WebhookRequestData, project: Project) | const headBranchName = body.pullrequest.source.branch.name
const headSha = body.pullrequest.source.commit.hash
const baseRepoId = body.pullrequest.destination.repository.uuid;
const baseBranchName = body.pullrequest.destination.branch.name
const baseSha = body.pullrequest.destination.commit.hash
... | {
const {
webhooktype,
event,
giturl,
uuid,
body,
} = webhook;
const meta = {
projectName: project.name,
pullrequestTitle: body.pullrequest.title,
pullrequestNumber: body.pullrequest.id,
pullrequestUrl: body.pullrequest.destination.repository.links.htm... | identifier_body |
ApiCall.ts | import { TSBuffer } from 'tsbuffer';
import { ApiService, TransportDataUtil } from "tsrpc-base-client";
import { ApiReturn, BaseServiceType, ServerOutputData, TsrpcError, TsrpcErrorData, TsrpcErrorType } from "tsrpc-proto";
import { PrefixLogger } from "../models/PrefixLogger";
import { BaseCall, BaseCallOptions } from... |
// record & log ret
this._usedTime = Date.now() - this.startTime;
if (ret.isSucc) {
this.logger.log('[ApiRes]', `${this.usedTime}ms`, this.server.options.logResBody ? ret.res : '');
}
else {
if (ret.err.type === TsrpcErrorType.ApiError) {
... | {
this.logger.error('[SendReturnErr]', opSend.errMsg, ret);
if (ret.isSucc || ret.err.type === TsrpcErrorType.ApiError) {
this._return = undefined;
this.server.onInternalServerError({ message: opSend.errMsg, name: 'SendReturnErr' }, this)
}
... | conditional_block |
ApiCall.ts | import { TSBuffer } from 'tsbuffer';
import { ApiService, TransportDataUtil } from "tsrpc-base-client";
import { ApiReturn, BaseServiceType, ServerOutputData, TsrpcError, TsrpcErrorData, TsrpcErrorType } from "tsrpc-proto";
import { PrefixLogger } from "../models/PrefixLogger";
import { BaseCall, BaseCallOptions } from... | /**
* Response Data that sent already.
* `undefined` means no return data is sent yet. (Never `call.succ()` and `call.error()`)
*/
public get return(): ApiReturn<Res> | undefined {
return this._return;
}
protected _usedTime: number | undefined;
/** Time from received req to s... |
protected _return?: ApiReturn<Res>; | random_line_split |
ApiCall.ts | import { TSBuffer } from 'tsbuffer';
import { ApiService, TransportDataUtil } from "tsrpc-base-client";
import { ApiReturn, BaseServiceType, ServerOutputData, TsrpcError, TsrpcErrorData, TsrpcErrorType } from "tsrpc-proto";
import { PrefixLogger } from "../models/PrefixLogger";
import { BaseCall, BaseCallOptions } from... |
protected _usedTime: number | undefined;
/** Time from received req to send return data */
public get usedTime(): number | undefined {
return this._usedTime;
}
/**
* Send a successful `ApiReturn` with response data
* @param res - Response data
* @returns Promise resolved me... | {
return this._return;
} | identifier_body |
ApiCall.ts | import { TSBuffer } from 'tsbuffer';
import { ApiService, TransportDataUtil } from "tsrpc-base-client";
import { ApiReturn, BaseServiceType, ServerOutputData, TsrpcError, TsrpcErrorData, TsrpcErrorType } from "tsrpc-proto";
import { PrefixLogger } from "../models/PrefixLogger";
import { BaseCall, BaseCallOptions } from... | (): ApiReturn<Res> | undefined {
return this._return;
}
protected _usedTime: number | undefined;
/** Time from received req to send return data */
public get usedTime(): number | undefined {
return this._usedTime;
}
/**
* Send a successful `ApiReturn` with response data
... | return | identifier_name |
main.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 ... | () {
remap_path_prefix_aux::some_aux_function();
aux_mod::some_aux_mod_function();
some_aux_mod_function();
}
// Here we check that local debuginfo is mapped correctly.
// CHECK: !DIFile(filename: "/the/src/remap_path_prefix/main.rs", directory: "/the/cwd/")
// And here that debuginfo from other crates ar... | main | identifier_name |
main.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 ... | include!("aux_mod.rs");
// Here we check that the expansion of the file!() macro is mapped.
// CHECK: @0 = private unnamed_addr constant <{ [34 x i8] }> <{ [34 x i8] c"/the/src/remap_path_prefix/main.rs" }>, align 1
pub static FILE_PATH: &'static str = file!();
fn main() {
remap_path_prefix_aux::some_aux_function... |
// Here we check that submodules and include files are found using the path without
// remapping. This test requires that rustc is called with an absolute path.
mod aux_mod; | random_line_split |
main.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 ... |
// Here we check that local debuginfo is mapped correctly.
// CHECK: !DIFile(filename: "/the/src/remap_path_prefix/main.rs", directory: "/the/cwd/")
// And here that debuginfo from other crates are expanded to absolute paths.
// CHECK: !DIFile(filename: "/the/aux-src/remap_path_prefix_aux.rs", directory: "")
| {
remap_path_prefix_aux::some_aux_function();
aux_mod::some_aux_mod_function();
some_aux_mod_function();
} | identifier_body |
PitchGraph.tsx | import { observer } from "mobx-react-lite"
import React, { FC } from "react"
import { ISize } from "../../../../common/geometry"
import { useStores } from "../../../hooks/useStores"
import LineGraphControl from "./LineGraphControl"
export type PitchGraphProps = ISize
const PitchGraph: FC<PitchGraphProps> = observer((... | width={width}
height={height}
maxValue={0x4000}
events={events}
axis={[0, 0x1000, 0x2000, 0x3000, 0x4000 - 1]}
axisLabelFormatter={(v) => (v - 0x2000).toString()}
eventType={{ type: "pitchBend" }}
/>
)
})
export default React.memo(PitchGraph) | random_line_split | |
p011.rs | #![feature(core)]
use euler::*; mod euler;
#[no_mangle]
pub extern "C" fn solution() -> EulerType {
let g = [
[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, ... | () { print_euler(solution()) }
| main | identifier_name |
p011.rs | #![feature(core)]
use euler::*; mod euler;
#[no_mangle] | [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66... | pub extern "C" fn solution() -> EulerType {
let g = [
[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8], | random_line_split |
p011.rs | #![feature(core)]
use euler::*; mod euler;
#[no_mangle]
pub extern "C" fn solution() -> EulerType | [20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48u64],
];
EulerU(
(0 .. 20).map(|j|
(0 .. 20 - 4).map(|i|
max(
(0 .. 4).map(|k| g[j][i + k]).product(),
(0 .. 4).map(|k| g[i + k][j]).p... | {
let g = [
[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32... | identifier_body |
regions-close-over-type-parameter-multiple.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 ... |
fn make_object_good2<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'b> {
// A outlives 'a AND 'b...
box v as Box<SomeTrait+'b> // ...hence this type is safe.
}
fn make_object_bad<'a,'b,'c,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'c> {
// A outlives 'a AND 'b...but not 'c.
box v as Box<SomeTrait+'a... | {
// A outlives 'a AND 'b...
box v as Box<SomeTrait+'a> // ...hence this type is safe.
} | identifier_body |
regions-close-over-type-parameter-multiple.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 outlives 'a AND 'b...
box v as Box<SomeTrait+'a> // ...hence this type is safe.
}
fn make_object_good2<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'b> {
// A outlives 'a AND 'b...
box v as Box<SomeTrait+'b> // ...hence this type is safe.
}
fn make_object_bad<'a,'b,'c,A:SomeTrait+'a+'b>(v: A) ... | trait SomeTrait { fn get(&self) -> isize; }
fn make_object_good1<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'a> { | random_line_split |
regions-close-over-type-parameter-multiple.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,'b,'c,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'c> {
// A outlives 'a AND 'b...but not 'c.
box v as Box<SomeTrait+'a> //~ ERROR cannot infer an appropriate lifetime
}
fn main() {
}
| make_object_bad | identifier_name |
service.py | #!/usr/bin/python
#
# Copyright (C) 2008 Google 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"... | random_line_split | |
service.py | #!/usr/bin/python
#
# Copyright (C) 2008 Google 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 ... | (self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cp', source=source,
se... | __init__ | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.