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 |
|---|---|---|---|---|
plivo.js | var extend = require('extend');
var plivo = require('plivo');
var crypto = require('crypto')
var phone = require('phone');
var TelcomPlivoClient = module.exports = function(opts){
if (!(this instanceof TelcomPlivoClient))
return new TelcomPlivoClient(options);
this.options = {};
extend(this.options,opts);
... |
TelcomPlivoClient.prototype.sms = function(obj,callback){
var plivoMesg = {
src : phone(obj.from),
dst : phone(obj.to),
text : obj.body
};
/*
{
api_id: 'xxxxxxxxx-1f9d-11e3-b44b-22000ac53995',
message: 'message(s) queued',
message_uuid: [ 'xxxxxxxx-1f9d-11e3-b1d3-123141013a24' ]
}... | callback('signature does not match');
} | random_line_split |
plivo.js | var extend = require('extend');
var plivo = require('plivo');
var crypto = require('crypto')
var phone = require('phone');
var TelcomPlivoClient = module.exports = function(opts){
if (!(this instanceof TelcomPlivoClient))
return new TelcomPlivoClient(options);
this.options = {};
extend(this.options,opts);
... | (url, params,token) {
var toSign = url;
Object.keys(params).sort().forEach(function(key) {
toSign += key + params[key];
});
var signature = crypto
.createHmac('sha1',token)
.update(toSign)
.digest('base64');
return signature;
};
| create_signature | identifier_name |
plivo.js | var extend = require('extend');
var plivo = require('plivo');
var crypto = require('crypto')
var phone = require('phone');
var TelcomPlivoClient = module.exports = function(opts){
if (!(this instanceof TelcomPlivoClient))
return new TelcomPlivoClient(options);
this.options = {};
extend(this.options,opts);
... | ;
| {
var toSign = url;
Object.keys(params).sort().forEach(function(key) {
toSign += key + params[key];
});
var signature = crypto
.createHmac('sha1',token)
.update(toSign)
.digest('base64');
return signature;
} | identifier_body |
save-case.component.ts | import { ChangeDetectionStrategy, Component, HostBinding, Input, OnDestroy, OnInit } from '@angular/core';
import { animate, style, transition, trigger } from '@angular/animations';
import { select, Store } from '@ngrx/store';
import { ICasesState, selectCaseById, selectSelectedCase } from '../../reducers/cases.reducer... | return this.cloneDeepOneTime(selectSelectedCase).pipe(
tap((selectedCase: ICase) => {
this.store.dispatch(new SaveCaseAsAction({ ...selectedCase, name: this.caseName }));
})
)
}
renameCase() {
return this.cloneDeepOneTime(selectCaseById(this.caseId)).pipe(
tap( (_case: ICase) => {
const oldNam... | this.store.dispatch(new CloseModalAction());
}
saveNewCase() { | random_line_split |
save-case.component.ts | import { ChangeDetectionStrategy, Component, HostBinding, Input, OnDestroy, OnInit } from '@angular/core';
import { animate, style, transition, trigger } from '@angular/animations';
import { select, Store } from '@ngrx/store';
import { ICasesState, selectCaseById, selectSelectedCase } from '../../reducers/cases.reducer... | ;
constructor(
protected store: Store<ICasesState>
) {
}
@AutoSubscription
caseName$ = () => this.store.pipe(
select(selectCaseById(this.caseId)),
tap( (_case) => {
this.caseName = _case ? _case.name : moment(new Date()).format('DD/MM/YYYY HH:mm:ss').toLocaleString();
})
);
private cloneDeepOneTim... | {
return true;
} | identifier_body |
save-case.component.ts | import { ChangeDetectionStrategy, Component, HostBinding, Input, OnDestroy, OnInit } from '@angular/core';
import { animate, style, transition, trigger } from '@angular/animations';
import { select, Store } from '@ngrx/store';
import { ICasesState, selectCaseById, selectSelectedCase } from '../../reducers/cases.reducer... | (): void {
this.store.dispatch(new CloseModalAction());
}
saveNewCase() {
return this.cloneDeepOneTime(selectSelectedCase).pipe(
tap((selectedCase: ICase) => {
this.store.dispatch(new SaveCaseAsAction({ ...selectedCase, name: this.caseName }));
})
)
}
renameCase() {
return this.cloneDeepOneTime(... | close | identifier_name |
doughnut-chart-demo.ts | import {Component, EventEmitter} from 'angular2/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from 'angular2/common';
import {CHART_DIRECTIVES} from '../../../ng2-charts';
// webpack html imports
let template = require('./doughnut-chart-demo.html');
@Component({
selector: 'doughnut-chart-demo',
templ... |
// events
chartClicked(e:any) {
console.log(e);
}
chartHovered(e:any) {
console.log(e);
}
// Doughnut
private doughnutChartLabels = ['Download Sales', 'In-Store Sales', 'Mail-Order Sales'];
private doughnutChartData = [350, 450, 100];
private doughnutChartType = 'Doughnut';
}
| {
console.log('doughnut demo');
} | identifier_body |
doughnut-chart-demo.ts | import {Component, EventEmitter} from 'angular2/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from 'angular2/common';
import {CHART_DIRECTIVES} from '../../../ng2-charts';
// webpack html imports
let template = require('./doughnut-chart-demo.html');
@Component({ | })
export class DoughnutChartDemo {
constructor() {
console.log('doughnut demo');
}
// events
chartClicked(e:any) {
console.log(e);
}
chartHovered(e:any) {
console.log(e);
}
// Doughnut
private doughnutChartLabels = ['Download Sales', 'In-Store Sales', 'Mail-Order Sales'];
private do... | selector: 'doughnut-chart-demo',
template: template,
directives: [CHART_DIRECTIVES, NgClass, CORE_DIRECTIVES, FORM_DIRECTIVES] | random_line_split |
doughnut-chart-demo.ts | import {Component, EventEmitter} from 'angular2/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from 'angular2/common';
import {CHART_DIRECTIVES} from '../../../ng2-charts';
// webpack html imports
let template = require('./doughnut-chart-demo.html');
@Component({
selector: 'doughnut-chart-demo',
templ... | (e:any) {
console.log(e);
}
chartHovered(e:any) {
console.log(e);
}
// Doughnut
private doughnutChartLabels = ['Download Sales', 'In-Store Sales', 'Mail-Order Sales'];
private doughnutChartData = [350, 450, 100];
private doughnutChartType = 'Doughnut';
}
| chartClicked | identifier_name |
PRESUBMIT.py | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... | (input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
return results
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChan... | CheckChangeOnUpload | identifier_name |
PRESUBMIT.py | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
return input_api.environ.get('PRESUBMIT_TREE_CHECK') == 'skip'
def _CheckChangeLogFlag(input_api, output_api):
"""Checks usage of LOG= flag in the commit message."""
results = []
if input_api.change.BUG and not 'LOG' in input_api.change.tags:
results.append(output_api.PresubmitError(
'An issue re... | return False | conditional_block |
PRESUBMIT.py | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... | import sys
def _V8PresubmitChecks(input_api, output_api):
"""Runs the V8 presubmit checks."""
import sys
sys.path.append(input_api.os_path.join(
input_api.PresubmitLocalPath(), 'tools'))
from presubmit import CppLintProcessor
from presubmit import SourceProcessor
from presubmit import CheckGenerat... | for more details about the presubmit API built into gcl.
"""
| random_line_split |
PRESUBMIT.py | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
def GetPreferredTryMasters(project, change):
return {
'tryserver.v8': {
'v8_linux_rel': set(['defaulttests']),
'v8_linux_dbg': set(['defaulttests']),
'v8_linux_nosnap_rel': set(['defaulttests']),
'v8_linux_nosnap_dbg': set(['defaulttests']),
'v8_linux64_rel': set(['defaulttests'])... | results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
results.extend(input_api.canned_checks.CheckChangeHasDescription(
input_api, output_api))
if not _SkipTreeCheck(input_api, output_api):
results.extend(input_api.canned_checks.Ch... | identifier_body |
edit_student_account_modal.tsx | import * as React from 'react'
import { Input, } from '../../../Shared/index'
import { requestPut } from '../../../../modules/request/index.js';
interface EditStudentAccountModalProps {
close: () => void;
onSuccess: (string) => void;
student: any;
classroom: any;
}
interface EditStudentAccountModalState {
... |
editStudentAccount() {
const { onSuccess, close, student, classroom, } = this.props
const { firstName, lastName, username, timesSubmitted, } = this.state
const user = { name: `${firstName} ${lastName}`, username }
requestPut(`/teachers/classrooms/${classroom.id}/students/${student.id}`, { user, }, (... | {
this.setState({ username: event.target.value })
} | identifier_body |
edit_student_account_modal.tsx | import * as React from 'react'
import { Input, } from '../../../Shared/index'
import { requestPut } from '../../../../modules/request/index.js';
interface EditStudentAccountModalProps {
close: () => void;
onSuccess: (string) => void;
student: any;
classroom: any;
}
interface EditStudentAccountModalState {
... |
})
}
submitButtonClass() {
const { student } = this.props
const { firstName, lastName, username } = this.state
let buttonClass = 'quill-button contained primary medium';
const originalSplitName = student.name.split(' ')
const nothingHasChanged = originalSplitName[0] === firstName && origin... | {
onSuccess('Student account saved')
close()
} | conditional_block |
edit_student_account_modal.tsx | import * as React from 'react'
import { Input, } from '../../../Shared/index'
import { requestPut } from '../../../../modules/request/index.js';
interface EditStudentAccountModalProps {
close: () => void;
onSuccess: (string) => void;
student: any;
classroom: any;
}
interface EditStudentAccountModalState {
... | timesSubmitted={timesSubmitted}
type="text"
value={username}
/>
<div className="form-buttons">
<button className="quill-button outlined secondary medium" onClick={this.props.close}>Cancel</button>
<button className={this.submitButtonClass()... | <Input
className="username"
error={errors.username}
handleChange={this.handleUsernameChange}
label="Username" | random_line_split |
edit_student_account_modal.tsx | import * as React from 'react'
import { Input, } from '../../../Shared/index'
import { requestPut } from '../../../../modules/request/index.js';
interface EditStudentAccountModalProps {
close: () => void;
onSuccess: (string) => void;
student: any;
classroom: any;
}
interface EditStudentAccountModalState {
... | (event) {
this.setState({ firstName: event.target.value })
}
handleLastNameChange(event) {
this.setState({ lastName: event.target.value })
}
handleUsernameChange(event) {
this.setState({ username: event.target.value })
}
editStudentAccount() {
const { onSuccess, close, student, classroom,... | handleFirstNameChange | identifier_name |
test_adapter.py | ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... | ():
return unittest.TestSuite((
DocTestSuite('zope.security.adapter'),
))
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
| test_suite | identifier_name |
test_adapter.py | ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... | unittest.main(defaultTest='test_suite') | conditional_block | |
test_adapter.py | ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... |
if __name__ == '__main__':
unittest.main(defaultTest='test_suite') | random_line_split | |
test_adapter.py | ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... |
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
| return unittest.TestSuite((
DocTestSuite('zope.security.adapter'),
)) | identifier_body |
flotation.py | # coding: utf-8
# In[1]:
import matplotlib.pyplot as plt #import modules
import matplotlib.patches as mpatches
import numpy as np
#get_ipython().magic(u'matplotlib inline') # set to inline for ipython
# In[2]:
water = [0,2,2,3,1.5,1.5,3,2,2,2,2,2.5,2] #arrange data from lab | alc = [0,2.5,2.5,2.5,2.5,3,2.5,2.5]
weight = [20.9+(0.41*5*x) for x in range(0,13)] #generate weight array, based on mass of paper clips, in grams
actWater = [(22)+sum(water[:x+1]) for x in range(0,len(water))] #cumulitive sum of water displacement
actalc = [(28)+sum(alc[:x+1]) for x in range(0,len(alc))] #cumultive ... | random_line_split | |
fake_sign.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | <B: MiningBlockChainClient, M: MinerService>(
client: &Arc<B>,
miner: &Arc<M>,
request: CallRequest,
) -> Result<SignedTransaction, Error> {
let from = request.from.unwrap_or(0.into());
Ok(Transaction {
nonce: request.nonce.unwrap_or_else(|| client.latest_nonce(&from)),
action: request.to.map_or(Action::Creat... | sign_call | identifier_name |
fake_sign.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | {
let from = request.from.unwrap_or(0.into());
Ok(Transaction {
nonce: request.nonce.unwrap_or_else(|| client.latest_nonce(&from)),
action: request.to.map_or(Action::Create, Action::Call),
gas: request.gas.unwrap_or(50_000_000.into()),
gas_price: request.gas_price.unwrap_or_else(|| default_gas_price(&**clien... | identifier_body | |
fake_sign.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use ethcore::client::MiningBlockChainClient;
use ... | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
print_help.rs | extern crate clap;
use clap::App;
#[test]
fn print_app_help() {
let mut app = App::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.args_from_usage("-f, --flag 'some flag'
--option [opt] 'some option'");
// We call a get_matches m... | let mut help = vec![];
app.write_help(&mut help).ok().expect("failed to print help");
assert_eq!(&*String::from_utf8_lossy(&*help), &*String::from("test 1.3\n\
Kevin K.
tests stuff
USAGE:
\ttest [FLAGS] [OPTIONS]
FLAGS:
-f, --flag some flag
-h, --help Prints help information
-V, --... | let _ = app.get_matches_from_safe_borrow(vec![""]);
// Now we check the output of print_help() | random_line_split |
print_help.rs | extern crate clap;
use clap::App;
#[test]
fn | () {
let mut app = App::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.args_from_usage("-f, --flag 'some flag'
--option [opt] 'some option'");
// We call a get_matches method to cause --help and --version to be built
let _ = a... | print_app_help | identifier_name |
print_help.rs | extern crate clap;
use clap::App;
#[test]
fn print_app_help() | FLAGS:
-f, --flag some flag
-h, --help Prints help information
-V, --version Prints version information
OPTIONS:
--option <opt> some option\n"));
}
| {
let mut app = App::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.args_from_usage("-f, --flag 'some flag'
--option [opt] 'some option'");
// We call a get_matches method to cause --help and --version to be built
let _ = app.... | identifier_body |
template_compiler.d.ts | import { Type } from 'angular2/src/facade/lang';
import { CompileDirectiveMetadata, CompilePipeMetadata } from './directive_metadata';
import { SourceModule } from './source_module';
import { ChangeDetectionCompiler } from './change_detector_compiler';
import { StyleCompiler } from './style_compiler';
import { ViewComp... | {
private _runtimeMetadataResolver;
private _templateNormalizer;
private _templateParser;
private _styleCompiler;
private _cdCompiler;
private _protoViewCompiler;
private _viewCompiler;
private _resolvedMetadataCache;
private _genConfig;
private _hostCacheKeys;
private _comp... | TemplateCompiler | identifier_name |
template_compiler.d.ts | import { Type } from 'angular2/src/facade/lang';
import { CompileDirectiveMetadata, CompilePipeMetadata } from './directive_metadata';
import { SourceModule } from './source_module';
import { ChangeDetectionCompiler } from './change_detector_compiler';
import { StyleCompiler } from './style_compiler';
import { ViewComp... | pipes: CompilePipeMetadata[];
constructor(component: CompileDirectiveMetadata, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[]);
} | component: CompileDirectiveMetadata;
directives: CompileDirectiveMetadata[]; | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::slice;
use rand::Rng;
#[derive(Eq, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum GameResult {
Human,
Computer,
Draw,
}
struct Game {
frequencies: [u32; 3],
}
impl Move {
fn beaten_by(&self) -> Move |
fn variants() -> slice::Iter<'static, Move> {
static VARIANTS: &'static [Move] = &[Move::Rock, Move::Paper, Move::Scissors];
VARIANTS.iter()
}
}
impl Game {
fn new() -> Game {
Game{frequencies: [0, 0, 0]}
}
fn increment_frequency(&mut self, m: &Move) {
let i = Mov... | {
match *self {
Move::Rock => Move::Paper,
Move::Paper => Move::Scissors,
Move::Scissors => Move::Rock,
}
} | identifier_body |
main.rs | extern crate rand;
use std::io;
use std::slice;
use rand::Rng;
#[derive(Eq, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum GameResult {
Human,
Computer,
Draw,
}
struct Game {
frequencies: [u32; 3],
}
impl Move {
fn beaten_by(&self) -> Move {
match *s... | VARIANTS.iter()
}
}
impl Game {
fn new() -> Game {
Game{frequencies: [0, 0, 0]}
}
fn increment_frequency(&mut self, m: &Move) {
let i = Move::variants().position(|n| n == m).expect("Unknown frequency.");
self.frequencies[i] += 1;
}
fn pick(&self) -> Move {
... | }
fn variants() -> slice::Iter<'static, Move> {
static VARIANTS: &'static [Move] = &[Move::Rock, Move::Paper, Move::Scissors]; | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::slice;
use rand::Rng;
#[derive(Eq, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum GameResult {
Human,
Computer,
Draw,
}
struct Game {
frequencies: [u32; 3],
}
impl Move {
fn beaten_by(&self) -> Move {
match *s... | else {
GameResult::Draw
}
}
}
fn main() {
let mut game = Game::new();
loop {
println!("Enter a guess (r, p, s): ");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.ok()
.expect("Could not read input.");
l... | {
GameResult::Human
} | conditional_block |
main.rs | extern crate rand;
use std::io;
use std::slice;
use rand::Rng;
#[derive(Eq, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum GameResult {
Human,
Computer,
Draw,
}
struct | {
frequencies: [u32; 3],
}
impl Move {
fn beaten_by(&self) -> Move {
match *self {
Move::Rock => Move::Paper,
Move::Paper => Move::Scissors,
Move::Scissors => Move::Rock,
}
}
fn variants() -> slice::Iter<'static, Move> {
static VARIANTS: &'... | Game | identifier_name |
test_utils.js | /* Copyright 2017 Mozilla Foundation
*
* 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... |
fetch(ref) {
return this._map[ref.toString()];
}
fetchAsync(ref) {
return Promise.resolve(this.fetch(ref));
}
fetchIfRef(obj) {
if (!isRef(obj)) {
return obj;
}
return this.fetch(obj);
}
fetchIfRefAsync(obj) {
return Promise.resolve(this.fetchIfRef(obj));
}
}
export {... | {
this._map = Object.create(null);
for (let key in array) {
let obj = array[key];
this._map[obj.ref.toString()] = obj.data;
}
} | identifier_body |
test_utils.js | /* Copyright 2017 Mozilla Foundation
*
* 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... | (filename, options) {
let params = Object.create(null);
if (isNodeJS()) {
params.data = NodeFileReaderFactory.fetch({
path: TEST_PDFS_PATH.node + filename,
});
} else {
params.url = new URL(TEST_PDFS_PATH.dom + filename, window.location).href;
}
for (let option in options) {
params[optio... | buildGetDocumentParams | identifier_name |
test_utils.js | /* Copyright 2017 Mozilla Foundation
*
* 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... |
return new Promise((resolve, reject) => {
let url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : '');
let fs = require('fs');
fs.readFile(url, (error, data) => {
if (error || !data) {
reject(new Error('Unable to load ' +
(this.isCompressed ? ... | {
return Promise.reject(new Error('CMap name must be specified.'));
} | conditional_block |
test_utils.js | /* Copyright 2017 Mozilla Foundation
*
* 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... | class NodeFileReaderFactory {
static fetch(params) {
var fs = require('fs');
var file = fs.readFileSync(params.path);
return new Uint8Array(file);
}
}
const TEST_PDFS_PATH = {
dom: '../pdfs/',
node: './test/pdfs/',
};
function buildGetDocumentParams(filename, options) {
let params = Object.creat... | random_line_split | |
import_odbc.py | License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
... | log['last_warn_count'] += 1
#Try ignoring each many2one (tip: in the SQL sentence select more problematic FKs first)
i = find_m2o(cols)
if i >= 0:
#Try again without the [i] column
del cols[i]
del data[i]
... | #Warn and retry ignoring many2one fields...
append_to_log(log, 'WARN', data, errmsg)
| random_line_split |
import_odbc.py | version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy o... | import_schedule | identifier_name | |
import_odbc.py | License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
... | 'last_run': None,
'last_record_count': 0,
'last_error_count': 0,
'last_warn_count': 0,
'last_log': list()}
self.write(cr, uid, [obj.id], log)
#Prepare SQL sentence; replace "%s" with the last_s... | db_model = self.pool.get('base.external.dbsource')
actions = self.read(cr, uid, ids, ['id', 'exec_order'])
actions.sort(key=lambda x: (x['exec_order'], x['id']))
#Consider each dbtable:
for action_ref in actions:
obj = self.browse(cr, uid, action_ref['id'])
... | identifier_body |
import_odbc.py | License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
... |
else:
sync = datetime.datetime(1900, 1, 1, 0, 0, 0)
params = {'sync': sync}
res = db_model.execute(cr, uid, [obj.dbsource_id.id],
obj.sql_source, params, metadata=True)
#Exclude columns titled "None"; add (xml_)"... | sync = datetime.strptime(obj.last_sync, "%Y-%m-%d %H:%M:%S") | conditional_block |
state-machine-tests.ts | interface StateMachineTest extends StateMachine { | warn?: StateMachineEvent;
panic?: StateMachineEvent;
calm?: StateMachineEvent;
clear?: StateMachineEvent;
}
var fsm: StateMachineTest = StateMachine.create({
initial: 'green',
events: [
{ name: 'warn', from: 'green', to: 'yellow' },
{ name: 'panic', from: 'yellow', to: 'red' },
{ name: 'c... | random_line_split | |
command.rs | {
if let Some(color) = targets.colors[i] {
let attachment = render_pass_descriptor.color_attachments().object_at(i);
attachment.set_texture(unsafe { *(color.0) });
attachment.set_store_action(MTLStoreAction::Store); // TODO: Multisample?
if l... | call_draw | identifier_name | |
command.rs | _clear.clear();
self.dsv_clear.clear();
}
self.encoder.end_encoding();
self.encoder.commit_command_buffer(drawable, false);
self.encoder.reset();
self.should_restore = false;
}
fn ensure_render_encoder(&mut self) {
if !self.encoder.has_command_buffe... |
fn set_scissor(&mut self, rect: target::Rect) {
// TODO(fkaa): why are getting 1x1 scissor?
/*self.encoder.set_scissor_rect(MTLScissorRect {
x: rect.x as u64,
y: rect.y as u64,
width: (rect.x + rect.w) as u64,
height: (rect.y + rect.h) as u64,
... | {
use map::map_index_type;
// TODO(fkaa): pass wrapper instead
self.encoder.set_index_buffer(unsafe { *(buf.0).0 }, map_index_type(idx_type));
} | identifier_body |
command.rs | tv_clear.clear();
self.dsv_clear.clear();
}
self.encoder.end_encoding();
self.encoder.commit_command_buffer(drawable, false);
self.encoder.reset();
self.should_restore = false;
}
fn ensure_render_encoder(&mut self) {
if !self.encoder.has_command_buf... | stencil_attachment.set_load_action(MTLLoadAction::Load);
}
}
}
self.encoder.set_render_pass_descriptor(render_pass_descriptor);
if let Some(dim) = targets.dimensions {
self.encoder.set_viewport(MTLViewport {
originX: 0f... | } else {
// see above
attachment.set_load_action(MTLLoadAction::Load);
if let Some(stencil_attachment) = stencil_attachment { | random_line_split |
student.service.spec.ts | import {
beforeEachProviders,
describe,
inject,
it,
beforeEach
} from '@angular/core/testing';
import { provideStore, Store } from '@ngrx/store';
import { StudentService } from './student.service';
import { AppStore } from '../reducers/app.store';
import { Student, GradedAssignment, Assignment } from '../mod... | CURRENT_STUDENT,
SET_STUDENTS
} from '../reducers/index';
describe('StudentService', () => {
beforeEachProviders(() => [
StudentService,
provideStore(REDUCERS)
]);
let service: StudentService;
let store: Store<AppStore>;
beforeEach(inject([StudentService, Store], (serv, sto) => {
service = ... | random_line_split | |
app.module.ts | import { Component, ViewEncapsulation, NgModule } from '@angular/core';
import { IonicApp, IonicModule } from '../../../../../ionic-angular';
@Component({
templateUrl: 'main.html',
encapsulation: ViewEncapsulation.None
})
export class E2EPage {
lastMonth: number;
items = [];
constructor() {
var utcSeco... | footerFn(record: any, recordIndex: number, records: any[]) {
if (recordIndex === records.length - 1) {
return true;
} else {
if (records[recordIndex + 1].date.getMonth() !== this.lastMonth) {
return true;
}
}
return null;
}
ngDoCheck() {
console.log('DoCheck');
... | random_line_split | |
app.module.ts | import { Component, ViewEncapsulation, NgModule } from '@angular/core';
import { IonicApp, IonicModule } from '../../../../../ionic-angular';
@Component({
templateUrl: 'main.html',
encapsulation: ViewEncapsulation.None
})
export class E2EPage {
lastMonth: number;
items = [];
constructor() {
var utcSeco... | else {
if (records[recordIndex + 1].date.getMonth() !== this.lastMonth) {
return true;
}
}
return null;
}
ngDoCheck() {
console.log('DoCheck');
}
reload() {
window.location.reload(true);
}
}
@Component({
template: '<ion-nav [root]="root"></ion-nav>',
})
export clas... | {
return true;
} | conditional_block |
app.module.ts | import { Component, ViewEncapsulation, NgModule } from '@angular/core';
import { IonicApp, IonicModule } from '../../../../../ionic-angular';
@Component({
templateUrl: 'main.html',
encapsulation: ViewEncapsulation.None
})
export class E2EPage {
lastMonth: number;
items = [];
constructor() {
var utcSeco... | () {
window.location.reload(true);
}
}
@Component({
template: '<ion-nav [root]="root"></ion-nav>',
})
export class E2EApp {
root = E2EPage;
}
@NgModule({
declarations: [
E2EApp,
E2EPage
],
imports: [
IonicModule.forRoot(E2EApp)
],
bootstrap: [IonicApp],
entryComponents: [
E2EA... | reload | identifier_name |
index.ts | export type Resolver = (...args: any[]) => any;
export interface MapLike<K = unknown, V = unknown> {
set(key: K, v: V): MapLike<K, V>;
get(key: K): V;
has(key: K): boolean;
}
export interface Config {
resolver?: Resolver;
cache?: MapLike;
}
function memoize(func: Function, resolver: Resolver, cache: MapLik... |
const defaultResolver: Resolver = (...args: any[]) => args[0];
export const memo = (config: Config = {}) =>
(_: any, __: string, descriptor: PropertyDescriptor): PropertyDescriptor => {
if (typeof descriptor.value !== 'function') {
throw new Error('Memoization can be applied only to methods');
... | {
const memoized = function() {
const args = arguments;
// @ts-ignore: ignore implicit any type
const key = resolver.apply(this, args);
const cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
// @ts-ignore: ignore implicit any type
const result = func.apply... | identifier_body |
index.ts | export type Resolver = (...args: any[]) => any;
export interface MapLike<K = unknown, V = unknown> {
set(key: K, v: V): MapLike<K, V>;
get(key: K): V;
has(key: K): boolean;
}
export interface Config { | resolver?: Resolver;
cache?: MapLike;
}
function memoize(func: Function, resolver: Resolver, cache: MapLike) {
const memoized = function() {
const args = arguments;
// @ts-ignore: ignore implicit any type
const key = resolver.apply(this, args);
const cache = memoized.cache;
if (cache.has(key... | random_line_split | |
index.ts | export type Resolver = (...args: any[]) => any;
export interface MapLike<K = unknown, V = unknown> {
set(key: K, v: V): MapLike<K, V>;
get(key: K): V;
has(key: K): boolean;
}
export interface Config {
resolver?: Resolver;
cache?: MapLike;
}
function | (func: Function, resolver: Resolver, cache: MapLike) {
const memoized = function() {
const args = arguments;
// @ts-ignore: ignore implicit any type
const key = resolver.apply(this, args);
const cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
// @ts-ignore: i... | memoize | identifier_name |
index.ts | export type Resolver = (...args: any[]) => any;
export interface MapLike<K = unknown, V = unknown> {
set(key: K, v: V): MapLike<K, V>;
get(key: K): V;
has(key: K): boolean;
}
export interface Config {
resolver?: Resolver;
cache?: MapLike;
}
function memoize(func: Function, resolver: Resolver, cache: MapLik... |
const resolver = config.resolver ?? defaultResolver;
const cache = config.cache ?? new Map();
descriptor.value = memoize(descriptor.value, resolver, cache);
return descriptor;
};
| {
throw new Error('Memoization can be applied only to methods');
} | conditional_block |
regula_falsi.rs | // Copyright (c) 2015, Mikhail Vorotilov
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of... | /// + Robust
/// + No need for derivative function
///
/// Contra
///
/// - Slow
/// - Needs initial bracketing
///
/// # Failures
/// ## NoBracketing
/// Initial values do not bracket the root.
/// ## NoConvergency
/// Algorithm cannot find a root within the given number of iterations.
/// # Examples
///... | ///
/// Pro
///
/// + Simple
| random_line_split |
regula_falsi.rs | // Copyright (c) 2015, Mikhail Vorotilov
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of... | () {
let f = |x| 1f64 * x * x - 1f64;
let mut conv = debug_convergency::DebugConvergency::new(1e-15f64, 30);
conv.reset();
assert_float_eq!(
1e-15f64,
find_root_regula_falsi(10f64, 0f64, &f, &mut conv).ok().unwrap(),
1f64
);
... | test_find_root_regula_falsi | identifier_name |
regula_falsi.rs | // Copyright (c) 2015, Mikhail Vorotilov
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of... | conv.reset();
assert_eq!(
find_root_regula_falsi(10f64, 20f64, &f, &mut conv),
Err(SearchError::NoBracketing)
);
let result = find_root_regula_falsi(10f64, 20f64, &f, &mut conv);
assert_eq!(result.unwrap_err().to_string(), "Bracketing Error");
... | {
let f = |x| 1f64 * x * x - 1f64;
let mut conv = debug_convergency::DebugConvergency::new(1e-15f64, 30);
conv.reset();
assert_float_eq!(
1e-15f64,
find_root_regula_falsi(10f64, 0f64, &f, &mut conv).ok().unwrap(),
1f64
);
ass... | identifier_body |
snrscript.py | class OCP_data:
def __init__(self,key,num):
info = requests.get(OCP_server+key+'/info/',verify=False).json()['dataset']
res = info['resolutions'][0]
x_size,y_size,z_size = info['imagesize'][str(res)]
x_off,y_off,z_off = info['neariso_offset'][str(res)]
ocp_x_rand = np.random.... | OCP_server = 'http://cloud.neurodata.io/ocp/ca/'
n_comp = 100
| random_line_split | |
snrscript.py | 0:
try_count2 = 0
try:
f = requests.get("http://cloud.neurodata.io/ocp/ca/"+key+"/npz/"+str(res)+"/"+str(ocp_x_rand[i])+","+str(ocp_x_rand[i]+2000)+"/"+str(ocp_y_rand[i])+","+str(ocp_y_rand[i]+2000)+"/"+str(ocp_z_rand[i])+","+str(ocp_z_rand[i]+1)+"/",timeout=60,verify... |
atum_snr = atum_snr[atum_snr < np.inf]
fibsem_snr = np.zeros(n_comp)
fib_random = np.random.permutation(range(1376,7651))[:300]
#fib_sem images have to be downloaded in advance
count = 0
for i,j in enumerate(fib_random):
if fbem_skip is True:
break
try:
fibsem_snr[count] = snr_of_images.S... | try:
atum_snr[count] = snr_of_images.SNR(atum.data[i,:,:],mode='im_array',conv=55,hess=800)
count += 1
if count == n_comp:
break
except:
continue | conditional_block |
snrscript.py | print(key,', type 1: ',count, "http://cloud.neurodata.io/ocp/ca/"+key+"/npz/"+str(res)+"/"+str(ocp_x_rand[i])+","+str(ocp_x_rand[i]+2000)+"/"+str(ocp_y_rand[i])+","+str(ocp_y_rand[i]+2000)+"/"+str(ocp_z_rand[i])+","+str(ocp_z_rand[i]+1)+"/")
try_count2 +=1
if ... | def __init__(self,key,num):
info = requests.get(OCP_server+key+'/info/',verify=False).json()['dataset']
res = info['resolutions'][0]
x_size,y_size,z_size = info['imagesize'][str(res)]
x_off,y_off,z_off = info['neariso_offset'][str(res)]
ocp_x_rand = np.random.randint(x_off,x_size... | identifier_body | |
snrscript.py | (self,key,num):
info = requests.get(OCP_server+key+'/info/',verify=False).json()['dataset']
res = info['resolutions'][0]
x_size,y_size,z_size = info['imagesize'][str(res)]
x_off,y_off,z_off = info['neariso_offset'][str(res)]
ocp_x_rand = np.random.randint(x_off,x_size-2000,num+40... | __init__ | identifier_name | |
strict_transport_security.rs | use std::fmt;
use std::str::{self, FromStr};
use unicase::UniCase;
use header::{Header, Raw, parsing};
/// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797)
///
/// This specification defines a mechanism enabling web sites to declare
/// themselves accessible only via secure... |
#[test]
fn test_parse_max_age_nan() {
let h: ::Result<StrictTransportSecurity> = Header::parse_header(&"max-age = derp".into());
assert!(h.is_err());
}
#[test]
fn test_parse_duplicate_directives() {
assert!(StrictTransportSecurity::parse_header(&"max-age=100; max-age=5; ma... | {
let h: ::Result<StrictTransportSecurity> = Header::parse_header(&"includeSubDomains".into());
assert!(h.is_err());
} | identifier_body |
strict_transport_security.rs | use std::fmt;
use std::str::{self, FromStr};
use unicase::UniCase;
use header::{Header, Raw, parsing};
/// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797)
///
/// This specification defines a mechanism enabling web sites to declare
/// themselves accessible only via secure... | (raw: &Raw) -> ::Result<StrictTransportSecurity> {
parsing::from_one_raw_str(raw)
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.include_subdomains {
write!(f, "max-age={}; includeSubdomains", self.max_age)
} else {
write!(f, "max-age={}"... | parse_header | identifier_name |
strict_transport_security.rs | use std::fmt;
use std::str::{self, FromStr};
use unicase::UniCase;
use header::{Header, Raw, parsing};
/// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797)
///
/// This specification defines a mechanism enabling web sites to declare
/// themselves accessible only via secure... | fn parse_header(raw: &Raw) -> ::Result<StrictTransportSecurity> {
parsing::from_one_raw_str(raw)
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.include_subdomains {
write!(f, "max-age={}; includeSubdomains", self.max_age)
} else {
wri... | random_line_split | |
strict_transport_security.rs | use std::fmt;
use std::str::{self, FromStr};
use unicase::UniCase;
use header::{Header, Raw, parsing};
/// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797)
///
/// This specification defines a mechanism enabling web sites to declare
/// themselves accessible only via secure... | else {
write!(f, "max-age={}", self.max_age)
}
}
}
#[cfg(test)]
mod tests {
use super::StrictTransportSecurity;
use header::Header;
#[test]
fn test_parse_max_age() {
let h = Header::parse_header(&"max-age=31536000".into());
assert_eq!(h.ok(), Some(StrictTranspo... | {
write!(f, "max-age={}; includeSubdomains", self.max_age)
} | conditional_block |
hello_world.js | var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var baseUrl = 'http://localhost:9000/';
function helloWorldWrapper() {
function pass(next) { next(); }
browser.ignoreSynchronization = true;
this.after = (function(end){
browser.m... | }
module.exports = helloWorldWrapper; |
this.Then(/I should be able to see the people who worked on this project/, function(callback) {
callback.pending();
}); | random_line_split |
hello_world.js | var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var baseUrl = 'http://localhost:9000/';
function helloWorldWrapper() {
function pass(next) { next(); }
browser.ignoreSynchronization = true;
this.after = (function(end){
browser.m... | (el) {
return el.isDisplayed()
.thenCatch(function(staleElement){
return browser.sleep(1000).then(function(){
return testIfDisplayed(el);
});
});
}
testIfDisplayed(personsName).then(function(){
expect(personsName.isDisplayed()).to.eventually.equal(true... | testIfDisplayed | identifier_name |
hello_world.js | var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var baseUrl = 'http://localhost:9000/';
function helloWorldWrapper() {
function pass(next) { next(); }
browser.ignoreSynchronization = true;
this.after = (function(end){
browser.m... |
testIfDisplayed(personsName).then(function(){
expect(personsName.isDisplayed()).to.eventually.equal(true)
.and.notify(next);
});
});
var person;
this.Given(/^the person is not active$/, function (next) {
person = element.all(By.css('.info-box:not(.Active)')).first();
person.then(ne... | {
return el.isDisplayed()
.thenCatch(function(staleElement){
return browser.sleep(1000).then(function(){
return testIfDisplayed(el);
});
});
} | identifier_body |
domain_selector_dialog.js | odoo.define("web.DomainSelectorDialog", function (require) {
"use strict";
var core = require("web.core");
var Dialog = require("web.Dialog");
var DomainSelector = require("web.DomainSelector");
var _t = core._t;
/**
* @class DomainSelectorDialog
*/
return Dialog.extend({
init: function (parent, model, domain,... | else {
buttons = [
{text: _t("Save"), classes: "btn-primary", close: true, click: function () {
this.trigger_up("domain_selected", {domain: this.domainSelector.getDomain()});
}},
{text: _t("Discard"), close: true},
];
}... | {
buttons = [
{text: _t("Close"), close: true},
];
} | conditional_block |
domain_selector_dialog.js | odoo.define("web.DomainSelectorDialog", function (require) {
"use strict";
var core = require("web.core");
var Dialog = require("web.Dialog");
var DomainSelector = require("web.DomainSelector");
var _t = core._t;
/**
* @class DomainSelectorDialog
*/
return Dialog.extend({
init: function (parent, model, domain,... | },
start: function () {
var self = this;
this.opened().then(function () {
// this restores default modal height (bootstrap) and allows field selector to overflow
self.$el.css('overflow', 'visible').closest('.modal-dialog').css('height', 'auto');
});
return... | buttons: buttons,
}, options || {}));
this.domainSelector = new DomainSelector(this, model, domain, options); | random_line_split |
toolbar.d.ts | import { ElementRef, Renderer } from '@angular/core';
import { Config } from '../../config/config';
import { Ion } from '../ion';
import { ToolbarTitle } from './toolbar-title';
import { ViewController } from '../../navigation/view-controller';
/**
* @name Header
* @description
* Header is a parent component that ho... | extends Ion {
constructor(config: Config, elementRef: ElementRef, renderer: Renderer, viewCtrl: ViewController);
}
/**
* @name Footer
* @description
* Footer is a root component of a page that sits at the bottom of the page.
* Footer can be a wrapper for `ion-toolbar` to make sure the content area is sized cor... | Header | identifier_name |
toolbar.d.ts | import { ElementRef, Renderer } from '@angular/core';
import { Config } from '../../config/config';
import { Ion } from '../ion';
import { ToolbarTitle } from './toolbar-title';
import { ViewController } from '../../navigation/view-controller';
/**
* @name Header
* @description
* Header is a parent component that ho... | * <ion-footer no-border>
*
* <ion-toolbar>
* <ion-title>I'm a footer</ion-title>
* </ion-toolbar>
*
* </ion-footer>
* ```
*
* @demo /docs/demos/src/toolbar/
* @see {@link ../../navbar/Navbar/ Navbar API Docs}
*/
export declare class Toolbar extends ToolbarBase {
/** @private */
_sbPadding: ... | *
* | random_line_split |
mir_build_match_comparisons.rs | // Copyright 2015 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 ... |
const U: Option<i8> = Some(10);
const S: &'static str = "hello";
fn test2(x: i8) -> i32 {
match Some(x) {
U => 0,
_ => 1,
}
}
fn test3(x: &'static str) -> i32 {
match x {
S => 0,
_ => 1,
}
}
enum Opt<T> {
Some { v: T },
None
}
fn test4(x: u64) -> i32 {
let opt = Opt::Some{ v: x }... | {
match x {
1...10 => 0,
_ => 1,
}
} | identifier_body |
mir_build_match_comparisons.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(test1(0), 1);
assert_eq!(test1(1), 0);
assert_eq!(test1(2), 0);
assert_eq!(test1(5), 0);
assert_eq!(test1(9), 0);
assert_eq!(test1(10), 0);
assert_eq!(test1(11), 1);
assert_eq!(test1(20), 1);
assert_eq!(test2(10), 0);
assert_eq!(test2(0), 1);
assert_eq!(test2(20), 1);
assert_eq!(... | main | identifier_name |
mir_build_match_comparisons.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert_eq!(test2(0), 1);
assert_eq!(test2(20), 1);
assert_eq!(test3("hello"), 0);
assert_eq!(test3(""), 1);
assert_eq!(test3("world"), 1);
assert_eq!(test4(10), 0);
assert_eq!(test4(0), 1);
assert_eq!(test4(20), 1);
} | assert_eq!(test1(9), 0);
assert_eq!(test1(10), 0);
assert_eq!(test1(11), 1);
assert_eq!(test1(20), 1);
assert_eq!(test2(10), 0); | random_line_split |
810-crypt-sha1.js | 456789abcdef";
var output = "";
var x;
for(var i = 0; i < input.length; i++)
{
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F)
+ hex_tab.charAt( x & 0x0F);
}
return output;
}
/*
* Convert a raw string to a base-64 string
*/
function rstr2b64(input)
{
try {... | * iteration | random_line_split | |
810-crypt-sha1.js | function any_hmac(k, d, e)
{ return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test()
{
return hex_sha1("abc").toLowerCase() == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA1 ... |
/*
* Convert a raw string to an array of big-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binb(input)
{
var output = Array(input.length >> 2);
for(var i = 0; i < output.length; i++)
output[i] = 0;
for(var i = 0; i < input.length * 8; i += 8)
output[i>>5] ... | {
var output = "";
for(var i = 0; i < input.length; i++)
output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
input.charCodeAt(i) & 0xFF);
return output;
} | identifier_body |
810-crypt-sha1.js | (k, d)
{ return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac(k, d, e)
{ return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test()
{
return hex_sha1("abc").toLowerCas... | b64_hmac | identifier_name | |
keys.py | #CHIPSEC: Platform Security Assessment Framework
#Copyright (c) 2010-2015, Intel Corporation
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; Version 2.
#
#This program is distributed in t... | ( self, name, guid ):
self.logger.log( "[*] Checking EFI variable %s {%s}.." % (name, guid) )
orig_var = self._uefi.get_EFI_variable( name, guid, None )
if not orig_var:
self.logger.log( "[*] EFI variable %s {%s} doesn't exist" % (name, guid) )
return keys.ERROR
... | check_EFI_variable_authentication | identifier_name |
keys.py | #CHIPSEC: Platform Security Assessment Framework
#Copyright (c) 2010-2015, Intel Corporation
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; Version 2.
#
#This program is distributed in t... | self.logger.start_test( "Protection of Secure Boot Key and Configuration EFI Variables" )
return self.check_secureboot_key_variables() | identifier_body | |
keys.py | #CHIPSEC: Platform Security Assessment Framework
#Copyright (c) 2010-2015, Intel Corporation
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; Version 2.
#
#This program is distributed in t... | #
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#Contact information:
#chipsec@intel.com
#
## \addtogroup modules
# __chipsec/modules/secure... | #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
| random_line_split |
keys.py | #CHIPSEC: Platform Security Assessment Framework
#Copyright (c) 2010-2015, Intel Corporation
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; Version 2.
#
#This program is distributed in t... |
if ok == keys.INSECURE:
self.logger.log_bad( "EFI variable %s is not protected! It has been modified. Restoring original contents.." % name )
self._uefi.set_EFI_variable( name, guid, orig_var )
else:
self.logger.log_good( "Could not modify EFI variable %s {%s}" ... | ok = keys.INSECURE
break | conditional_block |
help.component.ts | import {AfterViewInit, Component, ElementRef, OnInit} from '@angular/core';
import {TranslateService} from "@ngx-translate/core";
import {ActivatedRoute} from "@angular/router";
import {Account} from "@model/Account";
import {AuthenticationService} from "@core-services/authentication.service";
import {environment} from... |
ngAfterViewInit(): void {
setTimeout(() => {
this.toc = this.elem.nativeElement.querySelectorAll('h3,h4,h5');
this.route.fragment.pipe(first()).subscribe(fragment => {
this.viewportScroller.scrollToAnchor(fragment)
});
}, 0)
}
}
| {
this.lang = this.translate.currentLang;
this.isAdmin = this.authSrv.isAdmin();
this.user = this.authSrv.currentAccount;
this.authSrv.admins().subscribe(admins => {
this.admins = admins
})
} | identifier_body |
help.component.ts | import {AfterViewInit, Component, ElementRef, OnInit} from '@angular/core';
import {TranslateService} from "@ngx-translate/core";
import {ActivatedRoute} from "@angular/router";
import {Account} from "@model/Account";
import {AuthenticationService} from "@core-services/authentication.service";
import {environment} from... | (private translate: TranslateService,
private route: ActivatedRoute,
private elem: ElementRef,
private viewportScroller: ViewportScroller,
private authSrv: AuthenticationService) {
}
//TODO needs viewportScroller
ngOnInit() {
this.lang = this.translate... | constructor | identifier_name |
help.component.ts | import {AfterViewInit, Component, ElementRef, OnInit} from '@angular/core';
import {TranslateService} from "@ngx-translate/core";
import {ActivatedRoute} from "@angular/router"; |
@Component({
selector: 'app-help',
templateUrl: './help.component.html',
styleUrls: ['./help.component.css']
})
export class HelpComponent implements OnInit, AfterViewInit {
lang: string;
toc: NodeList;
isAdmin: boolean;
user: Account;
admins: Account[];
version: string = environment.version;
con... | import {Account} from "@model/Account";
import {AuthenticationService} from "@core-services/authentication.service";
import {environment} from "@env/environment";
import {first} from 'rxjs/operators';
import {ViewportScroller} from '@angular/common'; | random_line_split |
lifetime.rs | use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use proc_macro2::{Ident, Span};
#[cfg(feature = "parsing")]
use crate::lookahead;
/// A Rust lifetime: `'a`.
///
/// Lifetime names must conform to the following rules:
///
/// - Must start with an apostrophe.
/// - Must not consis... |
}
}
#[cfg(feature = "printing")]
mod printing {
use super::*;
use proc_macro2::{Punct, Spacing, TokenStream};
use quote::{ToTokens, TokenStreamExt};
impl ToTokens for Lifetime {
fn to_tokens(&self, tokens: &mut TokenStream) {
let mut apostrophe = Punct::new('\'', Spacing::Joi... | {
input.step(|cursor| {
cursor
.lifetime()
.ok_or_else(|| cursor.error("expected lifetime"))
})
} | identifier_body |
lifetime.rs | use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use proc_macro2::{Ident, Span};
#[cfg(feature = "parsing")]
use crate::lookahead;
/// A Rust lifetime: `'a`.
///
/// Lifetime names must conform to the following rules:
///
/// - Must start with an apostrophe.
/// - Must not consis... | {
pub apostrophe: Span,
pub ident: Ident,
}
impl Lifetime {
/// # Panics
///
/// Panics if the lifetime does not conform to the bulleted rules above.
///
/// # Invocation
///
/// ```
/// # use proc_macro2::Span;
/// # use syn::Lifetime;
/// #
/// # fn f() -> Lifetim... | Lifetime | identifier_name |
lifetime.rs | use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use proc_macro2::{Ident, Span};
#[cfg(feature = "parsing")]
use crate::lookahead;
/// A Rust lifetime: `'a`.
///
/// Lifetime names must conform to the following rules:
///
/// - Must start with an apostrophe.
/// - Must not consis... | use proc_macro2::{Punct, Spacing, TokenStream};
use quote::{ToTokens, TokenStreamExt};
impl ToTokens for Lifetime {
fn to_tokens(&self, tokens: &mut TokenStream) {
let mut apostrophe = Punct::new('\'', Spacing::Joint);
apostrophe.set_span(self.apostrophe);
tokens... | #[cfg(feature = "printing")]
mod printing {
use super::*;
| random_line_split |
lifetime.rs | use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use proc_macro2::{Ident, Span};
#[cfg(feature = "parsing")]
use crate::lookahead;
/// A Rust lifetime: `'a`.
///
/// Lifetime names must conform to the following rules:
///
/// - Must start with an apostrophe.
/// - Must not consis... |
if symbol == "'" {
panic!("lifetime name must not be empty");
}
if !crate::ident::xid_ok(&symbol[1..]) {
panic!("{:?} is not a valid lifetime name", symbol);
}
Lifetime {
apostrophe: span,
ident: Ident::new(&symbol[1..], span),
... | {
panic!(
"lifetime name must start with apostrophe as in \"'a\", got {:?}",
symbol
);
} | conditional_block |
type.js | const types = require('./packages/mjml-core/lib/types/type.js')
const enumtype = types.initializeType('enum(top,left,center)')
const colortype = types.initializeType('color')
const booleantype = types.initializeType('boolean')
const unittype = types.initializeType('unit(px,%){1,3}')
const stringtype = types.initialize... | new colortype('#DF'),
new booleantype('true'),
new booleantype('false'),
new booleantype('banana'),
new unittype('10 20px 20'),
new unittype('10px 20px 20px'),
new unittype('10px'),
new unittype('10%'),
new unittype('10px 10px'),
new unittype('0'),
new stringtype('hello world'),
].map(output) |
[new colortype('grey'),
new colortype('rgba(0,255,3,0.3)'),
new colortype('#DDF'), | random_line_split |
parser.rs | <rust::TokenTree>,
grammar_name: rust::Ident) -> Parser<'a>
{
Parser{
rp: rust::new_parser_from_tts(sess, cfg, tts),
inner_attrs: Vec::new(),
grammar_name: grammar_name
}
}
pub fn parse_grammar(&mut self) -> Grammar {
let (rules, rust_items) = self.parse_blocks();
Gramm... | },
rtok::Ident(id, _) => {
if self.is_rule_lhs() { None }
else {
self.bump();
Some(self.last_respan(NonTerminalSymbol(id)))
}
},
rtok::OpenDelim(rust::DelimToken::Bracket) => {
self.bump();
let res = self.parse_char_class(rule_name);
... | {
let token = self.rp.token.clone();
if token.is_any_keyword() {
return None
}
match token {
rtok::Literal(rust::token::Lit::Str_(name),_) => {
self.bump();
let cooked_lit = cook_lit(name);
Some(self.last_respan(StrLiteral(cooked_lit)))
},
rtok::Dot => {
... | identifier_body |
parser.rs | mut self) -> (Vec<Rule>, Vec<RItem>) {
let mut rules = vec![];
let mut rust_items = vec![];
while self.rp.token != rtok::Eof
{
self.parse_inner_attributes();
self.rp.parse_item().map_or_else(
|| rules.push(self.parse_rule()),
|item| rust_items.push(item))
}
(rules, ru... | {
intervals.push(CharacterInterval{lo: '-', hi: '-'});
ranges.next();
} | conditional_block | |
parser.rs | <rust::TokenTree>,
grammar_name: rust::Ident) -> Parser<'a>
{
Parser{
rp: rust::new_parser_from_tts(sess, cfg, tts),
inner_attrs: Vec::new(),
grammar_name: grammar_name
}
}
pub fn parse_grammar(&mut self) -> Grammar {
let (rules, rust_items) = self.parse_blocks();
Gramm... | None => return None
};
let hi = self.rp.span.hi;
let token = self.rp.token.clone();
match token {
rtok::BinOp(rbtok::Star) => {
self.bump();
Some(spanned_expr(lo, hi, ZeroOrMore(expr)))
},
rtok::BinOp(rbtok::Plus) => {
self.bump();
Some(spanned_exp... |
fn parse_rule_suffixed(&mut self, rule_name: &str) -> Option<Box<Expression>> {
let lo = self.rp.span.lo;
let expr = match self.parse_rule_atom(rule_name){
Some(expr) => expr, | random_line_split |
parser.rs | <rust::TokenTree>,
grammar_name: rust::Ident) -> Parser<'a>
{
Parser{
rp: rust::new_parser_from_tts(sess, cfg, tts),
inner_attrs: Vec::new(),
grammar_name: grammar_name
}
}
pub fn parse_grammar(&mut self) -> Grammar {
let (rules, rust_items) = self.parse_blocks();
Gramm... | (&self, expr: ExpressionNode) -> Box<Expression> {
respan_expr(self.rp.last_span, expr)
}
fn parse_rule_atom(&mut self, rule_name: &str) -> Option<Box<Expression>> {
let token = self.rp.token.clone();
if token.is_any_keyword() {
return None
}
match token {
rtok::Literal(rust::token:... | last_respan | identifier_name |
notebook.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
# Comms handling relies on the fact that the new_doc returned here
# has models with the same IDs as they were started with
with OutputDocumentFor([model], apply_theme=theme, always_new=True) as new_doc:
(docs_json, [render_item]) = standalone_docs_json_and_render_items([model])
div = div_for... | raise ValueError("notebook_content expects a single Model instance") | conditional_block |
notebook.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | )
return encode_utf8(script), encode_utf8(div), new_doc
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# ... |
script = DOC_NB_JS.render(
docs_json=serialize_json(docs_json),
render_items=serialize_json([render_item]), | random_line_split |
notebook.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | (model, notebook_comms_target=None, theme=FromCurdoc):
''' Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
... | notebook_content | identifier_name |
notebook.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
.. note::
Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent
has already been executed.
'''
if not isinstance(model, Model):
raise ValueError("notebook_content expects a single Model instance")
# Comms handling relies on the fact that the new_doc returned here... | ''' Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
A target name for a Jupyter Comms object that can... | identifier_body |
interpolation.ts | import { IPoint, Point } from '../primitives/point';
import { EasingMethod, linear } from './easing';
| */
export enum InterpolationMethod {
BEZIER2,
BEZIER3,
CIRCULAR,
}
/**
* This calculates a quadratic bezier curve.
*
* We use specific bezier curve implementations for low degree curves as it is
* much much faster to calculate.
*
* @param {number} t The 0 - 1 time interval for the part of the curve we des... | /**
* This enum is just a common way to define interpolation types | random_line_split |
interpolation.ts | import { IPoint, Point } from '../primitives/point';
import { EasingMethod, linear } from './easing';
/**
* This enum is just a common way to define interpolation types
*/
export enum InterpolationMethod {
BEZIER2,
BEZIER3,
CIRCULAR,
}
/**
* This calculates a quadratic bezier curve.
*
* We use specific bez... |
/**
* This calculates a point along a path defined as a circular path which is a
* path moving along the edge of a circle from one point to the next. This will
* even allow for moving along a circle with a growing radius.
*
* @param {number} t The 0 - 1 time interval for the part of the path we desire
* @param ... | {
const t2 = t * t;
const t3 = t2 * t;
const mt = 1 - t;
const mt2 = mt * mt;
const mt3 = mt2 * mt;
return {
x: p1.x * mt3 + 3 * c1.x * mt2 * t + 3 * c2.x * mt * t2 + p2.x * t3,
y: p1.y * mt3 + 3 * c1.y * mt2 * t + 3 * c2.y * mt * t2 + p2.y * t3,
};
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.