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 |
|---|---|---|---|---|
annotate_old_bird_calls.py | """
Annotates Old Bird call detections in the BirdVox-70k archive.
The annotations classify clips detected by the Old Bird Tseep and Thrush
detectors according to the archive's ground truth call clips.
This script must be run from the archive directory.
"""
from django.db.models import F
from django.db.utils import... | ():
center_index_annotation_info = \
AnnotationInfo.objects.get(name=CENTER_INDEX_ANNOTATION_NAME)
center_freq_annotation_info = \
AnnotationInfo.objects.get(name=CENTER_FREQ_ANNOTATION_NAME)
classification_annotation_info = \
AnnotationInfo.objects.get(name=CLASSIFICATION_ANNOT... | annotate_old_bird_calls | identifier_name |
annotate_old_bird_calls.py | """
Annotates Old Bird call detections in the BirdVox-70k archive.
The annotations classify clips detected by the Old Bird Tseep and Thrush
detectors according to the archive's ground truth call clips.
This script must be run from the archive directory.
"""
from django.db.models import F
from django.db.utils import... |
def sum_counts(df, detector):
if detector != 'All':
df = df.loc[df['Detector'] == detector]
return [
detector,
df['Ground Truth Calls'].sum(),
df['Old Bird Calls'].sum(),
df['Old Bird Clips'].sum()]
def add_precision_recall_f1(df):
p = df['O... | data = [
sum_counts(df, 'Tseep'),
sum_counts(df, 'Thrush'),
sum_counts(df, 'All')
]
columns = [
'Detector', 'Ground Truth Calls', 'Old Bird Calls', 'Old Bird Clips']
return pd.DataFrame(data, columns=columns) | identifier_body |
annotate_old_bird_calls.py | """
Annotates Old Bird call detections in the BirdVox-70k archive.
The annotations classify clips detected by the Old Bird Tseep and Thrush
detectors according to the archive's ground truth call clips.
This script must be run from the archive directory.
"""
from django.db.models import F
from django.db.utils import... | main() | conditional_block | |
platformSettings.js | /*
Copyright (c) 2016 eyeOS
This file is part of Open365.
Open365 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, either version 3 of the
License, or (at your option) any later ver... | disableAnalytics: false,
forceDomain: true,
defaultDomain: "open365.io",
publicTenant: "cloud",
domainFromUrl: false,
domainFromUrlExceptions: "",
suggestDomain: true,
enableUserRegistration: true,
minBrowsersVersion: { "Chrome":30, "Firefox": 30 },
lastSettingsInFile: null // This line is to make sure that a... | lang: 'en',
theme:'open365',
cleanUrlParameters: false,
customTitle: false, | random_line_split |
htmlappletelement.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/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding::HTMLAppletElementMethods;
use d... | random_line_split | |
htmlappletelement.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/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codeg... |
}
impl HTMLAppletElementMethods for HTMLAppletElement {
// https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name
make_atomic_setter!(SetName, "name");
}
impl VirtualMethods for HTML... | {
let element = HTMLAppletElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap)
} | identifier_body |
htmlappletelement.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/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codeg... | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAppletElement> {
let element = HTMLAppletElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap)
}
}
impl HTMLApple... | new | identifier_name |
cflow_line_parser.py | __author__ = 'kevin'
import re
from attacksurfacemeter.loaders.base_line_parser import BaseLineParser
class CflowLineParser(BaseLineParser):
""""""
_instance = None
@staticmethod
def get_instance(cflow_line=None):
if CflowLineParser._instance is None:
CflowLineParser._instance =... |
def get_level(self, cflow_line=None):
self._load_if_new(cflow_line)
return self._level
| self._function_signature = match.group(1) | conditional_block |
cflow_line_parser.py | __author__ = 'kevin'
import re
from attacksurfacemeter.loaders.base_line_parser import BaseLineParser
class CflowLineParser(BaseLineParser):
""""""
_instance = None
@staticmethod
def get_instance(cflow_line=None):
if CflowLineParser._instance is None:
CflowLineParser._instance =... |
def get_level(self, cflow_line=None):
self._load_if_new(cflow_line)
return self._level
| self.__init__()
split_line = cflow_line.split(CflowLineParser.indent)
function_info = split_line[-1].strip()
self._level = len(split_line) - 1
function_name = re.search(r"(\w+\(\))", function_info).group(0)
self._function_name = function_name[:function_name.index('(')]
... | identifier_body |
cflow_line_parser.py | __author__ = 'kevin'
import re
from attacksurfacemeter.loaders.base_line_parser import BaseLineParser
class | (BaseLineParser):
""""""
_instance = None
@staticmethod
def get_instance(cflow_line=None):
if CflowLineParser._instance is None:
CflowLineParser._instance = CflowLineParser()
CflowLineParser._instance.load(cflow_line)
return CflowLineParser._instance
indent = ... | CflowLineParser | identifier_name |
cflow_line_parser.py | __author__ = 'kevin'
import re
from attacksurfacemeter.loaders.base_line_parser import BaseLineParser
class CflowLineParser(BaseLineParser):
""""""
_instance = None
@staticmethod
def get_instance(cflow_line=None):
if CflowLineParser._instance is None:
CflowLineParser._instance =... |
def get_level(self, cflow_line=None):
self._load_if_new(cflow_line)
return self._level | self._function_name = function_name[:function_name.index('(')]
match = re.search(r"(?:at\s)(\..*)(?::\d+>)", function_info)
if match:
self._function_signature = match.group(1) | random_line_split |
gulpfile.js | ('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var pl... |
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `di... | var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
| random_line_split |
gulpfile.js | require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');... |
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() ... | {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
} | conditional_block |
regions-enum-not-wf.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // except according to those terms.
// Various examples of structs whose fields are not well-formed.
#![allow(dead_code)]
enum Ref1<'a, T> {
Ref1Variant1(&'a T) //~ ERROR the parameter type `T` may not live long enough
}
enum Ref2<'a, T> {
Ref2Variant1,
Ref2Variant2(isize, &'a T), //~ ERROR the paramete... | // option. This file may not be copied, modified, or distributed | random_line_split |
regions-enum-not-wf.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a, T> {
Ref1Variant1(&'a T) //~ ERROR the parameter type `T` may not live long enough
}
enum Ref2<'a, T> {
Ref2Variant1,
Ref2Variant2(isize, &'a T), //~ ERROR the parameter type `T` may not live long enough
}
enum RefOk<'a, T:'a> {
RefOkVariant1(&'a T)
}
enum RefIndirect<'a, T> {
RefIndirectVar... | Ref1 | identifier_name |
common.rs | = buf.into_inner().into();
self.sent.push(raw);
Ok(())
}
}
/// A mock `ReceiveFrame` implementation that simply serves the frames from a `Vec`.
pub struct MockReceiveFrame<'a> {
pub recv_list: Vec<HttpFrame<'a>>,
}
impl<'a> MockReceiveFrame<'a> {
pub fn new(recv_list: Vec<HttpFrame<'a>>) ... | data | impl Session for TestSession {
fn new_data_chunk(&mut self,
_: StreamId, | random_line_split |
common.rs | mut self, buf: &[u8]) -> io::Result<usize> {
if self.closed.get() {
Err(io::Error::new(io::ErrorKind::Other, "Closed"))
} else {
self.writer.borrow_mut().write(buf)
}
}
fn flush(&mut self) -> io::Result<()> {
self.writer.borrow_mut().flush()
}
}
impl... | {
self.state = state;
} | identifier_body | |
common.rs | = buf.into_inner().into();
self.sent.push(raw);
Ok(())
}
}
/// A mock `ReceiveFrame` implementation that simply serves the frames from a `Vec`.
pub struct MockReceiveFrame<'a> {
pub recv_list: Vec<HttpFrame<'a>>,
}
impl<'a> MockReceiveFrame<'a> {
pub fn new(recv_list: Vec<HttpFrame<'a>>) ... | {
pub silent: bool,
/// List of expected headers -- in the order that they are expected
pub headers: Vec<Vec<OwnedHeader>>,
/// List of expected data chunks -- in the order that they are expected
pub chunks: Vec<Vec<u8>>,
/// The current number of header calls.
pub curr_header: usize,
/... | TestSession | identifier_name |
index-3.js | 13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["preced"]="27";
w["prefac"]="15";
w["prefix"]="15";
w["previous"]="0";
w["print"]="25";
w["prior"]="0";
w["privileg"]="16";
w["problem"]="25";
w["proceed"]="15";
w["product"]="7,19,27";
w["profil"]="0";
w["project_id"]="16,21";
w["prompt"]="15";
w["proper"]="7,25";
w["pr... | w["recommend"]="7,19,27";
w["record"]="3,16,18";
w["recv"]="7";
w["red"]="3,6,10,11,16,18,22";
w["redund"]="27";
w["refer"]="20,27";
w["registr"]="12,14";
w["remind"]="15";
w["remot"]="27";
w["remov"]="0";
w["replac"]="19,24";
w["repli"]="7,25";
w["replic"]="1";
w["replication_factor"]="1";
w["repo"]="22";
w["repo_key"... | w["rack"]="25";
w["rack1"]="25";
w["random"]="3";
w["reboot"]="22,25";
w["receiv"]="7"; | random_line_split |
process.py | # OCFS2Console - GUI frontend for OCFS2 management and debugging
# Copyright (C) 2002, 2005 Oracle. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of th... |
self.spin_now = spin_now
self.pipe = popen2.Popen4(self.command)
def reap(self):
self.success = False
self.killed = False
self.count = TIMEOUT // INTERVAL
self.threshold = self.count - INTERVAL * 10
self.dialog = None
if self.spin_now:
... | self.title = title
self.desc = desc
self.parent = parent | random_line_split |
process.py | # OCFS2Console - GUI frontend for OCFS2 management and debugging
# Copyright (C) 2002, 2005 Oracle. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of th... |
if self.dialog:
self.pbar.pulse()
return True
def kill(self):
self.success = False
self.killed = True
os.kill(self.pipe.pid, 15)
gobject.timeout_add(INTERVAL * 5, self.kill_timeout)
gtk.main_quit()
def kill_timeout(self):
if self... | self.make_progress_box() | conditional_block |
process.py | # OCFS2Console - GUI frontend for OCFS2 management and debugging
# Copyright (C) 2002, 2005 Oracle. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of th... |
self.dialog.connect('delete-event', ignore)
self.dialog.set_transient_for(self.parent)
vbox = gtk.VBox()
set_props(vbox, spacing=0,
homogeneous=False,
border_width=4,
parent=self.dialog)
label = gtk.Label... | return True | identifier_body |
process.py | # OCFS2Console - GUI frontend for OCFS2 management and debugging
# Copyright (C) 2002, 2005 Oracle. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of th... | (self, command, title, desc, parent=None, spin_now=False):
if isinstance(command, basestring):
if len(command.split(None, 1)) < 2:
command = (command,)
self.command = command
self.title = title
self.desc = desc
self.parent = parent
self.spi... | __init__ | identifier_name |
util.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | {
match s.starts_with("0x") {
true => s[2..].from_hex().unwrap(),
false => From::from(s)
}
} | identifier_body | |
util.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (s: &str) -> Vec<u8> {
match s.starts_with("0x") {
true => s[2..].from_hex().unwrap(),
false => From::from(s)
}
}
| hex_or_string | identifier_name |
util.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use... | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful, | random_line_split |
entitiesReducer.ts | import {IFluxAction} from 'Core/API'
import {
ENTITIES_UPDATE
} from './EntitiesActionTypes'
import {
EActionTypes
} from 'API'
export interface IEntitiesState {
[name: string]: {[id: string]: any}
}
const ACTION_HANDLERS = {
[ENTITIES_UPDATE]: (state: IEntitiesState, action: IFluxAction<IEntitiesState>) ... | state[name][id] = Object.assign(
{},
state[name][id],
entities[name][id],
{isCompact: action['isCompact'] ? state[name][id] && state[name][id].isCompact : false}
)
})
})
// console.log('entities update state', state)
return state
}
}
const ini... | state[name] = {}
}
Object.keys(entities[name]).forEach(id => { | random_line_split |
entitiesReducer.ts | import {IFluxAction} from 'Core/API'
import {
ENTITIES_UPDATE
} from './EntitiesActionTypes'
import {
EActionTypes
} from 'API'
export interface IEntitiesState {
[name: string]: {[id: string]: any}
}
const ACTION_HANDLERS = {
[ENTITIES_UPDATE]: (state: IEntitiesState, action: IFluxAction<IEntitiesState>) ... | (state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
} | entitiesReducer | identifier_name |
entitiesReducer.ts | import {IFluxAction} from 'Core/API'
import {
ENTITIES_UPDATE
} from './EntitiesActionTypes'
import {
EActionTypes
} from 'API'
export interface IEntitiesState {
[name: string]: {[id: string]: any}
}
const ACTION_HANDLERS = {
[ENTITIES_UPDATE]: (state: IEntitiesState, action: IFluxAction<IEntitiesState>) ... | {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
} | identifier_body | |
entitiesReducer.ts | import {IFluxAction} from 'Core/API'
import {
ENTITIES_UPDATE
} from './EntitiesActionTypes'
import {
EActionTypes
} from 'API'
export interface IEntitiesState {
[name: string]: {[id: string]: any}
}
const ACTION_HANDLERS = {
[ENTITIES_UPDATE]: (state: IEntitiesState, action: IFluxAction<IEntitiesState>) ... |
Object.keys(entities[name]).forEach(id => {
state[name][id] = Object.assign(
{},
state[name][id],
entities[name][id],
{isCompact: action['isCompact'] ? state[name][id] && state[name][id].isCompact : false}
)
})
})
// console.log('entities upd... | {
state[name] = {}
} | conditional_block |
_RevenueStat.js | var _ = require('underscore');
var $ = require('jquery'),
Backbone = require('backbone'),
revenueTpl = require('../templates/_entityRevenue.tpl'),
loadingTpl = require('../templates/__loading.tpl');
var config = require('../conf');
Backbone.$ = $;
exports = module.exports = Backbone.View.extend({
el: '#statVi... | this.$el.html(this.loadingTemplate());
} else {
this.$el.html(this.template());
}
return this;
},
}); | random_line_split | |
_RevenueStat.js | var _ = require('underscore');
var $ = require('jquery'),
Backbone = require('backbone'),
revenueTpl = require('../templates/_entityRevenue.tpl'),
loadingTpl = require('../templates/__loading.tpl');
var config = require('../conf');
Backbone.$ = $;
exports = module.exports = Backbone.View.extend({
el: '#statVi... |
return this;
},
}); | {
this.$el.html(this.template());
} | conditional_block |
document.py |
from .fields import EmbeddedField
log = logging.getLogger('yamo')
class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return self.fget(owner_cls)
class MongoOperationMixin(object):
""" Mongodb raw operations """
@clas... | _db | identifier_name | |
document.py |
from .errors import ConfigError, ArgumentError
from .metatype import DocumentType, EmbeddedDocumentType
from .fields import EmbeddedField
log = logging.getLogger('yamo')
class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return... |
else:
names.add(key)
return names
@classmethod
def prepare(cls):
cls.ensure_indexes()
cls.ensure_shards()
@classmethod
def ensure_indexes(cls):
allowed_keys = set(['name', 'unique', 'background', 'sparse',
... | names.add(key[0]) | conditional_block |
document.py |
from .errors import ConfigError, ArgumentError
from .metatype import DocumentType, EmbeddedDocumentType
from .fields import EmbeddedField
log = logging.getLogger('yamo')
class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return... |
class MetaMixin(object):
""" helper methods for "Meta" info """
@classproperty
def unique_fields(cls):
names = set()
for idx in cls.Meta._indexes or []:
if idx.kwargs.get('unique'):
for key in idx.keys:
if isinstance(key, tuple):
... | def validate(self):
for name, field in self._fields.items():
if name in self._data:
value = field.to_python(self._data[name])
field.validate(value)
def to_dict(self):
d = {}
for name, field in self._fields.items():
value = field.to_pyt... | identifier_body |
document.py |
from .errors import ConfigError, ArgumentError
from .metatype import DocumentType, EmbeddedDocumentType
from .fields import EmbeddedField
log = logging.getLogger('yamo')
class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return... | def upsert(self, null=False):
""" Insert or Update Document
:param null: whether update null values
Wisely select unique field values as filter,
Update with upsert=True
"""
self._pre_save()
self.validate()
filter_ = self._upsert_filter()
if f... | def update(self, update):
""" Update self """
self._coll.update_one({'_id': self._data['_id']},
update)
| random_line_split |
index.d.ts | *
* @param a
* @param b
* @param c
* @param colorSpace The color space to use. Defaults to "rgb".
* @return the color object.
*/
(a: number, b: number, c: number, colorSpace?: keyof ColorSpaces): Color;
(a: number, b: number, c: number, d: number, ... | */
distance(color1: string | Color, color2: string | Color, colorSpace?: keyof ColorSpaces): Color;
/**
* Computes color difference {@link https://en.wikipedia.org/wiki/Color_difference#CMC_l:c_.281984.29} as
* developed by the Colour Measurement Committee of the Society of D... | random_line_split | |
main.js | // import third-party CSS
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import 'font-awesome/css/font-awesome.min.css';
import 'react-flex/index.css';
// import our own main CSS
import 'src/views/styles/styles.scss';
// import JS
// import 'bootstrap'; // bootstrap JS... | <LoadOverlay message="logging in..." className="color-lightred" />,
rootElement
);
// Wait until after authentication has finished before rendering the root
getFirebase().auth().onAuthStateChanged(function onAuthStateChanged(authData) {
// done! Let's kick this thing into gear!
// try {
ReactDOM.render(
... | });
}
// show a message while logging in
ReactDOM.render( | random_line_split |
main.js | // import third-party CSS
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import 'font-awesome/css/font-awesome.min.css';
import 'react-flex/index.css';
// import our own main CSS
import 'src/views/styles/styles.scss';
// import JS
// import 'bootstrap'; // bootstrap JS... |
// show a message while logging in
ReactDOM.render(
<LoadOverlay message="logging in..." className="color-lightred" />,
rootElement
);
// Wait until after authentication has finished before rendering the root
getFirebase().auth().onAuthStateChanged(function onAuthStateChanged(authData) {
// done! Let's kick t... | {
module.hot.accept('./views/root', () => {
render(require('./views/root').default);
});
} | conditional_block |
plog.py | # !/usr/bin/env python
from socket import socket, AF_INET, SOCK_DGRAM, error as socketError
from select import select
from json import loads
from numbers import Number
from checks import AgentCheck
class PlogCheck(AgentCheck):
def check(self, instance):
# read config
tags = instance.get('tags', ... | check.check(instance)
sleep(1)
check.check(instance)
# We don't support events yet
# pp.pprint(check.get_events())
pp.pprint(check.get_metrics()) | conditional_block | |
plog.py | # !/usr/bin/env python
from socket import socket, AF_INET, SOCK_DGRAM, error as socketError
from select import select
from json import loads
from numbers import Number
from checks import AgentCheck
class PlogCheck(AgentCheck):
def check(self, instance):
# read config
tags = instance.get('tags', ... | rate('invalid_checksum',
sum(stats['v0_invalid_checksum']))
rate('invalid_fragments',
sum(sum(a) for a in stats['v0_invalid_fragments']))
rate('missing_fragments',
sum(sum(a) for a in stats['dropped_fragments']))
defragmenter = stats['defragmenter... | random_line_split | |
plog.py | # !/usr/bin/env python
from socket import socket, AF_INET, SOCK_DGRAM, error as socketError
from select import select
from json import loads
from numbers import Number
from checks import AgentCheck
class PlogCheck(AgentCheck):
def check(self, instance):
# read config
tags = instance.get('tags', ... |
def gauge(name, val):
self.gauge(prefix + name + suffix, val, tags=tags)
gauge('uptime',
stats['uptime'])
rate('udp_simple',
stats['udp_simple_messages'])
rate('udp_invalid_version',
stats['udp_invalid_version'])
rate('v0_in... | self.rate(prefix + name + suffix, val, tags=tags) | identifier_body |
plog.py | # !/usr/bin/env python
from socket import socket, AF_INET, SOCK_DGRAM, error as socketError
from select import select
from json import loads
from numbers import Number
from checks import AgentCheck
class PlogCheck(AgentCheck):
def check(self, instance):
# read config
tags = instance.get('tags', ... | (json):
if isinstance(json, Number):
return json
elif isinstance(json, list):
return sum(flatsum(o) for o in json)
else:
return 0
def feed_handler_metrics(path, json):
if isinstance(json, dict):
for ... | flatsum | identifier_name |
crc.js | /**
* Created by nbenes on 11/16/13.
*/
var $window = $(window)
var $body = $(document.body)
var navHeight = $('.navbar').outerHeight(true) + 10
$body.scrollspy({
target: '.crc-sidebar',
offset: navHeight
}) |
$window.on('load', function () {
$body.scrollspy('refresh')
})
$('.crc-container [href=#]').click(function (e) {
e.preventDefault()
})
// back to top
setTimeout(function () {
var $sideBar = $('.crc-sidebar')
$sideBar.affix({
offset: {
top: function () {
var offset... | random_line_split | |
8091001.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General... |
/*Author : Raz
*
* LMPQ Maze - Reactor - Spawn Monster
*/
function act(){
rm.spawnMonster(9400211, 2);
rm.spawnMonster(9400212, 2);
rm.mapMessage(5, "Some monsters are summoned.");
} |
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ | random_line_split |
8091001.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General... | (){
rm.spawnMonster(9400211, 2);
rm.spawnMonster(9400212, 2);
rm.mapMessage(5, "Some monsters are summoned.");
} | act | identifier_name |
8091001.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General... | {
rm.spawnMonster(9400211, 2);
rm.spawnMonster(9400212, 2);
rm.mapMessage(5, "Some monsters are summoned.");
} | identifier_body | |
calculate_numba.py | import os
import json
import numpy as np
try:
from numba.pycc import CC
cc = CC('calculate_numba')
except ImportError:
# Will use these as regular Python functions if numba is not present.
class CCSubstitute(object):
# Make a cc.export that doesn't do anything
def export(*args, **kwar... | cc.compile() | conditional_block | |
calculate_numba.py | import os
import json
import numpy as np
try:
from numba.pycc import CC
cc = CC('calculate_numba')
except ImportError:
# Will use these as regular Python functions if numba is not present.
class CCSubstitute(object):
# Make a cc.export that doesn't do anything
def | (*args, **kwargs):
def wrapper(func):
return func
return wrapper
cc = CCSubstitute()
@cc.export('ldn_recode_traj', 'i2[:,:](i2[:,:])')
def ldn_recode_traj(x):
# Recode trajectory into deg, stable, imp. Capture trends that are at least
# 95% significant.
#
#... | export | identifier_name |
calculate_numba.py | import os
import json
import numpy as np
try:
from numba.pycc import CC
cc = CC('calculate_numba')
except ImportError:
# Will use these as regular Python functions if numba is not present.
class CCSubstitute(object):
# Make a cc.export that doesn't do anything
def export(*args, **kwar... |
cc = CCSubstitute()
@cc.export('ldn_recode_traj', 'i2[:,:](i2[:,:])')
def ldn_recode_traj(x):
# Recode trajectory into deg, stable, imp. Capture trends that are at least
# 95% significant.
#
# Remember that traj is coded as:
# -3: 99% signif decline
# -2: 95% signif decline
# -1: 90%... | def wrapper(func):
return func
return wrapper | identifier_body |
calculate_numba.py | import os
import json
import numpy as np
try:
from numba.pycc import CC
cc = CC('calculate_numba')
except ImportError:
# Will use these as regular Python functions if numba is not present.
class CCSubstitute(object):
# Make a cc.export that doesn't do anything
def export(*args, **kwar... | # @cc.export('ldn_total_by_trans_merge', '(f4[:], i2[:], f4[:], i2[:])')
# def ldn_total_by_trans_merge(total1, trans1, total2, trans2):
# """Calculates a total table for an array"""
# # Combine past totals with these totals
# trans = np.unique(np.concatenate((trans1, trans2)))
# totals = np.zeros(trans... | vals = d[trans_a == trans[i]] * cell_areas[trans_a == trans[i]]
totals[i] += np.sum(vals)
return trans, totals
| random_line_split |
gfortran.py | """SCons.Tool.gfortran
Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran
2003 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
... | import fortran
def generate(env):
"""Add Builders and construction variables for gfortran to an
Environment."""
fortran.generate(env)
for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03']:
env['%s' % dialect] = 'gfortran'
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFOR... |
import SCons.Util
| random_line_split |
gfortran.py | """SCons.Tool.gfortran
Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran
2003 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
... | (env):
return env.Detect('gfortran')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| exists | identifier_name |
gfortran.py | """SCons.Tool.gfortran
Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran
2003 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
... |
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| return env.Detect('gfortran') | identifier_body |
gfortran.py | """SCons.Tool.gfortran
Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran
2003 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
... |
def exists(env):
return env.Detect('gfortran')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| env['%s' % dialect] = 'gfortran'
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect)
else:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect)
... | conditional_block |
.markdown-doctest-setup.js | 'use strict';
var Rx = require(__dirname);
var marbleTesting = require('./spec-js/helpers/marble-testing');
global.rxTestScheduler = new Rx.TestScheduler(marbleTesting.assertDeepEqual);
function it(callback) {
callback();
}
it.asDiagram = function asDiagram() {
return function (spec, callback) {
callback();... | someObservable: Rx.Observable.range(1, 10),
it: it
},
regexRequire: {
'rxjs/(.*)': function (_, moduleName) {
return require(__dirname + '/dist/package/' + moduleName);
}
},
babel: {
stage: 0
}
}; | random_line_split | |
.markdown-doctest-setup.js | 'use strict';
var Rx = require(__dirname);
var marbleTesting = require('./spec-js/helpers/marble-testing');
global.rxTestScheduler = new Rx.TestScheduler(marbleTesting.assertDeepEqual);
function | (callback) {
callback();
}
it.asDiagram = function asDiagram() {
return function (spec, callback) {
callback();
}
};
module.exports = {
require: {
'@reactivex/rxjs': Rx
},
globals: {
document: {
querySelector: function () {
return {
addEventListener: function () {},
... | it | identifier_name |
.markdown-doctest-setup.js | 'use strict';
var Rx = require(__dirname);
var marbleTesting = require('./spec-js/helpers/marble-testing');
global.rxTestScheduler = new Rx.TestScheduler(marbleTesting.assertDeepEqual);
function it(callback) |
it.asDiagram = function asDiagram() {
return function (spec, callback) {
callback();
}
};
module.exports = {
require: {
'@reactivex/rxjs': Rx
},
globals: {
document: {
querySelector: function () {
return {
addEventListener: function () {},
removeEventListener:... | {
callback();
} | identifier_body |
statvfs.rs | //! Get filesystem statistics
//!
//! See [the man pages](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatvfs.html)
//! for more details.
use std::mem;
use std::os::unix::io::AsRawFd;
use libc::{self, c_ulong};
use crate::{Result, NixPath, errno::Errno};
#[cfg(not(target_os = "redox"))]
libc_bitflags... | ST_NODIRATIME;
/// Update access time relative to modify/change time
#[cfg(any(target_os = "android", all(target_os = "linux", not(target_env = "musl"))))]
ST_RELATIME;
}
);
/// Wrapper around the POSIX `statvfs` struct
///
/// For more information see the [`statvfs(3)` man pages](h... | #[cfg(any(target_os = "android", target_os = "linux"))] | random_line_split |
statvfs.rs | //! Get filesystem statistics
//!
//! See [the man pages](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatvfs.html)
//! for more details.
use std::mem;
use std::os::unix::io::AsRawFd;
use libc::{self, c_ulong};
use crate::{Result, NixPath, errno::Errno};
#[cfg(not(target_os = "redox"))]
libc_bitflags... | (&self) -> libc::fsfilcnt_t {
self.0.f_favail
}
/// Get the file system id
pub fn filesystem_id(&self) -> c_ulong {
self.0.f_fsid
}
/// Get the mount flags
#[cfg(not(target_os = "redox"))]
pub fn flags(&self) -> FsFlags {
FsFlags::from_bits_truncate(self.0.f_flag)
... | files_available | identifier_name |
statvfs.rs | //! Get filesystem statistics
//!
//! See [the man pages](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatvfs.html)
//! for more details.
use std::mem;
use std::os::unix::io::AsRawFd;
use libc::{self, c_ulong};
use crate::{Result, NixPath, errno::Errno};
#[cfg(not(target_os = "redox"))]
libc_bitflags... |
/// Get the number of free file inodes for unprivileged users
pub fn files_available(&self) -> libc::fsfilcnt_t {
self.0.f_favail
}
/// Get the file system id
pub fn filesystem_id(&self) -> c_ulong {
self.0.f_fsid
}
/// Get the mount flags
#[cfg(not(target_os = "redox... | {
self.0.f_ffree
} | identifier_body |
visualization.js | var visualization = function() {
var vizData;
var vizApp = this;
var padding = 40; // padding between groups
var max_group_width = 600;
// TODO: this assumes fixed note width and height, potentially handle for importance of notes
var max_note_width = 240;
var max_note_height = 110;
var container_width;
var ... | layoutButtons.removeClass('active');
$(this).addClass('active');
var cat = $(this).attr('data-layout')
console.log(cat);
rearrangeNotes(cat);
});
saveLayoutButton.on('click', saveCustomLayout);
}
var setGroupPositions = function(notes, type, start) {
// create a map representing a group:
// c... | colorNotes(cat);
});
layoutButtons.on('click', function() { | random_line_split |
visualization.js | var visualization = function() {
var vizData;
var vizApp = this;
var padding = 40; // padding between groups
var max_group_width = 600;
// TODO: this assumes fixed note width and height, potentially handle for importance of notes
var max_note_width = 240;
var max_note_height = 110;
var container_width;
var ... | else {
arrayOfNotes.map(function(note) {
note.setBackground('#eee')
});
}
}
var saveCustomLayout = function() {
arrayOfNotes.map(function(note) {
var pos = note.position();
console.log("custom layout");
console.log(pos);
note.customPosition(pos);
});
saveLayoutButton.fadeOut();
}
th... | {
var arrayOfCriteria = generateArrayOfAttributes(criteria, arrayOfNotes);
arrayOfNotes.map(function(note) {
var attr = note.getNoteAttr(criteria);
note.setBackground(colorArray[arrayOfCriteria.indexOf(attr)])
});
} | conditional_block |
visualization.js | var visualization = function() {
var vizData;
var vizApp = this;
var padding = 40; // padding between groups
var max_group_width = 600;
// TODO: this assumes fixed note width and height, potentially handle for importance of notes
var max_note_width = 240;
var max_note_height = 110;
var container_width;
var ... | (criteria, arrayOfNotes) {
var rawArray = arrayOfNotes.map(function(note) {
return note.getNoteAttr(criteria);
});
return rawArray.getUnique();
}
//http://stackoverflow.com/questions/1960473/unique-values-in-an-array
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length... | generateArrayOfAttributes | identifier_name |
visualization.js | var visualization = function() {
var vizData;
var vizApp = this;
var padding = 40; // padding between groups
var max_group_width = 600;
// TODO: this assumes fixed note width and height, potentially handle for importance of notes
var max_note_width = 240;
var max_note_height = 110;
var container_width;
var ... |
//http://stackoverflow.com/questions/1960473/unique-values-in-an-array
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
var c... | {
var rawArray = arrayOfNotes.map(function(note) {
return note.getNoteAttr(criteria);
});
return rawArray.getUnique();
} | identifier_body |
test_texture.rs | extern crate image;
use std::path::Path;
use self::image::GenericImage;
#[allow(unused_imports)]
use std::collections::HashMap;
#[allow(unused_imports)]
use implement::render::texture::{ TextureNormalized, TextureBuiltin, Texture, Channel };
#[allow(unused_imports)]
use implement::render::texture;
#[test]
pub fn te... | let t_modulated_checker : Texture = texture::modulate( &t_checker, &channel_val );
assert!( 255u8 == t_modulated_solid[(0usize,Channel::R)] );
assert!( 120u8 == t_modulated_solid[(0usize,Channel::G)] );
assert!( 0u8 == t_modulated_solid[(0usize,Channel::B)] );
assert!( 0u8 == t_modulated_checker[(... | {
//test for loading image into texture
let img = image::open( &Path::new( "core/asset/images/texture0.jpg" ) ).unwrap();
println!( "image dimension: {:?}", img.dimensions() );
println!( "image type: {:?}", img.color() );
// let texture0 = texture::Texture::from( &img );
//let texture_data = Ve... | identifier_body |
test_texture.rs | extern crate image;
use std::path::Path;
use self::image::GenericImage;
#[allow(unused_imports)]
use std::collections::HashMap;
#[allow(unused_imports)]
use implement::render::texture::{ TextureNormalized, TextureBuiltin, Texture, Channel };
#[allow(unused_imports)]
use implement::render::texture;
#[test]
pub fn te... | } | random_line_split | |
test_texture.rs | extern crate image;
use std::path::Path;
use self::image::GenericImage;
#[allow(unused_imports)]
use std::collections::HashMap;
#[allow(unused_imports)]
use implement::render::texture::{ TextureNormalized, TextureBuiltin, Texture, Channel };
#[allow(unused_imports)]
use implement::render::texture;
#[test]
pub fn | () {
//test for loading image into texture
let img = image::open( &Path::new( "core/asset/images/texture0.jpg" ) ).unwrap();
println!( "image dimension: {:?}", img.dimensions() );
println!( "image type: {:?}", img.color() );
// let texture0 = texture::Texture::from( &img );
//let texture_data =... | test_texture | identifier_name |
timeout.rs | use crate::stream_ext::Fuse;
use crate::Stream;
use tokio::time::{Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::fmt;
use std::time::Duration;
pin_project! {
/// Stream returned by the [`timeout`](super::StreamExt::timeou... |
return Poll::Ready(v.map(Ok));
}
Poll::Pending => {}
};
if *me.poll_deadline {
ready!(me.deadline.poll(cx));
*me.poll_deadline = false;
return Poll::Ready(Some(Err(Elapsed::new())));
}
Poll::Pending
}
... | {
let next = Instant::now() + *me.duration;
me.deadline.reset(next);
*me.poll_deadline = true;
} | conditional_block |
timeout.rs | use crate::stream_ext::Fuse;
use crate::Stream;
use tokio::time::{Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::fmt;
use std::time::Duration;
pin_project! {
/// Stream returned by the [`timeout`](super::StreamExt::timeou... |
Poll::Pending
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.stream.size_hint();
// The timeout stream may insert an error before and after each message
// from the underlying stream, but no more than one error between each
// message. Hen... | {
let me = self.project();
match me.stream.poll_next(cx) {
Poll::Ready(v) => {
if v.is_some() {
let next = Instant::now() + *me.duration;
me.deadline.reset(next);
*me.poll_deadline = true;
}
... | identifier_body |
timeout.rs | use crate::stream_ext::Fuse;
use crate::Stream;
use tokio::time::{Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::fmt;
use std::time::Duration;
pin_project! {
/// Stream returned by the [`timeout`](super::StreamExt::timeou... | return Poll::Ready(v.map(Ok));
}
Poll::Pending => {}
};
if *me.poll_deadline {
ready!(me.deadline.poll(cx));
*me.poll_deadline = false;
return Poll::Ready(Some(Err(Elapsed::new())));
}
Poll::Pending
}
... | random_line_split | |
timeout.rs | use crate::stream_ext::Fuse;
use crate::Stream;
use tokio::time::{Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
use std::fmt;
use std::time::Duration;
pin_project! {
/// Stream returned by the [`timeout`](super::StreamExt::timeou... | (&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
"deadline has elapsed".fmt(fmt)
}
}
impl std::error::Error for Elapsed {}
impl From<Elapsed> for std::io::Error {
fn from(_err: Elapsed) -> std::io::Error {
std::io::ErrorKind::TimedOut.into()
}
}
| fmt | identifier_name |
helpers.py | # -*- coding: utf-8 *-*
from collections import OrderedDict
from nicepy.utils import ljust_all, pretty_repr
def get_failed_msg(compare_method, values, expected_values, names=None, expected_names=None):
failed_list = []
names = names or map(str, range(len(values)))
expected_names = expected_names or [''] *... |
def get_multi_failed_msg(assert_method, *lists):
failed_msgs = OrderedDict()
for index, args in enumerate(zip(*lists)):
try:
assert_method(*args)
except AssertionError as e:
failed_msgs[index] = e.message
msg = None
if failed_msgs:
msg = 'Multi-assert fa... | if not failed_list:
return None
msg = 'actual values != expected values:'
failed_list = zip(*map(ljust_all, zip(*failed_list)))
for value_repr, expected_value_repr, name, expected_name in sorted(failed_list):
msg += '\n\t%s' % name
if expected_name:
msg += ' != %s' % expe... | identifier_body |
helpers.py | # -*- coding: utf-8 *-*
from collections import OrderedDict
from nicepy.utils import ljust_all, pretty_repr
def get_failed_msg(compare_method, values, expected_values, names=None, expected_names=None):
failed_list = []
names = names or map(str, range(len(values)))
expected_names = expected_names or [''] *... | (assert_method, *lists):
failed_msgs = OrderedDict()
for index, args in enumerate(zip(*lists)):
try:
assert_method(*args)
except AssertionError as e:
failed_msgs[index] = e.message
msg = None
if failed_msgs:
msg = 'Multi-assert failed:'
for index, ... | get_multi_failed_msg | identifier_name |
helpers.py | # -*- coding: utf-8 *-*
from collections import OrderedDict
from nicepy.utils import ljust_all, pretty_repr
def get_failed_msg(compare_method, values, expected_values, names=None, expected_names=None):
failed_list = []
names = names or map(str, range(len(values)))
expected_names = expected_names or [''] *... |
return _get_failed_msg(failed_list)
def _get_failed_msg(failed_list):
if not failed_list:
return None
msg = 'actual values != expected values:'
failed_list = zip(*map(ljust_all, zip(*failed_list)))
for value_repr, expected_value_repr, name, expected_name in sorted(failed_list):
ms... | if not compare_method(expected_value, value):
failed_list.append((pretty_repr(value), pretty_repr(expected_value),
name, expected_name)) | conditional_block |
helpers.py | # -*- coding: utf-8 *-*
from collections import OrderedDict
from nicepy.utils import ljust_all, pretty_repr
def get_failed_msg(compare_method, values, expected_values, names=None, expected_names=None):
failed_list = []
names = names or map(str, range(len(values)))
expected_names = expected_names or [''] *... | if not failed_list:
return None
msg = 'actual values != expected values:'
failed_list = zip(*map(ljust_all, zip(*failed_list)))
for value_repr, expected_value_repr, name, expected_name in sorted(failed_list):
msg += '\n\t%s' % name
if expected_name:
msg += ' != %s' % ... |
def _get_failed_msg(failed_list): | random_line_split |
lib.rs | //! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications
#![deny(warnings)]
#![feature(alloc)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feat... | unsafe {
interrupt::disable();
if context::switch() {
interrupt::enable_and_nop();
} else {
// Enable interrupts, then halt CPU (to save power) until the next interrupt is actually fired.
interrupt::enable_and_halt();
... | {
CPU_ID.store(0, Ordering::SeqCst);
CPU_COUNT.store(cpus, Ordering::SeqCst);
context::init();
let pid = syscall::getpid();
println!("BSP: {:?} {}", pid, cpus);
match context::contexts_mut().spawn(userspace_init) {
Ok(context_lock) => {
let mut context = context_lock.write... | identifier_body |
lib.rs | //! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications
#![deny(warnings)]
#![feature(alloc)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feat... |
}
syscall::exit(signal & 0x7F);
}
/// This is the kernel entry point for the primary CPU. The arch crate is responsible for calling this
#[no_mangle]
pub extern fn kmain(cpus: usize) {
CPU_ID.store(0, Ordering::SeqCst);
CPU_COUNT.store(cpus, Ordering::SeqCst);
context::init();
let pid = sysc... | {
let context = context_lock.read();
println!("NAME {}", unsafe { ::core::str::from_utf8_unchecked(&context.name.lock()) });
} | conditional_block |
lib.rs | //! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications
#![deny(warnings)]
#![feature(alloc)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feat... | interrupt::disable();
if context::switch() {
interrupt::enable_and_nop();
} else {
// Enable interrupts, then halt CPU (to save power) until the next interrupt is actually fired.
interrupt::enable_and_halt();
}
}
... | println!("AP {}: {:?}", id, pid);
loop {
unsafe { | random_line_split |
lib.rs | //! # The Redox OS Kernel, version 2
//!
//! The Redox OS Kernel is a hybrid kernel that supports X86_64 systems and
//! provides Unix-like syscalls for primarily Rust applications
#![deny(warnings)]
#![feature(alloc)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feat... | () {
assert_eq!(syscall::chdir(b"initfs:"), Ok(0));
assert_eq!(syscall::open(b"debug:", syscall::flag::O_RDONLY).map(FileHandle::into), Ok(0));
assert_eq!(syscall::open(b"debug:", syscall::flag::O_WRONLY).map(FileHandle::into), Ok(1));
assert_eq!(syscall::open(b"debug:", syscall::flag::O_WRONLY).map(Fi... | userspace_init | identifier_name |
webpack.dev.conf.js | var webpack = require('webpack')
var DevServer = require('webpack-dev-server')
var base = require('./webpack.base.conf.js')
var webConfig = base('vue', true)
var weexConfig = base('weex', true)
var port = process.env.DEMO_PORT | 3456
webConfig.entry = {
app: [
'./demo/src/render.js',
'./demo/src/app.js',
... | }
webConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
// weex 版跑在 playground,里不需要热替换
weexConfig.entry = {
app: ['./demo/src/app.js']
}
new DevServer(webpack([webConfig, weexConfig]), {
port: port,
host: '0.0.0.0',
// disable host check to avoid `Invalid Host header` issue
disableHostCheck: true,... | 'webpack-dev-server/client/?http://0.0.0.0:' + port
] | random_line_split |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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 ap... | /**
* Evaluates the moment-generating function (MGF) for a Rayleigh distribution with scale parameter `sigma` at a value `t`.
*
* ## Notes
*
* - If provided `sigma < 0`, the function returns `NaN`.
*
* @param t - input value
* @param sigma - scale parameter
* @returns evaluated MGF
*
* @example
* var y =... |
/**
* Interface for the moment-generating function (MGF) of a Rayleigh distribution.
*/
interface MGF { | 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/. */
#![feature(default_type_params, globs, macro_rules, phase, unsafe_destructor)]
#![deny(unsafe_blocks)]
#![deny(un... | extern crate hyper;
extern crate js;
extern crate libc;
extern crate msg;
extern crate net;
extern crate rustrt;
extern crate serialize;
extern crate time;
extern crate canvas;
extern crate script_traits;
#[phase(plugin)]
extern crate "plugins" as servo_plugins;
extern crate "net" as servo_net;
extern crate "util" as s... | extern crate encoding; | random_line_split |
filesystem_view.py | _standalone(self, spec):
"""
Add (link) a standalone package into this view.
"""
raise NotImplementedError
def check_added(self, spec):
"""
Check if the given concrete spec is active in this view.
"""
raise NotImplementedError
def remove_... |
def add_specs(self, *specs, **kwargs):
assert all((s.concrete for s in specs))
specs = set(specs)
if kwargs.get("with_dependencies", True):
specs.update(get_dependencies(specs))
if kwargs.get("exclude", None):
specs = set(filter_exclude(specs, kwargs["excl... | return {} | conditional_block |
filesystem_view.py | _standalone(self, spec):
"""
Add (link) a standalone package into this view.
"""
raise NotImplementedError
def check_added(self, spec):
"""
Check if the given concrete spec is active in this view.
"""
raise NotImplementedError
def remove_... | Should accept `with_dependencies` as keyword argument (default
True) to indicate wether or not dependencies should be deactivated
as well.
Should accept `with_dependents` as keyword argument (default True)
to indicate wether or not dependents on the deactivat... | another package.
| random_line_split |
filesystem_view.py | _standalone(self, spec):
"""
Add (link) a standalone package into this view.
"""
raise NotImplementedError
def check_added(self, spec):
"""
Check if the given concrete spec is active in this view.
"""
raise NotImplementedError
def remove_... | (self):
if self.projections:
mkdirp(os.path.dirname(self.projections_path))
with open(self.projections_path, 'w') as f:
f.write(s_yaml.dump_config({'projections': self.projections}))
def read_projections(self):
if os.path.exists(self.projections_path):
... | write_projections | identifier_name |
filesystem_view.py |
def view_hardlink(src, dst, **kwargs):
# keyword arguments are irrelevant
# here to fit required call signature
os.link(src, dst)
def view_copy(src, dst, view, spec=None):
"""
Copy a file from src to dst.
Use spec and view to generate relocations
"""
shutil.copyfile(src, dst)
i... | os.symlink(src, dst) | identifier_body | |
terrain.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | # -*- coding: utf-8 -*-
# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
# | random_line_split | |
terrain.py | # -*- coding: utf-8 -*-
# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# 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://w... | feature):
"""
Hook: Will be executed before each feature. Configures global vars and gets token from keystone.
Launch agents (puppet and chef) in the target VM
"""
setup_feature(feature)
@before.each_scenario
def before_each_scenario(scenario):
"""
Hook: Will be executed before each Scenar... | efore_each_feature( | identifier_name |
terrain.py | # -*- coding: utf-8 -*-
# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# 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://w... |
@after.all
def after_all(scenario):
"""
Hook: Will be executed after all each scenario
Removes Feature data and cleans the system. Kills all agents running in the VM.
"""
after_each_scenario(scenario)
tear_down(scenario)
| ""
Hook: Will be executed after all each scenario
Removes Feature data and cleans the system. Kills all agents running in the VM.
"""
execute_chef_client_stop()
execute_puppet_agent_stop()
remove_chef_client_cert_file()
remove_puppet_agent_cert_file()
remove_all_generated_test_files()
... | identifier_body |
kindck-impl-type-params.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a>() {
let t: Box<S<String>> = box S;
let a: Box<Gettable<String>> = t;
//~^ ERROR the trait `core::marker::Copy` is not implemented
}
fn main() { }
| foo3 | identifier_name |
kindck-impl-type-params.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn foo<'a>() {
let t: S<&'a int> = S;
let a = &t as &Gettable<&'a int>;
//~^ ERROR declared lifetime bound not satisfied
}
fn foo2<'a>() {
let t: Box<S<String>> = box S;
let a = t as Box<Gettable<String>>;
//~^ ERROR the trait `core::marker::Copy` is not implemented
}
fn foo3<'a>() {
let... | {
let t: S<T> = S;
let a: &Gettable<T> = &t;
//~^ ERROR the trait `core::marker::Send` is not implemented
//~^^ ERROR the trait `core::marker::Copy` is not implemented
} | identifier_body |
kindck-impl-type-params.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn foo<'a>() {
let t: S<&'a int> = S;
let a = &t as &Gettable<&'a int>;
//~^ ERROR declared lifetime bound not satisfied
}
fn foo2<'a>() {
let t: Box<S<String>> = box S;
let a = t as Box<Gettable<String>>;
//~^ ERROR the trait `core::marker::Copy` is not implemented
}
fn foo3<'a>() {
le... | let a: &Gettable<T> = &t;
//~^ ERROR the trait `core::marker::Send` is not implemented
//~^^ ERROR the trait `core::marker::Copy` is not implemented | random_line_split |
bless.rs | //! `bless` updates the reference files in the repo with changed output files
//! from the last test run.
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::clippy_project_root;
static CLIPPY_BUILD_TIME: SyncLazy<Option<std::time::SystemTime>> ... |
// If the test output was not updated since the last clippy build, it may be outdated
if !ignore_timestamp && !updated_since_clippy_build(&test_output_path).unwrap_or(true) {
return;
}
let test_output_file = fs::read(&test_output_path).expect("Unable to read test output file");
let refere... | {
return;
} | conditional_block |
bless.rs | //! `bless` updates the reference files in the repo with changed output files
//! from the last test run.
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::clippy_project_root;
static CLIPPY_BUILD_TIME: SyncLazy<Option<std::time::SystemTime>> ... |
fn build_dir() -> PathBuf {
let mut path = std::env::current_exe().unwrap();
path.set_file_name("test");
path
}
| {
let clippy_build_time = (*CLIPPY_BUILD_TIME)?;
let modified = fs::metadata(path).ok()?.modified().ok()?;
Some(modified >= clippy_build_time)
} | identifier_body |
bless.rs | //! `bless` updates the reference files in the repo with changed output files
//! from the last test run.
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::clippy_project_root;
static CLIPPY_BUILD_TIME: SyncLazy<Option<std::time::SystemTime>> ... | // We need to re-read the file now because it was potentially updated from copying
let reference_file = fs::read(&reference_file_path).unwrap_or_default();
if reference_file.is_empty() {
// If we copied over an empty output file, we remove the now empty reference file
pr... | println!("updating {}", &relative_reference_file_path.display());
fs::copy(test_output_path, &reference_file_path).expect("Could not update reference file");
| random_line_split |
bless.rs | //! `bless` updates the reference files in the repo with changed output files
//! from the last test run.
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::clippy_project_root;
static CLIPPY_BUILD_TIME: SyncLazy<Option<std::time::SystemTime>> ... | (ignore_timestamp: bool) {
let test_suite_dirs = [
clippy_project_root().join("tests").join("ui"),
clippy_project_root().join("tests").join("ui-internal"),
clippy_project_root().join("tests").join("ui-toml"),
clippy_project_root().join("tests").join("ui-cargo"),
];
for test_s... | bless | identifier_name |
gulpfile.js | const elixir = require('laravel-elixir');
elixir((mix) => {
// Mix all Sass files into one
mix.sass('app.scss');
// Mix all vendor scripts together
mix.scripts(
[
'jquery/dist/jquery.min.js',
'bootstrap-sass/assets/javascripts/bootstrap.min.js',
'bootstrap-s... | 'app.js'
], 'public/js/app.js');
});
*/ |
// Mix common JS files into one file
mix.scripts([ | random_line_split |
test_adapter.py | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Biggus. If not, see <http://www.gnu.org/licenses/>.
import unittest
import numpy as np
import biggus
class _Te... | [(30, 40), [(slice(5, 10),),
(slice(None, None), slice(2, 6))], (5, 4)],
[(30, 40), [(slice(None, None), slice(2, 6)),
(slice(5, 10),)], (5, 4)],
[(30, 40), [3.5], TypeError],
[(30, 40), ['foo'], TypeError],
[(30... | [(30, 40), [(slice(None, 10),), 5], (40,)],
[(30, 40), [(slice(None, 10),), (slice(None, 3),)], (3, 40)],
[(30, 40), [(slice(None, 10),), (slice(None, None, 2),)], (5, 40)], | random_line_split |
test_adapter.py | or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Biggus. If not, see <http://www.gnu.org/licenses/>.
import unittest
import numpy as np
import biggus
class _TestAdapter(object... |
def test_getitem(self):
# Sequence of tests, defined as:
# 1. Original array shape,
# 2. sequence of indexing operations to apply,
# 3. expected result shape or exception.
tests = [
[(30, 40), [], (30, 40)],
[(30, 40), [5], (40,)],
... | array = self.zeros_adapter((30, 40), keys=key)
self.assertEqual(array.shape, shape) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.