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
mod.rs
//! First set construction and computation. use collections::{map, Map}; use grammar::repr::*; use lr1::lookahead::{Token, TokenSet}; #[cfg(test)] mod test; #[derive(Clone)] pub struct FirstSets { map: Map<NonterminalString, TokenSet>, } impl FirstSets { pub fn new(grammar: &Grammar) -> FirstSets { ...
}
random_line_split
parallel_coordinates_container.ts
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
return colorMap[runId]; }; }) ); constructor(private readonly store: Store<State>) {} }
{ throw new Error(`[Color scale] unknown runId: ${runId}.`); }
conditional_block
parallel_coordinates_container.ts
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
(private readonly store: Store<State>) {} }
constructor
identifier_name
parallel_coordinates_container.ts
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
getSelectedAnnotations, getSidebarWidth, } from '../../../store'; import {convertToCoordinateData} from '../../../util/coordinate_data'; import { metricIsNpmiAndNotDiff, stripMetricString, } from '../../../util/metric_type'; @Component({ selector: 'npmi-parallel-coordinates', template: ` <parallel-coor...
import {RunColorScale} from '../../../../../types/ui'; import { getAnnotationData, getMetricFilters, getRunToMetrics,
random_line_split
raceData.js
/*global define*/ /*jslint nomen:true,plusplus:true,white:true,browser:true*/ define(["dojo/number"], function (number) { "use strict"; /** * @constructor */ function RaceData(/**{Object.<string,number>}*/ queryResults) { /** @member {!number} */ this.white = queryResults.SUM_White || queryResults.white || ...
/** @member {!number} */ this.other = queryResults.SUM_SomeOtherRace || queryResults.other || queryResults.SomeOtherRace || 0; /** @member {!number} */ this.twoOrMoreRaces = queryResults.SUM_TwoOrMoreRaces || queryResults.twoOrMoreRaces || queryResults.TwoOrMoreRaces || 0; /////** @member {Object.<string, nu...
random_line_split
raceData.js
/*global define*/ /*jslint nomen:true,plusplus:true,white:true,browser:true*/ define(["dojo/number"], function (number) { "use strict"; /** * @constructor */ function
(/**{Object.<string,number>}*/ queryResults) { /** @member {!number} */ this.white = queryResults.SUM_White || queryResults.white || queryResults.White || 0; /** @member {!number} */ this.minority = queryResults.SUM_NotWhite || queryResults.minority || queryResults.NotWhite || 0; /** @member {!number} */ th...
RaceData
identifier_name
raceData.js
/*global define*/ /*jslint nomen:true,plusplus:true,white:true,browser:true*/ define(["dojo/number"], function (number) { "use strict"; /** * @constructor */ function RaceData(/**{Object.<string,number>}*/ queryResults) { /** @member {!number} */ this.white = queryResults.SUM_White || queryResults.white || ...
} } return table; }; return RaceData; });
{ addRow(propertyName); }
conditional_block
raceData.js
/*global define*/ /*jslint nomen:true,plusplus:true,white:true,browser:true*/ define(["dojo/number"], function (number) { "use strict"; /** * @constructor */ function RaceData(/**{Object.<string,number>}*/ queryResults) { /** @member {!number} */ this.white = queryResults.SUM_White || queryResults.white || ...
tbody.appendChild(tr); } for (propertyName in self) { if (self.hasOwnProperty(propertyName)) { if (RaceData.labels.hasOwnProperty(propertyName)) { addRow(propertyName); } } } return table; }; return RaceData; });
{ var tr, td, label, value, percent; label = RaceData.labels[propertyName]; value = self[propertyName]; percent = (value / total) * 100; tr = document.createElement("tr"); td = document.createElement("td"); td.textContent = label; tr.appendChild(td); td = document.createElement("td"); ...
identifier_body
schema_tests.rs
//! //! Test Schema Loading, XML Validating //! use libxml::schemas::SchemaParserContext; use libxml::schemas::SchemaValidationContext; use libxml::parser::Parser; static SCHEMA: &'static str = r#"<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="note"> <xs:complexT...
() { let xml = Parser::default() .parse_string(INVALID_XML) .expect("Expected to be able to parse XML Document from string"); let mut xsdparser = SchemaParserContext::from_buffer(SCHEMA); let xsd = SchemaValidationContext::from_parser(&mut xsdparser); if let Err(errors) = xsd { for err in &errors ...
schema_from_string_generates_errors
identifier_name
schema_tests.rs
//! //! Test Schema Loading, XML Validating //! use libxml::schemas::SchemaParserContext; use libxml::schemas::SchemaValidationContext; use libxml::parser::Parser; static SCHEMA: &'static str = r#"<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="note"> <xs:complexT...
assert_eq!( "Element 'bad': This element is not expected. Expected is ( to ).\n", err.message() ); } } } }
{ let xml = Parser::default() .parse_string(INVALID_XML) .expect("Expected to be able to parse XML Document from string"); let mut xsdparser = SchemaParserContext::from_buffer(SCHEMA); let xsd = SchemaValidationContext::from_parser(&mut xsdparser); if let Err(errors) = xsd { for err in &errors { ...
identifier_body
schema_tests.rs
//! //! Test Schema Loading, XML Validating //! use libxml::schemas::SchemaParserContext; use libxml::schemas::SchemaValidationContext; use libxml::parser::Parser; static SCHEMA: &'static str = r#"<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="note"> <xs:complexT...
let mut xsdvalidator = xsd.unwrap(); for _ in 0..5 { if let Err(errors) = xsdvalidator.validate_document(&xml) { for err in &errors { assert_eq!( "Element 'bad': This element is not expected. Expected is ( to ).\n", err.message() ); } } } }
{ for err in &errors { println!("{}", err.message()); } panic!("Failed to parse schema"); }
conditional_block
schema_tests.rs
//! //! Test Schema Loading, XML Validating //! use libxml::schemas::SchemaParserContext; use libxml::schemas::SchemaValidationContext; use libxml::parser::Parser; static SCHEMA: &'static str = r#"<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="note"> <xs:complexT...
if let Err(errors) = xsdvalidator.validate_document(&xml) { for err in &errors { assert_eq!( "Element 'bad': This element is not expected. Expected is ( to ).\n", err.message() ); } } } }
} let mut xsdvalidator = xsd.unwrap(); for _ in 0..5 {
random_line_split
directory.ts
 import {DataService} from './dataservice'; import {DocumentLibrary} from './documentlibrary'; export class Directory { name: string; selected: boolean; directories: Array<Directory>; expanded: boolean; parent: any; dataService: DataService; relpath: string; absolutePath: string; s...
} } }
unsetAll(){ this.selected=false; for(var i=0; i<this.directories.length; i++) { this.directories[i].unsetAll();
random_line_split
directory.ts
 import {DataService} from './dataservice'; import {DocumentLibrary} from './documentlibrary'; export class Di
name: string; selected: boolean; directories: Array<Directory>; expanded: boolean; parent: any; dataService: DataService; relpath: string; absolutePath: string; static selectedPath: string; constructor(name,parent) { this.name = name; this.selected = false; ...
rectory {
identifier_name
directory.ts
 import {DataService} from './dataservice'; import {DocumentLibrary} from './documentlibrary'; export class Directory { name: string; selected: boolean; directories: Array<Directory>; expanded: boolean; parent: any; dataService: DataService; relpath: string; absolutePath: string; s...
unsetAll(){ this.selected=false; for(var i=0; i<this.directories.length; i++) { this.directories[i].unsetAll(); } } }
// this.parent.unsetAll(); if (name == "--1") { Directory.selectedPath = ""; } this.parent.select(this.selected); this.selected = true; Directory.selectedPath = Directory.selectedPath+this.name+"/"; }
identifier_body
error.rs
::abi; use syntax::ast; use errors::{Applicability, DiagnosticBuilder}; use syntax_pos::Span; use hir; #[derive(Clone, Copy, Debug)] pub struct ExpectedFound<T> { pub expected: T, pub found: T, } // Data structures used in type unification #[derive(Clone, Debug)] pub enum TypeError<'tcx> { Mismatch, ...
RegionsInsufficientlyPolymorphic(br, _) => { write!(f, "expected bound lifetime parameter{}{}, found concrete lifetime", if br.is_named() { " " } else { "" }, br) } RegionsOverlyPolymorphic(br, _) =...
{ write!(f, "lifetime mismatch") }
conditional_block
error.rs
spec::abi; use syntax::ast; use errors::{Applicability, DiagnosticBuilder}; use syntax_pos::Span; use hir; #[derive(Clone, Copy, Debug)] pub struct ExpectedFound<T> { pub expected: T, pub found: T, } // Data structures used in type unification #[derive(Clone, Debug)] pub enum TypeError<'tcx> { Mismatch, ...
/// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()` /// afterwards to present additional details, particularly when it comes to lifetime-related /// errors. impl<'tcx> fmt::Display for TypeError<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ...
random_line_split
error.rs
_pos::Span; use hir; #[derive(Clone, Copy, Debug)] pub struct ExpectedFound<T> { pub expected: T, pub found: T, } // Data structures used in type unification #[derive(Clone, Debug)] pub enum TypeError<'tcx> { Mismatch, UnsafetyMismatch(ExpectedFound<hir::Unsafety>), AbiMismatch(ExpectedFound<abi:...
note_and_explain_type_err
identifier_name
parser.py
""" functions for evaluating spreadsheet functions primary function is parse, which the rest revolves around evaluate should be called with the full string by a parent program A note on exec: This uses the exec function repeatedly, and where possible, use of it should be minimized, but the intention of this ...
if global_file.verbose: print(s)
identifier_body
parser.py
""" functions for evaluating spreadsheet functions primary function is parse, which the rest revolves around evaluate should be called with the full string by a parent program A note on exec: This uses the exec function repeatedly, and where possible, use of it should be minimized, but the intention of this ...
(s): # if verbose setting, print s if global_file.verbose: print(s)
verbose
identifier_name
parser.py
""" functions for evaluating spreadsheet functions primary function is parse, which the rest revolves around evaluate should be called with the full string by a parent program A note on exec: This uses the exec function repeatedly, and where possible, use of it should be minimized, but the intention of this ...
if char == ')': level -= 1 if level == 0: parent_close = it prefix = get_prefix(s, parent_start) body = s[parent_start + 1: parent_close] formula = '{}({})'.format(prefix, body) replace[formula] = str(parse(p...
if level == 1: parent_start = it
random_line_split
parser.py
""" functions for evaluating spreadsheet functions primary function is parse, which the rest revolves around evaluate should be called with the full string by a parent program A note on exec: This uses the exec function repeatedly, and where possible, use of it should be minimized, but the intention of this ...
exec_string = s exec_string = eval_append(exec_string) verbose(exec_string) exec(exec_string) return global_file.returned def get_prefix(formula_string, start): alpha = 'abcdefghijklmnopqrstuvwxyz' number = '.0123456789' prefix = '' string_position = start - 1 while...
while reference.lower() in s: replacement_cell = global_file.formulas[reference] if replacement_cell.data_type == 'string' and \ not replacement_cell.script: replacement = '\'%s\'' % replacement_cell.text else: ...
conditional_block
OptionalsMapFromTest.ts
import { Assert, UnitTest } from '@ephox/bedrock-client'; import * as Fun from 'ephox/katamari/api/Fun'; import { Optional } from 'ephox/katamari/api/Optional'; import { tOptional } from 'ephox/katamari/api/OptionalInstances'; import * as Optionals from 'ephox/katamari/api/Optionals';
}); UnitTest.test('Optionals.mapFrom === Optionals.map().from()', () => { const f = (x) => x + 1; const check = (input: number | null | undefined) => { Assert.eq('eq', true, Optionals.mapFrom(input, f).equals(Optional.from(input).map(f))); }; check(3); check(null); check(undefined); });
UnitTest.test('Optionals.mapFrom', () => { Assert.eq('eq', 4, Optionals.mapFrom(3, (x) => x + 1).getOrDie()); Assert.eq('eq', Optional.none(), Optionals.mapFrom<number, number>(null, Fun.die('boom')), tOptional()); Assert.eq('eq', Optional.none(), Optionals.mapFrom<number, number>(undefined, Fun.die('boom')), tO...
random_line_split
manc.py
absolute_import, division, print_function, ) # Make Py2's str type like Py3's str = type('') # Rules that take into account part of speech to alter text structure_rules = [ ((["JJ*","NN*"],), (["chuffing",0,1],), 0.1), ((["."],), (["our","kid",0],["init",0],["and","th...
((["ER","END"],), ["AA","'","END"]), ((["T","END"],), ["'","END"],), ((["AE","R"],), ["AE"]), ((["AA","R"],), ["AE","R"]), ((["AH1"],), ["UW"],), ((["AO","R","END"],["UH","R","END"],), ["AH","R"]), ((["AO"],), ["AA"],), ((["NG","END"]...
((["START","HH"],), ["START","'"]),
random_line_split
manc.py
= type('') # Rules that take into account part of speech to alter text structure_rules = [ ((["JJ*","NN*"],), (["chuffing",0,1],), 0.1), ((["."],), (["our","kid",0],["init",0],["and","that",0],["and","stuff",0]), 0.1), ((["NN"],), (["thing"],), 0.05), (...
import re,random,sys text = sys.argv[1] for patts,repls in words: for patt in patts: text = re.sub(r'\b'+patt+r'\b',lambda m: random.choice(repls),text) print(text)
conditional_block
logging-separate-lines.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...
let args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "child" { debug!("foo"); debug!("bar"); return } let p = Command::new(&args[0]) .arg("child") .spawn().unwrap().wait_with_output().unwrap(); assert!(p.statu...
use std::env; use std::str; fn main() {
random_line_split
logging-separate-lines.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...
let p = Command::new(&args[0]) .arg("child") .spawn().unwrap().wait_with_output().unwrap(); assert!(p.status.success()); let mut lines = str::from_utf8(&p.error).unwrap().lines(); assert!(lines.next().unwrap().contains("foo")); assert!(lines.next().unwrap()....
{ debug!("foo"); debug!("bar"); return }
conditional_block
logging-separate-lines.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...
() { let args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "child" { debug!("foo"); debug!("bar"); return } let p = Command::new(&args[0]) .arg("child") .spawn().unwrap().wait_with_output().unwrap(); assert!(p....
main
identifier_name
logging-separate-lines.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...
{ let args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "child" { debug!("foo"); debug!("bar"); return } let p = Command::new(&args[0]) .arg("child") .spawn().unwrap().wait_with_output().unwrap(); assert!(p.sta...
identifier_body
BackboneEncryption.js
define([ 'jquery', 'underscore', 'backbone', 'dispatch', ], function ($,_,Backbone) { Backbone.decryptJsonItem = function(aes, json, exposedFields, callbacks) { // objects provided by the server will not have an encrypted portion if (json.encrypted) { Crypto.decryptAESBlock(aes, json.encrypted, { ...
try { var json = jsons.shift(); var decryptedBlock = decryptedBlocks.shift(); var decrypted = decryptedBlock ? JSON.parse(decryptedBlock) : {}; _.each(exposedFields, function(field) { if (_.has(json,field)) decrypted[field] = json[field]; }); ...
{
random_line_split
reset_autoincrement.js
import {log} from 'node-bits';
const selectPostgres = (table, column) => `select max(${column}) from "${table}"`; const resetPostgres = (table, column, max) => `alter sequence "${table}_${column}_seq" restart with ${max + 1}`; const resetMssql = (table, column, max) => `DBCC CHECKIDENT ('[${table}]', RESEED, ${max + 1});`; const resetMySQL...
const select = (table, column) => `select max(${column}) from ${table}`;
random_line_split
reset_autoincrement.js
import {log} from 'node-bits'; const select = (table, column) => `select max(${column}) from ${table}`; const selectPostgres = (table, column) => `select max(${column}) from "${table}"`; const resetPostgres = (table, column, max) => `alter sequence "${table}_${column}_seq" restart with ${max + 1}`; const rese...
const table = model.getTableName(); const column = 'id'; const select = sqlGen.select(table, column); log(select); return sequelize.query(select).then(result => { const max = result[0][0].max; const reset = sqlGen.reset(table, column, max); log(reset); return sequelize.query(reset); });...
{ return Promise.resolve(); }
conditional_block
32e5974ada25_add_neutron_resources_table.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
(): op.create_table( 'standardattributes', sa.Column('id', sa.BigInteger(), autoincrement=True), sa.Column('resource_type', sa.String(length=255), nullable=False), sa.PrimaryKeyConstraint('id') ) for table in TABLES: op.add_column(table, sa.Column('standard_attr_id', ...
upgrade
identifier_name
32e5974ada25_add_neutron_resources_table.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
op.create_table( 'standardattributes', sa.Column('id', sa.BigInteger(), autoincrement=True), sa.Column('resource_type', sa.String(length=255), nullable=False), sa.PrimaryKeyConstraint('id') ) for table in TABLES: op.add_column(table, sa.Column('standard_attr_id', sa.BigIn...
identifier_body
32e5974ada25_add_neutron_resources_table.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
op.add_column(table, sa.Column('standard_attr_id', sa.BigInteger(), nullable=True))
conditional_block
32e5974ada25_add_neutron_resources_table.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
Revises: 13cfb89f881a Create Date: 2015-09-10 00:22:47.618593 """ # revision identifiers, used by Alembic. revision = '32e5974ada25' down_revision = '13cfb89f881a' TABLES = ('ports', 'networks', 'subnets', 'subnetpools', 'securitygroups', 'floatingips', 'routers', 'securitygrouprules') def upgrade(): ...
"""Add standard attribute table Revision ID: 32e5974ada25
random_line_split
issue-33884.rs
// Copyright 2017 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 ...
(stream: TcpStream) -> io::Result<()> { stream.write_fmt(format!("message received")) //~^ ERROR mismatched types } fn main() { if let Ok(listener) = TcpListener::bind("127.0.0.1:8080") { for incoming in listener.incoming() { if let Ok(stream) = incoming { handle_client(...
handle_client
identifier_name
issue-33884.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { if let Ok(listener) = TcpListener::bind("127.0.0.1:8080") { for incoming in listener.incoming() { if let Ok(stream) = incoming { handle_client(stream); } } } }
{ stream.write_fmt(format!("message received")) //~^ ERROR mismatched types }
identifier_body
issue-33884.rs
// Copyright 2017 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 ...
use std::net::TcpStream; use std::io::{self, Read, Write}; fn handle_client(stream: TcpStream) -> io::Result<()> { stream.write_fmt(format!("message received")) //~^ ERROR mismatched types } fn main() { if let Ok(listener) = TcpListener::bind("127.0.0.1:8080") { for incoming in listener.incoming()...
random_line_split
issue-33884.rs
// Copyright 2017 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 ...
} } }
{ handle_client(stream); }
conditional_block
runtime.js
'use strict' require('should') const DummyTransport = require('chix-transport/dummy') const ProcessManager = require('chix-flow/src/process/manager') const RuntimeHandler = require('../lib/handler/runtime') const pkg = require('../package') const schemas = require('../schemas') // TODO: this just loads the definitio...
const transport = new DummyTransport({ // logger: console, bail: true, schemas: schemas }) RuntimeHandler.handle(pm, transport /*, console*/) transport.capabilities = ['my-capabilities'] transport.once('send', (data, conn) => { data.protocol.should.eql('runtime') da...
const pm = new ProcessManager()
random_line_split
bootstrap-error-renderer.js
define(['exports', './error-renderer'], function (exports, _errorRenderer) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function
(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writa...
_inherits
identifier_name
bootstrap-error-renderer.js
define(['exports', './error-renderer'], function (exports, _errorRenderer) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superCla...
var BootstrapErrorRenderer = (function (_ErrorRenderer) { _inherits(BootstrapErrorRenderer, _ErrorRenderer); function BootstrapErrorRenderer() { _classCallCheck(this, BootstrapErrorRenderer); _ErrorRenderer.apply(this, arguments); } BootstrapErrorRenderer.prototype.render = function r...
{ if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable...
identifier_body
bootstrap-error-renderer.js
define(['exports', './error-renderer'], function (exports, _errorRenderer) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superCla...
exports.BootstrapErrorRenderer = BootstrapErrorRenderer; (function (ELEMENT) { ELEMENT.matches = ELEMENT.matches || ELEMENT.mozMatchesSelector || ELEMENT.msMatchesSelector || ELEMENT.oMatchesSelector || ELEMENT.webkitMatchesSelector; ELEMENT.closest = ELEMENT.closest || function closest(selector) { ...
return BootstrapErrorRenderer; })(_errorRenderer.ErrorRenderer);
random_line_split
bootstrap-error-renderer.js
define(['exports', './error-renderer'], function (exports, _errorRenderer) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superCla...
}; return BootstrapErrorRenderer; })(_errorRenderer.ErrorRenderer); exports.BootstrapErrorRenderer = BootstrapErrorRenderer; (function (ELEMENT) { ELEMENT.matches = ELEMENT.matches || ELEMENT.mozMatchesSelector || ELEMENT.msMatchesSelector || ELEMENT.oMatchesSelector || ELEMENT.webkitMatchesSelect...
{ alert.remove(); }
conditional_block
Logs.py
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import os,re,traceback,sys from waflib import Utils,ansiterm if not os.environ.get('NOSYNC',False): if sys.stdout.isatty()and id(sys.stdout)==id(sys.__stdout__): sys.stdout=ansiterm.AnsiTerm(sys.s...
else: msg=re.sub(r'\r(?!\n)|\x1B\[(K|.*?(m|h|l))','',msg) if rec.levelno>=logging.INFO: if rec.args: return msg%rec.args return msg rec.msg=msg rec.c1=colors.PINK rec.c2=colors.NORMAL return logging.Formatter.format(self,rec) log=None def debug(*k,**kw): global verbose if verbose: k=list(k...
def __init__(self): logging.Formatter.__init__(self,LOG_FORMAT,HOUR_FORMAT) def format(self,rec): try: msg=rec.msg.decode('utf-8') except Exception: msg=rec.msg use=colors_lst['USE'] if(use==1 and rec.stream.isatty())or use==2: c1=getattr(rec,'c1',None) if c1 is None: c1='' if rec.levelno...
identifier_body
Logs.py
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import os,re,traceback,sys from waflib import Utils,ansiterm if not os.environ.get('NOSYNC',False): if sys.stdout.isatty()and id(sys.stdout)==id(sys.__stdout__): sys.stdout=ansiterm.AnsiTerm(sys.s...
(self,record): try: try: self.stream=record.stream except AttributeError: if record.levelno>=logging.WARNING: record.stream=self.stream=sys.stderr else: record.stream=self.stream=sys.stdout self.emit_override(record) self.flush() except(KeyboardInterrupt,SystemExit): raise exc...
emit
identifier_name
Logs.py
#! /usr/bin/env python
if not os.environ.get('NOSYNC',False): if sys.stdout.isatty()and id(sys.stdout)==id(sys.__stdout__): sys.stdout=ansiterm.AnsiTerm(sys.stdout) if sys.stderr.isatty()and id(sys.stderr)==id(sys.__stderr__): sys.stderr=ansiterm.AnsiTerm(sys.stderr) import logging LOG_FORMAT=os.environ.get('WAF_LOG_FORMAT','%(asctime)...
# encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import os,re,traceback,sys from waflib import Utils,ansiterm
random_line_split
Logs.py
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import os,re,traceback,sys from waflib import Utils,ansiterm if not os.environ.get('NOSYNC',False): if sys.stdout.isatty()and id(sys.stdout)==id(sys.__stdout__): sys.stdout=ansiterm.AnsiTerm(sys.s...
if rec.levelno>=logging.INFO: if rec.args: return msg%rec.args return msg rec.msg=msg rec.c1=colors.PINK rec.c2=colors.NORMAL return logging.Formatter.format(self,rec) log=None def debug(*k,**kw): global verbose if verbose: k=list(k) k[0]=k[0].replace('\n',' ') global log log.debug(*k,**k...
msg=re.sub(r'\r(?!\n)|\x1B\[(K|.*?(m|h|l))','',msg)
conditional_block
conf.py
usr/bin/env python # -*- coding: utf-8 -*- # # pysia documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogene...
#html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pysiadoc' # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' ...
# will contain a <link> tag referring to it. The value of this option # must be the base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml").
random_line_split
basic_token_embedder_test.py
# pylint: disable=no-self-use,invalid-name import pytest import torch from torch.autograd import Variable from allennlp.common import Params from allennlp.common.checks import ConfigurationError from allennlp.data import Vocabulary from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder from allennlp...
self.token_embedder = BasicTextFieldEmbedder.from_params(self.vocab, params) self.inputs = { "words1": Variable(torch.LongTensor([[0, 2, 3, 5]])), "words2": Variable(torch.LongTensor([[1, 4, 3, 2]])), "words3": Variable(torch.LongTensor([[1, 5, 1, 2]])) ...
super(TestBasicTextFieldEmbedder, self).setUp() self.vocab = Vocabulary() self.vocab.add_token_to_namespace("1") self.vocab.add_token_to_namespace("2") self.vocab.add_token_to_namespace("3") self.vocab.add_token_to_namespace("4") params = Params({ "words1"...
identifier_body
basic_token_embedder_test.py
# pylint: disable=no-self-use,invalid-name import pytest import torch from torch.autograd import Variable from allennlp.common import Params from allennlp.common.checks import ConfigurationError from allennlp.data import Vocabulary from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder from allennlp...
(self): assert self.token_embedder.get_output_dim() == 10 def test_forward_asserts_input_field_match(self): self.inputs['words4'] = self.inputs['words3'] del self.inputs['words3'] with pytest.raises(ConfigurationError): self.token_embedder(self.inputs) self.input...
test_get_output_dim_aggregates_dimension_from_each_embedding
identifier_name
basic_token_embedder_test.py
# pylint: disable=no-self-use,invalid-name import pytest import torch from torch.autograd import Variable from allennlp.common import Params from allennlp.common.checks import ConfigurationError from allennlp.data import Vocabulary from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder from allennlp...
self.inputs['words3'] = self.inputs['words4'] del self.inputs['words4'] def test_forward_concats_resultant_embeddings(self): assert self.token_embedder(self.inputs).size() == (1, 4, 10)
with pytest.raises(ConfigurationError): self.token_embedder(self.inputs)
random_line_split
sse_spider.py
# -*- coding: utf-8 -*- __author__ = 'tyler' import urllib2 import scrapy from scrapy import log import demjson '''class AutoSpider(scrapy.Spider): name = "sse" allowed_domains = ["query.sse.com.cn"] preurl='http://data.eastmoney.com/stock'; start_urls = [ 'http://query.sse.com.cn/i...
r2=re.compile(ur'\s+[\u4e0 0-\u9fa5]+:\s(\d+)\s+[\u4e00-\u9fa5]+:\s[\u4e00-\u9fa5]+') def readA7(loop): for tmp in loop: mat=r1.match(tmp.decode('utf8')) if mat: lbhItem =LHBItem() lbhItem.symbol= mat.group(1) lbhItem.stockName= mat.group(2) ...
state='buy' rdep = re.compile(ur'\s+\(\d\)') rout=re.compile(ur'^\s?$') for tmp in loop: print tmp if tmp.find('买入营业部名称')>=0: state='buy' continue if tmp.find('卖出营业部名称')>=0: state='sell' continue outMatch=rout.match(t...
identifier_body
sse_spider.py
# -*- coding: utf-8 -*- __author__ = 'tyler' import urllib2 import scrapy from scrapy import log import demjson '''class AutoSpider(scrapy.Spider): name = "sse" allowed_domains = ["query.sse.com.cn"] preurl='http://data.eastmoney.com/stock'; start_urls = [ 'http://query.sse.com.cn/i...
for k in dictlist: print k
random_line_split
sse_spider.py
# -*- coding: utf-8 -*- __author__ = 'tyler' import urllib2 import scrapy from scrapy import log import demjson '''class AutoSpider(scrapy.Spider): name = "sse" allowed_domains = ["query.sse.com.cn"] preurl='http://data.eastmoney.com/stock'; start_urls = [ 'http://query.sse.com.cn/i...
(loop,code): state='buy' rdep = re.compile(ur'\s+\(\d\)') rout=re.compile(ur'^\s?$') for tmp in loop: print tmp if tmp.find('买入营业部名称')>=0: state='buy' continue if tmp.find('卖出营业部名称')>=0: state='sell' continue out...
readDep
identifier_name
sse_spider.py
# -*- coding: utf-8 -*- __author__ = 'tyler' import urllib2 import scrapy from scrapy import log import demjson '''class AutoSpider(scrapy.Spider): name = "sse" allowed_domains = ["query.sse.com.cn"] preurl='http://data.eastmoney.com/stock'; start_urls = [ 'http://query.sse.com.cn/i...
for k in dictlist: print k
k if tmp.find('二、')>=0: print '-------'
conditional_block
controller.js
/*jshint globalstrict: true*/ 'use strict'; function addToScope(locals, identifier, instance) { if (locals && _.isObject(locals.$scope))
else { throw 'Cannot export controller as ' + identifier + '! No $scope object provided via locals'; } } function $ControllerProvider() { var controllers = {}; var globals = false; this.allowGlobals = function() { globals = true; }; this.register = function(name, controller) { if (_.isO...
{ locals.$scope[identifier] = instance; }
conditional_block
controller.js
/*jshint globalstrict: true*/ 'use strict'; function
(locals, identifier, instance) { if (locals && _.isObject(locals.$scope)) { locals.$scope[identifier] = instance; } else { throw 'Cannot export controller as ' + identifier + '! No $scope object provided via locals'; } } function $ControllerProvider() { var controllers = {}; var globals = false;...
addToScope
identifier_name
controller.js
/*jshint globalstrict: true*/ 'use strict'; function addToScope(locals, identifier, instance) { if (locals && _.isObject(locals.$scope)) { locals.$scope[identifier] = instance; } else { throw 'Cannot export controller as ' + identifier + '! No $scope object provided via locals'; } } function $Contro...
ctrl = controllers[ctrl]; } else if (globals) { ctrl = window[ctrl]; } } var instance; if (later) { var ctrlConstructor = _.isArray(ctrl) ? _.last(ctrl) : ctrl; instance = Object.create(ctrlConstructor.prototype); if (identifier) { ...
identifier = identifier || match[3]; if (controllers.hasOwnProperty(ctrl)) {
random_line_split
controller.js
/*jshint globalstrict: true*/ 'use strict'; function addToScope(locals, identifier, instance) { if (locals && _.isObject(locals.$scope)) { locals.$scope[identifier] = instance; } else { throw 'Cannot export controller as ' + identifier + '! No $scope object provided via locals'; } } function $Contro...
if (_.isString(ctrl)) { var match = ctrl.match(/^(\S+)(\s+as\s+(\w+))?/); ctrl = match[1]; identifier = identifier || match[3]; if (controllers.hasOwnProperty(ctrl)) { ctrl = controllers[ctrl]; } else if (globals) { ctrl = window[ctrl]; } }...
{ var controllers = {}; var globals = false; this.allowGlobals = function() { globals = true; }; this.register = function(name, controller) { if (_.isObject(name)) { _.extend(controllers, name); } else { controllers[name] = controller; } }; this.$get = ['$injector', functio...
identifier_body
cron.js
SyncedCron.config({ // Log job run details to console log: true,
// Name of collection to use for synchronisation and logging collectionName: DRM.collectionNamePrefix + 'cronHistory', // Default to using localTime utc: false, /* TTL in seconds for history records in collection to expire NOTE: Unset to remove expiry but ensure you remove the index from mongo by ...
// Use a custom logger function (defaults to Meteor's logging package) //logger: null,
random_line_split
animals.js
import test from 'blue-tape'; import animal from '../../../source/zoo/1-just-protos/animal'; // this test is about linking the new instance to a prototype and just setting // the properties on it test('animal speaks', (assert) => { let actual; let expected; let instance = animal; // the proto itself actual ...
// just link the delegate prototye to new instance and augment with dynamic object extension let instance = Object.create(animal); instance.animalType = 'lion'; instance.legs = 4; instance.sound = 'roar'; actual = instance.describe(); expected = 'lion with 4 legs'; assert.equal(actual, expected); a...
random_line_split
ontov.component.ts
import {Component, ViewEncapsulation, Inject, OnInit, OnDestroy} from '@angular/core'; // import {MATERIAL_DIRECTIVES} from 'ng2-material'; import {GlobalEmittersArrayService} from '@colabo-puzzles/f-core/code/puzzles/globalEmitterServicesArray'; import {OntovService, ISearchParam} from './ontov.service'; // VS is a ...
show(path) { this.shown = true; } close() { this.shown = false; } }
{ var searchStr; if(typeof searchVal !== 'string'){ searchStr = this.ontovService.searchValObj2Str(searchVal); }else{ searchStr = searchVal; } this.visualSearch.searchBox.value(searchStr); }
identifier_body
ontov.component.ts
import {Component, ViewEncapsulation, Inject, OnInit, OnDestroy} from '@angular/core'; // import {MATERIAL_DIRECTIVES} from 'ng2-material'; import {GlobalEmittersArrayService} from '@colabo-puzzles/f-core/code/puzzles/globalEmitterServicesArray'; import {OntovService, ISearchParam} from './ontov.service'; // VS is a ...
else { } searchCollectionArray.push({ category: category, value: value }); }); that.ontovService.updateSearchValuesFromComponent(searchCollectionArray); that.ontovService.filterByFacets(); }, facetMatches: fun...
{ }
conditional_block
ontov.component.ts
import {Component, ViewEncapsulation, Inject, OnInit, OnDestroy} from '@angular/core'; // import {MATERIAL_DIRECTIVES} from 'ng2-material'; import {GlobalEmittersArrayService} from '@colabo-puzzles/f-core/code/puzzles/globalEmitterServicesArray'; import {OntovService, ISearchParam} from './ontov.service'; // VS is a ...
() { this.shown = false; } }
close
identifier_name
ontov.component.ts
import {Component, ViewEncapsulation, Inject, OnInit, OnDestroy} from '@angular/core'; // import {MATERIAL_DIRECTIVES} from 'ng2-material'; import {GlobalEmittersArrayService} from '@colabo-puzzles/f-core/code/puzzles/globalEmitterServicesArray'; import {OntovService, ISearchParam} from './ontov.service'; // VS is a ...
show(path) { this.shown = true; } close() { this.shown = false; } }
this.visualSearch.searchBox.value(searchStr); }
random_line_split
recipe-511434.py
HOST = '127.0.0.1' PORT = 8080 from Tkinter import * import tkColorChooser import socket import thread import spots ################################################################################ def main(): global hold, fill, draw, look hold = [] fill = '#000000' connect() root = Tk() root...
(event): if hold: hold.extend([event.x, event.y]) event.widget.create_line(hold[-4:], fill=fill, tag='TEMP') call('create_line', hold[-4:], fill=fill, tag='TEMP') def press(event): global hold hold = [event.x, event.y] def release(event): global hold if len(hold) > 2: ...
motion
identifier_name
recipe-511434.py
HOST = '127.0.0.1' PORT = 8080 from Tkinter import * import tkColorChooser import socket import thread import spots ################################################################################ def main(): global hold, fill, draw, look hold = [] fill = '#000000' connect() root = Tk() root...
draw.bind('<ButtonPress-1>', press) draw.bind('<ButtonRelease-1>', release) draw.bind('<Button-3>', delete) upper.grid(padx=5, pady=5) lower.grid(padx=5, pady=5) draw.grid(row=0, column=0, padx=5, pady=5, columnspan=2) look.grid(padx=5, pady=5) cursor.grid(row=1, column=0, padx=5, pady=5...
look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0) cursor = Button(upper, text='Cursor Color', command=change_cursor) canvas = Button(upper, text='Canvas Color', command=change_canvas) draw.bind('<Motion>', motion)
random_line_split
recipe-511434.py
HOST = '127.0.0.1' PORT = 8080 from Tkinter import * import tkColorChooser import socket import thread import spots ################################################################################ def main(): global hold, fill, draw, look hold = [] fill = '#000000' connect() root = Tk() root...
################################################################################ def motion(event): if hold: hold.extend([event.x, event.y]) event.widget.create_line(hold[-4:], fill=fill, tag='TEMP') call('create_line', hold[-4:], fill=fill, tag='TEMP') def press(event): global hold ...
color = tkColorChooser.askcolor(color=draw['bg'])[1] if color is not None: draw['bg'] = color draw.config(bg=color) call('config', bg=color)
identifier_body
recipe-511434.py
HOST = '127.0.0.1' PORT = 8080 from Tkinter import * import tkColorChooser import socket import thread import spots ################################################################################ def main(): global hold, fill, draw, look hold = [] fill = '#000000' connect() root = Tk() root...
################################################################################ def motion(event): if hold: hold.extend([event.x, event.y]) event.widget.create_line(hold[-4:], fill=fill, tag='TEMP') call('create_line', hold[-4:], fill=fill, tag='TEMP') def press(event): global hold ...
draw['bg'] = color draw.config(bg=color) call('config', bg=color)
conditional_block
util.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn min_stack() -> uint { static MIN: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT; match MIN.load(atomic::SeqCst) { 0 => {} n => return n - 1, } let amt = os::getenv("RUST_MIN_STACK").and_then(|s| from_str(s.as_slice())); let amt = amt.unwrap_or(2 * 1024 * 1024); // 0 is o...
{ (cfg!(target_os="macos")) && running_on_valgrind() }
identifier_body
util.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// 0 is our sentinel value, so ensure that we'll never see 0 after // initialization has run MIN.store(amt + 1, atomic::SeqCst); return amt; } /// Get's the number of scheduler threads requested by the environment /// either `RUST_THREADS` or `num_cpus`. pub fn default_sched_threads() -> uint { mat...
random_line_split
util.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() -> uint { match os::getenv("RUST_THREADS") { Some(nstr) => { let opt_n: Option<uint> = FromStr::from_str(nstr.as_slice()); match opt_n { Some(n) if n > 0 => n, _ => panic!("`RUST_THREADS` is `{}`, should be a positive integer", nstr) } ...
default_sched_threads
identifier_name
lib.rs
use std::collections::HashMap; use std::fmt::Display; use std::path::Path; use std::sync::Arc; use log::debug; use serde::{Deserialize, Serialize}; mod eval; pub mod util; #[derive(Clone, Serialize, Deserialize, Default, PartialEq, Debug)] struct EvalServiceCfg { timeout: usize, languages: HashMap<String, La...
context: Option<U>, ) -> Result<String, String> where T: AsRef<str>, U: AsRef<str>, { debug!("evaluating {}: \"{}\"", self.name, code.as_ref()); let timeout = match timeout { Some(0) => None, Some(n) => Some(n), None => self.timeout...
impl Language { pub async fn eval<T, U>( &self, code: T, timeout: Option<usize>,
random_line_split
lib.rs
use std::collections::HashMap; use std::fmt::Display; use std::path::Path; use std::sync::Arc; use log::debug; use serde::{Deserialize, Serialize}; mod eval; pub mod util; #[derive(Clone, Serialize, Deserialize, Default, PartialEq, Debug)] struct EvalServiceCfg { timeout: usize, languages: HashMap<String, La...
{ Exec(ExecBackend), Network(NetworkBackend), UnixSocket(UnixSocketBackend), } #[derive(Clone, Debug)] pub struct EvalService { timeout: usize, languages: HashMap<String, Arc<Language>>, } #[derive(Clone, PartialEq, Debug)] pub struct Language { name: String, code_before: Option<String>, ...
BackendCfg
identifier_name
soft_rope.js
function demo() { view.moveCam({ theta:40, phi:30, distance:70, target:[0,0,0] }); physic.set(); // reset default setting //physic.add({type:'plane', friction:0.6, restitution:0.1 }); // infinie plane var z = 0; for( var i = 0; i < 20; i++){ z = -20 + i*2; physic.add({ ...
diterations:0, fixed: 1+2, margin:0.5,// memorry bug !!! }); } var i = 10; while(i--){ physic.add({ type:'sphere', size:[Math.rand(2,4)], pos:[Math.rand(-30,30), 30+(i*3), Math.rand(-10,10)], mass:0.2}); } physic.postUpdate = update; } functio...
end:[40,10,z], numSegment:20, viterations:10, piterations:10, citerations:4,
random_line_split
soft_rope.js
function demo() { view.moveCam({ theta:40, phi:30, distance:70, target:[0,0,0] }); physic.set(); // reset default setting //physic.add({type:'plane', friction:0.6, restitution:0.1 }); // infinie plane var z = 0; for( var i = 0; i < 20; i++){ z = -20 + i*2; physic.add({ ...
() { var r = []; // get list of rigidbody var bodys = physic.getBodys(); bodys.forEach( function ( b, id ) { if( b.position.y < -3 ){ r.push( { name:b.name, pos:[ Math.rand(-30,30), 50, Math.rand(-10,10)], noVelocity:true } ); } }); // apply new matrix to bodys ...
update
identifier_name
soft_rope.js
function demo()
start:[-40,10,z], end:[40,10,z], numSegment:20, viterations:10, piterations:10, citerations:4, diterations:0, fixed: 1+2, margin:0.5,// memorry bug !!! }); } var i = 10; while(i--){ ...
{ view.moveCam({ theta:40, phi:30, distance:70, target:[0,0,0] }); physic.set(); // reset default setting //physic.add({type:'plane', friction:0.6, restitution:0.1 }); // infinie plane var z = 0; for( var i = 0; i < 20; i++){ z = -20 + i*2; physic.add({ type:'...
identifier_body
soft_rope.js
function demo() { view.moveCam({ theta:40, phi:30, distance:70, target:[0,0,0] }); physic.set(); // reset default setting //physic.add({type:'plane', friction:0.6, restitution:0.1 }); // infinie plane var z = 0; for( var i = 0; i < 20; i++){ z = -20 + i*2; physic.add({ ...
physic.postUpdate = update; } function update () { var r = []; // get list of rigidbody var bodys = physic.getBodys(); bodys.forEach( function ( b, id ) { if( b.position.y < -3 ){ r.push( { name:b.name, pos:[ Math.rand(-30,30), 50, Math.rand(-10,10)], noVelocity:true } );...
{ physic.add({ type:'sphere', size:[Math.rand(2,4)], pos:[Math.rand(-30,30), 30+(i*3), Math.rand(-10,10)], mass:0.2}); }
conditional_block
zh.js
// Copyright 2016 The HongJiang Library Project Authors. All right reserved. // Use of this source code is governed by a Apache-style // license that can be found in the LICENSE file. // // Administrator服務之簡體中文語言包 // // @authors hjboss <hongjiangproject@gmail.com> 2016-07-05 13:45:04 CST $$ // @version 0.1.0 module.exp...
'siteTitle': 'Collavis China', 'homeTitle': '康萊美姿 ', 'siteKeyword': '康萊美姿 collavis.com.cn', 'siteDescription': '康萊美姿 化妝品國際著名品牌', 'siteAuthor': 'collavis.com.cn', 'siteCopyright': 'collavis.com.cn, 2016 co.ltd', 'footerCompany': '濟南康婷生物科技有限公司 JINAN CO.LTD', ...
random_line_split
SIFpreprocessing_test.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Mar 10 11:34:46 2017 @author: maryam """ import nltk import numpy as np import sys from nltk.corpus import stopwords from sklearn.decomposition import TruncatedSVD np.seterr(divide='ignore', invalid='ignore') #reload(sys) #sys.setdefaultencoding("utf-8...
else: XX = X - X.dot(pc.transpose()).dot(pc) return XX def SIF_embedding(We, x, w, npc): """ Compute the scores between pairs of sentences using weighted average + removing the projection on the first principal component :param We: We[i,:] is the vector for word i :param x: x[i, :] ar...
XX = X - X.dot(pc.transpose()) * pc
conditional_block
SIFpreprocessing_test.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Mar 10 11:34:46 2017 @author: maryam """ import nltk import numpy as np import sys from nltk.corpus import stopwords from sklearn.decomposition import TruncatedSVD np.seterr(divide='ignore', invalid='ignore') #reload(sys) #sys.setdefaultencoding("utf-8...
def get_weighted_average(We, x, w): """ Compute the weighted average vectors :param We: We[i,:] is the vector for word i :param x: x[i, :] are the indices of the words in sentence i :param w: w[i, :] are the weights for the words in sentence i :return: emb[i, :] are the weighted average vector...
word2vec2= [] for word in vocabulary: try: #print (word) word2vec = word2vec_Dictionary[word.encode('utf-8')] except Exception: #print 'error' word2vec = [0.0000001] * 300 word2vec2.append(word2vec) return...
identifier_body
SIFpreprocessing_test.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Mar 10 11:34:46 2017 @author: maryam """ import nltk import numpy as np import sys from nltk.corpus import stopwords from sklearn.decomposition import TruncatedSVD np.seterr(divide='ignore', invalid='ignore') #reload(sys) #sys.setdefaultencoding("utf-8...
emb = get_weighted_average(We, x, w) embList = emb.tolist() newemb= [] x, y = emb.shape for i in range (x): if (not np.isnan(emb[i,0]) and not np.isinf(emb[i,0]) ): newemb.append(embList[i]) emb = np.asarray(newemb) emb = remove_pc(emb, npc=1) ...
def makingfile(trainTextList, vocabulary, vocabFreq, corpus, alpha, We): x , w= index_vector(trainTextList, vocabulary, vocabFreq, corpus, alpha)
random_line_split
SIFpreprocessing_test.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Mar 10 11:34:46 2017 @author: maryam """ import nltk import numpy as np import sys from nltk.corpus import stopwords from sklearn.decomposition import TruncatedSVD np.seterr(divide='ignore', invalid='ignore') #reload(sys) #sys.setdefaultencoding("utf-8...
(X,npc): """ Compute the principal components :param X: X[i,:] is a data point :param npc: number of principal components to remove :return: component_[i,:] is the i-th pc """ svd = TruncatedSVD(n_components=npc, n_iter=7, random_state=0) svd.fit(X) return svd.components_ def remove...
compute_pc
identifier_name
test_new_ingest.py
#!/usr/bin/env python #=============================================================================== # Copyright 2015 Geoscience Australia # # 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 #...
unittest.TextTestRunner(verbosity=2).run(the_suite())
conditional_block
test_new_ingest.py
#!/usr/bin/env python #=============================================================================== # Copyright 2015 Geoscience Australia # # 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 #...
# # Run unit tests if in __main__ # if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(the_suite())
"""Returns a test suile of all the tests to be run.""" suite_list = [] suite_list.append(test_abstract_ingester.the_suite()) suite_list.append(test_landsat_dataset.the_suite()) suite_list.append(test_landsat_bandstack.the_suite()) suite_list.append(test_dataset_record.the_suite()) # suite_list....
identifier_body
test_new_ingest.py
#!/usr/bin/env python #=============================================================================== # Copyright 2015 Geoscience Australia # # 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 #...
(): """Returns a test suile of all the tests to be run.""" suite_list = [] suite_list.append(test_abstract_ingester.the_suite()) suite_list.append(test_landsat_dataset.the_suite()) suite_list.append(test_landsat_bandstack.the_suite()) suite_list.append(test_dataset_record.the_suite()) # sui...
the_suite
identifier_name
test_new_ingest.py
#!/usr/bin/env python #=============================================================================== # Copyright 2015 Geoscience Australia # # 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 #...
suite_list = [] suite_list.append(test_abstract_ingester.the_suite()) suite_list.append(test_landsat_dataset.the_suite()) suite_list.append(test_landsat_bandstack.the_suite()) suite_list.append(test_dataset_record.the_suite()) # suite_list.append(test_tile_record.the_suite(fast=True)) # suit...
def the_suite(): """Returns a test suile of all the tests to be run."""
random_line_split
green-bean-add.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {ModalController, NavParams} from '@ionic/angular'; import {UIImage} from '../../../../services/uiImage'; import {UIHelper} from '../../../../services/uiHelper'; import {UIFileHelper} from '../../../../services/uiFileHelper'; import {IBeanInformation} fr...
} } public async __addBean() { await this.uiGreenBeanStorage.add(this.data); this.uiToast.showInfoToast('TOAST_GREEN_BEAN_ADDED_SUCCESSFULLY'); this.uiAnalytics.trackEvent(GREEN_BEAN_TRACKING.TITLE, GREEN_BEAN_TRACKING.ACTIONS.ADD_FINISH); this.dismiss(); } public dismiss(): void { ...
random_line_split
green-bean-add.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {ModalController, NavParams} from '@ionic/angular'; import {UIImage} from '../../../../services/uiImage'; import {UIHelper} from '../../../../services/uiHelper'; import {UIFileHelper} from '../../../../services/uiFileHelper'; import {IBeanInformation} fr...
} public async __addBean() { await this.uiGreenBeanStorage.add(this.data); this.uiToast.showInfoToast('TOAST_GREEN_BEAN_ADDED_SUCCESSFULLY'); this.uiAnalytics.trackEvent(GREEN_BEAN_TRACKING.TITLE, GREEN_BEAN_TRACKING.ACTIONS.ADD_FINISH); this.dismiss(); } public dismiss(): void { this....
{ await this.__addBean(); }
conditional_block
green-bean-add.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {ModalController, NavParams} from '@ionic/angular'; import {UIImage} from '../../../../services/uiImage'; import {UIHelper} from '../../../../services/uiHelper'; import {UIFileHelper} from '../../../../services/uiFileHelper'; import {IBeanInformation} fr...
private async __loadBean(_bean: GreenBean) { this.data.name = _bean.name; this.data.note = _bean.note; this.data.aromatics = _bean.aromatics; this.data.weight = _bean.weight; this.data.finished = false; this.data.cost = _bean.cost; this.data.decaffeinated = _bean.decaffeinated; thi...
{ this.modalController.dismiss({ dismissed: true },undefined,GreenBeanAddComponent.COMPONENT_ID); }
identifier_body
green-bean-add.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {ModalController, NavParams} from '@ionic/angular'; import {UIImage} from '../../../../services/uiImage'; import {UIHelper} from '../../../../services/uiHelper'; import {UIFileHelper} from '../../../../services/uiFileHelper'; import {IBeanInformation} fr...
(_bean: GreenBean) { this.data.name = _bean.name; this.data.note = _bean.note; this.data.aromatics = _bean.aromatics; this.data.weight = _bean.weight; this.data.finished = false; this.data.cost = _bean.cost; this.data.decaffeinated = _bean.decaffeinated; this.data.url = _bean.url; ...
__loadBean
identifier_name
textEditorModel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} this.modelService.updateModel(this.textEditorModel, newValue); } createSnapshot(): ITextSnapshot { const model = this.textEditorModel; if (model) { return model.createSnapshot(true /* Preserve BOM */); } return null; } isResolved(): boolean { return !!this.textEditorModelHandle; } dispose(...
return;
random_line_split
textEditorModel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
this.textEditorModelHandle = textEditorModelHandle; // Make sure we clean up when this model gets disposed this.registerModelDisposeListener(model); } private registerModelDisposeListener(model: ITextModel): void { if (this.modelDisposeListener) { this.modelDisposeListener.dispose(); } this.modelD...
{ throw new Error(`Document with resource ${textEditorModelHandle.toString()} does not exist`); }
conditional_block
textEditorModel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
createSnapshot(): ITextSnapshot { const model = this.textEditorModel; if (model) { return model.createSnapshot(true /* Preserve BOM */); } return null; } isResolved(): boolean { return !!this.textEditorModelHandle; } dispose(): void { if (this.modelDisposeListener) { this.modelDisposeListene...
{ if (!this.textEditorModel) { return; } this.modelService.updateModel(this.textEditorModel, newValue); }
identifier_body
textEditorModel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): void { if (this.modelDisposeListener) { this.modelDisposeListener.dispose(); // dispose this first because it will trigger another dispose() otherwise this.modelDisposeListener = null; } if (this.textEditorModelHandle && this.createdEditorModel) { this.modelService.destroyModel(this.textEditorModelH...
dispose
identifier_name
tilemap.rs
extern crate gl; extern crate nalgebra; use gl::types::*; use nalgebra::na::{Mat4}; use nalgebra::na; use std::mem; use std::ptr; use super::engine; use super::shader; use super::math; //static CHUNK_SIZE : u8 = 10; pub struct TilemapChunk { shader :shader::ShaderProgram, vao : u32, vbo_vertices : u32, vbo_in...
/* fn set_program_variable_vbo(&self, name: &str) { //in } */ //move to shader? fn set_program_uniform_mat4(&self, name: &str, m: &Mat4<f32>) { //self.shader let id = self.shader.get_uniform(name); unsafe { gl::UniformMatrix4fv(id, 1, gl::FALSE as u8, mem::transmute(m)); } } } impl engine::Draw...
random_line_split
tilemap.rs
extern crate gl; extern crate nalgebra; use gl::types::*; use nalgebra::na::{Mat4}; use nalgebra::na; use std::mem; use std::ptr; use super::engine; use super::shader; use super::math; //static CHUNK_SIZE : u8 = 10; pub struct TilemapChunk { shader :shader::ShaderProgram, vao : u32, vbo_vertices : u32, vbo_i...
} self.indices_count = tilemap_chunk_indices.len() as u32; //println!("tilemap::setup() Count of vertices: {}", tilemap_chunk_vertices.len()/2); //x,y so /2 //println!("tilemap::setup() Count of indices: {}", self.indices_count); //println!("tilemap::setup() vertices: {}", tilemap_chunk_vertices); //...
{ let index_of = |x :u32, y:u32| x + (y * (tile_count_x+1)); //requires 2 triangles per tile (quad) tilemap_chunk_indices.push(i); //index of (x,y) tilemap_chunk_indices.push(index_of(x+1,y)); tilemap_chunk_indices.push(index_of(x, y+1)); //println!("\ttriangle_one: {}", tilemap_chunk_indices.sl...
conditional_block
tilemap.rs
extern crate gl; extern crate nalgebra; use gl::types::*; use nalgebra::na::{Mat4}; use nalgebra::na; use std::mem; use std::ptr; use super::engine; use super::shader; use super::math; //static CHUNK_SIZE : u8 = 10; pub struct TilemapChunk { shader :shader::ShaderProgram, vao : u32, vbo_vertices : u32, vbo_i...
} impl engine::Drawable for TilemapChunk { fn draw(&self, rc: &engine::RenderContext) { //use shader self.shader.use_program(); let mut model : Mat4<f32> = na::zero(); math::set_identity(&mut model); //set uniform //let mvp = /*rc.projm **/ rc.view; let mvp = rc.projm * rc.view * model; self.set_p...
{ //self.shader let id = self.shader.get_uniform(name); unsafe { gl::UniformMatrix4fv(id, 1, gl::FALSE as u8, mem::transmute(m)); } }
identifier_body