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 |
|---|---|---|---|---|
calendar.js | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//<script>
$(document).ready(function() {
var curSource = "/alliance/dutylist/calendarsearch";
$('#dutylsitCale... | identifier_name | ||
calendar.js | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//<script>
$(document).ready(function() {
var curSource = "/alliance/dutylist/calendarsearch";
$('#dutylsitCale... | lse,
// includeSelectAllOption: true,
// nonSelectedText: 'Статус',
// }); | identifier_body | |
jowa_4.py | """
Jowa Header, Code # 4
Battery Voltage
"""
### INCLUDES ###
from common import JOWA_BATT_THRESHOLD, LOW_BATTERY
### CONSTANTS ###
## Battery Voltage Units and Variables ##
# Battery voltage calculation notes:
# Vbat = ((R5+R4)/R5)*Vch3 = (2*R/R)*Vch3 =
# 2*Vch3 = 2*(ADC/ADCmax)*Vref
# Where:
# Vref, ADC Voltage... | } | 'diagnostics': True | random_line_split |
ProductList.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { AppState } from '../../app.service';
import { isUndefined } from 'util'
import { ProductsService } from '../../services/products.service';
import { CategoriesEventsService } from '../../services/CategoryEvents.service'
import { Product, P... | })
export class ProductListComponent implements OnInit, OnDestroy {
public products: Product[];
public categoryHeading: String;
constructor(
public appState : AppState,
public productsService : ProductsService,
private categoryChangeEvent: CategoriesEventsServi... | templateUrl: './ProductList.component.html'
| random_line_split |
ProductList.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { AppState } from '../../app.service';
import { isUndefined } from 'util'
import { ProductsService } from '../../services/products.service';
import { CategoriesEventsService } from '../../services/CategoryEvents.service'
import { Product, P... | implements OnInit, OnDestroy {
public products: Product[];
public categoryHeading: String;
constructor(
public appState : AppState,
public productsService : ProductsService,
private categoryChangeEvent: CategoriesEventsService
){}
private _subscript... | ProductListComponent | identifier_name |
greaterThanOrEqualExpression.ts | module Facet {
export class GreaterThanOrEqualExpression extends BinaryExpression {
static fromJS(parameters: ExpressionJS): GreaterThanOrEqualExpression {
return new GreaterThanOrEqualExpression(BinaryExpression.jsToValue(parameters));
}
constructor(parameters: ExpressionValue) {
super(param... | return `${this.lhs.toString()} = ${this.rhs.toString()}`;
}
protected _specialSimplify(simpleLhs: Expression, simpleRhs: Expression): Expression {
return (new LessThanOrEqualExpression({
op: 'lessThanOrEqual',
lhs: simpleRhs,
rhs: simpleLhs
})).simplify()
}
pr... | random_line_split | |
greaterThanOrEqualExpression.ts | module Facet {
export class GreaterThanOrEqualExpression extends BinaryExpression {
static fromJS(parameters: ExpressionJS): GreaterThanOrEqualExpression {
return new GreaterThanOrEqualExpression(BinaryExpression.jsToValue(parameters));
}
constructor(parameters: ExpressionValue) {
super(param... |
protected _getFnHelper(lhsFn: ComputeFn, rhsFn: ComputeFn): ComputeFn {
return (d: Datum) => lhsFn(d) >= rhsFn(d);
}
protected _getJSExpressionHelper(lhsFnJS: string, rhsFnJS: string): string {
return `(${lhsFnJS}>=${rhsFnJS})`;
}
protected _getSQLHelper(lhsSQL: string, rhsSQL: strin... | {
return (new LessThanOrEqualExpression({
op: 'lessThanOrEqual',
lhs: simpleRhs,
rhs: simpleLhs
})).simplify()
} | identifier_body |
greaterThanOrEqualExpression.ts | module Facet {
export class GreaterThanOrEqualExpression extends BinaryExpression {
static | (parameters: ExpressionJS): GreaterThanOrEqualExpression {
return new GreaterThanOrEqualExpression(BinaryExpression.jsToValue(parameters));
}
constructor(parameters: ExpressionValue) {
super(parameters, dummyObject);
this._ensureOp("greaterThanOrEqual");
this._checkMatchingTypes();
... | fromJS | identifier_name |
Chart.Bar.js | except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
... |
this.scale = new this.ScaleClass(scaleOptions);
},
addData : function(valuesArray,label){
//Map the values array for each of the datasets
helpers.each(valuesArray,function(value,datasetIndex){
//Add a new point for each piece of data, passing any required data to draw.
this.datasets[datasetIndex]... | {
helpers.extend(scaleOptions, {
calculateYRange: helpers.noop,
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
});
} | conditional_block |
Chart.Bar.js | except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
... | font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
lineWidth : this.options.scaleLineWidth,
lineColor : this.options.scaleLineColor,
showHorizontalLines : this.options.scaleShowHorizontalLines,
showVerticalLines : this.options.scaleShowV... | },
xLabels : labels, | random_line_split |
update_interrupt_create.py | def check_resource_count(expected_count):
|
example_template = Template({
'A': RsrcDef({}, []),
'B': RsrcDef({'a': '4alpha'}, ['A']),
'C': RsrcDef({'a': 'foo'}, ['B']),
'D': RsrcDef({'a': 'bar'}, ['C']),
})
engine.create_stack('foo', example_template)
engine.noop(1)
example_template2 = Template({
'A': RsrcDef({}, []),
'B': RsrcDef({'a'... | test.assertEqual(expected_count, len(reality.all_resources())) | identifier_body |
update_interrupt_create.py | def | (expected_count):
test.assertEqual(expected_count, len(reality.all_resources()))
example_template = Template({
'A': RsrcDef({}, []),
'B': RsrcDef({'a': '4alpha'}, ['A']),
'C': RsrcDef({'a': 'foo'}, ['B']),
'D': RsrcDef({'a': 'bar'}, ['C']),
})
engine.create_stack('foo', example_template)
engine.noo... | check_resource_count | identifier_name |
update_interrupt_create.py | def check_resource_count(expected_count):
test.assertEqual(expected_count, len(reality.all_resources()))
example_template = Template({
'A': RsrcDef({}, []),
'B': RsrcDef({'a': '4alpha'}, ['A']),
'C': RsrcDef({'a': 'foo'}, ['B']),
'D': RsrcDef({'a': 'bar'}, ['C']),
})
engine.create_stack('foo', exam... | engine.call(check_resource_count, 2)
engine.noop(11)
engine.call(verify, example_template2) | 'B': RsrcDef({'a': '4alpha'}, ['A']),
'C': RsrcDef({'a': 'blarg'}, ['B']),
'D': RsrcDef({'a': 'wibble'}, ['C']),
})
engine.update_stack('foo', example_template2) | random_line_split |
GenericWrapper.js | import TriggerableMixin from '../Common/TriggerableMixin.js';
import Introspectable from '../Common/Introspectable.js';
class GenericWrapper extends TriggerableMixin(Introspectable) {
constructor (options) {
super();
this.index = options.index;
this.table = options.table;
if (this.index === undefined... | (tableIds) {
// First make sure that all the table caches have been fully built and
// connected
await Promise.all(tableIds.map(tableId => {
return this.classObj.model.tables[tableId].buildCache();
}));
yield * this._iterateAcrossConnections(tableIds);
}
* _iterateAcrossConnections (table... | iterateAcrossConnections | identifier_name |
GenericWrapper.js | import TriggerableMixin from '../Common/TriggerableMixin.js';
import Introspectable from '../Common/Introspectable.js';
class GenericWrapper extends TriggerableMixin(Introspectable) {
constructor (options) {
super();
this.index = options.index;
this.table = options.table;
if (this.index === undefined... | for (const itemList of Object.values(this.connectedItems)) {
for (const item of itemList) {
const index = (item.connectedItems[this.table.tableId] || []).indexOf(this);
if (index !== -1) {
item.connectedItems[this.table.tableId].splice(index, 1);
}
}
}
this.conn... | item.connectItem(dup);
dup.connectItem(item);
}
}
disconnect () { | random_line_split |
GenericWrapper.js | import TriggerableMixin from '../Common/TriggerableMixin.js';
import Introspectable from '../Common/Introspectable.js';
class GenericWrapper extends TriggerableMixin(Introspectable) {
constructor (options) {
super();
this.index = options.index;
this.table = options.table;
if (this.index === undefined... |
get exportId () {
return `${this.classObj.classId}_${this.index}`;
}
get label () {
return this.classObj.annotations.labelAttr ? this.row[this.classObj.annotations.labelAttr] : this.index;
}
equals (item) {
return this.instanceId === item.instanceId;
}
async * handleLimit (options, iterators)... | {
return `{"classId":"${this.classObj.classId}","index":"${this.index}"}`;
} | identifier_body |
GenericWrapper.js | import TriggerableMixin from '../Common/TriggerableMixin.js';
import Introspectable from '../Common/Introspectable.js';
class GenericWrapper extends TriggerableMixin(Introspectable) {
constructor (options) {
super();
this.index = options.index;
this.table = options.table;
if (this.index === undefined... |
const nextTableId = tableIds[0];
if (tableIds.length === 1) {
yield * (this.connectedItems[nextTableId] || []);
} else {
const remainingTableIds = tableIds.slice(1);
for (const item of this.connectedItems[nextTableId] || []) {
yield * item._iterateAcrossConnections(remainingTableI... | {
return;
} | conditional_block |
step_by.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// This module jus... |
}
| {
StepUp {
next: self.start,
end: self.end,
ammount: ammount
}
} | identifier_body |
step_by.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// This module jus... | else {
None
}
}
}
pub trait RangeExt<T> {
fn step_up(self, ammount: T) -> StepUp<T>;
}
impl <T> RangeExt<T> for Range<T> where
T: Add<T, Output = T> + PartialOrd + Copy {
fn step_up(self, ammount: T) -> StepUp<T> {
StepUp {
next: self.start,
end... | {
let n = self.next;
self.next = self.next + self.ammount;
Some(n)
} | conditional_block |
step_by.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// This module jus... | T: Add<T, Output = T> + PartialOrd + Copy {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
if self.next < self.end {
let n = self.next;
self.next = self.next + self.ammount;
Some(n)
} else {
None
}
}
}
pub trai... | end: T,
ammount: T
}
impl <T> Iterator for StepUp<T> where | random_line_split |
step_by.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// This module jus... | <T> {
next: T,
end: T,
ammount: T
}
impl <T> Iterator for StepUp<T> where
T: Add<T, Output = T> + PartialOrd + Copy {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
if self.next < self.end {
let n = self.next;
self.next = self.next + self.amm... | StepUp | identifier_name |
CollapsibleMixin.js | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import deprecationWarning from './utils/deprecationWarning';
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState() {
const defaultExpanded... | ,
// helps enable test stubs
_afterWillUpdate() {
},
_checkStartAnimation() {
if (!this.state.collapsing) {
return;
}
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = this.getCollapsibleDimensionValue();
// setting the dimension here starts... | {
// check if expanded is being toggled; if so, set collapsing
this._checkToggleCollapsing(prevProps, prevState);
// check if collapsing was turned on; if so, start animation
this._checkStartAnimation();
} | identifier_body |
CollapsibleMixin.js | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import deprecationWarning from './utils/deprecationWarning';
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState() {
const defaultExpanded... | _handleCollapse() {
let node = this.getCollapsibleDOMNode();
let complete = () => {
this._removeEndEventListener(node, complete);
this.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
... | },
| random_line_split |
CollapsibleMixin.js | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import deprecationWarning from './utils/deprecationWarning';
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState() {
const defaultExpanded... | (prevProps, prevState) {
let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
let isExpanded = this.isExpanded();
if (wasExpanded !== isExpanded) {
if (wasExpanded) {
this._handleCollapse();
} else {
this._handleExpand();
}
}
},
_... | _checkToggleCollapsing | identifier_name |
CollapsibleMixin.js | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import deprecationWarning from './utils/deprecationWarning';
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState() {
const defaultExpanded... | else {
result = '0px';
}
node.style[dimension] = result;
},
_checkToggleCollapsing(prevProps, prevState) {
let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
let isExpanded = this.isExpanded();
if (wasExpanded !== isExpanded) {
if (wasExpanded) ... | {
result = value + 'px';
} | conditional_block |
kubes-header.component.ts | import { Component, OnDestroy, AfterViewInit } from '@angular/core';
import { KubesService } from '../kubes.service';
import { Supergiant } from '../../shared/supergiant/supergiant.service';
import { Subscription } from 'rxjs/Subscription';
import { Notifications } from '../../shared/notifications/notifications.service... | (model, data) {
this.notifications.display(
'error',
'Kube: ' + model.name,
'Error:' + data.statusText);
}
sendOpen(message) {
let providers = [];
providers = this.cloudAccountsList.map((resource) => resource.name);
this.dropdownModalService.open('New Kube', 'Provider', providers)... | error | identifier_name |
kubes-header.component.ts | import { Component, OnDestroy, AfterViewInit } from '@angular/core';
import { KubesService } from '../kubes.service';
import { Supergiant } from '../../shared/supergiant/supergiant.service';
import { Subscription } from 'rxjs/Subscription';
import { Notifications } from '../../shared/notifications/notifications.service... | else {
for (const provider of selectedItems) {
this.subscriptions.add(this.supergiant.Kubes.delete(provider.id).subscribe(
(data) => {
this.notifications.display('success', 'Kube: ' + provider.name, 'Deleted...');
this.kubesService.resetSelected();
},
... | {
this.notifications.display('warn', 'Warning:', 'No Kube Selected.');
} | conditional_block |
kubes-header.component.ts | import { Component, OnDestroy, AfterViewInit } from '@angular/core';
import { KubesService } from '../kubes.service';
import { Supergiant } from '../../shared/supergiant/supergiant.service';
import { Subscription } from 'rxjs/Subscription';
import { Notifications } from '../../shared/notifications/notifications.service... |
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
setSearch(value) {
this.kubesService.searchString = value;
}
// After init, grab the schema
ngAfterViewInit() {
this.subscriptions.add(this.supergiant.CloudAccounts.get().subscribe(
(data) => { this.cloudAccountsList = data.items; }
... | { } | identifier_body |
kubes-header.component.ts | import { Component, OnDestroy, AfterViewInit } from '@angular/core';
import { KubesService } from '../kubes.service';
import { Supergiant } from '../../shared/supergiant/supergiant.service';
import { Subscription } from 'rxjs/Subscription';
import { Notifications } from '../../shared/notifications/notifications.service... | }
success(model) {
this.notifications.display(
'success',
'Kube: ' + model.name,
'Created...',
);
}
error(model, data) {
this.notifications.display(
'error',
'Kube: ' + model.name,
'Error:' + data.statusText);
}
sendOpen(message) {
let providers = [];
... | (err) => { this.error(model, err); }));
}
}
})); | random_line_split |
02-constraint.py | from __future__ import print_function
from __future__ import unicode_literals
from builtins import str, bytes, dict, int
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from pattern.search import search, Pattern, Constraint
from pattern.en import parsetree, parse, Sentenc... |
print("")
print("-------------------------------------------------------------")
# Finally, constraints can also include regular expressions.
# To include them we need to use the full syntax instead of the search() function:
import re
r = re.compile(r"[0-9|\.]+") # all numbers
p = Pattern()
p.sequence.append(Constrai... | print("%s\t=> %s" % (w, m[0].constraint(w))) | conditional_block |
02-constraint.py | from __future__ import print_function
from __future__ import unicode_literals
from builtins import str, bytes, dict, int
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from pattern.search import search, Pattern, Constraint
from pattern.en import parsetree, parse, Sentenc... | p.sequence.append(Constraint(words=[r]))
p.sequence.append(Constraint(tags=["NN*"]))
s = Sentence(parse("I have 9.5 rabbits."))
print(s)
print(p.search(s))
print("") | r = re.compile(r"[0-9|\.]+") # all numbers
p = Pattern() | random_line_split |
wikiconfig.py | # -*- coding: iso-8859-1 -*-
"""MoinMoin Desktop Edition (MMDE) - Configuration
ONLY to be used for MMDE - if you run a personal wiki on your notebook or PC.
This is NOT intended for internet or server or multiuser use due to relaxed security settings!
"""
import sys, os
from MoinMoin.config import multiconfig, url... |
Config = LocalConfig
| raise | conditional_block |
wikiconfig.py | # -*- coding: iso-8859-1 -*-
"""MoinMoin Desktop Edition (MMDE) - Configuration
ONLY to be used for MMDE - if you run a personal wiki on your notebook or PC.
This is NOT intended for internet or server or multiuser use due to relaxed security settings!
"""
import sys, os
from MoinMoin.config import multiconfig, url... | (multiconfig.DefaultConfig):
# vvv DON'T TOUCH THIS EXCEPT IF YOU KNOW WHAT YOU DO vvv
# Directory containing THIS wikiconfig:
wikiconfig_dir = os.path.abspath(os.path.dirname(__file__))
# We assume this structure for a simple "unpack and run" scenario:
# wikiconfig.py
# wiki/
# data/
... | LocalConfig | identifier_name |
wikiconfig.py | # -*- coding: iso-8859-1 -*-
"""MoinMoin Desktop Edition (MMDE) - Configuration
ONLY to be used for MMDE - if you run a personal wiki on your notebook or PC.
This is NOT intended for internet or server or multiuser use due to relaxed security settings!
"""
import sys, os
from MoinMoin.config import multiconfig, url... | surge_action_limits = None # no surge protection
sitename = u'MoinMoin DesktopEdition'
logo_string = u'<img src="%s/common/moinmoin.png" alt="MoinMoin Logo">' % url_prefix_static
# ^^^ DON'T TOUCH THIS EXCEPT IF YOU KNOW WHAT YOU DO ^^^
#page_front_page = u'FrontPage' # change to some better value
... | wikiconfig_dir = os.path.abspath(os.path.dirname(__file__))
# We assume this structure for a simple "unpack and run" scenario:
# wikiconfig.py
# wiki/
# data/
# underlay/
# If that's not true, feel free to just set instance_dir to the real path
# where data/ and underlay/ is locat... | identifier_body |
wikiconfig.py | # -*- coding: iso-8859-1 -*-
"""MoinMoin Desktop Edition (MMDE) - Configuration
ONLY to be used for MMDE - if you run a personal wiki on your notebook or PC.
This is NOT intended for internet or server or multiuser use due to relaxed security settings!
"""
import sys, os
from MoinMoin.config import multiconfig, url... | # wikiconfig.py
# wiki/
# data/
# underlay/
# If that's not true, feel free to just set instance_dir to the real path
# where data/ and underlay/ is located:
#instance_dir = '/where/ever/your/instance/is'
instance_dir = os.path.join(wikiconfig_dir, 'wiki')
# Where your own... | # vvv DON'T TOUCH THIS EXCEPT IF YOU KNOW WHAT YOU DO vvv
# Directory containing THIS wikiconfig:
wikiconfig_dir = os.path.abspath(os.path.dirname(__file__))
# We assume this structure for a simple "unpack and run" scenario: | random_line_split |
example_8.js | var example_8 = switcher.items({eventMethod: "mouseover"});
// Табы
example_8.addTabs('#tab_7 span', function () {
this.classList.add('tab_active');
}, function () {
this.classList.remove('tab_active');
});
// Блоки
example_8.addBlocks('#block_7 img', function() {
| this.style.opacity = 0;
this.style.display = "block";
// Удаляем таймер от предыдущего элемента, если есть
clearInterval(example_8.varTimer);
// Таймер
example_8.varTimer = setInterval(function() {
if(i >= 1) {
clearInterval(example_8.varTimer);
}
i+=0.1;
that.style.opacity = i;
}, 50);
}... | var
i=0,
that = this;
| random_line_split |
example_8.js | var example_8 = switcher.items({eventMethod: "mouseover"});
// Табы
example_8.addTabs('#tab_7 span', function () {
this.classList.add('tab_active');
}, function () {
this.classList.remove('tab_active');
});
// Блоки
example_8.addBlocks('#block_7 img', function() {
var
i=0,
that = this;
this.style.opacit... | nction() {
this.style.display = "none";
});
example_8.turnOn(4); | that.style.opacity = i;
}, 50);
}, fu | conditional_block |
kqueue.rs | (not(target_os = "netbsd"))]
type UData = *mut ::libc::c_void;
#[cfg(not(target_os = "netbsd"))]
type Count = c_int;
#[cfg(target_os = "netbsd")]
type Filter = u32;
#[cfg(target_os = "netbsd")]
type UData = ::libc::intptr_t;
#[cfg(target_os = "netbsd")]
type Count = usize;
macro_rules! kevent {
($id: expr, $filte... |
#[inline]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn get(&self, idx: usize) -> Option<Event> {
self.events.get(idx).map(|e| *e)
}
fn coalesce(&mut self, awakener: Token) -> bool {
let mut ret = false;
self.events.clear();
self.eve... | {
self.events.capacity()
} | identifier_body |
kqueue.rs | (not(target_os = "netbsd"))]
type UData = *mut ::libc::c_void;
#[cfg(not(target_os = "netbsd"))]
type Count = c_int;
#[cfg(target_os = "netbsd")]
type Filter = u32;
#[cfg(target_os = "netbsd")]
type UData = ::libc::intptr_t;
#[cfg(target_os = "netbsd")]
type Count = usize;
macro_rules! kevent {
($id: expr, $filte... |
for change in changes.iter() {
debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR);
if change.data != 0 && change.data as i32 != libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
... | {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
} | conditional_block |
kqueue.rs | cfg(not(target_os = "netbsd"))]
type UData = *mut ::libc::c_void;
#[cfg(not(target_os = "netbsd"))]
type Count = c_int;
#[cfg(target_os = "netbsd")]
type Filter = u32;
#[cfg(target_os = "netbsd")]
type UData = ::libc::intptr_t;
#[cfg(target_os = "netbsd")]
type Count = usize;
macro_rules! kevent {
($id: expr, $fi... | unsafe {
let _ = libc::close(self.kq);
}
}
}
pub struct Events {
sys_events: KeventList,
events: Vec<Event>,
event_map: HashMap<Token, usize>,
}
struct KeventList(Vec<libc::kevent>);
unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}
impl Events {
p... | }
impl Drop for Selector {
fn drop(&mut self) { | random_line_split |
kqueue.rs | cfg(not(target_os = "netbsd"))]
type UData = *mut ::libc::c_void;
#[cfg(not(target_os = "netbsd"))]
type Count = c_int;
#[cfg(target_os = "netbsd")]
type Filter = u32;
#[cfg(target_os = "netbsd")]
type UData = ::libc::intptr_t;
#[cfg(target_os = "netbsd")]
type Count = usize;
macro_rules! kevent {
($id: expr, $fi... | (Vec<libc::kevent>);
unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}
impl Events {
pub fn with_capacity(cap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capa... | KeventList | identifier_name |
asyncio.py | # -*- coding: iso-8859-1 -*-
ur"""AsyncIO objects wrap the Win32 Overlapped API. They are instantiated by
passing a handle which has been opened for Overlapped IO. They can be waited
on by the functions in the :mod:`ipc` module and are True when complete,
False otherwise.
"""
import pywintypes
import winerror
i... |
class AsyncWriter (AsyncHandler):
def __init__ (self, handle, data):
AsyncHandler.__init__ (self, handle)
self.data = data
wrapped (win32file.WriteFile, self.handle, data, self.overlapped)
class AsyncReader (AsyncHandler):
BUFFER_SIZE = 4096
def __init__ (self, handle):
AsyncHand... | self.handle = handle
| random_line_split |
asyncio.py | # -*- coding: iso-8859-1 -*-
ur"""AsyncIO objects wrap the Win32 Overlapped API. They are instantiated by
passing a handle which has been opened for Overlapped IO. They can be waited
on by the functions in the :mod:`ipc` module and are True when complete,
False otherwise.
"""
import pywintypes
import winerror
i... |
class AsyncHandler (AsyncIO):
BUFFER_SIZE = 4096
def __init__ (self, handle, buffer_size=BUFFER_SIZE):
AsyncIO.__init__ (self)
self.handle = handle
class AsyncWriter (AsyncHandler):
def __init__ (self, handle, data):
AsyncHandler.__init__ (self, handle)
self.data = data
wr... | pass | conditional_block |
asyncio.py | # -*- coding: iso-8859-1 -*-
ur"""AsyncIO objects wrap the Win32 Overlapped API. They are instantiated by
passing a handle which has been opened for Overlapped IO. They can be waited
on by the functions in the :mod:`ipc` module and are True when complete,
False otherwise.
"""
import pywintypes
import winerror
i... |
class AsyncWriter (AsyncHandler):
def __init__ (self, handle, data):
AsyncHandler.__init__ (self, handle)
self.data = data
wrapped (win32file.WriteFile, self.handle, data, self.overlapped)
class AsyncReader (AsyncHandler):
BUFFER_SIZE = 4096
def __init__ (self, handle):
AsyncHa... | BUFFER_SIZE = 4096
def __init__ (self, handle, buffer_size=BUFFER_SIZE):
AsyncIO.__init__ (self)
self.handle = handle | identifier_body |
asyncio.py | # -*- coding: iso-8859-1 -*-
ur"""AsyncIO objects wrap the Win32 Overlapped API. They are instantiated by
passing a handle which has been opened for Overlapped IO. They can be waited
on by the functions in the :mod:`ipc` module and are True when complete,
False otherwise.
"""
import pywintypes
import winerror
i... | (exc.x_winsys):
pass
WINERROR_MAP = {
}
wrapped = exc.wrapper (WINERROR_MAP, x_asyncio)
class AsyncIO (core._WinSysObject):
def __init__ (self):
core._WinSysObject.__init__ (self)
self.event = ipc.event (needs_manual_reset=True)
self.overlapped = wrapped (win32file.OVERLAPPED)
self.... | x_asyncio | identifier_name |
theme.js | $("#menu-close").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
$(function() { | if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
... | $('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() { | random_line_split |
theme.js | $("#menu-close").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
$(function() {
$('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function()... |
}
});
});
var fixed = false;
$(document).scroll(function() {
if ($(this).scrollTop() > 250) {
if (!fixed) {
fixed = true;
$('#to-top').show("slow", function() {
$('#to-top').css({
position: 'fixed',
display: 'block'
});
});
}
} else {
if (fixed) {
fixed = false;
$('#to-top')... | {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
} | conditional_block |
snoop.rs | //! Snoop plugin that exposes metrics on a local socket.
use errors::*;
use plugin::*;
use metric::*;
use std::collections::HashMap;
use std::sync::{Mutex, Arc};
use std::net::SocketAddr;
use tokio_io::{io, AsyncRead};
use tokio_core::net;
use futures::{sync, Future};
use futures::stream::Stream;
use std::convert::As... | () -> Result<Box<Output>> {
Ok(Box::new(SnoopOutput {}))
}
#[derive(Clone)]
pub struct Message(Arc<Box<[u8]>>);
impl AsRef<[u8]> for Message {
fn as_ref(&self) -> &[u8] {
let &Message(ref a) = self;
&a
}
}
| output | identifier_name |
snoop.rs | //! Snoop plugin that exposes metrics on a local socket.
use errors::*;
use plugin::*;
use metric::*;
use std::collections::HashMap; | use futures::stream::Stream;
use std::convert::AsRef;
use std::fmt;
use serde_json;
#[derive(Deserialize, Debug)]
struct SnoopInputConfig {
bind: Option<SocketAddr>,
}
#[derive(Debug)]
struct SnoopOutput {}
fn report_and_discard<E: fmt::Display>(e: E) -> () {
info!("An error occured: {}", e);
}
type Sender ... | use std::sync::{Mutex, Arc};
use std::net::SocketAddr;
use tokio_io::{io, AsyncRead};
use tokio_core::net;
use futures::{sync, Future}; | random_line_split |
modes.js | import { inherit } from './utils.js';
import * as regex from './regex.js';
/** @typedef {import('highlight.js').Mode} Mode */
/** @typedef {import('highlight.js').ModeCallback} ModeCallback */
// Common regexps
export const MATCH_NOTHING_RE = /\b\B/;
export const IDENT_RE = '[a-zA-Z]\\w*';
export const UNDERSCORE_IDE... |
return inherit({
scope: 'meta',
begin: beginShebang,
end: /$/,
relevance: 0,
/** @type {ModeCallback} */
"on:begin": (m, resp) => {
if (m.index !== 0) resp.ignoreMatch();
}
}, opts);
};
// Common modes
export const BACKSLASH_ESCAPE = {
begin: '\\\\[\\s\\S]', relevance: 0
};
exp... | {
opts.begin = regex.concat(
beginShebang,
/.*\b/,
opts.binary,
/\b.*/);
} | conditional_block |
modes.js | import { inherit } from './utils.js';
import * as regex from './regex.js';
/** @typedef {import('highlight.js').Mode} Mode */
/** @typedef {import('highlight.js').ModeCallback} ModeCallback */
// Common regexps
export const MATCH_NOTHING_RE = /\b\B/;
export const IDENT_RE = '[a-zA-Z]\\w*';
export const UNDERSCORE_IDE... | * @param {string | RegExp} begin
* @param {string | RegExp} end
* @param {Mode | {}} [modeOptions]
* @returns {Partial<Mode>}
*/
export const COMMENT = function(begin, end, modeOptions = {}) {
const mode = inherit(
{
scope: 'comment',
begin,
end,
contains: []
},
modeOptions
... | * | random_line_split |
test_context.py | import typing as t
import contextlib
import pytest
import diana
State = t.NewType("State", dict)
AsyncState = t.NewType("AsyncState", dict)
async def no_op():
pass
@pytest.fixture
def module():
class ContextModule(diana.Module):
def __init__(self):
self.state: State = {"count": 0}
... |
@pytest.mark.asyncio
async def test_within_context_async(injector):
@injector
async def uses_state(*, state: AsyncState):
assert state["count"] != 0
await uses_state()
| @injector
def uses_state(*, state: State):
assert state["count"] != 0
uses_state() | identifier_body |
test_context.py | import typing as t
import contextlib
import pytest
import diana
State = t.NewType("State", dict)
AsyncState = t.NewType("AsyncState", dict)
async def no_op(): |
@pytest.fixture
def module():
class ContextModule(diana.Module):
def __init__(self):
self.state: State = {"count": 0}
@diana.contextprovider
@contextlib.contextmanager
def provide(self) -> State:
self.state["count"] += 1
yield self.state
... | pass | random_line_split |
test_context.py | import typing as t
import contextlib
import pytest
import diana
State = t.NewType("State", dict)
AsyncState = t.NewType("AsyncState", dict)
async def | ():
pass
@pytest.fixture
def module():
class ContextModule(diana.Module):
def __init__(self):
self.state: State = {"count": 0}
@diana.contextprovider
@contextlib.contextmanager
def provide(self) -> State:
self.state["count"] += 1
yield self.... | no_op | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | # variant('graphicsmagick', default=True,
# description='painting to PNG, GIF')
variant('sqlite', default=False, description='create SQLite3 DBO')
variant('mariadb', default=False, description='create MariaDB/MySQL DBO')
variant('postgresql', default=False, description='create PostgreSQL DBO... | """Wt, C++ Web Toolkit.
Wt is a C++ library for developing web applications."""
homepage = "http://www.webtoolkit.eu/wt"
url = "https://github.com/emweb/wt/archive/3.3.7.tar.gz"
version('3.3.7', '09858901f2dcf5c3d36a9237daba3e3f')
version('master', branch='master',
git='https://github... | identifier_body |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | # Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed ... | random_line_split | |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (CMakePackage):
"""Wt, C++ Web Toolkit.
Wt is a C++ library for developing web applications."""
homepage = "http://www.webtoolkit.eu/wt"
url = "https://github.com/emweb/wt/archive/3.3.7.tar.gz"
version('3.3.7', '09858901f2dcf5c3d36a9237daba3e3f')
version('master', branch='master',
... | Wt | identifier_name |
textutils.py | # encoding: utf-8
def _unicode_truncate(ustr, length, encoding="UTF-8"):
"Truncate @ustr to specific encoded byte length"
bstr = ustr.encode(encoding)[:length]
return bstr.decode(encoding, 'ignore')
def extract_title_body(text, maxtitlelen=60):
"""Prepare @text: Return a (title, body) tuple
@text... | lit_first_words(text, maxtitlelen)
else:
return firstline, rest
if rest.strip():
return firstline, text
else:
return text, ""
if __name__ == '__main__':
import doctest
doctest.testmod()
| firstline, rest = sp | conditional_block |
textutils.py | # encoding: utf-8
def _unicode_truncate(ustr, length, encoding="UTF-8"):
"Truncate @ustr to specific encoded byte length"
bstr = ustr.encode(encoding)[:length]
return bstr.decode(encoding, 'ignore')
def extract_title_body(text, maxtitlelen=60):
"""Prepare @text: Return a (title, body) tuple
@text... |
>>> extract_title_body("Short Text")
('Short Text', '')
>>> title, body = extract_title_body(u"執筆方針については、項目名の付け方、"
... "フォーマットや表記上の諸問題に関して多くの方針が存在している。")
>>> print(title)
執筆方針については、項目名の付け方、フォ
>>> print(body) # doctest: +ELLIPSIS
執筆方針については、項目名の付け方、フォ...して多くの方針が存在している。
""... | and return the full text as body.
@maxtitlelen: A unitless measure of approximate length of title.
The default value yields a resulting title of approximately 60 ascii
characters, or 20 asian characters. | random_line_split |
textutils.py | # encoding: utf-8
def _unicode_truncate(ustr, length, encoding="UTF-8"):
"Truncate @ustr to specific encoded byte length"
bstr = ustr.encode(encoding)[:length]
return bstr.decode(encoding, 'ignore')
def extract_title_body(text, maxtitlelen=60):
"""Prepare @text: Return a (title, body) tuple
@text... | t = "\n".join(lines)
return l, rest
# We use the UTF-8 encoding and truncate due to it:
# this is a good heuristic for ascii vs "wide characters"
# it results in taking fewer characters if they are asian, which
# is exactly what we want
def split_first_words(text, maxlen):
text ... |
res | identifier_name |
textutils.py | # encoding: utf-8
def _unicode_truncate(ustr, length, encoding="UTF-8"):
"Truncate @ustr to specific encoded byte length"
bstr = ustr.encode(encoding)[:length]
return bstr.decode(encoding, 'ignore')
def extract_title_body(text, maxtitlelen=60):
"""Prepare @text: Return a (title, body) tuple
@text... | at we want
def split_first_words(text, maxlen):
text = text.lstrip()
first_text = _unicode_truncate(text, maxlen)
words = first_text.split()
if len(words) > 3:
words = words[:-1]
first_words = " ".join(words[:-1])
if text.startswith(first_words):
... | nes)
return l, rest
# We use the UTF-8 encoding and truncate due to it:
# this is a good heuristic for ascii vs "wide characters"
# it results in taking fewer characters if they are asian, which
# is exactly wh | identifier_body |
NewPollScreen.js | import React from 'react';
import { View, ScrollView } from 'react-native';
import ConcensusButton from '../components/ConcensusButton';
import axios from 'axios';
const t = require('tcomb-form-native');
const Form = t.form.Form;
const NewPollScreen = ({ navigation }) => {
function onProposePress() |
return (
<View style={{ padding: 20 }}>
<ScrollView>
<Form type={Poll} />
</ScrollView>
<ConcensusButton label="Propose Motion" onPress={onProposePress} />
</View>
);
};
NewPollScreen.navigationOptions = ({ navigation }) => ({
title: 'Pr... | {
navigation.navigate('QRCodeShower');
axios.post('http://4d23f078.ngrok.io/createPoll');
} | identifier_body |
NewPollScreen.js | import React from 'react';
import { View, ScrollView } from 'react-native';
import ConcensusButton from '../components/ConcensusButton';
import axios from 'axios';
const t = require('tcomb-form-native');
const Form = t.form.Form;
const NewPollScreen = ({ navigation }) => {
function | () {
navigation.navigate('QRCodeShower');
axios.post('http://4d23f078.ngrok.io/createPoll');
}
return (
<View style={{ padding: 20 }}>
<ScrollView>
<Form type={Poll} />
</ScrollView>
<ConcensusButton label="Propose Motion" onPress={on... | onProposePress | identifier_name |
NewPollScreen.js | import React from 'react';
import { View, ScrollView } from 'react-native';
import ConcensusButton from '../components/ConcensusButton';
import axios from 'axios';
const t = require('tcomb-form-native');
const Form = t.form.Form;
const NewPollScreen = ({ navigation }) => {
function onProposePress() {
navig... | const Poll = t.struct({
subject: t.String,
proposal: t.String,
endsInMinutes: t.Number,
consensusPercentage: t.Number,
}); | title: 'Propose a Motion',
});
export default NewPollScreen;
| random_line_split |
runtime.rs | #[cfg(windows)]
mod os
{
#[cfg(windows)]
#[link(name = "ole32")]
extern "system" {
#[doc(hidden)]
pub fn CoInitializeEx(
reserved: *const ::std::os::raw::c_void,
init: u32,
) -> crate::raw::HRESULT;
#[doc(hidden)]
pub fn CoUninitialize();
... |
}
pub fn initialize() -> crate::RawComResult<()>
{
match os::initialize() {
crate::raw::S_OK => Ok(()),
e => Err(e),
}
}
pub fn uninitialize()
{
os::uninitialize();
}
| {} | identifier_body |
runtime.rs | #[cfg(windows)]
mod os
{
#[cfg(windows)]
#[link(name = "ole32")]
extern "system" {
#[doc(hidden)]
pub fn CoInitializeEx(
reserved: *const ::std::os::raw::c_void,
init: u32,
) -> crate::raw::HRESULT;
#[doc(hidden)]
pub fn CoUninitialize();
... | () {}
}
pub fn initialize() -> crate::RawComResult<()>
{
match os::initialize() {
crate::raw::S_OK => Ok(()),
e => Err(e),
}
}
pub fn uninitialize()
{
os::uninitialize();
}
| uninitialize | identifier_name |
runtime.rs | #[cfg(windows)]
mod os
{
#[cfg(windows)]
#[link(name = "ole32")]
extern "system" {
#[doc(hidden)]
pub fn CoInitializeEx(
reserved: *const ::std::os::raw::c_void,
init: u32,
) -> crate::raw::HRESULT;
#[doc(hidden)]
pub fn CoUninitialize();
... | }
pub fn uninitialize() {}
}
pub fn initialize() -> crate::RawComResult<()>
{
match os::initialize() {
crate::raw::S_OK => Ok(()),
e => Err(e),
}
}
pub fn uninitialize()
{
os::uninitialize();
} | random_line_split | |
navbar.component.ts | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 requi... | implements OnInit, OnDestroy {
private domainSubscription: Subscription;
private environmentSubscription: Subscription;
private sidenavSubscription: Subscription;
reducedMode = false;
domains: any[];
currentDomain: any = {};
navLinks: any[];
currentEnvironment;
constructor(private authService: AuthS... | NavbarComponent | identifier_name |
navbar.component.ts | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 requi... |
this.navLinks.push({'href': '/logout', 'label': 'Sign out', 'icon': 'exit_to_app'});
}
hasCurrentEnvironment(): boolean {
return this.currentEnvironment && this.currentEnvironment !== EnvironmentService.NO_ENVIRONMENT;
}
private canDisplay(permissions): boolean {
return this.authService.hasPermi... | {
this.navLinks.push({'href': '/environments/' + this.currentEnvironment.hrids[0] + '/domains/new', 'label': 'Create domain', 'icon': 'add'});
} | conditional_block |
navbar.component.ts | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 requi... |
hasCurrentEnvironment(): boolean {
return this.currentEnvironment && this.currentEnvironment !== EnvironmentService.NO_ENVIRONMENT;
}
private canDisplay(permissions): boolean {
return this.authService.hasPermissions(permissions);
}
}
| {
this.navLinks = [];
if (this.hasCurrentEnvironment() && this.canDisplay(['domain_list'])) {
this.navLinks.push({'href': '/environments/' + this.currentEnvironment.hrids[0] + '/domains', 'label': 'All domains', 'icon': 'developer_board'});
}
if (this.hasCurrentEnvironment() && this.canDisplay(... | identifier_body |
navbar.component.ts | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 requi... | }
ngOnInit() {
this.initNavLinks();
this.environmentSubscription = this.environmentService.currentEnvironmentObs$.subscribe(environment => {
this.currentEnvironment = environment;
this.initNavLinks();
});
this.domainSubscription = this.navbarService.currentDomainObs$.subscribe(data => ... | private environmentService: EnvironmentService,
public router: Router) { | random_line_split |
lib.rs | #[macro_use]
extern crate error_chain;
// We'll put our errors in an `errors` module, and other modules in
// this crate will `use errors::*;` to get access to everything
// `error_chain!` creates.
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain!{}
}
use errors::*;
pub fn... | <T: AsRef<str>>(digits: T, length: usize) -> Result<u64> {
let digits = digits.as_ref();
if digits.len() < length {
bail!("The digits string must at least be {} characters in size but was only {}",
length,
digits.len());
}
let mut new_digits = Vec::with_capacity(digit... | lsp | identifier_name |
lib.rs | #[macro_use]
extern crate error_chain;
// We'll put our errors in an `errors` module, and other modules in
// this crate will `use errors::*;` to get access to everything
// `error_chain!` creates.
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain!{}
}
use errors::*;
pub fn... | {
match c {
'0'...'9' => Ok(c as u8 - '0' as u8),
_ => bail!("'{}' is not a digit"),
}
} | identifier_body | |
lib.rs | #[macro_use]
extern crate error_chain;
// We'll put our errors in an `errors` module, and other modules in
// this crate will `use errors::*;` to get access to everything
// `error_chain!` creates.
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain!{}
}
use errors::*;
pub fn... | _ => bail!("'{}' is not a digit"),
}
} | fn char_to_digit(c: char) -> Result<u8> {
match c {
'0'...'9' => Ok(c as u8 - '0' as u8), | random_line_split |
gridPositions.ts | import * as math from 'mathjs';
import { NodeSpatial } from './nodeSpatial';
export class GridPositions {
private readonly _name = 'grid';
private _center: number[];
private _edgeWrap: boolean;
private _extent: number[];
private _numDimensions: number;
private _pos: number[][];
private _shape: number[];... | (): void {
const minX: number = this._center[0] - this._extent[0] / 2;
const maxX: number = this._center[0] + this._extent[0] / 2;
const minY: number = this._center[1] - this._extent[1] / 2;
const maxY: number = this._center[1] + this._extent[1] / 2;
const X: number[] = this.range(minX, maxX, this._... | generate | identifier_name |
gridPositions.ts | import * as math from 'mathjs';
import { NodeSpatial } from './nodeSpatial';
export class GridPositions {
private readonly _name = 'grid';
private _center: number[];
private _edgeWrap: boolean;
private _extent: number[];
private _numDimensions: number;
private _pos: number[][];
private _shape: number[];... | }
get numDimensions(): number {
return this._numDimensions;
}
set numDimensions(value: number) {
this._numDimensions = value;
this._center = new Array(this._numDimensions).fill(0);
this._extent = new Array(this._numDimensions).fill(1);
this._shape = new Array(this._numDimensions).fill(1);
... | }
get name(): string {
return this._name; | random_line_split |
gridPositions.ts | import * as math from 'mathjs';
import { NodeSpatial } from './nodeSpatial';
export class GridPositions {
private readonly _name = 'grid';
private _center: number[];
private _edgeWrap: boolean;
private _extent: number[];
private _numDimensions: number;
private _pos: number[][];
private _shape: number[];... |
get edgeWrap(): boolean {
return this._edgeWrap;
}
set edgeWrap(value: boolean) {
this._edgeWrap = value;
}
get extent(): number[] {
return this._extent;
}
set extent(value: number[]) {
this._extent = value;
}
get name(): string {
return this._name;
}
get numDimensions()... | {
this._center = value;
} | identifier_body |
urls.py | """my_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/ | 2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
... | Examples:
Function views
1. Add an import: from my_app import views | random_line_split |
sash.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): void {
this.disposables.dispose();
}
}
| dispose | identifier_name |
sash.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
private onDidChangeHoverDelay(): void {
setGlobalHoverDelay(this.configurationService.getValue<number>('workbench.sash.hoverDelay'));
}
dispose(): void {
this.disposables.dispose();
}
} |
document.documentElement.style.setProperty('--sash-size', size + 'px');
document.documentElement.style.setProperty('--sash-hover-size', hoverSize + 'px');
setGlobalSashSize(size);
} | random_line_split |
sash.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
dispose(): void {
this.disposables.dispose();
}
}
| {
setGlobalHoverDelay(this.configurationService.getValue<number>('workbench.sash.hoverDelay'));
} | identifier_body |
codecard.tsx | import * as React from "react";
import * as sui from "./sui";
import * as data from "./data";
const repeat = pxt.Util.repeatMap;
export interface CodeCardState { }
export class CodeCardView extends data.Component<pxt.CodeCard, CodeCardState> {
public element: HTMLDivElement;
constructor(props: pxt.CodeCard... | () {
if (this.observer) return;
// setup intersection observer for the image
const preloadImage = (el: HTMLImageElement) => {
const lazyImageUrl = el.getAttribute('data-src');
el.style.backgroundImage = `url(${lazyImageUrl})`
}
const config = {
... | setupIntersectionObserver | identifier_name |
codecard.tsx | import * as React from "react";
import * as sui from "./sui";
import * as data from "./data";
const repeat = pxt.Util.repeatMap;
export interface CodeCardState { }
export class CodeCardView extends data.Component<pxt.CodeCard, CodeCardState> {
public element: HTMLDivElement;
constructor(props: pxt.CodeCard... | </label> : undefined}
{card.typeScript ? <pre key="promots">{card.typeScript}</pre> : undefined}
{card.cardType != "file" && imageUrl ? <div className="ui imagewrapper">
<div className={`ui cardimage`} data-src={imageUrl} ref="lazyimage" />
... | random_line_split | |
codecard.tsx | import * as React from "react";
import * as sui from "./sui";
import * as data from "./data";
const repeat = pxt.Util.repeatMap;
export interface CodeCardState { }
export class CodeCardView extends data.Component<pxt.CodeCard, CodeCardState> {
public element: HTMLDivElement;
constructor(props: pxt.CodeCard... |
private static observer: IntersectionObserver;
private static setupIntersectionObserver() {
if (this.observer) return;
// setup intersection observer for the image
const preloadImage = (el: HTMLImageElement) => {
const lazyImageUrl = el.getAttribute('data-src');
... | {
super(props);
this.state = {};
} | identifier_body |
list.js | TornadoFaces.declareWidget('List', function() {
var widget;
function isFunction(functionToCheck) |
this.init = function() {
widget = this;
widget.items = widget.elem.find('ul li');
widget.bindEvents();
};
this.getFilterFn = function() {
var filterFn = widget.conf.filterFn;
if (!filterFn) {
filterFn = function(item, query) {
return it... | {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
} | identifier_body |
list.js | TornadoFaces.declareWidget('List', function() {
var widget;
function | (functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
this.init = function() {
widget = this;
widget.items = widget.elem.find('ul li');
widget.bindEvents();
};
this.getFilterFn = functi... | isFunction | identifier_name |
list.js | TornadoFaces.declareWidget('List', function() {
var widget;
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
this.init = function() {
widget = this;
widget.items = widge... | event.preventDefault();
return false;
});
}
}); | widget.select(itemIndex); | random_line_split |
0019_consolidate_slug.py | """
Custom migration script to add slug field to all ProviderConfig models.
"""
from django.db import migrations, models
from django.utils.text import slugify
def fill_slug_field(apps, schema_editor):
"""
Fill in the slug field for each ProviderConfig class for backwards compatability.
"""
OAuth2Pro... |
for config in LTIProviderConfig.objects.all():
config.slug = slugify(config.lti_consumer_key)
config.save()
class Migration(migrations.Migration):
dependencies = [
('third_party_auth', '0018_auto_20180327_1631'),
]
operations = [
migrations.AddField(
mod... | config.slug = config.idp_slug
config.save() | conditional_block |
0019_consolidate_slug.py | """
Custom migration script to add slug field to all ProviderConfig models.
"""
from django.db import migrations, models
from django.utils.text import slugify
def fill_slug_field(apps, schema_editor):
"""
Fill in the slug field for each ProviderConfig class for backwards compatability.
"""
OAuth2Pro... | (migrations.Migration):
dependencies = [
('third_party_auth', '0018_auto_20180327_1631'),
]
operations = [
migrations.AddField(
model_name='ltiproviderconfig',
name='slug',
field=models.SlugField(default='default', help_text='A short string uniquely iden... | Migration | identifier_name |
0019_consolidate_slug.py | """
Custom migration script to add slug field to all ProviderConfig models.
"""
from django.db import migrations, models
from django.utils.text import slugify
def fill_slug_field(apps, schema_editor):
|
class Migration(migrations.Migration):
dependencies = [
('third_party_auth', '0018_auto_20180327_1631'),
]
operations = [
migrations.AddField(
model_name='ltiproviderconfig',
name='slug',
field=models.SlugField(default='default', help_text='A short st... | """
Fill in the slug field for each ProviderConfig class for backwards compatability.
"""
OAuth2ProviderConfig = apps.get_model('third_party_auth', 'OAuth2ProviderConfig')
SAMLProviderConfig = apps.get_model('third_party_auth', 'SAMLProviderConfig')
LTIProviderConfig = apps.get_model('third_party_au... | identifier_body |
0019_consolidate_slug.py | """
Custom migration script to add slug field to all ProviderConfig models.
"""
from django.db import migrations, models
from django.utils.text import slugify
def fill_slug_field(apps, schema_editor):
"""
Fill in the slug field for each ProviderConfig class for backwards compatability.
"""
OAuth2Pro... | ),
migrations.AddField(
model_name='oauth2providerconfig',
name='slug',
field=models.SlugField(default='default', help_text='A short string uniquely identifying this provider. Cannot contain spaces and should be a usable as a CSS class. Examples: "ubc", "mit-staging"'... | operations = [
migrations.AddField(
model_name='ltiproviderconfig',
name='slug',
field=models.SlugField(default='default', help_text='A short string uniquely identifying this provider. Cannot contain spaces and should be a usable as a CSS class. Examples: "ubc", "mit-stag... | random_line_split |
mod.rs | implies that a pointer to an object can safely be cast to a pointer
//! to all its classes.
//!
//! This invariant is enforced by the lint in
//! `plugins::lints::inheritance_integrity`.
//!
//! Interfaces which either derive from or are derived by other interfaces | //! and check whether a given instance is of a given type.
//!
//! ```ignore
//! use dom::bindings::inheritance::Castable;
//! use dom::element::Element;
//! use dom::htmlelement::HTMLElement;
//! use dom::htmlinputelement::HTMLInputElement;
//!
//! if let Some(elem) = node.downcast::<Element> {
//! if elem.is::<HT... | //! implement the `Castable` trait, which provides three methods `is::<T>()`,
//! `downcast::<T>()` and `upcast::<T>()` to cast across the type hierarchy | random_line_split |
RenameQualityGateForm.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | (props: Props) {
super(props);
this.state = { name: props.qualityGate.name };
}
handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ name: event.currentTarget.value });
};
handleRename = () => {
const { qualityGate } = this.props;
const { name } = this.state... | constructor | identifier_name |
RenameQualityGateForm.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | import { QualityGate } from '../../../types/types';
interface Props {
onClose: () => void;
onRename: () => Promise<void>;
qualityGate: QualityGate;
}
interface State {
name: string;
}
export default class RenameQualityGateForm extends React.PureComponent<Props, State> {
constructor(props: Props) {
supe... | import { renameQualityGate } from '../../../api/quality-gates';
import ConfirmModal from '../../../components/controls/ConfirmModal';
import MandatoryFieldMarker from '../../../components/ui/MandatoryFieldMarker';
import MandatoryFieldsExplanation from '../../../components/ui/MandatoryFieldsExplanation';
import { trans... | random_line_split |
RenameQualityGateForm.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... |
return renameQualityGate({ id: qualityGate.id, name }).then(() => this.props.onRename());
};
render() {
const { qualityGate } = this.props;
const { name } = this.state;
const confirmDisable = !name || (qualityGate && qualityGate.name === name);
return (
<ConfirmModal
confirmBut... | {
return undefined;
} | conditional_block |
RenameQualityGateForm.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... |
handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ name: event.currentTarget.value });
};
handleRename = () => {
const { qualityGate } = this.props;
const { name } = this.state;
if (!name) {
return undefined;
}
return renameQualityGate({ id: qua... | {
super(props);
this.state = { name: props.qualityGate.name };
} | identifier_body |
mod.rs | ) as *mut u8).into()
}
pub fn kernel_end() -> PhysicalAddr {
let p = unsafe { &mut _end as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
#[inline(always)]
pub fn v2p(v: VirtualAddr) -> Option<PhysicalAddr> {
v.as_usize().checked_sub(UPPER_SPACE_MASK).map(Into::into)
}
#[inline(always)... |
pub fn contains(&self, addr: VirtualAddr) -> bool {
self.start <= addr && addr < self.end
}
pub fn intersects(&self, other: Self) -> bool {
self.contains(other.start) || self.contains(other.end)
}
}
/// Set up page translation tables and enable virtual memory
pub fn initialize() {
... | {
self.start >= self.end
} | identifier_body |
mod.rs | ) as *mut u8).into()
}
pub fn kernel_end() -> PhysicalAddr {
let p = unsafe { &mut _end as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
#[inline(always)]
pub fn v2p(v: VirtualAddr) -> Option<PhysicalAddr> {
v.as_usize().checked_sub(UPPER_SPACE_MASK).map(Into::into)
}
#[inline(always)... | (&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RX))
}
#[must_use]
pub fn area_rw(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RW))
}
#[must_use]
pub fn area_ro(&mut self, area: Area) -> Option<()> {
self.area(area.prot(Prot::RO))
... | area_rx | identifier_name |
mod.rs | PAGESZ);
let end = align_up(area.end.as_usize(), PAGESZ);
let entry = area.entry;
let p = area.physical;
self.areas.try_reserve(1).ok()?;
self.areas.push(area);
if let Some(p) = p {
let mut p = align_down(p.as_usize(), PAGESZ);
while addr < end ... | unsafe { | random_line_split | |
mod.rs | ) as *mut u8).into()
}
pub fn kernel_end() -> PhysicalAddr {
let p = unsafe { &mut _end as *mut _ };
(((p as usize) & LOWER_SPACE_MASK) as *mut u8).into()
}
#[inline(always)]
pub fn v2p(v: VirtualAddr) -> Option<PhysicalAddr> {
v.as_usize().checked_sub(UPPER_SPACE_MASK).map(Into::into)
}
#[inline(always)... |
Some(())
}
pub fn find_area_mut(&mut self, addr: VirtualAddr) -> Option<&mut Area> {
self.areas.iter_mut().find(|area| area.contains(addr))
}
pub fn find_area(&self, addr: VirtualAddr) -> Option<&Area> {
self.areas.iter().find(|area| area.contains(addr))
}
pub fn has... | {
let mut p = align_down(p.as_usize(), PAGESZ);
while addr < end {
let v = (addr as *mut u8).into();
let l2 = self.root.next_table_or(v, Entry::USER_BASE)?;
if addr % HUGESZ == 0 && (end - addr) >= HUGESZ {
l2[v].write(Entry::bl... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.