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 |
|---|---|---|---|---|
gpu-donut-chart.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | didInsertElement: function() {
// ParentId includes minorNumber
var newParentId = this.get("parentId") + this.get("gpuInfo").minorNumber;
this.set("parentId", newParentId);
this.initChart();
this.draw();
},
}); | this.renderDonutChart(data, this.get("title"), this.get("showLabels"),
this.get("middleLabel"), this.get("middleValue"), this.get("suffix"));
},
| random_line_split |
editfns.rs | ).
#[lisp_fn]
pub fn point() -> LispObject {
let buffer_ref = ThreadState::current_buffer();
LispObject::from_natnum(buffer_ref.pt as EmacsInt)
}
/// Return the number of characters in the current buffer.
/// If BUFFER is not nil, return the number of characters in that buffer
/// instead.
///
/// This does no... |
/// Return the integer value of point or mark, whichever is larger.
#[lisp_fn]
fn region_end() -> LispObject {
region_limit(false)
}
/// Return this buffer's mark, as a marker object.
/// Watch out! Moving this marker changes the mark position.
/// If you set the marker not to point anywhere, the buffer will ha... | {
region_limit(true)
} | identifier_body |
editfns.rs | -min).
#[lisp_fn]
pub fn point() -> LispObject {
let buffer_ref = ThreadState::current_buffer();
LispObject::from_natnum(buffer_ref.pt as EmacsInt)
}
/// Return the number of characters in the current buffer.
/// If BUFFER is not nil, return the number of characters in that buffer
/// instead.
///
/// This doe... | }
/// Return the byte position for character position POSITION.
/// If POSITION is out of range, the value is nil.
#[lisp_fn]
pub fn position_bytes(position: LispObject) -> LispObject {
let pos = position.as_fixnum_coerce_marker_or_error() as ptrdiff_t;
let cur_buf = ThreadState::current_buffer();
if pos ... | wrong_type!(Qinteger_or_marker_p, position)
};
position | random_line_split |
editfns.rs | ).
#[lisp_fn]
pub fn point() -> LispObject {
let buffer_ref = ThreadState::current_buffer();
LispObject::from_natnum(buffer_ref.pt as EmacsInt)
}
/// Return the number of characters in the current buffer.
/// If BUFFER is not nil, return the number of characters in that buffer
/// instead.
///
/// This does no... | () -> LispObject {
region_limit(false)
}
/// Return this buffer's mark, as a marker object.
/// Watch out! Moving this marker changes the mark position.
/// If you set the marker not to point anywhere, the buffer will have no mark.
#[lisp_fn]
fn mark_marker() -> LispObject {
ThreadState::current_buffer().mark... | region_end | identifier_name |
editfns.rs | ).
#[lisp_fn]
pub fn point() -> LispObject {
let buffer_ref = ThreadState::current_buffer();
LispObject::from_natnum(buffer_ref.pt as EmacsInt)
}
/// Return the number of characters in the current buffer.
/// If BUFFER is not nil, return the number of characters in that buffer
/// instead.
///
/// This does no... |
} else {
let p = pos.as_fixnum_coerce_marker_or_error() as ptrdiff_t;
if p < buffer_ref.begv || p >= buffer_ref.zv() {
LispObject::constant_nil()
} else {
let pos_byte = unsafe { buf_charpos_to_bytepos(buffer_ref.as_ptr(), p) | {
LispObject::from_natnum(buffer_ref.fetch_char(pos_byte) as EmacsInt)
} | conditional_block |
activity-main.js | mui.init();
var postInfo = { 'page': 1 };
var activityUl = document.getElementById("activityUl");
var addActivityList = function(data) {
var li = document.createElement('li');
li.className = "mui-table-view-cell";
data.explain = imgTools.getDtlContent(data.explain);
li.innerHTML = template('act... | },
down: {
callback: function() {
var pullObj = this;
postInfo.page = 1;
activityUl.innerHTML = "";
activity.getActivityList(postInfo, function(res) {
if(res.data) {
for(i in res.data) {
var li = addActivityList(res.data[i]);
activityUl.ap... | } | random_line_split |
csstransition.js | this.primereact = this.primereact || {};
this.primereact.csstransition = (function (exports, React, reactTransitionGroup) {
'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(Rea... |
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" &... | {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configur... | identifier_body |
csstransition.js | this.primereact = this.primereact || {};
this.primereact.csstransition = (function (exports, React, reactTransitionGroup) {
'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(Rea... | else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) ... | { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } | conditional_block |
csstransition.js | this.primereact = this.primereact || {};
this.primereact.csstransition = (function (exports, React, reactTransitionGroup) {
'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(Rea... |
return /*#__PURE__*/React__default['default'].createElement(reactTransitionGroup.CSSTransition, props, this.props.children);
}
}]);
return CSSTransition;
}(React.Component);
exports.CSSTransition = CSSTransition;
Object.defineProperty(exports, '__esModule', { value: true });
return ex... | };
var props = _objectSpread(_objectSpread(_objectSpread({}, mutableProps), this.props.options || {}), immutableProps); | random_line_split |
csstransition.js | this.primereact = this.primereact || {};
this.primereact.csstransition = (function (exports, React, reactTransitionGroup) {
'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(Rea... | (self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
... | _assertThisInitialized | identifier_name |
ast.rs | use std::fmt::{Debug, Error, Formatter};
pub enum Expr {
Number(i32),
Op(Box<Expr>, Opcode, Box<Expr>),
Error,
}
#[derive(Copy, Clone)] | Div,
Add,
Sub,
}
impl Debug for Expr {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
use self::Expr::*;
match *self {
Number(n) => write!(fmt, "{:?}", n),
Op(ref l, op, ref r) => write!(fmt, "({:?} {:?} {:?})", l, op, r),
Error => write!(f... | pub enum Opcode {
Mul, | random_line_split |
ast.rs | use std::fmt::{Debug, Error, Formatter};
pub enum Expr {
Number(i32),
Op(Box<Expr>, Opcode, Box<Expr>),
Error,
}
#[derive(Copy, Clone)]
pub enum Opcode {
Mul,
Div,
Add,
Sub,
}
impl Debug for Expr {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
use self::Expr::*;
... |
}
| {
use self::Opcode::*;
match *self {
Mul => write!(fmt, "*"),
Div => write!(fmt, "/"),
Add => write!(fmt, "+"),
Sub => write!(fmt, "-"),
}
} | identifier_body |
ast.rs | use std::fmt::{Debug, Error, Formatter};
pub enum Expr {
Number(i32),
Op(Box<Expr>, Opcode, Box<Expr>),
Error,
}
#[derive(Copy, Clone)]
pub enum Opcode {
Mul,
Div,
Add,
Sub,
}
impl Debug for Expr {
fn | (&self, fmt: &mut Formatter) -> Result<(), Error> {
use self::Expr::*;
match *self {
Number(n) => write!(fmt, "{:?}", n),
Op(ref l, op, ref r) => write!(fmt, "({:?} {:?} {:?})", l, op, r),
Error => write!(fmt, "error"),
}
}
}
impl Debug for Opcode {
f... | fmt | identifier_name |
command.rs | // Copyright 2017 Google Inc.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | () {
let tokens = parse_cmd(r#"cmd 1 2
3 "
4" {}"#, &["5"]).unwrap();
assert_eq!("cmd", tokens[0]);
assert_eq!("1", tokens[1]);
assert_eq!("2", tokens[2]);
assert_eq!("3", tokens[3]);
assert_eq!("\n 4", tokens[4]);
assert_eq!("5", tokens[5]);
}
#[test]
fn te... | test_parse_cmd | identifier_name |
command.rs | // Copyright 2017 Google Inc.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
impl Token {
fn into_string(self, args: &mut Iterator<Item = &str>)
-> Result<String, VarError> {
let mut token = String::from("");
for part in self.0 {
match part {
TokenPart::Bare(s) => token += &s,
TokenPart::Placeholder =>
... | EnvVariable(String),
}
struct Token(Vec<TokenPart>); | random_line_split |
command.rs | // Copyright 2017 Google Inc.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
/// Creates a new command from `format` and `args`.
/// The function is invoked from `cmd!` macro internally.
pub fn new_command(format: &str, args: &[&str])
-> Result<ShellCommand, VarError> {
let vec = parse_cmd(format, args)?;
let mut command = Command::new(&vec[0]);
if vec.len() > 1 {
... | {
let tokens = match command(format) {
IResult::Done(_, result) => result,
IResult::Error(error) => panic!("Error {:?}", error),
IResult::Incomplete(needed) => panic!("Needed {:?}", needed)
};
let args = args.iter().map(|a| *a).collect::<Vec<_>>();
let mut args = args.into_iter()... | identifier_body |
document_rule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document)
//! initially in CSS C... | /// function or a final substring of the host component is a
/// period (U+002E) immediately followed by the argument to the
/// ‘domain()’ function.
Domain(String),
/// Regular expression matching function. It evaluates to true
/// whenever the regular expression matches the entirety of the URL... | /// host subcomponent is exactly the argument to the ‘domain()’ | random_line_split |
document_rule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document)
//! initially in CSS C... | input.try(|input| input.expect_function_matching("regexp")).is_ok() {
input.parse_nested_block(|input| {
Ok(UrlMatchingFunction::RegExp(input.expect_string()?.into_owned()))
})
} else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) {
O... | parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::Domain)
} else if | conditional_block |
document_rule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document)
//! initially in CSS C... |
}
impl DeepCloneWithLock for DocumentRule {
/// Deep clones this DocumentRule.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
) -> Self {
let rules = self.rules.read_with(guard);
DocumentRule {
condition: self.conditi... | {
try!(dest.write_str("@-moz-document "));
try!(self.condition.to_css(dest));
try!(dest.write_str(" {"));
for rule in self.rules.read_with(guard).0.iter() {
try!(dest.write_str(" "));
try!(rule.to_css(guard, dest));
}
dest.write_str(" }")
} | identifier_body |
document_rule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document)
//! initially in CSS C... | {
/// The parsed condition
pub condition: DocumentCondition,
/// Child rules
pub rules: Arc<Locked<CssRules>>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for DocumentRule {
fn to_css<W>(&self, guard: &SharedRwLockReadGuard,... | DocumentRule | identifier_name |
RepoUserHeatmap.js | import React, {PropTypes} from 'react';
import L from 'leaflet';
import gh from '../api/GitHubApi';
import RaisedButton from 'material-ui/RaisedButton';
const REPO_TIMESPAN = {
ALLTIME: 0,
THIRTYDAYS: 1,
SIXTYDAYS: 2,
ONEYEAR: 3
};
const defaultMapConfig = {
options: {
center: [
... | () {
}
render() {
return (
<div className="map-container">
<div className="os-map" ref={(div) => { this.mapDiv = div; }}></div>
<RaisedButton label="Default" />
</div>
);
}
}
RepoUserHeatmap.propTypes = {
mapOptions: PropTypes.ob... | updateData | identifier_name |
RepoUserHeatmap.js | import React, {PropTypes} from 'react';
import L from 'leaflet';
import gh from '../api/GitHubApi';
import RaisedButton from 'material-ui/RaisedButton';
const REPO_TIMESPAN = {
ALLTIME: 0,
THIRTYDAYS: 1,
SIXTYDAYS: 2,
ONEYEAR: 3
};
const defaultMapConfig = {
options: {
center: [
... |
else {
L.tileLayer(defaultMapConfig.tileLayer.uri, defaultMapConfig.tileLayer.options).addTo(this.map);
}
}
updateData() {
}
render() {
return (
<div className="map-container">
<div className="os-map" ref={(div) => { this.mapDiv = div; ... | {
for (let i=0; i < this.props.mapLayers.length; i++) {
this.props.mapLayers[i].addTo(this.map);
}
} | conditional_block |
RepoUserHeatmap.js | import React, {PropTypes} from 'react';
import L from 'leaflet';
import gh from '../api/GitHubApi';
import RaisedButton from 'material-ui/RaisedButton';
const REPO_TIMESPAN = {
ALLTIME: 0,
THIRTYDAYS: 1,
SIXTYDAYS: 2,
ONEYEAR: 3
};
| zoomControl: false,
zoom: 4,
maxZoom: 20,
minZoom: 2,
scrollwheel: false,
infoControl: false,
attributionControl: false
},
tileLayer: {
uri: 'http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png',
options: {
maxZoom: 18,
... | const defaultMapConfig = {
options: {
center: [
39.7589, -84.1916
], | random_line_split |
RepoUserHeatmap.js | import React, {PropTypes} from 'react';
import L from 'leaflet';
import gh from '../api/GitHubApi';
import RaisedButton from 'material-ui/RaisedButton';
const REPO_TIMESPAN = {
ALLTIME: 0,
THIRTYDAYS: 1,
SIXTYDAYS: 2,
ONEYEAR: 3
};
const defaultMapConfig = {
options: {
center: [
... | console.log('ERROR:');
console.log(err);
});
}
componentWillUnmount() {
this.map = null;
}
initializeMap() {
if (this.map) {
return;
}
this.map = L.map(this.mapDiv, this.props.mapOptions || defaultMapConfig.options);
if (this.props.mapL... | {
this.initializeMap();
this.updateData();
gh.getTopRepos().then(data => {
console.log('=== REPOS ===');
console.log(data);
return gh.getContributors(data.data[0].full_name);
}).then(contribs => {
console.log('=== CONTRIBS ===');
cons... | identifier_body |
partnership.py | Field
logger = logging.getLogger(__name__)
class Partnership(models.Model):
# the old way
FIELD_PARTNER = 'field'
FUNDING_PARTNER = 'funding'
SPONSOR_PARTNER = 'sponsor'
SUPPORT_PARTNER = 'support'
EXTENDING_PARTNER = 'extending'
PARTNER_TYPE_LIST = [
FIELD_PARTNER, FUNDING_PARTN... | def save(self, *args, **kwargs):
super(Partnership, self).save(*args, **kwargs)
self.set_primary_organisation()
self.project.update_use_project_roles()
def delete(self, *args, **kwargs):
super(Partnership, self).delete(*args, **kwargs)
self.set_primary_organisation()
... | ise ValidationError(
{'iati_organisation_role': '%s' % _('Project can only have one reporting '
'organisation')}
)
| conditional_block |
partnership.py | Field
logger = logging.getLogger(__name__)
class Partnership(models.Model):
# the old way
FIELD_PARTNER = 'field'
FUNDING_PARTNER = 'funding'
SPONSOR_PARTNER = 'sponsor'
SUPPORT_PARTNER = 'support'
EXTENDING_PARTNER = 'extending'
PARTNER_TYPE_LIST = [
FIELD_PARTNER, FUNDING_PARTN... | elf, *args, **kwargs):
super(Partnership, self).save(*args, **kwargs)
self.set_primary_organisation()
self.project.update_use_project_roles()
def delete(self, *args, **kwargs):
super(Partnership, self).delete(*args, **kwargs)
self.set_primary_organisation()
def set_prim... | ve(s | identifier_name |
partnership.py | Field
logger = logging.getLogger(__name__)
class Partnership(models.Model):
# the old way
FIELD_PARTNER = 'field'
FUNDING_PARTNER = 'funding'
SPONSOR_PARTNER = 'sponsor'
SUPPORT_PARTNER = 'support'
EXTENDING_PARTNER = 'extending'
PARTNER_TYPE_LIST = [
FIELD_PARTNER, FUNDING_PARTN... | def delete(self, *args, **kwargs):
super(Partnership, self).delete(*args, **kwargs)
self.set_primary_organisation()
def set_primary_organisation(self):
# Check which organisation should be set to the primary organisation of the project
# This is done to get better performance on... | per(Partnership, self).save(*args, **kwargs)
self.set_primary_organisation()
self.project.update_use_project_roles()
| identifier_body |
partnership.py | Field
logger = logging.getLogger(__name__)
class Partnership(models.Model):
# the old way
FIELD_PARTNER = 'field'
FUNDING_PARTNER = 'funding'
SPONSOR_PARTNER = 'sponsor'
SUPPORT_PARTNER = 'support'
EXTENDING_PARTNER = 'extending'
PARTNER_TYPE_LIST = [
FIELD_PARTNER, FUNDING_PARTN... | )
)
related_activity_id = ValidXMLCharField(
_('related IATI activity ID'), max_length=100, blank=True
)
def iati_organisation_role_label(self):
return dict(self.IATI_ROLES).get(self.iati_organisation_role, '')
def iati_organisation_role_label_unicode(self):
return ... | blank=True,
help_text=_(
'Please enter the URL for where the IATI Activity Id Funding details are published. '
'For projects directly or indirectly funded by the Dutch Government, this should '
'be the OpenAid.nl page. For other projects, an alternative URL can be use... | random_line_split |
issue-4264.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 type Foo = [int, ..3u];
pub struct Bar {
pub x: [int, ..3u]
}
pub struct TupleBar([int, ..4u]);
pub enum Baz {
BazVariant([int, ..5u])
}
pub fn id<T>(x: T) -> T { x }
pub fn use_id() {
let _ = id::<[int, ..3u]>([1,2,3]);
}
fn main() {} | random_line_split | |
issue-4264.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 fn use_id() {
let _ = id::<[int, ..3u]>([1,2,3]);
}
fn main() {}
| { x } | identifier_body |
issue-4264.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 ... | ([int, ..4u]);
pub enum Baz {
BazVariant([int, ..5u])
}
pub fn id<T>(x: T) -> T { x }
pub fn use_id() {
let _ = id::<[int, ..3u]>([1,2,3]);
}
fn main() {}
| TupleBar | identifier_name |
datepicker-fr-CA.js | /* */
"format amd";
/* Canadian-French initialisation for the jQuery UI date picker plugin. */ | if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define(["../datepicker"], factory );
} else {
// Browser globals
factory( jQuery.datepicker );
}
}(function( datepicker ) {
datepicker.regional['fr-CA'] = {
closeText: 'Fermer',
prevText: 'Précédent',
nextText:... | (function( factory ) { | random_line_split |
datepicker-fr-CA.js | /* */
"format amd";
/* Canadian-French initialisation for the jQuery UI date picker plugin. */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define(["../datepicker"], factory );
} else |
}(function( datepicker ) {
datepicker.regional['fr-CA'] = {
closeText: 'Fermer',
prevText: 'Précédent',
nextText: 'Suivant',
currentText: 'Aujourd\'hui',
monthNames: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
monthNamesShort: ['ja... | {
// Browser globals
factory( jQuery.datepicker );
} | conditional_block |
pe157-solving-the-diophantine-equation-sup1supsubvaravarsubsup1supsubvarbvarsub-supvarpvarsupsub10supvarnvarsupsub.py | #!/usr/bin/env python
# coding=utf-8
"""157. Solving the diophantine equation <sup>1</sup>/<sub><var>a</var></sub>+<sup>1</sup>/<sub><var>b</var></sub>= <sup><var>p</var></sup>/<sub>10<sup><var>n</var></sup></sub>
https://projecteuler.net/problem=157
Consider the diophantine equation 1/a+1/b= p/10n with a, b, p, n po... | """ | random_line_split | |
network.js | .getInfo(Curl.info.SIZE_DOWNLOAD),
url: curl.getInfo(Curl.info.EFFECTIVE_URL),
statusMessage: 'Cancelled',
error: 'Request was cancelled'
});
// Kill it!
curl.close();
};
// Set all the basic options
setOpt(Curl.option.CUSTOMREQUEST, renderedRequ... |
// SSL Validation
if (settings.validateSSL) {
timeline.push({name: 'TEXT', value: 'Enable SSL validation'});
} else {
setOpt(Curl.option.SSL_VERIFYHOST, 0);
setOpt(Curl.option.SSL_VERIFYPEER, 0);
timeline.push({name: 'TEXT', value: 'Disable SSL validation'});
}
... | {
timeline.push({name: 'TEXT', value: 'Disable automatic URL encoding'});
} | conditional_block |
network.js | const respond = patch => {
resolve(Object.assign({
parentId: renderedRequest._id,
timeline: timeline,
settingSendCookies: renderedRequest.settingSendCookies,
settingStoreCookies: renderedRequest.settingStoreCookies
}, patch));
};
// Define helpe... | {
return new Promise(async resolve => {
function handleError (err, prefix = null) {
resolve({
url: renderedRequest.url,
parentId: renderedRequest._id,
error: prefix ? `${prefix}: ${err.message}` : err.message,
elapsedTime: 0,
statusMessage: 'Error',
settingSen... | identifier_body | |
network.js | () {
if (typeof cancelRequestFunction === 'function') {
cancelRequestFunction();
}
}
export function _actuallySend (renderedRequest, workspace, settings) {
return new Promise(async resolve => {
function handleError (err, prefix = null) {
resolve({
url: renderedRequest.url,
parentId... | cancelCurrentRequest | identifier_name | |
network.js | } catch (err) {
if (!optional) {
throw new Error(`${err.message} (${opt} ${name || 'n/a'})`);
} else {
console.warn(`Failed to set optional Curl opt (${opt} ${name || 'n/a'})`);
}
}
};
const setOptionalOpt = (opt, val) => setOpt(opt, val... | curl.setOpt(opt, val); | random_line_split | |
date-picker.d.ts | import { ElementUIComponent, ElementUIComponentSize, ElementUIHorizontalAlignment } from './component'
export type DatePickerType = 'year' | 'month' | 'date' | 'datetime' | 'week' | 'datetimerange' | 'daterange'
export type FirstDayOfWeek = 1 | 2 | 3 | 4 | 5 | 6 | 7
export interface DisabledDateChecker {
/**
* D... | extends ElementUIComponent {
/** The value of the date picker */
value: Date | string | Date[] | string[]
/** Whether DatePicker is read only */
readonly: boolean
/** Whether DatePicker is disabled */
disabled: boolean
/** Size of Input */
size: ElementUIComponentSize
/** Whether the input is edi... | ElDatePicker | identifier_name |
date-picker.d.ts | import { ElementUIComponent, ElementUIComponentSize, ElementUIHorizontalAlignment } from './component'
export type DatePickerType = 'year' | 'month' | 'date' | 'datetime' | 'week' | 'datetimerange' | 'daterange'
export type FirstDayOfWeek = 1 | 2 | 3 | 4 | 5 | 6 | 7
export interface DisabledDateChecker {
/**
* D... | // Picked date range
export interface DateRange {
minDate: Date,
maxDate: Date
}
export interface PickEventHandler {
/**
* Callback function that triggers when picks a date range
*
* @param dateRange The selected date range
*/
(dateRange: DateRange): void
}
export interface ShortcutClickEventHandl... | * @returns if `date` will be disabled in the picker
*/
(date: Date): boolean
}
| random_line_split |
mod.rs | use std::rc::Rc;
use ::runtime::units::{Unit, UnitDatabase};
use ::runtime::parse::ConvPrimitive;
use ::utils::{NO_PREFIX, prefix_as_num};
#[derive(Debug)]
pub enum ConversionError
{
OutOfRange(bool), // input or output value not a valid f64, false: input
UnitNotFound(bool), // the unit was not found, fals... |
{
Short,
Desc,
Long,
}
impl Display for ConversionFmt
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result
{
match *self
{
ConversionFmt::Short => write!(f, "s: short / value only"),
ConversionFmt::Desc => write!(f, "d: descriptive / value and output unit"),
Co... | ConversionFmt | identifier_name |
mod.rs | };
use std::rc::Rc;
use ::runtime::units::{Unit, UnitDatabase};
use ::runtime::parse::ConvPrimitive;
use ::utils::{NO_PREFIX, prefix_as_num};
#[derive(Debug)]
pub enum ConversionError
{
OutOfRange(bool), // input or output value not a valid f64, false: input
UnitNotFound(bool), // the unit was not found, f... | // S1
let mut output_val = conversion.input * prefix_as_num(
conversion.from_prefix)
.unwrap().powi(from_dims);
// S2
if from_is_inverse
{
output_val = 1.0 / output_val;
}
output_val *= from_conv_factor; // S3
output_val += from_zero_point - to_zero_point; // S4... | random_line_split | |
bar-chart.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { ChartConfiguration, ChartData, ChartEvent, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
import DataLabelsPlugin from 'chartjs-plugin-datalabels';
@Component({
selector: 'app-bar-chart',
templateUrl: './bar-char... |
public chartHovered({ event, active }: { event?: ChartEvent, active?: {}[] }): void {
console.log(event, active);
}
public randomize(): void {
// Only Change 3 values
this.barChartData.datasets[0].data = [
Math.round(Math.random() * 100),
59,
80,
Math.round(Math.random() * 1... | {
console.log(event, active);
} | identifier_body |
bar-chart.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { ChartConfiguration, ChartData, ChartEvent, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
import DataLabelsPlugin from 'chartjs-plugin-datalabels';
@Component({
selector: 'app-bar-chart',
templateUrl: './bar-char... | @ViewChild(BaseChartDirective) chart: BaseChartDirective | undefined;
public barChartOptions: ChartConfiguration['options'] = {
responsive: true,
// We use these empty structures as placeholders for dynamic theming.
scales: {
x: {},
y: {
min: 10
}
},
plugins: {
l... | export class BarChartComponent { | random_line_split |
bar-chart.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { ChartConfiguration, ChartData, ChartEvent, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
import DataLabelsPlugin from 'chartjs-plugin-datalabels';
@Component({
selector: 'app-bar-chart',
templateUrl: './bar-char... | (): void {
// Only Change 3 values
this.barChartData.datasets[0].data = [
Math.round(Math.random() * 100),
59,
80,
Math.round(Math.random() * 100),
56,
Math.round(Math.random() * 100),
40 ];
this.chart?.update();
}
}
| randomize | identifier_name |
NodeInterface.d.ts | declare namespace Jymfony.Component.Config.Definition {
/**
* Common Interface among all nodes.
*
* In most cases, it is better to inherit from BaseNode instead of implementing
* this interface yourself.
*/
export class | {
/**
* Returns the name of the node.
*
* @returns The name of the node
*/
getName(): string;
/**
* Returns the path of the node.
*
* @returns The node path
*/
getPath(): string;
/**
* Returns tru... | NodeInterface | identifier_name |
NodeInterface.d.ts | declare namespace Jymfony.Component.Config.Definition {
/**
* Common Interface among all nodes.
*
* In most cases, it is better to inherit from BaseNode instead of implementing
* this interface yourself.
*/
export class NodeInterface {
/**
* Returns the name of the node... | /**
* Normalizes the supplied value.
*
* @param value The value to normalize
*
* @returns The normalized value
*/
normalize(value: any): any;
/**
* Merges two values together.
*
* @param leftSide
* @param ... | getDefaultValue(): any;
| random_line_split |
base-level.ts | init(mapName: string) { this.mapName = mapName; }
create() {
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.physics.arcade.TILE_BIAS = 32;
this.game.stage.backgroundColor = "#a9f0ff";
// Possible fix for jittery sprites.
// See http://www.html5gamedevs.com/topic/15266-phaser-ca... |
}
// Individual levels are subclasses of BaseLevel so we can override stuff
// as needed.
export class SaturdayLevel extends BaseLevel {
preload() {
super.preload();
this.game.load.tilemap('saturday_2', 'assets/saturday_2.json', null,
Phaser.Tilemap.TILED_JSON);
}
create() {
... | {
// Enable debugging for player body.
if (this.debug) {
this.game.debug.body(this.player.sprite);
}
} | identifier_body |
base-level.ts | init(mapName: string) { this.mapName = mapName; }
| () {
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.physics.arcade.TILE_BIAS = 32;
this.game.stage.backgroundColor = "#a9f0ff";
// Possible fix for jittery sprites.
// See http://www.html5gamedevs.com/topic/15266-phaser-camera-jittering/
this.game.renderer.renderSession.roundPi... | create | identifier_name |
base-level.ts | init(mapName: string) { this.mapName = mapName; }
create() {
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.physics.arcade.TILE_BIAS = 32;
this.game.stage.backgroundColor = "#a9f0ff";
// Possible fix for jittery sprites.
// See http://www.html5gamedevs.com/topic/15266-phaser-ca... | }
return false;
}
// Given a vent tile, find the other vent tile in this map.
getOtherVent(tile: Phaser.Tile) {
// TODO Really, this is wrong. Instead, we should follow the duct until we
// hit the exit, moving the player sprite along the way.
let exitType = LEFT_VENT_IDX;
if (tile.index... | {
// Debounce this event.
let elapsedSinceLastEvent =
this.game.time.totalElapsedSeconds() - this.lastVentEventSent
// This delay is set to give us time to exit the vent after getting
// sucked through it. A better way would be to have the ventCallback
// return whether we shoul... | conditional_block |
base-level.ts | init(mapName: string) { this.mapName = mapName; }
create() {
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.physics.arcade.TILE_BIAS = 32;
this.game.stage.backgroundColor = "#a9f0ff";
// Possible fix for jittery sprites.
// See http://www.html5gamedevs.com/topic/15266-phaser-ca... | }
}
render() {
// Enable debugging for player body.
if (this.debug) {
this.game.debug.body(this.player.sprite);
}
}
}
// Individual levels are subclasses of BaseLevel so we can override stuff
// as needed.
export class SaturdayLevel extends BaseLevel {
preload() {
super.preload();
... | update() {
// TODO Instead of passing this directly, allow touch or keyboard input.
this.player.update(this.cursors);
if (this.debug) {
this.game.debug.spriteInfo(this.player.sprite, 32, 32); | random_line_split |
DragonBones.ts | // 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 and the following disclaimer... | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc. | random_line_split | |
DragonBones.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology 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:
//... | /**
* DragonBones当前数据格式版本
*/
public static DATA_VERSION:string = "4.0";
/**
*
*/
public static PARENT_COORDINATE_DATA_VERSION:string = "3.0";
public static VERSION:string = "4.3.5";
public constructor(){
}
}
} | agonBones{
| identifier_name |
DragonBones.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology 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:
//... | identifier_body | ||
rpcapi.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, Inc.
#
# 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
#
... | (self, ctxt, service_name, host,
capabilities):
self.fanout_cast(ctxt, self.make_msg('update_service_capabilities',
service_name=service_name, host=host,
capabilities=capabilities),
version='2.4')
def select_hosts(self, ctxt, request_spec, filter_... | update_service_capabilities | identifier_name |
rpcapi.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, Inc.
#
# 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
#
... |
def prep_resize(self, ctxt, instance, instance_type, image,
request_spec, filter_properties, reservations):
instance_p = jsonutils.to_primitive(instance)
instance_type_p = jsonutils.to_primitive(instance_type)
reservations_p = jsonutils.to_primitive(reservations)
image_... | return self.cast(ctxt, self.make_msg('run_instance',
request_spec=request_spec, admin_password=admin_password,
injected_files=injected_files,
requested_networks=requested_networks,
is_first_time=is_first_time,
filter_properties=filter_prope... | identifier_body |
rpcapi.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, Inc.
#
# 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
#
... |
#
# NOTE(russellb): This is the default minimum version that the server
# (manager) side must implement unless otherwise specified using a version
# argument to self.call()/cast()/etc. here. It should be left as X.0 where
# X is the current major API version (1.0, 2.0, ...). For more information
... | ''' | random_line_split |
tag.py | from collections import UserList
from copy import copy
from npc.util import print_err
class Tag(UserList):
"""
Defines a mult-value tag object
"""
def __init__(self, name: str, *args, required: bool=False, hidden: bool=False, limit: int=-1):
"""
Create a new Tag object
Args:
... | (self, value: str):
"""
Append a value to the tag
If the value is blank, skip it
Args:
value (str): The value to append
"""
if not value.strip():
return
super().append(value)
@property
def filled(self):
"""
bool:... | append | identifier_name |
tag.py | from collections import UserList
from copy import copy
from npc.util import print_err
class Tag(UserList):
"""
Defines a mult-value tag object
"""
def __init__(self, name: str, *args, required: bool=False, hidden: bool=False, limit: int=-1):
"""
Create a new Tag object
Args:
... | def valid(self):
"""
bool: Whether this tag is internally valid
This property is only meaningful after calling validate()
"""
return len(self.problems) == 0
def validate(self, strict: bool=False):
"""
Validate this tag's attributes
Validations:
... | @property | random_line_split |
tag.py | from collections import UserList
from copy import copy
from npc.util import print_err
class Tag(UserList):
"""
Defines a mult-value tag object
"""
def __init__(self, name: str, *args, required: bool=False, hidden: bool=False, limit: int=-1):
"""
Create a new Tag object
Args:
... |
def touch(self, present: bool = True):
"""
No-op for compatibility with Flag class
Args:
present (bool): Whether to mark the flag present or not present.
Defaults to True.
Returns:
None
"""
print_err("Calling touch() on non-... | """
list: All non-whitespace values
"""
return [v for v in self.data if v.strip()] | identifier_body |
tag.py | from collections import UserList
from copy import copy
from npc.util import print_err
class Tag(UserList):
"""
Defines a mult-value tag object
"""
def __init__(self, name: str, *args, required: bool=False, hidden: bool=False, limit: int=-1):
"""
Create a new Tag object
Args:
... |
return self.valid
def to_header(self):
"""
Generate a text header representation of this tag
This creates the appropriate `@tag value` lines that, when parsed, will
recreate the data of this tag. If the tag is marked as hidden, an
additional `@hide tag` will be ap... | self.problems.append("Too many values for tag '{}'. Limit of {}".format(self.name, self.limit)) | conditional_block |
static-relocation-model.rs | // revisions: x64 A64 ppc64le
// assembly-output: emit-asm
// [x64] compile-flags: --target x86_64-unknown-linux-gnu -Crelocation-model=static
// [x64] needs-llvm-components: x86
// [A64] compile-flags: --target aarch64-unknown-linux-gnu -Crelocation-model=static
// [A64] needs-llvm-components: aarch64
// [ppc64le] com... |
fn chaenomeles();
}
// CHECK-LABEL: banana:
// x64: movb chaenomeles{{(\(%[a-z0-9]+\))?}}, %{{[a-z0-9]+}}
// A64: adrp [[REG:[a-z0-9]+]], chaenomeles
// A64-NEXT: ldrb {{[a-z0-9]+}}, {{\[}}[[REG]], :lo12:chaenomeles]
#[no_mangle]
pub fn banana() -> u8 {
unsafe {
*(chaenomeles as *mut u8)
... | pub static PIERIS: u8 = 42;
extern "C" {
static EXOCHORDA: *mut u8; | random_line_split |
static-relocation-model.rs | // revisions: x64 A64 ppc64le
// assembly-output: emit-asm
// [x64] compile-flags: --target x86_64-unknown-linux-gnu -Crelocation-model=static
// [x64] needs-llvm-components: x86
// [A64] compile-flags: --target aarch64-unknown-linux-gnu -Crelocation-model=static
// [A64] needs-llvm-components: aarch64
// [ppc64le] com... | () -> &'static u8 {
&PIERIS
}
// For ppc64 we need to make sure to generate TOC entries even with the static relocation model
// ppc64le: .tc chaenomeles[TC],chaenomeles
// ppc64le: .tc banana[TC],banana
// ppc64le: .tc EXOCHORDA[TC],EXOCHORDA
// ppc64le: .tc PIERIS[TC],PIERIS
| orange | identifier_name |
static-relocation-model.rs | // revisions: x64 A64 ppc64le
// assembly-output: emit-asm
// [x64] compile-flags: --target x86_64-unknown-linux-gnu -Crelocation-model=static
// [x64] needs-llvm-components: x86
// [A64] compile-flags: --target aarch64-unknown-linux-gnu -Crelocation-model=static
// [A64] needs-llvm-components: aarch64
// [ppc64le] com... |
// For ppc64 we need to make sure to generate TOC entries even with the static relocation model
// ppc64le: .tc chaenomeles[TC],chaenomeles
// ppc64le: .tc banana[TC],banana
// ppc64le: .tc EXOCHORDA[TC],EXOCHORDA
// ppc64le: .tc PIERIS[TC],PIERIS
| {
&PIERIS
} | identifier_body |
unsized.rs | // compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *a |
// gdb-command:print *b
// gdbg-check:$2 = {value = {value = [...] "abc"}}
// gdbr-check:$2 = unsized::Foo<unsized::Foo<[u8]>> {value: unsized::Foo<[u8]> {value: [...]}}
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
struct Foo<T: ?Sized> {
value: T
}
fn main() {
let foo: ... | // gdbg-check:$1 = {value = [...] "abc"}
// gdbr-check:$1 = unsized::Foo<[u8]> {value: [...]} | random_line_split |
unsized.rs | // compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *a
// gdbg-check:$1 = {value = [...] "abc"}
// gdbr-check:$1 = unsized::Foo<[u8]> {value: [...]}
// gdb-command:print *b
// gdbg-check:$2 = {value = {value... | <T: ?Sized> {
value: T
}
fn main() {
let foo: Foo<Foo<[u8; 4]>> = Foo {
value: Foo {
value: *b"abc\0"
}
};
let a: &Foo<[u8]> = &foo.value;
let b: &Foo<Foo<[u8]>> = &foo;
zzz(); // #break
}
fn zzz() { () }
| Foo | identifier_name |
feature-gate-unboxed-closures-manual-impls.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 ... | }
fn main() {} | struct Baz;
impl FnOnce<(), ()> for Baz { //~ ERROR manual implementations of `FnOnce` are experimental
extern "rust-call" fn call_once(&self, args: ()) -> () {} | random_line_split |
feature-gate-unboxed-closures-manual-impls.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 ... |
}
struct Baz;
impl FnOnce<(), ()> for Baz { //~ ERROR manual implementations of `FnOnce` are experimental
extern "rust-call" fn call_once(&self, args: ()) -> () {}
}
fn main() {}
| {} | identifier_body |
feature-gate-unboxed-closures-manual-impls.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 ... | (&self, args: ()) -> () {}
}
struct Baz;
impl FnOnce<(), ()> for Baz { //~ ERROR manual implementations of `FnOnce` are experimental
extern "rust-call" fn call_once(&self, args: ()) -> () {}
}
fn main() {}
| call_mut | identifier_name |
onEnter.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (opts?: IOnEnterSupportOptions) {
opts = opts || {};
opts.brackets = opts.brackets || [
['(', ')'],
['{', '}'],
['[', ']']
];
this._brackets = [];
opts.brackets.forEach((bracket) => {
const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]);
const closeRegExp = OnEnterSupport._cr... | constructor | identifier_name |
onEnter.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
| {
try {
return new RegExp(def);
} catch (err) {
onUnexpectedError(err);
return null;
}
} | identifier_body |
onEnter.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | ['{', '}'],
['[', ']']
];
this._brackets = [];
opts.brackets.forEach((bracket) => {
const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]);
const closeRegExp = OnEnterSupport._createCloseBracketRegExp(bracket[1]);
if (openRegExp && closeRegExp) {
this._brackets.push({
open... | opts.brackets = opts.brackets || [
['(', ')'], | random_line_split |
onEnter.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
}
// (4): Open bracket based logic
if (beforeEnterText.length > 0) {
for (let i = 0, len = this._brackets.length; i < len; i++) {
let bracket = this._brackets[i];
if (bracket.openRegExp.test(beforeEnterText)) {
return { indentAction: IndentAction.Indent };
}
}
}
return null;
}... | {
return { indentAction: IndentAction.IndentOutdent };
} | conditional_block |
main.rs | extern crate tera;
use std::alloc::System;
use tera::{Context, Tera};
#[global_allocator]
static GLOBAL: System = System;
static BIG_TABLE_TEMPLATE: &'static str = "<table>
{% for row in table %}
<tr>{% for col in row %}<td>{{ col }}</td>{% endfor %}</tr>
{% endfor %}
</table>";
fn main() {
let size = 100;
... | table.push(inner);
}
let mut tera = Tera::default();
tera.add_raw_templates(vec![("big-table.html", BIG_TABLE_TEMPLATE)]).unwrap();
let mut ctx = Context::new();
ctx.insert("table", &table);
let _ = tera.render("big-table.html", &ctx).unwrap();
println!("Done!");
} | inner.push(i);
} | random_line_split |
main.rs | extern crate tera;
use std::alloc::System;
use tera::{Context, Tera};
#[global_allocator]
static GLOBAL: System = System;
static BIG_TABLE_TEMPLATE: &'static str = "<table>
{% for row in table %}
<tr>{% for col in row %}<td>{{ col }}</td>{% endfor %}</tr>
{% endfor %}
</table>";
fn | () {
let size = 100;
let mut table = Vec::with_capacity(size);
for _ in 0..size {
let mut inner = Vec::with_capacity(size);
for i in 0..size {
inner.push(i);
}
table.push(inner);
}
let mut tera = Tera::default();
tera.add_raw_templates(vec![("big-tab... | main | identifier_name |
main.rs | extern crate tera;
use std::alloc::System;
use tera::{Context, Tera};
#[global_allocator]
static GLOBAL: System = System;
static BIG_TABLE_TEMPLATE: &'static str = "<table>
{% for row in table %}
<tr>{% for col in row %}<td>{{ col }}</td>{% endfor %}</tr>
{% endfor %}
</table>";
fn main() | {
let size = 100;
let mut table = Vec::with_capacity(size);
for _ in 0..size {
let mut inner = Vec::with_capacity(size);
for i in 0..size {
inner.push(i);
}
table.push(inner);
}
let mut tera = Tera::default();
tera.add_raw_templates(vec![("big-table.... | identifier_body | |
bitFunctions.js | var wru = require('wru');
var collection = [];
var functions = require('./..');
var setBit = functions.setBit;
var resetBit = functions.resetBit;
var isSetBit = functions.isSetBit;
var toggleBit = functions.toggleBit;
var result;
collection[collection.length] = function() {
var bitMask = 5; // 1 + 0 + 4
wru.assert("... | wru.assert("resetBit test 2", resetBit(bitMask, 4) === 1);
};
collection[collection.length] = function() {
var bitMask = 5; // 1 + 0 + 4
wru.assert("isSetBit test 1", isSetBit(bitMask, 2) === false);
wru.assert("isSetBit test 2", isSetBit(bitMask, 4) === true);
};
collection[collection.length] = function() {
var... | random_line_split | |
GlobalError.js | /* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2008 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/d... | /* ************************************************************************
#ignore(qx.core.Environment)
************************************************************************ */
/**
* The GlobalError class stores a reference to a global error handler function.
*
* This function is called for each uncatched Ja... | random_line_split | |
GlobalError.js | /* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2008 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/d... |
},
/**
* Set the global fallback error handler
*
* @param callback {Function} The error handler. The first argument is the
* exception, which caused the error
* @param context {Object} The "this" context of the callback function
*/
setErrorHandler : function(callback, con... | {
return !!qx.Bootstrap.getEnvironmentSetting("qx.globalErrorHandling");
} | conditional_block |
cartridgesavecouk.py | import re
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, FormRequest, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.http import FormRequest
from productloader import load_product
im... | (self, response):
if not isinstance(response, HtmlResponse):
return
#categories
hxs = HtmlXPathSelector(response)
# printer brands
printers_brands = hxs.select('//div[@id="manufacturers"]//li/a/@href').extract()
for url in printers_brands:
url = ur... | parse | identifier_name |
cartridgesavecouk.py | import re
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, FormRequest, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.http import FormRequest
from productloader import load_product
im... | # yield Request(url)
# products
products = hxs.select('//div[@class="group_products"]//li/a[not(@class="lowest_price info")]/@href').extract()
for product in products:
product = urljoin_rfc(self.URL_BASE, product)
yield Request(product, callback=self.parse_pr... | if not isinstance(response, HtmlResponse):
return
#categories
hxs = HtmlXPathSelector(response)
# printer brands
printers_brands = hxs.select('//div[@id="manufacturers"]//li/a/@href').extract()
for url in printers_brands:
url = urljoin_rfc(self.URL_BASE, u... | identifier_body |
cartridgesavecouk.py | import re
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, FormRequest, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.http import FormRequest
from productloader import load_product
im... | except IndexError:
return
def parse(self, response):
if not isinstance(response, HtmlResponse):
return
#categories
hxs = HtmlXPathSelector(response)
# printer brands
printers_brands = hxs.select('//div[@id="manufacturers"]//li/a/@href').extra... | res['price'] = price
res['sku'] = res['description']
yield load_product(res, response) | random_line_split |
cartridgesavecouk.py | import re
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, FormRequest, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.http import FormRequest
from productloader import load_product
im... | product = urljoin_rfc(self.URL_BASE, product)
yield Request(product, callback=self.parse_product) | conditional_block | |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | () {
let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap();
let mut acceptor = net::tcp::TcpListener::bind(addr).listen();
println(format!("Listening on [{:s}] ...", addr.to_str()));
for stream in acceptor.incoming() {
// Spawn a task to handle the connection
... | main | identifier_name |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | stream.read(buf);
let request_str = str::from_utf8(buf).to_owned();
if(request_str.contains("GET")){
let tempstr: ~[&str]= request_str.split(' ').collect();
if(tempstr[1].len() >2){
let file = Path::new(tempstr[1].slice_from(1));
println!("{}",tempstr[1].slice_from(1));
if temp... | },
None => ()
}
let mut buf = [0, ..500]; | random_line_split |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... |
let mut buf = [0, ..500];
stream.read(buf);
let request_str = str::from_utf8(buf).to_owned();
if(request_str.contains("GET")){
let tempstr: ~[&str]= request_str.split(' ').collect();
if(tempstr[1].len() >2){
let file = Path::new(tempstr[1].slice_from(1));
... | {
let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap();
let mut acceptor = net::tcp::TcpListener::bind(addr).listen();
println(format!("Listening on [{:s}] ...", addr.to_str()));
for stream in acceptor.incoming() {
// Spawn a task to handle the connection
... | identifier_body |
domstringmap.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMStringMapBinding;
use dom::bindings::codegen::Bindings::DOMStringMapBindi... | GlobalRef::Window(window.r()),
DOMStringMapBinding::Wrap)
}
}
// https://html.spec.whatwg.org/multipage/#domstringmap
impl DOMStringMapMethods for DOMStringMap {
// https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem
fn NamedDeleter(&sel... | }
pub fn new(element: &HTMLElement) -> Root<DOMStringMap> {
let window = window_from_node(element);
reflect_dom_object(box DOMStringMap::new_inherited(element), | random_line_split |
domstringmap.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMStringMapBinding;
use dom::bindings::codegen::Bindings::DOMStringMapBindi... |
}
// https://html.spec.whatwg.org/multipage/#domstringmap
impl DOMStringMapMethods for DOMStringMap {
// https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem
fn NamedDeleter(&self, name: DOMString) {
self.element.delete_custom_attr(name)
}
// https://html.spec.whatwg.org/multip... | {
let window = window_from_node(element);
reflect_dom_object(box DOMStringMap::new_inherited(element),
GlobalRef::Window(window.r()),
DOMStringMapBinding::Wrap)
} | identifier_body |
domstringmap.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMStringMapBinding;
use dom::bindings::codegen::Bindings::DOMStringMapBindi... | (&self) -> Vec<DOMString> {
self.element.supported_prop_names_custom_attr().iter().cloned().collect()
}
}
| SupportedPropertyNames | identifier_name |
getOccurrencesSwitchCaseDefaultBroken.ts | /// <reference path='fourslash.ts' />
////swi/*1*/tch(10) {
//// case 1:
//// case 2:
//// c/*2*/ase 4:
//// case 8:
//// case 0xBEEF:
//// de/*4*/fult:
//// break;
//// /*5*/cas 16:
//// c/*3*/ase 12:
| //// }
////}
////
////sw/*6*/itch (10) {
//// de/*7*/fault
//// case 1:
//// case 2
////
//// c/*8*/ose 4:
//// case 8:
//// case 0xBEEF:
//// bre/*9*/ak;
//// case 16:
//// () => bre/*10*/ak;
////}
for (var i = 1; i <= test.markers().length; i++) {
goTo.m... | //// function f() {
//// br/*11*/eak;
//// /*12*/break;
| random_line_split |
getOccurrencesSwitchCaseDefaultBroken.ts | /// <reference path='fourslash.ts' />
////swi/*1*/tch(10) {
//// case 1:
//// case 2:
//// c/*2*/ase 4:
//// case 8:
//// case 0xBEEF:
//// de/*4*/fult:
//// break;
//// /*5*/cas 16:
//// c/*3*/ase 12:
//// function f() {
//// br/*11*/eak;
//// ... | case 11:
case 12:
verify.occurrencesAtPositionCount(0);
break;
}
} | {
goTo.marker("" + i);
switch (i) {
case 1:
case 2:
case 3:
verify.occurrencesAtPositionCount(8);
break;
case 4:
verify.occurrencesAtPositionCount(1);
break;
case 6:
case 7:
case 9:
... | conditional_block |
image.py | from .attribute import html_attribute
from .element import VoidElement
class | (VoidElement):
"""An HTML image (<img>) element.
Images must have an alternate text description that describes the
contents of the image, if the image can not be displayed. In some
cases the alternate text can be empty. For example, if the image just
displays a company logo next to the company's na... | Image | identifier_name |
image.py | from .attribute import html_attribute
from .element import VoidElement
class Image(VoidElement):
"""An HTML image (<img>) element.
Images must have an alternate text description that describes the
contents of the image, if the image can not be displayed. In some
cases the alternate text can be empty.... |
url = html_attribute("src")
alternate_text = html_attribute("alt")
title = html_attribute("title")
| super().__init__("img")
self.url = url
self.alternate_text = alternate_text | identifier_body |
image.py | from .attribute import html_attribute
from .element import VoidElement
class Image(VoidElement):
"""An HTML image (<img>) element.
Images must have an alternate text description that describes the
contents of the image, if the image can not be displayed. In some
cases the alternate text can be empty.... | ... "A whiteboard filled with mathematical formulas.")
>>> image.title = "Whiteboards are a useful tool"
"""
def __init__(self, url, alternate_text=""):
super().__init__("img")
self.url = url
self.alternate_text = alternate_text
url = html_attribute("s... | Example:
>>> image = Image("whiteboard.jpg", | random_line_split |
run_comet_full.py | parser.add_argument('--parallel', default=False, action='store_true',
help='Use multiprocessing to run a job on each core.')
parser.add_argument('-np', '--num_permutations', required=True, type=int,
help='Number of permuted matrices to use.')
# Mutation data
... | if args.verbose: print "* Creating bipartite graph..."
G = C.construct_mutation_graph(geneToCases, patientToGenes)
if args.verbose:
print '\t- Graph has', len( G.edges() ), 'edges among', len( G.nodes() ), 'nodes.'
# reset the arguments for a general CoMEt run on permuted matrices
cometArgs... | realOutputDir = "{}/comet-results".format(args.output_directory)
realCometArgs = []
permuteFlags = ["-np", "--parallel", "--keep_temp_files", "-o"]
for i, arg in enumerate(sys.argv[1:]):
if arg not in permuteFlags and sys.argv[i] not in permuteFlags:
realCometArgs.append( arg )
... | identifier_body |
run_comet_full.py | parser.add_argument('--parallel', default=False, action='store_true',
help='Use multiprocessing to run a job on each core.')
parser.add_argument('-np', '--num_permutations', required=True, type=int,
help='Number of permuted matrices to use.')
# Mutation data
... | ( args ):
# Set up the arguments for a general CoMEt run on real data
realOutputDir = "{}/comet-results".format(args.output_directory)
realCometArgs = []
permuteFlags = ["-np", "--parallel", "--keep_temp_files", "-o"]
for i, arg in enumerate(sys.argv[1:]):
if arg not in permuteFlags and sys... | run | identifier_name |
run_comet_full.py | parser.add_argument('--parallel', default=False, action='store_true',
help='Use multiprocessing to run a job on each core.')
parser.add_argument('-np', '--num_permutations', required=True, type=int,
help='Number of permuted matrices to use.')
# Mutation data
... |
# Find the maximum test statistic on the permuted datasets
from itertools import islice
maxStat = 0
for rf in [ rf for rf in os.listdir(directory) if rf.startswith("comet-results-on-permutation") ]:
for df in [df for df in os.listdir("{}/{}/results".format(directory, rf) ) if df.endswith... | results = [ runComet(permuteArgs) for permuteArgs in arguments ] | conditional_block |
run_comet_full.py | parser.add_argument('--parallel', default=False, action='store_true',
help='Use multiprocessing to run a job on each core.')
parser.add_argument('-np', '--num_permutations', required=True, type=int,
help='Number of permuted matrices to use.')
# Mutation data
... | # Parameters for marginal probability graph (optional)
# File mapping genes/events to new names (optional).
parser.add_argument('-e', '--event_names', default=None, help=argparse.SUPPRESS)
# File mapping samples to cancer types.
parser.add_argument('-st', '--sample_types_file', default=None, help=ar... | help='File with a list of subtype for performing subtype-comet.')
parser.add_argument('-ce', '--core_events', default=None,
help='File with a list of core events for performing subtype-comet.')
# Hidden parameters: users can still use these parameters but the... | random_line_split |
video.rs | use ffmpeg::frame;
use glium::texture::{SrgbTexture2d};
use glium::{Program, Display, VertexBuffer, Surface};
use glium::buffer::BufferView;
use glium::buffer::BufferMode::Persistent;
use glium::buffer::BufferType::PixelUnpackBuffer;
use glium::index::PrimitiveType::TriangleStrip;
use glium::index::NoIndices;
use gliu... | <'a> {
display: &'a Display,
program: Program,
vertices: VertexBuffer<Vertex>,
timestamp: i64,
buffer: Option<BufferView<[(u8, u8, u8, u8)]>>,
texture: Option<SrgbTexture2d>,
}
impl<'a> Video<'a> {
pub fn new<'b>(display: &'b Display) -> Video<'b> {
Video {
display: display,
program: program!(d... | Video | identifier_name |
video.rs | use ffmpeg::frame;
use glium::texture::{SrgbTexture2d};
use glium::{Program, Display, VertexBuffer, Surface};
use glium::buffer::BufferView;
use glium::buffer::BufferMode::Persistent;
use glium::buffer::BufferType::PixelUnpackBuffer;
use glium::index::PrimitiveType::TriangleStrip;
use glium::index::NoIndices;
use gliu... |
// write to the buffer
self.buffer.as_mut().unwrap().write(frame.plane(0));
// write the buffer to the texture
self.texture.as_mut().unwrap().main_level()
.raw_upload_from_pixel_buffer_inverted(self.buffer.as_ref().unwrap().as_slice(),
0 .. frame.width(), 0 .. frame.height(), 0 .. 1);
}
let... | {
self.buffer = Some(BufferView::empty_array(self.display,
PixelUnpackBuffer,
(frame.width() * frame.height()) as usize,
Persistent).unwrap());
self.texture = Some(SrgbTexture2d::empty_with_format(self.display,
U8U8U8U8, NoMipmap, frame.width(), frame.height()).unwrap());
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.