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 |
|---|---|---|---|---|
mean.rs | //! Functions for calculating mean
use std::f64::NAN;
/// Calculates arithmetic mean (AM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [8., 16.];
/// assert_eq!(mean::arithmetic(&slice), 12.);
/// ```
pub fn arit... |
/// Calculate geometric mean (GM) of data set `slice`.
///
/// If the result would be imaginary, function returns `NAN`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [9., 16.];
/// assert_eq!(mean::geometric(&slice), 12.);
/// ```
p... | {
slice.iter().fold(0., |a, b| a + b) / slice.len() as f64
} | identifier_body |
page.js | /*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
/* global protractor, module, element, by, browser */
(function() {
var Page = function() {
};
Page.prototype.moveMouseTo = function(locator) {
var ele = ... |
// give it some time to save changes
browser.sleep(300).then(function() {
d.fulfill(true);
});
});
});
return d.promise;
};
module.exports = Page;
})();
| {
processEntry(entries[i]);
} | conditional_block |
page.js | /*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
/* global protractor, module, element, by, browser */
(function() {
var Page = function() {
};
Page.prototype.moveMouseTo = function(locator) {
var ele = ... | }
browser.wait(function() {
return dropDownEl.isPresent();
}, 1000).then(function() {
dropDownEl.all(by.css('[type=checkbox]')).then(function(entries) {
for (var i = 0; i < entries.length; i++) {
processEntry(entries[i]);
}
// give it some time to save changes
browser.sleep(300).then(... | {
entry.isSelected().then(function(selected) {
entry.getAttribute('id').then(function(inputId) {
// format is "ms0-option-theid", we extract that id
var dataId = inputId.split('-')[2];
var mustBeSelected = selection.indexOf(dataId) >= 0;
// if state doesn't match what we want, toggle
if... | identifier_body |
page.js | /*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
/* global protractor, module, element, by, browser */
(function() {
var Page = function() {
};
Page.prototype.moveMouseTo = function(locator) {
var ele = ... |
Page.appMenuEntryId = function(appId) {
return by.css('nav #apps [data-id=\'' + appId + '\']');
};
Page.settingsMenuId = function() {
return by.css('#header #settings');
};
//================ UTILITY FUNCTIONS ====================================//
/**
* Sets the selection of a multiselect element
*
... | random_line_split | |
page.js | /*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
/* global protractor, module, element, by, browser */
(function() {
var Page = function() {
};
Page.prototype.moveMouseTo = function(locator) {
var ele = ... | (entry) {
entry.isSelected().then(function(selected) {
entry.getAttribute('id').then(function(inputId) {
// format is "ms0-option-theid", we extract that id
var dataId = inputId.split('-')[2];
var mustBeSelected = selection.indexOf(dataId) >= 0;
// if state doesn't match what we want, toggle
... | processEntry | identifier_name |
index.ts | /// <reference path='../typings/node/node.d.ts' />
/// <reference path='../typings/MetadataClasses.d.ts' />
import fs = require("fs");
import path = require('path');
const stripBom = require("strip-bom");
import metadata = require('MetadataClasses');
module.exports = {
description: 'Generates an ember list-form for... | let listFormFile = path.join(listFormsDir, options.file);
let content = stripBom(fs.readFileSync(listFormFile, "utf8"));
this.listForm = JSON.parse(content);
}
}
|
options.file = options.entity.name + ".json";
}
| conditional_block |
index.ts | /// <reference path='../typings/node/node.d.ts' />
/// <reference path='../typings/MetadataClasses.d.ts' />
import fs = require("fs");
import path = require('path');
const stripBom = require("strip-bom");
import metadata = require('MetadataClasses');
module.exports = {
description: 'Generates an ember list-form for... | {
listForm: metadata.ListForm;
constructor(blueprint, options) {
let listFormsDir = path.join(options.metadataDir, "list-forms");
if (!options.file) {
options.file = options.entity.name + ".json";
}
let listFormFile = path.join(listFormsDir, options.file);
let content = stripBom(fs.readFil... | istFormBlueprint | identifier_name |
index.ts | /// <reference path='../typings/node/node.d.ts' />
/// <reference path='../typings/MetadataClasses.d.ts' />
import fs = require("fs");
import path = require('path');
const stripBom = require("strip-bom");
import metadata = require('MetadataClasses');
module.exports = {
description: 'Generates an ember list-form for... | /**
* Blueprint Hook locals.
* Use locals to add custom template variables. The method receives one argument: options.
*
* @method locals
* @public
*
* @param {Object} options Options is an object containing general and entity-specific options.
* @return {Object} Сustom template variables.
... | random_line_split | |
splashScreen.py | ###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# mod... | import startShellGui
global splashScreen
splashScreen.finish(startShellGui.shell) | identifier_body | |
splashScreen.py | ###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# mod... | ():
splash_path = os.path.join(os.path.split(ilastik.__file__)[0], 'ilastik-splash.png')
splashImage = QPixmap(splash_path)
global splashScreen
splashScreen = QSplashScreen(splashImage)
splashScreen.showMessage( ilastik.__version__, Qt.AlignBottom | Qt.AlignRight )
splashScreen.show()
def h... | showSplashScreen | identifier_name |
splashScreen.py | ###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# mod... | ###############################################################################
import os
from PyQt4.QtGui import QSplashScreen, QPixmap
from PyQt4.QtCore import Qt
import ilastik
splashScreen = None
def showSplashScreen():
splash_path = os.path.join(os.path.split(ilastik.__file__)[0], 'ilastik-splash.png')
... | random_line_split | |
window.rs | ypedSize2D(width as uint, height as uint)))
}
}
glut::reshape_func(glut_window, box ReshapeCallbackState);
struct KeyboardCallbackState;
impl glut::KeyboardCallback for KeyboardCallbackState {
fn call(&self, key: c_uchar, _x: c_int, _y: c_int) {
le... | utCompositorProxy {
sender: self.sender.clone(),
} as Box<CompositorProxy+Send>
}
}
local_data_ | identifier_body | |
window.rs | glut::init_window_size(window_size.width, window_size.height);
let glut_window = glut::create_window("Servo".to_string());
// Create our window object.
let window = Window {
glut_window: glut_window,
event_queue: RefCell::new(vec!()),
drag_origin: P... | if self.mouse_down_button.get() == button {
let pixel_dist = self.mouse_down_point.get() - Point2D(x, y);
let pixel_dist = ((pixel_dist.x * pixel_dist.x +
pixel_dist.y * pixel_dist.y) as f32).sqrt();
if pixel_dist < max... | conditional_block | |
window.rs | ;
use msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderState};
use msg::compositor_msg::{FinishedLoading, Blank, ReadyState};
use util::geometry::ScreenPx;
use glut::glut::{ACTIVE_SHIFT, WindowHeight};
use glut::glut::WindowWidth;
use glut::glut;
// static THROBBER: [char, ..8] = [ '⣾', '⣽', '⣻', '⢿... | lut::MouseCallback for MouseCallbackState {
fn call(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
if button < 3 {
let tmp = local_window();
tmp.handle_mouse(button, state, x, y);
} else {
match button {
... | te;
impl g | identifier_name |
window.rs | Metadata;
use msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderState};
use msg::compositor_msg::{FinishedLoading, Blank, ReadyState};
use util::geometry::ScreenPx;
use glut::glut::{ACTIVE_SHIFT, WindowHeight};
use glut::glut::WindowWidth; | /// The type of a window.
pub struct Window {
pub glut_window: glut::Window,
pub event_queue: RefCell<Vec<WindowEvent>>,
pub drag_origin: Point2D<c_int>,
pub mouse_down_button: Cell<c_int>,
pub mouse_down_point: Cell<Point2D<c_int>>,
pub ready_state: Cell<ReadyState>,
pub render_state: C... | use glut::glut;
// static THROBBER: [char, ..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];
| random_line_split |
views.py | #!/usr/bin/env python3
from django.shortcuts import render
# Create your views here.
from CnbetaApis.datas.Models import *
from CnbetaApis.datas.get_letv_json import get_letv_json
from CnbetaApis.datas.get_youku_json import get_youku_json
from django.views.decorators.csrf import csrf_exempt
from django.http import... | (req):
if not req.method == 'POST':
raise HttpResponseNotAllowed('POST')
source_url = req.POST.get('url')
source_type = req.POST.get('type')
if source_type == "youku":
source_url = get_youku_json(source_url)
elif source_type == "letv":
source_url = get_letv_json(source_url)
... | get_video_realUrl | identifier_name |
views.py | #!/usr/bin/env python3
from django.shortcuts import render
# Create your views here.
from CnbetaApis.datas.Models import *
from CnbetaApis.datas.get_letv_json import get_letv_json
from CnbetaApis.datas.get_youku_json import get_youku_json
from django.views.decorators.csrf import csrf_exempt
from django.http import... | if not len(datas):
raise Http404('Article not exist')
data = datas[0]
result = {'result': {
'id': data.id,
'title': data.title,
'url': data.url,
'imgUrl': data.imgUrl,
'source': data.source,
'introduction': data.introduction,
'createTime': data... | session = DBSession()
datas = session.query(Article).filter(Article.id == article_id).all() | random_line_split |
views.py | #!/usr/bin/env python3
from django.shortcuts import render
# Create your views here.
from CnbetaApis.datas.Models import *
from CnbetaApis.datas.get_letv_json import get_letv_json
from CnbetaApis.datas.get_youku_json import get_youku_json
from django.views.decorators.csrf import csrf_exempt
from django.http import... | if not req.method == 'POST':
raise HttpResponseNotAllowed('POST')
source_url = req.POST.get('url')
source_type = req.POST.get('type')
if source_type == "youku":
source_url = get_youku_json(source_url)
elif source_type == "letv":
source_url = get_letv_json(source_url)
else:
... | identifier_body | |
views.py | #!/usr/bin/env python3
from django.shortcuts import render
# Create your views here.
from CnbetaApis.datas.Models import *
from CnbetaApis.datas.get_letv_json import get_letv_json
from CnbetaApis.datas.get_youku_json import get_youku_json
from django.views.decorators.csrf import csrf_exempt
from django.http import... |
source_url = req.POST.get('url')
source_type = req.POST.get('type')
if source_type == "youku":
source_url = get_youku_json(source_url)
elif source_type == "letv":
source_url = get_letv_json(source_url)
else:
raise Http404('Article not exist')
return JsonResponse({"resul... | raise HttpResponseNotAllowed('POST') | conditional_block |
EmailObject.py | import hashlib
import sys
import datetime
class EmailObject:
def __init__(self, sender, date, subject, body):
|
def createEmailId(self):
hasher = hashlib.md5()
hasher.update(self.sender.encode() + self.date.strftime('%Y-%m-%d %H:%M:%S').encode() + self.subject.encode())
hasher.update(self.body.encode())
result = int(hasher.hexdigest(), 16) % sys.maxsize
return result
def fetchEm... | self.sender = sender
self.date = datetime.datetime.strptime(date[5:25], '%d %b %Y %H:%M:%S') #TODO: FIX THIS CODE TO BE MORE ROBUST
self.body = body
self.subject = subject
self.emailId = self.createEmailId() | identifier_body |
EmailObject.py | import hashlib
import sys
import datetime
class EmailObject:
def __init__(self, sender, date, subject, body):
self.sender = sender
self.date = datetime.datetime.strptime(date[5:25], '%d %b %Y %H:%M:%S') #TODO: FIX THIS CODE TO BE MORE ROBUST
self.body = body
self.subject = subject
... | (self):
descriptivestr = "Sender: " + "'" + self.sender + "'" + "\n"
descriptivestr += "Date: " + "'" + self.date.strftime('%Y-%m-%d %H:%M:%S') +"'" +"\n"
descriptivestr += "Subject: " + "'" + self.subject + "'" + "\n"
descriptivestr += "Body: " + self.body + "\n"
return descri... | __str__ | identifier_name |
EmailObject.py | import hashlib
import sys
import datetime
class EmailObject:
def __init__(self, sender, date, subject, body):
self.sender = sender
self.date = datetime.datetime.strptime(date[5:25], '%d %b %Y %H:%M:%S') #TODO: FIX THIS CODE TO BE MORE ROBUST
self.body = body
self.subject = subject
... | sqlLine = "('" + self.sender + "','" + self.date.strftime('%Y-%m-%d %H:%M:%S') + "','" + self.subject + "'," + str(self.emailId) + ")"
return sqlLine
def fetchEmailBodySql(self):
sqlLine = "(" + str(self.emailId) + ",'" + self.body + "')"
return sqlLine
def __str__(self):
... |
def fetchEmailMain(self): | random_line_split |
adaptation.py | #!/usr/bin/env python
## \file adjoint.py
# \brief python package for running adjoint problems
# \author T. Lukaczyk, F. Palacios
# \version 5.0.0 "Raven"
#
# SU2 Original Developers: Dr. Francisco D. Palacios.
# Dr. Thomas D. Economon.
#
# SU2 Developers: Prof. Juan J. Alonso's group at St... | info = adapt_function(konfig)
# update super config
config['MESH_FILENAME'] = meshname_new
config['KIND_ADAPT'] = kind
# files out
files = { 'MESH' : meshname_new }
# info out
append_nestdict( info, { 'FILES' : files } )
return info
| konfig = copy.deepcopy(config)
# check kind
if kind: konfig['KIND_ADAPT'] = kind
kind = konfig.get('KIND_ADAPT','NONE')
if kind == 'NONE':
return {}
# check adapted?
# get adaptation function
adapt_function = su2mesh.adapt.name_map[kind]
# setup problem
... | identifier_body |
adaptation.py | #!/usr/bin/env python
## \file adjoint.py
# \brief python package for running adjoint problems
# \author T. Lukaczyk, F. Palacios
# \version 5.0.0 "Raven"
#
# SU2 Original Developers: Dr. Francisco D. Palacios.
# Dr. Thomas D. Economon.
#
# SU2 Developers: Prof. Juan J. Alonso's group at St... | ( config , kind='' ):
# local copy
konfig = copy.deepcopy(config)
# check kind
if kind: konfig['KIND_ADAPT'] = kind
kind = konfig.get('KIND_ADAPT','NONE')
if kind == 'NONE':
return {}
# check adapted?
# get adaptation function
adapt_function = su2mes... | adaptation | identifier_name |
adaptation.py | #!/usr/bin/env python
## \file adjoint.py
# \brief python package for running adjoint problems
# \author T. Lukaczyk, F. Palacios
# \version 5.0.0 "Raven"
#
# SU2 Original Developers: Dr. Francisco D. Palacios.
# Dr. Thomas D. Economon.
#
# SU2 Developers: Prof. Juan J. Alonso's group at St... |
# check adapted?
# get adaptation function
adapt_function = su2mesh.adapt.name_map[kind]
# setup problem
suffix = 'adapt'
meshname_orig = konfig['MESH_FILENAME']
meshname_new = su2io.add_suffix( konfig['MESH_FILENAME'], suffix )
konfig['MESH_OUT_FILENAME'] = meshname... | return {} | conditional_block |
adaptation.py | #!/usr/bin/env python
## \file adjoint.py
# \brief python package for running adjoint problems
# \author T. Lukaczyk, F. Palacios
# \version 5.0.0 "Raven"
#
# SU2 Original Developers: Dr. Francisco D. Palacios.
# Dr. Thomas D. Economon.
#
# SU2 Developers: Prof. Juan J. Alonso's group at St... | return {}
# check adapted?
# get adaptation function
adapt_function = su2mesh.adapt.name_map[kind]
# setup problem
suffix = 'adapt'
meshname_orig = konfig['MESH_FILENAME']
meshname_new = su2io.add_suffix( konfig['MESH_FILENAME'], suffix )
konfig['MESH_OUT_FILE... |
# check kind
if kind: konfig['KIND_ADAPT'] = kind
kind = konfig.get('KIND_ADAPT','NONE')
if kind == 'NONE': | random_line_split |
instr_pmuldq.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn pmuldq_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XM... |
#[test]
fn pmuldq_4() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM5)), operand2: Some(Indirect(RSI, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 4... | {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 206], OperandSize::Qword)
} | identifier_body |
instr_pmuldq.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM0)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 200], OperandSize::Dword)
}
#[test]
fn pmuldq_2() {
... | pmuldq_1 | identifier_name |
instr_pmuldq.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn pmuldq_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XM... | }
#[test]
fn pmuldq_4() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM5)), operand2: Some(Indirect(RSI, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, ... |
#[test]
fn pmuldq_3() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 206], OperandSize::Qword) | random_line_split |
rc.rs | //! A reference-counted wrapper sharing one owned trace.
//!
//! The types in this module, `TraceBox` and `TraceRc` and meant to parallel `RcBox` and `Rc` in `std::rc`.
//!
//! The first typee is an owned trace with some information about the cumulative requirements of the shared
//! handles. This is roughly how much p... |
fn distinguish_frontier(&mut self) -> &[Tr::Time] { &self.through_frontier[..] }
/// Creates a new cursor over the wrapped trace.
fn cursor_through(&mut self, frontier: &[Tr::Time]) -> Option<(Tr::Cursor, <Tr::Cursor as Cursor<Tr::Key, Tr::Val, Tr::Time, Tr::R>>::Storage)> {
::std::cell::RefCell::b... | {
self.wrapper.borrow_mut().adjust_through_frontier(&self.through_frontier[..], frontier);
self.through_frontier = frontier.to_vec();
} | identifier_body |
rc.rs | //! A reference-counted wrapper sharing one owned trace.
//!
//! The types in this module, `TraceBox` and `TraceRc` and meant to parallel `RcBox` and `Rc` in `std::rc`.
//!
//! The first typee is an owned trace with some information about the cumulative requirements of the shared
//! handles. This is roughly how much p... | }
impl<Tr> TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
/// Allocates a new handle from an existing wrapped wrapper.
pub fn make_from(trace: Tr) -> (Self, Rc<RefCell<TraceBox<Tr>>>) {
let wrapped = Rc::new(RefCell::new(TraceBox::new(trace)));
let handle = ... | ::std::cell::RefCell::borrow_mut(&self.wrapper).trace.map_batches(f)
} | random_line_split |
rc.rs | //! A reference-counted wrapper sharing one owned trace.
//!
//! The types in this module, `TraceBox` and `TraceRc` and meant to parallel `RcBox` and `Rc` in `std::rc`.
//!
//! The first typee is an owned trace with some information about the cumulative requirements of the shared
//! handles. This is roughly how much p... | (&mut self, lower: &[Tr::Time], upper: &[Tr::Time]) {
self.through_frontiers.update_iter(upper.iter().cloned().map(|t| (t,1)));
self.through_frontiers.update_iter(lower.iter().cloned().map(|t| (t,-1)));
// for element in upper { self.through_frontiers.update_and(element, 1, |_,_| {}); }
... | adjust_through_frontier | identifier_name |
error.rs | use std::error::Error;
use std::fmt;
use std::io;
use std::num::{ParseFloatError, ParseIntError};
use std::str::Utf8Error;
#[derive(Debug)]
pub enum OperationError {
OverflowError,
NotANumberError,
ValueError(String),
UnknownKeyError,
WrongTypeError,
OutOfBoundsError,
IOError(io::Error), |
impl OperationError {
fn message(&self) -> &str {
match self {
OperationError::WrongTypeError => {
"WRONGTYPE Operation against a key holding the wrong kind of value"
}
OperationError::NotANumberError => "ERR resulting score is not a number (NaN)",
... | } | random_line_split |
error.rs | use std::error::Error;
use std::fmt;
use std::io;
use std::num::{ParseFloatError, ParseIntError};
use std::str::Utf8Error;
#[derive(Debug)]
pub enum OperationError {
OverflowError,
NotANumberError,
ValueError(String),
UnknownKeyError,
WrongTypeError,
OutOfBoundsError,
IOError(io::Error),
}
... | (&self) -> &str {
self.message()
}
}
impl From<Utf8Error> for OperationError {
fn from(_: Utf8Error) -> OperationError {
OperationError::ValueError("ERR value is not a string".to_owned())
}
}
impl From<ParseIntError> for OperationError {
fn from(_: ParseIntError) -> OperationError {
... | description | identifier_name |
error.rs | use std::error::Error;
use std::fmt;
use std::io;
use std::num::{ParseFloatError, ParseIntError};
use std::str::Utf8Error;
#[derive(Debug)]
pub enum OperationError {
OverflowError,
NotANumberError,
ValueError(String),
UnknownKeyError,
WrongTypeError,
OutOfBoundsError,
IOError(io::Error),
}
... |
}
| {
OperationError::IOError(e)
} | identifier_body |
ITC06010401_UpdateNetwork.py | #encoding:utf-8
__authors__ = ['wei keke']
__version__ = "V0.1" | #---------------------------------------------------------------------------------
# Version Date Desc Author
#---------------------------------------------------------------------------------
# V0.1 2014/10/17 初始版本 ... |
'''
# ChangeLog: | random_line_split |
asana.d.ts | // Type definitions for asana 0.9.1
// Project: https://github.com/Asana/node-asana
// Definitions by: Karan Sikka <https://github.com/ksikka>
/// <reference path="../bluebird/bluebird.d.ts"/>
/// <reference path="../node/node.d.ts"/>
declare module 'asana' {
export interface ResourceResponse {
id?: number;
... | export interface WorkspaceResource extends Resource<Workspace> {
}
export interface TaskResource extends Resource<Task> {
}
export interface ProjectResource extends Resource<Project> {
}
export class Client {
static create(options?): Client;
users: UserResource;
tasks: TaskResource;
pr... | random_line_split | |
asana.d.ts | // Type definitions for asana 0.9.1
// Project: https://github.com/Asana/node-asana
// Definitions by: Karan Sikka <https://github.com/ksikka>
/// <reference path="../bluebird/bluebird.d.ts"/>
/// <reference path="../node/node.d.ts"/>
declare module 'asana' {
export interface ResourceResponse {
id?: number;
... | {
static create(options?): Client;
users: UserResource;
tasks: TaskResource;
projects: ProjectResource;
workspaces: WorkspaceResource;
useBasicAuth(apiKey: string): Client;
}
}
| Client | identifier_name |
starttls.ts | <?xml version="1.0" ?><!DOCTYPE TS><TS language="nl" version="2.0">
<context>
<name>StartTLSFeatureFactory</name>
<message>
<location filename="../../plugins/starttls/starttlsfeaturefactory.cpp" line="22"/>
<source>StartTLS</source>
<translation>StartTLS</translation>
</message>
<message>
<location... | <translation>Verkeerde SASL verhandelings antwoord</translation>
</message>
<message>
<location filename="../../plugins/starttls/starttlsfeaturefactory.cpp" line="47"/>
<source>StartTLS negotiation failed</source>
<translation>StartTLS verhandeling mislukt</translation>
</message>
</context>
</TS> | <location filename="../../plugins/starttls/starttlsfeaturefactory.cpp" line="46"/>
<source>Wrong StartTLS negotiation response</source> | random_line_split |
series-column.js | /*
YUI 3.17.2 (build 9c3c78e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('series-column', function (Y, NAME) {
/**
* Provides functionality for creating a column series.
*
* @module charts
* @submodule series-column
*/
... |
}
}
}
}
}, {
ATTRS: {
/**
* Read-only attribute indicating the type of series.
*
* @attribute type
* @type String
* @readOnly
* @default column
*/
type: {
value: "colum... | {
renderer.set("x", (xs[n] - seriesSize/2));
} | conditional_block |
series-column.js | /*
YUI 3.17.2 (build 9c3c78e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('series-column', function (Y, NAME) {
/**
* Provides functionality for creating a column series.
*
* @module charts
* @submodule series-column
*/
... | *
* @method _getMarkerDimensions
* @param {Number} xcoord The x-coordinate representing the data point for the marker.
* @param {Number} ycoord The y-coordinate representing the data point for the marker.
* @param {Number} calculatedSize The calculated size for the marker. For a `BarSeries`... | Y.ColumnSeries = Y.Base.create("columnSeries", Y.MarkerSeries, [Y.Histogram], {
/**
* Helper method for calculating the size of markers.
| random_line_split |
content_test.py | import unittest
from mock import Mock
from biicode.common.model.content import Content
from biicode.common.model.content import ContentDeserializer
from biicode.common.model.content import content_diff
from biicode.common.exception import BiiSerializationException
from biicode.common.model.id import ID
class ContentT... | (self):
self.assertRaises(BiiSerializationException,
ContentDeserializer(ID((0, 0, 0))).deserialize,
"wrong object")
self.assertIsNone(ContentDeserializer(ID).deserialize(None))
def test_content_diff(self):
content_load1 = Mock()
c... | test_deserialize_exception | identifier_name |
content_test.py | import unittest
from mock import Mock
from biicode.common.model.content import Content
from biicode.common.model.content import ContentDeserializer
from biicode.common.model.content import content_diff
from biicode.common.exception import BiiSerializationException
from biicode.common.model.id import ID
class ContentT... | content_load1.is_binary = Mock(return_value=True)
self.assertEquals(content_diff(content_load1, content_load2),
"Unable to diff binary contents of base")
content_load1.is_binary = Mock(return_value=False)
content_load2.is_binary = Mock(return_value=True)
... | def test_content_diff(self):
content_load1 = Mock()
content_load2 = Mock() | random_line_split |
content_test.py | import unittest
from mock import Mock
from biicode.common.model.content import Content
from biicode.common.model.content import ContentDeserializer
from biicode.common.model.content import content_diff
from biicode.common.exception import BiiSerializationException
from biicode.common.model.id import ID
class ContentT... |
def test_content_diff(self):
content_load1 = Mock()
content_load2 = Mock()
content_load1.is_binary = Mock(return_value=True)
self.assertEquals(content_diff(content_load1, content_load2),
"Unable to diff binary contents of base")
content_load1.is_bi... | self.assertRaises(BiiSerializationException,
ContentDeserializer(ID((0, 0, 0))).deserialize,
"wrong object")
self.assertIsNone(ContentDeserializer(ID).deserialize(None)) | identifier_body |
functions_6.js | var searchData=
[
['put_125',['put',['../classpmem_1_1kv_1_1db.html#a31dbecf3c960dec47d4a04328b9efd92',1,'pmem::kv::db']]], | ['put_5fobject_130',['put_object',['../classpmem_1_1kv_1_1config.html#ab8dba893f7332490c7624a2802ebd931',1,'pmem::kv::config::put_object(const std::string &key, T *value, void(*deleter)(void *)) noexcept'],['../classpmem_1_1kv_1_1config.html#a1c0f1b1157e5922f2287f36be2d92015',1,'pmem::kv::config::put_object(const... | ['put_5fcomparator_126',['put_comparator',['../classpmem_1_1kv_1_1config.html#a95af80763cf924cf0b656d4ded034222',1,'pmem::kv::config']]],
['put_5fdata_127',['put_data',['../classpmem_1_1kv_1_1config.html#af6c8419518a384cdce1f36cd2a1e4545',1,'pmem::kv::config']]],
['put_5fforce_5fcreate_128',['put_force_create',['... | random_line_split |
keyFieldsMissingExternal.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const graphql_1 = require("graphql");
const apollo_graphql_1 = require("apollo-graphql");
const directives_1 = require("../../../directives");
const utils_1 = require("../../utils");
exports.keyFieldsMissingExternal = ({ name: serviceName, typ... | () {
const fieldDef = typeInfo.getFieldDef();
const parentType = typeInfo.getParentType();
if (parentType) {
if (!fieldDef) {
errors.push(utils_1.errorWithCode('KEY_FIELDS_MISSING_EXTERNAL', utils_1.logServiceAndType(serviceName... | Field | identifier_name |
keyFieldsMissingExternal.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const graphql_1 = require("graphql");
const apollo_graphql_1 = require("apollo-graphql");
const directives_1 = require("../../../directives");
const utils_1 = require("../../utils");
exports.keyFieldsMissingExternal = ({ name: serviceName, typ... | const keyDirectivesInfo = keyDirectivesOnTypeExtension
.map(keyDirective => keyDirective.arguments &&
utils_1.isStringValueNode(keyDirective.arguments[0].value)
? {
typeName: node.name.value,
keyArgument: keyDirective.ar... | const keyDirectivesOnTypeExtension = utils_1.findDirectivesOnTypeOrField(node, 'key'); | random_line_split |
keyFieldsMissingExternal.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const graphql_1 = require("graphql");
const apollo_graphql_1 = require("apollo-graphql");
const directives_1 = require("../../../directives");
const utils_1 = require("../../utils");
exports.keyFieldsMissingExternal = ({ name: serviceName, typ... |
},
}));
}
return errors;
};
//# sourceMappingURL=keyFieldsMissingExternal.js.map | {
if (!fieldDef) {
errors.push(utils_1.errorWithCode('KEY_FIELDS_MISSING_EXTERNAL', utils_1.logServiceAndType(serviceName, parentType.name) +
`A @key directive specifies a field which is not found in this service. Add a field to this type with @ext... | conditional_block |
keyFieldsMissingExternal.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const graphql_1 = require("graphql");
const apollo_graphql_1 = require("apollo-graphql");
const directives_1 = require("../../../directives");
const utils_1 = require("../../utils");
exports.keyFieldsMissingExternal = ({ name: serviceName, typ... | ,
}));
}
return errors;
};
//# sourceMappingURL=keyFieldsMissingExternal.js.map | {
const fieldDef = typeInfo.getFieldDef();
const parentType = typeInfo.getParentType();
if (parentType) {
if (!fieldDef) {
errors.push(utils_1.errorWithCode('KEY_FIELDS_MISSING_EXTERNAL', utils_1.logServiceAndType(serviceName, p... | identifier_body |
monitor_test.py | """
Test the "snabb lwaftr monitor" subcommand. Needs a NIC name and a TAP interface.
1. Execute "snabb lwaftr run" in on-a-stick mode and with the mirror option set.
2. Run "snabb lwaftr monitor" to set the counter and check its output.
"""
from random import randint
from subprocess import call, check_call
import un... | unittest.main() | conditional_block | |
monitor_test.py | """
Test the "snabb lwaftr monitor" subcommand. Needs a NIC name and a TAP interface.
1. Execute "snabb lwaftr run" in on-a-stick mode and with the mirror option set.
2. Run "snabb lwaftr monitor" to set the counter and check its output.
"""
from random import randint
from subprocess import call, check_call
import un... | monitor_args = list(self.monitor_args)
monitor_args.append(str(self.daemon.pid))
output = self.run_cmd(monitor_args)
self.assertIn(b'Mirror address set', output,
b'\n'.join((b'OUTPUT', output)))
self.assertIn(b'255.255.255.255', output,
b'\n'.join((b'OUTPU... | raise
def test_monitor(self): | random_line_split |
monitor_test.py | """
Test the "snabb lwaftr monitor" subcommand. Needs a NIC name and a TAP interface.
1. Execute "snabb lwaftr run" in on-a-stick mode and with the mirror option set.
2. Run "snabb lwaftr monitor" to set the counter and check its output.
"""
from random import randint
from subprocess import call, check_call
import un... | except Exception:
# Clean up the TAP interface.
call(('ip', 'tuntap', 'delete', cls.tap_name, 'mode', 'tap'))
raise
def test_monitor(self):
monitor_args = list(self.monitor_args)
monitor_args.append(str(self.daemon.pid))
output = self.run_cmd(moni... | daemon_args = [
str(SNABB_CMD), 'lwaftr', 'run',
'--bench-file', '/dev/null',
'--conf', str(DATA_DIR / 'icmp_on_fail.conf'),
'--on-a-stick', SNABB_PCI0,
'--mirror', # TAP interface name added in setUpClass.
]
monitor_args = (str(SNABB_CMD), 'lwaftr', 'monitor', 'all')
... | identifier_body |
monitor_test.py | """
Test the "snabb lwaftr monitor" subcommand. Needs a NIC name and a TAP interface.
1. Execute "snabb lwaftr run" in on-a-stick mode and with the mirror option set.
2. Run "snabb lwaftr monitor" to set the counter and check its output.
"""
from random import randint
from subprocess import call, check_call
import un... | (cls):
# Create the TAP interface and append its name to daemon_args
# before calling the superclass' setUpClass, which needs both.
# 'tapXXXXXX' where X is a 0-9 digit.
cls.tap_name = 'tap%s' % randint(100000, 999999)
check_call(('ip', 'tuntap', 'add', cls.tap_name, 'mode', 'tap... | setUpClass | identifier_name |
poll_immediate.rs | use super::assert_future;
use core::pin::Pin;
use futures_core::task::{Context, Poll};
use futures_core::{FusedFuture, Future, Stream};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`poll_immediate`](poll_immediate()) function.
///
/// It will never return [Poll::Pending](core::task... | (self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
match this.future.as_mut().as_pin_mut() {
// inner is gone, so we can signal that the stream is closed.
None => Poll::Ready(None),
Some(fut) => Poll::Ready(Some(f... | poll_next | identifier_name |
poll_immediate.rs | use super::assert_future;
use core::pin::Pin;
use futures_core::task::{Context, Poll};
use futures_core::{FusedFuture, Future, Stream};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`poll_immediate`](poll_immediate()) function.
///
/// It will never return [Poll::Pending](core::task... | impl<T: Future> FusedFuture for PollImmediate<T> {
fn is_terminated(&self) -> bool {
self.future.is_none()
}
}
/// A [Stream](crate::stream::Stream) implementation that can be polled repeatedly until the future is done.
/// The stream will never return [Poll::Pending](core::task::Poll::Pending)
/// so ... | }
| random_line_split |
poll_immediate.rs | use super::assert_future;
use core::pin::Pin;
use futures_core::task::{Context, Poll};
use futures_core::{FusedFuture, Future, Stream};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`poll_immediate`](poll_immediate()) function.
///
/// It will never return [Poll::Pending](core::task... |
}
/// Creates a future that is immediately ready with an Option of a value.
/// Specifically this means that [poll](core::future::Future::poll()) always returns [Poll::Ready](core::task::Poll::Ready).
///
/// # Caution
///
/// When consuming the future by this function, note the following:
///
/// - This function doe... | {
let mut this = self.project();
match this.future.as_mut().as_pin_mut() {
// inner is gone, so we can signal that the stream is closed.
None => Poll::Ready(None),
Some(fut) => Poll::Ready(Some(fut.poll(cx).map(|t| {
this.future.set(None);
... | identifier_body |
multi-select-sk.ts | // Copyright 2018 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
private _click(e: MouseEvent): void {
if (this.disabled) {
return;
}
// Look up the DOM path until we find an element that is a child of
// 'this', and set _selection based on that.
let target: Element | null = e.target as Element;
while (target && target.parentElement !== this) {
... | {
if (this.disabled) {
return;
}
if (!val || !val.sort) {
val = [];
}
val.sort();
this._selection = val;
this._rationalize();
} | identifier_body |
multi-select-sk.ts | // Copyright 2018 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | else {
target.setAttribute('selected', '');
}
this._bubbleUp();
this.dispatchEvent(new CustomEvent<MultiSelectSkSelectionChangedEventDetail>('selection-changed', {
detail: {
selection: this._selection,
},
bubbles: true,
}));
}
// Loop over all immediate child elemen... | {
target.removeAttribute('selected');
} | conditional_block |
multi-select-sk.ts | // Copyright 2018 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | this._selection = val;
this._rationalize();
}
private _click(e: MouseEvent): void {
if (this.disabled) {
return;
}
// Look up the DOM path until we find an element that is a child of
// 'this', and set _selection based on that.
let target: Element | null = e.target as Element;
... | val = [];
}
val.sort(); | random_line_split |
multi-select-sk.ts | // Copyright 2018 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (): number[] { return this._selection; }
set selection(val) {
if (this.disabled) {
return;
}
if (!val || !val.sort) {
val = [];
}
val.sort();
this._selection = val;
this._rationalize();
}
private _click(e: MouseEvent): void {
if (this.disabled) {
return;
}
... | selection | identifier_name |
storage.py | from django.conf import settings
from images.models import S3Connection
from shutil import copyfileobj
import tinys3
import os
import urllib
class LocalStorage(object):
def __init__(self, filename):
self.filename = filename
def get_file_data(self):
"""
Returns the raw data for the spec... |
def get_file_data(self):
"""
Returns the raw data for the specific file, downloading it from S3
"""
path = self.get_remote_path()
data = urllib.urlopen(path).read()
return data
def store(self, file_instance, content_type=None):
"""
Copy over the... | """
Returns an absolute remote path for the filename from the S3 bucket
"""
return 'https://%s.%s/%s' % (self.conn.default_bucket, self.conn.endpoint, self.filename) | identifier_body |
storage.py | from django.conf import settings
from images.models import S3Connection
from shutil import copyfileobj
import tinys3
import os
import urllib
class LocalStorage(object):
def __init__(self, filename):
self.filename = filename
def get_file_data(self):
"""
Returns the raw data for the spec... |
return self.__database_settings
| self.__database_settings = S3Connection.objects.get() | conditional_block |
storage.py | from django.conf import settings
from images.models import S3Connection
from shutil import copyfileobj
import tinys3
import os
import urllib
class LocalStorage(object):
def __init__(self, filename):
self.filename = filename
def get_file_data(self):
"""
Returns the raw data for the spec... | """
Returns the raw data for the specific file, downloading it from S3
"""
path = self.get_remote_path()
data = urllib.urlopen(path).read()
return data
def store(self, file_instance, content_type=None):
"""
Copy over the `file_instance` from memory to... | return 'https://%s.%s/%s' % (self.conn.default_bucket, self.conn.endpoint, self.filename)
def get_file_data(self): | random_line_split |
storage.py | from django.conf import settings
from images.models import S3Connection
from shutil import copyfileobj
import tinys3
import os
import urllib
class LocalStorage(object):
def __init__(self, filename):
self.filename = filename
def get_file_data(self):
"""
Returns the raw data for the spec... | (LocalStorage):
def __init__(self, *args, **kwargs):
"""
Overrides the LocalStorage and initializes a shared S3 connection
"""
super(S3Storage, self).__init__(*args, **kwargs)
self.conn = tinys3.Connection(self.S3_ACCESS_KEY, self.S3_SECRET_KEY, default_bucket=self.S3_BUCKET,... | S3Storage | identifier_name |
master.py | # Copyright 2015 Philipp Pahl, Sven Schubert, Daniel Britzger
#
# 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 appl... | (peachbox.model.MasterDataSet,TaskImportModel):
"""A particular realization of an 'edge'. Here: the user review edge """
data_unit_index = 0
partition_key = 'true_as_of_seconds'
partition_granularity = 60*60*24*360
schema = [{'field':'user_id', 'type':'StringType'},
{'field':'review_i... | UserReviewEdge | identifier_name |
master.py | # Copyright 2015 Philipp Pahl, Sven Schubert, Daniel Britzger
#
# 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 appl... | {'field':'profile_name', 'type':'StringType'}] | random_line_split | |
master.py | # Copyright 2015 Philipp Pahl, Sven Schubert, Daniel Britzger
#
# 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 appl... | lambda row: int(row['helpfulness'].split('/')[0])
def fill_review_id(self, row, field):
user_id = row['user_id']
product_id = row['product_id']
true_as_of_seconds = row['time']
return unicode(hash(user_id+product_id+str(true_as_of_seconds)))
def fill_nothelpful(self, ro... | """A particular realization of a node, containing several properties. Here: the review properties """
data_unit_index = 2
partition_key = 'true_as_of_seconds'
partition_granularity = 60*60*24*360
time_fill_method = fill_name('time')
model = [{'field':'review_id', 'type':'StringType', 'fill_method':... | identifier_body |
query.rs | use crate::namespace::*;
use crate::sparql::pattern::Pattern;
use crate::uri::Uri;
use crate::Result;
/// Query type.
#[derive(Clone, Debug)]
pub enum SparqlQueryType {
Ask,
Select,
SelectDistinct,
SelectReduced,
SelectAll,
SelectAllDistinct,
SelectAllReduced,
Construct,
Describe,
}... | // Variables used in the query.
variables: Vec<String>,
// Patterns used as constraints.
patterns: Vec<Box<Pattern>>,
}
impl SparqlQuery {
/// Constructor of `SparqlQuery`.
pub fn new(query_type: SparqlQueryType) -> SparqlQuery {
SparqlQuery {
query_type: query_type,
... | /// Namespaces stated in SPARQL query.
namespaces: NamespaceStore,
| random_line_split |
query.rs | use crate::namespace::*;
use crate::sparql::pattern::Pattern;
use crate::uri::Uri;
use crate::Result;
/// Query type.
#[derive(Clone, Debug)]
pub enum SparqlQueryType {
Ask,
Select,
SelectDistinct,
SelectReduced,
SelectAll,
SelectAllDistinct,
SelectAllReduced,
Construct,
Describe,
}... |
/// Get query variables.
///
/// todo
///
pub fn get_query_variables(&self) -> &Vec<String> {
&self.variables
}
/// Get the query patterns in the `WHERE` expression.
///
/// todo
///
// pub fn get_query_patterns(&self) -> &Vec<Pattern> {
// &self.patterns
... | {
&self.query_type
} | identifier_body |
query.rs | use crate::namespace::*;
use crate::sparql::pattern::Pattern;
use crate::uri::Uri;
use crate::Result;
/// Query type.
#[derive(Clone, Debug)]
pub enum | {
Ask,
Select,
SelectDistinct,
SelectReduced,
SelectAll,
SelectAllDistinct,
SelectAllReduced,
Construct,
Describe,
}
/// Represents a SPARQL query that can be applied to an RDF graph.
/// `SparqlQuery`s are created when parsing a SPARQL string using `SparqlParser`.
pub struct Sparq... | SparqlQueryType | identifier_name |
mod.rs | use crate::rendering::*;
use crate::geometry::*;
/// IMPORTANT: Must form a star domain at its center
#[derive(Clone, Debug)]
pub struct Polygon {
pub corners: Vec<Point>, /// defined anti-clockwise
pub center: Point,
pub rot: Rotation, /// anti-clockwise angle w.r.t. positive z-axis
pub pos: Point3,
... |
pub fn get_vertices(self) -> Vec<PolygonVertex> {
let mut output: Vec<PolygonVertex> = vec![];
let corners_it_shift = self.corners.clone().into_iter().cycle().skip(1);
for (corner1, corner2) in self.corners.into_iter().zip(corners_it_shift) {
output.push(PolygonVertex {
... | {
Polygon {
corners,
center,
rot: Rotation::new(0.0),
pos,
color,
fixed,
}
} | identifier_body |
mod.rs | use crate::rendering::*;
use crate::geometry::*;
/// IMPORTANT: Must form a star domain at its center
#[derive(Clone, Debug)]
pub struct Polygon {
pub corners: Vec<Point>, /// defined anti-clockwise
pub center: Point,
pub rot: Rotation, /// anti-clockwise angle w.r.t. positive z-axis
pub pos: Point3,
... | )
}
fn get_vertex(self) -> Vec<Self::Vertex> { self.get_vertices() }
}
#[derive(Copy, Clone, Debug)]
pub struct PolygonVertex {
pub corner1: [f32; 2],
pub corner2: [f32; 2],
pub center: [f32; 2],
pub rot: [[f32; 2]; 2],
pub pos: [f32; 3],
pub color: [f32; 4],
pub fixed_pos:... | include_str!("polygon.ges"),
include_str!("polygon.fs") | random_line_split |
mod.rs | use crate::rendering::*;
use crate::geometry::*;
/// IMPORTANT: Must form a star domain at its center
#[derive(Clone, Debug)]
pub struct Polygon {
pub corners: Vec<Point>, /// defined anti-clockwise
pub center: Point,
pub rot: Rotation, /// anti-clockwise angle w.r.t. positive z-axis
pub pos: Point3,
... | {
pub corner1: [f32; 2],
pub corner2: [f32; 2],
pub center: [f32; 2],
pub rot: [[f32; 2]; 2],
pub pos: [f32; 3],
pub color: [f32; 4],
pub fixed_pos: u32
}
implement_vertex!(PolygonVertex, corner1, corner2, center, rot, pos, color, fixed_pos);
| PolygonVertex | identifier_name |
viewerjs-tests.ts | import Viewer from 'viewerjs';
////////////////
// Static Methods
////////////////
Viewer.setDefaults({});
Viewer.noConflict();
////////////////
// Constructors
////////////////
const pictures: Element = <Element> document.querySelector('.docs-pictures');
let viewer = new Viewer(pictures);
viewer = new Viewer(pict... | movable: true,
// Enable to zoom the image
zoomable: true,
// Enable to rotate the image
rotatable: true,
// Enable to scale the image
scalable: true,
// Enable CSS3 Transition for some special elements
transition: true,
// Enable to r... |
// Enable to move the image | random_line_split |
fixtures.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as fs from 'fs-extra';
import { sleep } from '../client/common/utils/async';
import { PYTHON_PATH } from './common';
import { Proc, spawn } from './proc';
export type CleanupFunc = (() => void) | (() => Promise<vo... | (name: string, ...args: string[]): Proc {
return this.spawn('-m', name, ...args);
}
private spawn(...args: string[]) {
const proc = spawn(this.python, ...args);
this.addCleanup(async () => {
if (!proc.exited) {
await sleep(1000); // Wait a sec before the hamm... | runModule | identifier_name |
fixtures.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as fs from 'fs-extra';
import { sleep } from '../client/common/utils/async';
import { PYTHON_PATH } from './common';
import { Proc, spawn } from './proc';
export type CleanupFunc = (() => void) | (() => Promise<vo... | ) {
super();
if (python) {
this.python = python;
} else {
this.python = PYTHON_PATH;
}
}
public runScript(filename: string, ...args: string[]): Proc {
return this.spawn(filename, ...args);
}
public runModule(name: string, ...args: str... | random_line_split | |
fixtures.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as fs from 'fs-extra';
import { sleep } from '../client/common/utils/async';
import { PYTHON_PATH } from './common';
import { Proc, spawn } from './proc';
export type CleanupFunc = (() => void) | (() => Promise<vo... |
});
return proc;
}
}
| {
await sleep(1000); // Wait a sec before the hammer falls.
try {
proc.raw.kill();
} catch {
// It already finished.
}
} | conditional_block |
collapsible_match.rs | span_lint_and_then;
use clippy_utils::visitors::LocalUsedVisitor;
use clippy_utils::{higher, is_lang_ctor, is_unit_expr, path_to_local, peel_ref_operators, SpanlessEq};
use if_chain::if_chain;
use rustc_hir::LangItem::OptionNone;
use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, MatchSource, Pat, PatKind, StmtKind};
u... | (&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
match IfLetOrMatch::parse(cx, expr) {
Some(IfLetOrMatch::Match(_, arms, _)) => {
if let Some(els_arm) = arms.iter().rfind(|arm| arm_is_wild_like(cx, arm)) {
for arm in arms {
check_ar... | check_expr | identifier_name |
collapsible_match.rs | span_lint_and_then;
use clippy_utils::visitors::LocalUsedVisitor;
use clippy_utils::{higher, is_lang_ctor, is_unit_expr, path_to_local, peel_ref_operators, SpanlessEq};
use if_chain::if_chain;
use rustc_hir::LangItem::OptionNone;
use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, MatchSource, Pat, PatKind, StmtKind};
u... |
}
fn check_arm<'tcx>(
cx: &LateContext<'tcx>,
outer_is_match: bool,
outer_pat: &'tcx Pat<'tcx>,
outer_then_body: &'tcx Expr<'tcx>,
outer_guard: Option<&'tcx Guard<'tcx>>,
outer_else_body: Option<&'tcx Expr<'tcx>>
) {
let inner_expr = strip_singleton_blocks(outer_then_body);
if_chain! {... | {
match IfLetOrMatch::parse(cx, expr) {
Some(IfLetOrMatch::Match(_, arms, _)) => {
if let Some(els_arm) = arms.iter().rfind(|arm| arm_is_wild_like(cx, arm)) {
for arm in arms {
check_arm(cx, true, arm.pat, arm.body, arm.guard.as_ref(), Some... | identifier_body |
collapsible_match.rs | ::span_lint_and_then;
use clippy_utils::visitors::LocalUsedVisitor;
use clippy_utils::{higher, is_lang_ctor, is_unit_expr, path_to_local, peel_ref_operators, SpanlessEq};
use if_chain::if_chain;
use rustc_hir::LangItem::OptionNone;
use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, MatchSource, Pat, PatKind, StmtKind};... | /// Ok(n) => n,
/// _ => return,
/// }
/// None => return,
/// };
/// }
/// ```
/// Use instead:
/// ```rust
/// fn func(opt: Option<Result<u64, String>>) {
/// let n = match opt {
/// Some(Ok(n)) => n,
/// ... | /// fn func(opt: Option<Result<u64, String>>) {
/// let n = match opt {
/// Some(n) => match n { | random_line_split |
mensajes.js | /* * @felipe de jesus | iti_fjpp@hotmail.com */
var msj_beforeSend=function (){
bootbox.dialog({
title: 'Vive Pueblos Mágicos',
message: '<center><i class="fa fa-spinner fa-spin fa-3x msjOk"></i><br>Espere por favor.</center>'
,onEscape : function() {}
});
... | ){
coordx= screen.width ? (screen.width-200)/2 : 0;
coordy= screen.height ? (screen.height-150)/2 : 0;
window.open(base_url+ 'config/mapa','miventana','width=800,height=600,top=30,right='+coordx+',left='+coordy);
} ;
var msj_error_noti=function (msj){
Messenger().post({
... | entana( | identifier_name |
mensajes.js | /* * @felipe de jesus | iti_fjpp@hotmail.com */
var msj_beforeSend=function (){
bootbox.dialog({
title: 'Vive Pueblos Mágicos',
message: '<center><i class="fa fa-spinner fa-spin fa-3x msjOk"></i><br>Espere por favor.</center>'
,onEscape : function() {}
});
... | return yyyy+'/'+mm+'/'+dd;
}
var fecha_dd_mm_yyyy=function (){
var hoy = new Date();
var dd = hoy.getDate();
var mm = hoy.getMonth()+1; //hoy es 0!
var yyyy = hoy.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
... | mm='0'+mm;
}
| conditional_block |
mensajes.js | /* * @felipe de jesus | iti_fjpp@hotmail.com */
var msj_beforeSend=function (){
bootbox.dialog({
title: 'Vive Pueblos Mágicos',
message: '<center><i class="fa fa-spinner fa-spin fa-3x msjOk"></i><br>Espere por favor.</center>'
,onEscape : function() {}
});
... | ;
var msj_error_noti=function (msj){
Messenger().post({
message: msj,
type: 'error',
showCloseButton: true
});
}
var msj_error_serve=function (){
Messenger().post({
message: 'Error al procesar la petición al servidor',
type... |
coordx= screen.width ? (screen.width-200)/2 : 0;
coordy= screen.height ? (screen.height-150)/2 : 0;
window.open(base_url+ 'config/mapa','miventana','width=800,height=600,top=30,right='+coordx+',left='+coordy);
} | identifier_body |
mensajes.js | /* * @felipe de jesus | iti_fjpp@hotmail.com */
var msj_beforeSend=function (){
bootbox.dialog({
title: 'Vive Pueblos Mágicos',
message: '<center><i class="fa fa-spinner fa-spin fa-3x msjOk"></i><br>Espere por favor.</center>'
,onEscape : function() {}
});
... | document.title=(titulo ==undefined ? 'Vive Pueblos Mágicos' :titulo );
}
var get_fecha=function (){
var meses = new Array ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
var diasSemana = new Array("Domingo","Lunes","Ma... | });
}
var title=function (titulo){ | random_line_split |
removeRoomLeader.js | import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { hasPermission } from '../../app/authorization';
import { Users, Subscriptions, Messages } from '../../app/models';
import { settings } from '../../app/settings';
import { Notifications } from '../../app/notifications';
Meteor.metho... | });
}
const user = Users.findOneById(userId);
if (!user || !user.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomLeader',
});
}
const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (!subscription) {
throw new Meteor.... | }
if (!hasPermission(Meteor.userId(), 'set-leader', rid)) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'removeRoomLeader', | random_line_split |
removeRoomLeader.js | import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { hasPermission } from '../../app/authorization';
import { Users, Subscriptions, Messages } from '../../app/models';
import { settings } from '../../app/settings';
import { Notifications } from '../../app/notifications';
Meteor.metho... | (rid, userId) {
check(rid, String);
check(userId, String);
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomLeader',
});
}
if (!hasPermission(Meteor.userId(), 'set-leader', rid)) {
throw new Meteor.Error('error-not-allowed', 'Not allowed'... | removeRoomLeader | identifier_name |
removeRoomLeader.js | import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { hasPermission } from '../../app/authorization';
import { Users, Subscriptions, Messages } from '../../app/models';
import { settings } from '../../app/settings';
import { Notifications } from '../../app/notifications';
Meteor.metho... |
return true;
},
});
| {
Notifications.notifyLogged('roles-change', {
type: 'removed',
_id: 'leader',
u: {
_id: user._id,
username: user.username,
name: user.name,
},
scope: rid,
});
} | conditional_block |
removeRoomLeader.js | import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { hasPermission } from '../../app/authorization';
import { Users, Subscriptions, Messages } from '../../app/models';
import { settings } from '../../app/settings';
import { Notifications } from '../../app/notifications';
Meteor.metho... | method: 'removeRoomLeader',
});
}
const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'removeRoomLeader',
});
}
if (Array.isArray(subscription.roles) === true... | {
check(rid, String);
check(userId, String);
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomLeader',
});
}
if (!hasPermission(Meteor.userId(), 'set-leader', rid)) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method... | identifier_body |
mongodb.py | #!/bin/python
from zeroos.core0.client import Client
import sys
import time
"""
This script expect you know the IP of the core0 and you can access it from the machine running this script.
an easy way to do it is to build the initramfs with a customr zerotier network id (https://github.com/g8os/initramfs/tree/0.10.0#c... | disks_by_name = {d['name']: d for d in disks}
if disks_by_name['sda']['mountpoint'] is None:
print("[+] mount disk")
cl.disk.mount('/dev/sda', '/dev/mongodb_storage', [''])
try:
print("[+] create container")
container_id = cl.container.create('https://stor.jumpscale.org/stor... | print("[+] connect to core0")
cl = Client(CORE0IP)
try:
cl.ping()
except Exception as e:
print("cannot connect to the core0: %s" % e)
return 1
print("[+] prepare data disks")
cl.system('mkdir -p /dev/mongodb_storage').get()
if init:
cl.btrfs.create('mongodb_sto... | identifier_body |
mongodb.py | #!/bin/python
from zeroos.core0.client import Client
import sys
import time
"""
This script expect you know the IP of the core0 and you can access it from the machine running this script.
an easy way to do it is to build the initramfs with a customr zerotier network id (https://github.com/g8os/initramfs/tree/0.10.0#c... |
time.sleep(2)
i += 1
raise TimeoutError("[-] couldn't get an ip on zerotier network")
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='attach disks to core0')
parser.add_argument('--init', type=bool, default=False, const=True, required=False,
... | cidr = info['addrs'][0]['addr']
return cidr.split('/')[0] | conditional_block |
mongodb.py | #!/bin/python
from zeroos.core0.client import Client
import sys
import time
""" | CORE0IP = "INSERT CORE0 IP HERE"
ZEROTIER = "INSERT ZEROTIER NETWORK ID HERE"
def main(init=False):
print("[+] connect to core0")
cl = Client(CORE0IP)
try:
cl.ping()
except Exception as e:
print("cannot connect to the core0: %s" % e)
return 1
print("[+] prepare data disks"... | This script expect you know the IP of the core0 and you can access it from the machine running this script.
an easy way to do it is to build the initramfs with a customr zerotier network id (https://github.com/g8os/initramfs/tree/0.10.0#customize-build)
At boot core0 will connect to the zerotier network and you can ass... | random_line_split |
mongodb.py | #!/bin/python
from zeroos.core0.client import Client
import sys
import time
"""
This script expect you know the IP of the core0 and you can access it from the machine running this script.
an easy way to do it is to build the initramfs with a customr zerotier network id (https://github.com/g8os/initramfs/tree/0.10.0#c... | (container):
i = 0
while i < 10:
addrs = container.info.nic()
ifaces = {a['name']: a for a in addrs}
for iface, info in ifaces.items():
if iface.startswith('zt'):
cidr = info['addrs'][0]['addr']
return cidr.split('/')[0]
time.sleep(2)... | get_zerotier_ip | identifier_name |
filter_state.ts | /*
MIT License
Copyright (c) 2022 Looker Data Sciences, Inc.
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, modi... | import type { FilterASTNode } from '@looker/filter-expressions'
/**
* Interface for the <Filter/> component's state property
*/
export interface FilterState {
ast: FilterASTNode | undefined
expression: string
} | random_line_split | |
fallback.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fmt;
use std::sync::Arc;
use anyhow::Error;
use futures::{channel::mpsc::channel, SinkExt, StreamExt, TryStreamExt};
use tracing::e... | <K, VP, VF, VW> {
/// The preferred store, which will always be queried. Usually a local store.
pub preferred: BoxedReadStore<K, VP>,
/// The fallback store, which will be queried if the value is not found in the
/// primary store.
pub fallback: BoxedReadStore<K, VF>,
/// A `WriteStore` to whi... | FallbackCache | identifier_name |
fallback.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fmt;
use std::sync::Arc;
use anyhow::Error;
use futures::{channel::mpsc::channel, SinkExt, StreamExt, TryStreamExt}; | use crate::scmstore::{
BoxedReadStore, BoxedWriteStore, FetchError, FetchStream, KeyStream, ReadStore,
};
/// A combinator which queries a preferred store, then falls back to a fallback store
/// if a key is not found in the preferred store. Keys fetched from the fallback will
/// be written to the write_store if ... | use tracing::error;
use streams::select_drop;
| random_line_split |
fallback.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fmt;
use std::sync::Arc;
use anyhow::Error;
use futures::{channel::mpsc::channel, SinkExt, StreamExt, TryStreamExt};
use tracing::e... | },
// TODO(meyer): Should we also fall back on KeyedError, but also log an error?
Err(e) => Some(Err(e)),
}
}
});
let fallback_stream = self
.fallback
.clone()
... | {
// TODO(meyer): Write a custom Stream implementation to try to avoid use of channels
let (sender, receiver) = channel(CHANNEL_BUFFER);
let preferred_stream = self
.preferred
.clone()
.fetch_stream(keys)
.filter_map(move |res| {
l... | identifier_body |
RollbackServerGroupModal.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import Select from 'react-select';
import type { IModalComponentProps } from '@spinnaker/core';
import {
ModalClose,
noop,
ReactInjector,
ReactModal,
TaskMonitor,
TaskMonitorWrapper,
TaskReason,
} from '@spinnaker/core';
import { AzureM... |
constructor(props: IAzureRollbackServerGroupModalProps) {
super(props);
const { application, serverGroup } = props;
this.state = {
taskMonitor: new TaskMonitor({
application: application,
title: 'Rolling back your server group',
modalInstance: TaskMonitor.modalInstanceEmu... | {
const modalProps = {};
return ReactModal.show(AzureRollbackServerGroupModal, props, modalProps);
} | identifier_body |
RollbackServerGroupModal.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import Select from 'react-select';
import type { IModalComponentProps } from '@spinnaker/core';
import {
ModalClose,
noop,
ReactInjector,
ReactModal,
TaskMonitor,
TaskMonitorWrapper,
TaskReason,
} from '@spinnaker/core';
import { AzureM... | (props: IAzureRollbackServerGroupModalProps) {
super(props);
const { application, serverGroup } = props;
this.state = {
taskMonitor: new TaskMonitor({
application: application,
title: 'Rolling back your server group',
modalInstance: TaskMonitor.modalInstanceEmulation(() => th... | constructor | identifier_name |
RollbackServerGroupModal.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import Select from 'react-select';
import type { IModalComponentProps } from '@spinnaker/core';
import {
ModalClose,
noop,
ReactInjector,
ReactModal,
TaskMonitor,
TaskMonitorWrapper,
TaskReason,
} from '@spinnaker/core';
import { AzureM... | } | );
} | random_line_split |
framerate.rs | //! Framerate control
use libc;
use libc::{c_void, size_t};
use std::mem;
use ::get_error;
use sys::gfx;
/// Structure holding the state and timing information of the framerate controller.
pub struct FPSManager {
raw: *mut gfx::framerate::FPSmanager,
}
impl FPSManager {
/// Create the framerate manager.
... | (&self) -> i32 {
// will not get an error
unsafe { gfx::framerate::SDL_getFramerate(self.raw) as i32 }
}
/// Return the current framecount.
pub fn get_frame_count(&self) -> i32 {
// will not get an error
unsafe { gfx::framerate::SDL_getFramecount(self.raw) as i32 }
}
... | get_framerate | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.