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 |
|---|---|---|---|---|
getLinks.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): ILink {
return {
range: this.range,
url: this.url
};
}
get range(): IRange {
return this._link.range;
}
get url(): string {
return this._link.url;
}
resolve(): TPromise<URI> {
if (this._link.url) {
try {
return TPromise.as(URI.parse(this._link.url));
} catch (e) {
return TProm... | toJSON | identifier_name |
getLinks.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
get url(): string {
return this._link.url;
}
resolve(): TPromise<URI> {
if (this._link.url) {
try {
return TPromise.as(URI.parse(this._link.url));
} catch (e) {
return TPromise.wrapError<URI>(new Error('invalid'));
}
}
if (typeof this._provider.resolveLink === 'function') {
return asW... | {
return this._link.range;
} | identifier_body |
app.component.ts | import { Component } from '@angular/core';
import {RecipesService} from "./services/recipes.service";
import {Observable} from "rxjs";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
}) | constructor(private recipesService:RecipesService){}
ngOnInit(){
this.options={
debug: true,
blankLabel: 'n/a',
outer_form: 'both',
add:{
display:true,
caption: 'both',// head, title, both
show: false
},
editable: {
display: true,
show:... | export class AppComponent {
public recipes:any=[]
public options:any={}
public tableMessages:any=[]
public timer:any | random_line_split |
app.component.ts | import { Component } from '@angular/core';
import {RecipesService} from "./services/recipes.service";
import {Observable} from "rxjs";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public recipes:any=[]
public options... |
this.tableMessages.push(event)
this.timer=Observable.interval(3000).subscribe(() => {
this.tableMessages=[]
this.timer.unsubscribe()
})
console.log(event)
}
}
| {
this.timer.unsubscribe()
} | conditional_block |
app.component.ts | import { Component } from '@angular/core';
import {RecipesService} from "./services/recipes.service";
import {Observable} from "rxjs";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public recipes:any=[]
public options... | (event:any){
if(this.tableMessages.length>0){
this.timer.unsubscribe()
}
this.tableMessages.push(event)
this.timer=Observable.interval(3000).subscribe(() => {
this.tableMessages=[]
this.timer.unsubscribe()
})
console.log(event)
}
}
| updateMesage | identifier_name |
app.component.ts | import { Component } from '@angular/core';
import {RecipesService} from "./services/recipes.service";
import {Observable} from "rxjs";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public recipes:any=[]
public options... |
updateMesage(event:any){
if(this.tableMessages.length>0){
this.timer.unsubscribe()
}
this.tableMessages.push(event)
this.timer=Observable.interval(3000).subscribe(() => {
this.tableMessages=[]
this.timer.unsubscribe()
})
console.log(event)
}
}
| {
option!=option
} | identifier_body |
Map.ts | /// <reference path="lib/leaflet.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
class TweetMap {
private _map: L.Map;
constructor(div: string = 'map') {
this._map = new L.Map(div).setView(new L.LatLng(45.41, -75.698), 12);
L.tileLayer('http://services.arcgisonline.com/arcgis/r... |
}
| {
$.each(tweets, function(index: number, tweet: Tweet): void {
tweet.marker.closePopup();
});
$('.leaflet-marker-pane, .leaflet-shadow-pane').fadeToggle();
} | identifier_body |
Map.ts | /// <reference path="lib/leaflet.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
class TweetMap {
private _map: L.Map;
constructor(div: string = 'map') {
this._map = new L.Map(div).setView(new L.LatLng(45.41, -75.698), 12);
L.tileLayer('http://services.arcgisonline.com/arcgis/r... | (tweet: Tweet): void {
this._map.addLayer(tweet.marker);
}
removeTweet(tweet: Tweet): void {
this._map.removeLayer(tweet.marker);
}
panTo(tweet: Tweet): void {
this._map.panTo(tweet.marker.getLatLng());
tweet.marker.openPopup();
}
// Toggles the marker and shadow panes off -also closes any popup window... | addTweet | identifier_name |
Map.ts | /// <reference path="lib/leaflet.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
class TweetMap {
private _map: L.Map;
constructor(div: string = 'map') {
this._map = new L.Map(div).setView(new L.LatLng(45.41, -75.698), 12);
L.tileLayer('http://services.arcgisonline.com/arcgis/r... | } | random_line_split | |
script.js | /*****************************************************************************
** ANGRYBIRDS AI AGENT FRAMEWORK
** Copyright (c) 2014,XiaoYu (Gary) Ge, Stephen Gould,Jochen Renz
** Sahan Abeyasinghe, Jim Keys, Andrew Wang, Peng Zhang
** All rights reserved.
**This work is licensed under the terms of the GNU Affe... | else {
console.log('Invalid message: ' + e.type);
}
};
sock.onerror = function(e) {
sock = null;
reconnect();
};
}
function reconnect() {
setTimeout(connect, 1000);
}
function send(id, data) {
... | {
send(id, handlers[type](data));
} | conditional_block |
script.js | /*****************************************************************************
** ANGRYBIRDS AI AGENT FRAMEWORK
** Copyright (c) 2014,XiaoYu (Gary) Ge, Stephen Gould,Jochen Renz
** Sahan Abeyasinghe, Jim Keys, Andrew Wang, Peng Zhang
** All rights reserved.
**This work is licensed under the terms of the GNU Affe... | (data) {
var delta = data['delta'];
var canvas = $('canvas');
//var evt = document.createEvent('WheelEvent');
var eventInit = { deltaX: 0, deltaY: -delta*120 }
var evt = new WheelEvent("mousewheel", eventInit);
//evt.initWebKitWheelEvent(0, delta, window, 0, 0, 0, 0, false, false, false, false);
canvas[0]... | mousewheel | identifier_name |
script.js | /*****************************************************************************
** ANGRYBIRDS AI AGENT FRAMEWORK
** Copyright (c) 2014,XiaoYu (Gary) Ge, Stephen Gould,Jochen Renz
** Sahan Abeyasinghe, Jim Keys, Andrew Wang, Peng Zhang
** All rights reserved.
**This work is licensed under the terms of the GNU Affe... |
// define supported message handlers
var handlers = {
'click': click,
'drag': drag,
'mousewheel': mousewheel,
'screenshot': screenshot
};
// generate a mouse click event
function click(data) {
var x = data['x'];
var y = data['y'];
... | {
var msg = JSON.stringify([id, data || {}]);
sock.send(msg);
} | identifier_body |
script.js | /*****************************************************************************
** ANGRYBIRDS AI AGENT FRAMEWORK
** Copyright (c) 2014,XiaoYu (Gary) Ge, Stephen Gould,Jochen Renz
** Sahan Abeyasinghe, Jim Keys, Andrew Wang, Peng Zhang
** All rights reserved.
**This work is licensed under the terms of the GNU Affe... | evt.initMouseEvent('mousemove', true, true, window, 0, 0, 0, dx, dy, false, false, false, false, 0, null);
canvas[0].dispatchEvent(evt);
evt = document.createEvent('MouseEvent');
evt.initMouseEvent('mouseup', true, true, window, 1, 0, 0, dx, dy, false, false, false, false, 0, nu... |
evt = document.createEvent('MouseEvent'); | random_line_split |
universalCamera.ts | import { TouchCamera } from "./touchCamera";
import { Node } from "../node";
import { FreeCameraGamepadInput } from "../Cameras/Inputs/freeCameraGamepadInput";
import { Scene } from "../scene";
import { Vector3 } from "../Maths/math.vector";
import { Camera } from "./camera";
import "../Gamepads/gamepadSceneCom... |
}
/**
* Defines the gamepad move sensiblity.
* This is the threshold from when moving starts to be accounted for for to prevent jittering.
*/
public get gamepadMoveSensibility(): number {
var gamepad = <FreeCameraGamepadInput>this.inputs.attached["gamepad"];
if (gam... | {
gamepad.gamepadAngularSensibility = value;
} | conditional_block |
universalCamera.ts | import { TouchCamera } from "./touchCamera";
import { Node } from "../node";
import { FreeCameraGamepadInput } from "../Cameras/Inputs/freeCameraGamepadInput";
import { Scene } from "../scene";
import { Vector3 } from "../Maths/math.vector";
import { Camera } from "./camera";
import "../Gamepads/gamepadSceneCom... | (): number {
var gamepad = <FreeCameraGamepadInput>this.inputs.attached["gamepad"];
if (gamepad) {
return gamepad.gamepadMoveSensibility;
}
return 0;
}
public set gamepadMoveSensibility(value: number) {
var gamepad = <FreeCameraGamepadInput>this.in... | gamepadMoveSensibility | identifier_name |
universalCamera.ts | import { TouchCamera } from "./touchCamera";
import { Node } from "../node";
import { FreeCameraGamepadInput } from "../Cameras/Inputs/freeCameraGamepadInput";
import { Scene } from "../scene";
import { Vector3 } from "../Maths/math.vector";
import { Camera } from "./camera";
import "../Gamepads/gamepadSceneCom... | public set gamepadAngularSensibility(value: number) {
var gamepad = <FreeCameraGamepadInput>this.inputs.attached["gamepad"];
if (gamepad) {
gamepad.gamepadAngularSensibility = value;
}
}
/**
* Defines the gamepad move sensiblity.
* This is the threshol... |
return 0;
}
| random_line_split |
universalCamera.ts | import { TouchCamera } from "./touchCamera";
import { Node } from "../node";
import { FreeCameraGamepadInput } from "../Cameras/Inputs/freeCameraGamepadInput";
import { Scene } from "../scene";
import { Vector3 } from "../Maths/math.vector";
import { Camera } from "./camera";
import "../Gamepads/gamepadSceneCom... |
/**
* The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
* which still works and will still be found in many Playgrounds.
* @see https://doc.babylonjs.com/features/cam... | {
var gamepad = <FreeCameraGamepadInput>this.inputs.attached["gamepad"];
if (gamepad) {
gamepad.gamepadMoveSensibility = value;
}
} | identifier_body |
mod.rs | 'tcx> {
fn consume(&mut self,
consume_id: ast::NodeId,
_consume_span: Span,
cmt: mc::cmt<'tcx>,
mode: euv::ConsumeMode) {
debug!("consume(consume_id={}, cmt={}, mode={:?})",
consume_id, cmt.repr(self.tcx()), mode);
match mo... | (&mut self,
assignment_id: ast::NodeId,
assignment_span: Span,
assignee_cmt: mc::cmt<'tcx>,
mode: euv::MutateMode)
{
debug!("mutate(assignment_id={}, assignee_cmt={})",
assignment_id, assignee_cmt.repr(self.tcx()));
match opt_lo... | mutate | identifier_name |
mod.rs | 'tcx> {
fn consume(&mut self,
consume_id: ast::NodeId,
_consume_span: Span,
cmt: mc::cmt<'tcx>,
mode: euv::ConsumeMode) {
debug!("consume(consume_id={}, cmt={}, mode={:?})",
consume_id, cmt.repr(self.tcx()), mode);
match mo... |
(Some(mc::AliasableStatic(safety)), ty::ImmBorrow) => {
// Borrow of an immutable static item:
match safety {
mc::InteriorUnsafe => {
// If the static item contains an Unsafe<T>, it has interior
// mutability. In such cases, anoth... | {
/* Uniquely accessible path -- OK for `&` and `&mut` */
Ok(())
} | conditional_block |
mod.rs | , 'tcx> {
fn consume(&mut self,
consume_id: ast::NodeId,
_consume_span: Span,
cmt: mc::cmt<'tcx>,
mode: euv::ConsumeMode) {
debug!("consume(consume_id={}, cmt={}, mode={:?})",
consume_id, cmt.repr(self.tcx()), mode);
match m... | }
gather_moves::gather_move_from_pat(
self.bccx, &self.move_data, &self.move_error_collector,
consume_pat, cmt);
}
fn borrow(&mut self,
borrow_id: ast::NodeId,
borrow_span: Span,
cmt: mc::cmt<'tcx>,
loan_region: ty... | euv::Move(_) => { } | random_line_split |
mod.rs | fn guarantee_valid(&mut self,
borrow_id: ast::NodeId,
borrow_span: Span,
cmt: mc::cmt<'tcx>,
req_kind: ty::BorrowKind,
loan_region: ty::Region,
cause: euv::LoanCause) {
d... | {
self.move_error_collector.report_potential_errors(self.bccx);
} | identifier_body | |
mips.rs | //! Run-time feature detection for MIPS on Linux.
use crate::detect::{Feature, cache, bit};
use super::auxvec;
/// Performs run-time feature detection.
#[inline]
pub fn check_for(x: Feature) -> bool {
cache::test(x as u32, detect_features)
}
/// Try to read the features from the auxiliary vector, and if that fai... | () -> cache::Initializer {
let mut value = cache::Initializer::default();
let enable_feature = |value: &mut cache::Initializer, f, enable| {
if enable {
value.set(f as u32);
}
};
// The values are part of the platform-specific [asm/hwcap.h][hwcap]
//
// [hwcap]: http... | detect_features | identifier_name |
mips.rs | //! Run-time feature detection for MIPS on Linux.
use crate::detect::{Feature, cache, bit};
use super::auxvec;
/// Performs run-time feature detection.
#[inline]
pub fn check_for(x: Feature) -> bool {
cache::test(x as u32, detect_features)
}
/// Try to read the features from the auxiliary vector, and if that fai... |
};
// The values are part of the platform-specific [asm/hwcap.h][hwcap]
//
// [hwcap]: https://github.com/torvalds/linux/blob/master/arch/arm64/include/uapi/asm/hwcap.h
if let Ok(auxv) = auxvec::auxv() {
enable_feature(&mut value, Feature::msa, bit::test(auxv.hwcap, 1));
return val... | {
value.set(f as u32);
} | conditional_block |
mips.rs | //! Run-time feature detection for MIPS on Linux.
use crate::detect::{Feature, cache, bit};
use super::auxvec;
/// Performs run-time feature detection.
#[inline]
pub fn check_for(x: Feature) -> bool {
cache::test(x as u32, detect_features)
}
/// Try to read the features from the auxiliary vector, and if that fai... | {
let mut value = cache::Initializer::default();
let enable_feature = |value: &mut cache::Initializer, f, enable| {
if enable {
value.set(f as u32);
}
};
// The values are part of the platform-specific [asm/hwcap.h][hwcap]
//
// [hwcap]: https://github.com/torvalds/l... | identifier_body | |
mips.rs | //! Run-time feature detection for MIPS on Linux.
use crate::detect::{Feature, cache, bit};
use super::auxvec;
/// Performs run-time feature detection.
#[inline]
pub fn check_for(x: Feature) -> bool {
cache::test(x as u32, detect_features)
}
/// Try to read the features from the auxiliary vector, and if that fai... | } | // TODO: fall back via `cpuinfo`.
value | random_line_split |
type_symbol_table.py | """
A symbol table object to hold types for the parser.
"""
from __future__ import absolute_import, division, print_function
__all__ = ['TypeSymbolTable', 'sym']
import ctypes
from . import coretypes as ct
_is_64bit = (ctypes.sizeof(ctypes.c_void_p) == 8)
def _complex(tp):
"""Simple temporary type constructor... |
else:
raise TypeError('Cannot contruct a complex type with real component %s' % tp)
def _struct(names, dshapes):
"""Simple temporary type constructor for struct"""
return ct.Record(list(zip(names, dshapes)))
def _funcproto(args, ret):
"""Simple temporary type constructor for funcproto"""
... | return ct.complex_float64 | conditional_block |
type_symbol_table.py | """
A symbol table object to hold types for the parser.
"""
from __future__ import absolute_import, division, print_function
__all__ = ['TypeSymbolTable', 'sym']
import ctypes
from . import coretypes as ct
_is_64bit = (ctypes.sizeof(ctypes.c_void_p) == 8)
def _complex(tp):
"""Simple temporary type constructor... | return ct.complex_float32
elif tp == ct.DataShape(ct.float64):
return ct.complex_float64
else:
raise TypeError('Cannot contruct a complex type with real component %s' % tp)
def _struct(names, dshapes):
"""Simple temporary type constructor for struct"""
return ct.Record(list(zip(... | random_line_split | |
type_symbol_table.py | """
A symbol table object to hold types for the parser.
"""
from __future__ import absolute_import, division, print_function
__all__ = ['TypeSymbolTable', 'sym']
import ctypes
from . import coretypes as ct
_is_64bit = (ctypes.sizeof(ctypes.c_void_p) == 8)
def _complex(tp):
"""Simple temporary type constructor... | self.dtype_constr = {}
self.dim = {}
self.dim_constr = {}
if not bare:
self.add_default_types()
def add_default_types(self):
"""
Adds all the default datashape types to the symbol table.
"""
# data types with no type constructor
se... | """
This is a class which holds symbols for types and type constructors,
and is used by the datashape parser to build types during its parsing.
A TypeSymbolTable sym has four tables, as follows:
sym.dtype
Data type symbols with no type constructor.
sym.dtype_constr
Data type symbols... | identifier_body |
type_symbol_table.py | """
A symbol table object to hold types for the parser.
"""
from __future__ import absolute_import, division, print_function
__all__ = ['TypeSymbolTable', 'sym']
import ctypes
from . import coretypes as ct
_is_64bit = (ctypes.sizeof(ctypes.c_void_p) == 8)
def _complex(tp):
"""Simple temporary type constructor... | (names, dshapes):
"""Simple temporary type constructor for struct"""
return ct.Record(list(zip(names, dshapes)))
def _funcproto(args, ret):
"""Simple temporary type constructor for funcproto"""
return ct.Function(*(args + [ret]))
def _typevar_dim(name):
"""Simple temporary type constructor for typ... | _struct | identifier_name |
WebGLSpriteBatch.js | /**
* Created by chenqx on 8/5/15.
* @hack 添加三角形绘制提交方式
*/
/**
* 以四边形填充
* @constant
* @type {number}
*/
qc.BATCH_QUAD = 0;
/**
* 以三角形填充
* @constant
* @type {number}
*/
qc.BATCH_TRIANGLES = 1;
var oldWebGLSpriteBatchSetContext = PIXI.WebGLSpriteBatch.prototype.setContext;
PIXI.WebGLSpriteBatch.prototype.set... |
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.triangleIndexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.triangleIndices, gl.STATIC_DRAW);
};
var oldWebGLSpriteBatchDestroy = PIXI.WebGLSpriteBatch.prototype.destroy;
PIXI.WebGLSpriteBatch.prototype.destroy = function() {
this.triangleIndices = null;
... | this._batchType = qc.BATCH_QUAD;
this.quadIndexBuffer = this.indexBuffer;
this.triangleIndexBuffer = gl.createBuffer(); | random_line_split |
WebGLSpriteBatch.js | /**
* Created by chenqx on 8/5/15.
* @hack 添加三角形绘制提交方式
*/
/**
* 以四边形填充
* @constant
* @type {number}
*/
qc.BATCH_QUAD = 0;
/**
* 以三角形填充
* @constant
* @type {number}
*/
qc.BATCH_TRIANGLES = 1;
var oldWebGLSpriteBatchSetContext = PIXI.WebGLSpriteBatch.prototype.setContext;
PIXI.WebGLSpriteBatch.prototype.set... | exBuffer,Size
if (v === qc.BATCH_TRIANGLES) {
this.size = this.triangleSize;
this.indexBuffer = this.triangleIndexBuffer;
this._batchType = v;
this.batchIndexNumber = 3;
}
else {
this.size = this.quadSize... | this.stop();
// 切换Ind | conditional_block |
parse_annotations.py | # annotation parser that processes our hashtags
import re
def get_abstracts(filename):
output = []
abstract_buffer = []
notes_buffer = []
last_abstract_no = 0
last_pmid = 0
last_biviewid = 0
with open(filename, 'rb') as f:
for line in f: # fast forward to abstract 1
... |
def main():
a = get_abstracts("data/drug_trials_in_cochrane_BCW.txt")
b = get_abstracts("data/drug_trials_in_cochrane_IJM.txt")
i = 128
print
print a[i]
print
print b[i]
if __name__ == '__main__':
main() | random_line_split | |
parse_annotations.py |
# annotation parser that processes our hashtags
import re
def | (filename):
output = []
abstract_buffer = []
notes_buffer = []
last_abstract_no = 0
last_pmid = 0
last_biviewid = 0
with open(filename, 'rb') as f:
for line in f: # fast forward to abstract 1
m = re.match("Abstract 1 of [1-9][0-9]*", line)
if m:
... | get_abstracts | identifier_name |
parse_annotations.py |
# annotation parser that processes our hashtags
import re
def get_abstracts(filename):
output = []
abstract_buffer = []
notes_buffer = []
last_abstract_no = 0
last_pmid = 0
last_biviewid = 0
with open(filename, 'rb') as f:
for line in f: # fast forward to abstract 1
... |
if __name__ == '__main__':
main() | a = get_abstracts("data/drug_trials_in_cochrane_BCW.txt")
b = get_abstracts("data/drug_trials_in_cochrane_IJM.txt")
i = 128
print
print a[i]
print
print b[i] | identifier_body |
parse_annotations.py |
# annotation parser that processes our hashtags
import re
def get_abstracts(filename):
output = []
abstract_buffer = []
notes_buffer = []
last_abstract_no = 0
last_pmid = 0
last_biviewid = 0
with open(filename, 'rb') as f:
for line in f: # fast forward to abstract 1
... |
else:
output.append({"abstract": "\n".join(abstract_buffer),
"notes": notes_buffer})
return output
def main():
a = get_abstracts("data/drug_trials_in_cochrane_BCW.txt")
b = get_abstracts("data/drug_trials_in_cochrane_IJM.txt")
i = 128
p... | notes_buffer.append(line) | conditional_block |
primeng-timeline.js | /**
* Generated bundle index. Do not edit.
*/
export * from './public_api';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJpbWVuZy10aW1lbGluZS5qcyIsInNvdXJjZVJvb3QiOiIuLi8uLi8uLi9zcmMvYXBwL2NvbXBvbmVudHMvdGltZWxpbmUvIiwic291cmNlcyI6WyJwcmltZW5nLXRpbWVsaW5lLnRzIl0sIm5hbWVzIjpbXSwibWFw... | random_line_split | ||
confirmation.ts | /**
* @author Damien Dell'Amico <damien.dellamico@gmail.com>
* @copyright Copyright (c) 2016
* @license GPL-3.0
*/
import { Component } from '@angular/core';
import { AlertController, NavController } from 'ionic-angular';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { GeocoderSe... | (private nav: NavController,
private fb: FormBuilder,
private rideService: RideService,
private mapService: MapService,
private geocoderService: GeocoderService,
protected alertCtrl: AlertController) {
super(alertCtrl);
this.form = this.fb.g... | constructor | identifier_name |
confirmation.ts | /**
* @author Damien Dell'Amico <damien.dellamico@gmail.com>
* @copyright Copyright (c) 2016
* @license GPL-3.0
*/
import { Component } from '@angular/core';
import { AlertController, NavController } from 'ionic-angular';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { GeocoderSe... |
const prompt = this.alertCtrl.create({
title: 'Confirmation',
message: 'Taxi will pick you up within 5 minutes. Do you want to confirm ?',
buttons: [{
text: 'Cancel'
}, {
text: 'Confirm',
handler: () => {
this.rideService.addRide(model.departure, model.dest... | {
this.displayErrorAlert();
return;
} | conditional_block |
confirmation.ts | /**
* @author Damien Dell'Amico <damien.dellamico@gmail.com>
* @copyright Copyright (c) 2016
* @license GPL-3.0
*/
import { Component } from '@angular/core';
import { AlertController, NavController } from 'ionic-angular';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { GeocoderSe... | this.nav.setRoot(RideListPage);
}
}]
});
prompt.present();
}
} | handler: () => {
this.rideService.addRide(model.departure, model.destination); | random_line_split |
action_bar.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Bin;
use Buildable;
use Container;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct ActionBar(Object<ffi::GtkActionBar>): Widget, Container, Bin, Builda... | }
impl ActionBar {
#[cfg(feature = "3.12")]
pub fn new() -> ActionBar {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_action_bar_new()).downcast_unchecked()
}
}
#[cfg(feature = "3.12")]
pub fn get_center_widget(&self) -> Option<Widg... |
match fn {
get_type => || ffi::gtk_action_bar_get_type(),
} | random_line_split |
action_bar.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Bin;
use Buildable;
use Container;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct ActionBar(Object<ffi::GtkActionBar>): Widget, Container, Bin, Builda... |
#[cfg(feature = "3.12")]
pub fn pack_start<T: IsA<Widget>>(&self, child: &T) {
unsafe {
ffi::gtk_action_bar_pack_start(self.to_glib_none().0, child.to_glib_none().0);
}
}
#[cfg(feature = "3.12")]
pub fn set_center_widget<T: IsA<Widget>>(&self, center_widget: Option<&T>... | {
unsafe {
ffi::gtk_action_bar_pack_end(self.to_glib_none().0, child.to_glib_none().0);
}
} | identifier_body |
action_bar.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Bin;
use Buildable;
use Container;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct ActionBar(Object<ffi::GtkActionBar>): Widget, Container, Bin, Builda... | (&self) -> Option<Widget> {
unsafe {
from_glib_none(ffi::gtk_action_bar_get_center_widget(self.to_glib_none().0))
}
}
#[cfg(feature = "3.12")]
pub fn pack_end<T: IsA<Widget>>(&self, child: &T) {
unsafe {
ffi::gtk_action_bar_pack_end(self.to_glib_none().0, chi... | get_center_widget | identifier_name |
filecontainer.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | {
if direction == Direction::ToServer {
(&mut self.files_ts, self.flags_ts)
} else {
(&mut self.files_tc, self.flags_tc)
}
}
}
pub struct File;
#[repr(C)]
#[derive(Debug)]
pub struct FileContainer {
head: * mut c_void,
tail: * mut c_void,
}
impl Drop for... | pub fn get(&mut self, direction: Direction) -> (&mut FileContainer, u16) | random_line_split |
filecontainer.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | {
head: * mut c_void,
tail: * mut c_void,
}
impl Drop for FileContainer {
fn drop(&mut self) {
self.free();
}
}
impl Default for FileContainer {
fn default() -> Self { Self {
head: ptr::null_mut(),
tail: ptr::null_mut(),
}}
}
impl FileContainer {
pub fn default() ... | FileContainer | identifier_name |
lib.rs | ::push_many_back](trait.SliceRing.html#tymethod.push_many_back)
reads from a buffer that you
allocate and control.
it might allocate more capacity
when you push values and as a result there are more values in the ring than ever before.
if you repeatedly read and drop after each push, as in the [example](#example) above... | else {
self.buf.capacity()
}
}
#[inline]
pub fn capacity(&self) -> usize {
self.cap() - 1
}
#[inline]
pub fn is_continuous(&self) -> bool {
self.first_readable <= self.next_writable
}
/// returns the number of elements in the `SliceRingImpl`
#[... | {
// For zero sized types, we are always at maximum capacity
MAXIMUM_ZST_CAPACITY
} | conditional_block |
lib.rs | ::push_many_back](trait.SliceRing.html#tymethod.push_many_back)
reads from a buffer that you
allocate and control.
it might allocate more capacity
when you push values and as a result there are more values in the ring than ever before.
if you repeatedly read and drop after each push, as in the [example](#example) above... |
/// returns the number of elements in the `SliceRingImpl`
#[inline]
pub fn len(&self) -> usize {
count(self.first_readable, self.next_writable, self.cap())
}
/// returns the index into the underlying buffer
/// for a given logical element
/// index + addend
#[inline]
pub f... | {
self.first_readable <= self.next_writable
} | identifier_body |
lib.rs | Ring::push_many_back](trait.SliceRing.html#tymethod.push_many_back)
reads from a buffer that you
allocate and control.
it might allocate more capacity
when you push values and as a result there are more values in the ring than ever before.
if you repeatedly read and drop after each push, as in the [example](#example) a... | let copy_dst = old_cap;
// everything before next_writable
let copy_len = next_writable;
self.copy_nonoverlapping(copy_src, copy_dst, copy_len);
self.next_writable += old_cap;
debug_assert!(self.next_writable > self.first_readable);
deb... | // TODO test this
if self.next_writable < old_cap - self.first_readable {
let next_writable = self.next_writable;
let copy_src = 0;
// after the previous | random_line_split |
lib.rs | ::push_many_back](trait.SliceRing.html#tymethod.push_many_back)
reads from a buffer that you
allocate and control.
it might allocate more capacity
when you push values and as a result there are more values in the ring than ever before.
if you repeatedly read and drop after each push, as in the [example](#example) above... | (&self) -> usize {
self.cap() - 1
}
#[inline]
pub fn is_continuous(&self) -> bool {
self.first_readable <= self.next_writable
}
/// returns the number of elements in the `SliceRingImpl`
#[inline]
pub fn len(&self) -> usize {
count(self.first_readable, self.next_writ... | capacity | identifier_name |
step3_env.py | #import sys, traceback
import mal_readline
import mal_types as types
from mal_types import (MalSym, MalInt, MalStr,
_symbol, _keywordu,
MalList, _list, MalVector, MalHashMap, MalFunc)
import reader, printer
from env import Env
# read
def READ(str):
return reader.read_s... |
repl_env.set(_symbol(u'+'), MalFunc(plus))
repl_env.set(_symbol(u'-'), MalFunc(minus))
repl_env.set(_symbol(u'*'), MalFunc(multiply))
repl_env.set(_symbol(u'/'), MalFunc(divide))
def entry_point(argv):
while True:
try:
line = mal_readline.readline("user> ")
if line == "": continue
... | a, b = args[0], args[1]
assert isinstance(a, MalInt)
assert isinstance(b, MalInt)
return MalInt(int(a.value/b.value)) | identifier_body |
step3_env.py | #import sys, traceback
import mal_readline
import mal_types as types
from mal_types import (MalSym, MalInt, MalStr,
_symbol, _keywordu,
MalList, _list, MalVector, MalHashMap, MalFunc)
import reader, printer
from env import Env
# read
def READ(str):
return reader.read_s... | def REP(str, env):
return PRINT(EVAL(READ(str), env))
def plus(args):
a, b = args[0], args[1]
assert isinstance(a, MalInt)
assert isinstance(b, MalInt)
return MalInt(a.value+b.value)
def minus(args):
a, b = args[0], args[1]
assert isinstance(a, MalInt)
assert isinstance(b, MalInt)
r... | def PRINT(exp):
return printer._pr_str(exp)
# repl
repl_env = Env() | random_line_split |
step3_env.py | #import sys, traceback
import mal_readline
import mal_types as types
from mal_types import (MalSym, MalInt, MalStr,
_symbol, _keywordu,
MalList, _list, MalVector, MalHashMap, MalFunc)
import reader, printer
from env import Env
# read
def READ(str):
return reader.read_s... | (exp):
return printer._pr_str(exp)
# repl
repl_env = Env()
def REP(str, env):
return PRINT(EVAL(READ(str), env))
def plus(args):
a, b = args[0], args[1]
assert isinstance(a, MalInt)
assert isinstance(b, MalInt)
return MalInt(a.value+b.value)
def minus(args):
a, b = args[0], args[1]
ass... | PRINT | identifier_name |
step3_env.py | #import sys, traceback
import mal_readline
import mal_types as types
from mal_types import (MalSym, MalInt, MalStr,
_symbol, _keywordu,
MalList, _list, MalVector, MalHashMap, MalFunc)
import reader, printer
from env import Env
# read
def READ(str):
return reader.read_s... |
print(REP(line, repl_env))
except EOFError as e:
break
except reader.Blank:
continue
except types.MalException as e:
print(u"Error: %s" % printer._pr_str(e.object, False))
except Exception as e:
print("Error: %s" % e)
... | continue | conditional_block |
answer-counter-update.component.spec.ts | /* tslint:disable max-line-length */
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { ArTeMiSTestModule } from '../../../test.module';
import { AnswerCounterUpdateComponent } from 'ap... | }); | random_line_split | |
carbon-components-tests.ts | import {
Accordion,
Checkbox,
CodeSnippet,
ContentSwitcher,
CopyButton,
DataTable,
DataTableV2,
DatePicker,
Dropdown,
FileUploader,
FloatingMenu,
HeaderNav,
HeaderSubmenu,
InlineLoading,
Loading,
Modal,
NavigationMenu,
Notification,
NumberInput... | settings.prefix; // $ExpectType string
settings.selectorFocusable; // $ExpectType string
settings.selectorTabbable; // $ExpectType string
const tooltip = new Tooltip(document.getElementById('tooltip')!, { classShown: 'tooltip' });
tooltip.changeState('', {}, () => {});
const tableEl = document.getElementById('table'... | random_line_split | |
5ac1c354a051_n1kv_segment_alloc.py | # Copyright 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
from neutron.db import migration
def upgrade():
if not migration.schema_has_table('cisco_n1kv_vlan_allocations'):
# Assume that, in the database we are migrating from, the
# configured plugin did not create any n1kv tables.
return
op.add_column(
'cisco_n1kv_vlan_allocations'... | random_line_split | |
5ac1c354a051_n1kv_segment_alloc.py | # Copyright 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | ():
if not migration.schema_has_table('cisco_n1kv_vlan_allocations'):
# Assume that, in the database we are migrating from, the
# configured plugin did not create any n1kv tables.
return
op.add_column(
'cisco_n1kv_vlan_allocations',
sa.Column('network_profile_id',
... | upgrade | identifier_name |
5ac1c354a051_n1kv_segment_alloc.py | # Copyright 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
op.add_column(
'cisco_n1kv_vlan_allocations',
sa.Column('network_profile_id',
sa.String(length=36),
nullable=False)
)
op.create_foreign_key(
'cisco_n1kv_vlan_allocations_ibfk_1',
source='cisco_n1kv_vlan_allocations',
referent='cis... | return | conditional_block |
5ac1c354a051_n1kv_segment_alloc.py | # Copyright 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | sa.Column('network_profile_id',
sa.String(length=36),
nullable=False)
)
op.create_foreign_key(
'cisco_n1kv_vxlan_allocations_ibfk_1',
source='cisco_n1kv_vxlan_allocations',
referent='cisco_network_profiles',
local_cols=['network_profile... | if not migration.schema_has_table('cisco_n1kv_vlan_allocations'):
# Assume that, in the database we are migrating from, the
# configured plugin did not create any n1kv tables.
return
op.add_column(
'cisco_n1kv_vlan_allocations',
sa.Column('network_profile_id',
... | identifier_body |
offsetter.py | '''
offsets = [[[originalx,originaly], [511,709],[498,707]],\
[[522,711], [508,709],[493,706]],\
[[522,714], [503,708],[488,705]]]
'''
def offsetter(length,dim,dx,dy,sx,sy,fx,fy):
|
#print offsetter(3,3,-4,-1,532,713)
| x = x0 = sx
y = y0 = sy
arr = []
for i in range(dim):
arr.append([])
for j in range(length):
x = int(x0+dx*i+dx*(j+1))
y = int(y0+dy*i+dy*(j+1))
arr[i].append([x,y])
for i in range(dim):
for j in range(len(arr)):
arr[i][j][0] += ... | identifier_body |
offsetter.py | '''
offsets = [[[originalx,originaly], [511,709],[498,707]],\
[[522,711], [508,709],[493,706]],\
[[522,714], [503,708],[488,705]]]
'''
def | (length,dim,dx,dy,sx,sy,fx,fy):
x = x0 = sx
y = y0 = sy
arr = []
for i in range(dim):
arr.append([])
for j in range(length):
x = int(x0+dx*i+dx*(j+1))
y = int(y0+dy*i+dy*(j+1))
arr[i].append([x,y])
for i in range(dim):
for j in range(len... | offsetter | identifier_name |
offsetter.py | '''
offsets = [[[originalx,originaly], [511,709],[498,707]],\
[[522,711], [508,709],[493,706]],\
[[522,714], [503,708],[488,705]]]
'''
def offsetter(length,dim,dx,dy,sx,sy,fx,fy):
x = x0 = sx
y = y0 = sy
| for i in range(dim):
arr.append([])
for j in range(length):
x = int(x0+dx*i+dx*(j+1))
y = int(y0+dy*i+dy*(j+1))
arr[i].append([x,y])
for i in range(dim):
for j in range(len(arr)):
arr[i][j][0] += int(fx*i)
arr[i][j][1] += int(... | arr = [] | random_line_split |
offsetter.py | '''
offsets = [[[originalx,originaly], [511,709],[498,707]],\
[[522,711], [508,709],[493,706]],\
[[522,714], [503,708],[488,705]]]
'''
def offsetter(length,dim,dx,dy,sx,sy,fx,fy):
x = x0 = sx
y = y0 = sy
arr = []
for i in range(dim):
... |
return arr
#print offsetter(3,3,-4,-1,532,713)
| arr[i][j][0] += int(fx*i)
arr[i][j][1] += int(fy*i) | conditional_block |
models.py | from django.db import models
import warnings
from django.utils import timezone
import requests
from image_cropping import ImageRatioField
class CompMember(models.Model):
"""A member of compsoc"""
class Meta:
verbose_name = 'CompSoc Member'
verbose_name_plural = 'CompSoc Members'
index = ... |
else:
return self.social_link
def __str__(self):
return self.name
class Variable(models.Model): ##NOTE: This should not be used anymore
def __str__(self):
warnings.warn('''You are using a "General Variable".
Stop doing that.
This is bad design on Arjoonn's... | return 'javascript:void(0)' | conditional_block |
models.py | from django.db import models
import warnings
from django.utils import timezone
import requests
from image_cropping import ImageRatioField
class CompMember(models.Model):
"""A member of compsoc"""
class Meta:
verbose_name = 'CompSoc Member'
verbose_name_plural = 'CompSoc Members' | name = models.CharField(max_length=50, help_text='Enter your full name')
image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.')
cropping = ImageRatioField('image', '500x500')
alumni = models.BooleanField(default=Fa... |
index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1) | random_line_split |
models.py | from django.db import models
import warnings
from django.utils import timezone
import requests
from image_cropping import ImageRatioField
class CompMember(models.Model):
"""A member of compsoc"""
class Meta:
verbose_name = 'CompSoc Member'
verbose_name_plural = 'CompSoc Members'
index = ... | instance.image.delete(False) | identifier_body | |
models.py | from django.db import models
import warnings
from django.utils import timezone
import requests
from image_cropping import ImageRatioField
class CompMember(models.Model):
"""A member of compsoc"""
class | :
verbose_name = 'CompSoc Member'
verbose_name_plural = 'CompSoc Members'
index = models.IntegerField(blank=False, help_text="This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1", default=-1)
name = models.CharField(max... | Meta | identifier_name |
ConvertersTest.ts | import { Converters } from "../src/core/Converters";
describe("Converters", () => {
it("Text should take care of null and undefined converting to string", () => {
const text = Converters.text;
expect(text.toValue(undefined)).toMatch("");
expect(text.toValue(null)).toMatch("");
expect(text.toValue("")... | );
expect(Converters.date.fromValue({ value: "2020-01-02" })).toMatch(
"2020-01-02"
);
expect(Converters.time.fromValue({ value: "10:10" })).toMatch("10:10");
[Converters.url, Converters.date, Converters.time].forEach((type) => {
expect(type.fromValue({ value: "" })).toBeUndefined();
... | expect(Converters.url.fromValue({ value: "https://foo.com" })).toMatch(
"https://foo.com" | random_line_split |
shader-library.ts | // uniforms should have three sections:
// - light uniforms
// - unstructured uniforms
// attribute locations
// - attribute locations
interface ShaderUniformsV2 { [ name: string ]: WebGLUniformLocation }
interface ShaderVertexAttributes { [ name: string ]: GLint }
interface LightUniform { [ name: string ]: WebG... | () {
return this.outgoingRequests.length == 0;
}
constructor( gl: WebGLRenderingContext & WebGL2RenderingContext ) {
this.gl = gl;
this.allShadersLoaded = [];
this.shaderLoaded = null;
this.outgoingRequests = [];
this.sources = {};
this.programs = {};
}
loadShader( fil... | doneLoading | identifier_name |
shader-library.ts | // uniforms should have three sections:
// - light uniforms
// - unstructured uniforms
// attribute locations
// - attribute locations
interface ShaderUniformsV2 { [ name: string ]: WebGLUniformLocation }
interface ShaderVertexAttributes { [ name: string ]: GLint }
interface LightUniform { [ name: string ]: WebG... |
loadShader( filename: string ) {
var req = new XMLHttpRequest();
req.addEventListener( "load", evt => {
if ( this.shaderLoaded != null ) {
this.shaderLoaded( this, filename, req.responseText );
}
this.sources[ filename ] = req.responseText;
// remove me from the ... | {
this.gl = gl;
this.allShadersLoaded = [];
this.shaderLoaded = null;
this.outgoingRequests = [];
this.sources = {};
this.programs = {};
} | identifier_body |
shader-library.ts | // uniforms should have three sections:
// - light uniforms
// - unstructured uniforms
// attribute locations
// - attribute locations
interface ShaderUniformsV2 { [ name: string ]: WebGLUniformLocation }
interface ShaderVertexAttributes { [ name: string ]: GLint }
interface LightUniform { [ name: string ]: WebG... |
}
} );
req.open( "GET", "./shaders/" + filename, true );
this.outgoingRequests.push( req );
req.send();
}
compileProgram( gl: WebGLRenderingContext & WebGL2RenderingContext, vsFilename: string, fsFilename: string, programName: string, suppressErrors: boolean = false ): Compiled... | {
this.allShadersLoaded[i]( this.gl, this );
} | conditional_block |
shader-library.ts | // uniforms should have three sections:
// - light uniforms
// - unstructured uniforms
// attribute locations
// - attribute locations
interface ShaderUniformsV2 { [ name: string ]: WebGLUniformLocation }
interface ShaderVertexAttributes { [ name: string ]: GLint }
interface LightUniform { [ name: string ]: WebG... | // force aVertexPosition to be bound to 0 to avoid perf penalty
// gl.bindAttribLocation( program, 0, "aVertexPosition" );
gl.linkProgram( program );
if ( !gl.getProgramParameter( program, gl.LINK_STATUS ) ) {
console.log( "Unable to initialize the shader program: " + gl.getProgram... | random_line_split | |
app.py | #!/usr/bin/env python
import json
import falcon
from email.utils import formatdate
# resource endpoints
class JSONResource(object):
def on_get(self, request, response):
response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True))
json_data = {'message': "Hello, world!"}
... | from wsgiref import simple_server
httpd = simple_server.make_server('localhost', 8080, app)
httpd.serve_forever() | conditional_block | |
app.py | #!/usr/bin/env python
import json
import falcon
from email.utils import formatdate
# resource endpoints
class | (object):
def on_get(self, request, response):
response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True))
json_data = {'message': "Hello, world!"}
response.body = json.dumps(json_data)
class PlaintextResource(object):
def on_get(self, request, response):
... | JSONResource | identifier_name |
app.py | #!/usr/bin/env python
import json
import falcon
from email.utils import formatdate
# resource endpoints
class JSONResource(object):
def on_get(self, request, response):
response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True))
json_data = {'message': "Hello, world!"}
... | # entry point for debugging
if __name__ == "__main__":
from wsgiref import simple_server
httpd = simple_server.make_server('localhost', 8080, app)
httpd.serve_forever() | app = falcon.API()
app.add_route("/json", JSONResource())
app.add_route("/plaintext", PlaintextResource())
| random_line_split |
app.py | #!/usr/bin/env python
import json
import falcon
from email.utils import formatdate
# resource endpoints
class JSONResource(object):
def on_get(self, request, response):
response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True))
json_data = {'message': "Hello, world!"}
... |
# setup
app = falcon.API()
app.add_route("/json", JSONResource())
app.add_route("/plaintext", PlaintextResource())
# entry point for debugging
if __name__ == "__main__":
from wsgiref import simple_server
httpd = simple_server.make_server('localhost', 8080, app)
httpd.serve_forever()
| def on_get(self, request, response):
response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True))
response.set_header('Content-Type', 'text/plain')
response.body = b'Hello, world!' | identifier_body |
demo42.py | #!/usr/bin/python
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, 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:
# 1. Redistributions of source code must retain the above copyright n... | flow_entry2 = FlowEntry()
# Generic attributes of the Flow Entry
flow_entry2.set_flow_table_id(table_id)
flow_entry2.set_flow_name(flow_name)
flow_entry2.set_flow_id(flow_id)
flow_entry2.set_flow_cookie(cookie)
flow_entry2.set_flow_priority(priority)
flow_entry2.set_flow_hard_timeout(0)... |
time.sleep(rundelay)
# Allocate a placeholder for the Flow Entry | random_line_split |
demo42.py | #!/usr/bin/python
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, 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:
# 1. Redistributions of source code must retain the above copyright n... | (ofswitch, table_id, flow_ids):
for flow_id in flow_ids:
result = ofswitch.delete_flow(table_id, flow_id)
status = result.get_status()
if(status.eq(STATUS.OK)):
print ("<<< Flow with id of '%s' successfully removed "
"from the Controller" % flow_id)
els... | delete_flows | identifier_name |
demo42.py | #!/usr/bin/python
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, 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:
# 1. Redistributions of source code must retain the above copyright n... |
def of_demo_42():
f = "cfg.yml"
d = {}
if(load_dict_from_file(f, d) is False):
print("Config file '%s' read error: " % f)
exit(0)
try:
ctrlIpAddr = d['ctrlIpAddr']
ctrlPortNum = d['ctrlPortNum']
ctrlUname = d['ctrlUname']
ctrlPswd = d['ctrlPswd']
... | result = ofswitch.delete_flow(table_id, flow_id)
status = result.get_status()
if(status.eq(STATUS.OK)):
print ("<<< Flow with id of '%s' successfully removed "
"from the Controller" % flow_id)
else:
print ("!!!Flow '%s' removal error, reason: %s" %
... | conditional_block |
demo42.py | #!/usr/bin/python
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, 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:
# 1. Redistributions of source code must retain the above copyright n... |
ctrl = Controller(ctrlIpAddr, ctrlPortNum, ctrlUname, ctrlPswd)
ofswitch = OFSwitch(ctrl, nodeName)
print ("<<< 'Controller': %s, 'OpenFlow' switch: '%s'" %
(ctrlIpAddr, nodeName))
first_flow_id = 110
# ---------------------------------------------------
# First flow entry
# --... | f = "cfg.yml"
d = {}
if(load_dict_from_file(f, d) is False):
print("Config file '%s' read error: " % f)
exit(0)
try:
ctrlIpAddr = d['ctrlIpAddr']
ctrlPortNum = d['ctrlPortNum']
ctrlUname = d['ctrlUname']
ctrlPswd = d['ctrlPswd']
nodeName = d['nodeName... | identifier_body |
player_service.py | import time
import cgi
import json
import os
import BaseHTTPServer
HOST_NAME = 'localhost'
PORT_NUMBER = 9400
class PlayerService(BaseHTTPServer.BaseHTTPRequestHandler):
def | (self):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
postvars = cgi.parse_multipart(self.rfile, pdict)
... | do_POST | identifier_name |
player_service.py | import time
import cgi
import json
import os
import BaseHTTPServer
HOST_NAME = 'localhost'
PORT_NUMBER = 9400
class PlayerService(BaseHTTPServer.BaseHTTPRequestHandler):
| game_state = postvars['game_state'][0]
w.write(game_state)
w.close()
response = r.read()
self.wfile.write(response)
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), PlayerService)
print tim... | def do_POST(self):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
postvars = cgi.parse_multipart(self.rfile, p... | identifier_body |
player_service.py | import time
import cgi
import json
import os
import BaseHTTPServer
HOST_NAME = 'localhost'
PORT_NUMBER = 9400
class PlayerService(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
... |
action = postvars['action'][0]
w, r = os.popen2("./obj/player " + action)
if 'game_state' in postvars:
game_state = postvars['game_state'][0]
w.write(game_state)
w.close()
response = r.read()
self.wfile.write(response)
if __name__ == '__mai... | postvars = {} | conditional_block |
player_service.py | import time
import cgi
import json
import os
import BaseHTTPServer
HOST_NAME = 'localhost'
PORT_NUMBER = 9400
class PlayerService(BaseHTTPServer.BaseHTTPRequestHandler): |
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
postvars = cgi.parse_multipart(self.rfile, pdict)
elif ... |
def do_POST(self): | random_line_split |
user.js | angular.module('booksAR')
.directive('userNavbar', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-navbar.html'
};
})
.directive('userBooksTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-books... | })
.directive('ngConfirmClick', [
function(){
return {
link: function (scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.confirmedClick;
element.bind('click',function (event) {
... | restrict: 'E',
templateUrl: './app/components/directives/user/user-profile-info.html'
};
| random_line_split |
user.js | angular.module('booksAR')
.directive('userNavbar', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-navbar.html'
};
})
.directive('userBooksTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-books... |
});
}
};
}]); | {
scope.$eval(clickAction)
} | conditional_block |
backend.export.service.ts | import { Injectable, Inject } from '@angular/core';
import {Headers, Http, RequestMethod, RequestOptions, Response, ResponseContentType} from '@angular/http';
import { ValueMinerAPIUrl, ValueMinerExportAPIUrl, ValueMinerMessagingAPIUrl } from '../tokens';
import { TokenService } from './token.service';
import { Backend... | extends BackendService {
constructor(@Inject(ValueMinerAPIUrl) apiUrl: string,
@Inject(ValueMinerMessagingAPIUrl) messagingApiUrl: string,
@Inject(ValueMinerExportAPIUrl) exportApiUrl: string,
http: Http,
token: TokenService) {
super(apiUrl, messagingApiUr... | BackendExportService | identifier_name |
backend.export.service.ts | import { Injectable, Inject } from '@angular/core';
import {Headers, Http, RequestMethod, RequestOptions, Response, ResponseContentType} from '@angular/http';
import { ValueMinerAPIUrl, ValueMinerExportAPIUrl, ValueMinerMessagingAPIUrl } from '../tokens';
import { TokenService } from './token.service';
import { Backend... | return this.blobRequest(RequestMethod.Post, url, 'application/pdf', body);
case 'excel':
return this.blobRequest(RequestMethod.Post, url, 'application/vnd.openxmlformats-officedocument. spreadsheetml.sheet', body);
case 'png':
return this.blobRequest(RequestMethod.Post, url, 'image/p... | const url = BackendService.pathJoin([this.apiUrl, path]);
switch (body.data.type) {
case 'pdf': | random_line_split |
backend.export.service.ts | import { Injectable, Inject } from '@angular/core';
import {Headers, Http, RequestMethod, RequestOptions, Response, ResponseContentType} from '@angular/http';
import { ValueMinerAPIUrl, ValueMinerExportAPIUrl, ValueMinerMessagingAPIUrl } from '../tokens';
import { TokenService } from './token.service';
import { Backend... |
}
| {
return token.flatMap((accessToken: string) => {
const headers = new Headers({
'Content-Type': 'application/json',
'Accept': 'application/vnd.api.v2+json',
'Authorization': `Bearer ${accessToken}`
});
const requestOptions = new RequestOptions({
method: method,
... | identifier_body |
setup.tsx | import React from 'react';
import { JSDOM } from 'jsdom';
import { render } from '@testing-library/react';
declare global {
interface Window {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
result?: any;
}
}
export function | (html?: string) {
const HTML = html || '<!doctype html><html><head></head><body></body></html>';
const dom = new JSDOM(HTML, {
resources: 'usable',
runScripts: 'dangerously',
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
global.window = dom.window as any;
global.document = dom.... | setup | identifier_name |
setup.tsx | import React from 'react';
import { JSDOM } from 'jsdom';
import { render } from '@testing-library/react';
declare global {
interface Window {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
result?: any;
}
}
export function setup(html?: string) |
export function renderComponent(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback?: (res: (value: any) => void, rej: (reason?: any) => void) => void
) {
return new Promise((res, rej) => {
const Component = () => {
callback ? callback(res, rej) : res(null);
return null;
... | {
const HTML = html || '<!doctype html><html><head></head><body></body></html>';
const dom = new JSDOM(HTML, {
resources: 'usable',
runScripts: 'dangerously',
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
global.window = dom.window as any;
global.document = dom.window.document;... | identifier_body |
setup.tsx | interface Window {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
result?: any;
}
}
export function setup(html?: string) {
const HTML = html || '<!doctype html><html><head></head><body></body></html>';
const dom = new JSDOM(HTML, {
resources: 'usable',
runScripts: 'dangerously',... | import React from 'react';
import { JSDOM } from 'jsdom';
import { render } from '@testing-library/react';
declare global { | random_line_split | |
task-comm-16.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // run-pass
#![allow(unused_mut)]
#![allow(unused_parens)]
#![allow(non_camel_case_types)]
use std::sync::mpsc::channel;
use std::cmp;
// Tests of ports and channels on various types
fn test_rec() {
struct R {val0: isize, val1: u8, val2: char}
let (tx, rx) = channel();
let r0: R = R {val0: 0, val1: 1, va... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
task-comm-16.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let (tx, rx) = channel();
let s0 = "test".to_string();
tx.send(s0).unwrap();
let s1 = rx.recv().unwrap();
assert_eq!(s1.as_bytes()[0], 't' as u8);
assert_eq!(s1.as_bytes()[1], 'e' as u8);
assert_eq!(s1.as_bytes()[2], 's' as u8);
assert_eq!(s1.as_bytes()[3], 't' as u8);
}
#[derive(D... | test_str | identifier_name |
task-comm-16.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn test_str() {
let (tx, rx) = channel();
let s0 = "test".to_string();
tx.send(s0).unwrap();
let s1 = rx.recv().unwrap();
assert_eq!(s1.as_bytes()[0], 't' as u8);
assert_eq!(s1.as_bytes()[1], 'e' as u8);
assert_eq!(s1.as_bytes()[2], 's' as u8);
assert_eq!(s1.as_bytes()[3], 't' as u8);
... | {
let (tx, rx) = channel();
let v0: Vec<isize> = vec![0, 1, 2];
tx.send(v0).unwrap();
let v1 = rx.recv().unwrap();
assert_eq!(v1[0], 0);
assert_eq!(v1[1], 1);
assert_eq!(v1[2], 2);
} | identifier_body |
bluebird.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license | // used by other libraries such as sequelize, so I think it is
// safe to just expose a method to patch Bluebird explicitly
const BLUEBIRD = 'bluebird';
(Zone as any)[Zone.__symbol__(BLUEBIRD)] = function patchBluebird(Bluebird: any) {
Bluebird.setScheduler((fn: Function) => {
Zone.current.scheduleMic... | */
Zone.__load_patch('bluebird', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
// TODO: @JiaLiPassion, we can automatically patch bluebird
// if global.Promise = Bluebird, but sometimes in nodejs,
// global.Promise is not Bluebird, and Bluebird is just be | 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... | """This is a set of autoconf macros used by the configure.ac scripts in
other Xorg modular packages, and is needed to generate new versions
of their configure scripts with autoconf."""
homepage = "http://cgit.freedesktop.org/xorg/util/macros/"
url = "https://www.x.org/archive/individual/util/util-macro... | 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... | class UtilMacros(AutotoolsPackage):
"""This is a set of autoconf macros used by the configure.ac scripts in
other Xorg modular packages, and is needed to generate new versions
of their configure scripts with autoconf."""
homepage = "http://cgit.freedesktop.org/xorg/util/macros/"
url = "https://www.... | ##############################################################################
from spack import *
| 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... | (AutotoolsPackage):
"""This is a set of autoconf macros used by the configure.ac scripts in
other Xorg modular packages, and is needed to generate new versions
of their configure scripts with autoconf."""
homepage = "http://cgit.freedesktop.org/xorg/util/macros/"
url = "https://www.x.org/archive/in... | UtilMacros | identifier_name |
validation-mapping.ts | import { Observable, Subject, Subscriber } from 'rxjs';
import {
ValidationResultCompose,
MakeValidationResult
} from '../validation';
import { AbstractSource } from '../sources';
import {
Behavior,
FormElementBehavior,
FormElement
} from '../common';
/**
* Подключение Lodash (не Underscore!)
* @... | false
);
/**
* Действие в нескольких местах вызывается
* из под ActionContainer. Поэтому, оборачивание
* в контейнер может замкнуть работу ActionContainer.
*/
return Observable.create((subscriber: Subscriber<ValidationResult>) => {
Observabl... | iveElement,
'ng-async-complete',
| conditional_block |
validation-mapping.ts | import { Observable, Subject, Subscriber } from 'rxjs';
import {
ValidationResultCompose,
MakeValidationResult
} from '../validation';
import { AbstractSource } from '../sources';
import {
Behavior,
FormElementBehavior,
FormElement
} from '../common';
/**
* Подключение Lodash (не Underscore!)
* @... | }`,
asyncRevision = this.element.actionContainer.getRevision(asyncAction);
/**
* !!! ВАЖНО:
* Не нужно нарушать порядок проверок
* актуальности валидации. Например, если
* _checkValuesChanged будет запускаться
* перед isActive, то будет глюк, при котором... | path | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.