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 |
|---|---|---|---|---|
nibbleslice.rs | ,3,4,5
/// let n2 = NibbleSlice::new(d2); // 3,4,5,0,1,2
/// let n3 = NibbleSlice::new_offset(d3, 1); // 0,1,2
/// assert!(n1 > n3); // 0,1,2,... > 0,1,2
/// assert!(n1 < n2); // 0,... < 3,...
/// assert!(n2.mid(3) == n3); // 0,1,2 == 0,1,2
/// assert!(n1.starts_with(&n3));
/// assert_eq... |
}
impl<'a> PartialEq for NibbleSlice<'a> {
fn eq(&self, them: &Self) -> bool {
self.len() == them.len() && self.starts_with(them)
}
}
impl<'a> PartialOrd for NibbleSlice<'a> {
fn partial_cmp(&self, them: &Self) -> Option<Ordering> {
let s = min(self.len(), them.len());
let mut i = 0usize;
while i < s {
... | {
let l = min(self.len(), n);
let mut r = Bytes::with_capacity(l / 2 + 1);
let mut i = l % 2;
r.push(if i == 1 { 0x10 + self.at(0) } else { 0 } + if is_leaf { 0x20 } else { 0 });
while i < l {
r.push(self.at(i) * 16 + self.at(i + 1));
i += 2;
}
r
} | identifier_body |
nibbleslice.rs | 2,3,4,5
/// let n2 = NibbleSlice::new(d2); // 3,4,5,0,1,2
/// let n3 = NibbleSlice::new_offset(d3, 1); // 0,1,2
/// assert!(n1 > n3); // 0,1,2,... > 0,1,2
/// assert!(n1 < n2); // 0,... < 3,...
/// assert!(n2.mid(3) == n3); // 0,1,2 == 0,1,2
/// assert!(n1.starts_with(&n3));
/// assert_e... | (&self, i: usize) -> u8 {
let l = self.data.len() * 2 - self.offset;
if i < l {
if (self.offset + i) & 1 == 1 { self.data[(self.offset + i) / 2] & 15u8 } else { self.data[(self.offset + i) / 2] >> 4 }
} else {
let i = i - l;
if (self.offset_encode_suffix + i) & 1 == 1 { self.data_encode_suffix[(self.offs... | at | identifier_name |
nibbleslice.rs | 2,3,4,5
/// let n2 = NibbleSlice::new(d2); // 3,4,5,0,1,2
/// let n3 = NibbleSlice::new_offset(d3, 1); // 0,1,2
/// assert!(n1 > n3); // 0,1,2,... > 0,1,2
/// assert!(n1 < n2); // 0,... < 3,...
/// assert!(n2.mid(3) == n3); // 0,1,2 == 0,1,2
/// assert!(n1.starts_with(&n3));
/// assert_e... | where 'a: 'view,
{
/// Create a new nibble slice with the given byte-slice.
pub fn new(data: &'a [u8]) -> Self {
NibbleSlice::new_offset(data, 0)
}
/// Create a new nibble slice with the given byte-slice with a nibble offset.
pub fn new_offset(data: &'a [u8], offset: usize) -> Self {
NibbleSlice {
data... | }
impl<'a, 'view> NibbleSlice<'a> | random_line_split |
conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# mediawiki-utilities documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 10 17:31:47 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present ... | exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit t... | # directories to ignore when looking for source files. | random_line_split |
browser_device_modal_error.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test to check that RDM can handle properly an error in the device list
const TEST_URL = "data:text/html;charset=utf-8,";
const Types = require("devtools/client/responsive.html/types");
const { ge... |
addRDMTask(TEST_URL, function* ({ ui }) {
let { store, document } = ui.toolWindow;
let select = document.querySelector(".viewport-device-selector");
// Wait until the viewport has been added and the device list state indicates
// an error
yield waitUntilState(store, state => state.viewports.length == 1
... | add_task(function* () {
yield SpecialPowers.pushPrefEnv({
set: [["devtools.devices.url", TEST_URI_ROOT + "wrong_devices_file.json"]],
});
}); | random_line_split |
common.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... |
pub use self::NodeEnum::{Document, Doctype, Text, Comment, Element};
/// The different kinds of nodes in the DOM.
#[derive(Show)]
pub enum NodeEnum {
/// The `Document` itself.
Document,
/// A `DOCTYPE` with name, public id, and system id.
Doctype(String, String, String),
/// A text node.
Te... |
use collections::vec::Vec;
use collections::string::String;
use string_cache::QualName; | random_line_split |
common.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... | {
/// The `Document` itself.
Document,
/// A `DOCTYPE` with name, public id, and system id.
Doctype(String, String, String),
/// A text node.
Text(String),
/// A comment.
Comment(String),
/// An element with attributes.
Element(QualName, Vec<Attribute>),
}
| NodeEnum | identifier_name |
utils.py | # A Magento 2 module generator library
# Copyright (C) 2016 Maikel Martens
#
# This file is part of Mage2Gen.
#
# Mage2Gen 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
# ... |
def get_field(self, field_name, args, kwargs):
try:
return super().get_field(field_name, args, kwargs)
except (KeyError, AttributeError):
return self.default
def upperfirst(word):
return word[0].upper() + word[1:]
def lowerfirst(word):
return word[0].lower() + word[1:]
| self.default = default | identifier_body |
utils.py | # A Magento 2 module generator library
# Copyright (C) 2016 Maikel Martens
#
# This file is part of Mage2Gen.
#
# Mage2Gen 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
# ... | # along with this program. If not, see <http://www.gnu.org/licenses/>.
import string
class DefaultFormatter(string.Formatter):
def __init__(self, default=''):
self.default = default
def get_field(self, field_name, args, kwargs):
try:
return super().get_field(field_name, args, kwargs)
except (KeyError, At... | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License | random_line_split |
utils.py | # A Magento 2 module generator library
# Copyright (C) 2016 Maikel Martens
#
# This file is part of Mage2Gen.
#
# Mage2Gen 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
# ... | (self, default=''):
self.default = default
def get_field(self, field_name, args, kwargs):
try:
return super().get_field(field_name, args, kwargs)
except (KeyError, AttributeError):
return self.default
def upperfirst(word):
return word[0].upper() + word[1:]
def lowerfirst(word):
return word[0].lower()... | __init__ | identifier_name |
next-prev-pattern.js | import React from "react";
import styled from 'styled-components'
import Link from './link';
const nextArrow = "/icons/next-arrow.png"; | const prevArrow = "/icons/prev-arrow.png";
const PatternLink = styled.span`
width: 100%;
display: flex;
flex-direction: column;
padding: 1em;
float: ${props => props.previous ? 'left' : 'right'}
@media(min-width: $width-tablet) {
width: auto;
}
`;
const ImageContainer = styled.span`
height: 50px;... | random_line_split | |
StreamTableView.js | "use strict";
/*
* ooiui/static/js/views/science/StreamTableView.js
* View definitions to build a table view of streams
*
* Dependencies
* Partials:
* - ooiui/static/js/partials/StreamTable.html
* - ooiui/static/js/partials/StreamTableItem.html
* Libs
* - ooiui/static/lib/underscore/underscore.js
* - ooiui/st... |
this.listenTo(this.model, 'change', this.render);
this.render();
},
onDownload: function(event) {
event.stopPropagation();
event.preventDefault();
var option = $(event.currentTarget).attr("download-type");
ooi.trigger('StreamTableItemView:onClick', {model: this.m... | {
this.columns = options.columns;
} | conditional_block |
StreamTableView.js | "use strict";
/*
* ooiui/static/js/views/science/StreamTableView.js
* View definitions to build a table view of streams
*
* Dependencies
* Partials:
* - ooiui/static/js/partials/StreamTable.html
* - ooiui/static/js/partials/StreamTableItem.html | * - ooiui/static/lib/backbone/backbone.js
* - ooiui/static/js/ooi.js
* Usage
*/
var StreamTableView = Backbone.View.extend({
columns: [
{
name: 'plot',
label: ''
},
{
name: 'download',
label: ''
},
{
name : 'arr... | * Libs
* - ooiui/static/lib/underscore/underscore.js | random_line_split |
nav.ts | import { AfterViewInit, Component, ComponentFactoryResolver, ElementRef, ErrorHandler, Input, NgZone, Optional, Renderer, ViewChild, ViewContainerRef, ViewEncapsulation, forwardRef } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { DeepLinker } from '../../... |
initPane(): boolean {
const isMain = this._elementRef.nativeElement.hasAttribute('main');
return isMain;
}
paneChanged(isPane: boolean) {
if (isPane) {
this.resize();
}
}
goToRoot(opts: NavOptions) {
return this.setRoot(this._root, this.rootParams, opts, null);
}
/*
* @pr... | {
this.destroy();
} | identifier_body |
nav.ts | import { AfterViewInit, Component, ComponentFactoryResolver, ElementRef, ErrorHandler, Input, NgZone, Optional, Renderer, ViewChild, ViewContainerRef, ViewEncapsulation, forwardRef } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { DeepLinker } from '../../... | extends NavControllerBase implements AfterViewInit, RootNode, INav {
private _root: any;
private _hasInit: boolean = false;
constructor(
@Optional() viewCtrl: ViewController,
@Optional() parent: NavController,
app: App,
config: Config,
plt: Platform,
elementRef: ElementRef,
zone: Ng... | Nav | identifier_name |
nav.ts | import { AfterViewInit, Component, ComponentFactoryResolver, ElementRef, ErrorHandler, Input, NgZone, Optional, Renderer, ViewChild, ViewContainerRef, ViewEncapsulation, forwardRef } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { DeepLinker } from '../../... |
if (parent) {
// this Nav has a parent Nav
parent.registerChildNav(this);
} else if (viewCtrl && viewCtrl.getNav()) {
// this Nav was opened from a modal
this.parent = viewCtrl.getNav();
this.parent.registerChildNav(this);
} else if (app && !app.getRootNavById(this.id)) {
... | {
// an ion-nav can also act as an ion-page within a parent ion-nav
// this would happen when an ion-nav nests a child ion-nav.
viewCtrl._setContent(this);
} | conditional_block |
nav.ts | import { AfterViewInit, Component, ComponentFactoryResolver, ElementRef, ErrorHandler, Input, NgZone, Optional, Renderer, ViewChild, ViewContainerRef, ViewEncapsulation, forwardRef } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { DeepLinker } from '../../... | const setUrl = segment ? false : true;
return this.push(this._root, this.rootParams, {
isNavRoot: (<any>this._app.getRootNavById(this.id) === this),
updateUrl: setUrl
}, null);
}
}
/**
* @input {Page} The Page component to load as the root page within this nav.
*/
@Inp... | });
} else if (this._root) {
// no segment match, so use the root property but don't set the url I guess | random_line_split |
CharGenGui.py | (area):
MyChar = GemRB.GetVar ("Slot")
RaceID = GemRB.GetPlayerStat (MyChar, IE_RACE)
RaceIndex = CommonTables.Races.FindValue(3,RaceID)
RaceCap = CommonTables.Races.GetValue(RaceIndex,2)
area.Append(1048,-1) # new line
area.Append(": ")
area.Append(RaceCap)
#class
def unsetClass():
MyChar = GemRB.GetVar ("Slo... | getRace | identifier_name | |
CharGenGui.py | Var ("Slot")
ClassTitle = GUICommon.GetActorClassTitle(MyChar)
area.Append(12136, -1)
area.Append(": ")
area.Append(ClassTitle)
def guardSpecialist():
return GemRB.GetVar("Specialist") == 1
def guardMultiClass():
return GemRB.GetVar("Multi Class") == 1
#Alignment
def unsetAlignment():
MyChar = GemRB.GetVar... | area.Append(": ")
AllignIndex = CommonTables.Aligns.FindValue (3, AllignID)
AllignCap = CommonTables.Aligns.GetValue (AllignIndex, 2)
area.Append(AllignCap)
area.Append("\n")
#Abilties
def unsetAbilities():
MyChar = GemRB.GetVar ("Slot")
AbilityTable = GemRB.LoadTable ("ability")
AbilityCount = AbilityTable.Ge... | def getAlignment(area):
MyChar = GemRB.GetVar ("Slot")
AllignID = GemRB.GetPlayerStat (MyChar, IE_ALIGNMENT)
area.Append(1049, -1) | random_line_split |
CharGenGui.py |
def getGender(area):
MyChar = GemRB.GetVar ("Slot")
area.SetText(12135)
area.Append (": ")
if GemRB.GetPlayerStat(MyChar,IE_SEX) == 1:
return area.Append(1050)
else:
return area.Append(1051)
#race
def unsetRace():
MyChar = GemRB.GetVar ("Slot")
GemRB.SetPlayerStat (MyChar, IE_RACE, 0)
def getRace(area):
... | GemRB.SetToken("SmallPortrait","")
GemRB.SetToken("LargePortrait","") | identifier_body | |
CharGenGui.py | Var ("Slot")
ClassTitle = GUICommon.GetActorClassTitle(MyChar)
area.Append(12136, -1)
area.Append(": ")
area.Append(ClassTitle)
def guardSpecialist():
return GemRB.GetVar("Specialist") == 1
def guardMultiClass():
return GemRB.GetVar("Multi Class") == 1
#Alignment
def unsetAlignment():
MyChar = GemRB.GetVar... |
else:
ClassID = GemRB.GetPlayerStat (MyChar, IE_CLASS)
ClassIndex = CommonTables.Classes.FindValue(5,ClassID)
KitName = CommonTables.Classes.GetRowName(ClassIndex)
for i in range(RowCount):
SkillName = SkillTable.GetRowName(i+2)
if SkillTable.GetValue(SkillName, KitName)==1:
return True
return False
... | KitName = CommonTables.KitList.GetValue(Kit, 0) #rowname is just a number | conditional_block |
profile.py | from datetime import datetime
import cProfile
# Invokes the profiler when processing a query.
# Postprocess results with:
# pyprof2calltree -k -i /tmp/*.pro
#
# or, when kcachegrind is not available, you can also use
# cprofilev -f /tmp/*.pro
# navigate to http://127.0.0.1:4000
class ProfileMiddleware(obj... |
else:
return self.get_response(request)
| profiler = cProfile.Profile()
profiler.enable()
response = self.get_response(request)
profiler.disable()
stamp = request.path.replace("/", "__")
profiler.dump_stats(f'/tmp/{stamp}.pro')
print(f"Dumped profile info in /tmp/{stamp}.pro")
... | conditional_block |
profile.py | from datetime import datetime
import cProfile
# Invokes the profiler when processing a query.
# Postprocess results with:
# pyprof2calltree -k -i /tmp/*.pro
#
# or, when kcachegrind is not available, you can also use
# cprofilev -f /tmp/*.pro
# navigate to http://127.0.0.1:4000
class ProfileMiddleware(obj... | def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if hasattr(request, 'profiler'):
profiler = cProfile.Profile()
profiler.enable()
response = self.get_response(request)
profiler.disable()
sta... | identifier_body | |
profile.py | from datetime import datetime
import cProfile
# Invokes the profiler when processing a query.
# Postprocess results with:
# pyprof2calltree -k -i /tmp/*.pro
#
# or, when kcachegrind is not available, you can also use
# cprofilev -f /tmp/*.pro
# navigate to http://127.0.0.1:4000
class | (object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if hasattr(request, 'profiler'):
profiler = cProfile.Profile()
profiler.enable()
response = self.get_response(request)
profiler.disable()
... | ProfileMiddleware | identifier_name |
profile.py | from datetime import datetime | # Invokes the profiler when processing a query.
# Postprocess results with:
# pyprof2calltree -k -i /tmp/*.pro
#
# or, when kcachegrind is not available, you can also use
# cprofilev -f /tmp/*.pro
# navigate to http://127.0.0.1:4000
class ProfileMiddleware(object):
def __init__(self, get_response):
... | import cProfile
| random_line_split |
run.py | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... |
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
raise RuntimeError("can't find t... | random_line_split | |
run.py | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... |
sys.path.append(os.path.join(path[0], "scripts"))
import TestUtil
print("tests with regular server.")
TestUtil.clientServerTest()
print("tests with collocated server.")
TestUtil.collocatedTest()
| raise RuntimeError("can't find toplevel directory!") | conditional_block |
capacitor.js | define(function(require) {
'use strict';
var PIXI = require('pixi');
var PixiToImage = require('common/v3/pixi/pixi-to-image');
var RectangularComponentView = require('views/components/rectangular');
var Constants = require('constants');
var Assets = require('assets');
/**
... | schematicImagePath: Assets.Images.SCHEMATIC_CAPACITOR,
schematicMaskImagePath: Assets.Images.SCHEMATIC_CAPACITOR_MASK,
/**
* Initializes the new CapacitorView.
*/
initialize: function(options) {
RectangularComponentView.prototype.initialize.apply(this, ... |
imagePath: Assets.Images.CAPACITOR,
maskImagePath: Assets.Images.CAPACITOR_MASK,
| random_line_split |
feed2zinnia.py | """Feed to Zinnia command module"""
import os
import sys
from urllib2 import urlopen
from datetime import datetime
from optparse import make_option
from django.conf import settings
from django.utils import timezone
from django.core.files import File
from django.utils.text import Truncator
from django.utils.html import... | 'module to run this command.')
self.tags = options.get('tags', True)
self.default_author = options.get('author')
self.verbosity = int(options.get('verbosity', 1))
self.auto_excerpt = options.get('auto-excerpt', True)
self.image_enclosure = options.... | try:
import feedparser
except ImportError:
raise CommandError('You need to install the feedparser ' \ | random_line_split |
feed2zinnia.py | """Feed to Zinnia command module"""
import os
import sys
from urllib2 import urlopen
from datetime import datetime
from optparse import make_option
from django.conf import settings
from django.utils import timezone
from django.core.files import File
from django.utils.text import Truncator
from django.utils.html import... |
if self.default_author:
entry.authors.add(self.default_author)
elif feed_entry.get('author_detail'):
try:
user = User.objects.create_user(
slugify(feed_entry.author_detail.get('name')),
feed_ent... | if 'image' in enclosure.get('type') \
and enclosure.get('href'):
img_tmp = NamedTemporaryFile(delete=True)
img_tmp.write(urlopen(enclosure['href']).read())
img_tmp.flush()
entry.image.save(os.path.... | conditional_block |
feed2zinnia.py | """Feed to Zinnia command module"""
import os
import sys
from urllib2 import urlopen
from datetime import datetime
from optparse import make_option
from django.conf import settings
from django.utils import timezone
from django.core.files import File
from django.utils.text import Truncator
from django.utils.html import... | (self, categories):
tags = []
for cat in categories:
if len(cat.title.split()) > 1:
tags.append('"%s"' % slugify(cat.title).replace('-', ' '))
else:
tags.append(slugify(cat.title).replace('-', ' '))
return ', '.join(tags)
| import_tags | identifier_name |
feed2zinnia.py | """Feed to Zinnia command module"""
import os
import sys
from urllib2 import urlopen
from datetime import datetime
from optparse import make_option
from django.conf import settings
from django.utils import timezone
from django.core.files import File
from django.utils.text import Truncator
from django.utils.html import... |
feed = feedparser.parse(url)
self.import_entries(feed.entries)
def import_entries(self, feed_entries):
"""Import entries"""
for feed_entry in feed_entries:
self.write_out('> %s... ' % feed_entry.title)
if feed_entry.get('publised_parsed'):
c... | try:
import feedparser
except ImportError:
raise CommandError('You need to install the feedparser ' \
'module to run this command.')
self.tags = options.get('tags', True)
self.default_author = options.get('author')
self.verbosity = ... | identifier_body |
main.ts | /// <reference path="../src/amd.ts" />
interface Error {
stack: string;
}
namespace test {
function assert(value: boolean) {
if (value !== true) {
const [, , location] = (new Error).stack.split('\n');
throw new Error(`Failed assertion ${location.trim()}`);
}
}
/... | require(['tst/assign-require', 'tst/import-as'], (r: any, i: any) => {
console.log('Test multiple dependencies, all not defined yet...');
assert(r.test() === true);
assert(i.default === true)
console.log("PASSED!\n");
});
// Test mixed sequence of inter-dependent modules
... | console.log('Test multiple dependencies, one already defined...');
assert(m.compare(new m.NumericValue(s.plusOne(4)), m.five) === true);
console.log("PASSED!\n");
});
| random_line_split |
main.ts | /// <reference path="../src/amd.ts" />
interface Error {
stack: string;
}
namespace test {
function | (value: boolean) {
if (value !== true) {
const [, , location] = (new Error).stack.split('\n');
throw new Error(`Failed assertion ${location.trim()}`);
}
}
// Test variants of modules emitted by tsc...
require(['tst/single-export'], (s: any) => {
console.log(... | assert | identifier_name |
main.ts | /// <reference path="../src/amd.ts" />
interface Error {
stack: string;
}
namespace test {
function assert(value: boolean) {
if (value !== true) |
}
// Test variants of modules emitted by tsc...
require(['tst/single-export'], (s: any) => {
console.log('Test single dependency...');
assert(s.plusOne(4) === 5)
console.log("PASSED!\n");
});
require(['tst/multiple-exports', 'tst/single-export'], (m: any, s: any) => {
... | {
const [, , location] = (new Error).stack.split('\n');
throw new Error(`Failed assertion ${location.trim()}`);
} | conditional_block |
main.ts | /// <reference path="../src/amd.ts" />
interface Error {
stack: string;
}
namespace test {
function assert(value: boolean) |
// Test variants of modules emitted by tsc...
require(['tst/single-export'], (s: any) => {
console.log('Test single dependency...');
assert(s.plusOne(4) === 5)
console.log("PASSED!\n");
});
require(['tst/multiple-exports', 'tst/single-export'], (m: any, s: any) => {
c... | {
if (value !== true) {
const [, , location] = (new Error).stack.split('\n');
throw new Error(`Failed assertion ${location.trim()}`);
}
} | identifier_body |
cargo.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = cargo;
var _queue = require('./internal/queue');
var _queue2 = _interopRequireDefault(_queue);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* A cargo of tasks... | (worker, payload) {
return (0, _queue2.default)(worker, 1, payload);
}
module.exports = exports['default']; | cargo | identifier_name |
cargo.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = cargo;
var _queue = require('./internal/queue');
var _queue2 = _interopRequireDefault(_queue);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* A cargo of tasks... | * `worker` is in progress, the task is queued until it becomes available. Once
* the `worker` has completed some tasks, each callback of those tasks is
* called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736... | * Creates a `cargo` object with the specified payload. Tasks added to the
* cargo will be processed altogether (up to the `payload` limit). If the | random_line_split |
cargo.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = cargo;
var _queue = require('./internal/queue');
var _queue2 = _interopRequireDefault(_queue);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* A cargo of tasks... |
module.exports = exports['default']; | {
return (0, _queue2.default)(worker, 1, payload);
} | identifier_body |
node.rs |
use std::convert::From;
use std::io::Write;
use super::serializer::Serializer;
use string_cache::QualName;
pub struct Attr<'a>(&'a QualName, &'a str);
impl<'a> From<(&'a QualName, &'a str)> for Attr<'a> {
fn | ((key, value): (&'a QualName, &'a str)) -> Attr {
Attr(key, value)
}
}
impl<'a, 'b: 'a> From<&'a (&'b QualName, &'b str)> for Attr<'b> {
fn from(&(key, value): &'a (&'b QualName, &'b str)) -> Attr<'b> {
Attr(key, value)
}
}
pub struct NodeSerializer<'a, 'b: 'a, 'w: 'b, W: 'w + Write> {
... | from | identifier_name |
node.rs | use std::convert::From;
use std::io::Write;
use super::serializer::Serializer;
use string_cache::QualName;
pub struct Attr<'a>(&'a QualName, &'a str);
impl<'a> From<(&'a QualName, &'a str)> for Attr<'a> {
fn from((key, value): (&'a QualName, &'a str)) -> Attr {
Attr(key, value)
}
}
impl<'a, 'b: 'a>... | attrs.into_iter().map(|a| {
let a = a.into();
(a.0, a.1)
}));
NodeSerializer {
name: Some(name),
serializer: self.serializer,
}
... | -> NodeSerializer<'a, 'd, 'w, W>
where I: Iterator<Item = II>,
II: Into<Attr<'i>>
{
self.serializer.start_elem(name.clone(), | random_line_split |
node.rs |
use std::convert::From;
use std::io::Write;
use super::serializer::Serializer;
use string_cache::QualName;
pub struct Attr<'a>(&'a QualName, &'a str);
impl<'a> From<(&'a QualName, &'a str)> for Attr<'a> {
fn from((key, value): (&'a QualName, &'a str)) -> Attr {
Attr(key, value)
}
}
impl<'a, 'b: 'a... |
}
pub fn new_node_ser<'a, 'b: 'a, 'w: 'b, W>(s: &'a mut Serializer<'b, 'w, W>)
-> NodeSerializer<'a, 'b, 'w, W>
where W: 'w + Write
{
NodeSerializer {
name: None,
serializer: s,
}
}
| {
match self.name {
Some(ref name) => self.serializer.end_elem(name.clone()),
None => (),
}
} | identifier_body |
radio-button-group.d.ts | import * as React from "react";
import { MarginProps } from "styled-system"; | MarginProps {
/** Breakpoint for adaptive legend (inline labels change to top aligned). Enables the adaptive behaviour when set */
adaptiveLegendBreakpoint?: number;
/** Breakpoint for adaptive spacing (left margin changes to 0). Enables the adaptive behaviour when set */
adaptiveSpacingBreakpoint?: number;... | import { ValidationPropTypes } from "../../__internal__/validations";
export interface RadioButtonGroupProps
extends ValidationPropTypes, | random_line_split |
common-tap.js | var spawn = require('child_process').spawn
var port = exports.port = 1337
exports.registry = "http://localhost:" + port
exports.run = run
function | (cmd, t, opts, cb) {
if (!opts)
opts = {}
if (!Array.isArray(cmd))
throw new Error("cmd must be an Array")
if (!t || !t.end)
throw new Error("node-tap instance is missing")
var stdout = ""
, stderr = ""
, node = process.execPath
, child = spawn(node, cmd, opts)
child.stderr.on("data... | run | identifier_name |
common-tap.js | var spawn = require('child_process').spawn
var port = exports.port = 1337
exports.registry = "http://localhost:" + port
exports.run = run
function run (cmd, t, opts, cb) |
child.on("close", function (code) {
if (cb)
cb(t, stdout, stderr, code, { cmd: cmd, opts: opts })
else
t.end()
})
}
| {
if (!opts)
opts = {}
if (!Array.isArray(cmd))
throw new Error("cmd must be an Array")
if (!t || !t.end)
throw new Error("node-tap instance is missing")
var stdout = ""
, stderr = ""
, node = process.execPath
, child = spawn(node, cmd, opts)
child.stderr.on("data", function (chunk) ... | identifier_body |
common-tap.js | var spawn = require('child_process').spawn
var port = exports.port = 1337
exports.registry = "http://localhost:" + port
exports.run = run
function run (cmd, t, opts, cb) {
if (!opts)
opts = {}
if (!Array.isArray(cmd))
throw new Error("cmd must be an Array")
if (!t || !t.end)
throw new Error("node-ta... | t.end()
})
} | else | random_line_split |
DispersiveRamseyFringes.py | from matplotlib import pyplot as plt, colorbar
from lib2.VNATimeResolvedDispersiveMeasurement2D import *
class DispersiveRamseyFringes(VNATimeResolvedDispersiveMeasurement2D):
def | (self, name, sample_name, **devs_aliases_map):
devs_aliases_map["q_z_awg"] = None
super().__init__(name, sample_name, devs_aliases_map)
self._measurement_result = \
DispersiveRamseyFringesResult(name, sample_name)
self._sequence_generator = IQPulseBuilder.build_dispersive_ram... | __init__ | identifier_name |
DispersiveRamseyFringes.py | from matplotlib import pyplot as plt, colorbar
from lib2.VNATimeResolvedDispersiveMeasurement2D import *
class DispersiveRamseyFringes(VNATimeResolvedDispersiveMeasurement2D):
|
def _output_pulse_sequence(self, ramsey_delay):
self._pulse_sequence_parameters["ramsey_delay"] = ramsey_delay
super()._output_pulse_sequence()
class DispersiveRamseyFringesResult(VNATimeResolvedDispersiveMeasurement2DResult):
def _prepare_data_for_plot(self, data):
return data["exc... | def __init__(self, name, sample_name, **devs_aliases_map):
devs_aliases_map["q_z_awg"] = None
super().__init__(name, sample_name, devs_aliases_map)
self._measurement_result = \
DispersiveRamseyFringesResult(name, sample_name)
self._sequence_generator = IQPulseBuilder.build_di... | identifier_body |
DispersiveRamseyFringes.py | from matplotlib import pyplot as plt, colorbar
from lib2.VNATimeResolvedDispersiveMeasurement2D import *
class DispersiveRamseyFringes(VNATimeResolvedDispersiveMeasurement2D):
def __init__(self, name, sample_name, **devs_aliases_map):
devs_aliases_map["q_z_awg"] = None
super().__init__(name, samp... | super().set_fixed_parameters(pulse_sequence_parameters, **dev_params)
def set_swept_parameters(self, ramsey_delays, excitation_freqs):
q_if_frequency = self._q_awg.get_calibration() \
.get_radiation_parameters()["if_frequency"]
swept_pars = {"ramsey_delay": \
... | random_line_split | |
projection-no-regions-closure.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#![allow(warnings)]
#![feature(rustc_attrs)]
trait Anything { }
impl<T> Anything for T { }
fn with_signature<'a, T, F>(x: Box<T>, op: F) -> Box<dyn Anything + 'a>
where F: FnOnce(Box<T>) -> Box<dyn Anything + 'a>
{
op(x)
}
#[rustc_regions]
fn no_region<'a, T>(x: Box<T>) -> Box<dyn Anything + 'a>
where
... | // Tests closures that propagate an outlives relationship to their
// creator where the subject is a projection with no regions (`<T as
// Iterator>::Item`, to be exact). | random_line_split |
projection-no-regions-closure.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a, T, F>(x: Box<T>, op: F) -> Box<dyn Anything + 'a>
where F: FnOnce(Box<T>) -> Box<dyn Anything + 'a>
{
op(x)
}
#[rustc_regions]
fn no_region<'a, T>(x: Box<T>) -> Box<dyn Anything + 'a>
where
T: Iterator,
{
with_signature(x, |mut y| Box::new(y.next()))
//~^ ERROR the associated type `<T as std::... | with_signature | identifier_name |
projection-no-regions-closure.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[rustc_regions]
fn outlives_region<'a, 'b, T>(x: Box<T>) -> Box<dyn Anything + 'a>
where
T: 'b + Iterator,
'b: 'a,
{
with_signature(x, |mut y| Box::new(y.next()))
}
fn main() {}
| {
with_signature(x, |mut y| Box::new(y.next()))
//~^ ERROR the associated type `<T as std::iter::Iterator>::Item` may not live long enough
} | identifier_body |
base.py | # Copyright 2017 Huawei Technologies Co.,LTD.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... |
pecan.abort(405)
| return controller, remainder | conditional_block |
base.py | # Copyright 2017 Huawei Technologies Co.,LTD.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... |
pecan.abort(405)
| """Routes ``PATCH`` _custom_actions."""
# route to a patch_all or get if no additional parts are available
if not remainder or remainder == ['']:
controller = self._find_controller('patch_all', 'patch')
if controller:
return controller, []
pecan.abort(... | identifier_body |
base.py | # Copyright 2017 Huawei Technologies Co.,LTD.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | if controller and not inspect.ismethod(controller):
return pecan.routing.lookup_controller(controller, remainder[1:])
# route to custom_action
match = self._handle_custom_action(method, remainder, request)
if match:
return match
# finally, check for the r... | if controller:
return controller, []
pecan.abort(404)
controller = getattr(self, remainder[0], None) | random_line_split |
base.py | # Copyright 2017 Huawei Technologies Co.,LTD.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | (rest.RestController):
def _handle_patch(self, method, remainder, request=None):
"""Routes ``PATCH`` _custom_actions."""
# route to a patch_all or get if no additional parts are available
if not remainder or remainder == ['']:
controller = self._find_controller('patch_all', 'pat... | CyborgController | identifier_name |
setup.py | #!/usr/bin/env python
# "convertor" - converts ODF files from a YUSCII font-encoding to proper UTF-8.
# Copyright (C) 2009 Damjan Georgievski
#
# This program 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 S... | # 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/>.
import setuptools
__author__ = 'Damjan Georgievski'
__version__ = '2.0'
__email__ = 'gdamjan@gmail.com'
setuptools.setup(
name = 'convertor',
version = __ver... | random_line_split | |
tissue_classification.py | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Script example of tissue classification
"""
from __future__ import print_function # Python 2/3 compatibility
import numpy as np
from nipy import load_image, save_image
from nipy.... | print('Computing Dice index')
gold_ppm = np.zeros(S.ppm.shape)
gold_ppm_img = (args.probc, args.probg, args.probw)
for k in range(3):
img = load_image(gold_ppm_img[k])
gold_ppm[..., k] = img.get_data()
d = fuzzy_dice(gold_ppm, S.ppm, np.where(mask_img.get_data() > 0))
print('Fuzzy Di... | conditional_block | |
tissue_classification.py | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Script example of tissue classification
"""
from __future__ import print_function # Python 2/3 compatibility
import numpy as np
from nipy import load_image, save_image
from nipy.... |
# Parse command line
description = 'Perform brain tissue classification from skull stripped T1 \
image in CSF, GM and WM. If no mask image is provided, the mask is defined by \
thresholding the input image above zero (strictly).'
parser = ArgumentParser(description=description)
parser.add_argument('img', metavar='i... | """
Fuzzy dice index.
"""
dices = np.zeros(3)
if gold_ppm == None:
return dices
for k in range(3):
pk = gold_ppm[mask][:, k]
qk = ppm[mask][:, k]
PQ = np.sum(np.sqrt(np.maximum(pk * qk, 0)))
P = np.sum(pk)
Q = np.sum(qk)
dices[k] = 2 * PQ / flo... | identifier_body |
tissue_classification.py | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Script example of tissue classification
"""
from __future__ import print_function # Python 2/3 compatibility
import numpy as np
from nipy import load_image, save_image
from nipy.... | (gold_ppm, ppm, mask):
"""
Fuzzy dice index.
"""
dices = np.zeros(3)
if gold_ppm == None:
return dices
for k in range(3):
pk = gold_ppm[mask][:, k]
qk = ppm[mask][:, k]
PQ = np.sum(np.sqrt(np.maximum(pk * qk, 0)))
P = np.sum(pk)
Q = np.sum(qk)
... | fuzzy_dice | identifier_name |
tissue_classification.py | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Script example of tissue classification
"""
from __future__ import print_function # Python 2/3 compatibility
import numpy as np
from nipy import load_image, save_image
from nipy.... | parser.add_argument('img', metavar='img', nargs='+', help='input image')
parser.add_argument('--mask', dest='mask', help='mask image')
parser.add_argument('--niters', dest='niters',
help='number of iterations (default=%d)' % 25)
parser.add_argument('--beta', dest='beta',
help='Markov random field beta parameter... | random_line_split | |
withHeader.ts | import { Request, Middleware } from "./";
export type WithHeaderValue<Req> =
| string
| string[]
| { (request: Req): string | string[] };
/**
* Add a header to the request that can either override, or be overridden
* by, the headers in the request.
*/
export function withHeader<Req extends Request = Request>... | {
// If value isn't a function, make it one
const getValue = (typeof value !== "function" ? () => value : value);
return function (request, next) {
if (typeof request.headers !== "object") {
request.headers = {};
}
if (override) {
request.headers[name] = getValue(request as Req);
} e... | identifier_body | |
withHeader.ts | import { Request, Middleware } from "./";
export type WithHeaderValue<Req> =
| string
| string[]
| { (request: Req): string | string[] };
/**
* Add a header to the request that can either override, or be overridden
* by, the headers in the request.
*/
export function | <Req extends Request = Request>(
name: string,
value: WithHeaderValue<Req>,
override: boolean = false,
): Middleware {
// If value isn't a function, make it one
const getValue = (typeof value !== "function" ? () => value : value);
return function (request, next) {
if (typeof request.headers !== "object... | withHeader | identifier_name |
withHeader.ts | import { Request, Middleware } from "./";
export type WithHeaderValue<Req> =
| string
| string[]
| { (request: Req): string | string[] };
/**
* Add a header to the request that can either override, or be overridden
* by, the headers in the request.
*/
export function withHeader<Req extends Request = Request>... | else {
request.headers = { [name]: getValue(request as Req), ...request.headers };
}
return next();
};
} | {
request.headers[name] = getValue(request as Req);
} | conditional_block |
withHeader.ts | import { Request, Middleware } from "./";
export type WithHeaderValue<Req> =
| string
| string[]
| { (request: Req): string | string[] };
/**
* Add a header to the request that can either override, or be overridden
* by, the headers in the request.
*/
export function withHeader<Req extends Request = Request>... | // If value isn't a function, make it one
const getValue = (typeof value !== "function" ? () => value : value);
return function (request, next) {
if (typeof request.headers !== "object") {
request.headers = {};
}
if (override) {
request.headers[name] = getValue(request as Req);
} els... | ): Middleware { | random_line_split |
handler.spec.js | // THIS TEST WAS GENERATED AUTOMATICALLY ON Wed Dec 07 2016 14:07:23 GMT+0200 (EET)
'use strict';
import chai from 'chai';
import Handler from '../../../../../backend/src/account/unlink-user/Handler';
import Kernel from '../../../node_modules/deep-framework/node_modules/deep-kernel';
import KernelFactory from '../../... | let handler, kernelInstance;
test('Class Handler exists in deep-account-adapter-accounts-unlink-user module', () => {
chai.expect(Handler).to.be.an('function');
});
test('Load Kernel by using Kernel.load()', (done) => {
let callback = (backendKernel) => {
kernelInstance = backendKernel;
c... | // @todo: Add more advanced tests
suite('Handlers', () => { | random_line_split |
unwind.rs | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Stack unwinding
// Implementation of Rust stack unwinding
//
// For background on e... | // Copyright 2013 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 | random_line_split | |
unwind.rs | }
extern fn try_fn(code: *c_void, env: *c_void) {
unsafe {
let closure: || = mem::transmute(Closure {
code: code as *(),
env: env as *(),
});
closure();
}
}
extern {
... | begin_unwind_inner | identifier_name | |
unwind.rs | dr() API and finding all
// .eh_frame sections.
//
// Others, like Windows, require modules to actively register their unwind info
// sections by calling __register_frame_info() API at startup. In the latter
// case it is essential that there is only one copy of the unwinder runtime in
// the process. This is usually... | closure();
}
}
extern {
// Rust's try-catch
// When f(...) returns normally, the return value is null.
// When f(...) throws, the return value is a pointer to the caught
// exception object.
fn rust_try(f: extern "C... | {
use raw::Closure;
use libc::{c_void};
unsafe {
let closure: Closure = mem::transmute(f);
let ep = rust_try(try_fn, closure.code as *c_void,
closure.env as *c_void);
if !ep.is_null() {
rtdebug!("caught {}", (*ep)... | identifier_body |
unwind.rs | dr() API and finding all
// .eh_frame sections.
//
// Others, like Windows, require modules to actively register their unwind info
// sections by calling __register_frame_info() API at startup. In the latter
// case it is essential that there is only one copy of the unwinder runtime in
// the process. This is usually... |
else { // cleanup phase
unsafe {
__gcc_personality_v0(version, actions, exception_class, ue_header,
context)
}
}
}
}
// ARM EHABI uses a slightly different personality routine signature,
// but otherwise works the same.... | { // search phase
uw::_URC_HANDLER_FOUND // catch!
} | conditional_block |
static_priv_by_default.rs | // Copyright 2013 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 ... | () {}
}
mod foo {
pub static a: int = 0;
pub fn b() {}
pub struct c;
pub enum d {}
pub struct A(());
impl A {
fn foo() {}
}
// these are public so the parent can reexport them.
pub static reexported_a: int = 0;
pub fn reexported_b() {}
pub struct reexported_c;
... | foo | identifier_name |
static_priv_by_default.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn b() {}
pub struct c;
pub enum d {}
static i: int = 0;
fn j() {}
struct k;
enum l {} | pub use foo::reexported_d as h;
}
pub static a: int = 0; | random_line_split |
tags.js | and remove forms.
function initVocab() {
$('div.tags[data-tag-vocab-json]').each(
function() {
var $tagContainer = $(this);
var parsedVocab = $tagContainer.data('tag-vocab-json');
$tagContainer.data('tagVocab', _keys(parsedVocab));
}
);
}
// Attach an autocomplete wid... | data: {name: tagName, csrfmiddlewaretoken: csrf},
success: makeTagDisappear,
error: function makeTagReappear() {
$tag.removeClass('in-progress');
}
});
} else {
makeTagDisappear();
}
return false;
}
);
... | {
$container.find('.remover').click(
function() {
var $remover = $(this),
$tag = $remover.closest('.tag'),
tagName = $tag.find('.tag-name').text(),
csrf = $remover.closest('form')
.find('input[name=csrfmiddlewaretoken]').val();
function makeTagDisappear()... | identifier_body |
tags.js | and remove forms.
function initVocab() {
$('div.tags[data-tag-vocab-json]').each(
function() {
var $tagContainer = $(this);
var parsedVocab = $tagContainer.data('tag-vocab-json');
$tagContainer.data('tagVocab', _keys(parsedVocab));
}
);
}
// Attach an autocomplete wid... | (name) {
var $tagList = inputToTagList($input);
if (!(tagIsOnscreen(name, $tagList))) {
var $li = $("<li class='tag'><span class='tag-name' /><input type='submit' value='✖' class='remover' /></li> ");
if (async) {
$li.addClass('in-progress');
} else {
// Ad... | putTagOnscreen | identifier_name |
tags.js | and remove forms.
function initVocab() {
$('div.tags[data-tag-vocab-json]').each(
function() {
var $tagContainer = $(this);
var parsedVocab = $tagContainer.data('tag-vocab-json');
$tagContainer.data('tagVocab', _keys(parsedVocab));
}
);
}
// Attach an autocomplete wid... | else {
$this.find('input.adder').click(handler);
}
});
}
// Given the tag-adding form, return the tag list in the corresponding
// tag-removing form.
function inputToTagList($input) {
return $input.closest('div.tags').find('ul.tag-list');
}
// Case-insensitive array filter
// Rip... | {
$this.submit(handler);
} | conditional_block |
tags.js | // Attach an autocomplete widget to each input.autocomplete-tags. Get
// completion data from the data-tag-vocab attr on the nearest div.tags
// object outside the input.
function initAutoComplete() {
// Return a function() that sets the enabledness of the Add button appropriately.
function makeButtonTe... | return -1;
}
| random_line_split | |
multiple_subjects.py | """
===============================
Multiple subjects pipeline demo
===============================
A basic multiple subjects pipeline. CBF maps are normalized to
the reference MNI template.
"""
import matplotlib.pylab as plt
import nipype.interfaces.spm as spm
from nipype.caching import Memory
from nilearn import pl... | write_voxel_sizes=_utils.get_vox_dims(func_file),
write_interp=2,
jobtype='write')
# Mask CBF map with brain mask
cbf_map = preprocessing.apply_mask(
out_normalize.outputs.normalized_files[0],
out_normalize.outputs.normalized_files[1])
# Plot CBF map on top of MNI t... | out_normalize = normalize(
parameter_file=out_segment.outputs.transformation_mat,
apply_to_files=[out_quantify.outputs.cbf_file,
brain_mask_file], | random_line_split |
multiple_subjects.py | """
===============================
Multiple subjects pipeline demo
===============================
A basic multiple subjects pipeline. CBF maps are normalized to
the reference MNI template.
"""
import matplotlib.pylab as plt
import nipype.interfaces.spm as spm
from nipype.caching import Memory
from nilearn import pl... | segment = mem.cache(spm.Segment)
out_segment = segment(
data=anat_file,
gm_output_type=[True, False, True],
wm_output_type=[True, False, True],
csf_output_type=[True, False, True],
save_bias_corrected=True)
# Coregister anat to mean ASL
coregister_anat = mem.cach... | get_tag_ctl = mem.cache(preprocessing.GetTagControl)
out_get_tag_ctl = get_tag_ctl(in_file=func_file)
# Rescale
rescale = mem.cache(preprocessing.Rescale)
out_rescale = rescale(in_file=out_get_tag_ctl.outputs.tag_ctl_file,
ss_tr=35.4, t_i_1=800., t_i_2=1800.)
# Realign to... | conditional_block |
util.py | # Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions... | indices = [i * q + min(r, i) for i in range(k + 1)]
bins = [samples[indices[i]: indices[i + 1]] for i in range(k)]
bin_ranges = []
counts = []
for i in range(k):
bin_min = bins[i][0]
try:
bin_max = bins[i + 1][0]
except IndexError:
bin_max = bins[i][-1... | """
Bins a collection of univariate samples into k bins of equal
fill via the empirical cdf, to be used in goodness of fit testing.
Returns
counts : array k x 1
bin_ranges : arrary k x 2
each count is the number of samples in [bin_min, bin_max)
except for the last bin which is [bin_min, bi... | identifier_body |
util.py | # Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions... |
return multinomial_goodness_of_fit(probs, counts, len(samples), plot=plot)
def density_goodness_of_fit(samples, probs, plot=False):
"""
Transform arbitrary continuous samples to unif01 distribution
and assess goodness of fit via Pearson's chi^2 test.
Inputs:
samples - a list of real-valu... | counts[int(bin_count * sample)] += 1 | conditional_block |
util.py | # Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions... | (probs, counts):
WIDTH = 60.0
max_count = max(counts)
print '{: >8} {: >8}'.format('Prob', 'Count')
for prob, count in sorted(zip(probs, counts), reverse=True):
width = int(round(WIDTH * count / max_count))
print '{: >8.3f} {: >8d} {}'.format(prob, count, '-' * width)
def multinomial_g... | print_histogram | identifier_name |
util.py | # Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions... | counts[sample] += 1
items = [(prob, counts.get(i, 0)) for i, prob in probs_dict.iteritems()]
items.sort(reverse=True)
truncated = (truncate_beyond and truncate_beyond < len(items))
if truncated:
items = items[:truncate_beyond]
probs = [prob for prob, count in items]
counts = [cou... | random_line_split | |
issue-10465.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 ... | ;
impl A for B { fn foo(&self) {} }
pub mod c {
use b::B;
fn foo(b: &B) {
b.foo(); //~ ERROR: does not implement any method in scope named
}
}
}
fn main() {}
| B | identifier_name |
issue-10465.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 ... |
pub mod c {
use b::B;
fn foo(b: &B) {
b.foo(); //~ ERROR: does not implement any method in scope named
}
}
}
fn main() {} | impl A for B { fn foo(&self) {} } | random_line_split |
issue-10465.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 ... | }
pub mod c {
use b::B;
fn foo(b: &B) {
b.foo(); //~ ERROR: does not implement any method in scope named
}
}
}
fn main() {}
| {} | identifier_body |
ir.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use graphql_ir::*;
use intern::string_key::{StringKey, StringKeyMap, StringKeySet};
use relay_transforms::{DependencyMap, Resolve... | dependency_graph,
base_definition_names,
*parent,
);
}
}
}
// Recursively add all descendants of current node into the `result`
fn add_descendants(
result: &mut StringKeyMap<ExecutableDefinition>,
dependency_graph: &StringKeyMap<Node>,
... | {
if !visited.insert(key) {
return;
}
let parents = match dependency_graph.get(&key) {
None => {
panic!("Fragment {:?} not found in IR.", key);
}
Some(node) => &node.parents,
};
if parents.is_empty() {
if !base_definition_names.contains(&key) {
... | identifier_body |
ir.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use graphql_ir::*;
use intern::string_key::{StringKey, StringKeyMap, StringKeySet};
use relay_transforms::{DependencyMap, Resolve... | (
definitions: Vec<ExecutableDefinition>,
base_definition_names: StringKeySet,
changed_names: StringKeySet,
implicit_dependencies: &DependencyMap,
schema: &SDLSchema,
) -> Vec<ExecutableDefinition> {
if changed_names.is_empty() {
return vec![];
}
// For each executable definitio... | get_reachable_ir | identifier_name |
ir.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use graphql_ir::*;
use intern::string_key::{StringKey, StringKeyMap, StringKeySet};
use relay_transforms::{DependencyMap, Resolve... |
let parents = match dependency_graph.get(&key) {
None => {
panic!("Fragment {:?} not found in IR.", key);
}
Some(node) => &node.parents,
};
if parents.is_empty() {
if !base_definition_names.contains(&key) {
add_descendants(result, dependency_graph, k... | {
return;
} | conditional_block |
ir.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use graphql_ir::*; | use relay_transforms::{DependencyMap, ResolverFieldFinder};
use schema::SDLSchema;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::fmt;
struct Node {
ir: Option<ExecutableDefinition>,
parents: Vec<StringKey>,
children: Vec<StringKey>,
}
impl fmt::Debug for Node {
fn fmt(... | use intern::string_key::{StringKey, StringKeyMap, StringKeySet}; | random_line_split |
closure.rs | use trans::common::*;
use trans::datum::{self, Datum, rvalue_scratch_datum, Rvalue, ByValue};
use trans::debuginfo::{self, DebugLoc};
use trans::declare;
use trans::expr;
use trans::monomorphize::{self, MonoId};
use trans::type_of::*;
use middle::ty::{self, ClosureTyper};
use middle::subst::Substs;
use session::config:... | random_line_split | ||
closure.rs | i, freevar) in freevars.iter().enumerate() {
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: closure_id.node };
let upvar_capture = bcx.tcx().upvar_capture(upvar_id).unwrap();
let mut upvar_ptr = GEPi(bcx, llenv, &[0, i]);
... | <'blk,'tcx>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId)
-> Block<'blk, 'tcx>
{
match self {
ClosureEnv::NotClosure => bcx,
ClosureEnv::Closure(freevars) => {
if freevars.is_empty() {
bcx
} else {
... | load | identifier_name |
script.py | # Copyright (c) 2014 Museum Victoria
# This software is released under the MIT license (see license.txt for details)
from Queue import *
import threading
import atexit
remote_action_PowerOn = RemoteAction()
remote_action_PowerOff = RemoteAction()
remote_action_SetInput = RemoteAction()
def local_action_activate(x = ... |
def stop(self):
self.event.set()
queue = Queue()
th = TimerClass()
@atexit.register
def cleanup():
print 'shutdown'
th.stop()
def main():
th.start()
print 'Nodel script started.' | self.event.wait(1) | conditional_block |
script.py | # Copyright (c) 2014 Museum Victoria
# This software is released under the MIT license (see license.txt for details)
from Queue import *
import threading
import atexit
remote_action_PowerOn = RemoteAction()
remote_action_PowerOff = RemoteAction()
remote_action_SetInput = RemoteAction()
def local_action_activate(x = ... | class TimerClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.event = threading.Event()
def run(self):
while not self.event.isSet():
if queue.empty() != True:
job = queue.get()
try:
print "Calling command " + job['function']
func =... | random_line_split | |
script.py | # Copyright (c) 2014 Museum Victoria
# This software is released under the MIT license (see license.txt for details)
from Queue import *
import threading
import atexit
remote_action_PowerOn = RemoteAction()
remote_action_PowerOff = RemoteAction()
remote_action_SetInput = RemoteAction()
def local_action_activate(x = ... | th.start()
print 'Nodel script started.' | identifier_body | |
script.py | # Copyright (c) 2014 Museum Victoria
# This software is released under the MIT license (see license.txt for details)
from Queue import *
import threading
import atexit
remote_action_PowerOn = RemoteAction()
remote_action_PowerOff = RemoteAction()
remote_action_SetInput = RemoteAction()
def | (x = None):
'''{ "title": "Turn on", "desc": "Turn on." }'''
queue.put({'function': 'remote_action_PowerOn', 'delay': 120})
queue.put({'function': 'remote_action_SetInput', 'arg':{"source":"DIGITAL", "number":1}, 'delay': 5})
print 'Activated'
def local_action_deactivate(x = None):
'''{ "title": "Turn off"... | local_action_activate | identifier_name |
pixel_buffer.rs | /*!
Pixel buffers are buffers that contain two-dimensional texture data.
Contrary to textures, pixel buffers are stored in a client-defined format. They are used
to transfer data to or from the video memory, before or after being turned into a texture.
*/
use std::borrow::Cow;
use std::cell::Cell;
use std::ops::{Deref... |
}
// TODO: remove this hack
#[doc(hidden)]
pub fn store_infos<T>(b: &PixelBuffer<T>, dimensions: (u32, u32)) where T: PixelValue {
b.dimensions.set(Some(dimensions));
}
| {
self.buffer.get_buffer_id()
} | identifier_body |
pixel_buffer.rs | /*!
Pixel buffers are buffers that contain two-dimensional texture data.
Contrary to textures, pixel buffers are stored in a client-defined format. They are used
to transfer data to or from the video memory, before or after being turned into a texture.
*/
use std::borrow::Cow;
use std::cell::Cell;
use std::ops::{Deref... | (&mut self) -> &mut BufferView<[T]> {
&mut self.buffer
}
}
// TODO: rework this
impl<T> GlObject for PixelBuffer<T> where T: PixelValue {
type Id = gl::types::GLuint;
fn get_id(&self) -> gl::types::GLuint {
self.buffer.get_buffer_id()
}
}
// TODO: remove this hack
#[doc(hidden)]
pub f... | deref_mut | identifier_name |
pixel_buffer.rs | /*!
Pixel buffers are buffers that contain two-dimensional texture data.
Contrary to textures, pixel buffers are stored in a client-defined format. They are used
to transfer data to or from the video memory, before or after being turned into a texture.
*/
use std::borrow::Cow;
use std::cell::Cell;
use std::ops::{Deref... | pub struct PixelBuffer<T> where T: PixelValue {
buffer: BufferView<[T]>,
dimensions: Cell<Option<(u32, u32)>>,
}
impl<T> PixelBuffer<T> where T: PixelValue {
/// Builds a new buffer with an uninitialized content.
pub fn new_empty<F>(facade: &F, capacity: usize) -> PixelBuffer<T> where F: Facade {
... | /// Buffer that stores the content of a texture.
///
/// The generic type represents the type of pixels that the buffer contains. | random_line_split |
vtable_writer.rs | /* | *
* 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
* distribut... | * Copyright 2018 Google Inc. All rights reserved. | random_line_split |
vtable_writer.rs | /*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... |
/// Gets an object field offset from the vtable. Only used for debugging.
///
/// Note that this expects field offsets (which are like pointers), not
/// field ids (which are like array indices).
#[inline(always)]
pub fn get_field_offset(&self, vtable_offset: VOffsetT) -> VOffsetT {
le... | {
emplace_scalar::<VOffsetT>(&mut self.buf[SIZE_VOFFSET..2 * SIZE_VOFFSET], n);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.