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
//! Contains all of the currently completed standard bots/searchers/AIs. //! //! These are mostly for example purposes, to see how one can create a chess AI. extern crate rand; pub mod minimax; pub mod parallel_minimax; pub mod alphabeta; pub mod jamboree; pub mod iterative_parallel_mvv_lva; use core::piece_move::*;...
/// Searcher that randomly chooses a move. The fastest, yet dumbest, searcher we have to offer. pub struct RandomBot {} /// Searcher that uses a MiniMax algorithm to search for a best move. pub struct MiniMaxSearcher {} /// Searcher that uses a MiniMax algorithm to search for a best move, but does so in parallel. pub...
struct BoardWrapper<'a> { b: &'a mut Board }
random_line_split
mod.rs
//! Contains all of the currently completed standard bots/searchers/AIs. //! //! These are mostly for example purposes, to see how one can create a chess AI. extern crate rand; pub mod minimax; pub mod parallel_minimax; pub mod alphabeta; pub mod jamboree; pub mod iterative_parallel_mvv_lva; use core::piece_move::*;...
fn best_move(board: Board, depth: u16) -> BitMove { minimax::minimax( &mut board.shallow_clone(), depth).bit_move } } impl Searcher for ParallelMiniMaxSearcher { fn name() -> &'static str { "Parallel Searcher" } fn best_move(board: Board, depth: u16) -> BitMove { parall...
{ "Simple Searcher" }
identifier_body
camera.rs
use cgmath::Ortho; use glium::uniforms::{AsUniformValue, UniformValue}; use transform::Transform; use types::{Scalar, Mat4}; /// Orthogonal 2D Camera. pub struct Camera2D { pub transform: Transform, matrix: Mat4, } impl Camera2D { pub fn new(width: u32, height: u32) -> Camera2D
fn build_matrix(width: u32, height: u32, transform: &Mat4) -> Mat4 { let (w, h) = (width as Scalar, height as Scalar); let ortho = Ortho { left: 0.0, right: w, bottom: 0.0, top: h, near: -1.0, far: 1.0, }; Mat4...
{ let transform = Transform::new(); Camera2D { matrix: Camera2D::build_matrix(width, height, &transform.matrix), transform: transform, } }
identifier_body
camera.rs
use cgmath::Ortho; use glium::uniforms::{AsUniformValue, UniformValue}; use transform::Transform; use types::{Scalar, Mat4}; /// Orthogonal 2D Camera. pub struct Camera2D { pub transform: Transform, matrix: Mat4, } impl Camera2D { pub fn new(width: u32, height: u32) -> Camera2D { let transform =...
}
random_line_split
camera.rs
use cgmath::Ortho; use glium::uniforms::{AsUniformValue, UniformValue}; use transform::Transform; use types::{Scalar, Mat4}; /// Orthogonal 2D Camera. pub struct Camera2D { pub transform: Transform, matrix: Mat4, } impl Camera2D { pub fn
(width: u32, height: u32) -> Camera2D { let transform = Transform::new(); Camera2D { matrix: Camera2D::build_matrix(width, height, &transform.matrix), transform: transform, } } fn build_matrix(width: u32, height: u32, transform: &Mat4) -> Mat4 { let (w, ...
new
identifier_name
touch.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 euclid::point::TypedPoint2D; use euclid::scale_factor::ScaleFactor; use gfx_traits::DevicePixel; use script_tr...
pub fn on_touch_down(&mut self, id: TouchId, point: TypedPoint2D<f32, DevicePixel>) { let point = TouchPoint::new(id, point); self.active_touch_points.push(point); self.state = match self.state { Nothing => WaitingForScript, Touching | Panning => P...
{ TouchHandler { state: Nothing, active_touch_points: Vec::new(), } }
identifier_body
touch.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 euclid::point::TypedPoint2D; use euclid::scale_factor::ScaleFactor; use gfx_traits::DevicePixel; use script_tr...
pub fn on_touch_up(&mut self, id: TouchId, _point: TypedPoint2D<f32, DevicePixel>) -> TouchAction { match self.active_touch_points.iter().position(|t| t.id == id) { Some(i) => { self.active_touch_points.swap_remove(i); } None => { ...
random_line_split
touch.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 euclid::point::TypedPoint2D; use euclid::scale_factor::ScaleFactor; use gfx_traits::DevicePixel; use script_tr...
(&mut self, id: TouchId, point: TypedPoint2D<f32, DevicePixel>) { let point = TouchPoint::new(id, point); self.active_touch_points.push(point); self.state = match self.state { Nothing => WaitingForScript, Touching | Panning => Pinching, Waiti...
on_touch_down
identifier_name
ez_rpc.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
} } _ => {panic!()} }; return client; } } pub struct EzRpcServer { tcp_listener : ::std::net::TcpListener, } impl EzRpcServer { pub fn new<A: ::std::net::ToSocketAddrs>(bind_address : A) -> ::std::io::Result<EzRpcServer> { let tcp_listener...
{ panic!() }
conditional_block
ez_rpc.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
; impl Server for EmptyCap { fn dispatch_call(&mut self, _interface_id : u64, _method_id : u16, context : ::capnp::capability::CallContext<::capnp::any_pointer::Reader, ::capnp::any_pointer::Builder>) { context.fail("Attem...
EmptyCap
identifier_name
ez_rpc.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
} _ => {panic!()} }; return client; } } pub struct EzRpcServer { tcp_listener : ::std::net::TcpListener, } impl EzRpcServer { pub fn new<A: ::std::net::ToSocketAddrs>(bind_address : A) -> ::std::io::Result<EzRpcServer> { let tcp_listener = try!(::std::net:...
payload.get_content().get_as_capability::<T>().unwrap() } _ => { panic!() } }
random_line_split
selectors.js
/** * The global state selectors */ import { createSelector } from 'reselect'; export const selectGlobal = (state) => state.get('global'); export const makeSelectCurrentUser = () => createSelector( selectGlobal, (globalState) => globalState.get('currentUser') ); export const makeSelectLoading = () => createSe...
export const makeSelectRepos = () => createSelector( selectGlobal, (globalState) => globalState.getIn(['userData', 'repositories']) ); export const makeSelectLocationState = () => { let prevRoutingState; let prevRoutingStateJS; return (state) => { const routingState = state.get('route'); // or state.ro...
);
random_line_split
selectors.js
/** * The global state selectors */ import { createSelector } from 'reselect'; export const selectGlobal = (state) => state.get('global'); export const makeSelectCurrentUser = () => createSelector( selectGlobal, (globalState) => globalState.get('currentUser') ); export const makeSelectLoading = () => createSe...
return prevRoutingStateJS; }; }; const getRouter = (state) => state.get('router'); export const makeSelectLocation = () => createSelector( getRouter, (router) => router.get('location'), ); export const makeSelectDrawer = () => createSelector( selectGlobal, (state) => state.get('drawer') ); // export ...
{ prevRoutingState = routingState; prevRoutingStateJS = routingState.toJS(); }
conditional_block
batch-history.component.ts
/* * 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 * distribu...
this.datasourceId = datasourceId; // 히스토리 조회 this.getBatchHistory(datasourceId); } /** * get batch history status * @param {IngestionHistory} history * @returns {string} */ public getStatus(history: IngestionHistory): string { const status = history.status; let result = 'Fail'; ...
random_line_split
batch-history.component.ts
/* * 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 * distribu...
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // Init public ngOnInit() { // Init super.ngOnInit(); this.initView() } // Destory public ngOnDestroy() { // Destory super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-...
super(element, injector); } /*
identifier_body
batch-history.component.ts
/* * 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 * distribu...
< this.pageResult.totalPages - 1); } /** * 리스트 더보기 */ public moreList() { // 페이지 초기화 this.pageResult.number += 1; // 리스트 재조회 this.getBatchHistory(this.datasourceId); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-...
pageResult.number
identifier_name
save-map-form.component.ts
import {Component, OnDestroy} from '@angular/core'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {HsCoreService} from '../core/core.service'; import {HsLayerUtilsService} from '../utils/layer-utils.service'; import {HsSaveMapManagerService} from './save-map-manager.service'; import {...
} }
{ return true; }
conditional_block
save-map-form.component.ts
import {Component, OnDestroy} from '@angular/core'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {HsCoreService} from '../core/core.service'; import {HsLayerUtilsService} from '../utils/layer-utils.service'; import {HsSaveMapManagerService} from './save-map-manager.service'; import {...
(): void { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } setExtraFormTo(form: string): void { if (this.extraFormOpened === form) { this.extraFormOpened = ''; } else { this.extraFormOpened = form; } } saveCompoJson(): void { const compositionJSON = this.H...
ngOnDestroy
identifier_name
save-map-form.component.ts
import {Component, OnDestroy} from '@angular/core'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {HsCoreService} from '../core/core.service'; import {HsLayerUtilsService} from '../utils/layer-utils.service'; import {HsSaveMapManagerService} from './save-map-manager.service'; import {...
); } //*NOTE not being used capitalizeFirstLetter(string: string): string { return this.HsUtilsService.capitalizeFirstLetter(string); } titleChanged(): void { this.overwrite = false; this.HsSaveMapManagerService.missingTitle = false; this.HsSaveMapManagerService.missingName = false; } ...
selectDeselectAllLayers(): void { this.btnSelectDeselectClicked = !this.btnSelectDeselectClicked; this.HsSaveMapManagerService.compoData.layers.forEach( (layer) => (layer.checked = this.btnSelectDeselectClicked)
random_line_split
save-map-form.component.ts
import {Component, OnDestroy} from '@angular/core'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {HsCoreService} from '../core/core.service'; import {HsLayerUtilsService} from '../utils/layer-utils.service'; import {HsSaveMapManagerService} from './save-map-manager.service'; import {...
selectDeselectAllLayers(): void { this.btnSelectDeselectClicked = !this.btnSelectDeselectClicked; this.HsSaveMapManagerService.compoData.layers.forEach( (layer) => (layer.checked = this.btnSelectDeselectClicked) ); } //*NOTE not being used capitalizeFirstLetter(string: string): string { ...
{ const compositionJSON = this.HsSaveMapManagerService.generateCompositionJson(); const file = new Blob([JSON.stringify(compositionJSON)], { type: 'application/json', }); const a = <HTMLAnchorElement>document.getElementById('stc-download'), url = URL.createObjectURL(file); a.href ...
identifier_body
lib.rs
//! Functionality for working with SIMD registers and instructions. //! //! [Source](https://github.com/huonw/simd), [crates.io](https://crates.io/crates/simd) #![feature(trace_macros, link_llvm_intrinsics, simd_ffi, core)] extern crate simdty; extern crate llvmint; use std::mem; pub use convert::bitcast...
<T: maths::sqrt::Sqrt>(x: T) -> T { x.sqrt() } /// Return a platform-specific approximation to the reciprocal-square /// root of `x`. #[inline] pub fn rsqrt<T: maths::sqrt::RSqrt>(x: T) -> T { x.rsqrt() }
sqrt
identifier_name
lib.rs
//! Functionality for working with SIMD registers and instructions. //! //! [Source](https://github.com/huonw/simd), [crates.io](https://crates.io/crates/simd) #![feature(trace_macros, link_llvm_intrinsics, simd_ffi, core)] extern crate simdty; extern crate llvmint; use std::mem; pub use convert::bitcast...
let vsize = mem::size_of::<Self>(); let esize = mem::size_of::<Self::Item>(); assert!(vsize % esize == 0); vsize / esize } } /// SIMD vectors which can be separated into two SIMD vectors of half /// the size with the same elements. pub unsafe trait HalfVector: Vector { type Hal...
/// Return the number of items in `self`. #[inline(always)] fn count(_: Option<Self>) -> usize {
random_line_split
lib.rs
//! Functionality for working with SIMD registers and instructions. //! //! [Source](https://github.com/huonw/simd), [crates.io](https://crates.io/crates/simd) #![feature(trace_macros, link_llvm_intrinsics, simd_ffi, core)] extern crate simdty; extern crate llvmint; use std::mem; pub use convert::bitcast...
} /// SIMD vectors which can be merged with another of the same type to /// create one of double the length with the same elements. pub unsafe trait DoubleVector: Vector { type Double /*: Vector<Item = Self::Item>*/; /// Concatenate the elements of `self` and `other` into a single /// SIMD vector. fn ...
{ self.split().1 }
identifier_body
vlaCal-v2.1.js
var calFocus = false; var _class = this; (this.openWith ? $(this.openWith) : this.element) .addEvent('focus', function() { _class.show(); }) .addEvent('click', function() { _class.openWith ? _class.toggle() : _class.show() }) .addEvent('change', function() { _class.hide(); }); //If the datep...
if(_element.offsetParent) { do {
random_line_split
johab.py
# # johab.py: Python Unicode Codec for JOHAB # # Written by Hye-Shik Chang <perky@FreeBSD.org> # import _codecs_kr, codecs import _multibytecodec as mbc codec = _codecs_kr.getcodec('johab') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrement...
class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): codec = codec class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): codec = codec class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): codec = codec ...
codec = codec
identifier_body
johab.py
# # johab.py: Python Unicode Codec for JOHAB # # Written by Hye-Shik Chang <perky@FreeBSD.org> # import _codecs_kr, codecs import _multibytecodec as mbc codec = _codecs_kr.getcodec('johab') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrement...
codecs.IncrementalDecoder): codec = codec class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): codec = codec class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): codec = codec def getregentry(): return codecs.CodecInfo( name...
class IncrementalDecoder(mbc.MultibyteIncrementalDecoder,
random_line_split
johab.py
# # johab.py: Python Unicode Codec for JOHAB # # Written by Hye-Shik Chang <perky@FreeBSD.org> # import _codecs_kr, codecs import _multibytecodec as mbc codec = _codecs_kr.getcodec('johab') class
(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): codec = codec class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): codec ...
Codec
identifier_name
config.py
# Copyright 2016 Sotera Defense Solutions Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
: config_file = "" table_name = "" table_schema_id = "" table_schema_dt = "" table_schema_lat = "" table_schema_lon = "" time_filter = 0 distance_filter = 0 tripLat1 = 0 tripLon1 = 0 tripLat2 = 0 tripLon2 = 0 tripname = "" resolutionLat = 0 resolutionLon ...
AggregateMicroPathConfig
identifier_name
config.py
# Copyright 2016 Sotera Defense Solutions Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
self.table_schema_lon = configParser.get("AggregateMicroPath", "table_schema_lon") self.time_filter = long(configParser.get("AggregateMicroPath", "time_filter")) self.distance_filter = long(configParser.get("AggregateMicroPath", "distance_filter")) self.tripLat1 = float(configParser.ge...
random_line_split
config.py
# Copyright 2016 Sotera Defense Solutions Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
self.tripLonMin = int(math.floor(self.tripLon1/self.resolutionLon)) #8 self.tripLonMax = int(math.ceil(self.tripLon2/self.resolutionLon)) #9 self.triplineBlankets.append([self.tripLat1,self.tripLon1,self.tripLat2,self.tripLon2,self.tripname,self.resolutionLat,self.resolutionLon,self.tripLatMin,s...
configParser = SafeConfigParser() configParser.read(basePath + config) self.config_file = config self.database_name = configParser.get("AggregateMicroPath", "database_name") self.table_name = configParser.get("AggregateMicroPath", "table_name") self.table_schema_id = configPars...
identifier_body
to_bits.rs
use malachite_base::num::logic::traits::{BitAccess, SignificantBits}; use malachite_nz::integer::Integer; pub fn to_bits_asc_naive(n: &Integer) -> Vec<bool> { let mut bits = Vec::new(); if *n == 0 { return bits; } for i in 0..n.significant_bits() { bits.push(n.get_bit(i)); } let...
{ let mut bits = Vec::new(); if *n == 0 { return bits; } let significant_bits = n.significant_bits(); let last_bit = n.get_bit(significant_bits - 1); if last_bit != (*n < 0) { bits.push(!last_bit); } for i in (0..significant_bits).rev() { bits.push(n.get_bit(i)); ...
identifier_body
to_bits.rs
use malachite_base::num::logic::traits::{BitAccess, SignificantBits}; use malachite_nz::integer::Integer; pub fn to_bits_asc_naive(n: &Integer) -> Vec<bool> { let mut bits = Vec::new(); if *n == 0 { return bits; } for i in 0..n.significant_bits() { bits.push(n.get_bit(i)); } let...
bits } pub fn to_bits_desc_naive(n: &Integer) -> Vec<bool> { let mut bits = Vec::new(); if *n == 0 { return bits; } let significant_bits = n.significant_bits(); let last_bit = n.get_bit(significant_bits - 1); if last_bit != (*n < 0) { bits.push(!last_bit); } for i i...
{ bits.push(!last_bit); }
conditional_block
to_bits.rs
use malachite_base::num::logic::traits::{BitAccess, SignificantBits}; use malachite_nz::integer::Integer; pub fn to_bits_asc_naive(n: &Integer) -> Vec<bool> { let mut bits = Vec::new(); if *n == 0 { return bits; } for i in 0..n.significant_bits() { bits.push(n.get_bit(i)); } let...
(n: &Integer) -> Vec<bool> { let mut bits = Vec::new(); if *n == 0 { return bits; } let significant_bits = n.significant_bits(); let last_bit = n.get_bit(significant_bits - 1); if last_bit != (*n < 0) { bits.push(!last_bit); } for i in (0..significant_bits).rev() { ...
to_bits_desc_naive
identifier_name
to_bits.rs
use malachite_base::num::logic::traits::{BitAccess, SignificantBits}; use malachite_nz::integer::Integer; pub fn to_bits_asc_naive(n: &Integer) -> Vec<bool> { let mut bits = Vec::new(); if *n == 0 { return bits; } for i in 0..n.significant_bits() { bits.push(n.get_bit(i)); } let...
pub fn to_bits_desc_naive(n: &Integer) -> Vec<bool> { let mut bits = Vec::new(); if *n == 0 { return bits; } let significant_bits = n.significant_bits(); let last_bit = n.get_bit(significant_bits - 1); if last_bit != (*n < 0) { bits.push(!last_bit); } for i in (0..signifi...
random_line_split
main.rs
//! Requires the 'framework' feature flag be enabled in your project's //! `Cargo.toml`. //! //! This can be enabled by specifying the feature in the dependency section: //! //! ```toml //! [dependencies.serenity] //! git = "https://github.com/serenity-rs/serenity.git" //! features = ["framework", "standard_framework"]...
} #[group] #[commands(multiply, ping, quit)] struct General; #[tokio::main] async fn main() { // This will load the environment variables located at `./.env`, relative to // the CWD. See `./.env.example` for an example on how to structure this. dotenv::dotenv().expect("Failed to load .env file"); //...
{ info!("Resumed"); }
identifier_body
main.rs
//! Requires the 'framework' feature flag be enabled in your project's //! `Cargo.toml`. //! //! This can be enabled by specifying the feature in the dependency section: //! //! ```toml //! [dependencies.serenity] //! git = "https://github.com/serenity-rs/serenity.git" //! features = ["framework", "standard_framework"]...
(&self, _: Context, ready: Ready) { info!("Connected as {}", ready.user.name); } async fn resume(&self, _: Context, _: ResumedEvent) { info!("Resumed"); } } #[group] #[commands(multiply, ping, quit)] struct General; #[tokio::main] async fn main() { // This will load the environment va...
ready
identifier_name
main.rs
//! Requires the 'framework' feature flag be enabled in your project's //! `Cargo.toml`. //! //! This can be enabled by specifying the feature in the dependency section: //! //! ```toml //! [dependencies.serenity] //! git = "https://github.com/serenity-rs/serenity.git"
use commands::{math::*, meta::*, owner::*}; use serenity::{ async_trait, client::bridge::gateway::ShardManager, framework::{standard::macros::group, StandardFramework}, http::Http, model::{event::ResumedEvent, gateway::Ready}, prelude::*, }; use tracing::{error, info}; use tracing_subscriber::{...
//! features = ["framework", "standard_framework"] //! ``` mod commands; use std::{collections::HashSet, env, sync::Arc};
random_line_split
syslogparser.py
#!/usr/bin/env python """ This is a collection of classes that contain data for files from a sosreport in the directory:
@copyright : GPLv2 """ class VarLogMessagesMsg: def __init__(self, orginalMessage, timestamp, hostname, messageSender, pid, message): self.__orginalMessage = orginalMessage self.__timestamp = timestamp self.__hostname = hostname self.__messageSender = messageSender self.__pid = pid self.__me...
var/log/* @author : Shane Bradley @contact : sbradley@redhat.com @version : 2.16
random_line_split
syslogparser.py
#!/usr/bin/env python """ This is a collection of classes that contain data for files from a sosreport in the directory: var/log/* @author : Shane Bradley @contact : sbradley@redhat.com @version : 2.16 @copyright : GPLv2 """ class VarLogMessagesMsg: def __init__(self, orginalMessage, timestamp, hostname,...
def getOriginalMessage(self): return self.__orginalMessage def getTimestamp(self): return self.__timestamp def getHostname(self): return self.__hostname def getMessageSender(self): return self.__messageSender def getPid(self): return self.__pid def getMessage(self): return sel...
return self.getOriginalMessage()
identifier_body
syslogparser.py
#!/usr/bin/env python """ This is a collection of classes that contain data for files from a sosreport in the directory: var/log/* @author : Shane Bradley @contact : sbradley@redhat.com @version : 2.16 @copyright : GPLv2 """ class
: def __init__(self, orginalMessage, timestamp, hostname, messageSender, pid, message): self.__orginalMessage = orginalMessage self.__timestamp = timestamp self.__hostname = hostname self.__messageSender = messageSender self.__pid = pid self.__message = message def __str__(self): #retur...
VarLogMessagesMsg
identifier_name
strings.js
define( ({ showArcgisBasemaps: "Medtag Portal-baggrundskort", settings: "Indstillinger", add: "Klik for at tilføje et nyt baggrundskort", edit: "Egenskaber", title: "Titel", titlePH: "Baggrundskortets titel", thumbnail: "Miniature", thumbnailHint: "Klik på billedet for at opdatere", ...
);
invalidTitle2:"' findes i forvejen. Vælg en anden titel.", invalidBasemapUrl1: "Denne type lag kan ikke bruges som baggrundskort.", invalidBasemapUrl2: "Det baggrundskort, du er ved at tilføje, har en anden spatial reference end det aktuelle kort.", addBaselayer: "Tilføj baggrundskortlag" })
random_line_split
DeferredList.js
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.DeferredList"]){ //_hasResource checks added by build. Do not use _hasResource directly in your...
return ret; }); return d; }; }
var ret = []; dojo.forEach(results, function(result){ ret.push(result[1]); });
random_line_split
DeferredList.js
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.DeferredList"]){ //_hasResource checks added by build. Do not use _hasResource directly in your...
(succeeded, result){ resultList[i] = [succeeded, result]; finished++; if(finished === list.length){ self.resolve(resultList); } } }); }; dojo.DeferredList.prototype = new dojo.Deferred(); dojo.DeferredList.prototype.gatherResults= function(deferredList){ // summary: // Gathers the results of t...
addResult
identifier_name
DeferredList.js
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.DeferredList"]){ //_hasResource checks added by build. Do not use _hasResource directly in your...
}); }; dojo.DeferredList.prototype = new dojo.Deferred(); dojo.DeferredList.prototype.gatherResults= function(deferredList){ // summary: // Gathers the results of the deferreds for packaging // as the parameters to the Deferred Lists' callback var d = new dojo.DeferredList(deferredList, false, true, false); d....
{ resultList[i] = [succeeded, result]; finished++; if(finished === list.length){ self.resolve(resultList); } }
identifier_body
DeferredList.js
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.DeferredList"]){ //_hasResource checks added by build. Do not use _hasResource directly in your...
var finished = 0; dojo.forEach(list, function(item, i){ item.then(function(result){ if(fireOnOneCallback){ self.resolve([i, result]); }else{ addResult(true, result); } },function(error){ if(fireOnOneErrback){ self.reject(error); }else{ addResult(false, error); } if(consumeErr...
{ this.resolve([0, []]); }
conditional_block
06-tddft_gradients.py
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' TDDFT analytical nuclear gradients. ''' from pyscf import gto, scf, dft, tddft mol = gto.M( atom = [ ['O' , 0. , 0. , 0], ['H' , 0. , -0.757 , 0.587], ['H' , 0. , 0.757 , 0.587]], basis = 'ccpvdz') mf = sc...
g.kernel(state=1) mf = dft.RKS(mol).x2c().set(xc='pbe0').run() # Switch to xcfun because 3rd order GGA functional derivative is not # available in libxc mf._numint.libxc = dft.xcfun postmf = tddft.TDDFT(mf).run() # PySCF-1.6.1 and newer supports the .Gradients method to create a grad # object after grad module was imp...
random_line_split
Membership.ts
import { Model } from "objection"; import Artist from "./Artist"; import ArtistCredit from "./ArtistCredit"; class
extends Model { public static tableName = "memberships"; public static relationMappings = { artistCredit: { join: { from: "memberships.artist_credit_id", to: "artist_credits.id", }, modelClass: `${__dirname}/ArtistCredit`, ...
Membership
identifier_name
Membership.ts
import { Model } from "objection"; import Artist from "./Artist"; import ArtistCredit from "./ArtistCredit"; class Membership extends Model { public static tableName = "memberships"; public static relationMappings = { artistCredit: { join: { from: "memberships.artist_credi...
public ended_on_year?: number; public ended_on_month?: number; public ended_on_day?: number; // tslint:enable:variable-name public group?: Artist; public artistCredit?: ArtistCredit; } export default Membership;
public started_on_year?: number; public started_on_month?: number; public started_on_day?: number;
random_line_split
main.py
import werkzeug from openerp import http, SUPERUSER_ID from openerp.http import request class MassMailController(http.Controller): @http.route('/mail/track/<int:mail_id>/blank.gif', type='http', auth='none') def
(self, mail_id, **post): """ Email tracking. """ mail_mail_stats = request.registry.get('mail.mail.statistics') mail_mail_stats.set_opened(request.cr, SUPERUSER_ID, mail_mail_ids=[mail_id]) response = werkzeug.wrappers.Response() response.mimetype = 'image/gif' response.d...
track_mail_open
identifier_name
main.py
import werkzeug from openerp import http, SUPERUSER_ID from openerp.http import request class MassMailController(http.Controller): @http.route('/mail/track/<int:mail_id>/blank.gif', type='http', auth='none') def track_mail_open(self, mail_id, **post): """ Email tracking. """ mail_mail_stats ...
email_fname = 'email' if email_fname: record_ids = request.registry[mailing.mailing_model].search(cr, SUPERUSER_ID, [('id', '=', res_id), (email_fname, 'ilike', email)], context=context) if 'opt_out' in request.registry[mailing.mailing_model]._all_columns: ...
random_line_split
main.py
import werkzeug from openerp import http, SUPERUSER_ID from openerp.http import request class MassMailController(http.Controller): @http.route('/mail/track/<int:mail_id>/blank.gif', type='http', auth='none') def track_mail_open(self, mail_id, **post):
@http.route(['/mail/mailing/<int:mailing_id>/unsubscribe'], type='http', auth='none') def mailing(self, mailing_id, email=None, res_id=None, **post): cr, uid, context = request.cr, request.uid, request.context MassMailing = request.registry['mail.mass_mailing'] mailing_ids = MassMailin...
""" Email tracking. """ mail_mail_stats = request.registry.get('mail.mail.statistics') mail_mail_stats.set_opened(request.cr, SUPERUSER_ID, mail_mail_ids=[mail_id]) response = werkzeug.wrappers.Response() response.mimetype = 'image/gif' response.data = 'R0lGODlhAQABAIAAANvf7wAAAC...
identifier_body
main.py
import werkzeug from openerp import http, SUPERUSER_ID from openerp.http import request class MassMailController(http.Controller): @http.route('/mail/track/<int:mail_id>/blank.gif', type='http', auth='none') def track_mail_open(self, mail_id, **post): """ Email tracking. """ mail_mail_stats...
if email_fname: record_ids = request.registry[mailing.mailing_model].search(cr, SUPERUSER_ID, [('id', '=', res_id), (email_fname, 'ilike', email)], context=context) if 'opt_out' in request.registry[mailing.mailing_model]._all_columns: request.registry[mailing.mai...
email_fname = 'email'
conditional_block
0017_auto_20181109_1828.py
# Generated by Django 2.1.3 on 2018-11-09 18:28 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('proposals', '0016_auto_20180405_2116'), ] operations = [ migrations.AlterField( model_name='timeallocation', name='instrument_name', field=models.CharField(choices=[('0M4-SCICAM-SBIG', '0M4-SCICAM-SBIG'), ('0M8-NRES-SCICAM', '0M8-NRES-SCICA...
identifier_body
0017_auto_20181109_1828.py
# Generated by Django 2.1.3 on 2018-11-09 18:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proposals', '0016_auto_20180405_2116'), ] operations = [ migrations.AlterField(
model_name='timeallocation', name='instrument_name', field=models.CharField(choices=[('0M4-SCICAM-SBIG', '0M4-SCICAM-SBIG'), ('0M8-NRES-SCICAM', '0M8-NRES-SCICAM'), ('0M8-SCICAM-SBIG', '0M8-SCICAM-SBIG'), ('1M0-NRES-SCICAM', '1M0-NRES-SCICAM'), ('1M0-SCICAM-SINISTRO', '1M0-SCICAM-SIN...
random_line_split
0017_auto_20181109_1828.py
# Generated by Django 2.1.3 on 2018-11-09 18:28 from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('proposals', '0016_auto_20180405_2116'), ] operations = [ migrations.AlterField( model_name='timeallocation', name='instrument_name', field=models.CharField(choices=[('0M4-SCICAM-SBIG', '0M4-SCICAM-SBIG'), ('0M8-...
Migration
identifier_name
arrays.js
/* * Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog, * Circulation and User's Management. It's written in Perl, and uses Apache2 * Web-Server, MySQL database and Sphinx 2 indexing. * Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP * * This file is part of Meran. * ...
(a, compFn){ var i; if (compFn) { a.sort(compFn); for (i = 1; i < a.length; i++) { if (0 === compFn(a[i], a[i - 1])) { a.splice(i--, 1); } } } else { a.sort(); for (i = 1; i < a.length; i++) { // Use loosely typed comparsion if no compFn is given // to avoid sortUnique( [6, "6"...
sortUnique
identifier_name
arrays.js
/* * Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog, * Circulation and User's Management. It's written in Perl, and uses Apache2 * Web-Server, MySQL database and Sphinx 2 indexing. * Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP * * This file is part of Meran. * ...
} /** * Shallow comparison of two arrays. * * @param a, b * The arrays to compare. * @param equalFn * A custom comparison function that accepts two values a and * b from the given arrays and returns true or false for * equal and not equal respectively. * * If n...
{ var i; if (compFn) { a.sort(compFn); for (i = 1; i < a.length; i++) { if (0 === compFn(a[i], a[i - 1])) { a.splice(i--, 1); } } } else { a.sort(); for (i = 1; i < a.length; i++) { // Use loosely typed comparsion if no compFn is given // to avoid sortUnique( [6, "6", 6] ) => [...
identifier_body
arrays.js
/* * Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog, * Circulation and User's Management. It's written in Perl, and uses Apache2 * Web-Server, MySQL database and Sphinx 2 indexing. * Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP * * This file is part of Meran. * ...
else { a.sort(); for (i = 1; i < a.length; i++) { // Use loosely typed comparsion if no compFn is given // to avoid sortUnique( [6, "6", 6] ) => [6, "6", 6] if (a[i] == a[i - 1]) { a.splice(i--, 1); } } } return a; } /** * Shallow comparison of two arrays. * * @param a, b *...
{ a.sort(compFn); for (i = 1; i < a.length; i++) { if (0 === compFn(a[i], a[i - 1])) { a.splice(i--, 1); } } }
conditional_block
arrays.js
/* * Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog, * Circulation and User's Management. It's written in Perl, and uses Apache2 * Web-Server, MySQL database and Sphinx 2 indexing. * Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP * * This file is part of Meran. * ...
sortUnique: sortUnique, equal: equal, map: Array.prototype.map ? mapNative : map }; });
return a.map(fn); } return {
random_line_split
utils.py
# -*- coding: utf-8 -*- import os import httplib import logging import functools from modularodm.exceptions import ValidationValueError from framework.exceptions import HTTPError from framework.analytics import update_counter from website.addons.osfstorage import settings logger = logging.getLogger(__name__) LOCA...
return { 'user': user, 'index': index + 1, 'date': version.date_created.isoformat(), 'downloads': record.get_download_count(version=index), 'md5': version.metadata.get('md5'), 'sha256': version.metadata.get('sha256'), } SIGNED_REQUEST_ERROR = HTTPError( http...
'name': version.creator.fullname, 'url': version.creator.url, }
random_line_split
utils.py
# -*- coding: utf-8 -*- import os import httplib import logging import functools from modularodm.exceptions import ValidationValueError from framework.exceptions import HTTPError from framework.analytics import update_counter from website.addons.osfstorage import settings logger = logging.getLogger(__name__) LOCA...
return cloned
copy_files(child, target_settings, parent=cloned)
conditional_block
utils.py
# -*- coding: utf-8 -*- import os import httplib import logging import functools from modularodm.exceptions import ValidationValueError from framework.exceptions import HTTPError from framework.analytics import update_counter from website.addons.osfstorage import settings logger = logging.getLogger(__name__) LOCA...
(_type): """A small decorator factory for OsfStorageFileNode. Acts as a poor mans polymorphic inheritance, ensures that the given instance is of "kind" folder or file """ def _must_be(func): @functools.wraps(func) def wrapped(self, *args, **kwargs): if not self.kind == _type:...
must_be
identifier_name
utils.py
# -*- coding: utf-8 -*- import os import httplib import logging import functools from modularodm.exceptions import ValidationValueError from framework.exceptions import HTTPError from framework.analytics import update_counter from website.addons.osfstorage import settings logger = logging.getLogger(__name__) LOCA...
'downloads': record.get_download_count(version=index), 'md5': version.metadata.get('md5'), 'sha256': version.metadata.get('sha256'), } SIGNED_REQUEST_ERROR = HTTPError( httplib.SERVICE_UNAVAILABLE, data={ 'message_short': 'Upload service unavailable', 'message_long...
"""Serialize revision for use in revisions table. :param Node node: Root node :param FileRecord record: Root file record :param FileVersion version: The version to serialize :param int index: One-based index of version """ if anon: user = None else: user = { 'na...
identifier_body
drop-trait-enum.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}; assert_eq!(receiver.recv().unwrap(), Message::DestructorRan); assert_eq!(receiver.recv().unwrap(), Message::Dropped); assert_eq!(receiver.recv().unwrap(), Message::DestructorRan); assert_eq!(receiver.recv().unwrap(), Message::Dropped); assert_eq!(receiver.recv().unwrap(), Message::DestructorR...
SendOnDrop { sender: sender.clone() }, sender.clone()); v = Foo::SimpleVariant(sender.clone()); v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } }; })
random_line_split
drop-trait-enum.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { let (sender, receiver) = channel(); { let v = Foo::SimpleVariant(sender); } assert_eq!(receiver.recv().unwrap(), Message::DestructorRan); assert_eq!(receiver.recv().ok(), None); let (sender, receiver) = channel(); { let v = Foo::NestedVariant(box 42, Send...
{ match self { &mut Foo::SimpleVariant(ref mut sender) => { sender.send(Message::DestructorRan).unwrap(); } &mut Foo::NestedVariant(_, _, ref mut sender) => { sender.send(Message::DestructorRan).unwrap(); } &mut Foo::Fai...
identifier_body
drop-trait-enum.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ sender: Sender<Message> } impl Drop for SendOnDrop { fn drop(&mut self) { self.sender.send(Message::Dropped).unwrap(); } } enum Foo { SimpleVariant(Sender<Message>), NestedVariant(Box<usize>, SendOnDrop, Sender<Message>), FailingVariant { on_drop: SendOnDrop } } impl Drop for Foo {...
SendOnDrop
identifier_name
assert-eq-macro-success.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 ...
{ x : int } pub fn main() { assert_eq!(14,14); assert_eq!("abc".to_string(),"abc".to_string()); assert_eq!(box Point{x:34},box Point{x:34}); assert_eq!(&Point{x:34},&Point{x:34}); assert_eq!(@Point{x:34},@Point{x:34}); }
Point
identifier_name
assert-eq-macro-success.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 main() { assert_eq!(14,14); assert_eq!("abc".to_string(),"abc".to_string()); assert_eq!(box Point{x:34},box Point{x:34}); assert_eq!(&Point{x:34},&Point{x:34}); assert_eq!(@Point{x:34},@Point{x:34}); }
#[deriving(PartialEq, Show)] struct Point { x : int }
random_line_split
wordProbability.py
# -*- coding:utf8 -*- from __future__ import division import codecs import re def calWordProbability(infile, outfile):
val = wArr[1] # 目标语言词 if key in wordDic: wordDic[key][val] = 1 else: valMap = dict() valMap[val] = 1 wordDic[key] = valMap line = fin.readline() with codecs.open(outfile, 'w', ...
''' 计算词概率,源语言词翻译成目标语言词的概率 一个源语言可能对应多个目标语言,这里计算平均值 infile: 输入文件 格式:source word \t target word outfile: source word \t target word \t probability ''' with codecs.open(infile, 'r', 'utf8') as fin: # 用于存储数据结构 wordDic = {} line = fin.readline() linNum = 1 whi...
identifier_body
wordProbability.py
# -*- coding:utf8 -*- from __future__ import division import codecs import re def calWordProbability(infile, outfile): ''' 计算词概率,源语言词翻译成目标语言词的概率 一个源语言可能对应多个目标语言,这里计算平均值 infile: 输入文件 格式:source word \t target word outfile: source word \t target word \t probability ''' with codecs.open(infil...
in wordDic.keys(): wCount += 1 if(wCount % 1001 == 0): print('writing', wCount) if len(key.split(' ')) > 1: continue valMap = wordDic[key] valLen = len(valMap) for val in valMap.keys(): fout.write(ke...
utfile, 'w', 'utf8') as fout: print('start write') wCount = 0 for key
conditional_block
wordProbability.py
# -*- coding:utf8 -*- from __future__ import division import codecs import re def
(infile, outfile): ''' 计算词概率,源语言词翻译成目标语言词的概率 一个源语言可能对应多个目标语言,这里计算平均值 infile: 输入文件 格式:source word \t target word outfile: source word \t target word \t probability ''' with codecs.open(infile, 'r', 'utf8') as fin: # 用于存储数据结构 wordDic = {} line = fin.readline() ...
calWordProbability
identifier_name
wordProbability.py
# -*- coding:utf8 -*- from __future__ import division import codecs import re def calWordProbability(infile, outfile): ''' 计算词概率,源语言词翻译成目标语言词的概率 一个源语言可能对应多个目标语言,这里计算平均值 infile: 输入文件 格式:source word \t target word outfile: source word \t target word \t probability ''' with codecs.open(infil...
fout.write('\t') fout.write(val) fout.write('\t') fout.write(str(1/valLen)) fout.write('\n')
fout.write(key)
random_line_split
two_layer_neural_network.py
import sys import numpy as np # sigmoid function def nonlin(x, deriv=False): if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x)) # input dataset X = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]])
np.random.seed(1) # initialize weights randomly with mean 0 syn0 = 2*np.random.random((3,1)) - 1 for iter in xrange(10000): # forward propagation l0 = X l1 = nonlin(np.dot(l0,syn0)) # how much did we miss? l1_error = y - l1 # multiply how much we missed by the # slope of the sigmoid at...
# output dataset y = np.array([[0,0,1,1]]).T # seed random numbers to make calculation # deterministic (just a good practice)
random_line_split
two_layer_neural_network.py
import sys import numpy as np # sigmoid function def nonlin(x, deriv=False):
# input dataset X = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) # output dataset y = np.array([[0,0,1,1]]).T # seed random numbers to make calculation # deterministic (just a good practice) np.random.seed(1) # initialize weights randomly with mean 0 syn0 = 2...
if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x))
identifier_body
two_layer_neural_network.py
import sys import numpy as np # sigmoid function def nonlin(x, deriv=False): if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x)) # input dataset X = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) # output dataset y = np.array([[0,0,1,1]]).T #...
print "Output After Training:" print l1
l0 = X l1 = nonlin(np.dot(l0,syn0)) # how much did we miss? l1_error = y - l1 # multiply how much we missed by the # slope of the sigmoid at the values in l1 l1_delta = l1_error * nonlin(l1,True) # update weights syn0 += np.dot(l0.T,l1_delta)
conditional_block
two_layer_neural_network.py
import sys import numpy as np # sigmoid function def
(x, deriv=False): if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x)) # input dataset X = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) # output dataset y = np.array([[0,0,1,1]]).T # seed random numbers to make calculation # deterministic (ju...
nonlin
identifier_name
AudioObject.js
/** * @author alteredq / http://alteredqualia.com/ * * AudioObject * * - 3d spatialized sound with Doppler-shift effect * * - uses Audio API (currently supported in WebKit-based browsers) * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html * * - based on Doppler effect demo from Chromium ...
( url ) { // Load asynchronously var request = new XMLHttpRequest(); request.open( "GET", url, true ); request.responseType = "arraybuffer"; request.onload = function() { _this.source.buffer = _this.context.createBuffer( request.response, true ); _this.source.noteOn( 0 ); } request.send(); }...
loadBufferAndPlay
identifier_name
AudioObject.js
/** * @author alteredq / http://alteredqualia.com/ * * AudioObject * * - 3d spatialized sound with Doppler-shift effect * * - uses Audio API (currently supported in WebKit-based browsers) * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html * * - based on Doppler effect demo from Chromium ...
}; THREE.AudioObject.prototype = Object.create( THREE.Object3D.prototype ); THREE.AudioObject.prototype.constructor = THREE.AudioObject; THREE.AudioObject.prototype.context = null; THREE.AudioObject.prototype.type = null;
{ // Load asynchronously var request = new XMLHttpRequest(); request.open( "GET", url, true ); request.responseType = "arraybuffer"; request.onload = function() { _this.source.buffer = _this.context.createBuffer( request.response, true ); _this.source.noteOn( 0 ); } request.send(); }
identifier_body
AudioObject.js
/** * @author alteredq / http://alteredqualia.com/ * * AudioObject * * - 3d spatialized sound with Doppler-shift effect * * - uses Audio API (currently supported in WebKit-based browsers) * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html * * - based on Doppler effect demo from Chromium ...
this.directionalSource = false; this.listener = this.context.listener; this.panner = this.context.createPanner(); this.source = this.context.createBufferSource(); this.masterGainNode = this.context.createGainNode(); this.dryGainNode = this.context.createGainNode(); // Setup initial gains this.masterGainNod...
return this; } }
random_line_split
upgrade_downgrade.js
(function (angular) { "use strict"; angular.module("mfl.facility_mgmt.states.upgrade_downgrade", [ "ui.router" ])
.config(["$stateProvider", function ($stateProvider) { $stateProvider .state("facilities.upgrade", { url: "upgrade/:facility_id/", views: { "main-content@facility_mgmt": { templateUrl: "facility_mgmt/tpls/facility_up_down_grade.tpl.html", ...
random_line_split
ping_pong_paddle.js
function PingPongPaddle(x, y, z, radius) { this.x = x; this.y = y; this.z = z; this.radius = radius; } PingPongPaddle.prototype = { rotation: new THREE.Vector3(0, 0, 0), init: function(scene) { var tableImage = THREE.ImageUtils.loadTexture('images/paddle_texture.jpg'); //var geo...
else if (this.paddle.position.y < -20) { direction = 1; } this.paddle.position.y += direction * .1; }, hitPaddle: function(x, y, z, radius) { if (Math.abs(this.paddle.position.x - x) < radius) { return isBetween(y, this.paddle.position.y + this.radius / 2, this.p...
{ direction = -1; }
conditional_block
ping_pong_paddle.js
function
(x, y, z, radius) { this.x = x; this.y = y; this.z = z; this.radius = radius; } PingPongPaddle.prototype = { rotation: new THREE.Vector3(0, 0, 0), init: function(scene) { var tableImage = THREE.ImageUtils.loadTexture('images/paddle_texture.jpg'); //var geometry = new THREE.CubeG...
PingPongPaddle
identifier_name
ping_pong_paddle.js
function PingPongPaddle(x, y, z, radius) { this.x = x; this.y = y; this.z = z; this.radius = radius; } PingPongPaddle.prototype = {
var tableImage = THREE.ImageUtils.loadTexture('images/paddle_texture.jpg'); //var geometry = new THREE.CubeGeometry(this.radius, this.radius, .1); var geometry = new THREE.CylinderGeometry(this.radius, this.radius, .1, 16, 1); this.paddle = new THREE.Mesh(geometry, new THREE.MeshBasicMat...
rotation: new THREE.Vector3(0, 0, 0), init: function(scene) {
random_line_split
ping_pong_paddle.js
function PingPongPaddle(x, y, z, radius) { this.x = x; this.y = y; this.z = z; this.radius = radius; } PingPongPaddle.prototype = { rotation: new THREE.Vector3(0, 0, 0), init: function(scene) { var tableImage = THREE.ImageUtils.loadTexture('images/paddle_texture.jpg'); //var geo...
{ return (x <= x1 && x >= x2) || (x >= x1 && x <= x2); }
identifier_body
webpack.config.js
/* * Webpack development server configuration * * This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if * the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload. */ 'use strict'; import webpack from 'webpack'; impor...
postcss: [ autoprefixer({ browsers: 'last 2 versions' }) ], plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin({ __DEV__: true, __DEVTOOLS__: false, __API_URL__: `\'${API_URL}\'` }) ] };
random_line_split
test_disk_usage.py
#!/usr/bin/python # -*- coding: utf-8; -*- # # 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 # # Unles...
(): sensor = disk_usage.DiskUsage() ok_([] != sensor.measure()) def test_disk_usage_sensor_produces_core_metrics(): sensor = disk_usage.DiskUsage() events = [e.name() for e in sensor.measure()] ok_(reduce(lambda acc, e: acc or e.endswith(".total"), events, False)) ok_(reduce(lambda acc, e: acc ...
test_disk_usage_sensor_is_stateless
identifier_name
test_disk_usage.py
#!/usr/bin/python # -*- coding: utf-8; -*- # # 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 # # Unles...
from leela.client.sensors.linux import disk_usage def test_disk_usage_sensor_is_stateless(): sensor = disk_usage.DiskUsage() ok_([] != sensor.measure()) def test_disk_usage_sensor_produces_core_metrics(): sensor = disk_usage.DiskUsage() events = [e.name() for e in sensor.measure()] ok_(reduce(lamb...
# See the License for the specific language governing permissions and # limitations under the License. from nose.tools import *
random_line_split
test_disk_usage.py
#!/usr/bin/python # -*- coding: utf-8; -*- # # 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 # # Unles...
sensor = disk_usage.DiskUsage() events = [e.name() for e in sensor.measure()] ok_(reduce(lambda acc, e: acc or e.endswith(".total"), events, False)) ok_(reduce(lambda acc, e: acc or e.endswith(".used"), events, False)) ok_(reduce(lambda acc, e: acc or e.endswith(".free"), events, False))
identifier_body
common.rs
-> c_longlong { unsafe { llvm::LLVMConstIntGetSExtValue(v) } } pub fn const_to_uint(v: ValueRef) -> c_ulonglong { unsafe { llvm::LLVMConstIntGetZExtValue(v) } } pub fn is_undef(val: ValueRef) -> bool { unsafe { llvm::LLVMIsUndef(val) != False } } pub fn is_null(val: V...
random_line_split
common.rs
u64, false) } pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef { C_integral(Type::i32(ccx), i as u64, true) } pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef { C_integral(Type::i64(ccx), i as u64, true) } pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef { C_integral(Type::i64(ccx), i, false...
{ node_id_type(bcx, ex.id) }
identifier_body
common.rs
for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); } for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); } } } fn param_substs_to_str(this: &param_substs, tcx: &ty::ctxt) -> ~str { format!("param_substs \\{tys:{}, vtables:{}\\}", this.tys.repr(tcx), ...
(&self, e: &ast::Expr
expr_is_lval
identifier_name
ColorAnimationSystem.ts
module example.systems { import ColorAnimation = example.components.ColorAnimation; import Sprite = example.components.Sprite; import Mapper = artemis.annotations.Mapper; import EntityProcessingSystem = artemis.systems.EntityProcessingSystem; import ComponentMapper = artemis.ComponentMapper; import Aspect = a...
() { super(Aspect.getAspectForAll(ColorAnimation, Sprite)); } protected processEach(e:Entity) { var c:ColorAnimation = this.cam.get(e); var sprite:PIXI.Sprite = this.sm.get(e).sprite_; if (c.alphaAnimate) { sprite.alpha += c.alphaSpeed * this.world.delta; if (sprite.alpha > ...
constructor
identifier_name
ColorAnimationSystem.ts
module example.systems { import ColorAnimation = example.components.ColorAnimation; import Sprite = example.components.Sprite; import Mapper = artemis.annotations.Mapper; import EntityProcessingSystem = artemis.systems.EntityProcessingSystem; import ComponentMapper = artemis.ComponentMapper; import Aspect = a...
} protected processEach(e:Entity) { var c:ColorAnimation = this.cam.get(e); var sprite:PIXI.Sprite = this.sm.get(e).sprite_; if (c.alphaAnimate) { sprite.alpha += c.alphaSpeed * this.world.delta; if (sprite.alpha > c.alphaMax || sprite.alpha < c.alphaMin) { if (c.repe...
random_line_split
ColorAnimationSystem.ts
module example.systems { import ColorAnimation = example.components.ColorAnimation; import Sprite = example.components.Sprite; import Mapper = artemis.annotations.Mapper; import EntityProcessingSystem = artemis.systems.EntityProcessingSystem; import ComponentMapper = artemis.ComponentMapper; import Aspect = a...
} } } }
{ if (c.repeat) { c.alphaSpeed = -c.alphaSpeed; } else { c.alphaAnimate = false; } }
conditional_block
exerciseQueue.js
const serializeHook = require('../lib/serializeHook'); var shops = ['bob', 'carol', 'ted', 'alice']; var results = {}; shops.forEach(s=>{ results[s] = []; }); var maxTime = 10000; function
(idx){ var shop = shops[idx % 4]; return serializeHook(null, shop, {token:'t'+ idx}, ()=>{ var interval = Math.floor(maxTime * Math.random()); console.log('triggering '+ shop +' at '+ idx +' in '+ interval); return new Promise((resolve, reject)=>{ setTimeout(()=>{ // console.error('resolving '+ shop +' a...
addJob
identifier_name
exerciseQueue.js
const serializeHook = require('../lib/serializeHook'); var shops = ['bob', 'carol', 'ted', 'alice']; var results = {}; shops.forEach(s=>{ results[s] = []; }); var maxTime = 10000; function addJob(idx){ var shop = shops[idx % 4]; return serializeHook(null, shop, {token:'t'+ idx}, ()=>{ var interval = Math.floo...
var timeoutAt = setTimeout(()=>{ throw 'Timed out'; }, maxTime * checkSize * shops.length); var allDone = ()=>shops.reduce((d, s)=>(d && results[s].length == checkSize), true); var checkIt = ()=>{ if(allDone()){ clearInterval(timeoutAt); shops.forEach(s=>{ var lastIdx = -1; var r = results[s]; console....
var checkSize = 10 for (var i = 0; i< checkSize * shops.length; i++) addJob(i);
random_line_split
exerciseQueue.js
const serializeHook = require('../lib/serializeHook'); var shops = ['bob', 'carol', 'ted', 'alice']; var results = {}; shops.forEach(s=>{ results[s] = []; }); var maxTime = 10000; function addJob(idx)
var checkSize = 10 for (var i = 0; i< checkSize * shops.length; i++) addJob(i); var timeoutAt = setTimeout(()=>{ throw 'Timed out'; }, maxTime * checkSize * shops.length); var allDone = ()=>shops.reduce((d, s)=>(d && results[s].length == checkSize), true); var checkIt = ()=>{ if(allDone()){ clearInterval(time...
{ var shop = shops[idx % 4]; return serializeHook(null, shop, {token:'t'+ idx}, ()=>{ var interval = Math.floor(maxTime * Math.random()); console.log('triggering '+ shop +' at '+ idx +' in '+ interval); return new Promise((resolve, reject)=>{ setTimeout(()=>{ // console.error('resolving '+ shop +' at '+ ...
identifier_body
local-florist.js
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixi...
(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var MapsLocalFlorist = _react2.default.createClass({ displayName: 'MapsLocalFlorist', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default...
_interopRequireDefault
identifier_name
local-florist.js
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixi...
var MapsLocalFlorist = _react2.default.createClass({ displayName: 'MapsLocalFlorist', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M12 22c4.97 0 9-4.03 9-9-4.97 0-9 4.0...
random_line_split
local-florist.js
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixi...
var MapsLocalFlorist = _react2.default.createClass({ displayName: 'MapsLocalFlorist', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M12 22c4.97 0 9-4.03 9-9-4.97 0-9 4....
{ return obj && obj.__esModule ? obj : {default: obj}; }
identifier_body