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 |
|---|---|---|---|---|
server.js | var express = require('express'),
xml2js = require('xml2js'),
parser = new xml2js.Parser({explicitArray: false, mergeAttrs: true, explicitRoot: false});
var xmlBodyParser = function(req, res, next) {
if (req._body) return next();
req.body = req.body || {};
// ignore GET
if ('GET' == req.method... | var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function() {
parser.parseString(buf, function(err, json) {
if (err) {
err.status = 400;
next(err);
} else {
req.body = jso... | random_line_split | |
server.js | var express = require('express'),
xml2js = require('xml2js'),
parser = new xml2js.Parser({explicitArray: false, mergeAttrs: true, explicitRoot: false});
var xmlBodyParser = function(req, res, next) {
if (req._body) return next();
req.body = req.body || {};
// ignore GET
if ('GET' == req.method... | else {
req.body = json;
next();
}
});
});
};
exports.init = function(publicPath, builder) {
app = express();
app.use(xmlBodyParser);
app.post('/hex', function(req, res) {
logger.info('Client requests hex ' + req.headers['user-agent']);
... | {
err.status = 400;
next(err);
} | conditional_block |
filters-017.js | // # Demo Filters 017
// Filter parameters: displace
// [Run code](../../demo/filters-017.html)
import * as scrawl from '../source/scrawl.js';
import { reportSpeed, addImageDragAndDrop } from './utilities.js';
// Get Scrawl-canvas to recognise and act on device pixel ratios greater than 1
scrawl.setIgnorePixelRatio... | });
// Setup form
const offsetX = document.querySelector('#offset_x'),
offsetY = document.querySelector('#offset_y'),
scaleX = document.querySelector('#scale_x'),
scaleY = document.querySelector('#scale_y'),
opacity = document.querySelector('#opacity');
// @ts-expect-error
offsetX.value = 0;
// @ts-ex... | opacity: ['opacity', 'float'],
}, | random_line_split |
photo_grid.js | // app.photoGrid
var Backbone = require("backbone");
// var _ = require("underscore");
var $ = require("jquery");
var ImageGridFuncs = require("./photo_grid_functions");
var ImageCollection = require("../models/photo_grid_image_collection");
var ImageView = require("./photo_grid_image");
module.exports = Backbone.Vi... | imageInfo = this.model.get("images")[currSlide];
// calculate the size of the image when it fits the slideshow:
imgWidth = this.funcs.findSlideSize(imageInfo,
slideDiv.offsetWidth,
slideDiv.offsetHeight);
slideDiv.innerHTML = '<img src="'... | {
if (app.mindbodyModel.get("popoverVisible") !== true) {
app.mindbodyModel.set({popoverVisible : true});
}
// retrieve cached DOM object:
imageViewer = app.mbBackGroundShader.openPopUp("imageViewer");
// set the stage:
image... | conditional_block |
photo_grid.js | // app.photoGrid
var Backbone = require("backbone");
// var _ = require("underscore");
var $ = require("jquery");
var ImageGridFuncs = require("./photo_grid_functions");
var ImageCollection = require("../models/photo_grid_image_collection");
var ImageView = require("./photo_grid_image");
module.exports = Backbone.Vi... | "use strict";
var currSlide = this.model.get("currentSlide"),
allImages = this.model.get("imageURL"),
imageInfo,
imageViewer,
imgWidth,
slideDiv;
if (currSlide !== false) {
if (app.mindbodyModel.get("popoverVisible") !== ... | modelChange: function () { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license... | (port: Receiver<DevtoolsControlMsg>) {
let listener = TcpListener::bind("127.0.0.1", 6000);
// bind the listener to the specified address
let mut acceptor = listener.listen().unwrap();
acceptor.set_timeout(Some(POLL_TIMEOUT));
let mut registry = ActorRegistry::new();
let root = box RootActor ... | run_server | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license... | let packet_len = num::from_str_radix(packet_len_str.as_slice(), 10).unwrap();
let packet_buf = stream.read_exact(packet_len).unwrap();
let packet = String::from_utf8(packet_buf).unwrap();
println!("{:s}", packet);
... | {
println!("connection established to {:?}", stream.peer_name().unwrap());
{
let mut actors = actors.lock();
let msg = actors.find::<RootActor>("root").encodable();
stream.write_json_packet(&msg);
}
// https://wiki.mozilla.org/Remote_Debugging_Protoc... | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license... | acceptor.set_timeout(Some(POLL_TIMEOUT));
let mut registry = ActorRegistry::new();
let root = box RootActor {
tabs: vec!(),
};
registry.register(root);
registry.find::<RootActor>("root");
let actors = Arc::new(Mutex::new(registry));
/// Process the input from a single devtoo... | fn run_server(port: Receiver<DevtoolsControlMsg>) {
let listener = TcpListener::bind("127.0.0.1", 6000);
// bind the listener to the specified address
let mut acceptor = listener.listen().unwrap(); | random_line_split |
message.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units... | ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match *querymsg {
QueryMsg::NodesFromPointQuery(..) |
QueryMsg::TextIndexQuery(..) |
QueryMsg::InnerWindowDimensionsQuery(_) |
QueryM... | pub fn needs_display_list(&self) -> bool {
match *self { | random_line_split |
message.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units... | {
Full,
TickAnimations,
LayoutQuery(QueryMsg, u64),
}
impl ReflowGoal {
/// Returns true if the given ReflowQuery needs a full, up-to-date display list to
/// be present or false if it only needs stacking-relative positions.
pub fn needs_display_list(&self) -> bool {
match *self {
... | ReflowGoal | identifier_name |
authentication.rs | // Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub... |
// TODO Needs test
fn format_access_uri(temp_code: &TempCode) -> String {
let base = "https://slack.com/api/oauth.access";
let query = format!("?client_id={}&client_secret={}&code={}", SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, temp_code);
format!("{}{}", base, query)
}
fn extract_temp_code(path: &str) -> Opt... | {
let mut client = Client::new();
// I thought & is sufficient to make it a slice
let mut res = client.get(format_access_uri(temp_code).as_str()).send().unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
match Json::from_str(&body) {
Ok(json) => {
... | identifier_body |
authentication.rs | // Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub... |
// TODO Test
fn store_token(token: &AuthToken) {
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(token.as_bytes()).unwrap();
}
#[allow(dead_code)] // Hard to test
fn request_temp_code() -> (TempCode, Listening) {
Command::new("xdg-open").arg(format!("https://slack.com/oauth/authorize?s... | fn arrange_new_token() -> (AuthToken, Listening) {
let (temp_code, listener) = request_temp_code();
let token = request_token(&temp_code);
(token, listener)
} | random_line_split |
authentication.rs | // Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub... | () -> (TempCode, Listening) {
Command::new("xdg-open").arg(format!("https://slack.com/oauth/authorize?scope=client&client_id={}", SLACK_CLIENT_ID)).output().unwrap();
let (tx, rx) = channel();
let mtx = Mutex::new(tx);
let mut guard = Server::http("127.0.0.1:9999").unwrap().handle(move |req: Request, ... | request_temp_code | identifier_name |
index.js | // Generated by CoffeeScript 1.3.3
var binding, exports, leveldb;
leveldb = exports = module.exports = require('./leveldb/handle');
binding = require('./leveldb.node');
leveldb.version = '0.6.2';
leveldb.bindingVersion = "" + binding.majorVersion + "." + binding.minorVersion;
leveldb.Batch = require('./leveldb/bat... |
return binding.createPartitionedBitwiseComparator(bounds);
};
| {
_ref = args[_i], limit = _ref[0], reverse = _ref[1];
bounds.push(parseInt(limit));
bounds.push(!!reverse);
} | conditional_block |
index.js | // Generated by CoffeeScript 1.3.3
var binding, exports, leveldb;
leveldb = exports = module.exports = require('./leveldb/handle');
binding = require('./leveldb.node');
leveldb.version = '0.6.2';
leveldb.bindingVersion = "" + binding.majorVersion + "." + binding.minorVersion;
leveldb.Batch = require('./leveldb/bat... | }; | random_line_split | |
codeEditor.component.ts | import { Component, Input, Output, ViewEncapsulation, EventEmitter, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: "k-code-editor",
templateUrl: "./codeEditor.component.html",
styleUrls: ["./codeEditor.component.scss"],
encapsulation: ViewEncapsulation.None
})
export class KylinCod... | (value: string) {
let me = this;
me._value = value;
if(me.codemirror) {
me.codemirror.setValue(me._value); // 当从外面进来并设置的时候
me.codemirror.focus();
me.codemirror.setCursor(me.codemirror.lineCount(), 0);
}
};
get value(){
let me = this;
... | value | identifier_name |
codeEditor.component.ts | import { Component, Input, Output, ViewEncapsulation, EventEmitter, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: "k-code-editor",
templateUrl: "./codeEditor.component.html",
styleUrls: ["./codeEditor.component.scss"],
encapsulation: ViewEncapsulation.None
})
export class KylinCod... | let me = this;
return me._value;
}
@Output('valueChanged') valueChange:EventEmitter<string>= new EventEmitter();
@Output('initedCodemirror') initedCodemirror: EventEmitter<any> = new EventEmitter();
@ViewChild('element') element: ElementRef;
codemirror:any;
ngOnInit() {
//Cal... | {
let me = this;
me._value = value;
if(me.codemirror) {
me.codemirror.setValue(me._value); // 当从外面进来并设置的时候
me.codemirror.focus();
me.codemirror.setCursor(me.codemirror.lineCount(), 0);
}
};
get value(){
| identifier_body |
codeEditor.component.ts | import { Component, Input, Output, ViewEncapsulation, EventEmitter, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: "k-code-editor",
templateUrl: "./codeEditor.component.html",
styleUrls: ["./codeEditor.component.scss"],
encapsulation: ViewEncapsulation.None
})
export class KylinCod... |
let me = this;
return me._value;
}
@Output('valueChanged') valueChange:EventEmitter<string>= new EventEmitter();
@Output('initedCodemirror') initedCodemirror: EventEmitter<any> = new EventEmitter();
@ViewChild('element') element: ElementRef;
codemirror:any;
ngOnInit() {
... | {
me.codemirror.setValue(me._value); // 当从外面进来并设置的时候
me.codemirror.focus();
me.codemirror.setCursor(me.codemirror.lineCount(), 0);
}
};
get value(){ | conditional_block |
codeEditor.component.ts | import { Component, Input, Output, ViewEncapsulation, EventEmitter, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: "k-code-editor",
templateUrl: "./codeEditor.component.html",
styleUrls: ["./codeEditor.component.scss"],
encapsulation: ViewEncapsulation.None
})
export class KylinCod... | let me = this;
me._value = value;
if(me.codemirror) {
me.codemirror.setValue(me._value); // 当从外面进来并设置的时候
me.codemirror.focus();
me.codemirror.setCursor(me.codemirror.lineCount(), 0);
}
};
get value(){
let me = this;
return me._v... | random_line_split | |
checkbox.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"gui2py's CheckBox control (uses wx.CheckBox)"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013- Mariano Reingart" # where applicable
# Initial implementation was based on PythonCard's CehckBox component,
# but redesigned an... | app = wx.App(redirect=False)
frame = wx.Frame(None)
c = CheckBox(frame, name="chkTest", border='none', label="Check me!")
assert c.get_parent() is frame
assert c.name == "chkTest"
assert c.label == "Check me!"
from pprint import pprint
# assign some event handlers:
c.onclick = la... | conditional_block | |
checkbox.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"gui2py's CheckBox control (uses wx.CheckBox)"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013- Mariano Reingart" # where applicable
# Initial implementation was based on PythonCard's CehckBox component,
# but redesigned an... |
if __name__ == "__main__":
# basic test until unit_test
app = wx.App(redirect=False)
frame = wx.Frame(None)
c = CheckBox(frame, name="chkTest", border='none', label="Check me!")
assert c.get_parent() is frame
assert c.name == "chkTest"
assert c.label == "Check me!"
from ppr... | "A check box."
_wx_class = wx.CheckBox
_style = wx.CLIP_SIBLINGS | wx.NO_FULL_REPAINT_ON_RESIZE
_image = images.checkbox
value = Spec(lambda self: self.wx_obj.GetValue(),
lambda self, value: self.wx_obj.SetValue(value),
default=False, type="b... | identifier_body |
checkbox.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"gui2py's CheckBox control (uses wx.CheckBox)"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013- Mariano Reingart" # where applicable
# Initial implementation was based on PythonCard's CehckBox component,
# but redesigned an... | (Control):
"A check box."
_wx_class = wx.CheckBox
_style = wx.CLIP_SIBLINGS | wx.NO_FULL_REPAINT_ON_RESIZE
_image = images.checkbox
value = Spec(lambda self: self.wx_obj.GetValue(),
lambda self, value: self.wx_obj.SetValue(value),
defaul... | CheckBox | identifier_name |
checkbox.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"gui2py's CheckBox control (uses wx.CheckBox)"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013- Mariano Reingart" # where applicable
# Initial implementation was based on PythonCard's CehckBox component,
# but redesigned an... | _style = wx.CLIP_SIBLINGS | wx.NO_FULL_REPAINT_ON_RESIZE
_image = images.checkbox
value = Spec(lambda self: self.wx_obj.GetValue(),
lambda self, value: self.wx_obj.SetValue(value),
default=False, type="boolean")
label = InitSpec(lambda self: self.wx... | random_line_split | |
display.py | # coding: utf-8
"""
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
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 limit... |
def display(text):
output = _.Atlas.createHTML()
output.putTagAndValue("h1", text)
_dom().appendLayout(_OUTPUT, output)
def clearAndDisplay(text):
output = _.Atlas.createHTML()
output.putTagAndValue("h1", text)
_dom().setLayout(_OUTPUT, output)
def alert(text):
_dom().alert(text)
def con... | random_line_split | |
display.py | # coding: utf-8
"""
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
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 limit... | (text):
output = _.Atlas.createHTML()
output.putTagAndValue("h1", text)
_dom().setLayout(_OUTPUT, output)
def alert(text):
_dom().alert(text)
def confirm(text):
return _dom().confirm(text)
| clearAndDisplay | identifier_name |
display.py | # coding: utf-8
"""
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
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 limit... |
def confirm(text):
return _dom().confirm(text)
| _dom().alert(text) | identifier_body |
range_put.js | /*******************************************************************************
* Copyright 2013-2014 Aerospike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* | * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*********************************************************************... | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software | random_line_split |
range_put.js | /*******************************************************************************
* Copyright 2013-2014 Aerospike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://ww... |
done++;
if ( done >= total ) {
console.timeEnd(timeLabel);
console.log();
console.log("RANGE: start=%d end=%d skip=%d)", start, end, skip);
console.log("RESULTS: (%d completed, %d success, %d failed, %d skipped)", done, success, f... | {
switch ( err.code ) {
case Status.AEROSPIKE_OK:
console.log("OK - ", key);
success++;
break;
default:
console.log("ERR - ", err, key);
failure... | conditional_block |
range_put.js | /*******************************************************************************
* Copyright 2013-2014 Aerospike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://ww... | s: "abc",
i: i * 1000 + 123,
b: new Buffer([0xa, 0xb, 0xc])
};
var metadata = {
ttl: 10000,
gen: 0
};
client.put(key, record, metadata, done);
}
}
put_start(client, argv.st... | {
var done = put_done(client, start, end, skip);
var i = start, s = 0;
for (; i <= end; i++ ) {
var key = {
ns: argv.namespace,
set: argv.set,
key: i
};
if ( skip !== 0 && ++s >= skip ) {
s = ... | identifier_body |
range_put.js | /*******************************************************************************
* Copyright 2013-2014 Aerospike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://ww... | (client, start, end, skip) {
var total = end - start + 1;
var done = 0;
var success = 0;
var failure = 0;
var skipped = 0;
var timeLabel = "range_put @ " + total;
console.time(timeLabel);
return function(err, key, skippy) {
if ( skippy === t... | put_done | identifier_name |
charlie.py | '''
charlie.py
---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi
Relies upon RPi.GPIO written by Ben Croston
The MIT License (MIT)
Copyright (c) 2016 Amanda Cole
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentati... |
def display(self, pixels, duration):
'''
pixels: type 'list', list of pixels to be lit each in coordinate form [x,y]
duration: type 'int', duration to display coordinates
Lights specified pixels in array
'''
positives = []
for coord... | '''
Displays all pixels in array, one at a time, starting with [0,0] and ending with [6,7].
'''
x = 0
y = 0
while y < 8:
self.displayPoint([x,y])
time.sleep(0.1)
x += 1
if x >= 7:
x = 0
y += 1
... | identifier_body |
charlie.py | '''
charlie.py
---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi
Relies upon RPi.GPIO written by Ben Croston
The MIT License (MIT)
Copyright (c) 2016 Amanda Cole
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentati... | t += 0.1 |
self.display(coords, 0.15) | random_line_split |
charlie.py | '''
charlie.py
---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi
Relies upon RPi.GPIO written by Ben Croston
The MIT License (MIT)
Copyright (c) 2016 Amanda Cole
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentati... |
self.display(coords, 0.15)
t += 0.1
| coords.append(coord) | conditional_block |
charlie.py | '''
charlie.py
---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi
Relies upon RPi.GPIO written by Ben Croston
The MIT License (MIT)
Copyright (c) 2016 Amanda Cole
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentati... | (self, pixels, duration):
'''
pixels: type 'list', list of pixels to be lit each in coordinate form [x,y]
duration: type 'int', duration to display coordinates
Lights specified pixels in array
'''
positives = []
for coord in pixels:
i... | display | identifier_name |
test-polyfill.ts | /**
* Tests for polyfill function.
*
* Copyright (C) 2016 Martin Poelstra
* License: MIT
*/
import "source-map-support/register";
import { expect } from "chai";
import polyfill from "../lib/polyfill";
import tsPromise from "../lib/Promise";
import * as util from "../lib/util";
declare var Promise: any;
class | {
public then(): FakePromise {
return new FakePromise();
}
}
describe("polyfill", () => {
let restore: any;
beforeEach(() => {
restore = global.Promise;
delete global["Promise"]; // tslint:disable-line:no-string-literal
});
afterEach(() => {
global.Promise = restore;
});
it("doesn't polyfill by defau... | FakePromise | identifier_name |
test-polyfill.ts | /**
* Tests for polyfill function.
*
* Copyright (C) 2016 Martin Poelstra
* License: MIT
*/
import "source-map-support/register";
import { expect } from "chai";
import polyfill from "../lib/polyfill"; |
declare var Promise: any;
class FakePromise {
public then(): FakePromise {
return new FakePromise();
}
}
describe("polyfill", () => {
let restore: any;
beforeEach(() => {
restore = global.Promise;
delete global["Promise"]; // tslint:disable-line:no-string-literal
});
afterEach(() => {
global.Promise = ... | import tsPromise from "../lib/Promise";
import * as util from "../lib/util"; | random_line_split |
config.ts | declare const System:any;
/*
System.config({
defaultJSExtensions: true,
packages: {
app: { format: 'register', defaultExtension: 'js' },
'@ngrx/store': { main: 'dist/index.js', defaultExtension: 'js' }
},
paths: {
'*': '*.js',
'angular2/*': '../node_modules/angular2/*',
... | ;
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
ngPackageNames.forEach(setPackageConfig);
System.config({ map: map, packages: packages });
})(this);
... | { packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' } } | identifier_body |
config.ts | declare const System:any;
| defaultJSExtensions: true,
packages: {
app: { format: 'register', defaultExtension: 'js' },
'@ngrx/store': { main: 'dist/index.js', defaultExtension: 'js' }
},
paths: {
'*': '*.js',
'angular2/*': '../node_modules/angular2/*',
'fs': '../node_modules/fs/index',
... | /*
System.config({ | random_line_split |
config.ts | declare const System:any;
/*
System.config({
defaultJSExtensions: true,
packages: {
app: { format: 'register', defaultExtension: 'js' },
'@ngrx/store': { main: 'dist/index.js', defaultExtension: 'js' }
},
paths: {
'*': '*.js',
'angular2/*': '../node_modules/angular2/*',
... | (pkgName) { packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' } };
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
ngPacka... | packUmd | identifier_name |
indexMount.test.js | /* eslint no-undef: 0, fp/no-unused-expression: 0, fp/no-nil: 0, fp/no-mutation:0 , react/jsx-filename-extension:0 */
import React from 'react';
import {mount} from 'enzyme';
import {root} from 'utils';
import {HeaderPure} from './index';
jest.mock('react-router-dom/Link');
jest.mock('components/Container');
jest.mo... | it('component should removeEventListener on unmount', () => {
root.removeEventListener = jest.fn();
const wrapper = mount(<HeaderPure classes={classes} navigationLinkArray={[]} />);
wrapper.unmount();
expect(root.removeEventListener.mock.calls.length).toBeGreaterThan(0);
});
}); | random_line_split | |
index.js | function HtmlElementsPlugin(locations) {
this.locations = locations;
}
HtmlElementsPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('compilation', function(compilation) {
compilation.options.htmlElements = compilation.options.htmlElements || {};
compilation.pl... | }
const attributes = Object.getOwnPropertyNames(attrMap)
.filter(function(name) { return name[0] !== '='; } )
.map(function(name) {
var value = attrMap[name];
if (publicPath) {
// check if we have explicit instruction, use it if so (e.g: =herf: false)
... |
// add trailing slash if we have a publicPath and it doesn't have one.
if (publicPath && !RE_ENDS_WITH_BS.test(publicPath)) {
publicPath += '/'; | random_line_split |
index.js |
function | (locations) {
this.locations = locations;
}
HtmlElementsPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('compilation', function(compilation) {
compilation.options.htmlElements = compilation.options.htmlElements || {};
compilation.plugin('html-webpack-plugin-b... | HtmlElementsPlugin | identifier_name |
index.js |
function HtmlElementsPlugin(locations) {
this.locations = locations;
}
HtmlElementsPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('compilation', function(compilation) {
compilation.options.htmlElements = compilation.options.htmlElements || {};
compilation.p... |
callback(null, htmlPluginData);
});
});
};
const RE_ENDS_WITH_BS = /\/$/;
/**
* Create an HTML tag with attributes from a map.
*
* Example:
* createTag('link', { rel: "manifest", href: "/assets/manifest.json" })
* // <link rel="manifest" href="/assets/manifest.json">
* @param tagName... | {
const publicPath = htmlPluginData.assets.publicPath;
Object.getOwnPropertyNames(locations).forEach(function(loc) {
compilation.options.htmlElements[loc] = getHtmlElementString(locations[loc], publicPath);
});
} | conditional_block |
index.js |
function HtmlElementsPlugin(locations) |
HtmlElementsPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('compilation', function(compilation) {
compilation.options.htmlElements = compilation.options.htmlElements || {};
compilation.plugin('html-webpack-plugin-before-html-generation', function(htmlPluginData... | {
this.locations = locations;
} | identifier_body |
lint.py | import os
from typing import List
import click
from valohai_yaml.lint import lint_file
from valohai_cli.ctx import get_project
from valohai_cli.exceptions import CLIException
from valohai_cli.messages import success, warn
from valohai_cli.utils import get_project_directory
def | (filename: str) -> int:
"""
Validate `filename`, print its errors, and return the number of errors.
:param filename: YAML filename
:return: Number of errors
"""
lr = lint_file(filename)
if not lr.messages:
success(f'{filename}: No errors')
return 0
click.secho('{filenam... | validate_file | identifier_name |
lint.py | import os
from typing import List
import click
from valohai_yaml.lint import lint_file
from valohai_cli.ctx import get_project
from valohai_cli.exceptions import CLIException
from valohai_cli.messages import success, warn
from valohai_cli.utils import get_project_directory
| """
Validate `filename`, print its errors, and return the number of errors.
:param filename: YAML filename
:return: Number of errors
"""
lr = lint_file(filename)
if not lr.messages:
success(f'{filename}: No errors')
return 0
click.secho('{filename}: {error_count} errors... |
def validate_file(filename: str) -> int: | random_line_split |
lint.py | import os
from typing import List
import click
from valohai_yaml.lint import lint_file
from valohai_cli.ctx import get_project
from valohai_cli.exceptions import CLIException
from valohai_cli.messages import success, warn
from valohai_cli.utils import get_project_directory
def validate_file(filename: str) -> int:
... |
click.secho('{filename}: {error_count} errors, {warning_count} warnings'.format(
filename=filename,
error_count=lr.error_count,
warning_count=lr.warning_count,
), fg='yellow', bold=True)
for message in lr.messages:
click.echo(' {type}: {message}'.format(**message))
clic... | success(f'{filename}: No errors')
return 0 | conditional_block |
lint.py | import os
from typing import List
import click
from valohai_yaml.lint import lint_file
from valohai_cli.ctx import get_project
from valohai_cli.exceptions import CLIException
from valohai_cli.messages import success, warn
from valohai_cli.utils import get_project_directory
def validate_file(filename: str) -> int:
... | """
Lint (syntax-check) a valohai.yaml file.
The return code of this command will be the total number of errors found in all the files.
"""
if not filenames:
project = get_project()
directory = (project.directory if project else get_project_directory())
config_file = os.path.joi... | identifier_body | |
S15.7.4.4_A2_T04.js | // Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The valueOf function is not generic, it cannot be transferred
* to other kinds of objects for use as a method and there is should be
* a TypeError exception if its this value is not a Number object
*
* @path ch15/15.7/15.7.4/15.7.4.4/S15.7.4.4_A2_T... | } | $ERROR('#2: Number.prototype.valueOf on not a Number object should throw TypeError, not '+e);
} | random_line_split |
S15.7.4.4_A2_T04.js | // Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The valueOf function is not generic, it cannot be transferred
* to other kinds of objects for use as a method and there is should be
* a TypeError exception if its this value is not a Number object
*
* @path ch15/15.7/15.7.4/15.7.4.4/S15.7.4.4_A2_T... |
}
//CHECK#2
try{
var s2 = new Object();
s2.myValueOf = Number.prototype.valueOf;
var v2 = s2.myValueOf();
$ERROR('#2: Number.prototype.valueOf on not a Number object should throw TypeError');
}
catch(e){
if(!(e instanceof TypeError)){
$ERROR('#2: Number.prototype.valueOf on not a Number object should t... | {
$ERROR('#1: Number.prototype.valueOf on not a Number object should throw TypeError, not '+e);
} | conditional_block |
easyui-rtl.js | '], function(plugin){
if ($.fn[plugin]){
$.extend($.fn[plugin].defaults, {
iconAlign: 'left',
buttonAlign: 'left',
tipPosition: 'left',
panelAlign: 'right',
deltaX: -19
});
}
});
$.fn.validatebox.defaults.deltaX = 0;
$.map(['linkbutton','menubutton','splitbutton'], function(plugin){
i... | (){
var top = combo.offset().top + combo._outerHeight();
if (top + panel._outerHeight() > $(window)._outerHeight() + $(document).scrollTop()){
top = combo.offset().top - panel._outerHeight();
}
if (top < $(document).scrollTop()){
top = combo.offset().top + combo._outerHeight();
}
retur... | getTop | identifier_name |
easyui-rtl.js | '], function(plugin){
if ($.fn[plugin]){
$.extend($.fn[plugin].defaults, {
iconAlign: 'left',
buttonAlign: 'left',
tipPosition: 'left',
panelAlign: 'right',
deltaX: -19
});
}
});
$.fn.validatebox.defaults.deltaX = 0;
$.map(['linkbutton','menubutton','splitbutton'], function(plugin){
i... |
$.fn._scrollLeft = function(left){
if ($._rtlScrollType == undefined){checkScrollLeftType();}
if (left == undefined){
if ($._rtlScrollType == 'reverse'){
return this.scrollLeft();
} else if ($._rtlScrollType == 'negative'){
return -this.scrollLeft();
} else {
return this[0].scrollWidth - th... | {
var tmp = $('<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">test</div>').appendTo('body');
if (tmp.scrollLeft() > 0){
$._rtlScrollType = 'default'; // chrome
} else {
tmp.scrollLeft(1);
if (tmp.scrollLeft() == 0){
$._rtlScrollType... | identifier_body |
easyui-rtl.js | function(plugin){
if ($.fn[plugin]){
$.extend($.fn[plugin].defaults, {
iconAlign: 'left',
buttonAlign: 'left',
tipPosition: 'left',
panelAlign: 'right',
deltaX: -19
});
}
});
$.fn.validatebox.defaults.deltaX = 0;
$.map(['linkbutton','menubutton','splitbutton'], function(plugin){
if (... |
return top;
}
});
}
$.fn.menu.methods.show = function(jq, param){
return jq.each(function(){
var target = this;
var left,top;
param = param || {};
var menu = $(param.menu || target);
if (menu.hasClass('menu-top')){
var opts = $.data(target, 'menu').options;
$.extend(opts, param);
... | {
top = combo.offset().top + combo._outerHeight();
} | conditional_block |
easyui-rtl.js | '], function(plugin){
if ($.fn[plugin]){
$.extend($.fn[plugin].defaults, {
iconAlign: 'left',
buttonAlign: 'left',
tipPosition: 'left',
panelAlign: 'right',
deltaX: -19
});
}
});
$.fn.validatebox.defaults.deltaX = 0;
$.map(['linkbutton','menubutton','splitbutton'], function(plugin){
i... | }
}
if (top < 0){top = 0;}
return top;
}
menu.css({left:left,top:top});
menu.show( | random_line_split | |
timeline_demo.rs | ), Toggle(false), Toggle(true))
};
let bang_envelope = {
let points = bars::Periods::new(bars.iter().cloned(), PPQN).map(|period| Point {
ticks: period.start,
value: Bang,
});
Envelope::from_points(points, Bang, Bang)
};
let timeline_data = TimelineData ... | } | random_line_split | |
timeline_demo.rs | s {
window,
ruler,
timeline,
}
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.key_pressed(key_pressed)
.size(WIDTH, HEIGHT)
.title("Timeline Demo")
.view(view)
.build()
.unwrap();
// Create the UI.
let m... | (app: &App, model: &Model, frame: Frame) {
model.ui.draw_to_frame(app, &frame).unwrap();
}
// Update / draw the Ui.
fn set_widgets(ui: &mut UiCell, ids: &Ids, data: &mut TimelineData) {
use timeline::Timeline;
// Main window canvas.
widget::Canvas::new()
.border(0.0)
.color(ui::color::... | view | identifier_name |
timeline_demo.rs | s {
window,
ruler,
timeline,
}
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.key_pressed(key_pressed)
.size(WIDTH, HEIGHT)
.title("Timeline Demo")
.view(view)
.build()
.unwrap();
// Create the UI.
let m... | ;
let delta_ticks = time::Ms(delta_secs * ONE_SECOND_MS).to_ticks(current_bpm, PPQN);
let total_duration_ticks =
timeline::bars_duration_ticks(timeline_data.bars.iter().cloned(), PPQN);
let previous_playhead_ticks = timeline_data.playhead_ticks.clone();
timeline_data.playhead_ticks =
(ti... | {
0.0
} | conditional_block |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011-2012 Domsense s.r.l. (<http://www.domsense.com>).
# Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>)
#
# This progra... | "version": "2.0",
'category': 'Generic Modules/Accounting',
"depends": ["account_voucher_cash_basis"],
"author": "Agile Business Group",
"description": """
See 'account_voucher_cash_basis' description.
To activate the VAT on payment behaviour, this module adds a checkbox on invoice form... | ##############################################################################
{
"name": "VAT on payment", | random_line_split |
index.tsx | import * as React from 'react' // tslint:disable-line
import * as ReactDOM from 'react-dom'
import { Router, browserHistory, applyRouterMiddleware } from 'react-router'
import { useScroll } from 'react-router-scroll'
import routes from './routes'
import * as ReactGA from 'react-ga'
import { events } from './utils/event... |
if (window.Smooch) {
Smooch.on('widget:opened', () => {
ReactGA.event(events.SmoochOpened)
})
Smooch.on('message:sent', () => {
ReactGA.event(events.SmoochMessageSent)
})
}
function shouldScrollUp(previousProps, {location}) {
return location.hash === '' && (previousProps === null || previousProps.... | {
ReactGA.initialize(__GA_TRACKING_CODE__, {
titleCase: false,
} as ReactGA.InitializeOptions)
browserHistory.listen((location) => {
ReactGA.pageview(location.pathname)
})
} | conditional_block |
index.tsx | import * as React from 'react' // tslint:disable-line
import * as ReactDOM from 'react-dom'
import { Router, browserHistory, applyRouterMiddleware } from 'react-router' | import './polyfill'
if (__GA_TRACKING_CODE__) {
ReactGA.initialize(__GA_TRACKING_CODE__, {
titleCase: false,
} as ReactGA.InitializeOptions)
browserHistory.listen((location) => {
ReactGA.pageview(location.pathname)
})
}
if (window.Smooch) {
Smooch.on('widget:opened', () => {
ReactGA.event(event... | import { useScroll } from 'react-router-scroll'
import routes from './routes'
import * as ReactGA from 'react-ga'
import { events } from './utils/events'
| random_line_split |
index.tsx | import * as React from 'react' // tslint:disable-line
import * as ReactDOM from 'react-dom'
import { Router, browserHistory, applyRouterMiddleware } from 'react-router'
import { useScroll } from 'react-router-scroll'
import routes from './routes'
import * as ReactGA from 'react-ga'
import { events } from './utils/event... |
ReactDOM.render(
(
<Router
routes={routes}
history={browserHistory}
render={applyRouterMiddleware(useScroll(shouldScrollUp))}
/>
),
document.getElementById('root'),
)
| {
return location.hash === '' && (previousProps === null || previousProps.location.pathname !== location.pathname)
} | identifier_body |
index.tsx | import * as React from 'react' // tslint:disable-line
import * as ReactDOM from 'react-dom'
import { Router, browserHistory, applyRouterMiddleware } from 'react-router'
import { useScroll } from 'react-router-scroll'
import routes from './routes'
import * as ReactGA from 'react-ga'
import { events } from './utils/event... | (previousProps, {location}) {
return location.hash === '' && (previousProps === null || previousProps.location.pathname !== location.pathname)
}
ReactDOM.render(
(
<Router
routes={routes}
history={browserHistory}
render={applyRouterMiddleware(useScroll(shouldScrollUp))}
/>
),
document... | shouldScrollUp | identifier_name |
course_settings.js | /*
* Copyright (C) 2011 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License. | * Canvas 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 of the GNU Affero General Public Lic... | * | random_line_split |
course_settings.js | /*
* Copyright (C) 2011 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distribut... |
const navView = new NavigationView({el: $('#tab-navigation')})
const featureFlagView = new FeatureFlagAdminView({el: '#tab-features'})
featureFlagView.collection.fetchAll()
$(() => navView.render())
if (ENV.COURSE_IMAGES_ENABLED) {
const courseImageStore = configureStore(initialState)
ReactDOM.render(
<Co... | {
ReactDOM.render(
<BlueprintLockOptions
isMasterCourse={ENV.IS_MASTER_COURSE}
disabledMessage={ENV.DISABLED_BLUEPRINT_MESSAGE}
generalRestrictions={ENV.BLUEPRINT_RESTRICTIONS}
useRestrictionsbyType={ENV.USE_BLUEPRINT_RESTRICTIONS_BY_OBJECT_TYPE}
restrictionsByType={ENV.BLUEPRINT_RES... | conditional_block |
canvas.rs | 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 General Public License |
// | for details. |
// | ... |
}
pub fn draw_image(
&mut self,
image: &ahi::Image,
palette: &ahi::Palette,
left: i32,
top: i32,
scale: u32,
) {
for row in 0..image.height() {
for col in 0..image.width() {
let pixel = image[(col, row)];
l... | {
self.renderer.clear();
} | conditional_block |
canvas.rs | 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 General Public License |
// | for details. |
// | ... | Resources {
arrows: load_sprites_from_file(creator, "data/arrows.ahi"),
font: load_font_from_file(creator, "data/medfont.ahf"),
tool_icons: load_sprites_from_file(creator, "data/tool_icons.ahi"),
unsaved_icon: load_sprite_from_file(creator, "data/unsaved.ahi"),
... |
impl<'a> Resources<'a> {
pub fn new(creator: &'a TextureCreator<WindowContext>) -> Resources<'a> { | random_line_split |
canvas.rs | 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 General Public License |
// | for details. |
// | ... | <'a> {
glyphs: HashMap<char, Glyph<'a>>,
default_glyph: Glyph<'a>,
_baseline: i32,
}
impl<'a> Font<'a> {
pub fn text_width(&self, text: &str) -> i32 {
let mut width = 0;
for chr in text.chars() {
let glyph = self.glyph(chr);
width += glyph.right_edge - glyph.left... | Font | identifier_name |
__helper.py | """ This provides some useful code used by other modules. This is not to be
used by the end user which is why it is hidden. """
import string, sys
class LinkError(Exception):
|
def refine_import_err(mod_name, extension_name, exc):
""" Checks to see if the ImportError was because the library
itself was not there or because there was a link error. If there
was a link error it raises a LinkError if not it does nothing.
Keyword arguments
-----------------
- mod_name ... | pass | identifier_body |
__helper.py | """ This provides some useful code used by other modules. This is not to be
used by the end user which is why it is hidden. """
import string, sys
class LinkError(Exception):
pass
def refine_import_err(mod_name, extension_name, exc):
""" Checks to see if the ImportError was because the library
itself was... | raise LinkError, str(exc) | conditional_block | |
__helper.py | """ This provides some useful code used by other modules. This is not to be
used by the end user which is why it is hidden. """ | import string, sys
class LinkError(Exception):
pass
def refine_import_err(mod_name, extension_name, exc):
""" Checks to see if the ImportError was because the library
itself was not there or because there was a link error. If there
was a link error it raises a LinkError if not it does nothing.
Ke... | random_line_split | |
__helper.py | """ This provides some useful code used by other modules. This is not to be
used by the end user which is why it is hidden. """
import string, sys
class | (Exception):
pass
def refine_import_err(mod_name, extension_name, exc):
""" Checks to see if the ImportError was because the library
itself was not there or because there was a link error. If there
was a link error it raises a LinkError if not it does nothing.
Keyword arguments
--------------... | LinkError | identifier_name |
vm_console.py | A mixin to provide methods to get a vm console object
"""
@classmethod
def console_handle(cls, browser):
"""
The basic algorithm for getting the consoles window handle is to get the
appliances window handle and then iterate through the window_handles till we find
one that i... |
def find_text_on_screen(self, text_to_find, current_line=False):
"""Find particular text is present on Screen.
This function uses get_screen_text function to get string containing
the text on the screen and then tries to match it against the 'text_to_find'.
Args:
text... | self.switch_to_console()
self.selenium.close()
logger.info("Browser window/tab containing Console was closed.")
self.switch_to_appliance() | conditional_block |
vm_console.py | .info("Creating VMConsole:")
logger.info(" appliance_handle: {}".format(appliance_handle))
logger.info(" console_handle: {}".format(console_handle))
logger.info(" name: {}".format(self.name))
return VMConsole(appliance_handle=appliance_handle,
... | """Wait for as long as the specified/default timeout for the 'text' to show up on screen.
Args:
timeout: Wait Time before wait_for function times out.
text_to_find: value passed to find_text_on_screen function
to_disappear: if set to True, function will wait for text_to_find... | identifier_body | |
vm_console.py | A mixin to provide methods to get a vm console object
"""
@classmethod
def console_handle(cls, browser):
"""
The basic algorithm for getting the consoles window handle is to get the
appliances window handle and then iterate through the window_handles till we find
one that i... | (self, text):
"""Send text to the console."""
self.switch_to_console()
canvas = self.provider.get_remote_console_canvas()
logger.info("Sending following Keys to Console {}".format(text))
for character in text:
canvas.send_keys(character)
# time.sleep() is ... | send_keys | identifier_name |
vm_console.py | A mixin to provide methods to get a vm console object
"""
@classmethod
def console_handle(cls, browser): | The basic algorithm for getting the consoles window handle is to get the
appliances window handle and then iterate through the window_handles till we find
one that is not the appliances window handle. Once we find this check that it has
a canvas widget with a specific ID
"""
... | """ | random_line_split |
axisPointer.js | var echarts = require("../echarts");
var zrUtil = require("zrender/lib/core/util");
var axisPointerModelHelper = require("./axisPointer/modelHelper");
var axisTrigger = require("./axisPointer/axisTrigger");
require("./axisPointer/AxisPointerModel");
require("./axisPointer/AxisPointerView");
require("./axisPointer... |
}
}); // This process should proformed after coordinate systems created
// and series data processed. So put it on statistic processing stage.
echarts.registerProcessor(echarts.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
// Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
// a... | {
option.axisPointer.link = [link];
} | conditional_block |
axisPointer.js | var echarts = require("../echarts");
var zrUtil = require("zrender/lib/core/util");
var axisPointerModelHelper = require("./axisPointer/modelHelper");
var axisTrigger = require("./axisPointer/axisTrigger");
require("./axisPointer/AxisPointerModel");
require("./axisPointer/AxisPointerView");
require("./axisPointer... | }, axisTrigger); | echarts.registerAction({
type: 'updateAxisPointer',
event: 'updateAxisPointer',
update: ':updateAxisPointer' | random_line_split |
signalstrength.py | r"""Functions for Higgs signal strengths."""
import flavio
from . import production
from . import decay
from . import width
prod_modes = {
'ggF': {
'desc': 'gluon fusion production',
'tex': 'gg',
'str': 'gg',
},
'hw': {
'desc': '$W$ boson associated production',
't... | make_obs_higgs(prod, dec) | conditional_block | |
signalstrength.py | r"""Functions for Higgs signal strengths."""
import flavio
from . import production
from . import decay
from . import width
prod_modes = {
'ggF': {
'desc': 'gluon fusion production',
'tex': 'gg',
'str': 'gg',
},
'hw': {
'desc': '$W$ boson associated production',
't... |
for prod in prod_modes:
for dec in decay_modes:
make_obs_higgs(prod, dec)
| d_dec = decay_modes[name_dec]
d_prod = prod_modes[name_prod]
process_tex = r"h \to {}".format(d_dec['tex'])
process_taxonomy = r'Process :: Higgs production and decay :: $' + d_dec['tex_class'] + r'$ :: $' + process_tex + r"$"
obs_name = "mu_{}(h->{})".format(d_prod['str'], d_dec['str'])
obs = flavi... | identifier_body |
signalstrength.py | r"""Functions for Higgs signal strengths."""
import flavio
from . import production
from . import decay
from . import width
prod_modes = {
'ggF': {
'desc': 'gluon fusion production',
'tex': 'gg',
'str': 'gg',
},
'hw': {
'desc': '$W$ boson associated production',
't... | 'desc': 'weak boson fusion',
'tex': r'\text{VBF}',
'str': 'VBF',
},
}
decay_modes = {
'h_bb': {
'tex': r'b\bar b',
'str': 'bb',
'tex_class': r'h\to ff',
},
'h_cc': {
'tex': r'c\bar c',
'str': 'cc',
'tex_class': r'h\to ff',
},
... | 'str': 'tth',
},
'vv_h': { | random_line_split |
signalstrength.py | r"""Functions for Higgs signal strengths."""
import flavio
from . import production
from . import decay
from . import width
prod_modes = {
'ggF': {
'desc': 'gluon fusion production',
'tex': 'gg',
'str': 'gg',
},
'hw': {
'desc': '$W$ boson associated production',
't... | (wc_obj, par, name_prod, name_dec):
scale = flavio.config['renormalization scale']['hdecays']
C = wc_obj.get_wcxf(sector='all', scale=scale, par=par,
eft='SMEFT', basis='Warsaw')
f_prod = getattr(production, name_prod)
f_dec = getattr(decay, name_dec)
return f_prod(C) * f_dec... | higgs_signalstrength | identifier_name |
gadget.service.ts |
import {throwError as observableThrowError, interval as observableInterval, Observable } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Gadget } from './gadget';
import { Gad... | (error: any) {
try {
// if error comes from backend it has a json representation and error is type response
let errors = error.json();
let errorMessagesByType = Object.keys(errors).map(function(key){
return errors[key];
});
let errorMes... | handleError | identifier_name |
gadget.service.ts |
import {throwError as observableThrowError, interval as observableInterval, Observable } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Gadget } from './gadget';
import { Gad... |
getGadget (slug: string): Observable<Gadget> {
let headers = new HttpHeaders({'Content-Type': 'application/json'});
return this.http.get<Gadget>(this.gadgetsUrl+slug+'/', { headers }).pipe(
catchError(this.handleError)
);
}
getGadgetDataForGadget (slug: string, limit: ... | {
let headers = new HttpHeaders({'Content-Type': 'application/json'});
return this.http.get<Gadget[]>(this.gadgetsUrl, { headers }).pipe(
catchError(this.handleError)
);
} | identifier_body |
gadget.service.ts | import {throwError as observableThrowError, interval as observableInterval, Observable } from 'rxjs'; | import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Gadget } from './gadget';
import { GadgetData } from './gadget-data';
@Injectable()
export class GadgetService {
private gadgetsUrl = 'backend/api/v1/gadgets/';
constructor (
private http: HttpClient
) {}
getGadgets (): ... |
import { catchError, map, mergeMap } from 'rxjs/operators';
import { Injectable } from '@angular/core'; | random_line_split |
clean-conversation-filters.tsx | import cache from 'webext-storage-cache';
import select from 'select-dom';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
import {getRepo} from '../github-helpers';
const hasAnyProjects = cache.funct... |
void features.add(__filebasename, {
include: [
pageDetect.isRepoConversationList,
],
awaitDomReady: false,
deduplicate: 'has-rgh-inner',
init,
});
| {
if (!await elementReady('#js-issues-toolbar', {waitForChildren: false})) {
// Repo has no issues, so no toolbar is shown
return false;
}
await Promise.all([
hideMilestones(),
hideProjects(),
]);
} | identifier_body |
clean-conversation-filters.tsx | import cache from 'webext-storage-cache';
import select from 'select-dom';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
import {getRepo} from '../github-helpers'; | projects { totalCount }
}
organization(login: "${getRepo()!.owner}") {
projects { totalCount }
}
`, {
allowErrors: true,
});
return Boolean(repository.projects.totalCount) && Boolean(organization?.projects?.totalCount);
}, {
maxAge: {days: 1},
staleWhileRevalidate: {days: 20},
cacheKey: () => `has-... |
const hasAnyProjects = cache.function(async (): Promise<boolean> => {
const {repository, organization} = await api.v4(`
repository() { | random_line_split |
clean-conversation-filters.tsx | import cache from 'webext-storage-cache';
import select from 'select-dom';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
import {getRepo} from '../github-helpers';
const hasAnyProjects = cache.funct... |
await Promise.all([
hideMilestones(),
hideProjects(),
]);
}
void features.add(__filebasename, {
include: [
pageDetect.isRepoConversationList,
],
awaitDomReady: false,
deduplicate: 'has-rgh-inner',
init,
});
| {
// Repo has no issues, so no toolbar is shown
return false;
} | conditional_block |
clean-conversation-filters.tsx | import cache from 'webext-storage-cache';
import select from 'select-dom';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';
import features from '.';
import * as api from '../github-helpers/api';
import {getRepo} from '../github-helpers';
const hasAnyProjects = cache.funct... | (element: HTMLElement): number {
return Number(element.textContent!.trim());
}
async function hideMilestones(): Promise<void> {
const milestones = select('[data-selected-links^="repo_milestones"] .Counter')!;
if (getCount(milestones) === 0) {
(await elementReady('[data-hotkey="m"]'))!.parentElement!.remove();
}
... | getCount | identifier_name |
points.rs | use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i... | else {l1.i.x - l1.h.x};
if s1 > MAX || s1 < MIN {panic!("overload");}
let s2: i32 = if l1.h.y > l1.i.y {l1.h.y - l1.i.y} else {l1.i.y - l1.h.y};
if s2 > MAX || s2 < MIN {panic!("overload");}
let len = l1.length (s1, s2);
println!("length: {}", len);
let mid = l1.midpoint(l1.h.x, l1.i.x, l1.h.y, l1.i.y);
... | {l1.h.x - l1.i.x} | conditional_block |
points.rs | use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i... | () {
let mut numbox = vec![0, 0, 0, 0];
for i in 0..4 {
match i {
0 => println!("point 1 x-value: "),
1 => println!("point 1 y-value: "),
2 => println!("point 2 x-value: "),
3 => println!("point 2 y-value: "),
_ => panic!("error"),
}
let mut osin = io::stdin();
let mut ... | main | identifier_name |
points.rs | use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i... | osin.read_line(&mut entry).ok().expect("error.");
let gen: Option<i32> = entry.trim().parse::<i32>().ok();
let num = match gen {Some(num) => num, None => {return;}};
if num > MAX || num < MIN {panic!("overload");}
numbox[i] = num;
}
let p1: Point = Point {x: numbox[0], y: numbox[1]};
let p2: P... | _ => panic!("error"),
}
let mut osin = io::stdin();
let mut entry = String::new(); | random_line_split |
BaseModels.py | # -*- coding: utf-8 -*-
'''
Created on Mar 12, 2012
@author: moloch
Copyright 2012
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... | (self):
''' Converts name from camel case to snake case '''
name = self.__name__
return (
name[0].lower() +
re.sub(r'([A-Z])',
lambda letter: "_" + letter.group(0).lower(), name[1:]
)
)
id = Column(Integer, unique=True, primary_... | __tablename__ | identifier_name |
BaseModels.py | # -*- coding: utf-8 -*-
'''
Created on Mar 12, 2012
@author: moloch
Copyright 2012
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... |
id = Column(Integer, unique=True, primary_key=True) # lint:ok
uuid = Column(String(36), unique=True, default=generate_uuid)
created = Column(DateTime, default=datetime.now)
# Create an instance called "BaseObject"
DatabaseObject = declarative_base(cls=_DatabaseObject)
| ''' Converts name from camel case to snake case '''
name = self.__name__
return (
name[0].lower() +
re.sub(r'([A-Z])',
lambda letter: "_" + letter.group(0).lower(), name[1:]
)
) | identifier_body |
BaseModels.py | # -*- coding: utf-8 -*-
'''
Created on Mar 12, 2012
@author: moloch
Copyright 2012
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... |
# Create an instance called "BaseObject"
DatabaseObject = declarative_base(cls=_DatabaseObject) | id = Column(Integer, unique=True, primary_key=True) # lint:ok
uuid = Column(String(36), unique=True, default=generate_uuid)
created = Column(DateTime, default=datetime.now) | random_line_split |
tutorial-10.rs | #[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn | () {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_depth_buffer(24);
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
l... | main | identifier_name |
tutorial-10.rs | #[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn main() | out vec3 v_normal;
uniform mat4 perspective;
uniform mat4 matrix;
void main() {
v_normal = transpose(inverse(mat3(matrix))) * normal;
gl_Position = perspective * matrix * vec4(position, 1.0);
}
"#;
let fragment_shader_src = r#"
#version ... | {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_depth_buffer(24);
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
let ... | identifier_body |
tutorial-10.rs | #[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn main() {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_d... | let znear = 0.1;
let f = 1.0 / (fov / 2.0).tan();
[
[f * aspect_ratio , 0.0, 0.0 , 0.0],
[ 0.0 , f , 0.0 , 0.0],
[ 0.0 , 0.0, (zfar... |
let fov: f32 = 3.141592 / 3.0;
let zfar = 1024.0; | random_line_split |
featharalick_sharding_blend_pl_blend4_convroll4_doublescale_fs5_no_dropout_33_66.py | import numpy as np
import theano
import theano.tensor as T
import lasagne as nn
import data
import load
import nn_plankton
import dihedral
import tmp_dnn
import tta
features = [
# "hu",
# "tutorial",
"haralick",
# "aaronmoments",
# "lbp",
# "pftas",
# "zernike_moments",
# "image_siz... | (l_ins, l_out):
reg_param = 0.0002
alpha = 0. # 0 -> L2 1-> L1
print "regu", reg_param, alpha
# lambda_reg = 0.005
params = nn.layers.get_all_non_bias_params(l_out)
# reg_term = sum(T.sum(p**2) for p in params)
L2 = sum(T.sum(p**2) for p in params)
L1 = sum(T.sum(T.abs_(p)) for p in par... | build_objective | identifier_name |
featharalick_sharding_blend_pl_blend4_convroll4_doublescale_fs5_no_dropout_33_66.py | import numpy as np
import theano
import theano.tensor as T
import lasagne as nn
import data
import load
import nn_plankton
import dihedral
import tmp_dnn
import tta
features = [
# "hu",
# "tutorial",
"haralick",
# "aaronmoments",
# "lbp",
# "pftas",
# "zernike_moments",
# "image_siz... | params = nn.layers.get_all_non_bias_params(l_out)
# reg_term = sum(T.sum(p**2) for p in params)
L2 = sum(T.sum(p**2) for p in params)
L1 = sum(T.sum(T.abs_(p)) for p in params)
def loss(y, t):
return nn_plankton.log_loss(y, t) + reg_param*(alpha * L1 + (1-alpha) * L2)
return nn.objecti... | random_line_split | |
featharalick_sharding_blend_pl_blend4_convroll4_doublescale_fs5_no_dropout_33_66.py | import numpy as np
import theano
import theano.tensor as T
import lasagne as nn
import data
import load
import nn_plankton
import dihedral
import tmp_dnn
import tta
features = [
# "hu",
# "tutorial",
"haralick",
# "aaronmoments",
# "lbp",
# "pftas",
# "zernike_moments",
# "image_siz... | reg_param = 0.0002
alpha = 0. # 0 -> L2 1-> L1
print "regu", reg_param, alpha
# lambda_reg = 0.005
params = nn.layers.get_all_non_bias_params(l_out)
# reg_term = sum(T.sum(p**2) for p in params)
L2 = sum(T.sum(p**2) for p in params)
L1 = sum(T.sum(T.abs_(p)) for p in params)
def loss(y... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.