file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn | () -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> {
&self.timers
}
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());... | new | identifier_name |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub ... |
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
}
| {
panic!("Tried to stop non-live timer: {:?}", name);
} | conditional_block |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub ... |
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
... | {
&self.timers
} | identifier_body |
test_page_api.py | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.api.pa... | (self):
"""Test case for update_page
Update a landing page partially. # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
| test_update_page | identifier_name |
test_page_api.py | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.api.pa... | Update a landing page partially. # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main() | def test_update_page(self):
"""Test case for update_page
| random_line_split |
test_page_api.py | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.api.pa... |
if __name__ == '__main__':
unittest.main()
| """PageApi unit test stubs"""
def setUp(self):
self.api = mailmojo_sdk.api.page_api.PageApi() # noqa: E501
def tearDown(self):
pass
def test_get_page_by_id(self):
"""Test case for get_page_by_id
Retrieve a landing page. # noqa: E501
"""
pass
def tes... | identifier_body |
test_page_api.py | # coding: utf-8
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.api.pa... | unittest.main() | conditional_block | |
gulpfile.js | const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const webserver = require('gulp-webserver');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
co... | () {
return br.bundle()
.pipe(source('Solufa.js'))
.pipe(gulp.dest('./static/js'));
}
gulp.task( "msx", function() {
gulp.src('./components/*.js')
.pipe(msx({harmony: true}))
.pipe(gulp.dest('./static/components'));
});
gulp.task( "default", function() {
gulp.src('./static')
.pipe(webserver({
... | bundle | identifier_name |
gulpfile.js | const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const webserver = require('gulp-webserver');
const uglify = require('gulp-uglify'); | const br = watchify(
browserify({
entries: './src/Solufa.ts'
})
.plugin('tsify', {target: 'es6'})
.transform("babelify")
);
br.on( "update", bundle );
function bundle() {
return br.bundle()
.pipe(source('Solufa.js'))
.pipe(gulp.dest('./static/js'));
}
gulp.task( "msx", function() {
gulp.src('./co... | const rename = require('gulp-rename');
const msx = require('gulp-msx');
| random_line_split |
gulpfile.js | const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const webserver = require('gulp-webserver');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
co... |
gulp.task( "msx", function() {
gulp.src('./components/*.js')
.pipe(msx({harmony: true}))
.pipe(gulp.dest('./static/components'));
});
gulp.task( "default", function() {
gulp.src('./static')
.pipe(webserver({
host: '0.0.0.0',//スマホからIPアドレスでアクセスできる
livereload: true,
open: "http://0.0.0.0:8... | {
return br.bundle()
.pipe(source('Solufa.js'))
.pipe(gulp.dest('./static/js'));
} | identifier_body |
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | {
test_mpsc()
} | identifier_body | |
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | /*
use xi_rpc::chan::Chan;
pub fn test_chan() {
let n_iter = 1000000;
let chan1 = Chan::new();
let chan1s = chan1.clone();
let chan2 = Chan::new();
let chan2s = chan2.clone();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.try_send(chan1.recv());
}
... |
use std::thread;
use std::sync::mpsc;
| random_line_split |
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | () {
let n_iter = 1000000;
let (chan1s, chan1) = mpsc::channel();
let (chan2s, chan2) = mpsc::channel();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.send(chan1.recv()).unwrap();
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter... | test_mpsc | identifier_name |
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect + 'static> Any ... |
}
| {
struct A;
let x: A = A;
let _: TypeId = x.get_type_id();
} | identifier_body |
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect + 'static> Any ... | }
} | random_line_split | |
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect + 'static> Any ... | ;
let x: A = A;
let _: TypeId = x.get_type_id();
}
}
| A | identifier_name |
Set.js | /*
Copyright 2008-2013 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Pub... |
},
//-------------------------------------------------------------------------
'debug': function() {
var i, c;
result = -1;
c = this.items().length;
for (i=0; i<c; i++) {
alert("[" + i + "] " + this.items()[i].label);
}
},
//---------------------------------------------------------------------... | {
if (! this.contains(anItem)) {
this.items().push(anItem);
}
} | conditional_block |
Set.js | /*
Copyright 2008-2013 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Pub... | 'toString': function() {
return "Clipperz.Set";
},
//-------------------------------------------------------------------------
'items': function() {
return this._items;
},
//-------------------------------------------------------------------------
'popAnItem': function() {
var result;
if (this.size... | random_line_split | |
deploy_base.py | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELI... | desc = generate_desc(oldrev, newrev, changelog)
if changelog:
github_url = GITHUB_URL.format(oldrev=oldrev, newrev=newrev)
changelog = '{0}\n\n{1}'.format(changelog, github_url)
data = urllib.urlencode({
'deployment[description]': desc,
'deployment... | log_cmd = 'git log --oneline {0}..{1}'.format(oldrev, newrev)
changelog = ctx.local(log_cmd).out.strip()
print 'Post deployment to New Relic' | random_line_split |
deploy_base.py | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELI... |
@task
def pre_update(ctx, ref=settings.UPDATE_REF):
commands['update_code'](ref)
commands['update_info']()
@task
def update(ctx):
commands['database']()
commands['update_assets']()
commands['update_locales']()
commands['update_revision_file']()
commands['reload_crond']()
@task
def dep... | if NEW_RELIC_API_KEY and NEW_RELIC_APP_ID:
with ctx.lcd(settings.SRC_DIR):
oldrev = ctx.local('cat media/prev-revision.txt').out.strip()
newrev = ctx.local('cat media/revision.txt').out.strip()
log_cmd = 'git log --oneline {0}..{1}'.format(oldrev, newrev)
changelo... | identifier_body |
deploy_base.py | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELI... |
return sorted(list(bugs))
def generate_desc(from_commit, to_commit, changelog):
"""Figures out a good description based on what we're pushing out."""
if from_commit.startswith(to_commit):
desc = 'Pushing {0} again'.format(to_commit)
else:
bugs = extract_bugs(changelog.split('\n'))
... | bugs.add(bug) | conditional_block |
deploy_base.py | """
Deployment for Bedrock in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import urllib
import urllib2
from commander.deploy import commands, task, hostgroups
import commander_settings as settings
NEW_RELI... | (ctx, tag):
with ctx.lcd(settings.SRC_DIR):
ctx.local("git fetch --all")
ctx.local("git checkout -f %s" % tag)
ctx.local("git submodule sync")
ctx.local("git submodule update --init --recursive")
@task
def update_locales(ctx):
with ctx.lcd(os.path.join(settings.SRC_DIR, 'locale... | update_code | identifier_name |
plugin.py | # -*- coding: iso-8859-1 -*-
# (c) 2006 Stephan Reichholf
# This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright!
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
f... | (self):
self["SkinList"].down()
self.loadPreview()
def left(self):
self["SkinList"].pageUp()
self.loadPreview()
def right(self):
self["SkinList"].pageDown()
self.loadPreview()
def info(self):
aboutbox = self.session.open(MessageBox,_("STB-GUI Skinselector\n\nIf you experience any problems please con... | down | identifier_name |
plugin.py | # -*- coding: iso-8859-1 -*-
# (c) 2006 Stephan Reichholf
# This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright!
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
f... |
self.skinfile = os.path.join(self.skinfile, SKINXML)
print "Skinselector: Selected Skin: "+self.root+self.skinfile
restartbox = self.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart to apply a new skin\nDo you want to restart the GUI now?"), MessageBox.TYPE_YESNO)
restartbox.setTitle... | self.skinfile = self["SkinList"].getCurrent() | conditional_block |
plugin.py | # -*- coding: iso-8859-1 -*-
# (c) 2006 Stephan Reichholf
# This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright!
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
f... | def info(self):
aboutbox = self.session.open(MessageBox,_("STB-GUI Skinselector\n\nIf you experience any problems please contact\nstephan@reichholf.net\n\n\xA9 2006 - Stephan Reichholf"), MessageBox.TYPE_INFO)
aboutbox.setTitle(_("About..."))
def ok(self):
if self["SkinList"].getCurrent() == DEFAULTSKIN:
se... | def right(self):
self["SkinList"].pageDown()
self.loadPreview()
| random_line_split |
plugin.py | # -*- coding: iso-8859-1 -*-
# (c) 2006 Stephan Reichholf
# This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright!
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
f... | return PluginDescriptor(name="Skinselector", description="Select Your Skin", where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=SkinSelSetup) | identifier_body | |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct SamplerRenderer<'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator:... |
#[allow(unused_variables)]
fn li(&self, scene: &Scene, ray: &RayDifferential, sample: &Sampler) -> Box<Spectrum> {
unimplemented!()
}
#[allow(unused_variables)]
fn transmittance(&self,
scene: &Scene,
ray: &RayDifferential,
sam... | {
self.surface_integrator.preprocess(scene, &self.camera);
self.volume_integrator.preprocess(scene, &self.camera);
} | identifier_body |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct SamplerRenderer<'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator:... | fn new(sampler: S,
camera: C,
surface_integrator: &'a SurfaceIntegrator,
volume_integrator: &'a VolumeIntegrator)
-> SamplerRenderer<'a, S, C> {
SamplerRenderer {
sampler: sampler,
camera: camera,
surface_integrator: surface_int... | }
impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> { | random_line_split |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct | <'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator: &'a SurfaceIntegrator,
pub volume_integrator: &'a VolumeIntegrator,
}
impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> {
fn new(sampler: S,
camera: C,
surface_integrator: &'a SurfaceI... | SamplerRenderer | identifier_name |
app.js | import React, {
Component,
PropTypes
} from 'react';
import {
Provider,
connect
} from 'react-redux';
import {
Button
} from 'local-Antd';
import RoomSelect from 'components/ui-number-select/index.jsx';
import GuestSelect from 'components/ui-hotel-guest/index.jsx';
import NumberSelect from 'components/ui-numb... |
return Object.assign({}, {})
}
export default connect(mapStateToProps)(App) |
function mapStateToProps(state) { | random_line_split |
app.js | import React, {
Component,
PropTypes
} from 'react';
import {
Provider,
connect
} from 'react-redux';
import {
Button
} from 'local-Antd';
import RoomSelect from 'components/ui-number-select/index.jsx';
import GuestSelect from 'components/ui-hotel-guest/index.jsx';
import NumberSelect from 'components/ui-numb... | console.log('---_handle' + key);
}
_handleAsyn(key) {
console.log('---_handleAsyn' + key, this.state);
let state = this.alertAttrAsyn;
state.showFlag = false;
if (key == 'ok') {
// 此处假设只有ok按钮异步请求
// 模仿异步请求完成
setTimeout(() => {
this.setState(state);
}, 5000)
}
... | key) {
| identifier_name |
app.js | import React, {
Component,
PropTypes
} from 'react';
import {
Provider,
connect
} from 'react-redux';
import {
Button
} from 'local-Antd';
import RoomSelect from 'components/ui-number-select/index.jsx';
import GuestSelect from 'components/ui-hotel-guest/index.jsx';
import NumberSelect from 'components/ui-numb... | al);
}
_changeGuest(val) {
console.log('当前选择Guest Info', val);
}
_changeNm(val) {
console.log('当前选择Nm Info', val);
}
get showModal() {
return true;
}
get guestInit() {
let childAges = [{
defValue: 2
}, {
defValue: 5
}];
return {
childAges: [],
adultM... | nsole.log('---_handleAsyn' + key, this.state);
let state = this.alertAttrAsyn;
state.showFlag = false;
if (key == 'ok') {
// 此处假设只有ok按钮异步请求
// 模仿异步请求完成
setTimeout(() => {
this.setState(state);
}, 5000)
}
}
_changeRoom(val) {
console.log('当前房间数', v | identifier_body |
app.js | import React, {
Component,
PropTypes
} from 'react';
import {
Provider,
connect
} from 'react-redux';
import {
Button
} from 'local-Antd';
import RoomSelect from 'components/ui-number-select/index.jsx';
import GuestSelect from 'components/ui-hotel-guest/index.jsx';
import NumberSelect from 'components/ui-numb... | 数', val);
}
_changeGuest(val) {
console.log('当前选择Guest Info', val);
}
_changeNm(val) {
console.log('当前选择Nm Info', val);
}
get showModal() {
return true;
}
get guestInit() {
let childAges = [{
defValue: 2
}, {
defValue: 5
}];
return {
childAges: [],
a... | // 此处假设只有ok按钮异步请求
// 模仿异步请求完成
setTimeout(() => {
this.setState(state);
}, 5000)
}
}
_changeRoom(val) {
console.log('当前房间 | conditional_block |
crypto.py | """
Django's standard crypto functions and utilities.
""" | import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on... | from __future__ import unicode_literals
import hmac | random_line_split |
crypto.py | """
Django's standard crypto functions and utilities.
"""
from __future__ import unicode_literals
import hmac
import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
impo... | (val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circu... | constant_time_compare | identifier_name |
crypto.py | """
Django's standard crypto functions and utilities.
"""
from __future__ import unicode_literals
import hmac
import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
impo... |
else:
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings ... | return hmac.compare_digest(force_bytes(val1), force_bytes(val2)) | identifier_body |
crypto.py | """
Django's standard crypto functions and utilities.
"""
from __future__ import unicode_literals
import hmac
import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
impo... |
else:
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings ... | def constant_time_compare(val1, val2):
return hmac.compare_digest(force_bytes(val1), force_bytes(val2)) | conditional_block |
rmeta.rs | // Copyright 2016 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 ... | // aux-build:rmeta_rlib.rs
extern crate rmeta_aux;
use rmeta_aux::Foo;
pub fn main() {
let _ = Foo { field: 42 };
} |
// Test that using rlibs and rmeta dep crates work together. Specifically, that
// there can be both an rmeta and an rlib file and rustc will prefer the rlib.
// aux-build:rmeta_rmeta.rs | random_line_split |
rmeta.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let _ = Foo { field: 42 };
} | identifier_body | |
rmeta.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let _ = Foo { field: 42 };
}
| main | identifier_name |
parsers.py | import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def parse_genes(gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_f... |
go_dict[gene_id].append(go)
return go_dict
| go_dict[gene_id] = [] | conditional_block |
parsers.py | import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def parse_genes(gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_f... | if fields[9] != '':
try:
annotation['rank'] = int(fields[9])
except:
pass
annotations.append(annotation)
return coding, annotations, gene_name
def parse_snpeff(snp, is_custom_snp_eff):
"""parses the snpeff fields"""
anc = ''
if is_... | gene_name = annotation['gene_name']
coding = True
if fields[8] != '':
annotation['transcript_id'] = fields[8] | random_line_split |
parsers.py | import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def parse_genes(gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_f... |
def parse_lastel(last_el):
# Need to transform _ to # and check if string contains square brackets
if last_el[0] == '[':
last_el = last_el[1:-1]
last = last_el.split(',')
print(last)
score = float(last[0])
uid = '#'.join(last[1][1:-1].split('-'))
return [score, uid]
def _get_go_ma... | """parses the snpeff fields"""
anc = ''
if is_custom_snp_eff:
anc = snp[4]
if anc == '0':
anc = snp[2]
elif anc == '1':
anc = snp[3]
chrom = snp[0].lower()
pos = int(snp[1])
if is_custom_snp_eff:
ref = snp[2]
alt = snp[3]
genot... | identifier_body |
parsers.py | import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def | (gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_file)
gff = Gff3(gff3_file)
genes = [line for line in gff.lines if line['line_type'] == 'feature' and line['type'] == 'gene']
genes_map = {}
for gene in genes:
... | parse_genes | identifier_name |
app.js | 'use strict';
var path = require('path'),
logger = require('morgan'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser');
var routes = require('./routes/index');
var app = express();
app.config = require((process.env.NODE_ENV === 'test') ? './c... |
// Production error handler
// No stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
} | conditional_block |
app.js | 'use strict';
var path = require('path'),
logger = require('morgan'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser');
var routes = require('./routes/index');
var app = express();
app.config = require((process.env.NODE_ENV === 'test') ? './c... |
// Production error handler
// No stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app; | });
});
} | random_line_split |
main.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as path from 'canonical-path';
import * as yargs from 'yargs';
import {checkMarkerFile, writeMarkerFile} fr... | console.warn(`Skipping ${entryPoint.name} : ${format} (already built).`);
return;
}
const bundle =
makeEntryPointBundle(entryPoint, isCore, format, format === dtsTransformFormat);
if (bundle === null) {
console.warn(
`Skipping ${entryPoint... | random_line_split | |
main.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as path from 'canonical-path';
import * as yargs from 'yargs';
import {checkMarkerFile, writeMarkerFile} fr... | (args: string[]): number {
const options =
yargs
.option('s', {
alias: 'source',
describe: 'A path to the root folder to compile.',
default: './node_modules'
})
.option('f', {
alias: 'formats',
array: true,
des... | mainNgcc | identifier_name |
main.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as path from 'canonical-path';
import * as yargs from 'yargs';
import {checkMarkerFile, writeMarkerFile} fr... |
const bundle =
makeEntryPointBundle(entryPoint, isCore, format, format === dtsTransformFormat);
if (bundle === null) {
console.warn(
`Skipping ${entryPoint.name} : ${format} (no entry point file for this format).`);
} else {
transformer.transform(e... | {
console.warn(`Skipping ${entryPoint.name} : ${format} (already built).`);
return;
} | conditional_block |
main.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as path from 'canonical-path';
import * as yargs from 'yargs';
import {checkMarkerFile, writeMarkerFile} fr... | {
const options =
yargs
.option('s', {
alias: 'source',
describe: 'A path to the root folder to compile.',
default: './node_modules'
})
.option('f', {
alias: 'formats',
array: true,
describe: 'An array of forma... | identifier_body | |
test_database_upgrade_service.py | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(DatabaseBaseTest):
|
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | def setUp(self):
super().setUp()
self.upgrade_service = DatabaseUpgradeService(self.engine)
def tearDown(self):
super().tearDown()
def testUpgrade(self):
self.assertTrue(self.upgrade_service.is_update_necessary())
self.upgrade_service.run_update()
self.assertF... | identifier_body |
test_database_upgrade_service.py | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(DatabaseBaseTest):
def setUp(self):
super().setUp()
... | unittest.main() | conditional_block | |
test_database_upgrade_service.py | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(DatabaseBaseTest):
def setUp(self):
super().setUp()
... | (self):
registry_dao = RegistryDao(self.engine)
registry_dao.set('version', 'not_existing')
self.assertTrue(self.upgrade_service.is_update_necessary())
expected_exception = False
try:
self.upgrade_service.run_update()
except Exception:
expected_exc... | testFailingUpgrade | identifier_name |
test_database_upgrade_service.py | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(DatabaseBaseTest):
def setUp(self):
super().setUp()
... | registry_dao.set('version', 'not_existing')
self.assertTrue(self.upgrade_service.is_update_necessary())
expected_exception = False
try:
self.upgrade_service.run_update()
except Exception:
expected_exception = True
self.assertTrue(expected_exception... | self.upgrade_service.run_update()
self.assertFalse(self.upgrade_service.is_update_necessary())
def testFailingUpgrade(self):
registry_dao = RegistryDao(self.engine) | random_line_split |
opera.d.ts | import * as webdriver from "./index";
import * as remote from "./remote";
declare namespace opera {
/**
* Creates {@link remote.DriverService} instances that manages an
* [OperaDriver](https://github.com/operasoftware/operachromiumdriver)
* server in a child process.
*/
class ServiceBuilder... | * @param {capabilities.ProxyConfig} proxy The proxy configuration to use.
* @return {!Options} A self reference.
*/
setProxy(proxy: webdriver.ProxyConfig): Options;
/**
* Converts this options instance to a {@link capabilities.Capabilities}
* object.
... | random_line_split | |
opera.d.ts | import * as webdriver from "./index";
import * as remote from "./remote";
declare namespace opera {
/**
* Creates {@link remote.DriverService} instances that manages an
* [OperaDriver](https://github.com/operasoftware/operachromiumdriver)
* server in a child process.
*/
class | {
/**
* @param {string=} opt_exe Path to the server executable to use. If omitted,
* the builder will attempt to locate the operadriver on the current
* PATH.
* @throws {Error} If provided executable does not exist, or the operadriver
* cannot be found o... | ServiceBuilder | identifier_name |
OLA_nl_NL.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="nl_NL">
<context> | <location filename="configureolaio.ui" line="14"/>
<source>Configure OLA I/O</source>
<translation>Configureer OLA I/O</translation>
</message>
<message>
<location filename="configureolaio.ui" line="21"/>
<source>Output</source>
<translation>Output</translation>
... | <name>ConfigureOlaIO</name>
<message> | random_line_split |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub ... | let mp3_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()};
assert_eq!(read(Path::new("test/sample.mp3")).unwrap(), mp3_sample_tag);
assert_eq!(read(Path::new("test/sample.ogg")).unwrap(), sample_tags);
assert_eq!(read(Path::new("test/sample.flac")).unwrap(), flac_sample_tag);
} | year: Some(2016),
};
let flac_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()}; | random_line_split |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub ... | (path: &Path) -> Result<SongTags> {
let tag = metaflac::Tag::read_from_path(path)?;
let vorbis = tag.vorbis_comments().ok_or("Missing Vorbis comments")?;
let disc_number = vorbis
.get("DISCNUMBER")
.and_then(|d| d[0].parse::<u32>().ok());
let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok());
le... | read_flac | identifier_name |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub ... |
fn read_ape(path: &Path) -> Result<SongTags> {
let tag = ape::read(path)?;
let artist = tag.item("Artist").and_then(read_ape_string);
let album = tag.item("Album").and_then(read_ape_string);
let album_artist = tag.item("Album artist").and_then(read_ape_string);
let title = tag.item("Title").and_then(read_ape_str... | {
match item.value {
ape::ItemValue::Text(ref s) => {
let format = Regex::new(r#"^\d+"#).unwrap();
if let Some(m) = format.find(s) {
s[m.start()..m.end()].parse().ok()
} else {
None
}
}
_ => None,
}
} | identifier_body |
urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
import views
urlpatterns = patterns('',
url(r'^pis', views.pis),
url(r'^words', views.words, { 'titles': False }),
url(r'^p... | url(r'^$', views.index, name = 'index'),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) | random_line_split | |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUA... | {
app_from_crate!()
.arg(
Arg::with_name("zmq_uri")
.short("z")
.long("zmq")
.takes_value(true)
.value_name("URI")
.required(true)
.help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
.long("mysql")
... | identifier_body | |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUA... | <'a, 'b>() -> App<'a, 'b> {
app_from_crate!()
.arg(
Arg::with_name("zmq_uri")
.short("z")
.long("zmq")
.takes_value(true)
.value_name("URI")
.required(true)
.help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
... | build | identifier_name |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUA... | .help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
.long("mysql")
.takes_value(true)
.value_name("URI")
.required(true)
.help("MySQL destination server URI"),
)
.arg(
Arg::with_name("retry_interval")
... | .value_name("URI")
.required(true) | random_line_split |
example-repositories.js | export const EXAMPLE_REPOSITORIES = {
clock: { repo: 'https://github.com/meteor/clock' },
leaderboard: { repo: 'https://github.com/meteor/leaderboard' },
localmarket: { repo: 'https://github.com/meteor/localmarket' },
'simple-todos': { repo: 'https://github.com/meteor/simple-todos' },
'simple-todos-react': {
... | }
}; | },
'angular2-boilerplate': {
repo: 'https://github.com/bsliran/angular2-meteor-base' | random_line_split |
jvmcfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# 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
# th... | (self):
values = [
self.get_heap_size(),
self.get_heap_dump(),
self.get_perm_gen(),
]
if any([x.startswith("-XX:MaxPermSize") for x in values]):
values.append("-XX:+IgnoreUnrecognizedVMOptions")
values += self.get_append()
return [x... | get_memory_settings | identifier_name |
jvmcfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# 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
# th... | Uses the results of the default settings of
calculate_heap_size() as an argument to
get_heap_size(), in other words some percent
of the active memory.
"""
sz = self.calculate_heap_size()
return super(PercentStrategy, self).get_heap_size(sz)
def get_percent(se... | self.defaults = dict(self.PERCENT_DEFAULTS)
self.use_active = True
def get_heap_size(self):
""" | random_line_split |
jvmcfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# 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
# th... |
def get_heap_dump(self):
hd = self.settings.heap_dump
if hd == "off":
return ""
elif hd in ("on", "cwd", "tmp"):
return "-XX:+HeapDumpOnOutOfMemoryError"
def get_perm_gen(self):
pg = self.settings.perm_gen
if str(pg).startswith("-XX"):
... | if sz is None or self.settings.was_set("heap_size"):
sz = self.settings.heap_size
if str(sz).startswith("-X"):
return sz
else:
rv = "-Xmx%s" % sz
if rv[-1].lower() not in ("b", "k", "m", "g"):
rv = "%sm" % rv
return rv | identifier_body |
jvmcfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
# 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
# th... |
rv = defaultdict(list)
m = config.as_map()
loop = (("blitz", blitz), ("indexer", indexer),
("pixeldata", pixeldata), ("repository", repository))
for name, StrategyType in loop:
if name not in options:
raise Exception(
"Cannot find %s option. Make sure t... | for server in template.findall("server"):
for option in server.findall("option"):
o = option.text
if o.startswith("MEMORY:"):
options[o[7:]] = (server, option)
for props in server.findall("properties"):
for prop in props.findall... | conditional_block |
stdio.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 ... |
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDOUT_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
impl Stderr {
pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
pub fn write(&self, data: &[u8]) -> io::Re... | { Ok(Stdout(())) } | identifier_body |
stdio.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 ... | (());
impl Stdin {
pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDIN_FILENO);
let ret = fd.read(data);
fd.into_raw();
return ret;
}
}
impl Stdout {
pub fn new() -> io::Resul... | Stderr | identifier_name |
stdio.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. | // except according to those terms.
#[cfg(stage0)]
use prelude::v1::*;
use io;
use libc;
use sys::fd::FileDesc;
pub struct Stdin(());
pub struct Stdout(());
pub struct Stderr(());
impl Stdin {
pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
... | //
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
app.ts | /// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.onkey.d.ts"/>
module SandboxApp {
var imagesrc = "";
var PasteImageInput: IBobrilComponent = {
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.element = element;
},
onKeyDo... | ev.msConvertURL(file, "base64", url);
}
imagesrc = url;
b.invalidate();
} // for
});
}
};
b.init(() => {
b.invalidate();
return <IBobrilNode[]>[
{ tag: "h1", child... |
if (ev.convertURL) { // Use standard if available.
ev.convertURL(file, "base64", url);
} else { | random_line_split |
app.ts | /// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.onkey.d.ts"/>
module SandboxApp {
var imagesrc = "";
var PasteImageInput: IBobrilComponent = {
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.element = element;
},
onKeyDo... | ,
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.selfelement = element;
element.addEventListener("paste", (ev: any) => {
var cbData: any;
if (ev.clipboardData) {
cbData = ev.clipboardData;
} else if (... | {
var el = <HTMLElement>ctx.selfelement;
var imgs = el.getElementsByTagName("img");
if (imgs.length > 0) {
imagesrc = imgs.item(0).getAttribute("src");
b.invalidate();
}
el.innerHTML = "\u00a0";
if (k.ctrl || k.meta)... | identifier_body |
app.ts | /// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.onkey.d.ts"/>
module SandboxApp {
var imagesrc = "";
var PasteImageInput: IBobrilComponent = {
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.element = element;
},
onKeyDo... | (ctx: any, k: IKeyDownUpEvent): boolean {
var el = <HTMLElement>ctx.selfelement;
var imgs = el.getElementsByTagName("img");
if (imgs.length > 0) {
imagesrc = imgs.item(0).getAttribute("src");
b.invalidate();
}
el.innerHTML = "\u... | onKeyUp | identifier_name |
app.ts | /// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.onkey.d.ts"/>
module SandboxApp {
var imagesrc = "";
var PasteImageInput: IBobrilComponent = {
postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
ctx.element = element;
},
onKeyDo... | else if ((<any>window).clipboardData) {
cbData = (<any>window).clipboardData;
}
if (cbData.items && cbData.items.length > 0) {
var blob = cbData.items[0].getAsFile();
var reader = new FileReader();
reader.on... | {
cbData = ev.clipboardData;
} | conditional_block |
init.js | (function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
f... |
// Set checkbox on forms.html to indeterminate
var indeterminateCheckbox = document.getElementById('indeterminate-checkbox');
if (indeterminateCheckbox !== null)
indeterminateCheckbox.indeterminate = true;
// Pushpin Demo Init
if ($('.pushpin-demo-nav').length) {
$('.pushpin-... | }
}
if (is_touch_device()) {
$('#nav-mobile').css({ overflow: 'auto'});
}
| random_line_split |
init.js | (function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
f... | () {
if (!$bsa.find('#carbonads').length) {
$timesToCheck -= 1;
if ($timesToCheck >= 0) {
setTimeout(checkForChanges, 500);
}
else {
var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementByI... | checkForChanges | identifier_name |
init.js | (function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
f... |
checkForChanges();
// BuySellAds Demos close button.
$('.buysellads.buysellads-demo .close').on('click', function() {
$(this).parent().remove();
});
// Github Latest Commit
if ($('.github-commit').length) { // Checks if widget div exists (Index only)
$.ajax({
... | {
if (!$bsa.find('#carbonads').length) {
$timesToCheck -= 1;
if ($timesToCheck >= 0) {
setTimeout(checkForChanges, 500);
}
else {
var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementById(\... | identifier_body |
init.js | (function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
f... |
// Set checkbox on forms.html to indeterminate
var indeterminateCheckbox = document.getElementById('indeterminate-checkbox');
if (indeterminateCheckbox !== null)
indeterminateCheckbox.indeterminate = true;
// Pushpin Demo Init
if ($('.pushpin-demo-nav').length) {
$('.pushpi... | {
$('#nav-mobile').css({ overflow: 'auto'});
} | conditional_block |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);... |
}
| {
cttz32_test!(0x00000001, 0);
cttz32_test!(0x00000002, 1);
cttz32_test!(0x00000004, 2);
cttz32_test!(0x00000008, 3);
cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6);
cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0x00... | identifier_body |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);... | () {
cttz32_test!(0x00000001, 0);
cttz32_test!(0x00000002, 1);
cttz32_test!(0x00000004, 2);
cttz32_test!(0x00000008, 3);
cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6);
cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0... | cttz32_test1 | identifier_name |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);... | cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0x00000400, 10);
cttz32_test!(0x00000800, 11);
cttz32_test!(0x00001000, 12);
cttz32_test!(0x00002000, 13);
cttz32_test!(0x00004000, 14);
cttz32_test!(0x00008000, 15);
cttz32_test!(0x00010000, 16);
cttz32_test!... | cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6); | random_line_split |
afos_dump.py | """AFOS Database Workflow."""
# 3rd Party
from twisted.internet import reactor
from txyam.client import YamClient
from pyiem.util import LOG
from pyiem.nws import product
# Local
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
DBPOOL = get_database("afos", cp_max=5)
MEMCA... |
txn.execute(
"DELETE from products where pil = %s and source = %s and "
f"entered = %s {bbb}",
args,
)
LOG.info("Removed %s rows for %s", txn.rowcount, nws.get_product_id())
txn.execute(
"INSERT into products (pil, data, entered, "
"sourc... | bbb = " and bbb = %s "
args.append(nws.bbb) | conditional_block |
afos_dump.py | """AFOS Database Workflow."""
# 3rd Party
from twisted.internet import reactor
from txyam.client import YamClient
from pyiem.util import LOG
from pyiem.nws import product
# Local
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
DBPOOL = get_database("afos", cp_max=5)
MEMCA... | ():
"""Fire up our workflow."""
common.main(with_jabber=False)
bridge(process_data)
reactor.run() # @UndefinedVariable
# See how we are called.
if __name__ == "__main__":
main()
| main | identifier_name |
afos_dump.py | """AFOS Database Workflow."""
# 3rd Party
from twisted.internet import reactor
from txyam.client import YamClient
from pyiem.util import LOG
from pyiem.nws import product
# Local
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
DBPOOL = get_database("afos", cp_max=5)
MEMCA... | )
if nws.afos[:3] in MEMCACHE_EXCLUDE:
return None
return nws
def main():
"""Fire up our workflow."""
common.main(with_jabber=False)
bridge(process_data)
reactor.run() # @UndefinedVariable
# See how we are called.
if __name__ == "__main__":
main() | "source, wmo, bbb) VALUES(%s, %s, %s, %s, %s, %s)",
(nws.afos.strip(), nws.text, nws.valid, nws.source, nws.wmo, nws.bbb), | random_line_split |
afos_dump.py | """AFOS Database Workflow."""
# 3rd Party
from twisted.internet import reactor
from txyam.client import YamClient
from pyiem.util import LOG
from pyiem.nws import product
# Local
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
DBPOOL = get_database("afos", cp_max=5)
MEMCA... |
# See how we are called.
if __name__ == "__main__":
main()
| """Fire up our workflow."""
common.main(with_jabber=False)
bridge(process_data)
reactor.run() # @UndefinedVariable | identifier_body |
people-v3-qunit-test.js | import { test, module } from 'qunit';
import { setupTest } from 'ember-qunit';
import { setupPact, given, interaction } from 'ember-cli-pact';
import { run } from '@ember/runloop';
module('Pact | People', function(hooks) {
setupTest(hooks); |
test('listing people', async function(assert) {
given('a department exists', { id: '1', name: 'People' });
given('a person exists', { id: '1', name: 'Alice', departmentId: '1' });
given('a person exists', { id: '2', name: 'Bob', departmentId: '1' });
let people = await interaction(() => this.store()... | setupPact(hooks); | random_line_split |
classie.js | /*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
*/
/*jshint browser: true, strict: true, undef: true */
( function( window ) {
'use strict';
... |
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c... | {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
} | conditional_block |
classie.js | /*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
*/
/*jshint browser: true, strict: true, undef: true */
( function( window ) {
'use strict';
... |
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( e... | {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
} | identifier_body |
classie.js | /*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
*/
/*jshint browser: true, strict: true, undef: true */
( function( window ) {
'use strict';
... | // full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass
};
})( window ); |
window.classie = { | random_line_split |
classie.js | /*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
*/
/*jshint browser: true, strict: true, undef: true */
( function( window ) {
'use strict';
... | ( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c... | classReg | identifier_name |
interface_config.js | /* eslint-disable no-unused-vars, no-var, max-len */
var interfaceConfig = {
// TO FIX: this needs to be handled from SASS variables. There are some
// methods allowing to use variables both in css and js.
DEFAULT_BACKGROUND: '#474747',
/**
* In case the desktop sharing is disabled through the co... | * enabled. Also, the "profile" button will not display for user's with a
* jwt.
*/
TOOLBAR_BUTTONS: [
'microphone', 'camera', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup',
'profile', 'info', 'chat', 'recording', 'livestreaming', 'etherpad',
'sharedvideo', 'settings',... | * which also require being a moderator and some values in config.js to be | random_line_split |
BasePlayer.py |
import numpy as np
import cv2
from skimage.morphology import closing, erosion, opening
from pyKinectTools.algs.BackgroundSubtraction import *
class BasePlayer(object):
depthIm = None
colorIm = None
users = None
backgroundModel = None
foregroundMask = None
mask = None
prevcolorIm = None
def | (self, base_dir='./', get_depth=True, get_color=False,
get_skeleton=False, bg_subtraction=False, fill_images=False,
background_model=None, background_param=None):
self.base_dir = base_dir
self.deviceID = '[]'
if bg_subtraction and background_model is None:
raise Exception, "Must specify background_mo... | __init__ | identifier_name |
BasePlayer.py |
import numpy as np
import cv2
from skimage.morphology import closing, erosion, opening
from pyKinectTools.algs.BackgroundSubtraction import *
class BasePlayer(object):
depthIm = None
colorIm = None
users = None
backgroundModel = None
foregroundMask = None
mask = None
prevcolorIm = None
def __init__(self, b... |
self.bgSubtraction = StaticModel(depthIm=param)
elif bg_type == 'mean':
self.bgSubtraction = MeanModel(depthIm=self.depthIm)
elif bg_type == 'median':
self.bgSubtraction = MedianModel(depthIm=self.depthIm)
elif bg_type == 'adaptive_mog':
self.bgSubtraction = AdaptiveMixtureOfGaussians(self.depthIm, m... | param = self.depthIm | conditional_block |
BasePlayer.py | import numpy as np
import cv2
from skimage.morphology import closing, erosion, opening
from pyKinectTools.algs.BackgroundSubtraction import *
class BasePlayer(object):
depthIm = None
colorIm = None
users = None
backgroundModel = None
foregroundMask = None
mask = None
prevcolorIm = None
def __init__(self, ba... | elif bg_type == 'static':
if param==None:
param = self.depthIm
self.bgSubtraction = StaticModel(depthIm=param)
elif bg_type == 'mean':
self.bgSubtraction = MeanModel(depthIm=self.depthIm)
elif bg_type == 'median':
self.bgSubtraction = MedianModel(depthIm=self.depthIm)
elif bg_type == 'adaptive_m... | random_line_split | |
BasePlayer.py |
import numpy as np
import cv2
from skimage.morphology import closing, erosion, opening
from pyKinectTools.algs.BackgroundSubtraction import *
class BasePlayer(object):
depthIm = None
colorIm = None
users = None
backgroundModel = None
foregroundMask = None
mask = None
prevcolorIm = None
def __init__(self, b... |
def run(self):
pass
| if show_skel:
plotUsers(self.depthIm, self.users)
if self.get_depth and depth:
cv2.imshow("Depth"+self.deviceID, (self.depthIm-1000)/float(self.depthIm.max()))
# cv2.putText(self.deviceID, (5,220), (255,255,255), size=15)
# vv.imshow("Depth", self.depthIm/6000.)
if self.get_color and color:
cv2.ims... | identifier_body |
cs.py | # $Id: cs.py 7119 2011-09-02 13:00:23Z milde $
# Author: Marek Blaha <mb@dat.cz>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each lan... | u'line-block (translation required)': 'line-block',
u'parsed-literal (translation required)': 'parsed-literal',
u'odd\u00EDl': 'rubric',
u'moto': 'epigraph',
u'highlights (translation required)': 'highlights',
u'pull-quote (translation required)': 'pull-quote',
u'compound (tran... | u'tip (translation required)': 'tip',
u'varov\u00E1n\u00ED': 'warning',
u'admonition (translation required)': 'admonition',
u'sidebar (translation required)': 'sidebar',
u't\u00E9ma': 'topic', | random_line_split |
recipes.py | from collections import defaultdict, namedtuple
from minecraft_data.v1_8 import recipes as raw_recipes
RecipeItem = namedtuple('RecipeItem', 'id meta amount')
class Recipe(object):
def __init__(self, raw):
self.result = reformat_item(raw['result'], None)
if 'ingredients' in raw:
sel... | recipe = Recipe(raw)
if meta is None or meta == recipe.result.meta:
yield recipe
def get_any_recipe(item, meta=None):
# TODO return small recipes if present
for matching in iter_recipes(item, meta):
return matching
return None | else:
for raw in recipes_for_item: | random_line_split |
recipes.py | from collections import defaultdict, namedtuple
from minecraft_data.v1_8 import recipes as raw_recipes
RecipeItem = namedtuple('RecipeItem', 'id meta amount')
class Recipe(object):
def __init__(self, raw):
self.result = reformat_item(raw['result'], None)
if 'ingredients' in raw:
sel... |
def reformat_shape(shape):
return [[reformat_item(item, None) for item in row] for row in shape]
def iter_recipes(item_id, meta=None):
item_id = str(item_id)
meta = meta and int(meta)
try:
recipes_for_item = raw_recipes[item_id]
except KeyError:
return # no recipe found, do not... | if isinstance(raw, dict):
raw = raw.copy() # do not modify arg
if 'metadata' not in raw:
raw['metadata'] = default_meta
if 'count' not in raw:
raw['count'] = 1
return RecipeItem(raw['id'], raw['metadata'], raw['count'])
elif isinstance(raw, list):
ret... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.