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
jquery.contextmenu.js
/** * jQuery plugin for Pretty looking right click context menu. * * Requires popup.js and popup.css to be included in your page. And jQuery, obviously. * * Usage: * * $('.something').contextPopup({ * title: 'Some title', * items: [ * {label:'My Item', icon:'/some/icon1.png', action:function()...
(e) { var menu = $('<ul class="' + settings.contextMenuClass + '"><div class="' + settings.gutterLineClass + '"></div></ul>') .appendTo(document.body); if (settings.title) { $('<li class="' + settings.headerClass + '"></li>').text(settings.title).appendTo(menu); } settings.items.forEach(func...
createMenu
identifier_name
jquery.contextmenu.js
/** * jQuery plugin for Pretty looking right click context menu. * * Requires popup.js and popup.css to be included in your page. And jQuery, obviously. * * Usage: * * $('.something').contextPopup({ * title: 'Some title', * items: [ * {label:'My Item', icon:'/some/icon1.png', action:function()...
else { $('<li class="' + settings.seperatorClass + '"></li>').appendTo(menu); } }); menu.find('.' + settings.headerClass ).text(settings.title); return menu; } // On contextmenu event (right click) this.bind('contextmenu', function(e) { var menu = createMenu(e) .show(); ...
{ var rowCode = '<li><a href="#"><span></span></a></li>'; // if(item.icon) // rowCode += '<img>'; // rowCode += '<span></span></a></li>'; var row = $(rowCode).appendTo(menu); if(item.icon){ var icon = $('<img>'); icon.attr('src', item.icon); ...
conditional_block
UserService.ts
angular .module('services') .service('UserService', UserService); UserService.$inject = ['$resource', '$q']; function UserService($resource, $q) { var resource = $resource('', {}, { get_current_user: { method: 'GET', url: '/console/user/current' }, logout: ...
function logout() { var d = $q.defer(); resource.logout({}, function (result) { d.resolve(result); }, function (result) { d.reject(result); }); return d.promise; } return { ...
{ var d = $q.defer(); resource.get_current_user({}, function (result) { d.resolve(result); }, function (result) { d.reject(result); }); return d.promise; }
identifier_body
UserService.ts
angular .module('services') .service('UserService', UserService); UserService.$inject = ['$resource', '$q']; function UserService($resource, $q) { var resource = $resource('', {}, { get_current_user: { method: 'GET', url: '/console/user/current' }, logout: ...
} return { getCurrentUser: getCurrentUser, logout: logout } }
}, function (result) { d.reject(result); }); return d.promise;
random_line_split
UserService.ts
angular .module('services') .service('UserService', UserService); UserService.$inject = ['$resource', '$q']; function UserService($resource, $q) { var resource = $resource('', {}, { get_current_user: { method: 'GET', url: '/console/user/current' }, logout: ...
() { var d = $q.defer(); resource.logout({}, function (result) { d.resolve(result); }, function (result) { d.reject(result); }); return d.promise; } return { getCurrentUser: g...
logout
identifier_name
color.rs
location = input.current_source_location(); match input.next()?.clone() { Token::Number { value, .. } => Ok(NumberOrPercentage::Number { value }), Token::Percentage { unit_value, .. } => { Ok(NumberOrPercentage::Percentage { unit_value }) }, Toke...
random_line_split
color.rs
(value) } } struct ColorComponentParser<'a, 'b: 'a>(&'a ParserContext<'b>); impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponentParser<'a, 'b> { type Error = StyleParseErrorKind<'i>; fn parse_angle_or_number<'t>( &self, input: &mut Parser<'i, 't>, ) -> Resu...
} /// A wrapper of cssparser::Color::parse_hash. /// /// That function should never return CurrentColor, so it makes no sense to /// handle a cssparser::Color here. This should really be done in cssparser /// directly rather than here. fn parse_hash_color(value: &[u8]) -> Result<RGBA, ()> { CSSParserColor::parse_...
{ match *self { Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::Numeric { authored: Some(ref authored), .. } => dest.write_str(authored), Color::Numeric { parsed: ref rgba, .. } =...
identifier_body
color.rs
(value) } } struct ColorComponentParser<'a, 'b: 'a>(&'a ParserContext<'b>); impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponentParser<'a, 'b> { type Error = StyleParseErrorKind<'i>; fn parse_angle_or_number<'t>( &self, input: &mut Parser<'i, 't>, ) -> Resu...
<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, allow_quirks: AllowQuirks, ) -> Result<Self, ParseError<'i>> { input.try(|i| Self::parse(context, i)).or_else(|e| { if !allow_quirks.allowed(context.quirks_mode) { return Err(e); } ...
parse_quirky
identifier_name
color.rs
(value) } } struct ColorComponentParser<'a, 'b: 'a>(&'a ParserContext<'b>); impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponentParser<'a, 'b> { type Error = StyleParseErrorKind<'i>; fn parse_angle_or_number<'t>( &self, input: &mut Parser<'i, 't>, ) -> Resu...
else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(location.new_custom_error(StyleParseErrorKind::Un...
{ 1 }
conditional_block
work.service.ts
import {Injectable} from 'angular2/core'; import {Http, Response, Headers, RequestOptions} from 'angular2/http'; import {} from 'angular2/http'; import {Work} from '../models/work'; import {Observable} from 'rxjs/Observable'; @Injectable() export class WorkService { /* BEFORE getWorks() { re...
return this.http.post(this._worksUrl, body, options) .map(res => <Work> res.json().data) .catch(this.handleError) } }
let body = JSON.stringify({ title, description, types, groups, pictures, minpic }); // TODO add pictures let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers });
random_line_split
work.service.ts
import {Injectable} from 'angular2/core'; import {Http, Response, Headers, RequestOptions} from 'angular2/http'; import {} from 'angular2/http'; import {Work} from '../models/work'; import {Observable} from 'rxjs/Observable'; @Injectable() export class
{ /* BEFORE getWorks() { return Promise.resolve(WORKS); }*/ constructor (private http: Http) {} private _worksUrl = '/api/works'; // URL to web api /** * Get all works frorm the server */ getWorks () { return this.http.get(this._worksUrl) .map(res => <Work[]> res.json()) .do(data => con...
WorkService
identifier_name
work.service.ts
import {Injectable} from 'angular2/core'; import {Http, Response, Headers, RequestOptions} from 'angular2/http'; import {} from 'angular2/http'; import {Work} from '../models/work'; import {Observable} from 'rxjs/Observable'; @Injectable() export class WorkService { /* BEFORE getWorks() { re...
}
{ let body = JSON.stringify({ title, description, types, groups, pictures, minpic }); // TODO add pictures let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this._worksUrl, body, options) ...
identifier_body
sort.rs
#![deny(warnings)] extern crate coreutils; extern crate extra; use std::env; use std::io::{stdout, stderr, stdin, Error, Write, BufRead, BufReader}; use std::process::exit; use std::cmp::Ordering; use coreutils::ArgParser; use std::fs::File; use extra::option::OptionalExt; const MAN_PAGE: &'static str = r#" NAME ...
fn lines_from_files(paths: &Vec<&String>) -> Result<Vec<String>, Error> { let mut lines = Vec::new(); for path in paths { let f = try!(File::open(path)); let f = BufReader::new(f); for line in f.lines() { match line { Ok(l) => lines.push(l), ...
{ let stdin = stdin(); let mut lines = Vec::new(); let f = BufReader::new(stdin.lock()); for line in f.lines() { match line { Ok(l) => lines.push(l), Err(e) => return Err(e), } } Ok(lines) }
identifier_body
sort.rs
#![deny(warnings)] extern crate coreutils; extern crate extra; use std::env; use std::io::{stdout, stderr, stdin, Error, Write, BufRead, BufReader}; use std::process::exit; use std::cmp::Ordering; use coreutils::ArgParser; use std::fs::File; use extra::option::OptionalExt; const MAN_PAGE: &'static str = r#" NAME ...
() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(2) .add_flag(&["n", "numeric-sort"]) .add_flag(&["u", "unique"]) .add_flag(&["h", "help"]); parser.parse(env::args()); if parser.found("help") { ...
main
identifier_name
sort.rs
#![deny(warnings)] extern crate coreutils; extern crate extra; use std::env; use std::io::{stdout, stderr, stdin, Error, Write, BufRead, BufReader}; use std::process::exit; use std::cmp::Ordering; use coreutils::ArgParser; use std::fs::File; use extra::option::OptionalExt; const MAN_PAGE: &'static str = r#" NAME ...
} if parser.found("unique") { l.dedup(); } for x in l { println!("{}", x); } } Err(e) => { let _ = write!(stderr, "{}", e); } } }
l.sort_by(numeric_compare); } else { l.sort();
random_line_split
sort.rs
#![deny(warnings)] extern crate coreutils; extern crate extra; use std::env; use std::io::{stdout, stderr, stdin, Error, Write, BufRead, BufReader}; use std::process::exit; use std::cmp::Ordering; use coreutils::ArgParser; use std::fs::File; use extra::option::OptionalExt; const MAN_PAGE: &'static str = r#" NAME ...
let lines = match parser.args.is_empty() { true => lines_from_stdin(), false => { let mut paths = Vec::new(); for dir in parser.args.iter() { paths.push(dir); } lines_from_files(&paths) } }; match lines { Ok(m...
{ stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); }
conditional_block
fake_service.py
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICEN...
def get_backup_driver(context): return FakeBackupService(context)
raise IOError('fake')
conditional_block
fake_service.py
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICEN...
(self, backup): # if backup has magic name of 'fail_on_delete' # we raise an error - useful for some tests - # otherwise we return without error if backup['display_name'] == 'fail_on_delete': raise IOError('fake') def get_backup_driver(context): return FakeBackupService...
delete
identifier_name
fake_service.py
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICEN...
LOG = logging.getLogger(__name__) class FakeBackupService(BackupDriver): def __init__(self, context, db_driver=None): super(FakeBackupService, self).__init__(context, db_driver) def backup(self, backup, volume_file): pass def restore(self, backup, volume_id, volume_file): pass ...
random_line_split
fake_service.py
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICEN...
return FakeBackupService(context)
identifier_body
index.js
/** * @authors JayChenFE * @date 2017-03-21 11:17:13 * @version $1.0$ */ /** * 主要核心逻辑入口 **/ const fs = require('fs'); const path = require('path'); const staticServer = require('./static-server'); class App { constructor() { } initServer() {
辑 //返回一个函数 return (request, response) => { let { url } = request; let body = staticServer(url); response.writeHead(200, 'resolve ok', { 'X-Powered-By': 'Node.js' }); response.end(body); // const staticPrefix = path.resolve(process.cwd(), 'public'); // let staticFun = url => { ...
//方便增加别的逻
identifier_name
index.js
/** * @authors JayChenFE * @date 2017-03-21 11:17:13 * @version $1.0$ */ /** * 主要核心逻辑入口 **/ const fs = require('fs'); const path = require('path'); const staticServer = require('./static-server'); class App { constructor() { } initServer() { //方便增加别的逻辑 //返回一个函数 return (request, response) => {...
// fs.readFile('./public/js/index.js', 'utf-8', (error, data) => { // response.end(data); // }); // } // if (url == '/') { // //第一个路径相对的是process.cwd(); // fs.readFile('./public/index.html', 'utf-8', (error, data) => { // response.end(data); // }); // } }; } } module.exports...
// if (url == '/js/index.js') {
random_line_split
index.js
/** * @authors JayChenFE * @date 2017-03-21 11:17:13 * @version $1.0$ */ /** * 主要核心逻辑入口 **/ const fs = require('fs'); const path = require('path'); const staticServer = require('./static-server'); class App { constructor() { } initServ
{ //方便增加别的逻辑 //返回一个函数 return (request, response) => { let { url } = request; let body = staticServer(url); response.writeHead(200, 'resolve ok', { 'X-Powered-By': 'Node.js' }); response.end(body); // const staticPrefix = path.resolve(process.cwd(), 'public'); // let staticFu...
er()
identifier_body
lib.rs
extern crate num; pub use base64::{u8_to_base64, base64_to_u8, big_to_base64, chunk_to_bytes}; pub use buffer::{Buff}; pub use english::{english_dict, lowercase, levenshtein, score_fn, count}; pub use xor_cipher::{single_xor, hamming}; use std::io::{File, BufferedReader, IoError}; pub mod base64; pub mod buffer; pub...
{ let path = Path::new(input); let file = match File::open(&path) { Ok(t) => t, Err(e) => fail!("Couldn't open {}, got error {}", input, e) }; let mut reader = BufferedReader::new(file); reader.lines().map(unwrap_and_noline).collect() }
identifier_body
lib.rs
extern crate num; pub use base64::{u8_to_base64, base64_to_u8, big_to_base64, chunk_to_bytes}; pub use buffer::{Buff}; pub use english::{english_dict, lowercase, levenshtein, score_fn, count}; pub use xor_cipher::{single_xor, hamming}; use std::io::{File, BufferedReader, IoError}; pub mod base64; pub mod buffer; pub...
(x: Result<String, IoError>) -> String { let mut unwrapped = x.unwrap(); let n = unwrapped.len(); unwrapped.truncate(n-1); unwrapped } pub fn read_file(input: &str) -> Vec<String> { let path = Path::new(input); let file = match File::open(&path) { Ok(t) => t, Err(e) => fail!("C...
unwrap_and_noline
identifier_name
lib.rs
extern crate num; pub use base64::{u8_to_base64, base64_to_u8, big_to_base64, chunk_to_bytes}; pub use buffer::{Buff}; pub use english::{english_dict, lowercase, levenshtein, score_fn, count}; pub use xor_cipher::{single_xor, hamming}; use std::io::{File, BufferedReader, IoError}; pub mod base64; pub mod buffer; pub...
}; let mut reader = BufferedReader::new(file); reader.lines().map(unwrap_and_noline).collect() }
random_line_split
jquery.booleanEditor.js
@package enrol_attributes * @author Julien Furrer <Julien.Furrer@unil.ch> * @copyright 2012-2015 Université de Lausanne (@link http://www.unil.ch} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ ; (function ($) { $.booleanEditor = { defaults: { rules:...
ser_obj['rules'].push(cond_obj); } }); return ser_obj; } function getBooleanExpression(editor) { var expression = ""; $("ul:first > li", editor).each(function () { r = $(this); var c_op = $("select[name='cond-operator']", r).v...
var ser_obj = {rules: []}; var group_c_op = $("select:first[name='cond-operator']", root_elem).val(); if (group_c_op) ser_obj.cond_op = group_c_op; $("ul:first > li", root_elem).each(function () { r = $(this); if (r.hasClass('group')) { ...
identifier_body
jquery.booleanEditor.js
anne (@link http://www.unil.ch} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ ; (function ($) { $.booleanEditor = { defaults: { rules: [], change: null }, paramList: M.enrol_attributes.paramList, operatorList: [ ...
ddNewConditionAfter(
identifier_name
jquery.booleanEditor.js
@package enrol_attributes * @author Julien Furrer <Julien.Furrer@unil.ch> * @copyright 2012-2015 Université de Lausanne (@link http://www.unil.ch} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ ; (function ($) { $.booleanEditor = { defaults: { rules:...
if ($o.data('change')) { $o.data('change').apply($o.get(0)); } } function createRuleList(list_elem, rules) { //var list_elem = $(list_elem); if (list_elem.parent("li").eq(0).hasClass("group")) { console.log("inside a group"); return; ...
$o = $o.parents('.enrol-attributes-boolean-editor').eq(0); }
conditional_block
jquery.booleanEditor.js
}; $.fn.extend({ booleanEditor: function (options) { var isMethodCall = (typeof options == 'string'), // is it a method call or booleanEditor instantiation ? args = Array.prototype.slice.call(arguments, 1); if (isMethodCall) switch (options) { ca...
random_line_split
delta history.js
var config = { type: Phaser.CANVAS, width: 800, height: 600, parent: 'phaser-example', backgroundColor: '#2d2d2d', useTicker: true, scene: { preload: preload, create: create, update: update } }; var image; var time; var delta; var speed = (600 / 2) / 1000; var g...
() { this.load.image('bunny', 'assets/sprites/bunny.png'); this.load.atlas('gems', 'assets/tests/columns/gems.png', 'assets/tests/columns/gems.json'); } function create () { delta = this.add.text(32, 32); time = this.add.text(500, 400); image = this.add.image(0, 200, 'bunny'); this.anims.cre...
preload
identifier_name
delta history.js
var config = { type: Phaser.CANVAS, width: 800, height: 600, parent: 'phaser-example', backgroundColor: '#2d2d2d', useTicker: true, scene: { preload: preload, create: create, update: update } }; var image; var time; var delta; var speed = (600 / 2) / 1000; var g...
function update (timestep, dt) { image.x += speed * dt; if (image.x > 1000) { image.x = 0; } time.setText('time: ' + this.sys.game.loop.time.toString()); delta.setText(this.sys.game.loop.deltaHistory); }
{ delta = this.add.text(32, 32); time = this.add.text(500, 400); image = this.add.image(0, 200, 'bunny'); this.anims.create({ key: 'diamond', frames: this.anims.generateFrameNames('gems', { prefix: 'diamond_', end: 15, zeroPad: 4 }), repeat: -1 }); this.anims.create({ key: 'prism', frames: this.an...
identifier_body
delta history.js
var config = { type: Phaser.CANVAS, width: 800, height: 600, parent: 'phaser-example', backgroundColor: '#2d2d2d', useTicker: true, scene: { preload: preload, create: create, update: update } }; var image; var time; var delta; var speed = (600 / 2) / 1000; var g...
time.setText('time: ' + this.sys.game.loop.time.toString()); delta.setText(this.sys.game.loop.deltaHistory); }
{ image.x = 0; }
conditional_block
delta history.js
var config = { type: Phaser.CANVAS, width: 800, height: 600, parent: 'phaser-example', backgroundColor: '#2d2d2d', useTicker: true, scene: { preload: preload, create: create, update: update } }; var image; var time; var delta; var speed = (600 / 2) / 1000; var g...
image = this.add.image(0, 200, 'bunny'); this.anims.create({ key: 'diamond', frames: this.anims.generateFrameNames('gems', { prefix: 'diamond_', end: 15, zeroPad: 4 }), repeat: -1 }); this.anims.create({ key: 'prism', frames: this.anims.generateFrameNames('gems', { prefix: 'prism_', end: 6, zeroPad: 4 }), ...
function create () { delta = this.add.text(32, 32); time = this.add.text(500, 400);
random_line_split
htmlolistelement.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::HTMLOListElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOList...
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLOListElement { HTMLOListElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLOListElement, localName, prefix, document) } } #[allow(unrooted_mu...
new_inherited
identifier_name
htmlolistelement.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::HTMLOListElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOList...
}
{ let element = HTMLOListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOListElementBinding::Wrap) }
identifier_body
htmlolistelement.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::HTMLOListElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOList...
document: &Document) -> Root<HTMLOListElement> { let element = HTMLOListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOListElementBinding::Wrap) } }
pub fn new(localName: DOMString, prefix: Option<DOMString>,
random_line_split
validationGroup.ts
import { Component, Input, Optional, OnInit, AfterViewInit, OnChanges, SimpleChange } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { services } from 'typescript-angular-utilities'; import __validation = services.validation; import __array = services.array; import { FormCompone...
checkValidity(): void { this.validationControl.updateValueAndValidity(this.model); } }
{ if (changes.model) { this.validationControl.updateValueAndValidity(changes.model.currentValue); } }
identifier_body
validationGroup.ts
import { Component, Input, Optional, OnInit, AfterViewInit, OnChanges, SimpleChange } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { services } from 'typescript-angular-utilities'; import __validation = services.validation; import __array = services.array; import { FormCompone...
(changes: IGroupChanges): void { if (changes.model) { this.validationControl.updateValueAndValidity(changes.model.currentValue); } } checkValidity(): void { this.validationControl.updateValueAndValidity(this.model); } }
ngOnChanges
identifier_name
validationGroup.ts
import { Component, Input, Optional, OnInit, AfterViewInit, OnChanges, SimpleChange } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { services } from 'typescript-angular-utilities'; import __validation = services.validation; import __array = services.array; import { FormCompone...
if (this.validators) { validators = validators.concat(this.arrayUtility.arrayify(this.validators)); } this.groupValidator.initValidator(validators, this.validationControl.valueChanges, this.validationControl); } ngAfterViewInit(): void { this.validationControl.updateValueAndValidity(this.model || undef...
{ validators = validators.concat(this.arrayUtility.arrayify(this.validator)); }
conditional_block
validationGroup.ts
import { Component, Input, Optional, OnInit, AfterViewInit, OnChanges, SimpleChange } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { services } from 'typescript-angular-utilities'; import __validation = services.validation; import __array = services.array; import { FormCompone...
export class ValidationGroupComponent implements OnInit, AfterViewInit, OnChanges { @Input() validator: __validation.IObservableValidationHandler; @Input() validators: __validation.IObservableValidationHandler[]; @Input() model: any; groupValidator: ComponentValidator; formGroup: FormGroup; validationControl: Fo...
template: require('./validationGroup.html'), providers: [ComponentValidator], })
random_line_split
clase.js
module.exports = function (Clase) { Clase.saluda = function (msg, cb) { cb(null, 'Hola pos... ' + msg); }; Clase.remoteMethod( 'saluda', { accepts: { arg: 'msg', type: 'string' }, returns: { arg: 'greeting', type: 'string' } } ); Clase.getcomuna = function (idcomuna, callback) {...
};
random_line_split
stripe.d.ts
export interface StripeCardTokenParams { /** * Card number */ number: string;
*/ expMonth: number; /** * Expiry year */ expYear: number; /** * CVC / CVV */ cvc?: string; /** * Cardholder name */ name?: string; /** * Address line 1 */ address_line1?: string; /** * Address line 2 */ ...
/** * Expiry month
random_line_split
stripe.d.ts
export interface StripeCardTokenParams { /** * Card number */ number: string; /** * Expiry month */ expMonth: number; /** * Expiry year */ expYear: number; /** * CVC / CVV */ cvc?: string; /** * Cardholder name */ ...
{ /** * Set publishable key * @param publishableKey {string} Publishable key * @return {Promise<void>} */ static setPublishableKey(publishableKey: string): Promise<void>; /** * Create Credit Card Token * @param params {StripeCardTokenParams} Credit card information ...
Stripe
identifier_name
random_gen.rs
extern crate time; use std::sync::RwLock; pub trait PRNG { fn get(&mut self) -> u32; fn set_seed(&mut self, seed: u32); } pub fn set_seed_time(prng: &mut PRNG) { prng.set_seed((time::precise_time_ns() as f64 / 1000.0) as u32); } pub fn get_target(prng: &mut PRNG, t: u32) -> u32 { let v = get_01(prng...
} impl PRNG for Xorshift { fn get(&mut self) -> u32 { let t = self.m_x ^ (self.m_x >> 7); self.m_x = self.m_y; self.m_y = self.m_z; self.m_z = self.m_w; self.m_w = self.m_v; self.m_v = (self.m_v ^ (self.m_v << 6)) ^ (t ^ (t << 13)); (self.m_y + self.m_y + 1)...
{ let mut x = Xorshift { m_x: 0, m_y: 0, m_z: 0, m_w: 0, m_v: 0, }; x.set_seed(10000); x }
identifier_body
random_gen.rs
extern crate time; use std::sync::RwLock; pub trait PRNG { fn get(&mut self) -> u32; fn set_seed(&mut self, seed: u32); } pub fn set_seed_time(prng: &mut PRNG) { prng.set_seed((time::precise_time_ns() as f64 / 1000.0) as u32); } pub fn get_target(prng: &mut PRNG, t: u32) -> u32 { let v = get_01(prng...
() -> CMWC4096 { let mut m = CMWC4096 { m_q: [0; 4096], c: 0, }; m.set_seed(10000); m } } impl PRNG for CMWC4096 { fn get(&mut self) -> u32 { let mut t: u64; let a = 18782u64; let b = 4294967295u64; let r = b - 1; ...
new
identifier_name
random_gen.rs
extern crate time; use std::sync::RwLock; pub trait PRNG { fn get(&mut self) -> u32; fn set_seed(&mut self, seed: u32); } pub fn set_seed_time(prng: &mut PRNG) { prng.set_seed((time::precise_time_ns() as f64 / 1000.0) as u32); } pub fn get_target(prng: &mut PRNG, t: u32) -> u32 { let v = get_01(prng...
; let rg = ((high - low) + 1) as f64; let val = low as f64 + get_01(prng) * rg; val as u32 } pub fn get_01(prng: &mut PRNG) -> f64 { prng.get() as f64 / 4294967295f64 } pub struct LCG { m_state: u32, } impl LCG { pub fn new() -> LCG { let mut lcg = LCG { m_state: 0 }; lcg.set...
{ (low, high) }
conditional_block
random_gen.rs
extern crate time; use std::sync::RwLock; pub trait PRNG { fn get(&mut self) -> u32; fn set_seed(&mut self, seed: u32); } pub fn set_seed_time(prng: &mut PRNG) { prng.set_seed((time::precise_time_ns() as f64 / 1000.0) as u32); } pub fn get_target(prng: &mut PRNG, t: u32) -> u32 { let v = get_01(prng...
fn get(&mut self) -> u32 { let t = self.m_x ^ (self.m_x >> 7); self.m_x = self.m_y; self.m_y = self.m_z; self.m_z = self.m_w; self.m_w = self.m_v; self.m_v = (self.m_v ^ (self.m_v << 6)) ^ (t ^ (t << 13)); (self.m_y + self.m_y + 1) * self.m_v } fn set_...
impl PRNG for Xorshift {
random_line_split
material-tabs.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { JsonSchemaFormService } from '../../json-schema-form.service'; @Component({ selector: 'material-tabs-widget', template: ` <nav mat-tab-nav-bar [attr.aria-label]="options?.label || options?.title || ''" [style.width]="'100%'"> ...
() { this.options = this.layoutNode.options || {}; this.itemCount = this.layoutNode.items.length - 1; this.updateControl(); } select(index) { if (this.layoutNode.items[index].type === '$ref') { this.jsf.addItem({ layoutNode: this.layoutNode.items[index], layoutIndex: this.layo...
ngOnInit
identifier_name
material-tabs.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { JsonSchemaFormService } from '../../json-schema-form.service'; @Component({ selector: 'material-tabs-widget', template: ` <nav mat-tab-nav-bar [attr.aria-label]="options?.label || options?.title || ''"
<span *ngIf="showAddTab || item.type !== '$ref'" [innerHTML]="setTabTitle(item, i)"></span> </a> </nav> <div *ngFor="let layoutItem of layoutNode?.items; let i = index" [class]="options?.htmlClass || ''"> <select-framework-widget *ngIf="selectedItem === i" [clas...
[style.width]="'100%'"> <a mat-tab-link *ngFor="let item of layoutNode?.items; let i = index" [active]="selectedItem === i" (click)="select(i)">
random_line_split
material-tabs.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { JsonSchemaFormService } from '../../json-schema-form.service'; @Component({ selector: 'material-tabs-widget', template: ` <nav mat-tab-nav-bar [attr.aria-label]="options?.label || options?.title || ''" [style.width]="'100%'"> ...
; this.selectedItem = index; } updateControl() { this.itemCount = this.layoutNode.items.length - 1; const lastItem = this.layoutNode.items[this.layoutNode.items.length - 1]; this.showAddTab = lastItem.type === '$ref' && this.itemCount < (lastItem.options.maxItems || 1000); } setTabTitle(...
{ this.jsf.addItem({ layoutNode: this.layoutNode.items[index], layoutIndex: this.layoutIndex.concat(index), dataIndex: this.dataIndex.concat(index) }); this.updateControl(); }
conditional_block
CompoundPlugValueWidget.py
, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import IECore import Gaffer import GafferUI from Qt import QtWidgets # This was the predecessor to the far superior GafferUI.PlugLayout # class that we now use. It survives here as a rel...
assert( column is self.__column ) if self.__column.visible() : self.__updateChildPlugUIs() self.__visibilityChangedConnection = None # only need to build once
identifier_body
CompoundPlugValueWidget.py
EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY...
w.plugValueWidget().setReadOnly( readOnly ) def _updateFromPlug( self ) : if self.__summary is not None and self.__collapsible is not None : with self.getContext() : s = self.__summary( self.getPlug() ) if s : s = "<small>" + "&nbsp;( " + s + " ) </small>" self.__collapsible.getCornerWidget...
w.setReadOnly( readOnly ) elif isinstance( w, GafferUI.PlugWidget ) : w.labelPlugValueWidget().setReadOnly( readOnly ) w.plugValueWidget().setReadOnly( readOnly ) else :
random_line_split
CompoundPlugValueWidget.py
SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # ...
( self, plug, collapsed=True, label=None, summary=None, **kw ) : self.__column = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Vertical, spacing = 4 ) self.__label = label if label else IECore.CamelCase.toSpaced( plug.getName() ) self.__collapsible = None if collapsed is not None : self.__coll...
__init__
identifier_name
CompoundPlugValueWidget.py
SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # ...
else : w.plugValueWidget().setReadOnly( readOnly ) def _updateFromPlug( self ) : if self.__summary is not None and self.__collapsible is not None : with self.getContext() : s = self.__summary( self.getPlug() ) if s : s = "<small>" + "&nbsp;( " + s + " ) </small>" self.__collapsible.getC...
w.labelPlugValueWidget().setReadOnly( readOnly ) w.plugValueWidget().setReadOnly( readOnly )
conditional_block
extract_bits.rs
use word::{Word, ToWord}; /// Extract bits [`start`, `start + length`) from `x` into the lower bits /// of the result. /// /// # Keywords: /// /// Gather bit range. /// /// # Intrinsics: /// - BMI 1.0: bextr. /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// let n = 0b1011_1110_1001_0011u16; /// /// as...
<U: Word>(self, start: U, length: U) -> Self { extract_bits(self, start, length) } }
extract_bits
identifier_name
extract_bits.rs
use word::{Word, ToWord}; /// Extract bits [`start`, `start + length`) from `x` into the lower bits /// of the result. /// /// # Keywords: /// /// Gather bit range. /// /// # Intrinsics: /// - BMI 1.0: bextr. /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// let n = 0b1011_1110_1001_0011u16; /// /// as...
}
{ extract_bits(self, start, length) }
identifier_body
extract_bits.rs
use word::{Word, ToWord}; /// Extract bits [`start`, `start + length`) from `x` into the lower bits /// of the result. /// /// # Keywords: /// /// Gather bit range. /// /// # Intrinsics: /// - BMI 1.0: bextr. /// /// # Examples /// /// ```
/// /// assert_eq!(n.extract_bits(1u8, 4u8), 0b1001); /// ``` #[inline] pub fn extract_bits<T: Word, U: Word>(x: T, start: U, length: U) -> T { x.bextr(start.to(), length.to()) } /// Method version of [`extract_bits`](fn.extract_bits.html). pub trait ExtractBits { #[inline] fn extract_bits<U: Word>(self, U...
/// use bitwise::word::*; /// /// let n = 0b1011_1110_1001_0011u16;
random_line_split
lr0.rs
RampTable<Item> = RampTable::new(); let mut accessing_symbol: TVec<State, Symbol> = TVec::new(); // This function creates the initial state, using the DERIVES relation for // the start symbol. From this initial state, we will discover / create all // other states, by examining a state, the next varia...
{ let mut derives = RampTable::<Rule>::with_capacity(gram.nsyms, gram.nrules); for lhs in gram.iter_var_syms() { for rule in gram.iter_rules() { if gram.rlhs(rule) == lhs { derives.push_value(rule as Rule); } } derives.finish_key(); } if l...
identifier_body
lr0.rs
0..gram.nsyms { kernel_base[i] = count; count += symbol_count[i]; } let mut kernel_items: Vec<Item> = vec![Item(0); kernel_items_count]; // values in this array are indexes into kernel_base let mut kernel_end: Vec<usize> = vec![0; gram.nsyms]; // The item sets for each state. l...
(gram: &Grammar) -> RampTable<Rule> { let mut derives = RampTable::<Rule>::with_capacity(gram.nsyms, gram.nrules); for lhs in gram.iter_var_syms() { for rule in gram.iter_rules() { if gram.rlhs(rule) == lhs { derives.push_value(rule as Rule); }
set_derives
identifier_name
lr0.rs
0..gram.nsyms { kernel_base[i] = count; count += symbol_count[i]; } let mut kernel_items: Vec<Item> = vec![Item(0); kernel_items_count]; // values in this array are indexes into kernel_base let mut kernel_end: Vec<usize> = vec![0; gram.nsyms]; // The item sets for each state. l...
let mut rule_set: Bitv32 = Bitv32::from_elem(gram.nrules, false); let mut shift_symbol: Vec<Symbol> = Vec::new(); // this_state represents our position within our work list. The output.states // array represents both our final output, and this_state is the next state // within that array, where we...
// These vectors are used for building tables during each state. // It is inefficient to allocate and free these vectors within // the scope of processing each state. let mut item_set: Vec<Item> = Vec::with_capacity(gram.nitems());
random_line_split
lr0.rs
] let mut state_set: Vec<Vec<State>> = vec![vec![]; gram.nitems()]; let first_derives = set_first_derives(gram, &derives); // These vectors are used for building tables during each state. // It is inefficient to allocate and free these vectors within // the scope of processing each state. let ...
{ nullable[sym] = true; done = false; }
conditional_block
api_example_python.py
# ********************************************************************************************************************************* # # Name: api_example_python.py # # Desc: full api example ...
print('\tapiKeyInfo: returnCode = %s' % retval) # Show all Traffic details chartListTimes = [] chartListTrans = [] trafficItems = parsed['trafficResponse']['trafficItem'] for item in trafficItems: print('\tFound: %s' % item['dateTime']) print('\tFound: %s' % item['dataTransferred']) chartListTimes.append(...
print('API Failed, code: %s' % retval) sys.exit()
conditional_block
api_example_python.py
# ********************************************************************************************************************************* # # Name: api_example_python.py # # Desc: full api example ...
import re import urllib.request USER = os.popen('cat ./_user.db').read() # Create _user.db with your username inside PASS = os.popen('cat ./_pass.db').read() # Create _pass.db with your password inside SVCGRP = 'YourServiceGRP' ...
random_line_split
SpatialJoin.py
# -*- coding: utf-8 -*- """ *************************************************************************** SpatialJoin.py --------------------- Date : October 2013 Copyright : (C) 2013 by Joshua Arnott Email : josh at snorfalorpagus dot net *******************...
def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Join attributes by location') self.group, self.i18n_group = self.trAlgorithm('Vector general tools') self.predicates = ( ('intersects', self.tr('intersects')), ('contains', self.tr('cont...
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'join_location.png'))
identifier_body
SpatialJoin.py
# -*- coding: utf-8 -*- """ *************************************************************************** SpatialJoin.py --------------------- Date : October 2013 Copyright : (C) 2013 by Joshua Arnott Email : josh at snorfalorpagus dot net *******************...
(self): return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'join_location.png')) def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Join attributes by location') self.group, self.i18n_group = self.trAlgorithm('Vector general tools') self.predicate...
getIcon
identifier_name
SpatialJoin.py
# -*- coding: utf-8 -*- """ *************************************************************************** SpatialJoin.py --------------------- Date : October 2013 Copyright : (C) 2013 by Joshua Arnott Email : josh at snorfalorpagus dot net *******************...
median = 0 if count > 1: if (count % 2) == 0: median = 0.5 * ((data[count / 2 - 1]) + (data[count / 2])) else: median = data[(count + 1) / 2 - 1] return median
count = len(data) if count == 1: return data[0] data.sort()
random_line_split
SpatialJoin.py
# -*- coding: utf-8 -*- """ *************************************************************************** SpatialJoin.py --------------------- Date : October 2013 Copyright : (C) 2013 by Joshua Arnott Email : josh at snorfalorpagus dot net *******************...
atMap.append(NULL) numFields[j] = [] atMap.append(count) atMap = dict(list(zip(seq, atMap))) if none: outFeat.setAttributes(atMap1) else: outFeat.setAttributes(li...
for k in sumList: if k == 'sum': atMap.append(sum(self._filterNull(numFields[j]))) elif k == 'mean': try: nn_count = sum(1 for _ in self._filterNull(numFields[j])) ...
conditional_block
contractABI.js
::String; use std::result::Result; use std::fmt; use {util, ethabi}; ${convertContract(name, json, prefs)} `; } function convertContract(name, json, prefs) { return `${prefs._pub ? "pub " : ""}struct ${name} { contract: ethabi::Contract, pub address: util::Address, ${prefs._explicit_do_call ? "" : `do_call: Box<F...
} if (type == "address") return "util::Address"; if (type == "bool") return "bool"; if (type == "string") return "String"; if (type == "bytes") return "Vec<u8>"; if (type == "address[]") return "Vec<util::Address>"; console.log(`Unsupported return type: ${type} (${name})`); } function convertToken(na...
return `util::U${n}`; // ERROR - unsupported integer (signed > 32 or unsigned > 256) }
random_line_split
contractABI.js
::String; use std::result::Result; use std::fmt; use {util, ethabi}; ${convertContract(name, json, prefs)} `; } function convertContract(name, json, prefs) { return `${prefs._pub ? "pub " : ""}struct ${name} { contract: ethabi::Contract, pub address: util::Address, ${prefs._explicit_do_call ? "" : `do_call: Box<F...
(json, _prefs) { let cprefs = _prefs || {}; let prefs = (_prefs || {})[json.name] || (_prefs || {})['_'] || {}; let snakeName =
convertFunction
identifier_name
contractABI.js
::String; use std::result::Result; use std::fmt; use {util, ethabi}; ${convertContract(name, json, prefs)} `; } function convertContract(name, json, prefs) { return `${prefs._pub ? "pub " : ""}struct ${name} { contract: ethabi::Contract, pub address: util::Address, ${prefs._explicit_do_call ? "" : `do_call: Box<F...
} function tokenCoerce(name, type, _prefs) { let prefs = _prefs || {}; var m; if ((m = type.match(/^bytes(\d+)$/)) != null && m[1] <= 32) { if (prefs['string']) return `String::from_utf8(${name}).unwrap_or_else(String::new)`; else return `util::H${m[1] * 8}::from_slice(${name}.as_ref())`; } if ((m = ty...
{ let prefs = _prefs || {}; var m; if ((m = type.match(/^bytes(\d+)$/)) != null && m[1] <= 32) return `${name}.to_fixed_bytes()`; if ((m = type.match(/^(u?)int(\d+)$/)) != null) { return `${name}.to_${m[1]}int()`; } if (type == "address") return `${name}.to_address()`; if (type == "bool") return `${name}...
identifier_body
dashboard-schema_11.js
/** * @copyright Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
goog.provide('p3rf.perfkit.explorer.components.dashboard.versions.DashboardSchemaV11'); goog.require('p3rf.perfkit.explorer.components.dashboard.versions.DashboardVersionUtil'); goog.require('p3rf.perfkit.explorer.models.DatasourceType'); goog.require('p3rf.perfkit.explorer.models.WidgetType'); goog.scope(function...
random_line_split
dashboard-schema_11.js
/** * @copyright Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
return true; }); }; DashboardSchema.prototype.update = function(dashboard) { DashboardVersionUtil.UpdateDashboard(dashboard, null, function(widget) { switch (widget.type) { case WidgetType.TEXT: widget.datasource.type = DatasourceType.TEXT; break; def...
{ return false; }
conditional_block
common.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, re, time, sys import hashlib, bencode import requests from bs4 import BeautifulSoup reload(sys) #print sys.getdefaultencoding() #sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() def parse_tor(file):
#提取无码的格式,如 082516-001 def format_rule1(s): pattern="\d{6}-\d{3}|\d{6}-\d{2}|\d{6}_\d{3}|\d{6}_\d{2}" rs=re.findall(pattern, s); if len(rs)>=1: return rs[0] else: return "" def format_rule2(s): rs='' #匹配开头是数字,判断是非wm编号 wm=re.finda...
bt_path = {} bt_file = open(file, 'rb') bt_info = bencode.bdecode(bt_file.read()).get('info') bt_info_hash_hex = hashlib.sha1(bencode.bencode(bt_info)).hexdigest() bt_file_size = bt_info.get('length') bt_file_name = bt_info.get('name') bt_path[bt_file_name]=bt_file_size ...
identifier_body
common.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, re, time, sys import hashlib, bencode import requests from bs4 import BeautifulSoup reload(sys) #print sys.getdefaultencoding() #sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() def parse_tor(file): bt_path = {} bt_...
mpress', 'Accept-Language': 'en-us;q=0.5,en;q=0.3', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} print "download from "+url+"\n" try: response = requests.get(ur...
late, co
identifier_name
common.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, re, time, sys import hashlib, bencode import requests from bs4 import BeautifulSoup reload(sys) #print sys.getdefaultencoding() #sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() def parse_tor(file): bt_path = {} bt_...
alpha_list=re.findall(r'\D+', s) if len(alpha_list)>0: rs+=alpha_list[0] #查找所有的数字,['267', '0001', '4'] #第一个元素就是"267" num_list=re.findall(r'\d+', s) if len(num_list)>0: rs+=num_list[0] if rs=='': rs=s rs=rs.replace("-","") rs=rs.replac...
return rs # 如:mide-267FHD_ok_0001.mp4 #查找所有的非数字,['mide-', 'FHD_ok_', '.mp'] #第一个元素就是"mide-"
random_line_split
common.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, re, time, sys import hashlib, bencode import requests from bs4 import BeautifulSoup reload(sys) #print sys.getdefaultencoding() #sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() def parse_tor(file): bt_path = {} bt_...
c: ["file"] #des:[("file","path")] from collections import defaultdict dic=defaultdict(list) for x in src: for a,b in des: #print x,a,b if format_rule2(x)==format_rule2(a): dic[x].append(os.path.join(b,a)) return ...
ace("\n",""),txtfile)) return store #����list�ԱȺ��Ĺ��ܣ������ܵ��� def comparelist(src,des): #sr
conditional_block
setup.py
#!/usr/bin/env python # encoding: utf-8 # from __future__ import unicode_literals from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) def readme(): "Falls back to just file().read() on any error, because the conversion to rst is only really relevant when up...
author='Martin Häcker, Robert Buchholz, Felix Schwarz', author_email='mhaecker@mac.com, rbu@rbu.sh, felix@schwarz-online.org', license="ISC", url='https://github.com/dwt/simplesuper', keywords='python 2, super, convenience, api', py_modules=['simplesuper'], test_suite = "simplesuper", )
"Intended Audience :: Developers", "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: ISC License (ISCL)", ],
random_line_split
setup.py
#!/usr/bin/env python # encoding: utf-8 # from __future__ import unicode_literals from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) def readme():
setup( name='simplesuper', description='Simpler way to call super methods without all the repetition', long_description=readme(), version='1.0.9', classifiers=[ "Programming Language :: Python :: 2", "Topic :: Software Development", "Topic :: Utilities", "Intended ...
"Falls back to just file().read() on any error, because the conversion to rst is only really relevant when uploading the package to pypi" from subprocess import CalledProcessError try: from subprocess import check_output return check_output(['pandoc', '--from', 'markdown', '--to', 'rst', 'README...
identifier_body
setup.py
#!/usr/bin/env python # encoding: utf-8 # from __future__ import unicode_literals from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) def
(): "Falls back to just file().read() on any error, because the conversion to rst is only really relevant when uploading the package to pypi" from subprocess import CalledProcessError try: from subprocess import check_output return check_output(['pandoc', '--from', 'markdown', '--to', 'rst',...
readme
identifier_name
malware.ts
import { ExternalReference, KillChainPhase } from '.'; import { Constance } from '../utils/constance'; export class Malware { public url = Constance.MALWARE_URL; public id: string; public type: string; public links: {self: string}; public attributes: { version: string; created: Dat...
else { this.attributes = this.createAttributes(); } } private createAttributes(): any { return { // version: '1', // created: moment().format(Constance.DATE_FORMATE), // modified: moment().format(Constance.DATE_FORMATE), // descriptio...
{ this.attributes = data.attributes; this.id = data.id; }
conditional_block
malware.ts
import { ExternalReference, KillChainPhase } from '.'; import { Constance } from '../utils/constance'; export class Malware { public url = Constance.MALWARE_URL; public id: string; public type: string; public links: {self: string}; public attributes: { version: string; created: Dat...
private createAttributes(): any { return { // version: '1', // created: moment().format(Constance.DATE_FORMATE), // modified: moment().format(Constance.DATE_FORMATE), // description: '', // name: '', labels: [], external_r...
{ this.type = Constance.MALWARE_TYPE; if (data) { this.attributes = data.attributes; this.id = data.id; } else { this.attributes = this.createAttributes(); } }
identifier_body
malware.ts
import { ExternalReference, KillChainPhase } from '.'; import { Constance } from '../utils/constance'; export class Malware { public url = Constance.MALWARE_URL; public id: string; public type: string; public links: {self: string}; public attributes: { version: string; created: Dat...
(): any { return { // version: '1', // created: moment().format(Constance.DATE_FORMATE), // modified: moment().format(Constance.DATE_FORMATE), // description: '', // name: '', labels: [], external_references: [], kil...
createAttributes
identifier_name
malware.ts
import { ExternalReference, KillChainPhase } from '.'; import { Constance } from '../utils/constance'; export class Malware { public url = Constance.MALWARE_URL; public id: string; public type: string; public links: {self: string}; public attributes: { version: string; created: Dat...
}; } }
external_references: [], kill_chain_phases: [], metaProperties: { published: true }
random_line_split
trait-bounds-in-arc.rs
// Copyright 2013-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-MI...
(&self) -> usize { 4 } fn of_good_pedigree(&self) -> bool { self.bark_decibels < 70 || self.tricks_known > 20 } } impl Pet for Goldfyshe { fn name(&self, mut blk: Box<FnMut(&str)>) { blk(&self.name) } fn num_legs(&self) -> usize { 0 } fn of_good_pedigree(&self) -> bool { self.swim_speed >= 5...
num_legs
identifier_name
trait-bounds-in-arc.rs
// Copyright 2013-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-MI...
rx1.recv(); rx2.recv(); rx3.recv(); t1.join(); t2.join(); t3.join(); } fn check_legs(arc: Arc<Vec<Box<Pet+Sync+Send>>>) { let mut legs = 0; for pet in &*arc { legs += pet.num_legs(); } assert!(legs == 12); } fn check_names(arc: Arc<Vec<Box<Pet+Sync+Send>>>) { for pet...
let t3 = thread::spawn(move|| { check_pedigree(arc3); tx3.send(()); });
random_line_split
ghrelease.js
var React = require('react'); var request = require('superagent'); var GHRelease = React.createClass({ getInitialState: function() { return { windows: null } }, componentDidMount: function() { request.get( 'https://api.github.com/repos/musicpicker/MusicPickerDevice/releases/latest' )...
if (this.state.windows !== null) { buttons = <a href={this.state.windows} className="btn btn-primary">Windows</a> } return ( <div className="panel panel-primary"> <div className="panel-body"> <div className="row"> <div className="col-md-2"> <span sty...
render: function() { var buttons = ( <span>Fetching latest releases...</span> );
random_line_split
ghrelease.js
var React = require('react'); var request = require('superagent'); var GHRelease = React.createClass({ getInitialState: function() { return { windows: null } }, componentDidMount: function() { request.get( 'https://api.github.com/repos/musicpicker/MusicPickerDevice/releases/latest' )...
})[0].browser_download_url; this.setState({windows: url}); } }.bind(this)); }, render: function() { var buttons = ( <span>Fetching latest releases...</span> ); if (this.state.windows !== null) { buttons = <a href={this.state.windows} className="btn btn-primary">W...
{ return true; }
conditional_block
path_tool.py
__author__ = 'Dongwoo Kim' import itertools from collections import defaultdict import numpy as np def num_neighbor(T, idx, link_val=1): """ find neighborhood of given idx (node) """ outlink = len(np.nonzero(T[idx, :, :] == link_val)) inlink = len(np.nonzero(T[:, idx, :] == link_val)) retur...
return ((i, j, a), (j, k, b), (i, k, c)) def tri_index(T, link_val=1): """ extract indices of every possible triangular path in the graph especially for the following path structure i -> j j -> k i -> k @param T: [E x E x K] tensor graph where T[i,j,k] = 1 when there is type k link ...
find = True
conditional_block
path_tool.py
__author__ = 'Dongwoo Kim' import itertools from collections import defaultdict import numpy as np def num_neighbor(T, idx, link_val=1): """ find neighborhood of given idx (node) """ outlink = len(np.nonzero(T[idx, :, :] == link_val)) inlink = len(np.nonzero(T[:, idx, :] == link_val)) retur...
from scipy.io.matlab import loadmat mat = loadmat('../data/alyawarradata.mat') T = np.array(mat['Rs'], np.float32) indices = tri_index(T) print(len(indices)) for ix in range(10): a, b, c = indices[ix] i, j, t1 = a j, k, t2 = b i, k, t3 = c print('a path ...
def test():
random_line_split
path_tool.py
__author__ = 'Dongwoo Kim' import itertools from collections import defaultdict import numpy as np def num_neighbor(T, idx, link_val=1): """ find neighborhood of given idx (node) """ outlink = len(np.nonzero(T[idx, :, :] == link_val)) inlink = len(np.nonzero(T[:, idx, :] == link_val)) retur...
if len(_tmp) != 0: link_types[(i, j)] = np.nonzero(T[i, j, :])[0] for i in range(e): out_links = np.setdiff1d(np.nonzero(T_squeeze[i, :])[0], i) for j, k in itertools.permutations(out_links, 2): if T_squeeze[j, k] != 0: # at least one edge from j to k exists ...
""" extract indices of every possible triangular path in the graph especially for the following path structure i -> j j -> k i -> k @param T: [E x E x K] tensor graph where T[i,j,k] = 1 when there is type k link between node i and j @return: list of tuples consist of (x, y, z) where a, b, c...
identifier_body
path_tool.py
__author__ = 'Dongwoo Kim' import itertools from collections import defaultdict import numpy as np def
(T, idx, link_val=1): """ find neighborhood of given idx (node) """ outlink = len(np.nonzero(T[idx, :, :] == link_val)) inlink = len(np.nonzero(T[:, idx, :] == link_val)) return outlink + inlink def sample_broken_tri(T, link_val=1): """ find three nodes which do not have triangular pa...
num_neighbor
identifier_name
activex-iwshruntimelibrary-tests.ts
/// <reference types="windows-script-host" /> const collectionToArray = <T>(col: { Item(key: any): T }): T[] => { const results: T[] = []; const enumerator = new Enumerator<T>(col); enumerator.moveFirst(); while (!enumerator.atEnd())
return results; }; const wshn = new ActiveXObject('WScript.Network'); // https://msdn.microsoft.com/en-us/library/s6wt333f(v=vs.84).aspx // https://msdn.microsoft.com/en-us/library/wck0hkd7(v=vs.84).aspx // https://msdn.microsoft.com/en-us/library/tte130y1(v=vs.84).aspx // https://msdn.microsoft.com/en-us/librar...
{ results.push(enumerator.item()); enumerator.moveNext(); }
conditional_block
activex-iwshruntimelibrary-tests.ts
/// <reference types="windows-script-host" /> const collectionToArray = <T>(col: { Item(key: any): T }): T[] => { const results: T[] = []; const enumerator = new Enumerator<T>(col); enumerator.moveFirst();
enumerator.moveNext(); } return results; }; const wshn = new ActiveXObject('WScript.Network'); // https://msdn.microsoft.com/en-us/library/s6wt333f(v=vs.84).aspx // https://msdn.microsoft.com/en-us/library/wck0hkd7(v=vs.84).aspx // https://msdn.microsoft.com/en-us/library/tte130y1(v=vs.84).aspx // htt...
while (!enumerator.atEnd()) { results.push(enumerator.item());
random_line_split
index.test.tsx
import * as React from 'react'; import * as sinon from 'sinon'; import { mount } from 'enzyme'; import { expect } from 'chai'; import { Home } from './'; /** Data */ const props = { nodes: { isFetching: false, data: [ { id: 1, name: 'Santral', image: '/media/nodes/santral_AD5d4P...
it('calls getNodes', () => { expect(props.getNodes).to.have.property('callCount', 1); }); });
props.nodes.data = []; const component = mount(<Home {...props} />);
random_line_split
cli.py
import json from prismriver import util, main class SongJsonEncoder(json.JSONEncoder): def default(self, o):
def format_output(songs, output_format, txt_template=None): if output_format == 'txt': formatted_songs = [] for song in songs: lyrics_txt = '' if song.lyrics: index = 0 for lyric in song.lyrics: lyrics_txt += lyric ...
return o.__dict__
identifier_body
cli.py
import json from prismriver import util, main class SongJsonEncoder(json.JSONEncoder): def default(self, o): return o.__dict__ def format_output(songs, output_format, txt_template=None): if output_format == 'txt': formatted_songs = [] for song in songs: lyrics_txt = '' ...
else: pass def list_plugins(): plugins = main.get_plugins() plugins.sort(key=lambda x: x.plugin_name.lower()) for plugin in plugins: print('{:<20} [id: {}]'.format(plugin.plugin_name, plugin.ID)) def run(): parser = util.init_args_parser() parser.add_argument('--list', actio...
random_line_split
cli.py
import json from prismriver import util, main class SongJsonEncoder(json.JSONEncoder): def default(self, o): return o.__dict__ def format_output(songs, output_format, txt_template=None): if output_format == 'txt': formatted_songs = [] for song in songs: lyrics_txt = '' ...
result = txt_template result = result.replace('%TITLE%', song.title) result = result.replace('%ARTIST%', song.artist) result = result.replace('%PLUGIN_ID%', song.plugin_name) result = result.replace('%PLUGIN_NAME%', song.plugin_name) result = res...
lyrics_txt += lyric if index < len(song.lyrics) - 1: lyrics_txt += '\n\n<<< --- --- --- >>>\n\n' index += 1
conditional_block
cli.py
import json from prismriver import util, main class
(json.JSONEncoder): def default(self, o): return o.__dict__ def format_output(songs, output_format, txt_template=None): if output_format == 'txt': formatted_songs = [] for song in songs: lyrics_txt = '' if song.lyrics: index = 0 ...
SongJsonEncoder
identifier_name
app.po.ts
import { browser, element, by, ElementFinder, ExpectedConditions } from 'protractor'; const githubRegex = /https:\/\/github.com\/angular\/angular\//; export class SitePage { links = element.all(by.css('md-toolbar a')); homeLink = element(by.css('a.home')); docsMenuLink = element(by.cssContainingText('aio-top-m...
static async setWindowWidth(newWidth: number) { const win = browser.driver.manage().window(); const oldSize = await win.getSize(); await win.setSize(newWidth, oldSize.height); } getNavItem(pattern: RegExp) { return element.all(by.css('aio-nav-item .vertical-menu-item')) .filter...
docViewer = element(by.css('aio-doc-viewer')); codeExample = element.all(by.css('aio-doc-viewer pre > code')); ghLinks = this.docViewer .all(by.css('a')) .filter(async a => githubRegex.test(await a.getAttribute('href')));
random_line_split