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 |
|---|---|---|---|---|
RootCategoryChildren.ts | /* tslint:disable */
// This file was automatically generated and should not be edited. | // ====================================================
export interface RootCategoryChildren_categories_edges_node_children {
__typename: "CategoryCountableConnection";
totalCount: number | null;
}
export interface RootCategoryChildren_categories_edges_node_products {
__typename: "ProductCountableConnection";
... |
// ====================================================
// GraphQL query operation: RootCategoryChildren | random_line_split |
main.ts | import '@uirouter/angularjs'
import * as angular from 'angular'
import userdive from 'userdive' |
const _ud = userdive()
const main = angular.module('myapp', ['ui.router'])
main.config([
'$stateProvider',
'$urlRouterProvider',
($stateProvider: any, $urlRouterProvider: any) => {
$urlRouterProvider.otherwise('/sample1')
$stateProvider
.state('sample1', {
url: '/sample1',
templat... | import Sample1 from './controllers/sample1'
import Sample2 from './controllers/sample2' | random_line_split |
next_in_inclusive_range.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::random::variable_range_generator;
use malachite_base::random::EXAMPLE_SEED;
use std::panic::catch_unwind;
fn next_in_inclusive_range_helper<T: PrimitiveUnsigned>(a: T, b: T, expected_values: &[T]) {
let mut range_generator = var... |
#[test]
fn next_in_inclusive_range_fail() {
apply_fn_to_unsigneds!(next_in_inclusive_range_fail_helper);
}
| {
assert_panic!({
let mut range_generator = variable_range_generator(EXAMPLE_SEED);
range_generator.next_in_inclusive_range(T::TWO, T::ONE);
});
} | identifier_body |
next_in_inclusive_range.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::random::variable_range_generator;
use malachite_base::random::EXAMPLE_SEED;
use std::panic::catch_unwind;
fn next_in_inclusive_range_helper<T: PrimitiveUnsigned>(a: T, b: T, expected_values: &[T]) {
let mut range_generator = var... | assert_panic!({
let mut range_generator = variable_range_generator(EXAMPLE_SEED);
range_generator.next_in_inclusive_range(T::TWO, T::ONE);
});
}
#[test]
fn next_in_inclusive_range_fail() {
apply_fn_to_unsigneds!(next_in_inclusive_range_fail_helper);
} | );
}
fn next_in_inclusive_range_fail_helper<T: PrimitiveUnsigned>() { | random_line_split |
next_in_inclusive_range.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::random::variable_range_generator;
use malachite_base::random::EXAMPLE_SEED;
use std::panic::catch_unwind;
fn next_in_inclusive_range_helper<T: PrimitiveUnsigned>(a: T, b: T, expected_values: &[T]) {
let mut range_generator = var... | () {
next_in_inclusive_range_helper::<u8>(5, 5, &[5; 20]);
next_in_inclusive_range_helper::<u16>(
1,
6,
&[2, 6, 4, 2, 3, 5, 6, 2, 3, 6, 5, 1, 6, 1, 3, 6, 3, 1, 5, 1],
);
next_in_inclusive_range_helper::<u32>(
10,
19,
&[11, 17, 15, 14, 16, 14, 12, 18, 11, 1... | test_next_in_inclusive_range | identifier_name |
es6-destructuring5-out.js | var S_ITER$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol.iterator||'@@iterator';var S_MARK$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol["__setObjectSetter__"];function ITER$0(v,f){if(v){if(Array.isArray(v))return f?v.slice():v;var i,r;if(S_MARK$0)S_MARK$0(v);if(typeof v==='object'&&typeof (f=v[S_ITER$0])==='functi... | test42 = SLICE$0.call(test41, 0), test41;
test41.push(4);
console.log(test41.join("|") === "1|2|3|4", test42.join("|") === "1|2|3");
{
var test43 = [1, 2, 3];
var test44 = ITER$0(test43 );
console.log(test44.join("|") === "1|2|3");
}
}
{
var test51 = [0, 1, 2, 3];
var test52, test53;
test53 = test51[0],... |
{
var test41 = [1, 2, 3];
var test42; | random_line_split |
es6-destructuring5-out.js | var S_ITER$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol.iterator||'@@iterator';var S_MARK$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol["__setObjectSetter__"];function | (v,f){if(v){if(Array.isArray(v))return f?v.slice():v;var i,r;if(S_MARK$0)S_MARK$0(v);if(typeof v==='object'&&typeof (f=v[S_ITER$0])==='function'){i=f.call(v);r=[];}else if((v+'')==='[object Generator]'){i=v;r=[];};if(S_MARK$0)S_MARK$0(void 0);if(r) {while((f=i['next']()),f['done']!==true)r.push(f['value']);return r;}}t... | ITER$0 | identifier_name |
es6-destructuring5-out.js | var S_ITER$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol.iterator||'@@iterator';var S_MARK$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol["__setObjectSetter__"];function ITER$0(v,f) | ;var SLICE$0 = Array.prototype.slice;var $D$0;
{
var test11 = [1, 2, 3];
var test12 = SLICE$0.call(test11, 0);
test11.push(4);
console.log(test11.join("|") === "1|2|3|4", test12.join("|") === "1|2|3");
}
{
var test21 = SLICE$0.call(([1, 2, 3]), 0);
console.log(test21.join("|") === "1|2|3");
}
{
var test31;
te... | {if(v){if(Array.isArray(v))return f?v.slice():v;var i,r;if(S_MARK$0)S_MARK$0(v);if(typeof v==='object'&&typeof (f=v[S_ITER$0])==='function'){i=f.call(v);r=[];}else if((v+'')==='[object Generator]'){i=v;r=[];};if(S_MARK$0)S_MARK$0(void 0);if(r) {while((f=i['next']()),f['done']!==true)r.push(f['value']);return r;}}throw ... | identifier_body |
GridOnSVGIcon.tsx | // This is a generated file from running the "createIcons" script. This file should not be updated manually.
import { forwardRef } from "react";
import { SVGIcon, SVGIconProps } from "@react-md/icon";
export const GridOnSVGIcon = forwardRef<SVGSVGElement, SVGIconProps>(
function GridOnSVGIcon(props, ref) {
retu... | }
); | ); | random_line_split |
basic.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
mod examples_util;
use examples_util::*;
use cassandra_sys::*;
use std::ffi::CString;
#[derive(Debug)]
struct Basic {
bln: cass_bool_t,
flt: f32,
dbl: f64,
i32: i32,
i64: i64,
}
fn insert_into_basic(session: &mut CassSessi... |
};
cass_future_free(future);
cass_statement_free(statement);
result
}
}
fn select_from_basic(session: &mut CassSession, key: &str, basic: &mut Basic) -> Result<(), CassError> {
unsafe {
let query = "SELECT * FROM examples.basic WHERE key = ?";
let statement = c... | {
print_error(future);
Err(rc)
} | conditional_block |
basic.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
mod examples_util;
use examples_util::*;
use cassandra_sys::*;
use std::ffi::CString;
#[derive(Debug)]
struct Basic {
bln: cass_bool_t,
flt: f32,
dbl: f64,
i32: i32,
i64: i64,
}
fn insert_into_basic(session: &mut CassSessi... | i64: 0,
};
execute_query(session,
"CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': \
'SimpleStrategy', 'replication_factor': '1' };")
.unwrap();
execu... | {
unsafe {
let cluster = create_cluster();
let session = &mut *cass_session_new();
let input = &mut Basic {
bln: cass_true,
flt: 0.001f32,
dbl: 0.0002f64,
i32: 1,
i64: 2,
};
match connect_session(session, cluster) ... | identifier_body |
basic.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
mod examples_util;
use examples_util::*;
use cassandra_sys::*;
use std::ffi::CString;
#[derive(Debug)]
struct Basic {
bln: cass_bool_t,
flt: f32,
dbl: f64,
i32: i32,
i64: i64,
}
fn insert_into_basic(session: &mut CassSessi... | (session: &mut CassSession, key: &str, basic: &mut Basic) -> Result<(), CassError> {
unsafe {
let query = "SELECT * FROM examples.basic WHERE key = ?";
let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 1);
cass_statement_bind_string(statement, 0, CString::new(key).un... | select_from_basic | identifier_name |
basic.rs | // #![feature(plugin)]
// #![plugin(clippy)]
extern crate cassandra_sys;
mod examples_util;
use examples_util::*;
use cassandra_sys::*;
use std::ffi::CString;
#[derive(Debug)]
struct Basic {
bln: cass_bool_t,
flt: f32,
dbl: f64,
i32: i32,
i64: i64,
}
fn insert_into_basic(session: &mut CassSessi... | cass_future_free(future);
result
}
}
pub fn main() {
unsafe {
let cluster = create_cluster();
let session = &mut *cass_session_new();
let input = &mut Basic {
bln: cass_true,
flt: 0.001f32,
dbl: 0.0002f64,
i32: 1,
... | }
rc => Err(rc),
}; | random_line_split |
resolve.js | /**
* @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 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { forkJoin } from 'rxjs/observable/forkJ... |
//# sourceMappingURL=resolve.js.map | {
if (snapshot.component && snapshot._routeConfig && typeof snapshot.component === 'string') {
return resolver.resolveComponent(snapshot.component);
}
else {
return Promise.resolve(null);
}
} | identifier_body |
resolve.js | /**
* @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 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { forkJoin } from 'rxjs/observable/forkJ... | else {
return Promise.resolve(null);
}
}
//# sourceMappingURL=resolve.js.map | return resolver.resolveComponent(snapshot.component);
} | random_line_split |
resolve.js | /**
* @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 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { forkJoin } from 'rxjs/observable/forkJ... |
else {
return Promise.resolve(null);
}
}
//# sourceMappingURL=resolve.js.map | {
return resolver.resolveComponent(snapshot.component);
} | conditional_block |
resolve.js | /**
* @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 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { forkJoin } from 'rxjs/observable/forkJ... | (resolver, state) {
return resolveNode(resolver, state._root).map(_ => state);
}
function resolveNode(resolver, node) {
if (node.children.length === 0) {
return fromPromise(resolveComponent(resolver, node.value).then(factory => {
node.value._resolvedComponentFactory = factory;
re... | resolve | identifier_name |
object-iteration.js | /**
* Created by Pencroff on 04-Sep-16.
*/
window.test = {
id: '384A61CA-DA2E-4FD2-A113-080010D4A42B',
name: 'object literal iteration',
description: 'Performance case for iteration object properties. Comparison for StackOverflow question: How do I loop through or enumerate a JavaScript object? (<a href=... | c = result;
});
suite.on('start cycle', function () {
var len = 100;
var i;
obj = {};
for (i = 0; i < len; i += 1) {
obj['prop'+i] = 'value' + i;
}
});
suit... | random_line_split | |
object-iteration.js | /**
* Created by Pencroff on 04-Sep-16.
*/
window.test = {
id: '384A61CA-DA2E-4FD2-A113-080010D4A42B',
name: 'object literal iteration',
description: 'Performance case for iteration object properties. Comparison for StackOverflow question: How do I loop through or enumerate a JavaScript object? (<a href=... |
a = b;
b = c;
c = result;
});
suite.add('by Object.keys with native forEach', function () {
result = '';
Object.keys(obj).forEach(function(key) {
result += key + ': ' + obj[key] + ' ';
... | {
key = arr[i];
result += key + ': ' + obj[key] + ' ';
} | conditional_block |
extraction_functions.py | adf.columns = ["channelIDs", "time", "duration", "lengths", "quals", "barcode"]
else:
datadf.columns = ["channelIDs", "time", "duration", "lengths", "quals"]
logging.info("Nanoget: Finished collecting statistics from summary file {}".format(summaryfile))
return ut.reduce_memory_usage(datadf.loc[data... | (bam, **kwargs):
"""Extracting metrics from unaligned bam format
Extracting lengths
"""
logging.info("Nanoget: Starting to collect statistics from ubam file {}.".format(bam))
samfile = pysam.AlignmentFile(bam, "rb", check_sq=False)
if not samfile.has_index():
pysam.index(bam)
# N... | process_ubam | identifier_name |
extraction_functions.py | adf.columns = ["channelIDs", "time", "duration", "lengths", "quals", "barcode"]
else:
datadf.columns = ["channelIDs", "time", "duration", "lengths", "quals"]
logging.info("Nanoget: Finished collecting statistics from summary file {}".format(summaryfile))
return ut.reduce_memory_usage(datadf.loc[data... | return None
def parse_MD(MDlist):
"""Parse MD string to get number of mismatches and deletions."""
return sum([len(item) for item in re.split('[0-9^]', MDlist)])
def parse_CIGAR(cigartuples):
"""Count the insertions in the read using the CIGAR string."""
return sum([item[1] for item in cigar... | random_line_split | |
extraction_functions.py | read.is_supplementary]
def get_pID(read):
"""Return the percent identity of a read.
based on the NM tag if present,
if not calculate from MD tag and CIGAR string
read.query_alignment_length can be zero in the case of ultra long reads aligned with minimap2 -L
"""
match = reduce(lambda x, y: ... | """Minimal fastq metrics extractor.
Quickly parse a fasta/fastq file - but makes expectations on the file format
There will be dragons if unexpected format is used
Expects a fastq_rich format, but extracts only timestamp and length
"""
try:
while True:
time = next(fq)[1:].split(... | identifier_body | |
extraction_functions.py | _usage(datadf.loc[datadf["lengths"] != 0].copy())
def check_bam(bam, samtype="bam"):
"""Check if bam file is valid.
Bam file should:
- exists
- has an index (create if necessary)
- is sorted by coordinate
- has at least one mapped read
"""
ut.check_existance(bam)
samfile = pysam.A... | import gzip
logging.info("Nanoget: Decompressing gzipped {} {}".format(file_type, inputfq))
return gzip.open(inputfq, 'rt') | conditional_block | |
mock_api.py | from contextlib import contextmanager
import json
import mock
# Mock tastypi API.
class ProjectData(object):
def get(self):
return dict()
def mock_version(repo):
class | (object):
def __init__(self, x=None):
pass
def put(self, x=None):
return x
def get(self, **kwargs):
# SCIENTIST DOG
version = json.loads("""
{
"active": false,
"built": false,
... | MockVersion | identifier_name |
mock_api.py | from contextlib import contextmanager
import json
import mock
# Mock tastypi API.
class ProjectData(object):
def get(self):
return dict()
def mock_version(repo):
class MockVersion(object):
def __init__(self, x=None):
pass
def put(self, x=None):
return x
... |
return MockVersion
class MockApi(object):
def __init__(self, repo):
self.version = mock_version(repo)
def project(self, x):
return ProjectData()
@contextmanager
def mock_api(repo):
api_mock = MockApi(repo)
with (
mock.patch('readthedocs.restapi.client.api', api_mock... | return version | conditional_block |
mock_api.py | from contextlib import contextmanager
import json
import mock
# Mock tastypi API.
class ProjectData(object):
def get(self):
return dict()
def mock_version(repo):
class MockVersion(object):
def __init__(self, x=None):
pass
def put(self, x=None):
return x
... | "documentation_type": "sphinx",
"id": "2599",
"modified_date": "2012-03-12T19:59:09.130773",
"name": "docs",
"project_url": "",
"pub_date": "2012-02-19T18:10:56.582780",
"repo": "g... | "description": "Make docs.readthedocs.org work :D",
"django_packages_url": "", | random_line_split |
mock_api.py | from contextlib import contextmanager
import json
import mock
# Mock tastypi API.
class ProjectData(object):
def get(self):
return dict()
def mock_version(repo):
class MockVersion(object):
def __init__(self, x=None):
pass
def put(self, x=None):
return x
... | api_mock = MockApi(repo)
with (
mock.patch('readthedocs.restapi.client.api', api_mock) and
mock.patch('readthedocs.api.client.api', api_mock) and
mock.patch('readthedocs.projects.tasks.api_v2', api_mock) and
mock.patch('readthedocs.projects.tasks.api_v1', api_mock)):
... | identifier_body | |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2020 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... | interface Routine {
/**
* Computes the maximum value of a single-precision floating-point strided array.
*
* @param N - number of indexed elements
* @param x - input array
* @param stride - stride length
* @returns maximum value
*
* @example
* var Float32Array = require( `@stdlib/array/float32` );
*
* var x... | /**
* Interface describing `smax`.
*/ | random_line_split |
set-har.js | var _ = require('lodash');
var fs = require('fs');
var formatData = require('./format-data');
var moment = require('moment')
module.exports = function (smocks) {
var harOptions = smocks.options && smocks.options.har;
return function (request, reply, respondWithConfig) {
var data = request.payload;
if (dat... | var fileName = data.fileName;
var callData = extractCalls(contents, harOptions);
var harIndex = -1;
smocks.state.userState(request)['__har'] = {
startIndex: 0,
fileName: fileName,
index: harIndex,
calls: callData.calls,
minTime: callData.minTime,
... | random_line_split | |
set-har.js | var _ = require('lodash');
var fs = require('fs');
var formatData = require('./format-data');
var moment = require('moment')
module.exports = function (smocks) {
var harOptions = smocks.options && smocks.options.har;
return function (request, reply, respondWithConfig) {
var data = request.payload;
if (dat... | (harContents, harOptions) {
var minTime = -1;
var maxTime = -1;
var id = 1;
var calls = _.compact(harContents.log.entries.map(function (data) {
var type = data.response.content.mimeType;
// we're only going to do html and json
if (type === 'application/json') {
try {
var urlInfo = dat... | extractCalls | identifier_name |
set-har.js | var _ = require('lodash');
var fs = require('fs');
var formatData = require('./format-data');
var moment = require('moment')
module.exports = function (smocks) {
var harOptions = smocks.options && smocks.options.har;
return function (request, reply, respondWithConfig) {
var data = request.payload;
if (dat... |
reply(respondWithConfig ? formatData(smocks, request) : {});
};
};
var urlMatch = /^[^:]*:?\/?\/?[^/]+([^\?]*)\??(.*)/;
function extractCalls(harContents, harOptions) {
var minTime = -1;
var maxTime = -1;
var id = 1;
var calls = _.compact(harContents.log.entries.map(function (data) {
var type = da... | {
var contents = JSON.parse(data.contents);
var fileName = data.fileName;
var callData = extractCalls(contents, harOptions);
var harIndex = -1;
smocks.state.userState(request)['__har'] = {
startIndex: 0,
fileName: fileName,
index: harIndex,
calls: callData.... | conditional_block |
set-har.js | var _ = require('lodash');
var fs = require('fs');
var formatData = require('./format-data');
var moment = require('moment')
module.exports = function (smocks) {
var harOptions = smocks.options && smocks.options.har;
return function (request, reply, respondWithConfig) {
var data = request.payload;
if (dat... | var rtn = {
id: id + '',
type: type,
time: Math.floor(data.time),
startTime: startTime,
method: data.request.method.toUpperCase(),
path: harOptions && harOptions.pathMapper ? harOptions.pathMapper(urlInfo[1]) : urlInfo[1],
queryString: data.r... | {
var minTime = -1;
var maxTime = -1;
var id = 1;
var calls = _.compact(harContents.log.entries.map(function (data) {
var type = data.response.content.mimeType;
// we're only going to do html and json
if (type === 'application/json') {
try {
var urlInfo = data.request.url.match(urlMat... | identifier_body |
utils.py | # -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# 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 la... | (self, user_id):
(code, response) = yield self.mock_resource.trigger(
"POST",
"/register",
json.dumps({
"user": user_id,
"password": "test",
"type": "m.login.password"
}))
self.assertEquals(200, code)
... | register | identifier_name |
utils.py | # -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# 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 la... |
if body is None:
body = "body_text_here"
path = "/rooms/%s/send/m.room.message/%s" % (room_id, txn_id)
content = '{"msgtype":"m.text","body":"%s"}' % body
if tok:
path = path + "?access_token=%s" % tok
(code, response) = yield self.mock_resource.trigger... | txn_id = "m%s" % (str(time.time())) | conditional_block |
utils.py | # -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# 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 la... | if txn_id is None:
txn_id = "m%s" % (str(time.time()))
if body is None:
body = "body_text_here"
path = "/rooms/%s/send/m.room.message/%s" % (room_id, txn_id)
content = '{"msgtype":"m.text","body":"%s"}' % body
if tok:
path = path + "?access_to... | random_line_split | |
utils.py | # -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# 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 la... |
@defer.inlineCallbacks
def join(self, room=None, user=None, expect_code=200, tok=None):
yield self.change_membership(room=room, src=user, targ=user, tok=tok,
membership=Membership.JOIN,
expect_code=expect_code)
@defer.inlin... | yield self.change_membership(room=room, src=src, targ=targ, tok=tok,
membership=Membership.INVITE,
expect_code=expect_code) | identifier_body |
rangeDecorations.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
this.editorDisposables.forEach(disposable => disposable.dispose());
this.editorDisposables = [];
}
private static _WHOLE_LINE_RANGE_HIGHLIGHT = ModelDecorationOptions.register({
stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'rangeHighlight',
isWholeLine: true
... | disposeEditorListeners | identifier_name |
rangeDecorations.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
private static _WHOLE_LINE_RANGE_HIGHLIGHT = ModelDecorationOptions.register({
stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'rangeHighlight',
isWholeLine: true
});
private static _RANGE_HIGHLIGHT = ModelDecorationOptions.register({
stickiness: editorCommon.Tracke... | {
this.editorDisposables.forEach(disposable => disposable.dispose());
this.editorDisposables = [];
} | identifier_body |
rangeDecorations.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | if (resource) {
if (resource.toString() === resourceRange.resource.toString()) {
return <editorCommon.ICommonCodeEditor>this.editorService.getActiveEditor().getControl();
}
}
return null;
}
private setEditor(editor: editorCommon.ICommonCodeEditor) {
if (this.editor !== editor) {
this.disposeEdit... | const resource = toResource(this.editorService.getActiveEditorInput()); | random_line_split |
rangeDecorations.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return null;
}
private setEditor(editor: editorCommon.ICommonCodeEditor) {
if (this.editor !== editor) {
this.disposeEditorListeners();
this.editor = editor;
this.editorDisposables.push(this.editor.onDidChangeCursorPosition((e: ICursorPositionChangedEvent) => {
if (
e.reason === CursorChangeRe... | {
if (resource.toString() === resourceRange.resource.toString()) {
return <editorCommon.ICommonCodeEditor>this.editorService.getActiveEditor().getControl();
}
} | conditional_block |
scrollspy.js | import {
addClass,
removeClass,
EVENTS,
on,
off,
getViewportSize,
getClosest,
getParents
} from '../../utils/domUtils'
import {nodeListToArray} from '../../utils/arrayUtils'
function ScrollSpy (element, target = 'body', options = {}) {
this.el = element
this.opts = Object.assign({}, ScrollSpy.DEFAU... |
}
ScrollSpy.DEFAULTS = {
offset: 10,
callback: (ele) => 0
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
this.offsets = []
this.targets... | {
this.refresh()
this.process()
} | conditional_block |
scrollspy.js | import {
addClass,
removeClass,
EVENTS,
on,
off,
getViewportSize,
getClosest,
getParents
} from '../../utils/domUtils'
import {nodeListToArray} from '../../utils/arrayUtils'
function | (element, target = 'body', options = {}) {
this.el = element
this.opts = Object.assign({}, ScrollSpy.DEFAULTS, options)
this.opts.target = target
if (target === 'body') {
this.scrollElement = window
} else {
this.scrollElement = document.querySelector(`[id=${target}]`)
}
this.selector = 'li > a'
... | ScrollSpy | identifier_name |
scrollspy.js | import {
addClass,
removeClass,
EVENTS,
on,
off,
getViewportSize,
getClosest,
getParents
} from '../../utils/domUtils'
import {nodeListToArray} from '../../utils/arrayUtils'
function ScrollSpy (element, target = 'body', options = {}) {
this.el = element
this.opts = Object.assign({}, ScrollSpy.DEFAU... | this.activeTarget = null
this.scrollHeight = 0
if (this.scrollElement) {
this.refresh()
this.process()
}
}
ScrollSpy.DEFAULTS = {
offset: 10,
callback: (ele) => 0
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.scrollElement.scrollHeight || Math.max(document.body.scrollHeight, ... | this.selector = 'li > a'
this.offsets = []
this.targets = [] | random_line_split |
scrollspy.js | import {
addClass,
removeClass,
EVENTS,
on,
off,
getViewportSize,
getClosest,
getParents
} from '../../utils/domUtils'
import {nodeListToArray} from '../../utils/arrayUtils'
function ScrollSpy (element, target = 'body', options = {}) |
ScrollSpy.DEFAULTS = {
offset: 10,
callback: (ele) => 0
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
this.offsets = []
this.targets =... | {
this.el = element
this.opts = Object.assign({}, ScrollSpy.DEFAULTS, options)
this.opts.target = target
if (target === 'body') {
this.scrollElement = window
} else {
this.scrollElement = document.querySelector(`[id=${target}]`)
}
this.selector = 'li > a'
this.offsets = []
this.targets = []
... | identifier_body |
map2tmx.js | "use strict"
const process = require(`process`)
const fs = require(`fs`)
const path = require(`path`)
const js2xmlparser = require(`js2xmlparser`)
const abbrevJson = require(`../abbrevJson`)
const asset = require(`../asset.js`)
const loadMappoMap = require(`../loadMappoMap`)
const mapFilename = process.argv[2]
const... | tilecount: tileset.tileCount,
columns: tileColumns,
},
image: {
'@': {
source: vspFilename,
width: vspPngWidth,
height: vspPngHeight,
}
},
}
}
obj.layer = mappoMap.mapLayerOrder.map(layerIndex => {
const tileLayer = mappoMap.tileLayers[layerIndex]
retur... | random_line_split | |
create_ground_truth.py | import cv2
import numpy as np
import os
from math import sqrt
from constants import (
GROUND_TRUTH,
RAWDATA_FOLDER)
FONT = cv2.FONT_HERSHEY_SIMPLEX
WINDOW_NAME = "Labeling"
CTRL_PT_RADIUS = 10
class Boundary:
def __init__(self, width, height):
self.top = height
self.right = width
self.bottom = 0
self.lef... |
else:
if self.mode == SceneMode.DELETE_POINT:
self.active_point.in_use = False
self.active_point = None
def _find_active_point(self, x, y):
for point in self.points:
if point.is_clicked(x, y):
self.active_point = point
return
def _on_lbutton_up(self, x, y):
self.active_point = None
de... | new_point = ControlPoint(x, y)
new_marking = Marking(new_point)
self.points.append(new_point)
self.markings.append(new_marking)
self.active_marking = new_marking
self.mode = SceneMode.ADD_POINT | conditional_block |
create_ground_truth.py | import cv2
import numpy as np
import os
from math import sqrt
from constants import (
GROUND_TRUTH,
RAWDATA_FOLDER)
FONT = cv2.FONT_HERSHEY_SIMPLEX
WINDOW_NAME = "Labeling"
CTRL_PT_RADIUS = 10
class Boundary:
def __init__(self, width, height):
self.top = height
self.right = width
self.bottom = 0
self.lef... |
def main():
cv2.namedWindow(WINDOW_NAME)
img_names = os.listdir(DATASET_FOLDER)
if not os.path.exists(GROUND_TRUTH):
os.makedirs(GROUND_TRUTH)
n_frames = len(img_names)
frame_idx = 0
while frame_idx in range(n_frames):
img = cv2.imread(DATASET_FOLDER + img_names[frame_idx])
height, width, _ = img.shape
... | fg_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(fg_gray, 0, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
bg = cv2.bitwise_and(img1, img1, mask=mask_inv)
fg = cv2.bitwise_and(img2, img2, mask=mask)
return cv2.add(bg, fg) | identifier_body |
create_ground_truth.py | import cv2
import numpy as np
import os
from math import sqrt
from constants import (
GROUND_TRUTH,
RAWDATA_FOLDER)
FONT = cv2.FONT_HERSHEY_SIMPLEX
WINDOW_NAME = "Labeling"
CTRL_PT_RADIUS = 10
class Boundary:
def __init__(self, width, height):
self.top = height
self.right = width
self.bottom = 0
self.lef... | (self, x, y):
self.active_point = None
def _on_mouse_move(self, x, y):
if self.mode == SceneMode.EDIT_POINT and self.active_point is not None:
self.active_point.move_to(x, y)
def _not_handle(self, x, y):
pass
def merge_images(img1, img2):
fg_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
_, mask = cv2.t... | _on_lbutton_up | identifier_name |
create_ground_truth.py | import cv2
import numpy as np
import os
from math import sqrt
from constants import (
GROUND_TRUTH,
RAWDATA_FOLDER)
FONT = cv2.FONT_HERSHEY_SIMPLEX
WINDOW_NAME = "Labeling"
CTRL_PT_RADIUS = 10
class Boundary:
def __init__(self, width, height):
self.top = height
self.right = width
self.bottom = 0
self.lef... | return dist <= self.radius
class Marking:
def __init__(self, point):
self.points = [point]
self.in_use = True
def add_point(self, point):
self.points.append(point)
def update(self):
self.points = [point for point in self.points if point.in_use]
if len(self.points) == 0:
self.in_use = False
def d... | def is_clicked(self, x, y):
dist = sqrt((self.x - x) ** 2 + (self.y - y) ** 2) | random_line_split |
namednodemap.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::Attr;
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::code... | (&self, namespace: Option<DOMString>, local_name: DOMString)
-> Fallible<DomRoot<Attr>> {
let ns = namespace_from_domstring(namespace);
self.owner.remove_attribute(&ns, &LocalName::from(local_name))
.ok_or(Error::NotFound)
}
// https://dom.spec.whatwg.org/#dom-... | RemoveNamedItemNS | identifier_name |
namednodemap.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::Attr;
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::code... |
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditem
fn GetNamedItem(&self, name: DOMString) -> Option<DomRoot<Attr>> {
self.owner.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-namednodemap-getnameditemns
fn GetNamedItemNS(&self, namespace: Option<DOMString>, ... | {
self.owner.attrs().get(index as usize).map(|js| DomRoot::from_ref(&**js))
} | identifier_body |
namednodemap.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::bindings::error::{Error, Fallible};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString;
use dom::bindings::xmlname::namespace_from_domstring;
use dom::element::Element;
use dom::window::Window;
use dom_struct::dom_struct;
us... |
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding;
use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods; | random_line_split |
namednodemap.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::Attr;
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::code... |
}
names
}
}
| {
names.push(DOMString::from(s));
} | conditional_block |
ipython_config.py | _run = ''
# The date format used by logging formatters for %(asctime)s
# c.TerminalIPythonApp.log_datefmt = '%Y-%m-%d %H:%M:%S'
# Whether to overwrite existing config files when copying
# c.TerminalIPythonApp.overwrite = False
# Execute the given command string.
# c.TerminalIPythonApp.code_to_run = ''
# Set the log... | # List of files to run at IPython startup.
# c.TerminalIPythonApp.exec_files = []
# Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk3', 'osx',
# 'pyglet', 'qt', 'qt5', 'tk', 'wx').
# c.TerminalIPythonApp.gui = None
# Reraise exceptions encountered loading IPython extensions?
# c.TerminalIPythonApp.r... | # profile is being created, and IPython contains config files for that profile,
# then they will be staged into the new directory. Otherwise, default config
# files will be automatically generated.
# c.TerminalIPythonApp.copy_config_files = False
| random_line_split |
test_freebase_support_query.py | #
# Copyright 2012 Markus Pielmeier
#
# This file is part of tagfs.
#
# tagfs 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.
#
# tagfs... |
def testThenSelectedKeysIsSelector(self):
self.assertEqual(list(self.query.selectedKeys), ['selector',])
def testThenQueryStringIs(self):
self.assertEqual(self.query.queryString, '{"filter":"filterValue","selector":[]}')
| super(WhenQueryWithOneFilerAndOneSelector, self).setUp()
self.query = freebase_support.Query({'filter': 'filterValue', 'selector': None, }) | identifier_body |
test_freebase_support_query.py | #
# Copyright 2012 Markus Pielmeier
#
# This file is part of tagfs.
#
# tagfs is free software: you can redistribute it and/or modify | #
# tagfs is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ... | # 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. | random_line_split |
test_freebase_support_query.py | #
# Copyright 2012 Markus Pielmeier
#
# This file is part of tagfs.
#
# tagfs 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.
#
# tagfs... | (self):
self.assertEqual(self.query.queryString, '{"filter":"filterValue","selector":[]}')
| testThenQueryStringIs | identifier_name |
all_tests.py | part of Essentia
#
# Essentia 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 (FSF), either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope... | (newCompute):
def algodecorator(algo):
algo.normalCompute = algo.compute
algo.compute = newCompute
algo.__call__ = newCompute
algo.hasDoubleCompute = True
return algo
return algodecorator
# recursive helper function that finds outputs connected to pools and calls func
d... | computeDecorator | identifier_name |
all_tests.py | part of Essentia
#
# Essentia 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 (FSF), either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope... | for input in ins:
# TODO: assuming input is a tuple of pool and descriptor name
if isinstance(input, tuple):
func(algo, output, input)
elif isinstance(input, essentia.streaming._StreamConnector):
mapPools(input.input_algo, func)
... | ins = list(inputs) | random_line_split |
all_tests.py | part of Essentia
#
# Essentia 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 (FSF), either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope... |
# For this to work for networks that are connected to a pool, we need to conduct
# the first run of the network with all pools replaced by dummy pools. The
# second run will run with the network connected to the original pools. This
# method is required to avoid doubling of the data in the pools due to the fact
# t... | ins = list(inputs)
for input in ins:
# TODO: assuming input is a tuple of pool and descriptor name
if isinstance(input, tuple):
func(algo, output, input)
elif isinstance(input, essentia.streaming._StreamConnector):
mapPools(input.input_algo, ... | conditional_block |
all_tests.py | part of Essentia
#
# Essentia 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 (FSF), either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope... |
# For this to work for networks that are connected to a pool, we need to conduct
# the first run of the network with all pools replaced by dummy pools. The
# second run will run with the network connected to the original pools. This
# method is required to avoid doubling of the data in the pools due to the fact
# t... | connections = dict(algo.connections)
for output, inputs in connections.items():
ins = list(inputs)
for input in ins:
# TODO: assuming input is a tuple of pool and descriptor name
if isinstance(input, tuple):
func(algo, output, input)
elif isinst... | identifier_body |
korw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Direct(K1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 204, 69, 249], OperandSize::Dword)
}
fn korw_2() {
run... | korw_1 | identifier_name |
korw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn korw_1() |
fn korw_2() {
run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K3)), operand3: Some(Direct(K2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 228, 69, 250], OperandSize::Qword)
}
| {
run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Direct(K1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 204, 69, 249], OperandSize::Dword)
} | identifier_body |
korw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn korw_1() { |
fn korw_2() {
run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K3)), operand3: Some(Direct(K2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 228, 69, 250], OperandSize::Qword)
} | run_test(&Instruction { mnemonic: Mnemonic::KORW, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Direct(K1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 204, 69, 249], OperandSize::Dword)
} | random_line_split |
test-hidden-frame.js | /* 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 strict";
const { Loader } = require("sdk/test/loader");
const hiddenFrames = require("sdk/frame/hidden-frame"... |
this.element.addEventListener("DOMContentLoaded", onDOMReady);
this.element.setAttribute("src", url);
}
}));
};
exports["test frame removed properly"] = function(assert, done) {
let url = "data:text/html;charset=utf-8,<!DOCTYPE%20html>";
let hiddenFrame = hiddenFrames.add(HiddenFrame({
onR... | {
hiddenFrame.element.removeEventListener("DOMContentLoaded", onDOMReady);
assert.equal(hiddenFrame.element.contentWindow.location, url,
"HiddenFrame loads the specified content.");
done();
} | identifier_body |
test-hidden-frame.js | /* 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 strict";
const { Loader } = require("sdk/test/loader");
const hiddenFrames = require("sdk/frame/hidden-frame"... | () {
frames.forEach(function(frame) {
assert.ok(frame.parentNode, "frame is in the document");
})
loader.unload();
frames.forEach(function(frame) {
assert.ok(!frame.parentNode, "frame isn't in the document'");
});
done();
}
};
require("sdk/test").run(exports);
| complete | identifier_name |
test-hidden-frame.js | /* 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/. */ |
exports["test Frame"] = function(assert, done) {
let url = "data:text/html;charset=utf-8,<!DOCTYPE%20html>";
let hiddenFrame = hiddenFrames.add(HiddenFrame({
onReady: function () {
assert.equal(this.element.contentWindow.location, "about:blank",
"HiddenFrame loads about:blank by d... | "use strict";
const { Loader } = require("sdk/test/loader");
const hiddenFrames = require("sdk/frame/hidden-frame");
const { HiddenFrame } = hiddenFrames; | random_line_split |
UserEmailSelector.js | Ext.namespace("GeoNode");
GeoNode.UserEmailSelector = Ext.extend(Ext.util.Observable, {
constructor: function(config) {
Ext.apply(this, config);
this.initUserStore();
this.panel = this.doLayout();
},
initUserStore: function() {
if (!this.userstore) {
var cfg = ... | () {
var value = this.availableUsers.getValue();
var user = this.availableUsers.getValue();
var recordIndex = this.userstore.findExact('email', value);
if (recordIndex > -1)
{
user = this.userstore.getAt(recordIndex).get('user');
... | addSelectedUser | identifier_name |
UserEmailSelector.js | Ext.namespace("GeoNode");
GeoNode.UserEmailSelector = Ext.extend(Ext.util.Observable, {
constructor: function(config) {
Ext.apply(this, config);
this.initUserStore();
this.panel = this.doLayout();
},
|
initUserStore: function() {
if (!this.userstore) {
var cfg = {
proxy: new Ext.data.HttpProxy({ url: this.userLookup, method: 'POST' }),
reader: new Ext.data.JsonReader({
root: 'users',
totalProperty: 'count',
... | random_line_split | |
UserEmailSelector.js | Ext.namespace("GeoNode");
GeoNode.UserEmailSelector = Ext.extend(Ext.util.Observable, {
constructor: function(config) {
Ext.apply(this, config);
this.initUserStore();
this.panel = this.doLayout();
},
initUserStore: function() {
if (!this.userstore) {
var cfg = ... |
return { init: init };
})();
this.selectedUsers = new Ext.DataView({
store: this.store,
itemSelector: 'div.user_item',
tpl: new Ext.XTemplate('<div><tpl for="."> <div class="x-btn user_item"><button class="icon-removeuser remove-button"> </button>{... | {
var item = view.findItemFromChild(target);
var idx = view.indexOf(item);
var rec = view.store.getAt(idx);
if (rec.get("email") !== owner) {
view.store.removeAt(view.indexOf(item));
}
} | identifier_body |
UserEmailSelector.js | Ext.namespace("GeoNode");
GeoNode.UserEmailSelector = Ext.extend(Ext.util.Observable, {
constructor: function(config) {
Ext.apply(this, config);
this.initUserStore();
this.panel = this.doLayout();
},
initUserStore: function() {
if (!this.userstore) {
var cfg = ... |
},
doLayout: function() {
var owner = this.owner;
var plugin = (function() {
var view;
function init(v) {
view = v;
view.on('render', addHooks);
}
function addHooks() {
view.getEl().on('mousedown',... | {
this.store = new Ext.data.ArrayStore({
idIndex: 0,
fields: ['email','user'],
data: []
});
} | conditional_block |
pw_serializer.rs | use super::PlayerId;
use super::pw_rules::{PlanetWars, Planet, Expedition};
use super::pw_protocol as proto;
/// Serialize given gamestate
pub fn serialize(state: &PlanetWars) -> proto::State {
serialize_rotated(state, 0)
}
/// Serialize given gamestate with player numbers rotated by given offset.
pub fn seriali... | (&self, exp: &Expedition) -> proto::Expedition {
proto::Expedition {
id: exp.id,
owner: self.player_num(exp.fleet.owner.unwrap()),
ship_count: exp.fleet.ship_count,
origin: self.state.planets[exp.origin].name.clone(),
destination: self.state.planets[ex... | serialize_expedition | identifier_name |
pw_serializer.rs | use super::PlayerId;
use super::pw_rules::{PlanetWars, Planet, Expedition};
use super::pw_protocol as proto;
/// Serialize given gamestate
pub fn serialize(state: &PlanetWars) -> proto::State |
/// Serialize given gamestate with player numbers rotated by given offset.
pub fn serialize_rotated(state: &PlanetWars, offset: usize) -> proto::State {
let serializer = Serializer::new(state, offset);
serializer.serialize_state()
}
struct Serializer<'a> {
state: &'a PlanetWars,
player_num_offset: us... | {
serialize_rotated(state, 0)
} | identifier_body |
pw_serializer.rs | use super::PlayerId;
use super::pw_rules::{PlanetWars, Planet, Expedition};
use super::pw_protocol as proto;
/// Serialize given gamestate
pub fn serialize(state: &PlanetWars) -> proto::State {
serialize_rotated(state, 0)
}
/// Serialize given gamestate with player numbers rotated by given offset.
pub fn seriali... | origin: self.state.planets[exp.origin].name.clone(),
destination: self.state.planets[exp.target].name.clone(),
turns_remaining: exp.turns_remaining,
}
}
} | random_line_split | |
lib.rs | //! The `libopenreil` crate aims to provide an okay wrapper around openreil-sys.
extern crate openreil_sys;
extern crate libc;
use openreil_sys::root::{reil_addr_t, reil_inst_t, reil_t, reil_arch_t, reil_inst_print,
reil_inst_handler_t, reil_init, reil_close, reil_translate,
... |
fn third_operand(&self) -> Option<reil_arg_t> {
match self.c.type_ {
reil_type_t::A_NONE => None,
_ => Some(self.c)
}
}
fn opcode(&self) -> reil_op_t {
self.op
}
fn mnemonic(&self) -> Option<String> {
let raw_info = self.raw_info;
l... | {
match self.b.type_ {
reil_type_t::A_NONE => None,
_ => Some(self.b)
}
} | identifier_body |
lib.rs | //! The `libopenreil` crate aims to provide an okay wrapper around openreil-sys.
extern crate openreil_sys;
extern crate libc;
use openreil_sys::root::{reil_addr_t, reil_inst_t, reil_t, reil_arch_t, reil_inst_print,
reil_inst_handler_t, reil_init, reil_close, reil_translate,
... | (&mut self, data: &mut [u8], start_address: u32) {
unsafe {
reil_translate(
self.reil_handle,
start_address as reil_addr_t,
data.as_mut_ptr(),
data.len() as libc::c_int,
);
}
}
/// Translate a single instruc... | translate | identifier_name |
lib.rs | //! The `libopenreil` crate aims to provide an okay wrapper around openreil-sys.
extern crate openreil_sys;
extern crate libc;
use openreil_sys::root::{reil_addr_t, reil_inst_t, reil_t, reil_arch_t, reil_inst_print,
reil_inst_handler_t, reil_init, reil_close, reil_translate,
... | pub fn new(
arch: ReilArch,
handler: Option<ReilInstHandler<T>>,
context: &'a mut T,
) -> Option<Self> {
let arch = match arch {
ReilArch::X86 => reil_arch_t::ARCH_X86,
ReilArch::ARM => reil_arch_t::ARCH_ARM,
};
let handler: reil_inst_handl... | /// Construct a new disassembler object
/// The handler function can be used to process the resulting REIL instructions
/// The `context` gets handed to the callback function | random_line_split |
lib.rs | //! The `libopenreil` crate aims to provide an okay wrapper around openreil-sys.
extern crate openreil_sys;
extern crate libc;
use openreil_sys::root::{reil_addr_t, reil_inst_t, reil_t, reil_arch_t, reil_inst_print,
reil_inst_handler_t, reil_init, reil_close, reil_translate,
... |
let byte = *mnem.offset(i) as u8;
mnem_bytes.push(byte);
}
mnem_bytes.push(' ' as u8);
for i in 0.. {
if *op.offset(i) == 0 { break }
let byte = *op.offset(i) as u8;
mnem_bytes.push(byte);
}
... | { break } | conditional_block |
RWAjax.js | function makeRequest(page,divid)
{
var http_request = getHttpRequest();
http_request.onreadystatechange = function() { handle_request(http_request,divid); };
http_request.open('GET', page, true);
http_request.send(null);
| {
if (handle.readyState != 4) {
document.getElementById(divid).innerHTML = 'Anropet misslyckades, kontakta oss om detta!';
return;
}
if (handle.status && handle.status != 200) {
document.getElementById(divid).innerHTML = 'Ett fel har uppstått. Felkod: ' + handle.status;
return;
}... | return false;
}
function handle_request(handle,divid) | random_line_split |
RWAjax.js | function | (page,divid)
{
var http_request = getHttpRequest();
http_request.onreadystatechange = function() { handle_request(http_request,divid); };
http_request.open('GET', page, true);
http_request.send(null);
return false;
}
function handle_request(handle,divid)
{
if (handle.readyState != 4) {
doc... | makeRequest | identifier_name |
RWAjax.js | function makeRequest(page,divid)
{
var http_request = getHttpRequest();
http_request.onreadystatechange = function() { handle_request(http_request,divid); };
http_request.open('GET', page, true);
http_request.send(null);
return false;
}
function handle_request(handle,divid)
{
if (handle.readySta... |
return handle;
}
|
var handle = false;
if (window.XMLHttpRequest) { // Firefox, Opera, Safari
handle = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Internet Explorer
try {
handle = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
handle = new ActiveXObject... | identifier_body |
value.rs | use crate::data::{FloatType, IntegerType};
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
/// The different types of value that are used in the zed virtual machine.
#[derive(Debug)]
pub enum Value {
/// The `nil` value
Nil,
... | 0x08 => string.push_str("\\b"),
0x1b => string.push_str("\\e"),
0x0c => string.push_str("\\f"),
0x0a => string.push_str("\\n"),
0x0d => string.push_str("\\r"),
0x09 => string.push_str("\\t"),
0x0b => string.push_str("\\v"),
0x5c => string.push_str("\\\\"),... | match ch as u32 {
0x20 => string.push(' '),
0x00 => string.push_str("\\0"),
0x07 => string.push_str("\\a"), | random_line_split |
value.rs | use crate::data::{FloatType, IntegerType};
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
/// The different types of value that are used in the zed virtual machine.
#[derive(Debug)]
pub enum Value {
/// The `nil` value
Nil,
... | (&self, f: &mut Formatter) -> FmtResult {
use Value::*;
match self {
Nil => f.pad("nil"),
Boolean(true) => f.pad("true"),
Boolean(false) => f.pad("false"),
Integer(v) => Display::fmt(v, f),
Float(v) => Debug::fmt(v, f),
String(v) => f.pad(&escape_string(v)),
}
}
}
fn e... | fmt | identifier_name |
value.rs | use crate::data::{FloatType, IntegerType};
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
/// The different types of value that are used in the zed virtual machine.
#[derive(Debug)]
pub enum Value {
/// The `nil` value
Nil,
... |
}
impl PartialEq for Value {
fn eq(&self, other: &Value) -> bool {
use Value::*;
match (self, other) {
(Nil, Nil) => true,
(Boolean(a), Boolean(b)) => a == b,
(Integer(a), Integer(b)) => a == b,
(Float(a), Float(b)) => a.to_bits() == b.to_bits(),
(String(a), String(b)) => a == ... | {
use Value::*;
match self {
Nil => Nil,
Boolean(v) => Boolean(*v),
Integer(v) => Integer(*v),
Float(v) => Float(*v),
String(v) => String(v.clone()),
}
} | identifier_body |
scheduler.rs | use alloc::linked_list::LinkedList;
use alloc::arc::Arc;
use super::bottom_half;
use super::bottom_half::BottomHalfManager;
use super::task::{TID_BOTTOMHALFD, TID_SYSTEMIDLE};
use super::task::{Task, TaskContext, TaskPriority, TaskStatus};
use kernel::kget;
use memory::MemoryManager;
const THREAD_QUANTUM: usize = 1... | (&mut self) {
self.need_resched = true;
}
/// Update `last_resched` to now and reset the `need_resched` flag
fn update_last_resched(&mut self) {
let clock = unsafe { &mut *kget().clock.get() };
self.last_resched = clock.now();
self.need_resched = false;
}
/// Find t... | set_need_resched | identifier_name |
scheduler.rs | use alloc::linked_list::LinkedList;
use alloc::arc::Arc;
use super::bottom_half;
use super::bottom_half::BottomHalfManager;
use super::task::{TID_BOTTOMHALFD, TID_SYSTEMIDLE};
use super::task::{Task, TaskContext, TaskPriority, TaskStatus};
use kernel::kget;
use memory::MemoryManager;
const THREAD_QUANTUM: usize = 1... | }
}
// Theres definitely nothing higer priority!
self.next_task(TaskPriority::NORMAL).unwrap()
}
};
let mut old_task = self.active_task.take().unwrap();
// Swap the contexts
// Copy the active context to s... | if t.get_priority() == TaskPriority::IRQ && t.get_status() == TaskStatus::READY
{
return; | random_line_split |
scheduler.rs | use alloc::linked_list::LinkedList;
use alloc::arc::Arc;
use super::bottom_half;
use super::bottom_half::BottomHalfManager;
use super::task::{TID_BOTTOMHALFD, TID_SYSTEMIDLE};
use super::task::{Task, TaskContext, TaskPriority, TaskStatus};
use kernel::kget;
use memory::MemoryManager;
const THREAD_QUANTUM: usize = 1... | else {
found = true;
break;
}
}
if found {
// Split inactive_tasks, remove the task we found, then re-merge the two lists
let mut remainder = self.inactive_tasks.split_off(i);
let next_task = remainder.pop_front();
... | {
// On to the next, this is not suitable
i += 1;
} | conditional_block |
scheduler.rs | use alloc::linked_list::LinkedList;
use alloc::arc::Arc;
use super::bottom_half;
use super::bottom_half::BottomHalfManager;
use super::task::{TID_BOTTOMHALFD, TID_SYSTEMIDLE};
use super::task::{Task, TaskContext, TaskPriority, TaskStatus};
use kernel::kget;
use memory::MemoryManager;
const THREAD_QUANTUM: usize = 1... |
/// Set the internal 'need_resched' flag to true
pub fn set_need_resched(&mut self) {
self.need_resched = true;
}
/// Update `last_resched` to now and reset the `need_resched` flag
fn update_last_resched(&mut self) {
let clock = unsafe { &mut *kget().clock.get() };
self.la... | {
if let Some(ref mut t) = self.active_task {
if t.id() == id {
t.set_status(status);
return;
}
}
for t in self.inactive_tasks.iter_mut() {
if t.id() == id {
t.set_status(status);
return;
... | identifier_body |
run_on_dates.py | #!/usr/bin/env python
import sys
import os.path
import datetime
import subprocess
import time
"""
Run snapstream reader script for several files and out a table of match counts.
Example:
$ python run_on_dates.py eg01china.c 2014-01-01 2014-07-01
"""
def validate(date_string):
try:
datetime.datetime.strpti... | exit(-1)
file_name = sys.argv[1]
begin_date = sys.argv[2]
end_date = sys.argv[3]
if os.path.isfile(file_name) is False:
print(file_name + " does not exist or is an invalid file")
exit(-1)
validate(begin_date)
validate(end_date)
print("Running %s from %s to %s.... | if __name__ == "__main__":
start_time = time.time()
if len(sys.argv) != 4:
print("3 arguments are needed, file, begin date and end date") | random_line_split |
run_on_dates.py | #!/usr/bin/env python
import sys
import os.path
import datetime
import subprocess
import time
"""
Run snapstream reader script for several files and out a table of match counts.
Example:
$ python run_on_dates.py eg01china.c 2014-01-01 2014-07-01
"""
def validate(date_string):
|
if __name__ == "__main__":
start_time = time.time()
if len(sys.argv) != 4:
print("3 arguments are needed, file, begin date and end date")
exit(-1)
file_name = sys.argv[1]
begin_date = sys.argv[2]
end_date = sys.argv[3]
if os.path.isfile(file_name) is False:
prin... | try:
datetime.datetime.strptime(date_string,"%Y-%m-%d")
except ValueError as e:
raise ValueError("Incorrect date format, should be YYYY-MM-DD") | identifier_body |
run_on_dates.py | #!/usr/bin/env python
import sys
import os.path
import datetime
import subprocess
import time
"""
Run snapstream reader script for several files and out a table of match counts.
Example:
$ python run_on_dates.py eg01china.c 2014-01-01 2014-07-01
"""
def | (date_string):
try:
datetime.datetime.strptime(date_string,"%Y-%m-%d")
except ValueError as e:
raise ValueError("Incorrect date format, should be YYYY-MM-DD")
if __name__ == "__main__":
start_time = time.time()
if len(sys.argv) != 4:
print("3 arguments are needed, file, ... | validate | identifier_name |
run_on_dates.py | #!/usr/bin/env python
import sys
import os.path
import datetime
import subprocess
import time
"""
Run snapstream reader script for several files and out a table of match counts.
Example:
$ python run_on_dates.py eg01china.c 2014-01-01 2014-07-01
"""
def validate(date_string):
try:
datetime.datetime.strpti... |
validate(begin_date)
validate(end_date)
print("Running %s from %s to %s..." % (file_name, begin_date, end_date))
data_files = ["Data/" + f for f in os.listdir("Data") if f >= begin_date and f < end_date]
data_files.sort()
full_output = open("full_output.txt","w")
print("\t".join(["d... | print(file_name + " does not exist or is an invalid file")
exit(-1) | conditional_block |
resource.js | 'use strict';
var _ = require('lodash');
var helpers = require('./helpers');
var responseParser = require('./responseparser');
var request = require('./request');
// A resource on the API, instances of this are used as the prototype of
// instances of each API resource. This constructor will build up a method
// for... | (options, schema) {
this.logger = options.logger;
this.resourceName = options.resourceDefinition.resource;
this.host = options.resourceDefinition.host || schema.host;
this.sslHost = options.resourceDefinition.sslHost || schema.sslHost;
this.port = options.resourceDefinition.port || schema.port;
this.prefix = opti... | Resource | identifier_name |
resource.js | 'use strict';
var _ = require('lodash');
var helpers = require('./helpers');
var responseParser = require('./responseparser');
var request = require('./request');
// A resource on the API, instances of this are used as the prototype of
// instances of each API resource. This constructor will build up a method
// for... |
if (response && response.headers['location']) {
parsed.location = response.headers['location'];
}
return callback(null, parsed);
}
}
_.defaults(requestData, this.defaultParams);
if (httpMethod === 'GET') {
// Add the default parameters to the request data
return request.get(endpoint... | {
return callback(err);
} | conditional_block |
resource.js | 'use strict';
var _ = require('lodash');
var helpers = require('./helpers');
var responseParser = require('./responseparser');
var request = require('./request');
// A resource on the API, instances of this are used as the prototype of
// instances of each API resource. This constructor will build up a method
// for... |
// Figure out the appropriate method name for an action on a resource on
// the API
//
// - @param {Mixed} - actionDefinition - Either a string if the action method
// name is the same as the action path component on the underlying API call
// or a hash if they differ.
// - @return {String}
Resource.prototype.chooseM... | {
this.logger = options.logger;
this.resourceName = options.resourceDefinition.resource;
this.host = options.resourceDefinition.host || schema.host;
this.sslHost = options.resourceDefinition.sslHost || schema.sslHost;
this.port = options.resourceDefinition.port || schema.port;
this.prefix = options.resourceDefini... | identifier_body |
resource.js | 'use strict';
var _ = require('lodash');
var helpers = require('./helpers');
var responseParser = require('./responseparser');
var request = require('./request');
// A resource on the API, instances of this are used as the prototype of
// instances of each API resource. This constructor will build up a method
// for... | // - `format` - the desired response format
// - `logger` - for logging output
function Resource(options, schema) {
this.logger = options.logger;
this.resourceName = options.resourceDefinition.resource;
this.host = options.resourceDefinition.host || schema.host;
this.sslHost = options.resourceDefinition.sslHost || ... | random_line_split | |
kz.js | export default {
el: {
colorpicker: {
confirm: 'Қабылдау',
clear: 'Тазалау'
},
datepicker: { | confirm: 'Қабылдау',
selectDate: 'Күнді таңдаңыз',
selectTime: 'Сағатты таңдаңыз',
startDate: 'Басталу күні',
startTime: 'Басталу сағаты',
endDate: 'Аяқталу күні',
endTime: 'Аяқталу сағаты',
prevYear: 'Алдыңғы жыл',
nextYear: 'Келесі жыл',
prevMonth: 'Алдыңғы ... | now: 'Қазір',
today: 'Бүгін',
cancel: 'Болдырмау',
clear: 'Тазалау', | random_line_split |
predictor_py_utils.py | ## @package predictor_py_utils
# Module caffe2.python.predictor.predictor_py_utils
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, scope
def create_predict_net(predictor_export_meta):
... |
def AddNet(meta_net_def, net_name, net_def):
meta_net_def.nets.add(key=net_name, value=net_def)
def GetArgumentByName(net_def, arg_name):
for arg in net_def.arg:
if arg.name == arg_name:
return arg
return None
def AddModelIdArg(meta_net_def, net_def):
"""Takes the model_id fro... | meta_net_def.plans.add(key=plan_name, value=plan_def) | identifier_body |
predictor_py_utils.py | ## @package predictor_py_utils
# Module caffe2.python.predictor.predictor_py_utils
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, scope
def create_predict_net(predictor_export_meta):
... | return _ProtoMapGet(meta_net_def.plans, key)
def GetBlobs(meta_net_def, key):
blobs = _ProtoMapGet(meta_net_def.blobs, key)
if blobs is None:
return []
return blobs
def GetNet(meta_net_def, key):
return _ProtoMapGet(meta_net_def.nets, key)
def GetNetOriginal(meta_net_def, key):
ret... |
def GetPlanOriginal(meta_net_def, key): | random_line_split |
predictor_py_utils.py | ## @package predictor_py_utils
# Module caffe2.python.predictor.predictor_py_utils
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, scope
def create_predict_net(predictor_export_meta):
... | (meta_net_def, key):
blobs = _ProtoMapGet(meta_net_def.blobs, key)
if blobs is None:
return []
return blobs
def GetNet(meta_net_def, key):
return _ProtoMapGet(meta_net_def.nets, key)
def GetNetOriginal(meta_net_def, key):
return _ProtoMapGet(meta_net_def.nets, key)
def GetApplicationSp... | GetBlobs | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.