file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
user-settings.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from '../../userShared/user.service'; import * as Rx from 'rxjs/Rx'; import * as firebase from 'firebase'; @Component({ templateUrl: './user-settings.component.html', styleUrls: ['./user-settings.component.css'] }) export class UserSettingsComponent implements OnInit { theUser: any; blockedUserList: string[] = []; isDataAvailable = false; privacyOptions = [ 'Public', 'Friends Only', 'Private', ]; constructor(private router: Router, private userSVC: UserService) {} ngOnInit() { this.getUser(); } // TODO: Move to service as observable getUser() { const dbRef = firebase.database().ref('users/'); dbRef.once('value') .then((snapshot) => { const tmp: string[] = snapshot.val(); this.theUser = Object.keys(tmp).map(key => tmp[key]).filter(item => item.uid === this.userSVC.getUserId())[0]; if (this.theUser.blockedUsers) { for (const uid of this.theUser.blockedUsers) { dbRef.once('value') .then((snapshot) => { const tmp: string[] = snapshot.val(); this.blockedUserList.push(Object.keys(tmp).map(key => tmp[key]).filter(item => item.uid === uid)[0].email); }); } } else { this.blockedUserList = ['None']; } }).then(() => this.isDataAvailable = true); } blockedUsers() { this.router.navigate(['/user/settings/blockedUsers']); } securityQuestion() { this.router.navigate(['/user/settings/securityQuestion']); } resetPassword() { const verify = confirm(`Send a password reset email to ` + this.userSVC.loggedInUser + `?`) if (verify === true) { this.userSVC.passwordResetEmail(); } } reportAbuse() { this.router.navigate(['/user/settings/reportAbuse']); }
() { this.router.navigate(['/user']); } apply() { this.userSVC.updateUserSettings(this.theUser); this.router.navigate(['/user']); } }
cancel
identifier_name
user-settings.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from '../../userShared/user.service'; import * as Rx from 'rxjs/Rx'; import * as firebase from 'firebase'; @Component({ templateUrl: './user-settings.component.html', styleUrls: ['./user-settings.component.css'] }) export class UserSettingsComponent implements OnInit { theUser: any; blockedUserList: string[] = []; isDataAvailable = false; privacyOptions = [ 'Public', 'Friends Only', 'Private', ]; constructor(private router: Router, private userSVC: UserService) {} ngOnInit() { this.getUser(); } // TODO: Move to service as observable getUser() { const dbRef = firebase.database().ref('users/'); dbRef.once('value') .then((snapshot) => { const tmp: string[] = snapshot.val(); this.theUser = Object.keys(tmp).map(key => tmp[key]).filter(item => item.uid === this.userSVC.getUserId())[0]; if (this.theUser.blockedUsers) { for (const uid of this.theUser.blockedUsers) { dbRef.once('value') .then((snapshot) => { const tmp: string[] = snapshot.val(); this.blockedUserList.push(Object.keys(tmp).map(key => tmp[key]).filter(item => item.uid === uid)[0].email); }); } } else { this.blockedUserList = ['None']; } }).then(() => this.isDataAvailable = true); } blockedUsers() { this.router.navigate(['/user/settings/blockedUsers']); } securityQuestion() { this.router.navigate(['/user/settings/securityQuestion']); } resetPassword() { const verify = confirm(`Send a password reset email to ` + this.userSVC.loggedInUser + `?`) if (verify === true) { this.userSVC.passwordResetEmail(); } }
reportAbuse() { this.router.navigate(['/user/settings/reportAbuse']); } cancel() { this.router.navigate(['/user']); } apply() { this.userSVC.updateUserSettings(this.theUser); this.router.navigate(['/user']); } }
random_line_split
ForwardRenderStage.js
/** * Forward renderer */ var ForwardRenderStage = PostProcessRenderStage.extend({ init: function() { this._super(); this.debugActive = false; this.debugger = null; }, onPostRender: function(context, scene, camera) { this._super(context, scene, camera); if (this.debugActive) { if (!this.debugger) this.initDebugger(context, scene); var gl = context.gl; gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); context.modelview.push(); for (var i=0; i<this.debugger.quads.length; i++) { this.debugger.sampler.texture = this.debugger.quads[i].texture; this.material.bind({}, [this.debugger.sampler]); this.debugger.quads[i].quad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); } this.debugger.sampler.texture = this.debugger.vsyncTextures[0]; this.material.bind({}, [this.debugger.sampler]); this.debugger.vsyncQuad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); this.debugger.vsyncTextures.reverse(); context.modelview.pop(); } }, debug: function(val) { this.debugActive = !(val === false); }, initDebugger: function(context, scene) { var texRed = new Texture(context); texRed.name = "Red"; texRed.mipmapped = false; texRed.clearImage(context, [0xFF, 0x00, 0x00, 0xFF]); var texCyan = new Texture(context); texCyan.name = "Red"; texCyan.mipmapped = false; texCyan.clearImage(context, [0x00, 0xFF, 0xFF, 0xFF]); this.debugger = { quads: [], sampler: new Sampler('tex0', null), vsyncQuad: createQuad(0.85, 0.85, 0.1, 0.1), vsyncTextures: [ texRed, texCyan ] }; function createQuad(x, y, width, height)
// Draw shadowmaps var size = 0.5; var x = -1; var y = 1 - size; for (var i=0; i<scene.lights.length; i++) { if (!scene.lights[i].enabled) continue; if (!scene.lights[i].shadowCasting) continue; if (!scene.lights[i].shadow) continue; if (scene.lights[i] instanceof DirectionalLight) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: scene.lights[i].shadow.texture }); x+=size; } } // Draw OIT buffers var size = 2/4; var x = -1; var y = -1; if (this.generator.oitStage.enabled) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: this.generator.oitStage.transparencyTarget.texture }); this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.oitStage.transparencyWeight.texture }); } // Draw depth stage, if enabled if (this.generator.depthStage.enabled) { this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.depthStage.target.texture }); } } });
{ var vertices = [x,y,0, x,y+height,0, x+width,y+height,0, x+width,y,0]; var quad = new TrianglesRenderBuffer(context, [0, 1, 2, 0, 2, 3]); quad.add('position', vertices, 3); quad.add("uv0", [0,0, 0,1, 1,1, 1,0], 2); return quad; }
identifier_body
ForwardRenderStage.js
/** * Forward renderer */ var ForwardRenderStage = PostProcessRenderStage.extend({ init: function() { this._super(); this.debugActive = false; this.debugger = null; }, onPostRender: function(context, scene, camera) { this._super(context, scene, camera); if (this.debugActive) { if (!this.debugger) this.initDebugger(context, scene); var gl = context.gl; gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); context.modelview.push(); for (var i=0; i<this.debugger.quads.length; i++) { this.debugger.sampler.texture = this.debugger.quads[i].texture; this.material.bind({}, [this.debugger.sampler]); this.debugger.quads[i].quad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); } this.debugger.sampler.texture = this.debugger.vsyncTextures[0]; this.material.bind({}, [this.debugger.sampler]); this.debugger.vsyncQuad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); this.debugger.vsyncTextures.reverse(); context.modelview.pop(); } }, debug: function(val) { this.debugActive = !(val === false); }, initDebugger: function(context, scene) { var texRed = new Texture(context); texRed.name = "Red"; texRed.mipmapped = false; texRed.clearImage(context, [0xFF, 0x00, 0x00, 0xFF]); var texCyan = new Texture(context); texCyan.name = "Red"; texCyan.mipmapped = false; texCyan.clearImage(context, [0x00, 0xFF, 0xFF, 0xFF]); this.debugger = { quads: [], sampler: new Sampler('tex0', null), vsyncQuad: createQuad(0.85, 0.85, 0.1, 0.1), vsyncTextures: [ texRed, texCyan ] }; function createQuad(x, y, width, height) { var vertices = [x,y,0, x,y+height,0, x+width,y+height,0, x+width,y,0]; var quad = new TrianglesRenderBuffer(context, [0, 1, 2, 0, 2, 3]); quad.add('position', vertices, 3); quad.add("uv0", [0,0, 0,1, 1,1, 1,0], 2); return quad; } // Draw shadowmaps var size = 0.5; var x = -1; var y = 1 - size; for (var i=0; i<scene.lights.length; i++) { if (!scene.lights[i].enabled) continue; if (!scene.lights[i].shadowCasting) continue; if (!scene.lights[i].shadow) continue; if (scene.lights[i] instanceof DirectionalLight) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: scene.lights[i].shadow.texture }); x+=size; } } // Draw OIT buffers var size = 2/4; var x = -1;
this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.oitStage.transparencyWeight.texture }); } // Draw depth stage, if enabled if (this.generator.depthStage.enabled) { this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.depthStage.target.texture }); } } });
var y = -1; if (this.generator.oitStage.enabled) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: this.generator.oitStage.transparencyTarget.texture });
random_line_split
ForwardRenderStage.js
/** * Forward renderer */ var ForwardRenderStage = PostProcessRenderStage.extend({ init: function() { this._super(); this.debugActive = false; this.debugger = null; }, onPostRender: function(context, scene, camera) { this._super(context, scene, camera); if (this.debugActive) { if (!this.debugger) this.initDebugger(context, scene); var gl = context.gl; gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); context.modelview.push(); for (var i=0; i<this.debugger.quads.length; i++) { this.debugger.sampler.texture = this.debugger.quads[i].texture; this.material.bind({}, [this.debugger.sampler]); this.debugger.quads[i].quad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); } this.debugger.sampler.texture = this.debugger.vsyncTextures[0]; this.material.bind({}, [this.debugger.sampler]); this.debugger.vsyncQuad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); this.debugger.vsyncTextures.reverse(); context.modelview.pop(); } }, debug: function(val) { this.debugActive = !(val === false); }, initDebugger: function(context, scene) { var texRed = new Texture(context); texRed.name = "Red"; texRed.mipmapped = false; texRed.clearImage(context, [0xFF, 0x00, 0x00, 0xFF]); var texCyan = new Texture(context); texCyan.name = "Red"; texCyan.mipmapped = false; texCyan.clearImage(context, [0x00, 0xFF, 0xFF, 0xFF]); this.debugger = { quads: [], sampler: new Sampler('tex0', null), vsyncQuad: createQuad(0.85, 0.85, 0.1, 0.1), vsyncTextures: [ texRed, texCyan ] }; function
(x, y, width, height) { var vertices = [x,y,0, x,y+height,0, x+width,y+height,0, x+width,y,0]; var quad = new TrianglesRenderBuffer(context, [0, 1, 2, 0, 2, 3]); quad.add('position', vertices, 3); quad.add("uv0", [0,0, 0,1, 1,1, 1,0], 2); return quad; } // Draw shadowmaps var size = 0.5; var x = -1; var y = 1 - size; for (var i=0; i<scene.lights.length; i++) { if (!scene.lights[i].enabled) continue; if (!scene.lights[i].shadowCasting) continue; if (!scene.lights[i].shadow) continue; if (scene.lights[i] instanceof DirectionalLight) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: scene.lights[i].shadow.texture }); x+=size; } } // Draw OIT buffers var size = 2/4; var x = -1; var y = -1; if (this.generator.oitStage.enabled) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: this.generator.oitStage.transparencyTarget.texture }); this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.oitStage.transparencyWeight.texture }); } // Draw depth stage, if enabled if (this.generator.depthStage.enabled) { this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.depthStage.target.texture }); } } });
createQuad
identifier_name
ForwardRenderStage.js
/** * Forward renderer */ var ForwardRenderStage = PostProcessRenderStage.extend({ init: function() { this._super(); this.debugActive = false; this.debugger = null; }, onPostRender: function(context, scene, camera) { this._super(context, scene, camera); if (this.debugActive) { if (!this.debugger) this.initDebugger(context, scene); var gl = context.gl; gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); context.modelview.push(); for (var i=0; i<this.debugger.quads.length; i++) { this.debugger.sampler.texture = this.debugger.quads[i].texture; this.material.bind({}, [this.debugger.sampler]); this.debugger.quads[i].quad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); } this.debugger.sampler.texture = this.debugger.vsyncTextures[0]; this.material.bind({}, [this.debugger.sampler]); this.debugger.vsyncQuad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); this.debugger.vsyncTextures.reverse(); context.modelview.pop(); } }, debug: function(val) { this.debugActive = !(val === false); }, initDebugger: function(context, scene) { var texRed = new Texture(context); texRed.name = "Red"; texRed.mipmapped = false; texRed.clearImage(context, [0xFF, 0x00, 0x00, 0xFF]); var texCyan = new Texture(context); texCyan.name = "Red"; texCyan.mipmapped = false; texCyan.clearImage(context, [0x00, 0xFF, 0xFF, 0xFF]); this.debugger = { quads: [], sampler: new Sampler('tex0', null), vsyncQuad: createQuad(0.85, 0.85, 0.1, 0.1), vsyncTextures: [ texRed, texCyan ] }; function createQuad(x, y, width, height) { var vertices = [x,y,0, x,y+height,0, x+width,y+height,0, x+width,y,0]; var quad = new TrianglesRenderBuffer(context, [0, 1, 2, 0, 2, 3]); quad.add('position', vertices, 3); quad.add("uv0", [0,0, 0,1, 1,1, 1,0], 2); return quad; } // Draw shadowmaps var size = 0.5; var x = -1; var y = 1 - size; for (var i=0; i<scene.lights.length; i++) { if (!scene.lights[i].enabled) continue; if (!scene.lights[i].shadowCasting) continue; if (!scene.lights[i].shadow) continue; if (scene.lights[i] instanceof DirectionalLight) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: scene.lights[i].shadow.texture }); x+=size; } } // Draw OIT buffers var size = 2/4; var x = -1; var y = -1; if (this.generator.oitStage.enabled)
// Draw depth stage, if enabled if (this.generator.depthStage.enabled) { this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.depthStage.target.texture }); } } });
{ this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: this.generator.oitStage.transparencyTarget.texture }); this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.oitStage.transparencyWeight.texture }); }
conditional_block
send_msg.rs
//! Client Node Example. //! //! The node sends a message (atom) to the specified erlang node. //! //! # Usage Examples //! //! ```bash //! $ cargo run --example send_msg -- --help //! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello //! ``` extern crate clap; extern crate eetf; extern crate erl_dist; extern crate fibers; extern crate futures; use clap::{App, Arg}; use erl_dist::channel; use erl_dist::{EpmdClient, Handshake, Message}; use fibers::net::TcpStream; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::future::Either; use futures::{Future, Sink}; use std::io::{Error, ErrorKind}; use std::net::SocketAddr; fn main() { let matches = App::new("send_msg") .arg( Arg::with_name("EPMD_HOST") .short("h") .takes_value(true) .default_value("127.0.0.1"), ) .arg( Arg::with_name("EPMD_PORT") .short("p") .takes_value(true) .default_value("4369"), ) .arg( Arg::with_name("PEER_NAME") .long("peer") .takes_value(true) .default_value("foo"), ) .arg( Arg::with_name("COOKIE") .long("cookie") .takes_value(true) .default_value("WPKYDIOSJIMJUURLRUHV"), ) .arg( Arg::with_name("SELF_NODE") .long("self") .takes_value(true) .default_value("bar@localhost"), ) .arg( Arg::with_name("DESTINATION") .short("d") .long("destination") .takes_value(true) .default_value("foo"), ) .arg( Arg::with_name("MESSAGE") .short("m") .long("message") .takes_value(true) .default_value("hello_world"), ) .get_matches(); let peer_name = matches.value_of("PEER_NAME").unwrap().to_string(); let self_node = matches.value_of("SELF_NODE").unwrap().to_string(); let cookie = matches.value_of("COOKIE").unwrap().to_string(); let epmd_host = matches.value_of("EPMD_HOST").unwrap(); let epmd_port = matches.value_of("EPMD_PORT").unwrap(); let epmd_addr: SocketAddr = format!("{}:{}", epmd_host, epmd_port)
.parse() .expect("Invalid epmd address"); let dest_proc = matches.value_of("DESTINATION").unwrap().to_string(); let message = matches.value_of("MESSAGE").unwrap().to_string(); let self_node0 = self_node.to_string(); let mut executor = InPlaceExecutor::new().unwrap(); let monitor = executor.spawn_monitor( TcpStream::connect(epmd_addr.clone()) .and_then(move |epmd_socket| { // Gets peer node information from the EPMD EpmdClient::new().get_node_info(epmd_socket, &peer_name) }) .and_then(move |info| { if let Some(addr) = info.map(|i| SocketAddr::new(epmd_addr.ip(), i.port)) { // Executes the client side handshake Either::A(TcpStream::connect(addr).and_then(move |socket| { let handshake = Handshake::new(&self_node, &cookie); handshake.connect(socket) })) } else { Either::B(futures::failed(Error::new( ErrorKind::NotFound, "target node is not found", ))) } }) .and_then(move |peer| { // Sends a message to the peer node println!("# Connected: {}", peer.name); println!("# Distribution Flags: {:?}", peer.flags); let tx = channel::sender(peer.stream); let from_pid = eetf::Pid::new(self_node0, 0, 0, 0); let atom = eetf::Atom::from(message); let message = Message::reg_send(from_pid, dest_proc, atom); println!("# Send: {:?}", message); tx.send(message) }), ); let _ = executor.run_fiber(monitor).unwrap().expect("Failed"); println!("# DONE"); }
random_line_split
send_msg.rs
//! Client Node Example. //! //! The node sends a message (atom) to the specified erlang node. //! //! # Usage Examples //! //! ```bash //! $ cargo run --example send_msg -- --help //! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello //! ``` extern crate clap; extern crate eetf; extern crate erl_dist; extern crate fibers; extern crate futures; use clap::{App, Arg}; use erl_dist::channel; use erl_dist::{EpmdClient, Handshake, Message}; use fibers::net::TcpStream; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::future::Either; use futures::{Future, Sink}; use std::io::{Error, ErrorKind}; use std::net::SocketAddr; fn main()
{ let matches = App::new("send_msg") .arg( Arg::with_name("EPMD_HOST") .short("h") .takes_value(true) .default_value("127.0.0.1"), ) .arg( Arg::with_name("EPMD_PORT") .short("p") .takes_value(true) .default_value("4369"), ) .arg( Arg::with_name("PEER_NAME") .long("peer") .takes_value(true) .default_value("foo"), ) .arg( Arg::with_name("COOKIE") .long("cookie") .takes_value(true) .default_value("WPKYDIOSJIMJUURLRUHV"), ) .arg( Arg::with_name("SELF_NODE") .long("self") .takes_value(true) .default_value("bar@localhost"), ) .arg( Arg::with_name("DESTINATION") .short("d") .long("destination") .takes_value(true) .default_value("foo"), ) .arg( Arg::with_name("MESSAGE") .short("m") .long("message") .takes_value(true) .default_value("hello_world"), ) .get_matches(); let peer_name = matches.value_of("PEER_NAME").unwrap().to_string(); let self_node = matches.value_of("SELF_NODE").unwrap().to_string(); let cookie = matches.value_of("COOKIE").unwrap().to_string(); let epmd_host = matches.value_of("EPMD_HOST").unwrap(); let epmd_port = matches.value_of("EPMD_PORT").unwrap(); let epmd_addr: SocketAddr = format!("{}:{}", epmd_host, epmd_port) .parse() .expect("Invalid epmd address"); let dest_proc = matches.value_of("DESTINATION").unwrap().to_string(); let message = matches.value_of("MESSAGE").unwrap().to_string(); let self_node0 = self_node.to_string(); let mut executor = InPlaceExecutor::new().unwrap(); let monitor = executor.spawn_monitor( TcpStream::connect(epmd_addr.clone()) .and_then(move |epmd_socket| { // Gets peer node information from the EPMD EpmdClient::new().get_node_info(epmd_socket, &peer_name) }) .and_then(move |info| { if let Some(addr) = info.map(|i| SocketAddr::new(epmd_addr.ip(), i.port)) { // Executes the client side handshake Either::A(TcpStream::connect(addr).and_then(move |socket| { let handshake = Handshake::new(&self_node, &cookie); handshake.connect(socket) })) } else { Either::B(futures::failed(Error::new( ErrorKind::NotFound, "target node is not found", ))) } }) .and_then(move |peer| { // Sends a message to the peer node println!("# Connected: {}", peer.name); println!("# Distribution Flags: {:?}", peer.flags); let tx = channel::sender(peer.stream); let from_pid = eetf::Pid::new(self_node0, 0, 0, 0); let atom = eetf::Atom::from(message); let message = Message::reg_send(from_pid, dest_proc, atom); println!("# Send: {:?}", message); tx.send(message) }), ); let _ = executor.run_fiber(monitor).unwrap().expect("Failed"); println!("# DONE"); }
identifier_body
send_msg.rs
//! Client Node Example. //! //! The node sends a message (atom) to the specified erlang node. //! //! # Usage Examples //! //! ```bash //! $ cargo run --example send_msg -- --help //! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello //! ``` extern crate clap; extern crate eetf; extern crate erl_dist; extern crate fibers; extern crate futures; use clap::{App, Arg}; use erl_dist::channel; use erl_dist::{EpmdClient, Handshake, Message}; use fibers::net::TcpStream; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::future::Either; use futures::{Future, Sink}; use std::io::{Error, ErrorKind}; use std::net::SocketAddr; fn main() { let matches = App::new("send_msg") .arg( Arg::with_name("EPMD_HOST") .short("h") .takes_value(true) .default_value("127.0.0.1"), ) .arg( Arg::with_name("EPMD_PORT") .short("p") .takes_value(true) .default_value("4369"), ) .arg( Arg::with_name("PEER_NAME") .long("peer") .takes_value(true) .default_value("foo"), ) .arg( Arg::with_name("COOKIE") .long("cookie") .takes_value(true) .default_value("WPKYDIOSJIMJUURLRUHV"), ) .arg( Arg::with_name("SELF_NODE") .long("self") .takes_value(true) .default_value("bar@localhost"), ) .arg( Arg::with_name("DESTINATION") .short("d") .long("destination") .takes_value(true) .default_value("foo"), ) .arg( Arg::with_name("MESSAGE") .short("m") .long("message") .takes_value(true) .default_value("hello_world"), ) .get_matches(); let peer_name = matches.value_of("PEER_NAME").unwrap().to_string(); let self_node = matches.value_of("SELF_NODE").unwrap().to_string(); let cookie = matches.value_of("COOKIE").unwrap().to_string(); let epmd_host = matches.value_of("EPMD_HOST").unwrap(); let epmd_port = matches.value_of("EPMD_PORT").unwrap(); let epmd_addr: SocketAddr = format!("{}:{}", epmd_host, epmd_port) .parse() .expect("Invalid epmd address"); let dest_proc = matches.value_of("DESTINATION").unwrap().to_string(); let message = matches.value_of("MESSAGE").unwrap().to_string(); let self_node0 = self_node.to_string(); let mut executor = InPlaceExecutor::new().unwrap(); let monitor = executor.spawn_monitor( TcpStream::connect(epmd_addr.clone()) .and_then(move |epmd_socket| { // Gets peer node information from the EPMD EpmdClient::new().get_node_info(epmd_socket, &peer_name) }) .and_then(move |info| { if let Some(addr) = info.map(|i| SocketAddr::new(epmd_addr.ip(), i.port)) { // Executes the client side handshake Either::A(TcpStream::connect(addr).and_then(move |socket| { let handshake = Handshake::new(&self_node, &cookie); handshake.connect(socket) })) } else
}) .and_then(move |peer| { // Sends a message to the peer node println!("# Connected: {}", peer.name); println!("# Distribution Flags: {:?}", peer.flags); let tx = channel::sender(peer.stream); let from_pid = eetf::Pid::new(self_node0, 0, 0, 0); let atom = eetf::Atom::from(message); let message = Message::reg_send(from_pid, dest_proc, atom); println!("# Send: {:?}", message); tx.send(message) }), ); let _ = executor.run_fiber(monitor).unwrap().expect("Failed"); println!("# DONE"); }
{ Either::B(futures::failed(Error::new( ErrorKind::NotFound, "target node is not found", ))) }
conditional_block
send_msg.rs
//! Client Node Example. //! //! The node sends a message (atom) to the specified erlang node. //! //! # Usage Examples //! //! ```bash //! $ cargo run --example send_msg -- --help //! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello //! ``` extern crate clap; extern crate eetf; extern crate erl_dist; extern crate fibers; extern crate futures; use clap::{App, Arg}; use erl_dist::channel; use erl_dist::{EpmdClient, Handshake, Message}; use fibers::net::TcpStream; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::future::Either; use futures::{Future, Sink}; use std::io::{Error, ErrorKind}; use std::net::SocketAddr; fn
() { let matches = App::new("send_msg") .arg( Arg::with_name("EPMD_HOST") .short("h") .takes_value(true) .default_value("127.0.0.1"), ) .arg( Arg::with_name("EPMD_PORT") .short("p") .takes_value(true) .default_value("4369"), ) .arg( Arg::with_name("PEER_NAME") .long("peer") .takes_value(true) .default_value("foo"), ) .arg( Arg::with_name("COOKIE") .long("cookie") .takes_value(true) .default_value("WPKYDIOSJIMJUURLRUHV"), ) .arg( Arg::with_name("SELF_NODE") .long("self") .takes_value(true) .default_value("bar@localhost"), ) .arg( Arg::with_name("DESTINATION") .short("d") .long("destination") .takes_value(true) .default_value("foo"), ) .arg( Arg::with_name("MESSAGE") .short("m") .long("message") .takes_value(true) .default_value("hello_world"), ) .get_matches(); let peer_name = matches.value_of("PEER_NAME").unwrap().to_string(); let self_node = matches.value_of("SELF_NODE").unwrap().to_string(); let cookie = matches.value_of("COOKIE").unwrap().to_string(); let epmd_host = matches.value_of("EPMD_HOST").unwrap(); let epmd_port = matches.value_of("EPMD_PORT").unwrap(); let epmd_addr: SocketAddr = format!("{}:{}", epmd_host, epmd_port) .parse() .expect("Invalid epmd address"); let dest_proc = matches.value_of("DESTINATION").unwrap().to_string(); let message = matches.value_of("MESSAGE").unwrap().to_string(); let self_node0 = self_node.to_string(); let mut executor = InPlaceExecutor::new().unwrap(); let monitor = executor.spawn_monitor( TcpStream::connect(epmd_addr.clone()) .and_then(move |epmd_socket| { // Gets peer node information from the EPMD EpmdClient::new().get_node_info(epmd_socket, &peer_name) }) .and_then(move |info| { if let Some(addr) = info.map(|i| SocketAddr::new(epmd_addr.ip(), i.port)) { // Executes the client side handshake Either::A(TcpStream::connect(addr).and_then(move |socket| { let handshake = Handshake::new(&self_node, &cookie); handshake.connect(socket) })) } else { Either::B(futures::failed(Error::new( ErrorKind::NotFound, "target node is not found", ))) } }) .and_then(move |peer| { // Sends a message to the peer node println!("# Connected: {}", peer.name); println!("# Distribution Flags: {:?}", peer.flags); let tx = channel::sender(peer.stream); let from_pid = eetf::Pid::new(self_node0, 0, 0, 0); let atom = eetf::Atom::from(message); let message = Message::reg_send(from_pid, dest_proc, atom); println!("# Send: {:?}", message); tx.send(message) }), ); let _ = executor.run_fiber(monitor).unwrap().expect("Failed"); println!("# DONE"); }
main
identifier_name
test_chart_format23.py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('chart_format23.xlsx') def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [108321024, 108328448] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$B$1:$B$5', 'border': {'color': 'yellow'}, 'fill': {'color': 'red', 'transparency': 100}, }) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$C$1:$C$5', }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
identifier_body
test_chart_format23.py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class
(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('chart_format23.xlsx') def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [108321024, 108328448] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$B$1:$B$5', 'border': {'color': 'yellow'}, 'fill': {'color': 'red', 'transparency': 100}, }) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$C$1:$C$5', }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
identifier_name
test_chart_format23.py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self):
workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [108321024, 108328448] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$B$1:$B$5', 'border': {'color': 'yellow'}, 'fill': {'color': 'red', 'transparency': 100}, }) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$C$1:$C$5', }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
self.set_filename('chart_format23.xlsx') def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting."""
random_line_split
index.js
'use strict'; var express = require("express"); var http = require("http"); var app = express(); var httpServer = http.Server(app); var io = require('socket.io')(httpServer); // Users array. var users = []; // Channels pre-defined array. var channels = [ 'Angular', 'React', 'Laravel', 'Symfony' ]; // Start http server. httpServer.listen(3000, function () { }); // Use static files 'app' folder for '/' path. app.use(express.static(__dirname + '/app/')); // Channels endpoint. app.get('/channels', function (req, res) {
// Join event. socket.on('join', function (data) { // Join socket to channel. socket.join(data.channel); // Add user to users lists. users.push({id: socket.id, name: data.user}); // Bind username to socket object. socket.username = data.user; // If socket already exists in a channel, leave. if (typeof socket.channel != 'undefined') { socket.leave(socket.channel); } // Bind channel to socket. socket.channel = data.channel; }); // Message event. socket.on('message', function (data) { // Send to selected channel user's message. io.sockets.in(data.channel).emit('message', {message: data.message, user: data.username}); }); // Private message event. socket.on('private', function (data) { // Split message to take receiver name. var message = data.message.split(" "); // Get username from message array. var to_user = message[0].slice(1); // Filter users to find user's socket id and send message. users.filter(function (user) { if (user.name == to_user) { // Format message. var private_message = "(private) " + data.message.slice(to_user.length + 2); // Send message to user who sent the message. io.sockets.connected[socket.id].emit('message', {message: private_message, user: "me -> " + to_user}); // Send message to receiver. io.sockets.connected[user.id].emit('message', {message: private_message, user: data.username}); } }); }); // Disconnect event. socket.on('disconnect', function () { // Check if user joined any room and clean users array. users = users.filter(function (user) { if (user.id == socket.id) { return false; } return true }); }); });
res.send(channels); }); // On connection event. io.on('connection', function (socket) {
random_line_split
index.js
'use strict'; var express = require("express"); var http = require("http"); var app = express(); var httpServer = http.Server(app); var io = require('socket.io')(httpServer); // Users array. var users = []; // Channels pre-defined array. var channels = [ 'Angular', 'React', 'Laravel', 'Symfony' ]; // Start http server. httpServer.listen(3000, function () { }); // Use static files 'app' folder for '/' path. app.use(express.static(__dirname + '/app/')); // Channels endpoint. app.get('/channels', function (req, res) { res.send(channels); }); // On connection event. io.on('connection', function (socket) { // Join event. socket.on('join', function (data) { // Join socket to channel. socket.join(data.channel); // Add user to users lists. users.push({id: socket.id, name: data.user}); // Bind username to socket object. socket.username = data.user; // If socket already exists in a channel, leave. if (typeof socket.channel != 'undefined') { socket.leave(socket.channel); } // Bind channel to socket. socket.channel = data.channel; }); // Message event. socket.on('message', function (data) { // Send to selected channel user's message. io.sockets.in(data.channel).emit('message', {message: data.message, user: data.username}); }); // Private message event. socket.on('private', function (data) { // Split message to take receiver name. var message = data.message.split(" "); // Get username from message array. var to_user = message[0].slice(1); // Filter users to find user's socket id and send message. users.filter(function (user) { if (user.name == to_user)
}); }); // Disconnect event. socket.on('disconnect', function () { // Check if user joined any room and clean users array. users = users.filter(function (user) { if (user.id == socket.id) { return false; } return true }); }); });
{ // Format message. var private_message = "(private) " + data.message.slice(to_user.length + 2); // Send message to user who sent the message. io.sockets.connected[socket.id].emit('message', {message: private_message, user: "me -> " + to_user}); // Send message to receiver. io.sockets.connected[user.id].emit('message', {message: private_message, user: data.username}); }
conditional_block
trait-coercion-generic.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Trait<T> { fn f(&self, x: T); } struct Struct { x: int, y: int, } impl Trait<&'static str> for Struct { fn f(&self, x: &'static str) { println!("Hi, {}!", x); } }
let a = Struct { x: 1, y: 2 }; let b: Box<Trait<&'static str>> = box a; b.f("Mary"); let c: &Trait<&'static str> = &a; c.f("Joe"); }
pub fn main() {
random_line_split
trait-coercion-generic.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Trait<T> { fn f(&self, x: T); } struct Struct { x: int, y: int, } impl Trait<&'static str> for Struct { fn f(&self, x: &'static str) { println!("Hi, {}!", x); } } pub fn
() { let a = Struct { x: 1, y: 2 }; let b: Box<Trait<&'static str>> = box a; b.f("Mary"); let c: &Trait<&'static str> = &a; c.f("Joe"); }
main
identifier_name
trait-coercion-generic.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Trait<T> { fn f(&self, x: T); } struct Struct { x: int, y: int, } impl Trait<&'static str> for Struct { fn f(&self, x: &'static str)
} pub fn main() { let a = Struct { x: 1, y: 2 }; let b: Box<Trait<&'static str>> = box a; b.f("Mary"); let c: &Trait<&'static str> = &a; c.f("Joe"); }
{ println!("Hi, {}!", x); }
identifier_body
ErrorBoundary.tsx
import * as React from "react" import { ErrorWithMetadata } from "v2/Utils/errors" import createLogger from "v2/Utils/logger" import { ErrorPage } from "v2/Components/ErrorPage" import { AppContainer } from "v2/Apps/Components/AppContainer" import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding" import { ArtsyLogoBlackIcon, Button, ThemeProviderV3 } from "@artsy/palette" import { RouterLink } from "./RouterLink" const logger = createLogger() interface Props { children?: any onCatch?: () => void } interface State { asyncChunkLoadError: boolean detail: string genericError: boolean isError: boolean message: string } export class ErrorBoundary extends React.Component<Props, State> { state: State = { asyncChunkLoadError: false, detail: "", genericError: false, isError: false, message: "", } componentDidCatch(error: Error, errorInfo) { logger.error(new ErrorWithMetadata(error.message, errorInfo)) if (this.props.onCatch) { this.props.onCatch() }
const message = error?.message || "Internal Server Error" const detail = error.stack /** * Check to see if there's been a network error while asynchronously loading * a dynamic webpack split chunk bundle. Can happen if a user is navigating * between routes and their network connection goes out. * * @see https://reactjs.org/docs/code-splitting.html */ if (error.message.match(/Loading chunk .* failed/)) { return { isError: true, asyncChunkLoadError: true, detail, message, } } return { isError: true, genericError: true, detail, message, } } render() { const { asyncChunkLoadError, detail, genericError, isError, message, } = this.state if (isError) { return ( <ThemeProviderV3> <AppContainer my={4}> <HorizontalPadding> <RouterLink to="/" display="block" mb={4}> <ArtsyLogoBlackIcon /> </RouterLink> {(() => { switch (true) { case asyncChunkLoadError: { return ( <ErrorPage code={500} message="Please check your network connection and try again." > <Button mt={2} size="small" variant="secondaryOutline" onClick={() => window.location.reload()} > Reload </Button> </ErrorPage> ) } case genericError: { return ( <ErrorPage code={500} message={message} detail={detail}> <Button mt={2} size="small" variant="secondaryOutline" onClick={() => window.location.reload()} > Reload </Button> </ErrorPage> ) } } })()} </HorizontalPadding> </AppContainer> </ThemeProviderV3> ) } return this.props.children } }
} static getDerivedStateFromError(error: Error) {
random_line_split
ErrorBoundary.tsx
import * as React from "react" import { ErrorWithMetadata } from "v2/Utils/errors" import createLogger from "v2/Utils/logger" import { ErrorPage } from "v2/Components/ErrorPage" import { AppContainer } from "v2/Apps/Components/AppContainer" import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding" import { ArtsyLogoBlackIcon, Button, ThemeProviderV3 } from "@artsy/palette" import { RouterLink } from "./RouterLink" const logger = createLogger() interface Props { children?: any onCatch?: () => void } interface State { asyncChunkLoadError: boolean detail: string genericError: boolean isError: boolean message: string } export class ErrorBoundary extends React.Component<Props, State> { state: State = { asyncChunkLoadError: false, detail: "", genericError: false, isError: false, message: "", } componentDidCatch(error: Error, errorInfo) { logger.error(new ErrorWithMetadata(error.message, errorInfo)) if (this.props.onCatch)
} static getDerivedStateFromError(error: Error) { const message = error?.message || "Internal Server Error" const detail = error.stack /** * Check to see if there's been a network error while asynchronously loading * a dynamic webpack split chunk bundle. Can happen if a user is navigating * between routes and their network connection goes out. * * @see https://reactjs.org/docs/code-splitting.html */ if (error.message.match(/Loading chunk .* failed/)) { return { isError: true, asyncChunkLoadError: true, detail, message, } } return { isError: true, genericError: true, detail, message, } } render() { const { asyncChunkLoadError, detail, genericError, isError, message, } = this.state if (isError) { return ( <ThemeProviderV3> <AppContainer my={4}> <HorizontalPadding> <RouterLink to="/" display="block" mb={4}> <ArtsyLogoBlackIcon /> </RouterLink> {(() => { switch (true) { case asyncChunkLoadError: { return ( <ErrorPage code={500} message="Please check your network connection and try again." > <Button mt={2} size="small" variant="secondaryOutline" onClick={() => window.location.reload()} > Reload </Button> </ErrorPage> ) } case genericError: { return ( <ErrorPage code={500} message={message} detail={detail}> <Button mt={2} size="small" variant="secondaryOutline" onClick={() => window.location.reload()} > Reload </Button> </ErrorPage> ) } } })()} </HorizontalPadding> </AppContainer> </ThemeProviderV3> ) } return this.props.children } }
{ this.props.onCatch() }
conditional_block
ErrorBoundary.tsx
import * as React from "react" import { ErrorWithMetadata } from "v2/Utils/errors" import createLogger from "v2/Utils/logger" import { ErrorPage } from "v2/Components/ErrorPage" import { AppContainer } from "v2/Apps/Components/AppContainer" import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding" import { ArtsyLogoBlackIcon, Button, ThemeProviderV3 } from "@artsy/palette" import { RouterLink } from "./RouterLink" const logger = createLogger() interface Props { children?: any onCatch?: () => void } interface State { asyncChunkLoadError: boolean detail: string genericError: boolean isError: boolean message: string } export class ErrorBoundary extends React.Component<Props, State> { state: State = { asyncChunkLoadError: false, detail: "", genericError: false, isError: false, message: "", } componentDidCatch(error: Error, errorInfo) { logger.error(new ErrorWithMetadata(error.message, errorInfo)) if (this.props.onCatch) { this.props.onCatch() } } static
(error: Error) { const message = error?.message || "Internal Server Error" const detail = error.stack /** * Check to see if there's been a network error while asynchronously loading * a dynamic webpack split chunk bundle. Can happen if a user is navigating * between routes and their network connection goes out. * * @see https://reactjs.org/docs/code-splitting.html */ if (error.message.match(/Loading chunk .* failed/)) { return { isError: true, asyncChunkLoadError: true, detail, message, } } return { isError: true, genericError: true, detail, message, } } render() { const { asyncChunkLoadError, detail, genericError, isError, message, } = this.state if (isError) { return ( <ThemeProviderV3> <AppContainer my={4}> <HorizontalPadding> <RouterLink to="/" display="block" mb={4}> <ArtsyLogoBlackIcon /> </RouterLink> {(() => { switch (true) { case asyncChunkLoadError: { return ( <ErrorPage code={500} message="Please check your network connection and try again." > <Button mt={2} size="small" variant="secondaryOutline" onClick={() => window.location.reload()} > Reload </Button> </ErrorPage> ) } case genericError: { return ( <ErrorPage code={500} message={message} detail={detail}> <Button mt={2} size="small" variant="secondaryOutline" onClick={() => window.location.reload()} > Reload </Button> </ErrorPage> ) } } })()} </HorizontalPadding> </AppContainer> </ThemeProviderV3> ) } return this.props.children } }
getDerivedStateFromError
identifier_name
ErrorBoundary.tsx
import * as React from "react" import { ErrorWithMetadata } from "v2/Utils/errors" import createLogger from "v2/Utils/logger" import { ErrorPage } from "v2/Components/ErrorPage" import { AppContainer } from "v2/Apps/Components/AppContainer" import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding" import { ArtsyLogoBlackIcon, Button, ThemeProviderV3 } from "@artsy/palette" import { RouterLink } from "./RouterLink" const logger = createLogger() interface Props { children?: any onCatch?: () => void } interface State { asyncChunkLoadError: boolean detail: string genericError: boolean isError: boolean message: string } export class ErrorBoundary extends React.Component<Props, State> { state: State = { asyncChunkLoadError: false, detail: "", genericError: false, isError: false, message: "", } componentDidCatch(error: Error, errorInfo) { logger.error(new ErrorWithMetadata(error.message, errorInfo)) if (this.props.onCatch) { this.props.onCatch() } } static getDerivedStateFromError(error: Error)
render() { const { asyncChunkLoadError, detail, genericError, isError, message, } = this.state if (isError) { return ( <ThemeProviderV3> <AppContainer my={4}> <HorizontalPadding> <RouterLink to="/" display="block" mb={4}> <ArtsyLogoBlackIcon /> </RouterLink> {(() => { switch (true) { case asyncChunkLoadError: { return ( <ErrorPage code={500} message="Please check your network connection and try again." > <Button mt={2} size="small" variant="secondaryOutline" onClick={() => window.location.reload()} > Reload </Button> </ErrorPage> ) } case genericError: { return ( <ErrorPage code={500} message={message} detail={detail}> <Button mt={2} size="small" variant="secondaryOutline" onClick={() => window.location.reload()} > Reload </Button> </ErrorPage> ) } } })()} </HorizontalPadding> </AppContainer> </ThemeProviderV3> ) } return this.props.children } }
{ const message = error?.message || "Internal Server Error" const detail = error.stack /** * Check to see if there's been a network error while asynchronously loading * a dynamic webpack split chunk bundle. Can happen if a user is navigating * between routes and their network connection goes out. * * @see https://reactjs.org/docs/code-splitting.html */ if (error.message.match(/Loading chunk .* failed/)) { return { isError: true, asyncChunkLoadError: true, detail, message, } } return { isError: true, genericError: true, detail, message, } }
identifier_body
basic_block.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use llvm; use llvm::{BasicBlockRef}; use trans::value::{Users, Value}; use std::iter::{Filter, Map}; pub struct BasicBlock(pub BasicBlockRef); pub type Preds<'a> = Map<'a, Value, BasicBlock, Filter<'a, Value, Users>>; /** * Wrapper for LLVM BasicBlockRef */ impl BasicBlock { pub fn get(&self) -> BasicBlockRef
pub fn as_value(self) -> Value { unsafe { Value(llvm::LLVMBasicBlockAsValue(self.get())) } } pub fn pred_iter(self) -> Preds<'static> { self.as_value().user_iter() .filter(|user| user.is_a_terminator_inst()) .map(|user| user.get_parent().unwrap()) } pub fn get_single_predecessor(self) -> Option<BasicBlock> { let mut iter = self.pred_iter(); match (iter.next(), iter.next()) { (Some(first), None) => Some(first), _ => None } } }
{ let BasicBlock(v) = *self; v }
identifier_body
basic_block.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use llvm; use llvm::{BasicBlockRef}; use trans::value::{Users, Value}; use std::iter::{Filter, Map}; pub struct
(pub BasicBlockRef); pub type Preds<'a> = Map<'a, Value, BasicBlock, Filter<'a, Value, Users>>; /** * Wrapper for LLVM BasicBlockRef */ impl BasicBlock { pub fn get(&self) -> BasicBlockRef { let BasicBlock(v) = *self; v } pub fn as_value(self) -> Value { unsafe { Value(llvm::LLVMBasicBlockAsValue(self.get())) } } pub fn pred_iter(self) -> Preds<'static> { self.as_value().user_iter() .filter(|user| user.is_a_terminator_inst()) .map(|user| user.get_parent().unwrap()) } pub fn get_single_predecessor(self) -> Option<BasicBlock> { let mut iter = self.pred_iter(); match (iter.next(), iter.next()) { (Some(first), None) => Some(first), _ => None } } }
BasicBlock
identifier_name
basic_block.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use llvm; use llvm::{BasicBlockRef}; use trans::value::{Users, Value}; use std::iter::{Filter, Map}; pub struct BasicBlock(pub BasicBlockRef); pub type Preds<'a> = Map<'a, Value, BasicBlock, Filter<'a, Value, Users>>; /** * Wrapper for LLVM BasicBlockRef */ impl BasicBlock { pub fn get(&self) -> BasicBlockRef { let BasicBlock(v) = *self; v } pub fn as_value(self) -> Value { unsafe { Value(llvm::LLVMBasicBlockAsValue(self.get())) } } pub fn pred_iter(self) -> Preds<'static> { self.as_value().user_iter() .filter(|user| user.is_a_terminator_inst()) .map(|user| user.get_parent().unwrap()) } pub fn get_single_predecessor(self) -> Option<BasicBlock> {
} } }
let mut iter = self.pred_iter(); match (iter.next(), iter.next()) { (Some(first), None) => Some(first), _ => None
random_line_split
bwa.py
"""BWA (https://github.com/lh3/bwa) """ import os import signal import subprocess from bcbio.pipeline import config_utils from bcbio import bam, utils from bcbio.distributed import objectstore from bcbio.distributed.transaction import file_transaction, tx_tmpdir from bcbio.ngsalign import alignprep, novoalign, postalign, rtg from bcbio.provenance import do from bcbio.rnaseq import gtf from bcbio.variation import sentieon import bcbio.pipeline.datadict as dd from bcbio.bam import fastq from bcbio.log import logger galaxy_location_file = "bwa_index.loc" def align_bam(in_bam, ref_file, names, align_dir, data): """Perform direct alignment of an input BAM file with BWA using pipes. This avoids disk IO by piping between processes: - samtools sort of input BAM to queryname - bedtools conversion to interleaved FASTQ - bwa-mem alignment - samtools conversion to BAM - samtools sort to coordinate """ config = data["config"] out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) samtools = config_utils.get_program("samtools", config) bedtools = config_utils.get_program("bedtools", config) resources = config_utils.get_resources("samtools", config) num_cores = config["algorithm"].get("num_cores", 1) # adjust memory for samtools since used for input and output max_mem = config_utils.adjust_memory(resources.get("memory", "1G"), 3, "decrease").upper() if not utils.file_exists(out_file): with tx_tmpdir(data) as work_dir: with postalign.tobam_cl(data, out_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file): if not hla_on(data) or needs_separate_hla(data): bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-", with_hla=False) else: bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-", with_hla=True) tx_out_prefix = os.path.splitext(tx_out_file)[0] prefix1 = "%s-in1" % tx_out_prefix cmd = ("unset JAVA_HOME && " "{samtools} sort -n -l 1 -@ {num_cores} -m {max_mem} {in_bam} -T {prefix1} " "| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout " "| {bwa_cmd} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)]) data["work_bam"] = out_file hla_file = "HLA-" + out_file if needs_separate_hla(data) and not utils.file_exists(hla_file): with tx_tmpdir(data) as work_dir: with postalign.tobam_cl(data, hla_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file): bwa_cmd = _get_bwa_mem_cmd(data, hla_file, ref_file, "-", with_hla=True) tx_out_prefix = os.path.splitext(tx_out_file)[0] prefix1 = "%s-in1" % tx_out_prefix cmd = ("unset JAVA_HOME && " "{samtools} sort -n -l 1 -@ {num_cores} -m {max_mem} {in_bam} -T {prefix1} " "| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout " "| {bwa_cmd} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)]) hla_file = _align_mem_hla(fastq_file, pair_file, ref_file, hla_file, names, rg_info, data) data["hla_bam"] = hla_file return data def _get_bwa_mem_cmd(data, out_file, ref_file, fastq1, fastq2="", with_hla=False): """Perform piped bwa mem mapping potentially with alternative alleles in GRCh38 + HLA typing. Commands for HLA post-processing: base=TEST run-HLA $base.hla > $base.hla.top cat $base.hla.HLA*.gt | grep ^GT | cut -f2- > $base.hla.all rm -f $base.hla.HLA*gt rm -f $base.hla.HLA*gz """ alt_file = ref_file + ".alt" if with_hla: bwakit_dir = os.path.dirname(os.path.realpath(utils.which("run-bwamem"))) hla_base = os.path.join(utils.safe_makedir(os.path.join(os.path.dirname(out_file), "hla")), os.path.basename(out_file) + ".hla") alt_cmd = (" | {bwakit_dir}/k8 {bwakit_dir}/bwa-postalt.js -p {hla_base} {alt_file}") else: alt_cmd = "" if dd.get_aligner(data) == "sentieon-bwa": bwa_exe = "sentieon-bwa" exports = sentieon.license_export(data) else: bwa_exe = "bwa" exports = "" bwa = config_utils.get_program(bwa_exe, data["config"]) num_cores = data["config"]["algorithm"].get("num_cores", 1) bwa_resources = config_utils.get_resources("bwa", data["config"]) bwa_params = (" ".join([str(x) for x in bwa_resources.get("options", [])]) if "options" in bwa_resources else "") rg_info = novoalign.get_rg_info(data["rgnames"]) # For UMI runs, pass along consensus tags c_tags = "-C" if "umi_bam" in data else "" pairing = "-p" if not fastq2 else "" # Restrict seed occurances to 1/2 of default, manage memory usage for centromere repeats in hg38 # https://sourceforge.net/p/bio-bwa/mailman/message/31514937/ # http://ehc.ac/p/bio-bwa/mailman/message/32268544/ mem_usage = "-c 250" bwa_cmd = ("{exports}{bwa} mem {pairing} {c_tags} {mem_usage} -M -t {num_cores} {bwa_params} -R '{rg_info}' " "-v 1 {ref_file} {fastq1} {fastq2} ") return (bwa_cmd + alt_cmd).format(**locals()) def is_precollapsed_bam(data): return dd.get_umi_type(data) == "fastq_name" and not has_umi(data) def hla_on(data): return has_hla(data) and dd.get_hlacaller(data) def has_umi(data): return "umi_bam" in data def has_hla(data): from bcbio.heterogeneity import chromhacks return len(chromhacks.get_hla_chroms(dd.get_ref_file(data))) != 0 def fastq_size_output(fastq_file, tocheck): head_count = 8000000 fastq_file = objectstore.cl_input(fastq_file) gzip_cmd = "zcat {fastq_file}" if fastq_file.endswith(".gz") else "cat {fastq_file}" cmd = (utils.local_path_export() + gzip_cmd + " | head -n {head_count} | " "seqtk sample -s42 - {tocheck} | " "awk '{{if(NR%4==2) print length($1)}}' | sort | uniq -c") def fix_signal(): """Avoid spurious 'cat: write error: Broken pipe' message due to head command. Work around from: https://bitbucket.org/brodie/cram/issues/16/broken-pipe-when-heading-certain-output """ signal.signal(signal.SIGPIPE, signal.SIG_DFL) count_out = subprocess.check_output(cmd.format(**locals()), shell=True, executable="/bin/bash", preexec_fn=fix_signal).decode() if not count_out.strip(): raise IOError("Failed to check fastq file sizes with: %s" % cmd.format(**locals())) for count, size in (l.strip().split() for l in count_out.strip().split("\n")): yield count, size def _can_use_mem(fastq_file, data, read_min_size=None): """bwa-mem handle longer (> 70bp) reads with improved piping. Randomly samples 5000 reads from the first two million. Default to no piping if more than 75% of the sampled reads are small. If we've previously calculated minimum read sizes (from rtg SDF output) we can skip the formal check. """ min_size = 70 if read_min_size and read_min_size >= min_size: return True thresh = 0.75 tocheck = 5000 shorter = 0 for count, size in fastq_size_output(fastq_file, tocheck): if int(size) < min_size: shorter += int(count) return (float(shorter) / float(tocheck)) <= thresh def align_pipe(fastq_file, pair_file, ref_file, names, align_dir, data): """Perform piped alignment of fastq input files, generating sorted output BAM. """ pair_file = pair_file if pair_file else "" # back compatible -- older files were named with lane information, use sample name now if names["lane"] != dd.get_sample_name(data): out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) else: out_file = None if not out_file or not utils.file_exists(out_file): umi_ext = "-cumi" if "umi_bam" in data else "" out_file = os.path.join(align_dir, "{0}-sort{1}.bam".format(dd.get_sample_name(data), umi_ext)) qual_format = data["config"]["algorithm"].get("quality_format", "").lower() min_size = None if data.get("align_split") or fastq_file.endswith(".sdf"): if fastq_file.endswith(".sdf"): min_size = rtg.min_read_size(fastq_file) final_file = out_file out_file, data = alignprep.setup_combine(final_file, data) fastq_file, pair_file = alignprep.split_namedpipe_cls(fastq_file, pair_file, data) else: final_file = None if qual_format == "illumina": fastq_file = alignprep.fastq_convert_pipe_cl(fastq_file, data) if pair_file: pair_file = alignprep.fastq_convert_pipe_cl(pair_file, data) rg_info = novoalign.get_rg_info(names) if not utils.file_exists(out_file) and (final_file is None or not utils.file_exists(final_file)): # If we cannot do piping, use older bwa aln approach if ("bwa-mem" not in dd.get_tools_on(data) and ("bwa-mem" in dd.get_tools_off(data) or not _can_use_mem(fastq_file, data, min_size))): out_file = _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) else: if is_precollapsed_bam(data) or not hla_on(data) or needs_separate_hla(data): out_file = _align_mem(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) else: out_file = _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) data["work_bam"] = out_file # bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file # (see https://github.com/bcbio/bcbio-nextgen/issues/3069) if needs_separate_hla(data): hla_file = os.path.join(os.path.dirname(out_file), "HLA-" + os.path.basename(out_file)) hla_file = _align_mem_hla(fastq_file, pair_file, ref_file, hla_file, names, rg_info, data) data["hla_bam"] = hla_file return data def _align_mem(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths. """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" % (_get_bwa_mem_cmd(data, out_file, ref_file, fastq_file, pair_file, with_hla=False), tobam_cl)) do.run(cmd, "bwa mem alignment from fastq: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, fastq_file)]) return out_file def _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths with HLA alignments """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" % (_get_bwa_mem_cmd(data, out_file, ref_file, fastq_file, pair_file, with_hla=True), tobam_cl)) do.run(cmd, "bwa mem alignment from fastq: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, fastq_file)]) return out_file def needs_separate_hla(data): """ bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file (see https://github.com/bcbio/bcbio-nextgen/issues/3069) """ return hla_on(data) and has_umi(data) def _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform a BWA alignment using 'aln' backtrack algorithm. """ bwa = config_utils.get_program("bwa", data["config"]) config = data["config"] sai1_file = "%s_1.sai" % os.path.splitext(out_file)[0] sai2_file = "%s_2.sai" % os.path.splitext(out_file)[0] if pair_file else "" if not utils.file_exists(sai1_file): with file_transaction(data, sai1_file) as tx_sai1_file: _run_bwa_align(fastq_file, ref_file, tx_sai1_file, config) if sai2_file and not utils.file_exists(sai2_file): with file_transaction(data, sai2_file) as tx_sai2_file: _run_bwa_align(pair_file, ref_file, tx_sai2_file, config) with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): align_type = "sampe" if sai2_file else "samse" cmd = ("unset JAVA_HOME && {bwa} {align_type} -r '{rg_info}' {ref_file} {sai1_file} {sai2_file} " "{fastq_file} {pair_file} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa %s" % align_type, data) return out_file def _bwa_args_from_config(config): num_cores = config["algorithm"].get("num_cores", 1) core_flags = ["-t", str(num_cores)] if num_cores > 1 else [] return core_flags def _run_bwa_align(fastq_file, ref_file, out_file, config): aln_cl = [config_utils.get_program("bwa", config), "aln", "-n 2", "-k 2"] aln_cl += _bwa_args_from_config(config) aln_cl += [ref_file, fastq_file] cmd = "{cl} > {out_file}".format(cl=" ".join(aln_cl), out_file=out_file) do.run(cmd, "bwa aln: {f}".format(f=os.path.basename(fastq_file)), None) def index_transcriptome(gtf_file, ref_file, data): """ use a GTF file and a reference FASTA file to index the transcriptome """ gtf_fasta = gtf.gtf_to_fasta(gtf_file, ref_file) return build_bwa_index(gtf_fasta, data) def build_bwa_index(fasta_file, data): bwa = config_utils.get_program("bwa", data["config"]) cmd = "{bwa} index {fasta_file}".format(**locals()) message = "Creating transcriptome index of %s with bwa." % (fasta_file) do.run(cmd, message) return fasta_file def align_transcriptome(fastq_file, pair_file, ref_file, data): """ bwa mem with settings for aligning to the transcriptome for eXpress/RSEM/etc """
out_file = base + ".transcriptome" + ext if utils.file_exists(out_file): data = dd.set_transcriptome_bam(data, out_file) return data # bwa mem needs phred+33 quality, so convert if it is Illumina if dd.get_quality_format(data).lower() == "illumina": logger.info("bwa mem does not support the phred+64 quality format, " "converting %s and %s to phred+33.") fastq_file = fastq.groom(fastq_file, data, in_qual="fastq-illumina") if pair_file: pair_file = fastq.groom(pair_file, data, in_qual="fastq-illumina") bwa = config_utils.get_program("bwa", data["config"]) gtf_file = dd.get_gtf_file(data) gtf_fasta = index_transcriptome(gtf_file, ref_file, data) args = " ".join(_bwa_args_from_config(data["config"])) num_cores = data["config"]["algorithm"].get("num_cores", 1) samtools = config_utils.get_program("samtools", data["config"]) cmd = ("{bwa} mem {args} -a -t {num_cores} {gtf_fasta} {fastq_file} " "{pair_file} ") with file_transaction(data, out_file) as tx_out_file: message = "Aligning %s and %s to the transcriptome." % (fastq_file, pair_file) cmd += "| " + postalign.sam_to_sortbam_cl(data, tx_out_file, name_sort=True) do.run(cmd.format(**locals()), message) data = dd.set_transcriptome_bam(data, out_file) return data def filter_multimappers(align_file, data): """ Filtering a BWA alignment file for uniquely mapped reads, from here: https://bioinformatics.stackexchange.com/questions/508/obtaining-uniquely-mapped-reads-from-bwa-mem-alignment """ config = dd.get_config(data) type_flag = "" if bam.is_bam(align_file) else "S" base, ext = os.path.splitext(align_file) out_file = base + ".unique" + ext bed_file = dd.get_variant_regions(data) or dd.get_sample_callable(data) bed_cmd = '-L {0}'.format(bed_file) if bed_file else " " if utils.file_exists(out_file): return out_file base_filter = '-F "not unmapped {paired_filter} and [XA] == null and [SA] == null and not supplementary " ' if bam.is_paired(align_file): paired_filter = "and paired and proper_pair" else: paired_filter = "" filter_string = base_filter.format(paired_filter=paired_filter) sambamba = config_utils.get_program("sambamba", config) num_cores = dd.get_num_cores(data) with file_transaction(out_file) as tx_out_file: cmd = ('{sambamba} view -h{type_flag} ' '--nthreads {num_cores} ' '-f bam {bed_cmd} ' '{filter_string} ' '{align_file} ' '> {tx_out_file}') message = "Removing multimapped reads from %s." % align_file do.run(cmd.format(**locals()), message) bam.index(out_file, config) return out_file
work_bam = dd.get_work_bam(data) base, ext = os.path.splitext(work_bam)
random_line_split
bwa.py
"""BWA (https://github.com/lh3/bwa) """ import os import signal import subprocess from bcbio.pipeline import config_utils from bcbio import bam, utils from bcbio.distributed import objectstore from bcbio.distributed.transaction import file_transaction, tx_tmpdir from bcbio.ngsalign import alignprep, novoalign, postalign, rtg from bcbio.provenance import do from bcbio.rnaseq import gtf from bcbio.variation import sentieon import bcbio.pipeline.datadict as dd from bcbio.bam import fastq from bcbio.log import logger galaxy_location_file = "bwa_index.loc" def align_bam(in_bam, ref_file, names, align_dir, data): """Perform direct alignment of an input BAM file with BWA using pipes. This avoids disk IO by piping between processes: - samtools sort of input BAM to queryname - bedtools conversion to interleaved FASTQ - bwa-mem alignment - samtools conversion to BAM - samtools sort to coordinate """ config = data["config"] out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) samtools = config_utils.get_program("samtools", config) bedtools = config_utils.get_program("bedtools", config) resources = config_utils.get_resources("samtools", config) num_cores = config["algorithm"].get("num_cores", 1) # adjust memory for samtools since used for input and output max_mem = config_utils.adjust_memory(resources.get("memory", "1G"), 3, "decrease").upper() if not utils.file_exists(out_file): with tx_tmpdir(data) as work_dir: with postalign.tobam_cl(data, out_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file): if not hla_on(data) or needs_separate_hla(data): bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-", with_hla=False) else: bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-", with_hla=True) tx_out_prefix = os.path.splitext(tx_out_file)[0] prefix1 = "%s-in1" % tx_out_prefix cmd = ("unset JAVA_HOME && " "{samtools} sort -n -l 1 -@ {num_cores} -m {max_mem} {in_bam} -T {prefix1} " "| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout " "| {bwa_cmd} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)]) data["work_bam"] = out_file hla_file = "HLA-" + out_file if needs_separate_hla(data) and not utils.file_exists(hla_file): with tx_tmpdir(data) as work_dir: with postalign.tobam_cl(data, hla_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file): bwa_cmd = _get_bwa_mem_cmd(data, hla_file, ref_file, "-", with_hla=True) tx_out_prefix = os.path.splitext(tx_out_file)[0] prefix1 = "%s-in1" % tx_out_prefix cmd = ("unset JAVA_HOME && " "{samtools} sort -n -l 1 -@ {num_cores} -m {max_mem} {in_bam} -T {prefix1} " "| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout " "| {bwa_cmd} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)]) hla_file = _align_mem_hla(fastq_file, pair_file, ref_file, hla_file, names, rg_info, data) data["hla_bam"] = hla_file return data def _get_bwa_mem_cmd(data, out_file, ref_file, fastq1, fastq2="", with_hla=False): """Perform piped bwa mem mapping potentially with alternative alleles in GRCh38 + HLA typing. Commands for HLA post-processing: base=TEST run-HLA $base.hla > $base.hla.top cat $base.hla.HLA*.gt | grep ^GT | cut -f2- > $base.hla.all rm -f $base.hla.HLA*gt rm -f $base.hla.HLA*gz """ alt_file = ref_file + ".alt" if with_hla: bwakit_dir = os.path.dirname(os.path.realpath(utils.which("run-bwamem"))) hla_base = os.path.join(utils.safe_makedir(os.path.join(os.path.dirname(out_file), "hla")), os.path.basename(out_file) + ".hla") alt_cmd = (" | {bwakit_dir}/k8 {bwakit_dir}/bwa-postalt.js -p {hla_base} {alt_file}") else: alt_cmd = "" if dd.get_aligner(data) == "sentieon-bwa": bwa_exe = "sentieon-bwa" exports = sentieon.license_export(data) else: bwa_exe = "bwa" exports = "" bwa = config_utils.get_program(bwa_exe, data["config"]) num_cores = data["config"]["algorithm"].get("num_cores", 1) bwa_resources = config_utils.get_resources("bwa", data["config"]) bwa_params = (" ".join([str(x) for x in bwa_resources.get("options", [])]) if "options" in bwa_resources else "") rg_info = novoalign.get_rg_info(data["rgnames"]) # For UMI runs, pass along consensus tags c_tags = "-C" if "umi_bam" in data else "" pairing = "-p" if not fastq2 else "" # Restrict seed occurances to 1/2 of default, manage memory usage for centromere repeats in hg38 # https://sourceforge.net/p/bio-bwa/mailman/message/31514937/ # http://ehc.ac/p/bio-bwa/mailman/message/32268544/ mem_usage = "-c 250" bwa_cmd = ("{exports}{bwa} mem {pairing} {c_tags} {mem_usage} -M -t {num_cores} {bwa_params} -R '{rg_info}' " "-v 1 {ref_file} {fastq1} {fastq2} ") return (bwa_cmd + alt_cmd).format(**locals()) def is_precollapsed_bam(data): return dd.get_umi_type(data) == "fastq_name" and not has_umi(data) def hla_on(data): return has_hla(data) and dd.get_hlacaller(data) def has_umi(data): return "umi_bam" in data def has_hla(data):
def fastq_size_output(fastq_file, tocheck): head_count = 8000000 fastq_file = objectstore.cl_input(fastq_file) gzip_cmd = "zcat {fastq_file}" if fastq_file.endswith(".gz") else "cat {fastq_file}" cmd = (utils.local_path_export() + gzip_cmd + " | head -n {head_count} | " "seqtk sample -s42 - {tocheck} | " "awk '{{if(NR%4==2) print length($1)}}' | sort | uniq -c") def fix_signal(): """Avoid spurious 'cat: write error: Broken pipe' message due to head command. Work around from: https://bitbucket.org/brodie/cram/issues/16/broken-pipe-when-heading-certain-output """ signal.signal(signal.SIGPIPE, signal.SIG_DFL) count_out = subprocess.check_output(cmd.format(**locals()), shell=True, executable="/bin/bash", preexec_fn=fix_signal).decode() if not count_out.strip(): raise IOError("Failed to check fastq file sizes with: %s" % cmd.format(**locals())) for count, size in (l.strip().split() for l in count_out.strip().split("\n")): yield count, size def _can_use_mem(fastq_file, data, read_min_size=None): """bwa-mem handle longer (> 70bp) reads with improved piping. Randomly samples 5000 reads from the first two million. Default to no piping if more than 75% of the sampled reads are small. If we've previously calculated minimum read sizes (from rtg SDF output) we can skip the formal check. """ min_size = 70 if read_min_size and read_min_size >= min_size: return True thresh = 0.75 tocheck = 5000 shorter = 0 for count, size in fastq_size_output(fastq_file, tocheck): if int(size) < min_size: shorter += int(count) return (float(shorter) / float(tocheck)) <= thresh def align_pipe(fastq_file, pair_file, ref_file, names, align_dir, data): """Perform piped alignment of fastq input files, generating sorted output BAM. """ pair_file = pair_file if pair_file else "" # back compatible -- older files were named with lane information, use sample name now if names["lane"] != dd.get_sample_name(data): out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) else: out_file = None if not out_file or not utils.file_exists(out_file): umi_ext = "-cumi" if "umi_bam" in data else "" out_file = os.path.join(align_dir, "{0}-sort{1}.bam".format(dd.get_sample_name(data), umi_ext)) qual_format = data["config"]["algorithm"].get("quality_format", "").lower() min_size = None if data.get("align_split") or fastq_file.endswith(".sdf"): if fastq_file.endswith(".sdf"): min_size = rtg.min_read_size(fastq_file) final_file = out_file out_file, data = alignprep.setup_combine(final_file, data) fastq_file, pair_file = alignprep.split_namedpipe_cls(fastq_file, pair_file, data) else: final_file = None if qual_format == "illumina": fastq_file = alignprep.fastq_convert_pipe_cl(fastq_file, data) if pair_file: pair_file = alignprep.fastq_convert_pipe_cl(pair_file, data) rg_info = novoalign.get_rg_info(names) if not utils.file_exists(out_file) and (final_file is None or not utils.file_exists(final_file)): # If we cannot do piping, use older bwa aln approach if ("bwa-mem" not in dd.get_tools_on(data) and ("bwa-mem" in dd.get_tools_off(data) or not _can_use_mem(fastq_file, data, min_size))): out_file = _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) else: if is_precollapsed_bam(data) or not hla_on(data) or needs_separate_hla(data): out_file = _align_mem(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) else: out_file = _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) data["work_bam"] = out_file # bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file # (see https://github.com/bcbio/bcbio-nextgen/issues/3069) if needs_separate_hla(data): hla_file = os.path.join(os.path.dirname(out_file), "HLA-" + os.path.basename(out_file)) hla_file = _align_mem_hla(fastq_file, pair_file, ref_file, hla_file, names, rg_info, data) data["hla_bam"] = hla_file return data def _align_mem(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths. """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" % (_get_bwa_mem_cmd(data, out_file, ref_file, fastq_file, pair_file, with_hla=False), tobam_cl)) do.run(cmd, "bwa mem alignment from fastq: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, fastq_file)]) return out_file def _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths with HLA alignments """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" % (_get_bwa_mem_cmd(data, out_file, ref_file, fastq_file, pair_file, with_hla=True), tobam_cl)) do.run(cmd, "bwa mem alignment from fastq: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, fastq_file)]) return out_file def needs_separate_hla(data): """ bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file (see https://github.com/bcbio/bcbio-nextgen/issues/3069) """ return hla_on(data) and has_umi(data) def _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform a BWA alignment using 'aln' backtrack algorithm. """ bwa = config_utils.get_program("bwa", data["config"]) config = data["config"] sai1_file = "%s_1.sai" % os.path.splitext(out_file)[0] sai2_file = "%s_2.sai" % os.path.splitext(out_file)[0] if pair_file else "" if not utils.file_exists(sai1_file): with file_transaction(data, sai1_file) as tx_sai1_file: _run_bwa_align(fastq_file, ref_file, tx_sai1_file, config) if sai2_file and not utils.file_exists(sai2_file): with file_transaction(data, sai2_file) as tx_sai2_file: _run_bwa_align(pair_file, ref_file, tx_sai2_file, config) with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): align_type = "sampe" if sai2_file else "samse" cmd = ("unset JAVA_HOME && {bwa} {align_type} -r '{rg_info}' {ref_file} {sai1_file} {sai2_file} " "{fastq_file} {pair_file} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa %s" % align_type, data) return out_file def _bwa_args_from_config(config): num_cores = config["algorithm"].get("num_cores", 1) core_flags = ["-t", str(num_cores)] if num_cores > 1 else [] return core_flags def _run_bwa_align(fastq_file, ref_file, out_file, config): aln_cl = [config_utils.get_program("bwa", config), "aln", "-n 2", "-k 2"] aln_cl += _bwa_args_from_config(config) aln_cl += [ref_file, fastq_file] cmd = "{cl} > {out_file}".format(cl=" ".join(aln_cl), out_file=out_file) do.run(cmd, "bwa aln: {f}".format(f=os.path.basename(fastq_file)), None) def index_transcriptome(gtf_file, ref_file, data): """ use a GTF file and a reference FASTA file to index the transcriptome """ gtf_fasta = gtf.gtf_to_fasta(gtf_file, ref_file) return build_bwa_index(gtf_fasta, data) def build_bwa_index(fasta_file, data): bwa = config_utils.get_program("bwa", data["config"]) cmd = "{bwa} index {fasta_file}".format(**locals()) message = "Creating transcriptome index of %s with bwa." % (fasta_file) do.run(cmd, message) return fasta_file def align_transcriptome(fastq_file, pair_file, ref_file, data): """ bwa mem with settings for aligning to the transcriptome for eXpress/RSEM/etc """ work_bam = dd.get_work_bam(data) base, ext = os.path.splitext(work_bam) out_file = base + ".transcriptome" + ext if utils.file_exists(out_file): data = dd.set_transcriptome_bam(data, out_file) return data # bwa mem needs phred+33 quality, so convert if it is Illumina if dd.get_quality_format(data).lower() == "illumina": logger.info("bwa mem does not support the phred+64 quality format, " "converting %s and %s to phred+33.") fastq_file = fastq.groom(fastq_file, data, in_qual="fastq-illumina") if pair_file: pair_file = fastq.groom(pair_file, data, in_qual="fastq-illumina") bwa = config_utils.get_program("bwa", data["config"]) gtf_file = dd.get_gtf_file(data) gtf_fasta = index_transcriptome(gtf_file, ref_file, data) args = " ".join(_bwa_args_from_config(data["config"])) num_cores = data["config"]["algorithm"].get("num_cores", 1) samtools = config_utils.get_program("samtools", data["config"]) cmd = ("{bwa} mem {args} -a -t {num_cores} {gtf_fasta} {fastq_file} " "{pair_file} ") with file_transaction(data, out_file) as tx_out_file: message = "Aligning %s and %s to the transcriptome." % (fastq_file, pair_file) cmd += "| " + postalign.sam_to_sortbam_cl(data, tx_out_file, name_sort=True) do.run(cmd.format(**locals()), message) data = dd.set_transcriptome_bam(data, out_file) return data def filter_multimappers(align_file, data): """ Filtering a BWA alignment file for uniquely mapped reads, from here: https://bioinformatics.stackexchange.com/questions/508/obtaining-uniquely-mapped-reads-from-bwa-mem-alignment """ config = dd.get_config(data) type_flag = "" if bam.is_bam(align_file) else "S" base, ext = os.path.splitext(align_file) out_file = base + ".unique" + ext bed_file = dd.get_variant_regions(data) or dd.get_sample_callable(data) bed_cmd = '-L {0}'.format(bed_file) if bed_file else " " if utils.file_exists(out_file): return out_file base_filter = '-F "not unmapped {paired_filter} and [XA] == null and [SA] == null and not supplementary " ' if bam.is_paired(align_file): paired_filter = "and paired and proper_pair" else: paired_filter = "" filter_string = base_filter.format(paired_filter=paired_filter) sambamba = config_utils.get_program("sambamba", config) num_cores = dd.get_num_cores(data) with file_transaction(out_file) as tx_out_file: cmd = ('{sambamba} view -h{type_flag} ' '--nthreads {num_cores} ' '-f bam {bed_cmd} ' '{filter_string} ' '{align_file} ' '> {tx_out_file}') message = "Removing multimapped reads from %s." % align_file do.run(cmd.format(**locals()), message) bam.index(out_file, config) return out_file
from bcbio.heterogeneity import chromhacks return len(chromhacks.get_hla_chroms(dd.get_ref_file(data))) != 0
identifier_body
bwa.py
"""BWA (https://github.com/lh3/bwa) """ import os import signal import subprocess from bcbio.pipeline import config_utils from bcbio import bam, utils from bcbio.distributed import objectstore from bcbio.distributed.transaction import file_transaction, tx_tmpdir from bcbio.ngsalign import alignprep, novoalign, postalign, rtg from bcbio.provenance import do from bcbio.rnaseq import gtf from bcbio.variation import sentieon import bcbio.pipeline.datadict as dd from bcbio.bam import fastq from bcbio.log import logger galaxy_location_file = "bwa_index.loc" def align_bam(in_bam, ref_file, names, align_dir, data): """Perform direct alignment of an input BAM file with BWA using pipes. This avoids disk IO by piping between processes: - samtools sort of input BAM to queryname - bedtools conversion to interleaved FASTQ - bwa-mem alignment - samtools conversion to BAM - samtools sort to coordinate """ config = data["config"] out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) samtools = config_utils.get_program("samtools", config) bedtools = config_utils.get_program("bedtools", config) resources = config_utils.get_resources("samtools", config) num_cores = config["algorithm"].get("num_cores", 1) # adjust memory for samtools since used for input and output max_mem = config_utils.adjust_memory(resources.get("memory", "1G"), 3, "decrease").upper() if not utils.file_exists(out_file): with tx_tmpdir(data) as work_dir: with postalign.tobam_cl(data, out_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file): if not hla_on(data) or needs_separate_hla(data): bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-", with_hla=False) else: bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-", with_hla=True) tx_out_prefix = os.path.splitext(tx_out_file)[0] prefix1 = "%s-in1" % tx_out_prefix cmd = ("unset JAVA_HOME && " "{samtools} sort -n -l 1 -@ {num_cores} -m {max_mem} {in_bam} -T {prefix1} " "| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout " "| {bwa_cmd} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)]) data["work_bam"] = out_file hla_file = "HLA-" + out_file if needs_separate_hla(data) and not utils.file_exists(hla_file): with tx_tmpdir(data) as work_dir: with postalign.tobam_cl(data, hla_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file): bwa_cmd = _get_bwa_mem_cmd(data, hla_file, ref_file, "-", with_hla=True) tx_out_prefix = os.path.splitext(tx_out_file)[0] prefix1 = "%s-in1" % tx_out_prefix cmd = ("unset JAVA_HOME && " "{samtools} sort -n -l 1 -@ {num_cores} -m {max_mem} {in_bam} -T {prefix1} " "| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout " "| {bwa_cmd} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)]) hla_file = _align_mem_hla(fastq_file, pair_file, ref_file, hla_file, names, rg_info, data) data["hla_bam"] = hla_file return data def _get_bwa_mem_cmd(data, out_file, ref_file, fastq1, fastq2="", with_hla=False): """Perform piped bwa mem mapping potentially with alternative alleles in GRCh38 + HLA typing. Commands for HLA post-processing: base=TEST run-HLA $base.hla > $base.hla.top cat $base.hla.HLA*.gt | grep ^GT | cut -f2- > $base.hla.all rm -f $base.hla.HLA*gt rm -f $base.hla.HLA*gz """ alt_file = ref_file + ".alt" if with_hla: bwakit_dir = os.path.dirname(os.path.realpath(utils.which("run-bwamem"))) hla_base = os.path.join(utils.safe_makedir(os.path.join(os.path.dirname(out_file), "hla")), os.path.basename(out_file) + ".hla") alt_cmd = (" | {bwakit_dir}/k8 {bwakit_dir}/bwa-postalt.js -p {hla_base} {alt_file}") else: alt_cmd = "" if dd.get_aligner(data) == "sentieon-bwa": bwa_exe = "sentieon-bwa" exports = sentieon.license_export(data) else: bwa_exe = "bwa" exports = "" bwa = config_utils.get_program(bwa_exe, data["config"]) num_cores = data["config"]["algorithm"].get("num_cores", 1) bwa_resources = config_utils.get_resources("bwa", data["config"]) bwa_params = (" ".join([str(x) for x in bwa_resources.get("options", [])]) if "options" in bwa_resources else "") rg_info = novoalign.get_rg_info(data["rgnames"]) # For UMI runs, pass along consensus tags c_tags = "-C" if "umi_bam" in data else "" pairing = "-p" if not fastq2 else "" # Restrict seed occurances to 1/2 of default, manage memory usage for centromere repeats in hg38 # https://sourceforge.net/p/bio-bwa/mailman/message/31514937/ # http://ehc.ac/p/bio-bwa/mailman/message/32268544/ mem_usage = "-c 250" bwa_cmd = ("{exports}{bwa} mem {pairing} {c_tags} {mem_usage} -M -t {num_cores} {bwa_params} -R '{rg_info}' " "-v 1 {ref_file} {fastq1} {fastq2} ") return (bwa_cmd + alt_cmd).format(**locals()) def is_precollapsed_bam(data): return dd.get_umi_type(data) == "fastq_name" and not has_umi(data) def hla_on(data): return has_hla(data) and dd.get_hlacaller(data) def has_umi(data): return "umi_bam" in data def has_hla(data): from bcbio.heterogeneity import chromhacks return len(chromhacks.get_hla_chroms(dd.get_ref_file(data))) != 0 def fastq_size_output(fastq_file, tocheck): head_count = 8000000 fastq_file = objectstore.cl_input(fastq_file) gzip_cmd = "zcat {fastq_file}" if fastq_file.endswith(".gz") else "cat {fastq_file}" cmd = (utils.local_path_export() + gzip_cmd + " | head -n {head_count} | " "seqtk sample -s42 - {tocheck} | " "awk '{{if(NR%4==2) print length($1)}}' | sort | uniq -c") def fix_signal(): """Avoid spurious 'cat: write error: Broken pipe' message due to head command. Work around from: https://bitbucket.org/brodie/cram/issues/16/broken-pipe-when-heading-certain-output """ signal.signal(signal.SIGPIPE, signal.SIG_DFL) count_out = subprocess.check_output(cmd.format(**locals()), shell=True, executable="/bin/bash", preexec_fn=fix_signal).decode() if not count_out.strip(): raise IOError("Failed to check fastq file sizes with: %s" % cmd.format(**locals())) for count, size in (l.strip().split() for l in count_out.strip().split("\n")): yield count, size def _can_use_mem(fastq_file, data, read_min_size=None): """bwa-mem handle longer (> 70bp) reads with improved piping. Randomly samples 5000 reads from the first two million. Default to no piping if more than 75% of the sampled reads are small. If we've previously calculated minimum read sizes (from rtg SDF output) we can skip the formal check. """ min_size = 70 if read_min_size and read_min_size >= min_size: return True thresh = 0.75 tocheck = 5000 shorter = 0 for count, size in fastq_size_output(fastq_file, tocheck): if int(size) < min_size: shorter += int(count) return (float(shorter) / float(tocheck)) <= thresh def align_pipe(fastq_file, pair_file, ref_file, names, align_dir, data): """Perform piped alignment of fastq input files, generating sorted output BAM. """ pair_file = pair_file if pair_file else "" # back compatible -- older files were named with lane information, use sample name now if names["lane"] != dd.get_sample_name(data): out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) else: out_file = None if not out_file or not utils.file_exists(out_file): umi_ext = "-cumi" if "umi_bam" in data else "" out_file = os.path.join(align_dir, "{0}-sort{1}.bam".format(dd.get_sample_name(data), umi_ext)) qual_format = data["config"]["algorithm"].get("quality_format", "").lower() min_size = None if data.get("align_split") or fastq_file.endswith(".sdf"): if fastq_file.endswith(".sdf"): min_size = rtg.min_read_size(fastq_file) final_file = out_file out_file, data = alignprep.setup_combine(final_file, data) fastq_file, pair_file = alignprep.split_namedpipe_cls(fastq_file, pair_file, data) else: final_file = None if qual_format == "illumina": fastq_file = alignprep.fastq_convert_pipe_cl(fastq_file, data) if pair_file: pair_file = alignprep.fastq_convert_pipe_cl(pair_file, data) rg_info = novoalign.get_rg_info(names) if not utils.file_exists(out_file) and (final_file is None or not utils.file_exists(final_file)): # If we cannot do piping, use older bwa aln approach if ("bwa-mem" not in dd.get_tools_on(data) and ("bwa-mem" in dd.get_tools_off(data) or not _can_use_mem(fastq_file, data, min_size))): out_file = _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) else: if is_precollapsed_bam(data) or not hla_on(data) or needs_separate_hla(data): out_file = _align_mem(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) else: out_file = _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) data["work_bam"] = out_file # bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file # (see https://github.com/bcbio/bcbio-nextgen/issues/3069) if needs_separate_hla(data): hla_file = os.path.join(os.path.dirname(out_file), "HLA-" + os.path.basename(out_file)) hla_file = _align_mem_hla(fastq_file, pair_file, ref_file, hla_file, names, rg_info, data) data["hla_bam"] = hla_file return data def _align_mem(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths. """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" % (_get_bwa_mem_cmd(data, out_file, ref_file, fastq_file, pair_file, with_hla=False), tobam_cl)) do.run(cmd, "bwa mem alignment from fastq: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, fastq_file)]) return out_file def _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths with HLA alignments """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" % (_get_bwa_mem_cmd(data, out_file, ref_file, fastq_file, pair_file, with_hla=True), tobam_cl)) do.run(cmd, "bwa mem alignment from fastq: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, fastq_file)]) return out_file def
(data): """ bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file (see https://github.com/bcbio/bcbio-nextgen/issues/3069) """ return hla_on(data) and has_umi(data) def _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform a BWA alignment using 'aln' backtrack algorithm. """ bwa = config_utils.get_program("bwa", data["config"]) config = data["config"] sai1_file = "%s_1.sai" % os.path.splitext(out_file)[0] sai2_file = "%s_2.sai" % os.path.splitext(out_file)[0] if pair_file else "" if not utils.file_exists(sai1_file): with file_transaction(data, sai1_file) as tx_sai1_file: _run_bwa_align(fastq_file, ref_file, tx_sai1_file, config) if sai2_file and not utils.file_exists(sai2_file): with file_transaction(data, sai2_file) as tx_sai2_file: _run_bwa_align(pair_file, ref_file, tx_sai2_file, config) with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): align_type = "sampe" if sai2_file else "samse" cmd = ("unset JAVA_HOME && {bwa} {align_type} -r '{rg_info}' {ref_file} {sai1_file} {sai2_file} " "{fastq_file} {pair_file} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa %s" % align_type, data) return out_file def _bwa_args_from_config(config): num_cores = config["algorithm"].get("num_cores", 1) core_flags = ["-t", str(num_cores)] if num_cores > 1 else [] return core_flags def _run_bwa_align(fastq_file, ref_file, out_file, config): aln_cl = [config_utils.get_program("bwa", config), "aln", "-n 2", "-k 2"] aln_cl += _bwa_args_from_config(config) aln_cl += [ref_file, fastq_file] cmd = "{cl} > {out_file}".format(cl=" ".join(aln_cl), out_file=out_file) do.run(cmd, "bwa aln: {f}".format(f=os.path.basename(fastq_file)), None) def index_transcriptome(gtf_file, ref_file, data): """ use a GTF file and a reference FASTA file to index the transcriptome """ gtf_fasta = gtf.gtf_to_fasta(gtf_file, ref_file) return build_bwa_index(gtf_fasta, data) def build_bwa_index(fasta_file, data): bwa = config_utils.get_program("bwa", data["config"]) cmd = "{bwa} index {fasta_file}".format(**locals()) message = "Creating transcriptome index of %s with bwa." % (fasta_file) do.run(cmd, message) return fasta_file def align_transcriptome(fastq_file, pair_file, ref_file, data): """ bwa mem with settings for aligning to the transcriptome for eXpress/RSEM/etc """ work_bam = dd.get_work_bam(data) base, ext = os.path.splitext(work_bam) out_file = base + ".transcriptome" + ext if utils.file_exists(out_file): data = dd.set_transcriptome_bam(data, out_file) return data # bwa mem needs phred+33 quality, so convert if it is Illumina if dd.get_quality_format(data).lower() == "illumina": logger.info("bwa mem does not support the phred+64 quality format, " "converting %s and %s to phred+33.") fastq_file = fastq.groom(fastq_file, data, in_qual="fastq-illumina") if pair_file: pair_file = fastq.groom(pair_file, data, in_qual="fastq-illumina") bwa = config_utils.get_program("bwa", data["config"]) gtf_file = dd.get_gtf_file(data) gtf_fasta = index_transcriptome(gtf_file, ref_file, data) args = " ".join(_bwa_args_from_config(data["config"])) num_cores = data["config"]["algorithm"].get("num_cores", 1) samtools = config_utils.get_program("samtools", data["config"]) cmd = ("{bwa} mem {args} -a -t {num_cores} {gtf_fasta} {fastq_file} " "{pair_file} ") with file_transaction(data, out_file) as tx_out_file: message = "Aligning %s and %s to the transcriptome." % (fastq_file, pair_file) cmd += "| " + postalign.sam_to_sortbam_cl(data, tx_out_file, name_sort=True) do.run(cmd.format(**locals()), message) data = dd.set_transcriptome_bam(data, out_file) return data def filter_multimappers(align_file, data): """ Filtering a BWA alignment file for uniquely mapped reads, from here: https://bioinformatics.stackexchange.com/questions/508/obtaining-uniquely-mapped-reads-from-bwa-mem-alignment """ config = dd.get_config(data) type_flag = "" if bam.is_bam(align_file) else "S" base, ext = os.path.splitext(align_file) out_file = base + ".unique" + ext bed_file = dd.get_variant_regions(data) or dd.get_sample_callable(data) bed_cmd = '-L {0}'.format(bed_file) if bed_file else " " if utils.file_exists(out_file): return out_file base_filter = '-F "not unmapped {paired_filter} and [XA] == null and [SA] == null and not supplementary " ' if bam.is_paired(align_file): paired_filter = "and paired and proper_pair" else: paired_filter = "" filter_string = base_filter.format(paired_filter=paired_filter) sambamba = config_utils.get_program("sambamba", config) num_cores = dd.get_num_cores(data) with file_transaction(out_file) as tx_out_file: cmd = ('{sambamba} view -h{type_flag} ' '--nthreads {num_cores} ' '-f bam {bed_cmd} ' '{filter_string} ' '{align_file} ' '> {tx_out_file}') message = "Removing multimapped reads from %s." % align_file do.run(cmd.format(**locals()), message) bam.index(out_file, config) return out_file
needs_separate_hla
identifier_name
bwa.py
"""BWA (https://github.com/lh3/bwa) """ import os import signal import subprocess from bcbio.pipeline import config_utils from bcbio import bam, utils from bcbio.distributed import objectstore from bcbio.distributed.transaction import file_transaction, tx_tmpdir from bcbio.ngsalign import alignprep, novoalign, postalign, rtg from bcbio.provenance import do from bcbio.rnaseq import gtf from bcbio.variation import sentieon import bcbio.pipeline.datadict as dd from bcbio.bam import fastq from bcbio.log import logger galaxy_location_file = "bwa_index.loc" def align_bam(in_bam, ref_file, names, align_dir, data): """Perform direct alignment of an input BAM file with BWA using pipes. This avoids disk IO by piping between processes: - samtools sort of input BAM to queryname - bedtools conversion to interleaved FASTQ - bwa-mem alignment - samtools conversion to BAM - samtools sort to coordinate """ config = data["config"] out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) samtools = config_utils.get_program("samtools", config) bedtools = config_utils.get_program("bedtools", config) resources = config_utils.get_resources("samtools", config) num_cores = config["algorithm"].get("num_cores", 1) # adjust memory for samtools since used for input and output max_mem = config_utils.adjust_memory(resources.get("memory", "1G"), 3, "decrease").upper() if not utils.file_exists(out_file): with tx_tmpdir(data) as work_dir: with postalign.tobam_cl(data, out_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file): if not hla_on(data) or needs_separate_hla(data): bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-", with_hla=False) else: bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-", with_hla=True) tx_out_prefix = os.path.splitext(tx_out_file)[0] prefix1 = "%s-in1" % tx_out_prefix cmd = ("unset JAVA_HOME && " "{samtools} sort -n -l 1 -@ {num_cores} -m {max_mem} {in_bam} -T {prefix1} " "| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout " "| {bwa_cmd} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)]) data["work_bam"] = out_file hla_file = "HLA-" + out_file if needs_separate_hla(data) and not utils.file_exists(hla_file): with tx_tmpdir(data) as work_dir: with postalign.tobam_cl(data, hla_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file): bwa_cmd = _get_bwa_mem_cmd(data, hla_file, ref_file, "-", with_hla=True) tx_out_prefix = os.path.splitext(tx_out_file)[0] prefix1 = "%s-in1" % tx_out_prefix cmd = ("unset JAVA_HOME && " "{samtools} sort -n -l 1 -@ {num_cores} -m {max_mem} {in_bam} -T {prefix1} " "| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout " "| {bwa_cmd} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)]) hla_file = _align_mem_hla(fastq_file, pair_file, ref_file, hla_file, names, rg_info, data) data["hla_bam"] = hla_file return data def _get_bwa_mem_cmd(data, out_file, ref_file, fastq1, fastq2="", with_hla=False): """Perform piped bwa mem mapping potentially with alternative alleles in GRCh38 + HLA typing. Commands for HLA post-processing: base=TEST run-HLA $base.hla > $base.hla.top cat $base.hla.HLA*.gt | grep ^GT | cut -f2- > $base.hla.all rm -f $base.hla.HLA*gt rm -f $base.hla.HLA*gz """ alt_file = ref_file + ".alt" if with_hla: bwakit_dir = os.path.dirname(os.path.realpath(utils.which("run-bwamem"))) hla_base = os.path.join(utils.safe_makedir(os.path.join(os.path.dirname(out_file), "hla")), os.path.basename(out_file) + ".hla") alt_cmd = (" | {bwakit_dir}/k8 {bwakit_dir}/bwa-postalt.js -p {hla_base} {alt_file}") else: alt_cmd = "" if dd.get_aligner(data) == "sentieon-bwa": bwa_exe = "sentieon-bwa" exports = sentieon.license_export(data) else: bwa_exe = "bwa" exports = "" bwa = config_utils.get_program(bwa_exe, data["config"]) num_cores = data["config"]["algorithm"].get("num_cores", 1) bwa_resources = config_utils.get_resources("bwa", data["config"]) bwa_params = (" ".join([str(x) for x in bwa_resources.get("options", [])]) if "options" in bwa_resources else "") rg_info = novoalign.get_rg_info(data["rgnames"]) # For UMI runs, pass along consensus tags c_tags = "-C" if "umi_bam" in data else "" pairing = "-p" if not fastq2 else "" # Restrict seed occurances to 1/2 of default, manage memory usage for centromere repeats in hg38 # https://sourceforge.net/p/bio-bwa/mailman/message/31514937/ # http://ehc.ac/p/bio-bwa/mailman/message/32268544/ mem_usage = "-c 250" bwa_cmd = ("{exports}{bwa} mem {pairing} {c_tags} {mem_usage} -M -t {num_cores} {bwa_params} -R '{rg_info}' " "-v 1 {ref_file} {fastq1} {fastq2} ") return (bwa_cmd + alt_cmd).format(**locals()) def is_precollapsed_bam(data): return dd.get_umi_type(data) == "fastq_name" and not has_umi(data) def hla_on(data): return has_hla(data) and dd.get_hlacaller(data) def has_umi(data): return "umi_bam" in data def has_hla(data): from bcbio.heterogeneity import chromhacks return len(chromhacks.get_hla_chroms(dd.get_ref_file(data))) != 0 def fastq_size_output(fastq_file, tocheck): head_count = 8000000 fastq_file = objectstore.cl_input(fastq_file) gzip_cmd = "zcat {fastq_file}" if fastq_file.endswith(".gz") else "cat {fastq_file}" cmd = (utils.local_path_export() + gzip_cmd + " | head -n {head_count} | " "seqtk sample -s42 - {tocheck} | " "awk '{{if(NR%4==2) print length($1)}}' | sort | uniq -c") def fix_signal(): """Avoid spurious 'cat: write error: Broken pipe' message due to head command. Work around from: https://bitbucket.org/brodie/cram/issues/16/broken-pipe-when-heading-certain-output """ signal.signal(signal.SIGPIPE, signal.SIG_DFL) count_out = subprocess.check_output(cmd.format(**locals()), shell=True, executable="/bin/bash", preexec_fn=fix_signal).decode() if not count_out.strip(): raise IOError("Failed to check fastq file sizes with: %s" % cmd.format(**locals())) for count, size in (l.strip().split() for l in count_out.strip().split("\n")): yield count, size def _can_use_mem(fastq_file, data, read_min_size=None): """bwa-mem handle longer (> 70bp) reads with improved piping. Randomly samples 5000 reads from the first two million. Default to no piping if more than 75% of the sampled reads are small. If we've previously calculated minimum read sizes (from rtg SDF output) we can skip the formal check. """ min_size = 70 if read_min_size and read_min_size >= min_size: return True thresh = 0.75 tocheck = 5000 shorter = 0 for count, size in fastq_size_output(fastq_file, tocheck): if int(size) < min_size: shorter += int(count) return (float(shorter) / float(tocheck)) <= thresh def align_pipe(fastq_file, pair_file, ref_file, names, align_dir, data): """Perform piped alignment of fastq input files, generating sorted output BAM. """ pair_file = pair_file if pair_file else "" # back compatible -- older files were named with lane information, use sample name now if names["lane"] != dd.get_sample_name(data): out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) else: out_file = None if not out_file or not utils.file_exists(out_file): umi_ext = "-cumi" if "umi_bam" in data else "" out_file = os.path.join(align_dir, "{0}-sort{1}.bam".format(dd.get_sample_name(data), umi_ext)) qual_format = data["config"]["algorithm"].get("quality_format", "").lower() min_size = None if data.get("align_split") or fastq_file.endswith(".sdf"): if fastq_file.endswith(".sdf"): min_size = rtg.min_read_size(fastq_file) final_file = out_file out_file, data = alignprep.setup_combine(final_file, data) fastq_file, pair_file = alignprep.split_namedpipe_cls(fastq_file, pair_file, data) else: final_file = None if qual_format == "illumina":
rg_info = novoalign.get_rg_info(names) if not utils.file_exists(out_file) and (final_file is None or not utils.file_exists(final_file)): # If we cannot do piping, use older bwa aln approach if ("bwa-mem" not in dd.get_tools_on(data) and ("bwa-mem" in dd.get_tools_off(data) or not _can_use_mem(fastq_file, data, min_size))): out_file = _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) else: if is_precollapsed_bam(data) or not hla_on(data) or needs_separate_hla(data): out_file = _align_mem(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) else: out_file = _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data) data["work_bam"] = out_file # bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file # (see https://github.com/bcbio/bcbio-nextgen/issues/3069) if needs_separate_hla(data): hla_file = os.path.join(os.path.dirname(out_file), "HLA-" + os.path.basename(out_file)) hla_file = _align_mem_hla(fastq_file, pair_file, ref_file, hla_file, names, rg_info, data) data["hla_bam"] = hla_file return data def _align_mem(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths. """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" % (_get_bwa_mem_cmd(data, out_file, ref_file, fastq_file, pair_file, with_hla=False), tobam_cl)) do.run(cmd, "bwa mem alignment from fastq: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, fastq_file)]) return out_file def _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths with HLA alignments """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" % (_get_bwa_mem_cmd(data, out_file, ref_file, fastq_file, pair_file, with_hla=True), tobam_cl)) do.run(cmd, "bwa mem alignment from fastq: %s" % names["sample"], None, [do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, fastq_file)]) return out_file def needs_separate_hla(data): """ bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file (see https://github.com/bcbio/bcbio-nextgen/issues/3069) """ return hla_on(data) and has_umi(data) def _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform a BWA alignment using 'aln' backtrack algorithm. """ bwa = config_utils.get_program("bwa", data["config"]) config = data["config"] sai1_file = "%s_1.sai" % os.path.splitext(out_file)[0] sai2_file = "%s_2.sai" % os.path.splitext(out_file)[0] if pair_file else "" if not utils.file_exists(sai1_file): with file_transaction(data, sai1_file) as tx_sai1_file: _run_bwa_align(fastq_file, ref_file, tx_sai1_file, config) if sai2_file and not utils.file_exists(sai2_file): with file_transaction(data, sai2_file) as tx_sai2_file: _run_bwa_align(pair_file, ref_file, tx_sai2_file, config) with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): align_type = "sampe" if sai2_file else "samse" cmd = ("unset JAVA_HOME && {bwa} {align_type} -r '{rg_info}' {ref_file} {sai1_file} {sai2_file} " "{fastq_file} {pair_file} | ") cmd = cmd.format(**locals()) + tobam_cl do.run(cmd, "bwa %s" % align_type, data) return out_file def _bwa_args_from_config(config): num_cores = config["algorithm"].get("num_cores", 1) core_flags = ["-t", str(num_cores)] if num_cores > 1 else [] return core_flags def _run_bwa_align(fastq_file, ref_file, out_file, config): aln_cl = [config_utils.get_program("bwa", config), "aln", "-n 2", "-k 2"] aln_cl += _bwa_args_from_config(config) aln_cl += [ref_file, fastq_file] cmd = "{cl} > {out_file}".format(cl=" ".join(aln_cl), out_file=out_file) do.run(cmd, "bwa aln: {f}".format(f=os.path.basename(fastq_file)), None) def index_transcriptome(gtf_file, ref_file, data): """ use a GTF file and a reference FASTA file to index the transcriptome """ gtf_fasta = gtf.gtf_to_fasta(gtf_file, ref_file) return build_bwa_index(gtf_fasta, data) def build_bwa_index(fasta_file, data): bwa = config_utils.get_program("bwa", data["config"]) cmd = "{bwa} index {fasta_file}".format(**locals()) message = "Creating transcriptome index of %s with bwa." % (fasta_file) do.run(cmd, message) return fasta_file def align_transcriptome(fastq_file, pair_file, ref_file, data): """ bwa mem with settings for aligning to the transcriptome for eXpress/RSEM/etc """ work_bam = dd.get_work_bam(data) base, ext = os.path.splitext(work_bam) out_file = base + ".transcriptome" + ext if utils.file_exists(out_file): data = dd.set_transcriptome_bam(data, out_file) return data # bwa mem needs phred+33 quality, so convert if it is Illumina if dd.get_quality_format(data).lower() == "illumina": logger.info("bwa mem does not support the phred+64 quality format, " "converting %s and %s to phred+33.") fastq_file = fastq.groom(fastq_file, data, in_qual="fastq-illumina") if pair_file: pair_file = fastq.groom(pair_file, data, in_qual="fastq-illumina") bwa = config_utils.get_program("bwa", data["config"]) gtf_file = dd.get_gtf_file(data) gtf_fasta = index_transcriptome(gtf_file, ref_file, data) args = " ".join(_bwa_args_from_config(data["config"])) num_cores = data["config"]["algorithm"].get("num_cores", 1) samtools = config_utils.get_program("samtools", data["config"]) cmd = ("{bwa} mem {args} -a -t {num_cores} {gtf_fasta} {fastq_file} " "{pair_file} ") with file_transaction(data, out_file) as tx_out_file: message = "Aligning %s and %s to the transcriptome." % (fastq_file, pair_file) cmd += "| " + postalign.sam_to_sortbam_cl(data, tx_out_file, name_sort=True) do.run(cmd.format(**locals()), message) data = dd.set_transcriptome_bam(data, out_file) return data def filter_multimappers(align_file, data): """ Filtering a BWA alignment file for uniquely mapped reads, from here: https://bioinformatics.stackexchange.com/questions/508/obtaining-uniquely-mapped-reads-from-bwa-mem-alignment """ config = dd.get_config(data) type_flag = "" if bam.is_bam(align_file) else "S" base, ext = os.path.splitext(align_file) out_file = base + ".unique" + ext bed_file = dd.get_variant_regions(data) or dd.get_sample_callable(data) bed_cmd = '-L {0}'.format(bed_file) if bed_file else " " if utils.file_exists(out_file): return out_file base_filter = '-F "not unmapped {paired_filter} and [XA] == null and [SA] == null and not supplementary " ' if bam.is_paired(align_file): paired_filter = "and paired and proper_pair" else: paired_filter = "" filter_string = base_filter.format(paired_filter=paired_filter) sambamba = config_utils.get_program("sambamba", config) num_cores = dd.get_num_cores(data) with file_transaction(out_file) as tx_out_file: cmd = ('{sambamba} view -h{type_flag} ' '--nthreads {num_cores} ' '-f bam {bed_cmd} ' '{filter_string} ' '{align_file} ' '> {tx_out_file}') message = "Removing multimapped reads from %s." % align_file do.run(cmd.format(**locals()), message) bam.index(out_file, config) return out_file
fastq_file = alignprep.fastq_convert_pipe_cl(fastq_file, data) if pair_file: pair_file = alignprep.fastq_convert_pipe_cl(pair_file, data)
conditional_block
auth.service.ts
module op.common { 'use strict'; export interface IAuthService { register: (user: IUser) => ng.IPromise<string>; login: (email: string, password: string) => ng.IPromise<string>; logout: () => void; } class AuthService implements IAuthService { /* @ngInject */ constructor(public AUTH_URL: string, public $window: ng.IWindowService, public $http: ng.IHttpService, public $q: ng.IQService, public SessionService: op.common.ISessionService)
register(user: IUser): ng.IPromise<string> { var deferred: ng.IDeferred<string> = this.$q.defer(); var requestConfig: ng.IRequestConfig = { method: 'POST', url: this.AUTH_URL + '/register', headers: { 'Content-Type': 'application/json' }, data: user }; this.$http(requestConfig) .success((response: string) => { deferred.resolve(response); }) .error((response: string) => deferred.reject(response)); return deferred.promise; } login(email: string, password: string): ng.IPromise<string> { var deferred: ng.IDeferred<string> = this.$q.defer(); var auth: string = this.$window.btoa(email + ':' + password); var requestConfig: ng.IRequestConfig = { method: 'POST', url: this.AUTH_URL + '/login', headers: { 'Authorization': 'Basic ' + auth } }; this.$http(requestConfig) .success((response: IToken) => { var token: string = response.token; this.SessionService.setUser(response); deferred.resolve(token); }) .error((response: string) => deferred.reject(response)); return deferred.promise; } logout(): void { this.SessionService.unsetUser(); } } // register LoginService angular.module('op.common') .service('AuthService', AuthService); }
{ }
identifier_body
auth.service.ts
module op.common { 'use strict'; export interface IAuthService { register: (user: IUser) => ng.IPromise<string>; login: (email: string, password: string) => ng.IPromise<string>; logout: () => void; } class AuthService implements IAuthService { /* @ngInject */ constructor(public AUTH_URL: string, public $window: ng.IWindowService, public $http: ng.IHttpService, public $q: ng.IQService, public SessionService: op.common.ISessionService) { } register(user: IUser): ng.IPromise<string> { var deferred: ng.IDeferred<string> = this.$q.defer(); var requestConfig: ng.IRequestConfig = { method: 'POST', url: this.AUTH_URL + '/register', headers: { 'Content-Type': 'application/json' }, data: user }; this.$http(requestConfig) .success((response: string) => { deferred.resolve(response); }) .error((response: string) => deferred.reject(response)); return deferred.promise; } login(email: string, password: string): ng.IPromise<string> { var deferred: ng.IDeferred<string> = this.$q.defer(); var auth: string = this.$window.btoa(email + ':' + password); var requestConfig: ng.IRequestConfig = { method: 'POST', url: this.AUTH_URL + '/login', headers: { 'Authorization': 'Basic ' + auth } }; this.$http(requestConfig) .success((response: IToken) => { var token: string = response.token; this.SessionService.setUser(response); deferred.resolve(token); }) .error((response: string) => deferred.reject(response)); return deferred.promise; } logout(): void { this.SessionService.unsetUser(); }
} // register LoginService angular.module('op.common') .service('AuthService', AuthService); }
random_line_split
auth.service.ts
module op.common { 'use strict'; export interface IAuthService { register: (user: IUser) => ng.IPromise<string>; login: (email: string, password: string) => ng.IPromise<string>; logout: () => void; } class AuthService implements IAuthService { /* @ngInject */
(public AUTH_URL: string, public $window: ng.IWindowService, public $http: ng.IHttpService, public $q: ng.IQService, public SessionService: op.common.ISessionService) { } register(user: IUser): ng.IPromise<string> { var deferred: ng.IDeferred<string> = this.$q.defer(); var requestConfig: ng.IRequestConfig = { method: 'POST', url: this.AUTH_URL + '/register', headers: { 'Content-Type': 'application/json' }, data: user }; this.$http(requestConfig) .success((response: string) => { deferred.resolve(response); }) .error((response: string) => deferred.reject(response)); return deferred.promise; } login(email: string, password: string): ng.IPromise<string> { var deferred: ng.IDeferred<string> = this.$q.defer(); var auth: string = this.$window.btoa(email + ':' + password); var requestConfig: ng.IRequestConfig = { method: 'POST', url: this.AUTH_URL + '/login', headers: { 'Authorization': 'Basic ' + auth } }; this.$http(requestConfig) .success((response: IToken) => { var token: string = response.token; this.SessionService.setUser(response); deferred.resolve(token); }) .error((response: string) => deferred.reject(response)); return deferred.promise; } logout(): void { this.SessionService.unsetUser(); } } // register LoginService angular.module('op.common') .service('AuthService', AuthService); }
constructor
identifier_name
services.py
# Copyright 2016 IBM Corp. # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.common import logging from rally import consts from rally.plugins.openstack import scenario from rally.plugins.openstack.scenarios.nova import utils from rally.task import validation LOG = logging.getLogger(__name__) class NovaServices(utils.NovaScenario):
"""Benchmark scenarios for Nova agents.""" @validation.required_services(consts.Service.NOVA) @validation.required_openstack(admin=True) @scenario.configure() def list_services(self, host=None, binary=None): """List all nova services. Measure the "nova service-list" command performance. :param host: List nova services on host :param binary: List nova services matching given binary """ self._list_services(host, binary)
identifier_body
services.py
# Copyright 2016 IBM Corp. # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.common import logging from rally import consts from rally.plugins.openstack import scenario from rally.plugins.openstack.scenarios.nova import utils from rally.task import validation LOG = logging.getLogger(__name__) class
(utils.NovaScenario): """Benchmark scenarios for Nova agents.""" @validation.required_services(consts.Service.NOVA) @validation.required_openstack(admin=True) @scenario.configure() def list_services(self, host=None, binary=None): """List all nova services. Measure the "nova service-list" command performance. :param host: List nova services on host :param binary: List nova services matching given binary """ self._list_services(host, binary)
NovaServices
identifier_name
services.py
# Copyright 2016 IBM Corp. # 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.common import logging from rally import consts from rally.plugins.openstack import scenario from rally.plugins.openstack.scenarios.nova import utils from rally.task import validation LOG = logging.getLogger(__name__) class NovaServices(utils.NovaScenario): """Benchmark scenarios for Nova agents.""" @validation.required_services(consts.Service.NOVA) @validation.required_openstack(admin=True) @scenario.configure() def list_services(self, host=None, binary=None): """List all nova services. Measure the "nova service-list" command performance.
:param host: List nova services on host :param binary: List nova services matching given binary """ self._list_services(host, binary)
random_line_split
jukebox_mpg123.py
# -*- coding: UTF-8 -*- from django.core.management.base import BaseCommand from optparse import make_option import daemon import daemon.pidfile from signal import SIGTSTP, SIGTERM, SIGABRT import sys, os, subprocess import time from jukebox.jukebox_core import api class Command(BaseCommand): daemon = None proc = None mpg123 = None option_list = BaseCommand.option_list + ( make_option( "--start", action="store_true", dest="start", help="Start mpg123 playback" ), make_option( "--stop", action="store_true", dest="stop", help="Stop mpg123 playback" ), ) def handle(self, *args, **options): # check if mpg123 is available fin, fout = os.popen4(["which", "mpg123"]) self.mpg123 = fout.read().replace("\n", "") if not len(self.mpg123): print "mpg123 is not installed" return pidFile = os.path.dirname( os.path.abspath(__file__) ) + "/../../daemon.pid" if options["start"]: if os.path.exists(pidFile): print "Daemon already running, pid file exists" return pid = daemon.pidfile.TimeoutPIDLockFile( pidFile, 10 ) print "Starting jukebox_mpg123 daemon..." self.daemon = daemon.DaemonContext( uid=os.getuid(), gid=os.getgid(), pidfile=pid, working_directory=os.getcwd(), detach_process=True, signal_map={ SIGTSTP: self.shutdown, SIGABRT: self.skipSong } ) with self.daemon: print "Register player" pid = int(open(pidFile).read()) players_api = api.players() players_api.add(pid) self.play() elif options["stop"]: if not os.path.exists(pidFile): print "Daemon not running" return print "Stopping daemon..." pid = int(open(pidFile).read()) os.kill(pid, SIGTSTP) print "Unregister player " + str(pid) players_api = api.players() players_api.remove(pid) else: self.print_help("jukebox_mpg123", "help") def play(self): songs_api = api.songs() while 1: if self.proc is None: song_instance = songs_api.getNextSong() if not os.path.exists(song_instance.Filename): print "File not found: %s" % song_instance.Filename continue print "Playing " + song_instance.Filename self.proc = subprocess.Popen( [self.mpg123, song_instance.Filename] ) else: if not self.proc.poll() is None: self.proc = None time.sleep(0.5) def
(self, signal, action): if not self.proc is None: os.kill(self.proc.pid, SIGTERM) if not self.daemon is None: self.daemon.close() sys.exit(0) def skipSong(self, signal, action): if not self.proc is None: os.kill(self.proc.pid, SIGTERM)
shutdown
identifier_name
jukebox_mpg123.py
# -*- coding: UTF-8 -*- from django.core.management.base import BaseCommand from optparse import make_option import daemon import daemon.pidfile from signal import SIGTSTP, SIGTERM, SIGABRT import sys, os, subprocess import time from jukebox.jukebox_core import api class Command(BaseCommand): daemon = None proc = None mpg123 = None option_list = BaseCommand.option_list + ( make_option( "--start", action="store_true", dest="start", help="Start mpg123 playback" ), make_option( "--stop", action="store_true", dest="stop", help="Stop mpg123 playback" ), ) def handle(self, *args, **options): # check if mpg123 is available fin, fout = os.popen4(["which", "mpg123"]) self.mpg123 = fout.read().replace("\n", "") if not len(self.mpg123): print "mpg123 is not installed" return pidFile = os.path.dirname( os.path.abspath(__file__) ) + "/../../daemon.pid" if options["start"]: if os.path.exists(pidFile): print "Daemon already running, pid file exists" return pid = daemon.pidfile.TimeoutPIDLockFile( pidFile, 10 ) print "Starting jukebox_mpg123 daemon..." self.daemon = daemon.DaemonContext( uid=os.getuid(), gid=os.getgid(), pidfile=pid, working_directory=os.getcwd(), detach_process=True, signal_map={ SIGTSTP: self.shutdown, SIGABRT: self.skipSong } ) with self.daemon: print "Register player" pid = int(open(pidFile).read()) players_api = api.players() players_api.add(pid) self.play() elif options["stop"]: if not os.path.exists(pidFile):
print "Stopping daemon..." pid = int(open(pidFile).read()) os.kill(pid, SIGTSTP) print "Unregister player " + str(pid) players_api = api.players() players_api.remove(pid) else: self.print_help("jukebox_mpg123", "help") def play(self): songs_api = api.songs() while 1: if self.proc is None: song_instance = songs_api.getNextSong() if not os.path.exists(song_instance.Filename): print "File not found: %s" % song_instance.Filename continue print "Playing " + song_instance.Filename self.proc = subprocess.Popen( [self.mpg123, song_instance.Filename] ) else: if not self.proc.poll() is None: self.proc = None time.sleep(0.5) def shutdown(self, signal, action): if not self.proc is None: os.kill(self.proc.pid, SIGTERM) if not self.daemon is None: self.daemon.close() sys.exit(0) def skipSong(self, signal, action): if not self.proc is None: os.kill(self.proc.pid, SIGTERM)
print "Daemon not running" return
conditional_block
jukebox_mpg123.py
# -*- coding: UTF-8 -*- from django.core.management.base import BaseCommand from optparse import make_option import daemon import daemon.pidfile from signal import SIGTSTP, SIGTERM, SIGABRT import sys, os, subprocess import time from jukebox.jukebox_core import api class Command(BaseCommand):
daemon = None proc = None mpg123 = None option_list = BaseCommand.option_list + ( make_option( "--start", action="store_true", dest="start", help="Start mpg123 playback" ), make_option( "--stop", action="store_true", dest="stop", help="Stop mpg123 playback" ), ) def handle(self, *args, **options): # check if mpg123 is available fin, fout = os.popen4(["which", "mpg123"]) self.mpg123 = fout.read().replace("\n", "") if not len(self.mpg123): print "mpg123 is not installed" return pidFile = os.path.dirname( os.path.abspath(__file__) ) + "/../../daemon.pid" if options["start"]: if os.path.exists(pidFile): print "Daemon already running, pid file exists" return pid = daemon.pidfile.TimeoutPIDLockFile( pidFile, 10 ) print "Starting jukebox_mpg123 daemon..." self.daemon = daemon.DaemonContext( uid=os.getuid(), gid=os.getgid(), pidfile=pid, working_directory=os.getcwd(), detach_process=True, signal_map={ SIGTSTP: self.shutdown, SIGABRT: self.skipSong } ) with self.daemon: print "Register player" pid = int(open(pidFile).read()) players_api = api.players() players_api.add(pid) self.play() elif options["stop"]: if not os.path.exists(pidFile): print "Daemon not running" return print "Stopping daemon..." pid = int(open(pidFile).read()) os.kill(pid, SIGTSTP) print "Unregister player " + str(pid) players_api = api.players() players_api.remove(pid) else: self.print_help("jukebox_mpg123", "help") def play(self): songs_api = api.songs() while 1: if self.proc is None: song_instance = songs_api.getNextSong() if not os.path.exists(song_instance.Filename): print "File not found: %s" % song_instance.Filename continue print "Playing " + song_instance.Filename self.proc = subprocess.Popen( [self.mpg123, song_instance.Filename] ) else: if not self.proc.poll() is None: self.proc = None time.sleep(0.5) def shutdown(self, signal, action): if not self.proc is None: os.kill(self.proc.pid, SIGTERM) if not self.daemon is None: self.daemon.close() sys.exit(0) def skipSong(self, signal, action): if not self.proc is None: os.kill(self.proc.pid, SIGTERM)
identifier_body
jukebox_mpg123.py
# -*- coding: UTF-8 -*- from django.core.management.base import BaseCommand from optparse import make_option import daemon import daemon.pidfile from signal import SIGTSTP, SIGTERM, SIGABRT import sys, os, subprocess import time from jukebox.jukebox_core import api class Command(BaseCommand): daemon = None proc = None mpg123 = None
make_option( "--start", action="store_true", dest="start", help="Start mpg123 playback" ), make_option( "--stop", action="store_true", dest="stop", help="Stop mpg123 playback" ), ) def handle(self, *args, **options): # check if mpg123 is available fin, fout = os.popen4(["which", "mpg123"]) self.mpg123 = fout.read().replace("\n", "") if not len(self.mpg123): print "mpg123 is not installed" return pidFile = os.path.dirname( os.path.abspath(__file__) ) + "/../../daemon.pid" if options["start"]: if os.path.exists(pidFile): print "Daemon already running, pid file exists" return pid = daemon.pidfile.TimeoutPIDLockFile( pidFile, 10 ) print "Starting jukebox_mpg123 daemon..." self.daemon = daemon.DaemonContext( uid=os.getuid(), gid=os.getgid(), pidfile=pid, working_directory=os.getcwd(), detach_process=True, signal_map={ SIGTSTP: self.shutdown, SIGABRT: self.skipSong } ) with self.daemon: print "Register player" pid = int(open(pidFile).read()) players_api = api.players() players_api.add(pid) self.play() elif options["stop"]: if not os.path.exists(pidFile): print "Daemon not running" return print "Stopping daemon..." pid = int(open(pidFile).read()) os.kill(pid, SIGTSTP) print "Unregister player " + str(pid) players_api = api.players() players_api.remove(pid) else: self.print_help("jukebox_mpg123", "help") def play(self): songs_api = api.songs() while 1: if self.proc is None: song_instance = songs_api.getNextSong() if not os.path.exists(song_instance.Filename): print "File not found: %s" % song_instance.Filename continue print "Playing " + song_instance.Filename self.proc = subprocess.Popen( [self.mpg123, song_instance.Filename] ) else: if not self.proc.poll() is None: self.proc = None time.sleep(0.5) def shutdown(self, signal, action): if not self.proc is None: os.kill(self.proc.pid, SIGTERM) if not self.daemon is None: self.daemon.close() sys.exit(0) def skipSong(self, signal, action): if not self.proc is None: os.kill(self.proc.pid, SIGTERM)
option_list = BaseCommand.option_list + (
random_line_split
graphql.d.ts
import { GraphQLCompositeType, GraphQLObjectType, GraphQLEnumValue, GraphQLSchema, GraphQLType, ASTNode, Location, ValueNode, OperationDefinitionNode, FieldNode, GraphQLField, DocumentNode } from "graphql"; declare module "graphql/utilities/buildASTSchema" { function buildASTSchema(ast: DocumentNode, options?: { assumeValid?: boolean; commentDescriptions?: boolean; }): GraphQLSchema; } export declare function sortEnumValues(values: GraphQLEnumValue[]): GraphQLEnumValue[]; export declare function isList(type: GraphQLType): boolean;
export declare function isMetaFieldName(name: string): boolean; export declare function withTypenameFieldAddedWhereNeeded(ast: ASTNode): any; export declare function sourceAt(location: Location): string; export declare function filePathForNode(node: ASTNode): string; export declare function valueFromValueNode(valueNode: ValueNode): any | { kind: "Variable"; variableName: string; }; export declare function isTypeProperSuperTypeOf(schema: GraphQLSchema, maybeSuperType: GraphQLCompositeType, subType: GraphQLCompositeType): boolean; export declare function getOperationRootType(schema: GraphQLSchema, operation: OperationDefinitionNode): import("graphql/tsutils/Maybe").default<GraphQLObjectType>; export declare function getFieldDef(schema: GraphQLSchema, parentType: GraphQLCompositeType, fieldAST: FieldNode): GraphQLField<any, any> | undefined;
random_line_split
array.rs
//! Generic-length array strategy. // Adapted from proptest's array code // Copyright 2017 Jason Lingle use core::{marker::PhantomData, mem::MaybeUninit}; use proptest::{ strategy::{NewTree, Strategy, ValueTree}, test_runner::TestRunner, }; #[must_use = "strategies do nothing unless used"] #[derive(Clone, Copy, Debug)] pub struct UniformArrayStrategy<S, T> { strategy: S, _marker: PhantomData<T>, }
Self { strategy, _marker: PhantomData, } } } pub struct ArrayValueTree<T> { tree: T, shrinker: usize, last_shrinker: Option<usize>, } impl<T, S, const LANES: usize> Strategy for UniformArrayStrategy<S, [T; LANES]> where T: core::fmt::Debug, S: Strategy<Value = T>, { type Tree = ArrayValueTree<[S::Tree; LANES]>; type Value = [T; LANES]; fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> { let tree: [S::Tree; LANES] = unsafe { let mut tree: [MaybeUninit<S::Tree>; LANES] = MaybeUninit::uninit().assume_init(); for t in tree.iter_mut() { *t = MaybeUninit::new(self.strategy.new_tree(runner)?) } core::mem::transmute_copy(&tree) }; Ok(ArrayValueTree { tree, shrinker: 0, last_shrinker: None, }) } } impl<T: ValueTree, const LANES: usize> ValueTree for ArrayValueTree<[T; LANES]> { type Value = [T::Value; LANES]; fn current(&self) -> Self::Value { unsafe { let mut value: [MaybeUninit<T::Value>; LANES] = MaybeUninit::uninit().assume_init(); for (tree_elem, value_elem) in self.tree.iter().zip(value.iter_mut()) { *value_elem = MaybeUninit::new(tree_elem.current()); } core::mem::transmute_copy(&value) } } fn simplify(&mut self) -> bool { while self.shrinker < LANES { if self.tree[self.shrinker].simplify() { self.last_shrinker = Some(self.shrinker); return true; } else { self.shrinker += 1; } } false } fn complicate(&mut self) -> bool { if let Some(shrinker) = self.last_shrinker { self.shrinker = shrinker; if self.tree[shrinker].complicate() { true } else { self.last_shrinker = None; false } } else { false } } }
impl<S, T> UniformArrayStrategy<S, T> { pub const fn new(strategy: S) -> Self {
random_line_split
array.rs
//! Generic-length array strategy. // Adapted from proptest's array code // Copyright 2017 Jason Lingle use core::{marker::PhantomData, mem::MaybeUninit}; use proptest::{ strategy::{NewTree, Strategy, ValueTree}, test_runner::TestRunner, }; #[must_use = "strategies do nothing unless used"] #[derive(Clone, Copy, Debug)] pub struct UniformArrayStrategy<S, T> { strategy: S, _marker: PhantomData<T>, } impl<S, T> UniformArrayStrategy<S, T> { pub const fn new(strategy: S) -> Self
} pub struct ArrayValueTree<T> { tree: T, shrinker: usize, last_shrinker: Option<usize>, } impl<T, S, const LANES: usize> Strategy for UniformArrayStrategy<S, [T; LANES]> where T: core::fmt::Debug, S: Strategy<Value = T>, { type Tree = ArrayValueTree<[S::Tree; LANES]>; type Value = [T; LANES]; fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> { let tree: [S::Tree; LANES] = unsafe { let mut tree: [MaybeUninit<S::Tree>; LANES] = MaybeUninit::uninit().assume_init(); for t in tree.iter_mut() { *t = MaybeUninit::new(self.strategy.new_tree(runner)?) } core::mem::transmute_copy(&tree) }; Ok(ArrayValueTree { tree, shrinker: 0, last_shrinker: None, }) } } impl<T: ValueTree, const LANES: usize> ValueTree for ArrayValueTree<[T; LANES]> { type Value = [T::Value; LANES]; fn current(&self) -> Self::Value { unsafe { let mut value: [MaybeUninit<T::Value>; LANES] = MaybeUninit::uninit().assume_init(); for (tree_elem, value_elem) in self.tree.iter().zip(value.iter_mut()) { *value_elem = MaybeUninit::new(tree_elem.current()); } core::mem::transmute_copy(&value) } } fn simplify(&mut self) -> bool { while self.shrinker < LANES { if self.tree[self.shrinker].simplify() { self.last_shrinker = Some(self.shrinker); return true; } else { self.shrinker += 1; } } false } fn complicate(&mut self) -> bool { if let Some(shrinker) = self.last_shrinker { self.shrinker = shrinker; if self.tree[shrinker].complicate() { true } else { self.last_shrinker = None; false } } else { false } } }
{ Self { strategy, _marker: PhantomData, } }
identifier_body
array.rs
//! Generic-length array strategy. // Adapted from proptest's array code // Copyright 2017 Jason Lingle use core::{marker::PhantomData, mem::MaybeUninit}; use proptest::{ strategy::{NewTree, Strategy, ValueTree}, test_runner::TestRunner, }; #[must_use = "strategies do nothing unless used"] #[derive(Clone, Copy, Debug)] pub struct
<S, T> { strategy: S, _marker: PhantomData<T>, } impl<S, T> UniformArrayStrategy<S, T> { pub const fn new(strategy: S) -> Self { Self { strategy, _marker: PhantomData, } } } pub struct ArrayValueTree<T> { tree: T, shrinker: usize, last_shrinker: Option<usize>, } impl<T, S, const LANES: usize> Strategy for UniformArrayStrategy<S, [T; LANES]> where T: core::fmt::Debug, S: Strategy<Value = T>, { type Tree = ArrayValueTree<[S::Tree; LANES]>; type Value = [T; LANES]; fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> { let tree: [S::Tree; LANES] = unsafe { let mut tree: [MaybeUninit<S::Tree>; LANES] = MaybeUninit::uninit().assume_init(); for t in tree.iter_mut() { *t = MaybeUninit::new(self.strategy.new_tree(runner)?) } core::mem::transmute_copy(&tree) }; Ok(ArrayValueTree { tree, shrinker: 0, last_shrinker: None, }) } } impl<T: ValueTree, const LANES: usize> ValueTree for ArrayValueTree<[T; LANES]> { type Value = [T::Value; LANES]; fn current(&self) -> Self::Value { unsafe { let mut value: [MaybeUninit<T::Value>; LANES] = MaybeUninit::uninit().assume_init(); for (tree_elem, value_elem) in self.tree.iter().zip(value.iter_mut()) { *value_elem = MaybeUninit::new(tree_elem.current()); } core::mem::transmute_copy(&value) } } fn simplify(&mut self) -> bool { while self.shrinker < LANES { if self.tree[self.shrinker].simplify() { self.last_shrinker = Some(self.shrinker); return true; } else { self.shrinker += 1; } } false } fn complicate(&mut self) -> bool { if let Some(shrinker) = self.last_shrinker { self.shrinker = shrinker; if self.tree[shrinker].complicate() { true } else { self.last_shrinker = None; false } } else { false } } }
UniformArrayStrategy
identifier_name
array.rs
//! Generic-length array strategy. // Adapted from proptest's array code // Copyright 2017 Jason Lingle use core::{marker::PhantomData, mem::MaybeUninit}; use proptest::{ strategy::{NewTree, Strategy, ValueTree}, test_runner::TestRunner, }; #[must_use = "strategies do nothing unless used"] #[derive(Clone, Copy, Debug)] pub struct UniformArrayStrategy<S, T> { strategy: S, _marker: PhantomData<T>, } impl<S, T> UniformArrayStrategy<S, T> { pub const fn new(strategy: S) -> Self { Self { strategy, _marker: PhantomData, } } } pub struct ArrayValueTree<T> { tree: T, shrinker: usize, last_shrinker: Option<usize>, } impl<T, S, const LANES: usize> Strategy for UniformArrayStrategy<S, [T; LANES]> where T: core::fmt::Debug, S: Strategy<Value = T>, { type Tree = ArrayValueTree<[S::Tree; LANES]>; type Value = [T; LANES]; fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> { let tree: [S::Tree; LANES] = unsafe { let mut tree: [MaybeUninit<S::Tree>; LANES] = MaybeUninit::uninit().assume_init(); for t in tree.iter_mut() { *t = MaybeUninit::new(self.strategy.new_tree(runner)?) } core::mem::transmute_copy(&tree) }; Ok(ArrayValueTree { tree, shrinker: 0, last_shrinker: None, }) } } impl<T: ValueTree, const LANES: usize> ValueTree for ArrayValueTree<[T; LANES]> { type Value = [T::Value; LANES]; fn current(&self) -> Self::Value { unsafe { let mut value: [MaybeUninit<T::Value>; LANES] = MaybeUninit::uninit().assume_init(); for (tree_elem, value_elem) in self.tree.iter().zip(value.iter_mut()) { *value_elem = MaybeUninit::new(tree_elem.current()); } core::mem::transmute_copy(&value) } } fn simplify(&mut self) -> bool { while self.shrinker < LANES { if self.tree[self.shrinker].simplify() { self.last_shrinker = Some(self.shrinker); return true; } else { self.shrinker += 1; } } false } fn complicate(&mut self) -> bool { if let Some(shrinker) = self.last_shrinker
else { false } } }
{ self.shrinker = shrinker; if self.tree[shrinker].complicate() { true } else { self.last_shrinker = None; false } }
conditional_block
item_chooser.js
define([ 'backbone', 'text!templates/item_chooser.tpl', 'models/item', 'models/trigger', 'models/instance', 'models/media', 'views/item_chooser_row', 'views/trigger_creator', 'vent', 'util',
Template, Item, Trigger, Instance, Media, ItemChooserRowView, TriggerCreatorView, vent, util ) { return Backbone.Marionette.CompositeView.extend( { template: _.template(Template), itemView: ItemChooserRowView, itemViewContainer: ".items", itemViewOptions: function(model, index) { return { parent: this.options.parent } }, events: { "click .new-item": "onClickNewItem" }, /* TODO move complex sets like this into a controller */ onClickNewItem: function() { var loc = util.default_location(); var trigger = new Trigger ({game_id:this.options.parent.get("game_id"), scene_id:this.options.parent.get("scene_id"), latitude:loc.latitude, longitude:loc.longitude }); var instance = new Instance ({game_id: this.options.parent.get("game_id")}); var item = new Item ({game_id: this.options.parent.get("game_id")}); var trigger_creator = new TriggerCreatorView({scene: this.options.parent, game_object: item, instance: instance, model: trigger}); vent.trigger("application:popup:show", trigger_creator, "Add Item to Scene"); }, // Marionette override appendBuffer: function(compositeView, buffer) { var $container = this.getItemViewContainer(compositeView); $container.find(".foot").before(buffer); }, appendHtml: function(compositeView, itemView, index) { if (compositeView.isBuffering) { compositeView.elBuffer.appendChild(itemView.el); } else { // If we've already rendered the main collection, just // append the new items directly into the element. var $container = this.getItemViewContainer(compositeView); $container.find(".foot").before(itemView.el); } } }); });
], function( Backbone,
random_line_split
item_chooser.js
define([ 'backbone', 'text!templates/item_chooser.tpl', 'models/item', 'models/trigger', 'models/instance', 'models/media', 'views/item_chooser_row', 'views/trigger_creator', 'vent', 'util', ], function( Backbone, Template, Item, Trigger, Instance, Media, ItemChooserRowView, TriggerCreatorView, vent, util ) { return Backbone.Marionette.CompositeView.extend( { template: _.template(Template), itemView: ItemChooserRowView, itemViewContainer: ".items", itemViewOptions: function(model, index) { return { parent: this.options.parent } }, events: { "click .new-item": "onClickNewItem" }, /* TODO move complex sets like this into a controller */ onClickNewItem: function() { var loc = util.default_location(); var trigger = new Trigger ({game_id:this.options.parent.get("game_id"), scene_id:this.options.parent.get("scene_id"), latitude:loc.latitude, longitude:loc.longitude }); var instance = new Instance ({game_id: this.options.parent.get("game_id")}); var item = new Item ({game_id: this.options.parent.get("game_id")}); var trigger_creator = new TriggerCreatorView({scene: this.options.parent, game_object: item, instance: instance, model: trigger}); vent.trigger("application:popup:show", trigger_creator, "Add Item to Scene"); }, // Marionette override appendBuffer: function(compositeView, buffer) { var $container = this.getItemViewContainer(compositeView); $container.find(".foot").before(buffer); }, appendHtml: function(compositeView, itemView, index) { if (compositeView.isBuffering)
else { // If we've already rendered the main collection, just // append the new items directly into the element. var $container = this.getItemViewContainer(compositeView); $container.find(".foot").before(itemView.el); } } }); });
{ compositeView.elBuffer.appendChild(itemView.el); }
conditional_block
getLocations.js
'use strict'; /* INSTRUCCIONES - Ejecutar getLocations - Ejecutar correlateCines para a mano encontrar correlaciones. */ var request = require('request'), cheerio = require('cheerio'), mongoose = require('mongoose'), md5 = require('md5'), fs = require('fs'), async = require('async'), events = require('events'), compare = require('levenshtein'), modelos = require('./models/models.js'), urlBase = 'http://www.ecartelera.com/', urlIMDB = 'http://www.imdb.com/showtimes/ES/', provincias = [], cines = [], codPostales = [], correlations = []; var contadorE = 0, listaCadenas = '', listaIds = '', correlados = ''; //Conecto a mongo mongoose.connect(process.env.OPENSHIFT_MONGODB_DB_URL + process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/cine', { db: {safe: true} }); //Gestor de eventos var eventEmitter = new events.EventEmitter(); initCodPostalesArray(); //Cojo de mongo las correlaciones modelos.Correlation .find().exec(function (err, correlat) { if (!err) { //Array de corr correlat.forEach(function (corr) { correlations[corr.cineId] = corr.imdbId; }); getProvincias(); } }); //Cojo la web de provincias function getProvincias() { request(urlBase + 'cartelera', function (err, resp, body) { if (err || resp.statusCode !== 200) { console.log('Se produjo un error'); throw err; } var $ = cheerio.load(body); /*var fs = require('fs'); fs.writeFile("tmp/provincias.html", body, function (err) { if (err) { return console.log(err); } console.log("The file was saved!"); });*/ console.log(' - - '); console.log(' ------------ Obtengo provincias -------------- '); console.log(' - - '); //Por cada provincia... $('ul.cityselector li a').each(function () { var pId = extractId($(this).attr('href')); if (pId === null) { return false; } var name = $(this).text().trim(); console.log(' ·Provincia: ' + name + ' (Id: ' + pId + ')'); provincias.push({ _id: md5(pId), provinciaId: pId, nombre: name, ciudades: [], actualizado: new Date().getTime(), sortfield: sortfielizar(name) }); }); //console.log(provincias); console.log(' - - '); console.log(' ------------ Obtengo ciudades y cines -------------- '); console.log(' - - '); //Por cada provincia voy recogiendo sus ciudades y cines async.map(provincias, getCiudades, function (err, results) { if (err) { throw err; } else { provincias = results; //Lanzo el proceso de actualización en Mongo de las cosas eventEmitter.emit('updateProvincias', provincias); } }); }); } //Obtiene las ciudades de una provincia y sus cines function getCiudades(provincia, callback) { var enlaceCiudad = urlBase + 'cines/' + provincia.provinciaId; console.log(' -- Miro las ciudades del enlace: ' + enlaceCiudad); //Saco el id de IMBD del cine var codpost = codPostales[provincia.nombre]; //Lo consulto en IMDB request(urlIMDB + codpost, function (err, response, body) { if (err) { callback(err); } else { var $IMDB = cheerio.load(body); request(enlaceCiudad, function (err, response, body) { if (err) { callback(err); } else { var $ = cheerio.load(body), lastCityId = 0, lastCityName = ''; var counter = 0; //Saco las ciudades y de paso los cines también $('ul.cityselector li').each(function () { var enlace = $(this).find('a'); //Si es título, es que es ciudad if ($(this).hasClass('tit')) { var cityId = lastCityId = extractId(enlace.attr('href')); var cityName = lastCityName = enlace.text().trim(); console.log(' ··Ciudad: ' + cityName + ' (Id: ' + cityId + ')'); //Añado la ciudad a la lista de la provincia provincia.ciudades.push({ _id: md5(cityId), ciudadId: cityId, nombre: cityName, actualizado: 0 }); } else { //Si no está inactivo, es un cine de la ciudad if (!enlace.hasClass('inactivo') && lastCityId !== 0) { var cineId = extractId(enlace.attr('href')); var cineName = enlace.text().trim(); var idIMDB = null, nameIMDB = ''; var nombresIMDB = '', idsIMDB = ''; console.log(' ··Cine: ' + cineName + ' (Id: ' + cineId + ')'); //Si ya está el id del cine correlado no hago más que añadirlos a la lista de correlados if (correlations[cineId] !== undefined) { idIMDB = correlations[cineId]; correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB; } else { //INTENTO SACARLOS. Por cada cine en IMDB comparo a ver si es este cine $IMDB('div[itemtype="http://schema.org/MovieTheater"]').each(function () { var h3Cine = $(this).find('h3'); var enlaceCine = h3Cine.find('a[itemprop="url"]'); var thisIdIMDB = extractIMDBId(enlaceCine.attr('href').trim()); //Comparo nombres nameIMDB = enlaceCine.text().trim(); //Auxiliares nombresIMDB = (nombresIMDB == '') ? nameIMDB : nombresIMDB + '||' + nameIMDB; idsIMDB = (idsIMDB == '') ? thisIdIMDB : idsIMDB + '||' + thisIdIMDB; var comparison = new compare(prepareToCompare(nameIMDB), prepareToCompare(cineName)); if (comparison.distance < 4) { idIMDB = thisIdIMDB; return false; //salgo del bucle } else { //Comprobaciones extra if (cineName.indexOf(nameIMDB) > -1 || nameIMDB.indexOf(cineName) > -1) { idIMDB = thisIdIMDB; return false; } } }); if (idIMDB === null) { //console.log(' *** No encontré el cine << ' + cineName + ' >> de ' + lastCityName + ' (' + provincia.nombre + ') CODPOSTAL: ' + codpost); //console.log(' *** De entre estos: ' + nombresIMDB); listaCadenas = (listaCadenas == '') ? cineName + '##' + nombresIMDB : listaCadenas + '$$' + cineName + '##' + nombresIMDB; listaIds = (listaIds == '') ? cineId + '##' + idsIMDB : listaIds + '$$' + cineId + '##' + idsIMDB; counter = counter + 1; contadorE++;
} } //Añado el cine a la lista de cines cines.push({ _id: md5(cineId), cineId: cineId, imdbId: idIMDB, nombre: cineName, _idCiudad: md5(lastCityId), nombreCiudad: lastCityName, actualizado: 0 }); } } }); console.log('No encontré de esta provincia: ' + counter); callback(null, provincia); // First param indicates error, null=> no error } }); } }); } //Listener del evento de actualizar provincias y ciudades en Mongo eventEmitter.on('updateProvincias', function (misProvincias) { //Limpio la colección de provincias modelos.Provincia.remove({}, function (err) { }); //Guardo en base de datos modelos.Provincia.create(misProvincias, function (err) { if (err) { console.error(err); } console.log(' Mongo - He metido ' + misProvincias.length + ' provincias'); //Emito señal para continuar eventEmitter.emit('updateCines', cines); }); }); //Listener del evento de actualizar cines en Mongo eventEmitter.on('updateCines', function (misCines) { //Limpio la colección de cines modelos.Cine.remove({}, function (err) { }); //Guardo en base de datos modelos.Cine.create(misCines, function (err) { if (err) { console.error(err); } console.log(' Mongo - He metido ' + misCines.length + ' cines'); //Finalizo eventEmitter.emit('finalize'); }); }); //Listener del evento de terminar eventEmitter.on('finalize', function () { mongoose.disconnect(); console.log('Finalizado'); console.log('No encontré: ' + contadorE); fs.writeFileSync("cadenasNotFound.txt", listaCadenas); fs.writeFileSync("idsNotFound.txt", listaIds); fs.writeFileSync("correlados.txt", correlados); //Finalizo process.exit(); }); //Extrae el id de un enlace http://www.ecartelera.com/cines/0,165,0.html que es 0,165,0.html function extractId(href) { var patt = /(\/cines\/)(.+)/; var res = patt.exec(href); if (res !== null) { return res[2]; } else { return null; } } function extractIMDBId(href) { var patt = /(.*\/)(ci[0-9]+)(\/.*)/; var res = patt.exec(href); if (res !== null) { return res[2]; } else { return null; } } function sortfielizar(text) { text = text.toLowerCase(); text = text.replace(' ', '_'); text = text.replace('.', '_'); text = text.replace('á', 'a'); text = text.replace('é', 'e'); text = text.replace('í', 'i'); text = text.replace('ó', 'o'); text = text.replace('ú', 'u'); text = text.replace('ñ', 'n'); return text; } //Elimina ciertas palabras para poder comparar mejor function prepareToCompare(text) { text = text.replace(/Cine(s)?/g, ''); return text; } function initCodPostalesArray() { codPostales['A Coruña'] = '15001'; codPostales['Álava'] = '01001'; codPostales['Albacete'] = '02001'; codPostales['Alicante'] = '03001'; codPostales['Almería'] = '04001'; codPostales['Asturias'] = '33001'; codPostales['Ávila'] = '05001'; codPostales['Badajoz'] = '06001'; codPostales['Baleares'] = '07001'; codPostales['Barcelona'] = '08001'; codPostales['Burgos'] = '09001'; codPostales['Cáceres'] = '10001'; codPostales['Cádiz'] = '11001'; codPostales['Cantabria'] = '39001'; codPostales['Castellón'] = '12001'; codPostales['Ceuta'] = '51001'; codPostales['Ciudad Real'] = '13001'; codPostales['Córdoba'] = '14001'; codPostales['Cuenca'] = '16001'; codPostales['Girona'] = '17001'; codPostales['Granada'] = '18001'; codPostales['Guadalajara'] = '19001'; codPostales['Guipúzcoa'] = '20001'; codPostales['Huelva'] = '21001'; codPostales['Huesca'] = '22001'; codPostales['Jaén'] = '23001'; codPostales['La Rioja'] = '26001'; codPostales['Las Palmas'] = '35001'; codPostales['León'] = '24001'; codPostales['Lleida'] = '25001'; codPostales['Lugo'] = '27001'; codPostales['Madrid'] = '28001'; codPostales['Málaga'] = '29001'; codPostales['Melilla'] = '52001'; codPostales['Murcia'] = '30001'; codPostales['Navarra'] = '31001'; codPostales['Ourense'] = '32001'; codPostales['Palencia'] = '34001'; codPostales['Pontevedra'] = '36001'; codPostales['S.C. Tenerife'] = '38001'; codPostales['Salamanca'] = '37001'; codPostales['Segovia'] = '40001'; codPostales['Sevilla'] = '41001'; codPostales['Soria'] = '42001'; codPostales['Tarragona'] = '43001'; codPostales['Teruel'] = '44001'; codPostales['Toledo'] = '45001'; codPostales['Valencia'] = '46001'; codPostales['Valladolid'] = '47001'; codPostales['Vizcaya'] = '48001'; codPostales['Zamora'] = '49001'; codPostales['Zaragoza'] = '50001'; }
} else { console.log(" --IMDB: " + nameIMDB + ' (Id: ' + idIMDB + ')'); correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB;
random_line_split
getLocations.js
'use strict'; /* INSTRUCCIONES - Ejecutar getLocations - Ejecutar correlateCines para a mano encontrar correlaciones. */ var request = require('request'), cheerio = require('cheerio'), mongoose = require('mongoose'), md5 = require('md5'), fs = require('fs'), async = require('async'), events = require('events'), compare = require('levenshtein'), modelos = require('./models/models.js'), urlBase = 'http://www.ecartelera.com/', urlIMDB = 'http://www.imdb.com/showtimes/ES/', provincias = [], cines = [], codPostales = [], correlations = []; var contadorE = 0, listaCadenas = '', listaIds = '', correlados = ''; //Conecto a mongo mongoose.connect(process.env.OPENSHIFT_MONGODB_DB_URL + process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/cine', { db: {safe: true} }); //Gestor de eventos var eventEmitter = new events.EventEmitter(); initCodPostalesArray(); //Cojo de mongo las correlaciones modelos.Correlation .find().exec(function (err, correlat) { if (!err) { //Array de corr correlat.forEach(function (corr) { correlations[corr.cineId] = corr.imdbId; }); getProvincias(); } }); //Cojo la web de provincias function getProvincias() { request(urlBase + 'cartelera', function (err, resp, body) { if (err || resp.statusCode !== 200) { console.log('Se produjo un error'); throw err; } var $ = cheerio.load(body); /*var fs = require('fs'); fs.writeFile("tmp/provincias.html", body, function (err) { if (err) { return console.log(err); } console.log("The file was saved!"); });*/ console.log(' - - '); console.log(' ------------ Obtengo provincias -------------- '); console.log(' - - '); //Por cada provincia... $('ul.cityselector li a').each(function () { var pId = extractId($(this).attr('href')); if (pId === null) { return false; } var name = $(this).text().trim(); console.log(' ·Provincia: ' + name + ' (Id: ' + pId + ')'); provincias.push({ _id: md5(pId), provinciaId: pId, nombre: name, ciudades: [], actualizado: new Date().getTime(), sortfield: sortfielizar(name) }); }); //console.log(provincias); console.log(' - - '); console.log(' ------------ Obtengo ciudades y cines -------------- '); console.log(' - - '); //Por cada provincia voy recogiendo sus ciudades y cines async.map(provincias, getCiudades, function (err, results) { if (err) { throw err; } else { provincias = results; //Lanzo el proceso de actualización en Mongo de las cosas eventEmitter.emit('updateProvincias', provincias); } }); }); } //Obtiene las ciudades de una provincia y sus cines function getCiudades(provincia, callback) { var enlaceCiudad = urlBase + 'cines/' + provincia.provinciaId; console.log(' -- Miro las ciudades del enlace: ' + enlaceCiudad); //Saco el id de IMBD del cine var codpost = codPostales[provincia.nombre]; //Lo consulto en IMDB request(urlIMDB + codpost, function (err, response, body) { if (err) { callback(err); } else { var $IMDB = cheerio.load(body); request(enlaceCiudad, function (err, response, body) { if (err) { callback(err); } else { var $ = cheerio.load(body), lastCityId = 0, lastCityName = ''; var counter = 0; //Saco las ciudades y de paso los cines también $('ul.cityselector li').each(function () { var enlace = $(this).find('a'); //Si es título, es que es ciudad if ($(this).hasClass('tit')) { var cityId = lastCityId = extractId(enlace.attr('href')); var cityName = lastCityName = enlace.text().trim(); console.log(' ··Ciudad: ' + cityName + ' (Id: ' + cityId + ')'); //Añado la ciudad a la lista de la provincia provincia.ciudades.push({ _id: md5(cityId), ciudadId: cityId, nombre: cityName, actualizado: 0 }); } else { //Si no está inactivo, es un cine de la ciudad if (!enlace.hasClass('inactivo') && lastCityId !== 0) { var cineId = extractId(enlace.attr('href')); var cineName = enlace.text().trim(); var idIMDB = null, nameIMDB = ''; var nombresIMDB = '', idsIMDB = ''; console.log(' ··Cine: ' + cineName + ' (Id: ' + cineId + ')'); //Si ya está el id del cine correlado no hago más que añadirlos a la lista de correlados if (correlations[cineId] !== undefined) { idIMDB = correlations[cineId]; correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB; } else { //INTENTO SACARLOS. Por cada cine en IMDB comparo a ver si es este cine $IMDB('div[itemtype="http://schema.org/MovieTheater"]').each(function () { var h3Cine = $(this).find('h3'); var enlaceCine = h3Cine.find('a[itemprop="url"]'); var thisIdIMDB = extractIMDBId(enlaceCine.attr('href').trim()); //Comparo nombres nameIMDB = enlaceCine.text().trim(); //Auxiliares nombresIMDB = (nombresIMDB == '') ? nameIMDB : nombresIMDB + '||' + nameIMDB; idsIMDB = (idsIMDB == '') ? thisIdIMDB : idsIMDB + '||' + thisIdIMDB; var comparison = new compare(prepareToCompare(nameIMDB), prepareToCompare(cineName)); if (comparison.distance < 4) { idIMDB = thisIdIMDB; return false; //salgo del bucle } else { //Comprobaciones extra if (cineName.indexOf(nameIMDB) > -1 || nameIMDB.indexOf(cineName) > -1) { idIMDB = thisIdIMDB; return false; } } }); if (idIMDB === null) { //console.log(' *** No encontré el cine << ' + cineName + ' >> de ' + lastCityName + ' (' + provincia.nombre + ') CODPOSTAL: ' + codpost); //console.log(' *** De entre estos: ' + nombresIMDB); listaCadenas = (listaCadenas == '') ? cineName + '##' + nombresIMDB : listaCadenas + '$$' + cineName + '##' + nombresIMDB; listaIds = (listaIds == '') ? cineId + '##' + idsIMDB : listaIds + '$$' + cineId + '##' + idsIMDB; counter = counter + 1; contadorE++; } else { console.log(" --IMDB: " + nameIMDB + ' (Id: ' + idIMDB + ')'); correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB; } } //Añado el cine a la lista de cines cines.push({ _id: md5(cineId), cineId: cineId, imdbId: idIMDB, nombre: cineName, _idCiudad: md5(lastCityId), nombreCiudad: lastCityName, actualizado: 0 }); } } }); console.log('No encontré de esta provincia: ' + counter); callback(null, provincia); // First param indicates error, null=> no error } }); } }); } //Listener del evento de actualizar provincias y ciudades en Mongo eventEmitter.on('updateProvincias', function (misProvincias) { //Limpio la colección de provincias modelos.Provincia.remove({}, function (err) { }); //Guardo en base de datos modelos.Provincia.create(misProvincias, function (err) { if (err) { console.error(err); } console.log(' Mongo - He metido ' + misProvincias.length + ' provincias'); //Emito señal para continuar eventEmitter.emit('updateCines', cines); }); }); //Listener del evento de actualizar cines en Mongo eventEmitter.on('updateCines', function (misCines) { //Limpio la colección de cines modelos.Cine.remove({}, function (err) { }); //Guardo en base de datos modelos.Cine.create(misCines, function (err) { if (err) { console.error(err); } console.log(' Mongo - He metido ' + misCines.length + ' cines'); //Finalizo eventEmitter.emit('finalize'); }); }); //Listener del evento de terminar eventEmitter.on('finalize', function () { mongoose.disconnect(); console.log('Finalizado'); console.log('No encontré: ' + contadorE); fs.writeFileSync("cadenasNotFound.txt", listaCadenas); fs.writeFileSync("idsNotFound.txt", listaIds); fs.writeFileSync("correlados.txt", correlados); //Finalizo process.exit(); }); //Extrae el id de un enlace http://www.ecartelera.com/cines/0,165,0.html que es 0,165,0.html function extractId(href) {
t = /(\/cines\/)(.+)/; var res = patt.exec(href); if (res !== null) { return res[2]; } else { return null; } } function extractIMDBId(href) { var patt = /(.*\/)(ci[0-9]+)(\/.*)/; var res = patt.exec(href); if (res !== null) { return res[2]; } else { return null; } } function sortfielizar(text) { text = text.toLowerCase(); text = text.replace(' ', '_'); text = text.replace('.', '_'); text = text.replace('á', 'a'); text = text.replace('é', 'e'); text = text.replace('í', 'i'); text = text.replace('ó', 'o'); text = text.replace('ú', 'u'); text = text.replace('ñ', 'n'); return text; } //Elimina ciertas palabras para poder comparar mejor function prepareToCompare(text) { text = text.replace(/Cine(s)?/g, ''); return text; } function initCodPostalesArray() { codPostales['A Coruña'] = '15001'; codPostales['Álava'] = '01001'; codPostales['Albacete'] = '02001'; codPostales['Alicante'] = '03001'; codPostales['Almería'] = '04001'; codPostales['Asturias'] = '33001'; codPostales['Ávila'] = '05001'; codPostales['Badajoz'] = '06001'; codPostales['Baleares'] = '07001'; codPostales['Barcelona'] = '08001'; codPostales['Burgos'] = '09001'; codPostales['Cáceres'] = '10001'; codPostales['Cádiz'] = '11001'; codPostales['Cantabria'] = '39001'; codPostales['Castellón'] = '12001'; codPostales['Ceuta'] = '51001'; codPostales['Ciudad Real'] = '13001'; codPostales['Córdoba'] = '14001'; codPostales['Cuenca'] = '16001'; codPostales['Girona'] = '17001'; codPostales['Granada'] = '18001'; codPostales['Guadalajara'] = '19001'; codPostales['Guipúzcoa'] = '20001'; codPostales['Huelva'] = '21001'; codPostales['Huesca'] = '22001'; codPostales['Jaén'] = '23001'; codPostales['La Rioja'] = '26001'; codPostales['Las Palmas'] = '35001'; codPostales['León'] = '24001'; codPostales['Lleida'] = '25001'; codPostales['Lugo'] = '27001'; codPostales['Madrid'] = '28001'; codPostales['Málaga'] = '29001'; codPostales['Melilla'] = '52001'; codPostales['Murcia'] = '30001'; codPostales['Navarra'] = '31001'; codPostales['Ourense'] = '32001'; codPostales['Palencia'] = '34001'; codPostales['Pontevedra'] = '36001'; codPostales['S.C. Tenerife'] = '38001'; codPostales['Salamanca'] = '37001'; codPostales['Segovia'] = '40001'; codPostales['Sevilla'] = '41001'; codPostales['Soria'] = '42001'; codPostales['Tarragona'] = '43001'; codPostales['Teruel'] = '44001'; codPostales['Toledo'] = '45001'; codPostales['Valencia'] = '46001'; codPostales['Valladolid'] = '47001'; codPostales['Vizcaya'] = '48001'; codPostales['Zamora'] = '49001'; codPostales['Zaragoza'] = '50001'; }
var pat
identifier_name
getLocations.js
'use strict'; /* INSTRUCCIONES - Ejecutar getLocations - Ejecutar correlateCines para a mano encontrar correlaciones. */ var request = require('request'), cheerio = require('cheerio'), mongoose = require('mongoose'), md5 = require('md5'), fs = require('fs'), async = require('async'), events = require('events'), compare = require('levenshtein'), modelos = require('./models/models.js'), urlBase = 'http://www.ecartelera.com/', urlIMDB = 'http://www.imdb.com/showtimes/ES/', provincias = [], cines = [], codPostales = [], correlations = []; var contadorE = 0, listaCadenas = '', listaIds = '', correlados = ''; //Conecto a mongo mongoose.connect(process.env.OPENSHIFT_MONGODB_DB_URL + process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/cine', { db: {safe: true} }); //Gestor de eventos var eventEmitter = new events.EventEmitter(); initCodPostalesArray(); //Cojo de mongo las correlaciones modelos.Correlation .find().exec(function (err, correlat) { if (!err) { //Array de corr correlat.forEach(function (corr) { correlations[corr.cineId] = corr.imdbId; }); getProvincias(); } }); //Cojo la web de provincias function getProvincias() { request(urlBase + 'cartelera', function (err, resp, body) { if (err || resp.statusCode !== 200) { console.log('Se produjo un error'); throw err; } var $ = cheerio.load(body); /*var fs = require('fs'); fs.writeFile("tmp/provincias.html", body, function (err) { if (err) { return console.log(err); } console.log("The file was saved!"); });*/ console.log(' - - '); console.log(' ------------ Obtengo provincias -------------- '); console.log(' - - '); //Por cada provincia... $('ul.cityselector li a').each(function () { var pId = extractId($(this).attr('href')); if (pId === null)
var name = $(this).text().trim(); console.log(' ·Provincia: ' + name + ' (Id: ' + pId + ')'); provincias.push({ _id: md5(pId), provinciaId: pId, nombre: name, ciudades: [], actualizado: new Date().getTime(), sortfield: sortfielizar(name) }); }); //console.log(provincias); console.log(' - - '); console.log(' ------------ Obtengo ciudades y cines -------------- '); console.log(' - - '); //Por cada provincia voy recogiendo sus ciudades y cines async.map(provincias, getCiudades, function (err, results) { if (err) { throw err; } else { provincias = results; //Lanzo el proceso de actualización en Mongo de las cosas eventEmitter.emit('updateProvincias', provincias); } }); }); } //Obtiene las ciudades de una provincia y sus cines function getCiudades(provincia, callback) { var enlaceCiudad = urlBase + 'cines/' + provincia.provinciaId; console.log(' -- Miro las ciudades del enlace: ' + enlaceCiudad); //Saco el id de IMBD del cine var codpost = codPostales[provincia.nombre]; //Lo consulto en IMDB request(urlIMDB + codpost, function (err, response, body) { if (err) { callback(err); } else { var $IMDB = cheerio.load(body); request(enlaceCiudad, function (err, response, body) { if (err) { callback(err); } else { var $ = cheerio.load(body), lastCityId = 0, lastCityName = ''; var counter = 0; //Saco las ciudades y de paso los cines también $('ul.cityselector li').each(function () { var enlace = $(this).find('a'); //Si es título, es que es ciudad if ($(this).hasClass('tit')) { var cityId = lastCityId = extractId(enlace.attr('href')); var cityName = lastCityName = enlace.text().trim(); console.log(' ··Ciudad: ' + cityName + ' (Id: ' + cityId + ')'); //Añado la ciudad a la lista de la provincia provincia.ciudades.push({ _id: md5(cityId), ciudadId: cityId, nombre: cityName, actualizado: 0 }); } else { //Si no está inactivo, es un cine de la ciudad if (!enlace.hasClass('inactivo') && lastCityId !== 0) { var cineId = extractId(enlace.attr('href')); var cineName = enlace.text().trim(); var idIMDB = null, nameIMDB = ''; var nombresIMDB = '', idsIMDB = ''; console.log(' ··Cine: ' + cineName + ' (Id: ' + cineId + ')'); //Si ya está el id del cine correlado no hago más que añadirlos a la lista de correlados if (correlations[cineId] !== undefined) { idIMDB = correlations[cineId]; correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB; } else { //INTENTO SACARLOS. Por cada cine en IMDB comparo a ver si es este cine $IMDB('div[itemtype="http://schema.org/MovieTheater"]').each(function () { var h3Cine = $(this).find('h3'); var enlaceCine = h3Cine.find('a[itemprop="url"]'); var thisIdIMDB = extractIMDBId(enlaceCine.attr('href').trim()); //Comparo nombres nameIMDB = enlaceCine.text().trim(); //Auxiliares nombresIMDB = (nombresIMDB == '') ? nameIMDB : nombresIMDB + '||' + nameIMDB; idsIMDB = (idsIMDB == '') ? thisIdIMDB : idsIMDB + '||' + thisIdIMDB; var comparison = new compare(prepareToCompare(nameIMDB), prepareToCompare(cineName)); if (comparison.distance < 4) { idIMDB = thisIdIMDB; return false; //salgo del bucle } else { //Comprobaciones extra if (cineName.indexOf(nameIMDB) > -1 || nameIMDB.indexOf(cineName) > -1) { idIMDB = thisIdIMDB; return false; } } }); if (idIMDB === null) { //console.log(' *** No encontré el cine << ' + cineName + ' >> de ' + lastCityName + ' (' + provincia.nombre + ') CODPOSTAL: ' + codpost); //console.log(' *** De entre estos: ' + nombresIMDB); listaCadenas = (listaCadenas == '') ? cineName + '##' + nombresIMDB : listaCadenas + '$$' + cineName + '##' + nombresIMDB; listaIds = (listaIds == '') ? cineId + '##' + idsIMDB : listaIds + '$$' + cineId + '##' + idsIMDB; counter = counter + 1; contadorE++; } else { console.log(" --IMDB: " + nameIMDB + ' (Id: ' + idIMDB + ')'); correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB; } } //Añado el cine a la lista de cines cines.push({ _id: md5(cineId), cineId: cineId, imdbId: idIMDB, nombre: cineName, _idCiudad: md5(lastCityId), nombreCiudad: lastCityName, actualizado: 0 }); } } }); console.log('No encontré de esta provincia: ' + counter); callback(null, provincia); // First param indicates error, null=> no error } }); } }); } //Listener del evento de actualizar provincias y ciudades en Mongo eventEmitter.on('updateProvincias', function (misProvincias) { //Limpio la colección de provincias modelos.Provincia.remove({}, function (err) { }); //Guardo en base de datos modelos.Provincia.create(misProvincias, function (err) { if (err) { console.error(err); } console.log(' Mongo - He metido ' + misProvincias.length + ' provincias'); //Emito señal para continuar eventEmitter.emit('updateCines', cines); }); }); //Listener del evento de actualizar cines en Mongo eventEmitter.on('updateCines', function (misCines) { //Limpio la colección de cines modelos.Cine.remove({}, function (err) { }); //Guardo en base de datos modelos.Cine.create(misCines, function (err) { if (err) { console.error(err); } console.log(' Mongo - He metido ' + misCines.length + ' cines'); //Finalizo eventEmitter.emit('finalize'); }); }); //Listener del evento de terminar eventEmitter.on('finalize', function () { mongoose.disconnect(); console.log('Finalizado'); console.log('No encontré: ' + contadorE); fs.writeFileSync("cadenasNotFound.txt", listaCadenas); fs.writeFileSync("idsNotFound.txt", listaIds); fs.writeFileSync("correlados.txt", correlados); //Finalizo process.exit(); }); //Extrae el id de un enlace http://www.ecartelera.com/cines/0,165,0.html que es 0,165,0.html function extractId(href) { var patt = /(\/cines\/)(.+)/; var res = patt.exec(href); if (res !== null) { return res[2]; } else { return null; } } function extractIMDBId(href) { var patt = /(.*\/)(ci[0-9]+)(\/.*)/; var res = patt.exec(href); if (res !== null) { return res[2]; } else { return null; } } function sortfielizar(text) { text = text.toLowerCase(); text = text.replace(' ', '_'); text = text.replace('.', '_'); text = text.replace('á', 'a'); text = text.replace('é', 'e'); text = text.replace('í', 'i'); text = text.replace('ó', 'o'); text = text.replace('ú', 'u'); text = text.replace('ñ', 'n'); return text; } //Elimina ciertas palabras para poder comparar mejor function prepareToCompare(text) { text = text.replace(/Cine(s)?/g, ''); return text; } function initCodPostalesArray() { codPostales['A Coruña'] = '15001'; codPostales['Álava'] = '01001'; codPostales['Albacete'] = '02001'; codPostales['Alicante'] = '03001'; codPostales['Almería'] = '04001'; codPostales['Asturias'] = '33001'; codPostales['Ávila'] = '05001'; codPostales['Badajoz'] = '06001'; codPostales['Baleares'] = '07001'; codPostales['Barcelona'] = '08001'; codPostales['Burgos'] = '09001'; codPostales['Cáceres'] = '10001'; codPostales['Cádiz'] = '11001'; codPostales['Cantabria'] = '39001'; codPostales['Castellón'] = '12001'; codPostales['Ceuta'] = '51001'; codPostales['Ciudad Real'] = '13001'; codPostales['Córdoba'] = '14001'; codPostales['Cuenca'] = '16001'; codPostales['Girona'] = '17001'; codPostales['Granada'] = '18001'; codPostales['Guadalajara'] = '19001'; codPostales['Guipúzcoa'] = '20001'; codPostales['Huelva'] = '21001'; codPostales['Huesca'] = '22001'; codPostales['Jaén'] = '23001'; codPostales['La Rioja'] = '26001'; codPostales['Las Palmas'] = '35001'; codPostales['León'] = '24001'; codPostales['Lleida'] = '25001'; codPostales['Lugo'] = '27001'; codPostales['Madrid'] = '28001'; codPostales['Málaga'] = '29001'; codPostales['Melilla'] = '52001'; codPostales['Murcia'] = '30001'; codPostales['Navarra'] = '31001'; codPostales['Ourense'] = '32001'; codPostales['Palencia'] = '34001'; codPostales['Pontevedra'] = '36001'; codPostales['S.C. Tenerife'] = '38001'; codPostales['Salamanca'] = '37001'; codPostales['Segovia'] = '40001'; codPostales['Sevilla'] = '41001'; codPostales['Soria'] = '42001'; codPostales['Tarragona'] = '43001'; codPostales['Teruel'] = '44001'; codPostales['Toledo'] = '45001'; codPostales['Valencia'] = '46001'; codPostales['Valladolid'] = '47001'; codPostales['Vizcaya'] = '48001'; codPostales['Zamora'] = '49001'; codPostales['Zaragoza'] = '50001'; }
{ return false; }
conditional_block
getLocations.js
'use strict'; /* INSTRUCCIONES - Ejecutar getLocations - Ejecutar correlateCines para a mano encontrar correlaciones. */ var request = require('request'), cheerio = require('cheerio'), mongoose = require('mongoose'), md5 = require('md5'), fs = require('fs'), async = require('async'), events = require('events'), compare = require('levenshtein'), modelos = require('./models/models.js'), urlBase = 'http://www.ecartelera.com/', urlIMDB = 'http://www.imdb.com/showtimes/ES/', provincias = [], cines = [], codPostales = [], correlations = []; var contadorE = 0, listaCadenas = '', listaIds = '', correlados = ''; //Conecto a mongo mongoose.connect(process.env.OPENSHIFT_MONGODB_DB_URL + process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/cine', { db: {safe: true} }); //Gestor de eventos var eventEmitter = new events.EventEmitter(); initCodPostalesArray(); //Cojo de mongo las correlaciones modelos.Correlation .find().exec(function (err, correlat) { if (!err) { //Array de corr correlat.forEach(function (corr) { correlations[corr.cineId] = corr.imdbId; }); getProvincias(); } }); //Cojo la web de provincias function getProvincias() { request(urlBase + 'cartelera', function (err, resp, body) { if (err || resp.statusCode !== 200) { console.log('Se produjo un error'); throw err; } var $ = cheerio.load(body); /*var fs = require('fs'); fs.writeFile("tmp/provincias.html", body, function (err) { if (err) { return console.log(err); } console.log("The file was saved!"); });*/ console.log(' - - '); console.log(' ------------ Obtengo provincias -------------- '); console.log(' - - '); //Por cada provincia... $('ul.cityselector li a').each(function () { var pId = extractId($(this).attr('href')); if (pId === null) { return false; } var name = $(this).text().trim(); console.log(' ·Provincia: ' + name + ' (Id: ' + pId + ')'); provincias.push({ _id: md5(pId), provinciaId: pId, nombre: name, ciudades: [], actualizado: new Date().getTime(), sortfield: sortfielizar(name) }); }); //console.log(provincias); console.log(' - - '); console.log(' ------------ Obtengo ciudades y cines -------------- '); console.log(' - - '); //Por cada provincia voy recogiendo sus ciudades y cines async.map(provincias, getCiudades, function (err, results) { if (err) { throw err; } else { provincias = results; //Lanzo el proceso de actualización en Mongo de las cosas eventEmitter.emit('updateProvincias', provincias); } }); }); } //Obtiene las ciudades de una provincia y sus cines function getCiudades(provincia, callback) {
l evento de actualizar provincias y ciudades en Mongo eventEmitter.on('updateProvincias', function (misProvincias) { //Limpio la colección de provincias modelos.Provincia.remove({}, function (err) { }); //Guardo en base de datos modelos.Provincia.create(misProvincias, function (err) { if (err) { console.error(err); } console.log(' Mongo - He metido ' + misProvincias.length + ' provincias'); //Emito señal para continuar eventEmitter.emit('updateCines', cines); }); }); //Listener del evento de actualizar cines en Mongo eventEmitter.on('updateCines', function (misCines) { //Limpio la colección de cines modelos.Cine.remove({}, function (err) { }); //Guardo en base de datos modelos.Cine.create(misCines, function (err) { if (err) { console.error(err); } console.log(' Mongo - He metido ' + misCines.length + ' cines'); //Finalizo eventEmitter.emit('finalize'); }); }); //Listener del evento de terminar eventEmitter.on('finalize', function () { mongoose.disconnect(); console.log('Finalizado'); console.log('No encontré: ' + contadorE); fs.writeFileSync("cadenasNotFound.txt", listaCadenas); fs.writeFileSync("idsNotFound.txt", listaIds); fs.writeFileSync("correlados.txt", correlados); //Finalizo process.exit(); }); //Extrae el id de un enlace http://www.ecartelera.com/cines/0,165,0.html que es 0,165,0.html function extractId(href) { var patt = /(\/cines\/)(.+)/; var res = patt.exec(href); if (res !== null) { return res[2]; } else { return null; } } function extractIMDBId(href) { var patt = /(.*\/)(ci[0-9]+)(\/.*)/; var res = patt.exec(href); if (res !== null) { return res[2]; } else { return null; } } function sortfielizar(text) { text = text.toLowerCase(); text = text.replace(' ', '_'); text = text.replace('.', '_'); text = text.replace('á', 'a'); text = text.replace('é', 'e'); text = text.replace('í', 'i'); text = text.replace('ó', 'o'); text = text.replace('ú', 'u'); text = text.replace('ñ', 'n'); return text; } //Elimina ciertas palabras para poder comparar mejor function prepareToCompare(text) { text = text.replace(/Cine(s)?/g, ''); return text; } function initCodPostalesArray() { codPostales['A Coruña'] = '15001'; codPostales['Álava'] = '01001'; codPostales['Albacete'] = '02001'; codPostales['Alicante'] = '03001'; codPostales['Almería'] = '04001'; codPostales['Asturias'] = '33001'; codPostales['Ávila'] = '05001'; codPostales['Badajoz'] = '06001'; codPostales['Baleares'] = '07001'; codPostales['Barcelona'] = '08001'; codPostales['Burgos'] = '09001'; codPostales['Cáceres'] = '10001'; codPostales['Cádiz'] = '11001'; codPostales['Cantabria'] = '39001'; codPostales['Castellón'] = '12001'; codPostales['Ceuta'] = '51001'; codPostales['Ciudad Real'] = '13001'; codPostales['Córdoba'] = '14001'; codPostales['Cuenca'] = '16001'; codPostales['Girona'] = '17001'; codPostales['Granada'] = '18001'; codPostales['Guadalajara'] = '19001'; codPostales['Guipúzcoa'] = '20001'; codPostales['Huelva'] = '21001'; codPostales['Huesca'] = '22001'; codPostales['Jaén'] = '23001'; codPostales['La Rioja'] = '26001'; codPostales['Las Palmas'] = '35001'; codPostales['León'] = '24001'; codPostales['Lleida'] = '25001'; codPostales['Lugo'] = '27001'; codPostales['Madrid'] = '28001'; codPostales['Málaga'] = '29001'; codPostales['Melilla'] = '52001'; codPostales['Murcia'] = '30001'; codPostales['Navarra'] = '31001'; codPostales['Ourense'] = '32001'; codPostales['Palencia'] = '34001'; codPostales['Pontevedra'] = '36001'; codPostales['S.C. Tenerife'] = '38001'; codPostales['Salamanca'] = '37001'; codPostales['Segovia'] = '40001'; codPostales['Sevilla'] = '41001'; codPostales['Soria'] = '42001'; codPostales['Tarragona'] = '43001'; codPostales['Teruel'] = '44001'; codPostales['Toledo'] = '45001'; codPostales['Valencia'] = '46001'; codPostales['Valladolid'] = '47001'; codPostales['Vizcaya'] = '48001'; codPostales['Zamora'] = '49001'; codPostales['Zaragoza'] = '50001'; }
var enlaceCiudad = urlBase + 'cines/' + provincia.provinciaId; console.log(' -- Miro las ciudades del enlace: ' + enlaceCiudad); //Saco el id de IMBD del cine var codpost = codPostales[provincia.nombre]; //Lo consulto en IMDB request(urlIMDB + codpost, function (err, response, body) { if (err) { callback(err); } else { var $IMDB = cheerio.load(body); request(enlaceCiudad, function (err, response, body) { if (err) { callback(err); } else { var $ = cheerio.load(body), lastCityId = 0, lastCityName = ''; var counter = 0; //Saco las ciudades y de paso los cines también $('ul.cityselector li').each(function () { var enlace = $(this).find('a'); //Si es título, es que es ciudad if ($(this).hasClass('tit')) { var cityId = lastCityId = extractId(enlace.attr('href')); var cityName = lastCityName = enlace.text().trim(); console.log(' ··Ciudad: ' + cityName + ' (Id: ' + cityId + ')'); //Añado la ciudad a la lista de la provincia provincia.ciudades.push({ _id: md5(cityId), ciudadId: cityId, nombre: cityName, actualizado: 0 }); } else { //Si no está inactivo, es un cine de la ciudad if (!enlace.hasClass('inactivo') && lastCityId !== 0) { var cineId = extractId(enlace.attr('href')); var cineName = enlace.text().trim(); var idIMDB = null, nameIMDB = ''; var nombresIMDB = '', idsIMDB = ''; console.log(' ··Cine: ' + cineName + ' (Id: ' + cineId + ')'); //Si ya está el id del cine correlado no hago más que añadirlos a la lista de correlados if (correlations[cineId] !== undefined) { idIMDB = correlations[cineId]; correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB; } else { //INTENTO SACARLOS. Por cada cine en IMDB comparo a ver si es este cine $IMDB('div[itemtype="http://schema.org/MovieTheater"]').each(function () { var h3Cine = $(this).find('h3'); var enlaceCine = h3Cine.find('a[itemprop="url"]'); var thisIdIMDB = extractIMDBId(enlaceCine.attr('href').trim()); //Comparo nombres nameIMDB = enlaceCine.text().trim(); //Auxiliares nombresIMDB = (nombresIMDB == '') ? nameIMDB : nombresIMDB + '||' + nameIMDB; idsIMDB = (idsIMDB == '') ? thisIdIMDB : idsIMDB + '||' + thisIdIMDB; var comparison = new compare(prepareToCompare(nameIMDB), prepareToCompare(cineName)); if (comparison.distance < 4) { idIMDB = thisIdIMDB; return false; //salgo del bucle } else { //Comprobaciones extra if (cineName.indexOf(nameIMDB) > -1 || nameIMDB.indexOf(cineName) > -1) { idIMDB = thisIdIMDB; return false; } } }); if (idIMDB === null) { //console.log(' *** No encontré el cine << ' + cineName + ' >> de ' + lastCityName + ' (' + provincia.nombre + ') CODPOSTAL: ' + codpost); //console.log(' *** De entre estos: ' + nombresIMDB); listaCadenas = (listaCadenas == '') ? cineName + '##' + nombresIMDB : listaCadenas + '$$' + cineName + '##' + nombresIMDB; listaIds = (listaIds == '') ? cineId + '##' + idsIMDB : listaIds + '$$' + cineId + '##' + idsIMDB; counter = counter + 1; contadorE++; } else { console.log(" --IMDB: " + nameIMDB + ' (Id: ' + idIMDB + ')'); correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB; } } //Añado el cine a la lista de cines cines.push({ _id: md5(cineId), cineId: cineId, imdbId: idIMDB, nombre: cineName, _idCiudad: md5(lastCityId), nombreCiudad: lastCityName, actualizado: 0 }); } } }); console.log('No encontré de esta provincia: ' + counter); callback(null, provincia); // First param indicates error, null=> no error } }); } }); } //Listener de
identifier_body
order.js
var OrderModel = require('./OrderModel'); function
(order) { this.name = order.name; this.sex = order.sex; this.age = order.age; this.mobile = order.mobile; this.price = order.price; this.userId = order.userId; this.activityId = order.activityId; this.activityTitle = order.activityTitle; this.activityPic = order.activityPic; this.activityTime = order.activityTime; this.state = order.state; this.orderTime = order.orderTime; this.createTime = order.createTime; this.updateTime = order.updateTime; } module.exports = Order; Order.prototype.save = function(callback) { var order = { name: this.name, sex: this.sex, age: this.age, mobile: this.mobile, orderNo: new Date().getTime(), price: this.price, userId: this.userId, activityId: this.activityId, activityTitle: this.activityTitle, activityPic: this.activityPic, activityTime: this.activityTime, state: this.state, orderTime: new Date(), createTime: new Date(), updateTime: new Date() }; var newOrder = new OrderModel(order); newOrder.save(function (err, order) { if(err) { return callback(err); } callback(err, order); }); }; Order.getAll = function(skip, limit, callback) { OrderModel.count(function(err, count) { OrderModel.find({}, null, {skip: skip, limit: limit},function (err, orders) { if(err) { return callback(err); } callback(err, orders, count); }); }); }; Order.getByUserId = function(skip, limit, userId, callback) { OrderModel.count(function(err, count) { OrderModel.find({userId: userId}, null, {skip: skip, limit: limit},function (err, orders) { if(err) { return callback(err); } callback(err, orders, count); }); }); };
Order
identifier_name
order.js
var OrderModel = require('./OrderModel'); function Order(order) { this.name = order.name; this.sex = order.sex; this.age = order.age; this.mobile = order.mobile; this.price = order.price; this.userId = order.userId; this.activityId = order.activityId; this.activityTitle = order.activityTitle; this.activityPic = order.activityPic; this.activityTime = order.activityTime; this.state = order.state; this.orderTime = order.orderTime; this.createTime = order.createTime; this.updateTime = order.updateTime; } module.exports = Order; Order.prototype.save = function(callback) { var order = { name: this.name, sex: this.sex, age: this.age, mobile: this.mobile, orderNo: new Date().getTime(), price: this.price, userId: this.userId, activityId: this.activityId, activityTitle: this.activityTitle, activityPic: this.activityPic, activityTime: this.activityTime, state: this.state, orderTime: new Date(), createTime: new Date(), updateTime: new Date() }; var newOrder = new OrderModel(order); newOrder.save(function (err, order) { if(err) {
}); }; Order.getAll = function(skip, limit, callback) { OrderModel.count(function(err, count) { OrderModel.find({}, null, {skip: skip, limit: limit},function (err, orders) { if(err) { return callback(err); } callback(err, orders, count); }); }); }; Order.getByUserId = function(skip, limit, userId, callback) { OrderModel.count(function(err, count) { OrderModel.find({userId: userId}, null, {skip: skip, limit: limit},function (err, orders) { if(err) { return callback(err); } callback(err, orders, count); }); }); };
return callback(err); } callback(err, order);
random_line_split
order.js
var OrderModel = require('./OrderModel'); function Order(order) { this.name = order.name; this.sex = order.sex; this.age = order.age; this.mobile = order.mobile; this.price = order.price; this.userId = order.userId; this.activityId = order.activityId; this.activityTitle = order.activityTitle; this.activityPic = order.activityPic; this.activityTime = order.activityTime; this.state = order.state; this.orderTime = order.orderTime; this.createTime = order.createTime; this.updateTime = order.updateTime; } module.exports = Order; Order.prototype.save = function(callback) { var order = { name: this.name, sex: this.sex, age: this.age, mobile: this.mobile, orderNo: new Date().getTime(), price: this.price, userId: this.userId, activityId: this.activityId, activityTitle: this.activityTitle, activityPic: this.activityPic, activityTime: this.activityTime, state: this.state, orderTime: new Date(), createTime: new Date(), updateTime: new Date() }; var newOrder = new OrderModel(order); newOrder.save(function (err, order) { if(err) { return callback(err); } callback(err, order); }); }; Order.getAll = function(skip, limit, callback) { OrderModel.count(function(err, count) { OrderModel.find({}, null, {skip: skip, limit: limit},function (err, orders) { if(err) { return callback(err); } callback(err, orders, count); }); }); }; Order.getByUserId = function(skip, limit, userId, callback) { OrderModel.count(function(err, count) { OrderModel.find({userId: userId}, null, {skip: skip, limit: limit},function (err, orders) { if(err)
callback(err, orders, count); }); }); };
{ return callback(err); }
conditional_block
order.js
var OrderModel = require('./OrderModel'); function Order(order)
module.exports = Order; Order.prototype.save = function(callback) { var order = { name: this.name, sex: this.sex, age: this.age, mobile: this.mobile, orderNo: new Date().getTime(), price: this.price, userId: this.userId, activityId: this.activityId, activityTitle: this.activityTitle, activityPic: this.activityPic, activityTime: this.activityTime, state: this.state, orderTime: new Date(), createTime: new Date(), updateTime: new Date() }; var newOrder = new OrderModel(order); newOrder.save(function (err, order) { if(err) { return callback(err); } callback(err, order); }); }; Order.getAll = function(skip, limit, callback) { OrderModel.count(function(err, count) { OrderModel.find({}, null, {skip: skip, limit: limit},function (err, orders) { if(err) { return callback(err); } callback(err, orders, count); }); }); }; Order.getByUserId = function(skip, limit, userId, callback) { OrderModel.count(function(err, count) { OrderModel.find({userId: userId}, null, {skip: skip, limit: limit},function (err, orders) { if(err) { return callback(err); } callback(err, orders, count); }); }); };
{ this.name = order.name; this.sex = order.sex; this.age = order.age; this.mobile = order.mobile; this.price = order.price; this.userId = order.userId; this.activityId = order.activityId; this.activityTitle = order.activityTitle; this.activityPic = order.activityPic; this.activityTime = order.activityTime; this.state = order.state; this.orderTime = order.orderTime; this.createTime = order.createTime; this.updateTime = order.updateTime; }
identifier_body
set_pusher.rs
//! [POST /_matrix/client/r0/pushers/set](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-pushers-set) use ruma_api::ruma_api; use super::Pusher; ruma_api! { metadata { description: "This endpoint allows the creation, modification and deletion of pushers for this user ID.", method: POST, name: "set_pusher", path: "/_matrix/client/r0/pushers/set",
request { /// The pusher to configure #[serde(flatten)] pub pusher: Pusher, /// Controls if another pusher with the same pushkey and app id should be created. /// See the spec for details. #[serde(default)] pub append: bool } response {} error: crate::Error }
rate_limited: true, requires_authentication: true, }
random_line_split
clean_mac_info_plist.py
#!/usr/bin/env python # Jonas Schnelli, 2013 # make sure the KombatKoin-Qt.app contains the right plist (including the right version) # fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267) from string import Template from datetime import date bitcoinDir = "./";
outFile = "KombatKoin-Qt.app/Contents/Info.plist" version = "unknown"; fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro" for line in open(fileForGrabbingVersion): lineArr = line.replace(" ", "").split("="); if lineArr[0].startswith("VERSION"): version = lineArr[1].replace("\n", ""); fIn = open(inFile, "r") fileContent = fIn.read() s = Template(fileContent) newFileContent = s.substitute(VERSION=version,YEAR=date.today().year) fOut = open(outFile, "w"); fOut.write(newFileContent); print "Info.plist fresh created"
inFile = bitcoinDir+"/share/qt/Info.plist"
random_line_split
clean_mac_info_plist.py
#!/usr/bin/env python # Jonas Schnelli, 2013 # make sure the KombatKoin-Qt.app contains the right plist (including the right version) # fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267) from string import Template from datetime import date bitcoinDir = "./"; inFile = bitcoinDir+"/share/qt/Info.plist" outFile = "KombatKoin-Qt.app/Contents/Info.plist" version = "unknown"; fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro" for line in open(fileForGrabbingVersion):
fIn = open(inFile, "r") fileContent = fIn.read() s = Template(fileContent) newFileContent = s.substitute(VERSION=version,YEAR=date.today().year) fOut = open(outFile, "w"); fOut.write(newFileContent); print "Info.plist fresh created"
lineArr = line.replace(" ", "").split("="); if lineArr[0].startswith("VERSION"): version = lineArr[1].replace("\n", "");
conditional_block
lib.rs
//! rimd is a set of utilities to deal with midi messages and standard //! midi files (SMF). It handles both standard midi messages and the meta //! messages that are found in SMFs. //! //! rimd is fairly low level, and messages are stored and accessed in //! their underlying format (i.e. a vector of u8s). There are some //! utility methods for accessing the various pieces of a message, and //! for constructing new messages. //! //! For example usage see the bin directory. //! //! For a description of the underlying format of midi messages see:<br/> //! http://www.midi.org/techspecs/midimessages.php<br/> //! For a description of the underlying format of meta messages see:<br/> //! http://cs.fit.edu/~ryan/cse4051/projects/midi/midi.html#meta_event extern crate byteorder; extern crate encoding; extern crate num_traits; #[macro_use] extern crate num_derive; use std::error; use std::convert::From; use std::fs::File; use std::io::{Error,Read}; use std::path::Path; use std::fmt; use std::string::FromUtf8Error; pub use midi:: { Status, MidiError, MidiMessage, STATUS_MASK, CHANNEL_MASK, make_status, }; pub use meta:: { MetaCommand, MetaError, MetaEvent, }; pub use builder:: { SMFBuilder, AbsoluteEvent, }; use reader:: { SMFReader, }; pub use writer:: { SMFWriter, }; pub use util:: { note_num_to_name, }; mod builder; mod midi; mod meta; mod reader; mod writer; mod util; /// Format of the SMF #[derive(Debug,Clone,Copy,PartialEq)] pub enum SMFFormat { /// single track file format Single = 0, /// multiple track file format MultiTrack = 1, /// multiple song file format (i.e., a series of single type files) MultiSong = 2, } impl fmt::Display for SMFFormat { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}",match *self { SMFFormat::Single => "single track", SMFFormat::MultiTrack => "multiple track", SMFFormat::MultiSong => "multiple song", }) } } /// An event can be either a midi message or a meta event #[derive(Debug,Clone)] pub enum
{ Midi(MidiMessage), Meta(MetaEvent), } impl fmt::Display for Event { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Event::Midi(ref m) => { write!(f, "{}", m) } Event::Meta(ref m) => { write!(f, "{}", m) } } } } impl Event { /// Return the number of bytes this event uses. pub fn len(&self) -> usize { match *self { Event::Midi(ref m) => { m.data.len() } Event::Meta(ref m) => { let v = SMFWriter::vtime_to_vec(m.length); // +1 for command byte +1 for 0xFF to indicate Meta event v.len() + m.data.len() + 2 } } } } /// An event occuring in the track. #[derive(Debug,Clone)] pub struct TrackEvent { /// A delta offset, indicating how many ticks after the previous /// event this event occurs pub vtime: u64, /// The actual event pub event: Event, } impl fmt::Display for TrackEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "vtime: {}\t{}",self.vtime,self.event) } } impl TrackEvent { pub fn fmt_with_time_offset(&self, cur_time: u64) -> String { format!("time: {}\t{}",(self.vtime+cur_time),self.event) } /// Return the number of bytes this event uses in the track, /// including the space for the time offset. pub fn len(&self) -> usize { let v = SMFWriter::vtime_to_vec(self.vtime); v.len() + self.event.len() } } /// A sequence of midi/meta events #[derive(Debug, Clone)] pub struct Track { /// Optional copyright notice pub copyright: Option<String>, /// Optional name for this track pub name: Option<String>, /// Vector of the events in this track pub events: Vec<TrackEvent> } impl fmt::Display for Track { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Track, copyright: {}, name: {}", match self.copyright { Some(ref c) => &c[..], None => "[none]" }, match self.name { Some(ref n) => &n[..], None => "[none]" }) } } /// An error that occured in parsing an SMF #[derive(Debug)] pub enum SMFError { InvalidSMFFile(&'static str), MidiError(MidiError), MetaError(MetaError), Error(Error), } impl From<Error> for SMFError { fn from(err: Error) -> SMFError { SMFError::Error(err) } } impl From<MidiError> for SMFError { fn from(err: MidiError) -> SMFError { SMFError::MidiError(err) } } impl From<MetaError> for SMFError { fn from(err: MetaError) -> SMFError { SMFError::MetaError(err) } } impl From<FromUtf8Error> for SMFError { fn from(_: FromUtf8Error) -> SMFError { SMFError::InvalidSMFFile("Invalid UTF8 data in file") } } impl error::Error for SMFError { fn description(&self) -> &str { match *self { SMFError::InvalidSMFFile(_) => "The SMF file was invalid", SMFError::Error(ref e) => e.description(), SMFError::MidiError(ref m) => m.description(), SMFError::MetaError(ref m) => m.description(), } } fn cause(&self) -> Option<&error::Error> { match *self { SMFError::MidiError(ref m) => Some(m as &error::Error), SMFError::MetaError(ref m) => Some(m as &error::Error), SMFError::Error(ref err) => Some(err as &error::Error), _ => None, } } } impl fmt::Display for SMFError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SMFError::InvalidSMFFile(s) => write!(f,"SMF file is invalid: {}",s), SMFError::MidiError(ref err) => { write!(f,"{}",err) }, SMFError::MetaError(ref err) => { write!(f,"{}",err) }, SMFError::Error(ref err) => { write!(f,"{}",err) }, } } } /// A standard midi file #[derive(Debug, Clone)] pub struct SMF { /// The format of the SMF pub format: SMFFormat, /// Vector holding each track in this SMF pub tracks: Vec<Track>, /// The unit of time for delta timing. If the value is positive, /// then it represents the units per beat. For example, +96 would /// mean 96 ticks per beat. If the value is negative, delta times /// are in SMPTE compatible units. pub division: i16, } impl SMF { /// Read an SMF file at the given path pub fn from_file(path: &Path) -> Result<SMF,SMFError> { let mut file = try!(File::open(path)); SMFReader::read_smf(&mut file) } /// Read an SMF from the given reader pub fn from_reader(reader: &mut Read) -> Result<SMF,SMFError> { SMFReader::read_smf(reader) } /// Convert a type 0 (single track) to type 1 (multi track) SMF /// Does nothing if the SMF is already in type 1 /// Returns None if the SMF is in type 2 (multi song) pub fn to_multi_track(&self) -> Option<SMF> { match self.format { SMFFormat::MultiTrack => Some(self.clone()), SMFFormat::MultiSong => None, SMFFormat::Single => { let mut tracks = vec![Vec::<TrackEvent>::new(); 1 + 16]; // meta track and 16 for the 16 channels let mut time = 0; for event in &self.tracks[0].events { time += event.vtime; match event.event { Event::Midi(ref msg) if msg.channel().is_some() => { let events = &mut tracks[msg.channel().unwrap() as usize + 1]; events.push(TrackEvent {vtime: time, event: event.event.clone()}); } /*MidiEvent::Meta(ref msg) if [ MetaCommand::MIDIChannelPrefixAssignment, MetaCommand::MIDIPortPrefixAssignment, MetaCommand::SequenceOrTrackName, MetaCommand::InstrumentName, ].contains(&msg.command) => { println!("prefix: {:?}", event); }*/ _ => { tracks[0].push(TrackEvent {vtime: time, event: event.event.clone()}); } } } let mut out = SMF { format: SMFFormat::MultiTrack, tracks: vec![], division: self.division, }; for events in &mut tracks { if events.len() > 0 { let mut time = 0; for event in events.iter_mut() { let tmp = event.vtime; event.vtime -= time; time = tmp; } out.tracks.push(Track {events: events.clone(), copyright: None, name: None}); } } out.tracks[0].name = self.tracks[0].name.clone(); out.tracks[0].copyright = self.tracks[0].copyright.clone(); Some(out) } } } }
Event
identifier_name
lib.rs
//! rimd is a set of utilities to deal with midi messages and standard //! midi files (SMF). It handles both standard midi messages and the meta //! messages that are found in SMFs. //! //! rimd is fairly low level, and messages are stored and accessed in //! their underlying format (i.e. a vector of u8s). There are some //! utility methods for accessing the various pieces of a message, and //! for constructing new messages. //! //! For example usage see the bin directory. //! //! For a description of the underlying format of midi messages see:<br/> //! http://www.midi.org/techspecs/midimessages.php<br/> //! For a description of the underlying format of meta messages see:<br/> //! http://cs.fit.edu/~ryan/cse4051/projects/midi/midi.html#meta_event extern crate byteorder; extern crate encoding; extern crate num_traits; #[macro_use] extern crate num_derive; use std::error; use std::convert::From; use std::fs::File; use std::io::{Error,Read}; use std::path::Path; use std::fmt; use std::string::FromUtf8Error; pub use midi:: { Status, MidiError, MidiMessage, STATUS_MASK, CHANNEL_MASK, make_status, }; pub use meta:: { MetaCommand, MetaError, MetaEvent, }; pub use builder:: { SMFBuilder, AbsoluteEvent, }; use reader:: { SMFReader, }; pub use writer:: { SMFWriter, }; pub use util:: { note_num_to_name, }; mod builder; mod midi; mod meta; mod reader; mod writer; mod util; /// Format of the SMF #[derive(Debug,Clone,Copy,PartialEq)] pub enum SMFFormat { /// single track file format Single = 0, /// multiple track file format MultiTrack = 1, /// multiple song file format (i.e., a series of single type files) MultiSong = 2, } impl fmt::Display for SMFFormat { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}",match *self { SMFFormat::Single => "single track", SMFFormat::MultiTrack => "multiple track", SMFFormat::MultiSong => "multiple song", }) } } /// An event can be either a midi message or a meta event #[derive(Debug,Clone)] pub enum Event { Midi(MidiMessage), Meta(MetaEvent), } impl fmt::Display for Event { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Event::Midi(ref m) => { write!(f, "{}", m) } Event::Meta(ref m) => { write!(f, "{}", m) } } } } impl Event { /// Return the number of bytes this event uses. pub fn len(&self) -> usize { match *self { Event::Midi(ref m) => { m.data.len() } Event::Meta(ref m) => { let v = SMFWriter::vtime_to_vec(m.length); // +1 for command byte +1 for 0xFF to indicate Meta event v.len() + m.data.len() + 2 } } } } /// An event occuring in the track. #[derive(Debug,Clone)] pub struct TrackEvent { /// A delta offset, indicating how many ticks after the previous /// event this event occurs pub vtime: u64, /// The actual event pub event: Event, } impl fmt::Display for TrackEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "vtime: {}\t{}",self.vtime,self.event) } } impl TrackEvent { pub fn fmt_with_time_offset(&self, cur_time: u64) -> String { format!("time: {}\t{}",(self.vtime+cur_time),self.event) } /// Return the number of bytes this event uses in the track, /// including the space for the time offset. pub fn len(&self) -> usize { let v = SMFWriter::vtime_to_vec(self.vtime); v.len() + self.event.len() } } /// A sequence of midi/meta events #[derive(Debug, Clone)] pub struct Track { /// Optional copyright notice pub copyright: Option<String>, /// Optional name for this track pub name: Option<String>, /// Vector of the events in this track pub events: Vec<TrackEvent> } impl fmt::Display for Track { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Track, copyright: {}, name: {}", match self.copyright { Some(ref c) => &c[..], None => "[none]" }, match self.name { Some(ref n) => &n[..], None => "[none]" }) } } /// An error that occured in parsing an SMF #[derive(Debug)] pub enum SMFError { InvalidSMFFile(&'static str), MidiError(MidiError), MetaError(MetaError), Error(Error), } impl From<Error> for SMFError { fn from(err: Error) -> SMFError { SMFError::Error(err) } } impl From<MidiError> for SMFError { fn from(err: MidiError) -> SMFError { SMFError::MidiError(err) } }
fn from(err: MetaError) -> SMFError { SMFError::MetaError(err) } } impl From<FromUtf8Error> for SMFError { fn from(_: FromUtf8Error) -> SMFError { SMFError::InvalidSMFFile("Invalid UTF8 data in file") } } impl error::Error for SMFError { fn description(&self) -> &str { match *self { SMFError::InvalidSMFFile(_) => "The SMF file was invalid", SMFError::Error(ref e) => e.description(), SMFError::MidiError(ref m) => m.description(), SMFError::MetaError(ref m) => m.description(), } } fn cause(&self) -> Option<&error::Error> { match *self { SMFError::MidiError(ref m) => Some(m as &error::Error), SMFError::MetaError(ref m) => Some(m as &error::Error), SMFError::Error(ref err) => Some(err as &error::Error), _ => None, } } } impl fmt::Display for SMFError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SMFError::InvalidSMFFile(s) => write!(f,"SMF file is invalid: {}",s), SMFError::MidiError(ref err) => { write!(f,"{}",err) }, SMFError::MetaError(ref err) => { write!(f,"{}",err) }, SMFError::Error(ref err) => { write!(f,"{}",err) }, } } } /// A standard midi file #[derive(Debug, Clone)] pub struct SMF { /// The format of the SMF pub format: SMFFormat, /// Vector holding each track in this SMF pub tracks: Vec<Track>, /// The unit of time for delta timing. If the value is positive, /// then it represents the units per beat. For example, +96 would /// mean 96 ticks per beat. If the value is negative, delta times /// are in SMPTE compatible units. pub division: i16, } impl SMF { /// Read an SMF file at the given path pub fn from_file(path: &Path) -> Result<SMF,SMFError> { let mut file = try!(File::open(path)); SMFReader::read_smf(&mut file) } /// Read an SMF from the given reader pub fn from_reader(reader: &mut Read) -> Result<SMF,SMFError> { SMFReader::read_smf(reader) } /// Convert a type 0 (single track) to type 1 (multi track) SMF /// Does nothing if the SMF is already in type 1 /// Returns None if the SMF is in type 2 (multi song) pub fn to_multi_track(&self) -> Option<SMF> { match self.format { SMFFormat::MultiTrack => Some(self.clone()), SMFFormat::MultiSong => None, SMFFormat::Single => { let mut tracks = vec![Vec::<TrackEvent>::new(); 1 + 16]; // meta track and 16 for the 16 channels let mut time = 0; for event in &self.tracks[0].events { time += event.vtime; match event.event { Event::Midi(ref msg) if msg.channel().is_some() => { let events = &mut tracks[msg.channel().unwrap() as usize + 1]; events.push(TrackEvent {vtime: time, event: event.event.clone()}); } /*MidiEvent::Meta(ref msg) if [ MetaCommand::MIDIChannelPrefixAssignment, MetaCommand::MIDIPortPrefixAssignment, MetaCommand::SequenceOrTrackName, MetaCommand::InstrumentName, ].contains(&msg.command) => { println!("prefix: {:?}", event); }*/ _ => { tracks[0].push(TrackEvent {vtime: time, event: event.event.clone()}); } } } let mut out = SMF { format: SMFFormat::MultiTrack, tracks: vec![], division: self.division, }; for events in &mut tracks { if events.len() > 0 { let mut time = 0; for event in events.iter_mut() { let tmp = event.vtime; event.vtime -= time; time = tmp; } out.tracks.push(Track {events: events.clone(), copyright: None, name: None}); } } out.tracks[0].name = self.tracks[0].name.clone(); out.tracks[0].copyright = self.tracks[0].copyright.clone(); Some(out) } } } }
impl From<MetaError> for SMFError {
random_line_split
lib.rs
//! rimd is a set of utilities to deal with midi messages and standard //! midi files (SMF). It handles both standard midi messages and the meta //! messages that are found in SMFs. //! //! rimd is fairly low level, and messages are stored and accessed in //! their underlying format (i.e. a vector of u8s). There are some //! utility methods for accessing the various pieces of a message, and //! for constructing new messages. //! //! For example usage see the bin directory. //! //! For a description of the underlying format of midi messages see:<br/> //! http://www.midi.org/techspecs/midimessages.php<br/> //! For a description of the underlying format of meta messages see:<br/> //! http://cs.fit.edu/~ryan/cse4051/projects/midi/midi.html#meta_event extern crate byteorder; extern crate encoding; extern crate num_traits; #[macro_use] extern crate num_derive; use std::error; use std::convert::From; use std::fs::File; use std::io::{Error,Read}; use std::path::Path; use std::fmt; use std::string::FromUtf8Error; pub use midi:: { Status, MidiError, MidiMessage, STATUS_MASK, CHANNEL_MASK, make_status, }; pub use meta:: { MetaCommand, MetaError, MetaEvent, }; pub use builder:: { SMFBuilder, AbsoluteEvent, }; use reader:: { SMFReader, }; pub use writer:: { SMFWriter, }; pub use util:: { note_num_to_name, }; mod builder; mod midi; mod meta; mod reader; mod writer; mod util; /// Format of the SMF #[derive(Debug,Clone,Copy,PartialEq)] pub enum SMFFormat { /// single track file format Single = 0, /// multiple track file format MultiTrack = 1, /// multiple song file format (i.e., a series of single type files) MultiSong = 2, } impl fmt::Display for SMFFormat { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}",match *self { SMFFormat::Single => "single track", SMFFormat::MultiTrack => "multiple track", SMFFormat::MultiSong => "multiple song", }) } } /// An event can be either a midi message or a meta event #[derive(Debug,Clone)] pub enum Event { Midi(MidiMessage), Meta(MetaEvent), } impl fmt::Display for Event { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Event::Midi(ref m) => { write!(f, "{}", m) } Event::Meta(ref m) => { write!(f, "{}", m) } } } } impl Event { /// Return the number of bytes this event uses. pub fn len(&self) -> usize { match *self { Event::Midi(ref m) => { m.data.len() } Event::Meta(ref m) => { let v = SMFWriter::vtime_to_vec(m.length); // +1 for command byte +1 for 0xFF to indicate Meta event v.len() + m.data.len() + 2 } } } } /// An event occuring in the track. #[derive(Debug,Clone)] pub struct TrackEvent { /// A delta offset, indicating how many ticks after the previous /// event this event occurs pub vtime: u64, /// The actual event pub event: Event, } impl fmt::Display for TrackEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "vtime: {}\t{}",self.vtime,self.event) } } impl TrackEvent { pub fn fmt_with_time_offset(&self, cur_time: u64) -> String { format!("time: {}\t{}",(self.vtime+cur_time),self.event) } /// Return the number of bytes this event uses in the track, /// including the space for the time offset. pub fn len(&self) -> usize { let v = SMFWriter::vtime_to_vec(self.vtime); v.len() + self.event.len() } } /// A sequence of midi/meta events #[derive(Debug, Clone)] pub struct Track { /// Optional copyright notice pub copyright: Option<String>, /// Optional name for this track pub name: Option<String>, /// Vector of the events in this track pub events: Vec<TrackEvent> } impl fmt::Display for Track { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Track, copyright: {}, name: {}", match self.copyright { Some(ref c) => &c[..], None => "[none]" }, match self.name { Some(ref n) => &n[..], None => "[none]" }) } } /// An error that occured in parsing an SMF #[derive(Debug)] pub enum SMFError { InvalidSMFFile(&'static str), MidiError(MidiError), MetaError(MetaError), Error(Error), } impl From<Error> for SMFError { fn from(err: Error) -> SMFError { SMFError::Error(err) } } impl From<MidiError> for SMFError { fn from(err: MidiError) -> SMFError { SMFError::MidiError(err) } } impl From<MetaError> for SMFError { fn from(err: MetaError) -> SMFError
} impl From<FromUtf8Error> for SMFError { fn from(_: FromUtf8Error) -> SMFError { SMFError::InvalidSMFFile("Invalid UTF8 data in file") } } impl error::Error for SMFError { fn description(&self) -> &str { match *self { SMFError::InvalidSMFFile(_) => "The SMF file was invalid", SMFError::Error(ref e) => e.description(), SMFError::MidiError(ref m) => m.description(), SMFError::MetaError(ref m) => m.description(), } } fn cause(&self) -> Option<&error::Error> { match *self { SMFError::MidiError(ref m) => Some(m as &error::Error), SMFError::MetaError(ref m) => Some(m as &error::Error), SMFError::Error(ref err) => Some(err as &error::Error), _ => None, } } } impl fmt::Display for SMFError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SMFError::InvalidSMFFile(s) => write!(f,"SMF file is invalid: {}",s), SMFError::MidiError(ref err) => { write!(f,"{}",err) }, SMFError::MetaError(ref err) => { write!(f,"{}",err) }, SMFError::Error(ref err) => { write!(f,"{}",err) }, } } } /// A standard midi file #[derive(Debug, Clone)] pub struct SMF { /// The format of the SMF pub format: SMFFormat, /// Vector holding each track in this SMF pub tracks: Vec<Track>, /// The unit of time for delta timing. If the value is positive, /// then it represents the units per beat. For example, +96 would /// mean 96 ticks per beat. If the value is negative, delta times /// are in SMPTE compatible units. pub division: i16, } impl SMF { /// Read an SMF file at the given path pub fn from_file(path: &Path) -> Result<SMF,SMFError> { let mut file = try!(File::open(path)); SMFReader::read_smf(&mut file) } /// Read an SMF from the given reader pub fn from_reader(reader: &mut Read) -> Result<SMF,SMFError> { SMFReader::read_smf(reader) } /// Convert a type 0 (single track) to type 1 (multi track) SMF /// Does nothing if the SMF is already in type 1 /// Returns None if the SMF is in type 2 (multi song) pub fn to_multi_track(&self) -> Option<SMF> { match self.format { SMFFormat::MultiTrack => Some(self.clone()), SMFFormat::MultiSong => None, SMFFormat::Single => { let mut tracks = vec![Vec::<TrackEvent>::new(); 1 + 16]; // meta track and 16 for the 16 channels let mut time = 0; for event in &self.tracks[0].events { time += event.vtime; match event.event { Event::Midi(ref msg) if msg.channel().is_some() => { let events = &mut tracks[msg.channel().unwrap() as usize + 1]; events.push(TrackEvent {vtime: time, event: event.event.clone()}); } /*MidiEvent::Meta(ref msg) if [ MetaCommand::MIDIChannelPrefixAssignment, MetaCommand::MIDIPortPrefixAssignment, MetaCommand::SequenceOrTrackName, MetaCommand::InstrumentName, ].contains(&msg.command) => { println!("prefix: {:?}", event); }*/ _ => { tracks[0].push(TrackEvent {vtime: time, event: event.event.clone()}); } } } let mut out = SMF { format: SMFFormat::MultiTrack, tracks: vec![], division: self.division, }; for events in &mut tracks { if events.len() > 0 { let mut time = 0; for event in events.iter_mut() { let tmp = event.vtime; event.vtime -= time; time = tmp; } out.tracks.push(Track {events: events.clone(), copyright: None, name: None}); } } out.tracks[0].name = self.tracks[0].name.clone(); out.tracks[0].copyright = self.tracks[0].copyright.clone(); Some(out) } } } }
{ SMFError::MetaError(err) }
identifier_body
index.tsx
import * as React from 'react' // import * as css from './styles.scss' import styled from 'styled-components' export interface P { title?: string; bolded?: boolean; variant?: 'info' | 'normal' | 'primary' | 'success' | 'warning' | 'danger'; children?: JSX.Element[] | JSX.Element | string; className?: string; } // color: ${props => props.variant}; // border: 1px solid ${props => props.variant}; // background-color: ${props => props.variant}; // background-color: ${props => // (props.variant === 'primary' && '$primary') || // (props.variant === 'danger' && '$danger') // }; const StyledBadge = styled.div` padding: 3px; font-size: 1.3rem;
vertical-align: baseline; font-weight: ${(props: P) => (props.bolded ? '700' : '400')}; color: $c-primary-color; border: 1px solid $c-info-border; background-color: $c-info-background; ` export default class Badge extends React.PureComponent<P, {}> { static defaultProps = { title: '', variant: 'normal', className: '', } render () { const { title, className, children, ...rest } = this.props return ( <StyledBadge className={className} {...rest}> {title || children} </StyledBadge> ) } }
line-height: 1; border-radius: 2px; display: inline-block;
random_line_split
index.tsx
import * as React from 'react' // import * as css from './styles.scss' import styled from 'styled-components' export interface P { title?: string; bolded?: boolean; variant?: 'info' | 'normal' | 'primary' | 'success' | 'warning' | 'danger'; children?: JSX.Element[] | JSX.Element | string; className?: string; } // color: ${props => props.variant}; // border: 1px solid ${props => props.variant}; // background-color: ${props => props.variant}; // background-color: ${props => // (props.variant === 'primary' && '$primary') || // (props.variant === 'danger' && '$danger') // }; const StyledBadge = styled.div` padding: 3px; font-size: 1.3rem; line-height: 1; border-radius: 2px; display: inline-block; vertical-align: baseline; font-weight: ${(props: P) => (props.bolded ? '700' : '400')}; color: $c-primary-color; border: 1px solid $c-info-border; background-color: $c-info-background; ` export default class
extends React.PureComponent<P, {}> { static defaultProps = { title: '', variant: 'normal', className: '', } render () { const { title, className, children, ...rest } = this.props return ( <StyledBadge className={className} {...rest}> {title || children} </StyledBadge> ) } }
Badge
identifier_name
Gruntfile.js
"use strict"; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), interval: 200, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: false, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true, es5: true, strict: true, globalstrict: true }, files: { src: ['Gruntfile.js', 'package.json', 'lib/*.js', 'lib/controllers/**/*.js', 'lib/models/**/*.js', 'lib/utils/**/*.js', 'demo/*.js'] } }, watch: {
} }); // npm tasks grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); // Default task. grunt.registerTask('default', ['jshint']); };
files: ['<%= jshint.files.src %>'], tasks: ['default']
random_line_split
NavigationUI.ts
/// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as vd from "virtual-dom"; import {EdgeDirection} from "../Edge"; import {Node} from "../Graph"; import {Container, Navigator} from "../Viewer"; import {UIService, UI} from "../UI"; import {IVNodeHash} from "../Render"; export class NavigationUI extends UI { public static uiName: string = "navigation"; private _disposable: rx.IDisposable; private _dirNames: {[dir: number]: string}; constructor(name: string, container: Container, navigator: Navigator) { super(name, container, navigator); this._dirNames = {}; this._dirNames[EdgeDirection.STEP_FORWARD] = "Forward"; this._dirNames[EdgeDirection.STEP_BACKWARD] = "Backward"; this._dirNames[EdgeDirection.STEP_LEFT] = "Left"; this._dirNames[EdgeDirection.STEP_RIGHT] = "Right"; this._dirNames[EdgeDirection.TURN_LEFT] = "Turnleft"; this._dirNames[EdgeDirection.TURN_RIGHT] = "Turnright"; this._dirNames[EdgeDirection.TURN_U] = "Turnaround"; } protected _activate(): void { this._disposable = this._navigator.stateService.currentNode$.map((node: Node): IVNodeHash => { let btns: vd.VNode[] = []; for (let edge of node.edges) { let direction: EdgeDirection = edge.data.direction; let name: string = this._dirNames[direction]; if (name == null)
btns.push(this.createVNode(direction, name)); } return {name: this._name, vnode: vd.h(`div.NavigationUI`, btns)}; }).subscribe(this._container.domRenderer.render$); } protected _deactivate(): void { this._disposable.dispose(); } private createVNode(direction: EdgeDirection, name: string): vd.VNode { return vd.h(`span.btn.Direction.Direction${name}`, {onclick: (ev: Event): void => { this._navigator.moveDir(direction).first().subscribe(); }}, []); } } UIService.register(NavigationUI); export default NavigationUI;
{ continue; }
conditional_block
NavigationUI.ts
/// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as vd from "virtual-dom"; import {EdgeDirection} from "../Edge"; import {Node} from "../Graph"; import {Container, Navigator} from "../Viewer"; import {UIService, UI} from "../UI"; import {IVNodeHash} from "../Render"; export class NavigationUI extends UI { public static uiName: string = "navigation"; private _disposable: rx.IDisposable; private _dirNames: {[dir: number]: string}; constructor(name: string, container: Container, navigator: Navigator) { super(name, container, navigator); this._dirNames = {}; this._dirNames[EdgeDirection.STEP_FORWARD] = "Forward"; this._dirNames[EdgeDirection.STEP_BACKWARD] = "Backward"; this._dirNames[EdgeDirection.STEP_LEFT] = "Left"; this._dirNames[EdgeDirection.STEP_RIGHT] = "Right"; this._dirNames[EdgeDirection.TURN_LEFT] = "Turnleft"; this._dirNames[EdgeDirection.TURN_RIGHT] = "Turnright"; this._dirNames[EdgeDirection.TURN_U] = "Turnaround"; }
this._disposable = this._navigator.stateService.currentNode$.map((node: Node): IVNodeHash => { let btns: vd.VNode[] = []; for (let edge of node.edges) { let direction: EdgeDirection = edge.data.direction; let name: string = this._dirNames[direction]; if (name == null) { continue; } btns.push(this.createVNode(direction, name)); } return {name: this._name, vnode: vd.h(`div.NavigationUI`, btns)}; }).subscribe(this._container.domRenderer.render$); } protected _deactivate(): void { this._disposable.dispose(); } private createVNode(direction: EdgeDirection, name: string): vd.VNode { return vd.h(`span.btn.Direction.Direction${name}`, {onclick: (ev: Event): void => { this._navigator.moveDir(direction).first().subscribe(); }}, []); } } UIService.register(NavigationUI); export default NavigationUI;
protected _activate(): void {
random_line_split
NavigationUI.ts
/// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as vd from "virtual-dom"; import {EdgeDirection} from "../Edge"; import {Node} from "../Graph"; import {Container, Navigator} from "../Viewer"; import {UIService, UI} from "../UI"; import {IVNodeHash} from "../Render"; export class NavigationUI extends UI { public static uiName: string = "navigation"; private _disposable: rx.IDisposable; private _dirNames: {[dir: number]: string}; constructor(name: string, container: Container, navigator: Navigator) { super(name, container, navigator); this._dirNames = {}; this._dirNames[EdgeDirection.STEP_FORWARD] = "Forward"; this._dirNames[EdgeDirection.STEP_BACKWARD] = "Backward"; this._dirNames[EdgeDirection.STEP_LEFT] = "Left"; this._dirNames[EdgeDirection.STEP_RIGHT] = "Right"; this._dirNames[EdgeDirection.TURN_LEFT] = "Turnleft"; this._dirNames[EdgeDirection.TURN_RIGHT] = "Turnright"; this._dirNames[EdgeDirection.TURN_U] = "Turnaround"; } protected _activate(): void { this._disposable = this._navigator.stateService.currentNode$.map((node: Node): IVNodeHash => { let btns: vd.VNode[] = []; for (let edge of node.edges) { let direction: EdgeDirection = edge.data.direction; let name: string = this._dirNames[direction]; if (name == null) { continue; } btns.push(this.createVNode(direction, name)); } return {name: this._name, vnode: vd.h(`div.NavigationUI`, btns)}; }).subscribe(this._container.domRenderer.render$); } protected _deactivate(): void { this._disposable.dispose(); } private createVNode(direction: EdgeDirection, name: string): vd.VNode
} UIService.register(NavigationUI); export default NavigationUI;
{ return vd.h(`span.btn.Direction.Direction${name}`, {onclick: (ev: Event): void => { this._navigator.moveDir(direction).first().subscribe(); }}, []); }
identifier_body
NavigationUI.ts
/// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as vd from "virtual-dom"; import {EdgeDirection} from "../Edge"; import {Node} from "../Graph"; import {Container, Navigator} from "../Viewer"; import {UIService, UI} from "../UI"; import {IVNodeHash} from "../Render"; export class NavigationUI extends UI { public static uiName: string = "navigation"; private _disposable: rx.IDisposable; private _dirNames: {[dir: number]: string}; constructor(name: string, container: Container, navigator: Navigator) { super(name, container, navigator); this._dirNames = {}; this._dirNames[EdgeDirection.STEP_FORWARD] = "Forward"; this._dirNames[EdgeDirection.STEP_BACKWARD] = "Backward"; this._dirNames[EdgeDirection.STEP_LEFT] = "Left"; this._dirNames[EdgeDirection.STEP_RIGHT] = "Right"; this._dirNames[EdgeDirection.TURN_LEFT] = "Turnleft"; this._dirNames[EdgeDirection.TURN_RIGHT] = "Turnright"; this._dirNames[EdgeDirection.TURN_U] = "Turnaround"; } protected _activate(): void { this._disposable = this._navigator.stateService.currentNode$.map((node: Node): IVNodeHash => { let btns: vd.VNode[] = []; for (let edge of node.edges) { let direction: EdgeDirection = edge.data.direction; let name: string = this._dirNames[direction]; if (name == null) { continue; } btns.push(this.createVNode(direction, name)); } return {name: this._name, vnode: vd.h(`div.NavigationUI`, btns)}; }).subscribe(this._container.domRenderer.render$); } protected _deactivate(): void { this._disposable.dispose(); } private
(direction: EdgeDirection, name: string): vd.VNode { return vd.h(`span.btn.Direction.Direction${name}`, {onclick: (ev: Event): void => { this._navigator.moveDir(direction).first().subscribe(); }}, []); } } UIService.register(NavigationUI); export default NavigationUI;
createVNode
identifier_name
dynamicBindings.js
function testEval(x, y) { x = 5; eval("arguments[0] += 10"); assertEq(x, 15); } for (var i = 0; i < 5; i++) testEval(3);
eval("arguments[0] += 10"); assertEq(arguments[y], 13); } for (var i = 0; i < 5; i++) testEvalWithArguments(3, 0); function testNestedEval(x, y) { x = 5; eval("eval('arguments[0] += 10')"); assertEq(x, 15); } for (var i = 0; i < 5; i++) testNestedEval(3); function testWith(x, y) { with ({}) { arguments[0] += 10; assertEq(x, 13); } } for (var i = 0; i < 5; i++) testWith(3);
function testEvalWithArguments(x, y) {
random_line_split
dynamicBindings.js
function testEval(x, y)
for (var i = 0; i < 5; i++) testEval(3); function testEvalWithArguments(x, y) { eval("arguments[0] += 10"); assertEq(arguments[y], 13); } for (var i = 0; i < 5; i++) testEvalWithArguments(3, 0); function testNestedEval(x, y) { x = 5; eval("eval('arguments[0] += 10')"); assertEq(x, 15); } for (var i = 0; i < 5; i++) testNestedEval(3); function testWith(x, y) { with ({}) { arguments[0] += 10; assertEq(x, 13); } } for (var i = 0; i < 5; i++) testWith(3);
{ x = 5; eval("arguments[0] += 10"); assertEq(x, 15); }
identifier_body
dynamicBindings.js
function testEval(x, y) { x = 5; eval("arguments[0] += 10"); assertEq(x, 15); } for (var i = 0; i < 5; i++) testEval(3); function testEvalWithArguments(x, y) { eval("arguments[0] += 10"); assertEq(arguments[y], 13); } for (var i = 0; i < 5; i++) testEvalWithArguments(3, 0); function
(x, y) { x = 5; eval("eval('arguments[0] += 10')"); assertEq(x, 15); } for (var i = 0; i < 5; i++) testNestedEval(3); function testWith(x, y) { with ({}) { arguments[0] += 10; assertEq(x, 13); } } for (var i = 0; i < 5; i++) testWith(3);
testNestedEval
identifier_name
configuration.rs
//! Konfiguration Datei Managment //! use errors::*; use std::fs::File; use std::path::Path; use std::io::Read; pub struct Configuration; impl Configuration { /// Liest die Konfiguration /// /// # Return values /// /// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als String, oder ein Error, /// wenn die Konfiguration nicht ausgelesen werden konnte. /// /// # Parameters /// /// # Examples /// /// ```rust /// assert!(true); /// ``` pub fn g
) -> Result<String> { // TODO: In production nur Konfig von `/boot` verwenden! let possible_paths = vec![ Path::new("/boot/xMZ-Mod-Touch.json"), Path::new("/usr/share/xmz-mod-touch-server/xMZ-Mod-Touch.json.production"), Path::new("xMZ-Mod-Touch.json"), ]; let mut ret = String::new(); for p in possible_paths { if Path::new(p).exists() { match File::open(&p) { Ok(mut file) => { println!("Verwende Konfigurationsdatei: {}", p.display()); file.read_to_string(&mut ret)?; } Err(_) => panic!("Could not open file: {}", p.display()), }; break; } } Ok(ret) } }
et_config(
identifier_name
configuration.rs
//! Konfiguration Datei Managment //! use errors::*; use std::fs::File; use std::path::Path; use std::io::Read; pub struct Configuration; impl Configuration { /// Liest die Konfiguration /// /// # Return values /// /// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als String, oder ein Error, /// wenn die Konfiguration nicht ausgelesen werden konnte. /// /// # Parameters /// /// # Examples /// /// ```rust /// assert!(true); /// ``` pub fn get_config() -> Result<String> { // TODO: In production nur Konfig von `/boot` verwenden! let possible_paths = vec![ Path::new("/boot/xMZ-Mod-Touch.json"), Path::new("/usr/share/xmz-mod-touch-server/xMZ-Mod-Touch.json.production"), Path::new("xMZ-Mod-Touch.json"), ]; let mut ret = String::new(); for p in possible_paths { if Path::new(p).exists() {
} Ok(ret) } }
match File::open(&p) { Ok(mut file) => { println!("Verwende Konfigurationsdatei: {}", p.display()); file.read_to_string(&mut ret)?; } Err(_) => panic!("Could not open file: {}", p.display()), }; break; }
conditional_block
configuration.rs
//! Konfiguration Datei Managment //! use errors::*; use std::fs::File; use std::path::Path; use std::io::Read; pub struct Configuration; impl Configuration { /// Liest die Konfiguration /// /// # Return values /// /// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als String, oder ein Error, /// wenn die Konfiguration nicht ausgelesen werden konnte. /// /// # Parameters /// /// # Examples /// /// ```rust /// assert!(true); /// ``` pub fn get_config() -> Result<String> { // TODO: In production nur Konfig von `/boot` verwenden! let possible_paths = vec![ Path::new("/boot/xMZ-Mod-Touch.json"), Path::new("/usr/share/xmz-mod-touch-server/xMZ-Mod-Touch.json.production"), Path::new("xMZ-Mod-Touch.json"), ]; let mut ret = String::new(); for p in possible_paths { if Path::new(p).exists() { match File::open(&p) { Ok(mut file) => { println!("Verwende Konfigurationsdatei: {}", p.display()); file.read_to_string(&mut ret)?; } Err(_) => panic!("Could not open file: {}", p.display()), }; break; } } Ok(ret)
} }
random_line_split
baseRequiredField.validator.ts
import { get, has, upperFirst } from 'lodash'; import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain'; import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator'; export interface IRequiredField { fieldName: string; fieldLabel?: string; } export interface IBaseRequiredFieldValidationConfig extends IValidatorConfig { message?: string; } export abstract class BaseRequiredFieldValidator implements IStageOrTriggerValidator { public validate( pipeline: IPipeline, stage: IStage | ITrigger, validationConfig: IBaseRequiredFieldValidationConfig,
config: IStageOrTriggerTypeConfig, ): string { if (!this.passesValidation(pipeline, stage, validationConfig)) { return this.validationMessage(validationConfig, config); } return null; } protected abstract passesValidation( pipeline: IPipeline, stage: IStage | ITrigger, validationConfig: IBaseRequiredFieldValidationConfig, ): boolean; protected abstract validationMessage( validationConfig: IBaseRequiredFieldValidationConfig, config: IStageOrTriggerTypeConfig, ): string; protected printableFieldLabel(field: IRequiredField): string { const fieldLabel: string = field.fieldLabel || field.fieldName; return upperFirst(fieldLabel); } protected fieldIsValid(pipeline: IPipeline, stage: IStage | ITrigger, fieldName: string): boolean { if (pipeline.strategy === true && ['cluster', 'regions', 'zones', 'credentials'].includes(fieldName)) { return true; } const fieldExists = has(stage, fieldName); const field: any = get(stage, fieldName); return fieldExists && (field || field === 0) && !(Array.isArray(field) && field.length === 0); } }
random_line_split
baseRequiredField.validator.ts
import { get, has, upperFirst } from 'lodash'; import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain'; import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator'; export interface IRequiredField { fieldName: string; fieldLabel?: string; } export interface IBaseRequiredFieldValidationConfig extends IValidatorConfig { message?: string; } export abstract class BaseRequiredFieldValidator implements IStageOrTriggerValidator { public validate( pipeline: IPipeline, stage: IStage | ITrigger, validationConfig: IBaseRequiredFieldValidationConfig, config: IStageOrTriggerTypeConfig, ): string { if (!this.passesValidation(pipeline, stage, validationConfig))
return null; } protected abstract passesValidation( pipeline: IPipeline, stage: IStage | ITrigger, validationConfig: IBaseRequiredFieldValidationConfig, ): boolean; protected abstract validationMessage( validationConfig: IBaseRequiredFieldValidationConfig, config: IStageOrTriggerTypeConfig, ): string; protected printableFieldLabel(field: IRequiredField): string { const fieldLabel: string = field.fieldLabel || field.fieldName; return upperFirst(fieldLabel); } protected fieldIsValid(pipeline: IPipeline, stage: IStage | ITrigger, fieldName: string): boolean { if (pipeline.strategy === true && ['cluster', 'regions', 'zones', 'credentials'].includes(fieldName)) { return true; } const fieldExists = has(stage, fieldName); const field: any = get(stage, fieldName); return fieldExists && (field || field === 0) && !(Array.isArray(field) && field.length === 0); } }
{ return this.validationMessage(validationConfig, config); }
conditional_block
baseRequiredField.validator.ts
import { get, has, upperFirst } from 'lodash'; import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain'; import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator'; export interface IRequiredField { fieldName: string; fieldLabel?: string; } export interface IBaseRequiredFieldValidationConfig extends IValidatorConfig { message?: string; } export abstract class BaseRequiredFieldValidator implements IStageOrTriggerValidator { public validate( pipeline: IPipeline, stage: IStage | ITrigger, validationConfig: IBaseRequiredFieldValidationConfig, config: IStageOrTriggerTypeConfig, ): string { if (!this.passesValidation(pipeline, stage, validationConfig)) { return this.validationMessage(validationConfig, config); } return null; } protected abstract passesValidation( pipeline: IPipeline, stage: IStage | ITrigger, validationConfig: IBaseRequiredFieldValidationConfig, ): boolean; protected abstract validationMessage( validationConfig: IBaseRequiredFieldValidationConfig, config: IStageOrTriggerTypeConfig, ): string; protected printableFieldLabel(field: IRequiredField): string
protected fieldIsValid(pipeline: IPipeline, stage: IStage | ITrigger, fieldName: string): boolean { if (pipeline.strategy === true && ['cluster', 'regions', 'zones', 'credentials'].includes(fieldName)) { return true; } const fieldExists = has(stage, fieldName); const field: any = get(stage, fieldName); return fieldExists && (field || field === 0) && !(Array.isArray(field) && field.length === 0); } }
{ const fieldLabel: string = field.fieldLabel || field.fieldName; return upperFirst(fieldLabel); }
identifier_body
baseRequiredField.validator.ts
import { get, has, upperFirst } from 'lodash'; import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain'; import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator'; export interface IRequiredField { fieldName: string; fieldLabel?: string; } export interface IBaseRequiredFieldValidationConfig extends IValidatorConfig { message?: string; } export abstract class BaseRequiredFieldValidator implements IStageOrTriggerValidator { public validate( pipeline: IPipeline, stage: IStage | ITrigger, validationConfig: IBaseRequiredFieldValidationConfig, config: IStageOrTriggerTypeConfig, ): string { if (!this.passesValidation(pipeline, stage, validationConfig)) { return this.validationMessage(validationConfig, config); } return null; } protected abstract passesValidation( pipeline: IPipeline, stage: IStage | ITrigger, validationConfig: IBaseRequiredFieldValidationConfig, ): boolean; protected abstract validationMessage( validationConfig: IBaseRequiredFieldValidationConfig, config: IStageOrTriggerTypeConfig, ): string; protected
(field: IRequiredField): string { const fieldLabel: string = field.fieldLabel || field.fieldName; return upperFirst(fieldLabel); } protected fieldIsValid(pipeline: IPipeline, stage: IStage | ITrigger, fieldName: string): boolean { if (pipeline.strategy === true && ['cluster', 'regions', 'zones', 'credentials'].includes(fieldName)) { return true; } const fieldExists = has(stage, fieldName); const field: any = get(stage, fieldName); return fieldExists && (field || field === 0) && !(Array.isArray(field) && field.length === 0); } }
printableFieldLabel
identifier_name
end.js
const EventEmitter = require('events'); /** * Ends the session. Uses session protocol command. * * @example * this.demoTest = function (browser) { * browser.end(); * }; * * @method end * @syntax .end([callback]) * @param {function} [callback] Optional callback function to be called when the command finishes. * @see session * @api protocol.sessions */ class End extends EventEmitter { command(callback) { const client = this.client; if (this.api.sessionId) { this.api.session('delete', result => { client.session.clearSession(); client.setApiProperty('sessionId', null); this.complete(callback, result); }); } else { setImmediate(() => { this.complete(callback, null); }); } return this.client.api; } complete(callback, result) { if (typeof callback === 'function') { callback.call(this.api, result);
} this.emit('complete'); } } module.exports = End;
random_line_split
end.js
const EventEmitter = require('events'); /** * Ends the session. Uses session protocol command. * * @example * this.demoTest = function (browser) { * browser.end(); * }; * * @method end * @syntax .end([callback]) * @param {function} [callback] Optional callback function to be called when the command finishes. * @see session * @api protocol.sessions */ class End extends EventEmitter {
(callback) { const client = this.client; if (this.api.sessionId) { this.api.session('delete', result => { client.session.clearSession(); client.setApiProperty('sessionId', null); this.complete(callback, result); }); } else { setImmediate(() => { this.complete(callback, null); }); } return this.client.api; } complete(callback, result) { if (typeof callback === 'function') { callback.call(this.api, result); } this.emit('complete'); } } module.exports = End;
command
identifier_name
end.js
const EventEmitter = require('events'); /** * Ends the session. Uses session protocol command. * * @example * this.demoTest = function (browser) { * browser.end(); * }; * * @method end * @syntax .end([callback]) * @param {function} [callback] Optional callback function to be called when the command finishes. * @see session * @api protocol.sessions */ class End extends EventEmitter { command(callback) { const client = this.client; if (this.api.sessionId) { this.api.session('delete', result => { client.session.clearSession(); client.setApiProperty('sessionId', null); this.complete(callback, result); }); } else
return this.client.api; } complete(callback, result) { if (typeof callback === 'function') { callback.call(this.api, result); } this.emit('complete'); } } module.exports = End;
{ setImmediate(() => { this.complete(callback, null); }); }
conditional_block
end.js
const EventEmitter = require('events'); /** * Ends the session. Uses session protocol command. * * @example * this.demoTest = function (browser) { * browser.end(); * }; * * @method end * @syntax .end([callback]) * @param {function} [callback] Optional callback function to be called when the command finishes. * @see session * @api protocol.sessions */ class End extends EventEmitter { command(callback)
complete(callback, result) { if (typeof callback === 'function') { callback.call(this.api, result); } this.emit('complete'); } } module.exports = End;
{ const client = this.client; if (this.api.sessionId) { this.api.session('delete', result => { client.session.clearSession(); client.setApiProperty('sessionId', null); this.complete(callback, result); }); } else { setImmediate(() => { this.complete(callback, null); }); } return this.client.api; }
identifier_body
blob_samples_authentication_async.py
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ FILE: blob_samples_authentication_async.py DESCRIPTION: These samples demonstrate authenticating a client via a connection string, shared access key, or by generating a sas token with which the returned signature can be used with the credential parameter of any BlobServiceClient, ContainerClient, BlobClient. USAGE: python blob_samples_authentication_async.py Set the environment variables with your own values before running the sample: 1) AZURE_STORAGE_CONNECTION_STRING - the connection string to your storage account 2) OAUTH_STORAGE_ACCOUNT_NAME - the oath storage account name 3) AZURE_STORAGE_ACCOUNT_NAME - the name of the storage account 4) AZURE_STORAGE_ACCESS_KEY - the storage account access key 5) ACTIVE_DIRECTORY_APPLICATION_ID - Azure Active Directory application ID 6) ACTIVE_DIRECTORY_APPLICATION_SECRET - Azure Active Directory application secret 7) ACTIVE_DIRECTORY_TENANT_ID - Azure Active Directory tenant ID """ import os import asyncio class AuthSamplesAsync(object): url = "https://{}.blob.core.windows.net".format( os.getenv("AZURE_STORAGE_ACCOUNT_NAME") ) oauth_url = "https://{}.blob.core.windows.net".format( os.getenv("OAUTH_STORAGE_ACCOUNT_NAME") ) connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING") shared_access_key = os.getenv("AZURE_STORAGE_ACCESS_KEY") active_directory_application_id = os.getenv("ACTIVE_DIRECTORY_APPLICATION_ID") active_directory_application_secret = os.getenv("ACTIVE_DIRECTORY_APPLICATION_SECRET") active_directory_tenant_id = os.getenv("ACTIVE_DIRECTORY_TENANT_ID") async def
(self): # [START auth_from_connection_string] from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(self.connection_string) # [END auth_from_connection_string] # [START auth_from_connection_string_container] from azure.storage.blob.aio import ContainerClient container_client = ContainerClient.from_connection_string( self.connection_string, container_name="mycontainer") # [END auth_from_connection_string_container] # [START auth_from_connection_string_blob] from azure.storage.blob.aio import BlobClient blob_client = BlobClient.from_connection_string( self.connection_string, container_name="mycontainer", blob_name="blobname.txt") # [END auth_from_connection_string_blob] async def auth_shared_key_async(self): # [START create_blob_service_client] from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient(account_url=self.url, credential=self.shared_access_key) # [END create_blob_service_client] async def auth_blob_url_async(self): # [START create_blob_client] from azure.storage.blob.aio import BlobClient blob_client = BlobClient.from_blob_url(blob_url="https://account.blob.core.windows.net/container/blob-name") # [END create_blob_client] # [START create_blob_client_sas_url] from azure.storage.blob.aio import BlobClient sas_url = "https://account.blob.core.windows.net/container/blob-name?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D" blob_client = BlobClient.from_blob_url(sas_url) # [END create_blob_client_sas_url] async def auth_active_directory_async(self): # [START create_blob_service_client_oauth] # Get a token credential for authentication from azure.identity.aio import ClientSecretCredential token_credential = ClientSecretCredential(self.active_directory_tenant_id, self.active_directory_application_id, self.active_directory_application_secret) # Instantiate a BlobServiceClient using a token credential from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient(account_url=self.oauth_url, credential=token_credential) # [END create_blob_service_client_oauth] async def auth_shared_access_signature_async(self): # Instantiate a BlobServiceClient using a connection string from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(self.connection_string) # [START create_sas_token] # Create a SAS token to use to authenticate a new client from datetime import datetime, timedelta from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas sas_token = generate_account_sas( blob_service_client.account_name, account_key=blob_service_client.credential.account_key, resource_types=ResourceTypes(object=True), permission=AccountSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1) ) # [END create_sas_token] async def main(): sample = AuthSamplesAsync() # Uncomment the methods you want to execute. await sample.auth_connection_string_async() # await sample.auth_active_directory() await sample.auth_shared_access_signature_async() await sample.auth_blob_url_async() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main())
auth_connection_string_async
identifier_name
blob_samples_authentication_async.py
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ FILE: blob_samples_authentication_async.py DESCRIPTION: These samples demonstrate authenticating a client via a connection string, shared access key, or by generating a sas token with which the returned signature can be used with the credential parameter of any BlobServiceClient, ContainerClient, BlobClient. USAGE: python blob_samples_authentication_async.py Set the environment variables with your own values before running the sample: 1) AZURE_STORAGE_CONNECTION_STRING - the connection string to your storage account 2) OAUTH_STORAGE_ACCOUNT_NAME - the oath storage account name 3) AZURE_STORAGE_ACCOUNT_NAME - the name of the storage account 4) AZURE_STORAGE_ACCESS_KEY - the storage account access key 5) ACTIVE_DIRECTORY_APPLICATION_ID - Azure Active Directory application ID 6) ACTIVE_DIRECTORY_APPLICATION_SECRET - Azure Active Directory application secret 7) ACTIVE_DIRECTORY_TENANT_ID - Azure Active Directory tenant ID """ import os import asyncio class AuthSamplesAsync(object): url = "https://{}.blob.core.windows.net".format( os.getenv("AZURE_STORAGE_ACCOUNT_NAME") ) oauth_url = "https://{}.blob.core.windows.net".format( os.getenv("OAUTH_STORAGE_ACCOUNT_NAME") ) connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING") shared_access_key = os.getenv("AZURE_STORAGE_ACCESS_KEY") active_directory_application_id = os.getenv("ACTIVE_DIRECTORY_APPLICATION_ID") active_directory_application_secret = os.getenv("ACTIVE_DIRECTORY_APPLICATION_SECRET") active_directory_tenant_id = os.getenv("ACTIVE_DIRECTORY_TENANT_ID") async def auth_connection_string_async(self): # [START auth_from_connection_string] from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(self.connection_string) # [END auth_from_connection_string] # [START auth_from_connection_string_container] from azure.storage.blob.aio import ContainerClient container_client = ContainerClient.from_connection_string( self.connection_string, container_name="mycontainer") # [END auth_from_connection_string_container] # [START auth_from_connection_string_blob] from azure.storage.blob.aio import BlobClient blob_client = BlobClient.from_connection_string( self.connection_string, container_name="mycontainer", blob_name="blobname.txt") # [END auth_from_connection_string_blob] async def auth_shared_key_async(self): # [START create_blob_service_client] from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient(account_url=self.url, credential=self.shared_access_key) # [END create_blob_service_client] async def auth_blob_url_async(self): # [START create_blob_client] from azure.storage.blob.aio import BlobClient blob_client = BlobClient.from_blob_url(blob_url="https://account.blob.core.windows.net/container/blob-name") # [END create_blob_client] # [START create_blob_client_sas_url] from azure.storage.blob.aio import BlobClient sas_url = "https://account.blob.core.windows.net/container/blob-name?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D" blob_client = BlobClient.from_blob_url(sas_url) # [END create_blob_client_sas_url] async def auth_active_directory_async(self): # [START create_blob_service_client_oauth] # Get a token credential for authentication from azure.identity.aio import ClientSecretCredential token_credential = ClientSecretCredential(self.active_directory_tenant_id, self.active_directory_application_id, self.active_directory_application_secret) # Instantiate a BlobServiceClient using a token credential from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient(account_url=self.oauth_url, credential=token_credential) # [END create_blob_service_client_oauth] async def auth_shared_access_signature_async(self): # Instantiate a BlobServiceClient using a connection string from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(self.connection_string) # [START create_sas_token] # Create a SAS token to use to authenticate a new client from datetime import datetime, timedelta from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas sas_token = generate_account_sas( blob_service_client.account_name, account_key=blob_service_client.credential.account_key, resource_types=ResourceTypes(object=True), permission=AccountSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1) ) # [END create_sas_token] async def main():
# await sample.auth_active_directory() await sample.auth_shared_access_signature_async() await sample.auth_blob_url_async() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main())
sample = AuthSamplesAsync() # Uncomment the methods you want to execute. await sample.auth_connection_string_async()
random_line_split
blob_samples_authentication_async.py
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ FILE: blob_samples_authentication_async.py DESCRIPTION: These samples demonstrate authenticating a client via a connection string, shared access key, or by generating a sas token with which the returned signature can be used with the credential parameter of any BlobServiceClient, ContainerClient, BlobClient. USAGE: python blob_samples_authentication_async.py Set the environment variables with your own values before running the sample: 1) AZURE_STORAGE_CONNECTION_STRING - the connection string to your storage account 2) OAUTH_STORAGE_ACCOUNT_NAME - the oath storage account name 3) AZURE_STORAGE_ACCOUNT_NAME - the name of the storage account 4) AZURE_STORAGE_ACCESS_KEY - the storage account access key 5) ACTIVE_DIRECTORY_APPLICATION_ID - Azure Active Directory application ID 6) ACTIVE_DIRECTORY_APPLICATION_SECRET - Azure Active Directory application secret 7) ACTIVE_DIRECTORY_TENANT_ID - Azure Active Directory tenant ID """ import os import asyncio class AuthSamplesAsync(object): url = "https://{}.blob.core.windows.net".format( os.getenv("AZURE_STORAGE_ACCOUNT_NAME") ) oauth_url = "https://{}.blob.core.windows.net".format( os.getenv("OAUTH_STORAGE_ACCOUNT_NAME") ) connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING") shared_access_key = os.getenv("AZURE_STORAGE_ACCESS_KEY") active_directory_application_id = os.getenv("ACTIVE_DIRECTORY_APPLICATION_ID") active_directory_application_secret = os.getenv("ACTIVE_DIRECTORY_APPLICATION_SECRET") active_directory_tenant_id = os.getenv("ACTIVE_DIRECTORY_TENANT_ID") async def auth_connection_string_async(self): # [START auth_from_connection_string] from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(self.connection_string) # [END auth_from_connection_string] # [START auth_from_connection_string_container] from azure.storage.blob.aio import ContainerClient container_client = ContainerClient.from_connection_string( self.connection_string, container_name="mycontainer") # [END auth_from_connection_string_container] # [START auth_from_connection_string_blob] from azure.storage.blob.aio import BlobClient blob_client = BlobClient.from_connection_string( self.connection_string, container_name="mycontainer", blob_name="blobname.txt") # [END auth_from_connection_string_blob] async def auth_shared_key_async(self): # [START create_blob_service_client] from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient(account_url=self.url, credential=self.shared_access_key) # [END create_blob_service_client] async def auth_blob_url_async(self): # [START create_blob_client] from azure.storage.blob.aio import BlobClient blob_client = BlobClient.from_blob_url(blob_url="https://account.blob.core.windows.net/container/blob-name") # [END create_blob_client] # [START create_blob_client_sas_url] from azure.storage.blob.aio import BlobClient sas_url = "https://account.blob.core.windows.net/container/blob-name?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D" blob_client = BlobClient.from_blob_url(sas_url) # [END create_blob_client_sas_url] async def auth_active_directory_async(self): # [START create_blob_service_client_oauth] # Get a token credential for authentication from azure.identity.aio import ClientSecretCredential token_credential = ClientSecretCredential(self.active_directory_tenant_id, self.active_directory_application_id, self.active_directory_application_secret) # Instantiate a BlobServiceClient using a token credential from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient(account_url=self.oauth_url, credential=token_credential) # [END create_blob_service_client_oauth] async def auth_shared_access_signature_async(self): # Instantiate a BlobServiceClient using a connection string from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(self.connection_string) # [START create_sas_token] # Create a SAS token to use to authenticate a new client from datetime import datetime, timedelta from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas sas_token = generate_account_sas( blob_service_client.account_name, account_key=blob_service_client.credential.account_key, resource_types=ResourceTypes(object=True), permission=AccountSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1) ) # [END create_sas_token] async def main():
if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main())
sample = AuthSamplesAsync() # Uncomment the methods you want to execute. await sample.auth_connection_string_async() # await sample.auth_active_directory() await sample.auth_shared_access_signature_async() await sample.auth_blob_url_async()
identifier_body
blob_samples_authentication_async.py
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ FILE: blob_samples_authentication_async.py DESCRIPTION: These samples demonstrate authenticating a client via a connection string, shared access key, or by generating a sas token with which the returned signature can be used with the credential parameter of any BlobServiceClient, ContainerClient, BlobClient. USAGE: python blob_samples_authentication_async.py Set the environment variables with your own values before running the sample: 1) AZURE_STORAGE_CONNECTION_STRING - the connection string to your storage account 2) OAUTH_STORAGE_ACCOUNT_NAME - the oath storage account name 3) AZURE_STORAGE_ACCOUNT_NAME - the name of the storage account 4) AZURE_STORAGE_ACCESS_KEY - the storage account access key 5) ACTIVE_DIRECTORY_APPLICATION_ID - Azure Active Directory application ID 6) ACTIVE_DIRECTORY_APPLICATION_SECRET - Azure Active Directory application secret 7) ACTIVE_DIRECTORY_TENANT_ID - Azure Active Directory tenant ID """ import os import asyncio class AuthSamplesAsync(object): url = "https://{}.blob.core.windows.net".format( os.getenv("AZURE_STORAGE_ACCOUNT_NAME") ) oauth_url = "https://{}.blob.core.windows.net".format( os.getenv("OAUTH_STORAGE_ACCOUNT_NAME") ) connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING") shared_access_key = os.getenv("AZURE_STORAGE_ACCESS_KEY") active_directory_application_id = os.getenv("ACTIVE_DIRECTORY_APPLICATION_ID") active_directory_application_secret = os.getenv("ACTIVE_DIRECTORY_APPLICATION_SECRET") active_directory_tenant_id = os.getenv("ACTIVE_DIRECTORY_TENANT_ID") async def auth_connection_string_async(self): # [START auth_from_connection_string] from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(self.connection_string) # [END auth_from_connection_string] # [START auth_from_connection_string_container] from azure.storage.blob.aio import ContainerClient container_client = ContainerClient.from_connection_string( self.connection_string, container_name="mycontainer") # [END auth_from_connection_string_container] # [START auth_from_connection_string_blob] from azure.storage.blob.aio import BlobClient blob_client = BlobClient.from_connection_string( self.connection_string, container_name="mycontainer", blob_name="blobname.txt") # [END auth_from_connection_string_blob] async def auth_shared_key_async(self): # [START create_blob_service_client] from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient(account_url=self.url, credential=self.shared_access_key) # [END create_blob_service_client] async def auth_blob_url_async(self): # [START create_blob_client] from azure.storage.blob.aio import BlobClient blob_client = BlobClient.from_blob_url(blob_url="https://account.blob.core.windows.net/container/blob-name") # [END create_blob_client] # [START create_blob_client_sas_url] from azure.storage.blob.aio import BlobClient sas_url = "https://account.blob.core.windows.net/container/blob-name?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D" blob_client = BlobClient.from_blob_url(sas_url) # [END create_blob_client_sas_url] async def auth_active_directory_async(self): # [START create_blob_service_client_oauth] # Get a token credential for authentication from azure.identity.aio import ClientSecretCredential token_credential = ClientSecretCredential(self.active_directory_tenant_id, self.active_directory_application_id, self.active_directory_application_secret) # Instantiate a BlobServiceClient using a token credential from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient(account_url=self.oauth_url, credential=token_credential) # [END create_blob_service_client_oauth] async def auth_shared_access_signature_async(self): # Instantiate a BlobServiceClient using a connection string from azure.storage.blob.aio import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(self.connection_string) # [START create_sas_token] # Create a SAS token to use to authenticate a new client from datetime import datetime, timedelta from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas sas_token = generate_account_sas( blob_service_client.account_name, account_key=blob_service_client.credential.account_key, resource_types=ResourceTypes(object=True), permission=AccountSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1) ) # [END create_sas_token] async def main(): sample = AuthSamplesAsync() # Uncomment the methods you want to execute. await sample.auth_connection_string_async() # await sample.auth_active_directory() await sample.auth_shared_access_signature_async() await sample.auth_blob_url_async() if __name__ == '__main__':
loop = asyncio.get_event_loop() loop.run_until_complete(main())
conditional_block
win_tool.py
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for Windows builds. These functions are executed via gyp-win-tool when using the ninja generator. """ from ctypes import windll, wintypes import os import shutil import subprocess import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def main(args): executor = WinTool() exit_code = executor.Dispatch(args) if exit_code is not None: sys.exit(exit_code) class LinkLock(object): """A flock-style lock to limit the number of concurrent links to one. Uses a session-local mutex based on the file's directory. """ def __enter__(self): name = 'Local\\%s' % BASE_DIR.replace('\\', '_').replace(':', '_') self.mutex = windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(0), wintypes.create_unicode_buffer(name)) assert self.mutex result = windll.kernel32.WaitForSingleObject( self.mutex, wintypes.c_int(0xFFFFFFFF)) # 0x80 means another process was killed without releasing the mutex, but # that this process has been given ownership. This is fine for our # purposes. assert result in (0, 0x80), ( "%s, %s" % (result, windll.kernel32.GetLastError())) def __exit__(self, type, value, traceback): windll.kernel32.ReleaseMutex(self.mutex) windll.kernel32.CloseHandle(self.mutex) class WinTool(object): """This class performs all the Windows tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like recursive-mirror to RecursiveMirror.""" return name_string.title().replace('-', '') def _GetEnv(self, arch): """Gets the saved environment from a file for a given architecture.""" # The environment is saved as an "environment block" (see CreateProcess # and msvs_emulation for details). We convert to a dict here. # Drop last 2 NULs, one for list terminator, one for trailing vs. separator. pairs = open(arch).read()[:-2].split('\0') kvs = [item.split('=', 1) for item in pairs] return dict(kvs) def
(self, path): """Simple stamp command.""" open(path, 'w').close() def ExecRecursiveMirror(self, source, dest): """Emulation of rm -rf out && cp -af in out.""" if os.path.exists(dest): if os.path.isdir(dest): shutil.rmtree(dest) else: os.unlink(dest) if os.path.isdir(source): shutil.copytree(source, dest) else: shutil.copy2(source, dest) def ExecLinkWrapper(self, arch, *args): """Filter diagnostic output from link that looks like: ' Creating library ui.dll.lib and object ui.dll.exp' This happens when there are exports from the dll or exe. """ with LinkLock(): env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if not line.startswith(' Creating library '): print line return popen.returncode def ExecManifestWrapper(self, arch, *args): """Run manifest tool with environment set. Strip out undesirable warning (some XML blocks are recognized by the OS loader, but not the manifest tool).""" env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if line and 'manifest authoring warning 81010002' not in line: print line return popen.returncode def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags): """Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags. """ args = ['midl', '/nologo'] + list(flags) + [ '/out', outdir, '/tlb', tlb, '/h', h, '/dlldata', dlldata, '/iid', iid, '/proxy', proxy, idl] env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() # Filter junk out of stdout, and write filtered versions. Output we want # to filter is pairs of lines that look like this: # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl # objidl.idl lines = out.splitlines() prefix = 'Processing ' processing = set(os.path.basename(x) for x in lines if x.startswith(prefix)) for line in lines: if not line.startswith(prefix) and line not in processing: print line return popen.returncode def ExecAsmWrapper(self, arch, *args): """Filter logo banner from invocations of asm.exe.""" env = self._GetEnv(arch) # MSVS doesn't assemble x64 asm files. if arch == 'environment.x64': return 0 popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if (not line.startswith('Copyright (C) Microsoft Corporation') and not line.startswith('Microsoft (R) Macro Assembler') and not line.startswith(' Assembling: ') and line): print line return popen.returncode def ExecRcWrapper(self, arch, *args): """Filter logo banner from invocations of rc.exe. Older versions of RC don't support the /nologo flag.""" env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and not line.startswith('Copyright (C) Microsoft Corporation') and line): print line return popen.returncode def ExecActionWrapper(self, arch, rspfile, *dir): """Runs an action command line from a response file using the environment for |arch|. If |dir| is supplied, use that as the working directory.""" env = self._GetEnv(arch) args = open(rspfile).read() dir = dir[0] if dir else None popen = subprocess.Popen(args, shell=True, env=env, cwd=dir) popen.wait() return popen.returncode if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
ExecStamp
identifier_name
win_tool.py
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for Windows builds. These functions are executed via gyp-win-tool when using the ninja generator. """ from ctypes import windll, wintypes import os import shutil import subprocess import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def main(args): executor = WinTool() exit_code = executor.Dispatch(args) if exit_code is not None: sys.exit(exit_code) class LinkLock(object): """A flock-style lock to limit the number of concurrent links to one. Uses a session-local mutex based on the file's directory. """ def __enter__(self): name = 'Local\\%s' % BASE_DIR.replace('\\', '_').replace(':', '_') self.mutex = windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(0), wintypes.create_unicode_buffer(name)) assert self.mutex result = windll.kernel32.WaitForSingleObject( self.mutex, wintypes.c_int(0xFFFFFFFF)) # 0x80 means another process was killed without releasing the mutex, but # that this process has been given ownership. This is fine for our # purposes. assert result in (0, 0x80), ( "%s, %s" % (result, windll.kernel32.GetLastError())) def __exit__(self, type, value, traceback): windll.kernel32.ReleaseMutex(self.mutex) windll.kernel32.CloseHandle(self.mutex) class WinTool(object): """This class performs all the Windows tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like recursive-mirror to RecursiveMirror.""" return name_string.title().replace('-', '') def _GetEnv(self, arch): """Gets the saved environment from a file for a given architecture.""" # The environment is saved as an "environment block" (see CreateProcess # and msvs_emulation for details). We convert to a dict here. # Drop last 2 NULs, one for list terminator, one for trailing vs. separator. pairs = open(arch).read()[:-2].split('\0') kvs = [item.split('=', 1) for item in pairs] return dict(kvs) def ExecStamp(self, path): """Simple stamp command.""" open(path, 'w').close() def ExecRecursiveMirror(self, source, dest): """Emulation of rm -rf out && cp -af in out.""" if os.path.exists(dest): if os.path.isdir(dest): shutil.rmtree(dest) else: os.unlink(dest) if os.path.isdir(source): shutil.copytree(source, dest) else: shutil.copy2(source, dest) def ExecLinkWrapper(self, arch, *args): """Filter diagnostic output from link that looks like: ' Creating library ui.dll.lib and object ui.dll.exp' This happens when there are exports from the dll or exe. """ with LinkLock(): env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if not line.startswith(' Creating library '): print line return popen.returncode def ExecManifestWrapper(self, arch, *args): """Run manifest tool with environment set. Strip out undesirable warning (some XML blocks are recognized by the OS loader, but not the manifest tool).""" env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if line and 'manifest authoring warning 81010002' not in line: print line return popen.returncode def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags): """Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags. """ args = ['midl', '/nologo'] + list(flags) + [ '/out', outdir, '/tlb', tlb, '/h', h, '/dlldata', dlldata, '/iid', iid, '/proxy', proxy, idl] env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() # Filter junk out of stdout, and write filtered versions. Output we want # to filter is pairs of lines that look like this: # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl # objidl.idl lines = out.splitlines() prefix = 'Processing ' processing = set(os.path.basename(x) for x in lines if x.startswith(prefix)) for line in lines: if not line.startswith(prefix) and line not in processing: print line return popen.returncode def ExecAsmWrapper(self, arch, *args): """Filter logo banner from invocations of asm.exe.""" env = self._GetEnv(arch) # MSVS doesn't assemble x64 asm files. if arch == 'environment.x64': return 0 popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines():
return popen.returncode def ExecRcWrapper(self, arch, *args): """Filter logo banner from invocations of rc.exe. Older versions of RC don't support the /nologo flag.""" env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and not line.startswith('Copyright (C) Microsoft Corporation') and line): print line return popen.returncode def ExecActionWrapper(self, arch, rspfile, *dir): """Runs an action command line from a response file using the environment for |arch|. If |dir| is supplied, use that as the working directory.""" env = self._GetEnv(arch) args = open(rspfile).read() dir = dir[0] if dir else None popen = subprocess.Popen(args, shell=True, env=env, cwd=dir) popen.wait() return popen.returncode if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
if (not line.startswith('Copyright (C) Microsoft Corporation') and not line.startswith('Microsoft (R) Macro Assembler') and not line.startswith(' Assembling: ') and line): print line
conditional_block
win_tool.py
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for Windows builds. These functions are executed via gyp-win-tool when using the ninja generator. """ from ctypes import windll, wintypes import os import shutil import subprocess import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def main(args): executor = WinTool() exit_code = executor.Dispatch(args) if exit_code is not None: sys.exit(exit_code) class LinkLock(object): """A flock-style lock to limit the number of concurrent links to one. Uses a session-local mutex based on the file's directory. """ def __enter__(self): name = 'Local\\%s' % BASE_DIR.replace('\\', '_').replace(':', '_') self.mutex = windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(0), wintypes.create_unicode_buffer(name)) assert self.mutex result = windll.kernel32.WaitForSingleObject( self.mutex, wintypes.c_int(0xFFFFFFFF)) # 0x80 means another process was killed without releasing the mutex, but # that this process has been given ownership. This is fine for our # purposes. assert result in (0, 0x80), ( "%s, %s" % (result, windll.kernel32.GetLastError())) def __exit__(self, type, value, traceback): windll.kernel32.ReleaseMutex(self.mutex) windll.kernel32.CloseHandle(self.mutex) class WinTool(object): """This class performs all the Windows tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like recursive-mirror to RecursiveMirror.""" return name_string.title().replace('-', '') def _GetEnv(self, arch): """Gets the saved environment from a file for a given architecture.""" # The environment is saved as an "environment block" (see CreateProcess # and msvs_emulation for details). We convert to a dict here. # Drop last 2 NULs, one for list terminator, one for trailing vs. separator. pairs = open(arch).read()[:-2].split('\0') kvs = [item.split('=', 1) for item in pairs] return dict(kvs) def ExecStamp(self, path): """Simple stamp command.""" open(path, 'w').close() def ExecRecursiveMirror(self, source, dest): """Emulation of rm -rf out && cp -af in out.""" if os.path.exists(dest): if os.path.isdir(dest): shutil.rmtree(dest) else: os.unlink(dest) if os.path.isdir(source): shutil.copytree(source, dest) else: shutil.copy2(source, dest) def ExecLinkWrapper(self, arch, *args): """Filter diagnostic output from link that looks like: ' Creating library ui.dll.lib and object ui.dll.exp' This happens when there are exports from the dll or exe. """ with LinkLock(): env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if not line.startswith(' Creating library '): print line return popen.returncode def ExecManifestWrapper(self, arch, *args): """Run manifest tool with environment set. Strip out undesirable warning (some XML blocks are recognized by the OS loader, but not the manifest tool).""" env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if line and 'manifest authoring warning 81010002' not in line: print line return popen.returncode def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags): """Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags. """ args = ['midl', '/nologo'] + list(flags) + [ '/out', outdir, '/tlb', tlb, '/h', h, '/dlldata', dlldata, '/iid', iid, '/proxy', proxy, idl] env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() # Filter junk out of stdout, and write filtered versions. Output we want # to filter is pairs of lines that look like this: # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl # objidl.idl lines = out.splitlines() prefix = 'Processing ' processing = set(os.path.basename(x) for x in lines if x.startswith(prefix)) for line in lines: if not line.startswith(prefix) and line not in processing: print line return popen.returncode def ExecAsmWrapper(self, arch, *args): """Filter logo banner from invocations of asm.exe.""" env = self._GetEnv(arch) # MSVS doesn't assemble x64 asm files. if arch == 'environment.x64': return 0 popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if (not line.startswith('Copyright (C) Microsoft Corporation') and not line.startswith('Microsoft (R) Macro Assembler') and not line.startswith(' Assembling: ') and line): print line return popen.returncode def ExecRcWrapper(self, arch, *args): """Filter logo banner from invocations of rc.exe. Older versions of RC don't support the /nologo flag.""" env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and not line.startswith('Copyright (C) Microsoft Corporation') and line): print line return popen.returncode def ExecActionWrapper(self, arch, rspfile, *dir): """Runs an action command line from a response file using the environment for |arch|. If |dir| is supplied, use that as the working directory.""" env = self._GetEnv(arch) args = open(rspfile).read() dir = dir[0] if dir else None popen = subprocess.Popen(args, shell=True, env=env, cwd=dir) popen.wait() return popen.returncode if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
random_line_split
win_tool.py
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for Windows builds. These functions are executed via gyp-win-tool when using the ninja generator. """ from ctypes import windll, wintypes import os import shutil import subprocess import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def main(args): executor = WinTool() exit_code = executor.Dispatch(args) if exit_code is not None: sys.exit(exit_code) class LinkLock(object): """A flock-style lock to limit the number of concurrent links to one. Uses a session-local mutex based on the file's directory. """ def __enter__(self): name = 'Local\\%s' % BASE_DIR.replace('\\', '_').replace(':', '_') self.mutex = windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(0), wintypes.create_unicode_buffer(name)) assert self.mutex result = windll.kernel32.WaitForSingleObject( self.mutex, wintypes.c_int(0xFFFFFFFF)) # 0x80 means another process was killed without releasing the mutex, but # that this process has been given ownership. This is fine for our # purposes. assert result in (0, 0x80), ( "%s, %s" % (result, windll.kernel32.GetLastError())) def __exit__(self, type, value, traceback): windll.kernel32.ReleaseMutex(self.mutex) windll.kernel32.CloseHandle(self.mutex) class WinTool(object): """This class performs all the Windows tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like recursive-mirror to RecursiveMirror.""" return name_string.title().replace('-', '') def _GetEnv(self, arch): """Gets the saved environment from a file for a given architecture.""" # The environment is saved as an "environment block" (see CreateProcess # and msvs_emulation for details). We convert to a dict here. # Drop last 2 NULs, one for list terminator, one for trailing vs. separator. pairs = open(arch).read()[:-2].split('\0') kvs = [item.split('=', 1) for item in pairs] return dict(kvs) def ExecStamp(self, path): """Simple stamp command.""" open(path, 'w').close() def ExecRecursiveMirror(self, source, dest): """Emulation of rm -rf out && cp -af in out.""" if os.path.exists(dest): if os.path.isdir(dest): shutil.rmtree(dest) else: os.unlink(dest) if os.path.isdir(source): shutil.copytree(source, dest) else: shutil.copy2(source, dest) def ExecLinkWrapper(self, arch, *args): """Filter diagnostic output from link that looks like: ' Creating library ui.dll.lib and object ui.dll.exp' This happens when there are exports from the dll or exe. """ with LinkLock(): env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if not line.startswith(' Creating library '): print line return popen.returncode def ExecManifestWrapper(self, arch, *args): """Run manifest tool with environment set. Strip out undesirable warning (some XML blocks are recognized by the OS loader, but not the manifest tool).""" env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if line and 'manifest authoring warning 81010002' not in line: print line return popen.returncode def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags):
def ExecAsmWrapper(self, arch, *args): """Filter logo banner from invocations of asm.exe.""" env = self._GetEnv(arch) # MSVS doesn't assemble x64 asm files. if arch == 'environment.x64': return 0 popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if (not line.startswith('Copyright (C) Microsoft Corporation') and not line.startswith('Microsoft (R) Macro Assembler') and not line.startswith(' Assembling: ') and line): print line return popen.returncode def ExecRcWrapper(self, arch, *args): """Filter logo banner from invocations of rc.exe. Older versions of RC don't support the /nologo flag.""" env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() for line in out.splitlines(): if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and not line.startswith('Copyright (C) Microsoft Corporation') and line): print line return popen.returncode def ExecActionWrapper(self, arch, rspfile, *dir): """Runs an action command line from a response file using the environment for |arch|. If |dir| is supplied, use that as the working directory.""" env = self._GetEnv(arch) args = open(rspfile).read() dir = dir[0] if dir else None popen = subprocess.Popen(args, shell=True, env=env, cwd=dir) popen.wait() return popen.returncode if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
"""Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags. """ args = ['midl', '/nologo'] + list(flags) + [ '/out', outdir, '/tlb', tlb, '/h', h, '/dlldata', dlldata, '/iid', iid, '/proxy', proxy, idl] env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() # Filter junk out of stdout, and write filtered versions. Output we want # to filter is pairs of lines that look like this: # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl # objidl.idl lines = out.splitlines() prefix = 'Processing ' processing = set(os.path.basename(x) for x in lines if x.startswith(prefix)) for line in lines: if not line.startswith(prefix) and line not in processing: print line return popen.returncode
identifier_body
detox-global-tests.ts
declare var describe: (test: string, callback: () => void) => void; declare var beforeAll: (callback: () => void) => void; declare var afterAll: (callback: () => void) => void; declare var test: (test: string, callback: () => void) => void; describe("Test", () => { beforeAll(async () => { await device.reloadReactNative(); }); afterAll(async () => { await element(by.id("element")).clearText(); }); test("Test", async () => { await element(by.id("element")).replaceText("text"); await element(by.id("element")).tap(); await element(by.id("element")).scroll(50, "down"); await element(by.id("scrollView")).scrollTo("bottom"); await expect(element(by.id("element")).atIndex(0)).toNotExist();
await element(by.id("scrollView")).swipe("down", "fast"); await element(by.type("UIPickerView")).setColumnToValue(1, "6"); await expect( element(by.id("element").withAncestor(by.id("parent_element"))) ).toNotExist(); await expect( element(by.id("element").withDescendant(by.id("child_element"))) ).toNotExist(); await waitFor(element(by.id("element"))) .toBeVisible() .withTimeout(2000); await device.pressBack(); await waitFor(element(by.text("Text5"))) .toBeVisible() .whileElement(by.id("ScrollView630")) .scroll(50, "down"); }); });
random_line_split
scipy_test.py
import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from scipy.stats import multivariate_normal as mvn norm.pdf(0) # mean: loc, stddev: scale norm.pdf(0, loc=5, scale=10) r = np.random.randn(10) # probability distribution function: norm.pdf(r) # log probability: norm.logpdf(r) # cumulative distribution function: norm.cdf(r) # log cumulative distribution function: norm.logcdf(r) # sampling from standard normal: r = np.random.randn(10000) plt.hist(r, bins=100) plt.show() mean = 5 stddev = 10 r = stddev*np.random.randn(10000)+mean plt.hist(r, bins=100) plt.show() # spherical Gaussian: r = np.random.randn(10000, 2) plt.scatter(r[:,0], r[:,1]) plt.show() # elliptical Gaussian: r[:,1] = stddev*r[:,1]+mean plt.scatter(r[:,0], r[:,1]) plt.axis('equal') plt.show() # non-axis-aligned Gaussian: cov = np.array([[1,0.8],[0.8,3]]) # covariant matrix, covariance: 0.8 in both dimensions mu = np.array([0,2]) r = mvn.rvs(mean=mu, cov=cov, size=1000) plt.scatter(r[:,0], r[:,1]) plt.axis('equal') plt.show() r = np.random.multivariate_normal(mean=mu, cov=cov, size=1000) plt.scatter(r[:,0], r[:,1]) plt.axis('equal') plt.show() # loading Matlab .mat files: scipy.io.loadmat # loading WAV files: scipy.io.wavfile.read (default sampling: 44100 Hz) # saving WAV files: scipy.io.wavfile.write # signal processing, filtering: scipy.signal # convolution: scipy.signal.convolve, scipy.signal.convolve2d # FFT is in numpy: x = np.linspace(0, 100, 10000) y = np.sin(x) + np.sin(3*x) + np.sin(5*x)
plt.show() Y = np.fft.fft(y) plt.plot(np.abs(Y)) plt.show() 2*np.pi*16/100 2*np.pi*48/100 2*np.pi*80/100
plt.plot(x, y)
random_line_split
attribute-config.ts
/* * Copyright (c) 2015-2018 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ 'use strict'; import {CheFocusable} from './focusable/che-focusable.directive'; import {CheAutoScroll} from './scroll/che-automatic-scroll.directive'; import {CheListOnScrollBottom} from './scroll/che-list-on-scroll-bottom.directive'; import {CheReloadHref} from './reload-href/che-reload-href.directive'; import {CheFormatOutput} from './format-output/che-format-output.directive'; import {CheOnLongTouch} from './touch/che-on-long-touch.directive'; import {CheOnRightClick} from './click/che-on-right-click.directive'; import {CheTypeNumber} from './input-type/input-number.directive'; import {CheTypeCity} from './input-type/input-city.directive'; import {CheMultiTransclude} from './multi-transclude/che-multi-transclude.directive'; import {CheMultiTranscludePart} from './multi-transclude/che-multi-transclude-part.directive'; import {ImgSrc} from './img-src/img-src.directive'; import {CheClipTheMiddle} from './clip-the-middle/che-clip-the-middle.directive'; export class AttributeConfig {
(register: che.IRegisterService) { register.directive('focusable', CheFocusable); register.directive('cheAutoScroll', CheAutoScroll); register.directive('cheListOnScrollBottom', CheListOnScrollBottom); register.directive('cheReloadHref', CheReloadHref); register.directive('cheFormatOutput', CheFormatOutput); register.directive('cheOnLongTouch', CheOnLongTouch); register.directive('cheOnRightClick', CheOnRightClick); register.directive('cheTypeNumber', CheTypeNumber); register.directive('cheTypeCity', CheTypeCity); register.directive('cheMultiTransclude', CheMultiTransclude); register.directive('cheMultiTranscludePart', CheMultiTranscludePart); register.directive('imgSrc', ImgSrc); register.directive('cheClipTheMiddle', CheClipTheMiddle); } }
constructor
identifier_name
attribute-config.ts
/* * Copyright (c) 2015-2018 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ 'use strict'; import {CheFocusable} from './focusable/che-focusable.directive'; import {CheAutoScroll} from './scroll/che-automatic-scroll.directive'; import {CheListOnScrollBottom} from './scroll/che-list-on-scroll-bottom.directive'; import {CheReloadHref} from './reload-href/che-reload-href.directive'; import {CheFormatOutput} from './format-output/che-format-output.directive'; import {CheOnLongTouch} from './touch/che-on-long-touch.directive'; import {CheOnRightClick} from './click/che-on-right-click.directive'; import {CheTypeNumber} from './input-type/input-number.directive'; import {CheTypeCity} from './input-type/input-city.directive'; import {CheMultiTransclude} from './multi-transclude/che-multi-transclude.directive'; import {CheMultiTranscludePart} from './multi-transclude/che-multi-transclude-part.directive'; import {ImgSrc} from './img-src/img-src.directive'; import {CheClipTheMiddle} from './clip-the-middle/che-clip-the-middle.directive'; export class AttributeConfig { constructor(register: che.IRegisterService) {
register.directive('focusable', CheFocusable); register.directive('cheAutoScroll', CheAutoScroll); register.directive('cheListOnScrollBottom', CheListOnScrollBottom); register.directive('cheReloadHref', CheReloadHref); register.directive('cheFormatOutput', CheFormatOutput); register.directive('cheOnLongTouch', CheOnLongTouch); register.directive('cheOnRightClick', CheOnRightClick); register.directive('cheTypeNumber', CheTypeNumber); register.directive('cheTypeCity', CheTypeCity); register.directive('cheMultiTransclude', CheMultiTransclude); register.directive('cheMultiTranscludePart', CheMultiTranscludePart); register.directive('imgSrc', ImgSrc); register.directive('cheClipTheMiddle', CheClipTheMiddle); } }
random_line_split
get_last_with_len.rs
//! lint on using `x.get(x.len() - 1)` instead of `x.last()` use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::SpanlessEq; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Spanned; use rustc_span::sym; declare_clippy_lint! { /// ### What it does /// Checks for using `x.get(x.len() - 1)` instead of /// `x.last()`. /// /// ### Why is this bad? /// Using `x.last()` is easier to read and has the same /// result. /// /// Note that using `x[x.len() - 1]` is semantically different from /// `x.last()`. Indexing into the array will panic on out-of-bounds /// accesses, while `x.get()` and `x.last()` will return `None`. /// /// There is another lint (get_unwrap) that covers the case of using /// `x.get(index).unwrap()` instead of `x[index]`. /// /// ### Example /// ```rust /// // Bad /// let x = vec![2, 3, 5]; /// let last_element = x.get(x.len() - 1); /// /// // Good /// let x = vec![2, 3, 5]; /// let last_element = x.last(); /// ``` pub GET_LAST_WITH_LEN, complexity, "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler" } declare_lint_pass!(GetLastWithLen => [GET_LAST_WITH_LEN]); impl<'tcx> LateLintPass<'tcx> for GetLastWithLen { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)
}
{ if_chain! { // Is a method call if let ExprKind::MethodCall(path, _, args, _) = expr.kind; // Method name is "get" if path.ident.name == sym!(get); // Argument 0 (the struct we're calling the method on) is a vector if let Some(struct_calling_on) = args.get(0); let struct_ty = cx.typeck_results().expr_ty(struct_calling_on); if is_type_diagnostic_item(cx, struct_ty, sym::Vec); // Argument to "get" is a subtraction if let Some(get_index_arg) = args.get(1); if let ExprKind::Binary( Spanned { node: BinOpKind::Sub, .. }, lhs, rhs, ) = &get_index_arg.kind; // LHS of subtraction is "x.len()" if let ExprKind::MethodCall(arg_lhs_path, _, lhs_args, _) = &lhs.kind; if arg_lhs_path.ident.name == sym::len; if let Some(arg_lhs_struct) = lhs_args.get(0); // The two vectors referenced (x in x.get(...) and in x.len()) if SpanlessEq::new(cx).eq_expr(struct_calling_on, arg_lhs_struct); // RHS of subtraction is 1 if let ExprKind::Lit(rhs_lit) = &rhs.kind; if let LitKind::Int(1, ..) = rhs_lit.node; then { let mut applicability = Applicability::MachineApplicable; let vec_name = snippet_with_applicability( cx, struct_calling_on.span, "vec", &mut applicability, ); span_lint_and_sugg( cx, GET_LAST_WITH_LEN, expr.span, &format!("accessing last element with `{0}.get({0}.len() - 1)`", vec_name), "try", format!("{}.last()", vec_name), applicability, ); } } }
identifier_body
get_last_with_len.rs
//! lint on using `x.get(x.len() - 1)` instead of `x.last()` use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::SpanlessEq; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Spanned; use rustc_span::sym; declare_clippy_lint! { /// ### What it does /// Checks for using `x.get(x.len() - 1)` instead of /// `x.last()`. /// /// ### Why is this bad? /// Using `x.last()` is easier to read and has the same /// result. /// /// Note that using `x[x.len() - 1]` is semantically different from /// `x.last()`. Indexing into the array will panic on out-of-bounds /// accesses, while `x.get()` and `x.last()` will return `None`. /// /// There is another lint (get_unwrap) that covers the case of using /// `x.get(index).unwrap()` instead of `x[index]`. /// /// ### Example /// ```rust /// // Bad /// let x = vec![2, 3, 5]; /// let last_element = x.get(x.len() - 1); /// /// // Good /// let x = vec![2, 3, 5]; /// let last_element = x.last(); /// ``` pub GET_LAST_WITH_LEN, complexity, "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { // Is a method call if let ExprKind::MethodCall(path, _, args, _) = expr.kind; // Method name is "get" if path.ident.name == sym!(get); // Argument 0 (the struct we're calling the method on) is a vector if let Some(struct_calling_on) = args.get(0); let struct_ty = cx.typeck_results().expr_ty(struct_calling_on); if is_type_diagnostic_item(cx, struct_ty, sym::Vec); // Argument to "get" is a subtraction if let Some(get_index_arg) = args.get(1); if let ExprKind::Binary( Spanned { node: BinOpKind::Sub, .. }, lhs, rhs, ) = &get_index_arg.kind; // LHS of subtraction is "x.len()" if let ExprKind::MethodCall(arg_lhs_path, _, lhs_args, _) = &lhs.kind; if arg_lhs_path.ident.name == sym::len; if let Some(arg_lhs_struct) = lhs_args.get(0); // The two vectors referenced (x in x.get(...) and in x.len()) if SpanlessEq::new(cx).eq_expr(struct_calling_on, arg_lhs_struct); // RHS of subtraction is 1 if let ExprKind::Lit(rhs_lit) = &rhs.kind; if let LitKind::Int(1, ..) = rhs_lit.node; then { let mut applicability = Applicability::MachineApplicable; let vec_name = snippet_with_applicability( cx, struct_calling_on.span, "vec", &mut applicability, ); span_lint_and_sugg( cx, GET_LAST_WITH_LEN, expr.span, &format!("accessing last element with `{0}.get({0}.len() - 1)`", vec_name), "try", format!("{}.last()", vec_name), applicability, ); } } } }
} declare_lint_pass!(GetLastWithLen => [GET_LAST_WITH_LEN]); impl<'tcx> LateLintPass<'tcx> for GetLastWithLen {
random_line_split
get_last_with_len.rs
//! lint on using `x.get(x.len() - 1)` instead of `x.last()` use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::SpanlessEq; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Spanned; use rustc_span::sym; declare_clippy_lint! { /// ### What it does /// Checks for using `x.get(x.len() - 1)` instead of /// `x.last()`. /// /// ### Why is this bad? /// Using `x.last()` is easier to read and has the same /// result. /// /// Note that using `x[x.len() - 1]` is semantically different from /// `x.last()`. Indexing into the array will panic on out-of-bounds /// accesses, while `x.get()` and `x.last()` will return `None`. /// /// There is another lint (get_unwrap) that covers the case of using /// `x.get(index).unwrap()` instead of `x[index]`. /// /// ### Example /// ```rust /// // Bad /// let x = vec![2, 3, 5]; /// let last_element = x.get(x.len() - 1); /// /// // Good /// let x = vec![2, 3, 5]; /// let last_element = x.last(); /// ``` pub GET_LAST_WITH_LEN, complexity, "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler" } declare_lint_pass!(GetLastWithLen => [GET_LAST_WITH_LEN]); impl<'tcx> LateLintPass<'tcx> for GetLastWithLen { fn
(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { // Is a method call if let ExprKind::MethodCall(path, _, args, _) = expr.kind; // Method name is "get" if path.ident.name == sym!(get); // Argument 0 (the struct we're calling the method on) is a vector if let Some(struct_calling_on) = args.get(0); let struct_ty = cx.typeck_results().expr_ty(struct_calling_on); if is_type_diagnostic_item(cx, struct_ty, sym::Vec); // Argument to "get" is a subtraction if let Some(get_index_arg) = args.get(1); if let ExprKind::Binary( Spanned { node: BinOpKind::Sub, .. }, lhs, rhs, ) = &get_index_arg.kind; // LHS of subtraction is "x.len()" if let ExprKind::MethodCall(arg_lhs_path, _, lhs_args, _) = &lhs.kind; if arg_lhs_path.ident.name == sym::len; if let Some(arg_lhs_struct) = lhs_args.get(0); // The two vectors referenced (x in x.get(...) and in x.len()) if SpanlessEq::new(cx).eq_expr(struct_calling_on, arg_lhs_struct); // RHS of subtraction is 1 if let ExprKind::Lit(rhs_lit) = &rhs.kind; if let LitKind::Int(1, ..) = rhs_lit.node; then { let mut applicability = Applicability::MachineApplicable; let vec_name = snippet_with_applicability( cx, struct_calling_on.span, "vec", &mut applicability, ); span_lint_and_sugg( cx, GET_LAST_WITH_LEN, expr.span, &format!("accessing last element with `{0}.get({0}.len() - 1)`", vec_name), "try", format!("{}.last()", vec_name), applicability, ); } } } }
check_expr
identifier_name
IPostComponentProps.ts
import { Comment } from 'core/domain/comments' import { Post } from 'core/domain/posts/post' import {Map} from 'immutable' export interface IPostComponentProps { /** * Post object */ post: Map<string, any> /** * Owner's post avatar * * @type {string} * @memberof IPostComponentProps */ avatar?: string /** * User full name * * @type {string} * @memberof IPostComponentProps */ fullName?: string /** * Number of vote on a post * * @type {number} * @memberof IPostComponentProps */ voteCount?: number /** * Current user vote the post {true} or not {false} * * @type {boolean} * @memberof IPostComponentProps */ currentUserVote?: boolean /** * Current user is the owner of the post {true} or not {false} * * @type {boolean} * @memberof IPostComponentProps */ isPostOwner?: boolean
* Vote a post * * @memberof IPostComponentProps */ vote?: () => any /** * Delete a vote on the post * * @memberof IPostComponentProps */ unvote?: () => any /** * Delte a post * * @memberof IPostComponentProps */ delete?: (id: string) => any /** * Toggle comment disable/enable * * @memberof IPostComponentProps */ toggleDisableComments?: (status: boolean) => any /** * Toggle sharing disable/enable * * @memberof IPostComponentProps */ toggleSharingComments?: (status: boolean) => any /** * Redirect to {url} route * * @memberof IPostComponentProps */ goTo?: (url: string) => any /** * Set tile of top bar * * @memberof IPostComponentProps */ setHomeTitle?: (title: string) => any /** * Get the comments of a post * * @memberof IPostComponentProps */ getPostComments?: (ownerUserId: string, postId: string) => any /** * Commnets * * @type {{[commentId: string]: Comment}} * @memberof ICommentGroupComponentProps */ commentList?: Map<string, Comment> /** * Styles */ classes?: any /** * Translate to locale string */ translate?: (state: any) => any }
/**
random_line_split
RootItem.js
import React from 'react'; import PropTypes from 'prop-types'; import style from 'PVWStyle/ReactWidgets/CompositePipelineWidget.mcss'; import ChildItem from './ChildItem'; /** * This React component expect the following input properties: * - model: * Expect a LokkupTable instance that you want to render and edit. * - item: * Root of the tree * - layer: * Layer id. */ export default class CompositePipelineWidgetRootItem extends React.Component { constructor(props) { super(props); this.state = { dropDown: false, }; // Bind callback this.toggleVisibility = this.toggleVisibility.bind(this); this.toggleDropDown = this.toggleDropDown.bind(this); this.updateColorBy = this.updateColorBy.bind(this); this.toggleEditMode = this.toggleEditMode.bind(this); this.updateOpacity = this.updateOpacity.bind(this); } toggleVisibility() { this.props.model.toggleLayerVisible(this.props.layer); }
() { if (this.props.model.getColor(this.props.layer).length > 1) { this.setState({ dropDown: !this.state.dropDown, }); } } updateColorBy(event) { this.props.model.setActiveColor( this.props.layer, event.target.dataset.color ); this.toggleDropDown(); } toggleEditMode() { this.props.model.toggleEditMode(this.props.layer); } updateOpacity(e) { this.props.model.setOpacity(this.props.layer, e.target.value); this.forceUpdate(); } render() { const model = this.props.model; const layer = this.props.layer; const visible = model.isLayerVisible(this.props.layer); const children = this.props.item.children || []; const inEditMode = this.props.model.isLayerInEditMode(this.props.layer); const hasChildren = children.length > 0; const hasOpacity = model.hasOpacity(); const hasDropDown = this.props.model.getColor(this.props.layer).length > 1; const editButton = hasChildren ? ( <i className={inEditMode ? style.editButtonOn : style.editButtonOff} onClick={this.toggleEditMode} /> ) : ( '' ); return ( <div className={style.section}> <div className={style.item}> <div className={style.label}>{this.props.item.name}</div> <div className={style.actions}> {editButton} <i className={ visible ? style.visibleButtonOn : style.visibleButtonOff } onClick={this.toggleVisibility} /> <i className={ hasDropDown ? style.dropDownButtonOn : style.dropDownButtonOff } onClick={this.toggleDropDown} /> <div onClick={this.updateColorBy} className={this.state.dropDown ? style.menu : style.hidden} > {model.getColor(layer).map((color) => ( <div key={color} data-color={color} className={ model.isActiveColor(layer, color) ? style.selectedMenuItem : style.menuItem } > {model.getColorToLabel(color)} </div> ))} </div> </div> </div> <div className={hasOpacity && !hasChildren ? style.item : style.hidden}> <input className={style.opacity} type="range" min="0" max="100" value={model.getOpacity(layer)} onChange={this.updateOpacity} /> </div> <div className={style.children}> {children.map((item, idx) => ( <ChildItem key={idx} item={item} layer={item.ids.join('')} model={model} /> ))} </div> </div> ); } } CompositePipelineWidgetRootItem.propTypes = { item: PropTypes.object, layer: PropTypes.string, model: PropTypes.object, }; CompositePipelineWidgetRootItem.defaultProps = { item: undefined, layer: undefined, model: undefined, };
toggleDropDown
identifier_name
RootItem.js
import React from 'react'; import PropTypes from 'prop-types'; import style from 'PVWStyle/ReactWidgets/CompositePipelineWidget.mcss'; import ChildItem from './ChildItem'; /** * This React component expect the following input properties: * - model: * Expect a LokkupTable instance that you want to render and edit. * - item: * Root of the tree * - layer: * Layer id. */ export default class CompositePipelineWidgetRootItem extends React.Component { constructor(props) { super(props); this.state = { dropDown: false, }; // Bind callback this.toggleVisibility = this.toggleVisibility.bind(this); this.toggleDropDown = this.toggleDropDown.bind(this); this.updateColorBy = this.updateColorBy.bind(this); this.toggleEditMode = this.toggleEditMode.bind(this); this.updateOpacity = this.updateOpacity.bind(this); } toggleVisibility() { this.props.model.toggleLayerVisible(this.props.layer); } toggleDropDown() { if (this.props.model.getColor(this.props.layer).length > 1)
} updateColorBy(event) { this.props.model.setActiveColor( this.props.layer, event.target.dataset.color ); this.toggleDropDown(); } toggleEditMode() { this.props.model.toggleEditMode(this.props.layer); } updateOpacity(e) { this.props.model.setOpacity(this.props.layer, e.target.value); this.forceUpdate(); } render() { const model = this.props.model; const layer = this.props.layer; const visible = model.isLayerVisible(this.props.layer); const children = this.props.item.children || []; const inEditMode = this.props.model.isLayerInEditMode(this.props.layer); const hasChildren = children.length > 0; const hasOpacity = model.hasOpacity(); const hasDropDown = this.props.model.getColor(this.props.layer).length > 1; const editButton = hasChildren ? ( <i className={inEditMode ? style.editButtonOn : style.editButtonOff} onClick={this.toggleEditMode} /> ) : ( '' ); return ( <div className={style.section}> <div className={style.item}> <div className={style.label}>{this.props.item.name}</div> <div className={style.actions}> {editButton} <i className={ visible ? style.visibleButtonOn : style.visibleButtonOff } onClick={this.toggleVisibility} /> <i className={ hasDropDown ? style.dropDownButtonOn : style.dropDownButtonOff } onClick={this.toggleDropDown} /> <div onClick={this.updateColorBy} className={this.state.dropDown ? style.menu : style.hidden} > {model.getColor(layer).map((color) => ( <div key={color} data-color={color} className={ model.isActiveColor(layer, color) ? style.selectedMenuItem : style.menuItem } > {model.getColorToLabel(color)} </div> ))} </div> </div> </div> <div className={hasOpacity && !hasChildren ? style.item : style.hidden}> <input className={style.opacity} type="range" min="0" max="100" value={model.getOpacity(layer)} onChange={this.updateOpacity} /> </div> <div className={style.children}> {children.map((item, idx) => ( <ChildItem key={idx} item={item} layer={item.ids.join('')} model={model} /> ))} </div> </div> ); } } CompositePipelineWidgetRootItem.propTypes = { item: PropTypes.object, layer: PropTypes.string, model: PropTypes.object, }; CompositePipelineWidgetRootItem.defaultProps = { item: undefined, layer: undefined, model: undefined, };
{ this.setState({ dropDown: !this.state.dropDown, }); }
conditional_block
RootItem.js
import React from 'react'; import PropTypes from 'prop-types'; import style from 'PVWStyle/ReactWidgets/CompositePipelineWidget.mcss'; import ChildItem from './ChildItem'; /** * This React component expect the following input properties: * - model: * Expect a LokkupTable instance that you want to render and edit. * - item: * Root of the tree * - layer: * Layer id. */ export default class CompositePipelineWidgetRootItem extends React.Component { constructor(props) { super(props); this.state = { dropDown: false, }; // Bind callback this.toggleVisibility = this.toggleVisibility.bind(this); this.toggleDropDown = this.toggleDropDown.bind(this); this.updateColorBy = this.updateColorBy.bind(this); this.toggleEditMode = this.toggleEditMode.bind(this); this.updateOpacity = this.updateOpacity.bind(this); } toggleVisibility() { this.props.model.toggleLayerVisible(this.props.layer);
toggleDropDown() { if (this.props.model.getColor(this.props.layer).length > 1) { this.setState({ dropDown: !this.state.dropDown, }); } } updateColorBy(event) { this.props.model.setActiveColor( this.props.layer, event.target.dataset.color ); this.toggleDropDown(); } toggleEditMode() { this.props.model.toggleEditMode(this.props.layer); } updateOpacity(e) { this.props.model.setOpacity(this.props.layer, e.target.value); this.forceUpdate(); } render() { const model = this.props.model; const layer = this.props.layer; const visible = model.isLayerVisible(this.props.layer); const children = this.props.item.children || []; const inEditMode = this.props.model.isLayerInEditMode(this.props.layer); const hasChildren = children.length > 0; const hasOpacity = model.hasOpacity(); const hasDropDown = this.props.model.getColor(this.props.layer).length > 1; const editButton = hasChildren ? ( <i className={inEditMode ? style.editButtonOn : style.editButtonOff} onClick={this.toggleEditMode} /> ) : ( '' ); return ( <div className={style.section}> <div className={style.item}> <div className={style.label}>{this.props.item.name}</div> <div className={style.actions}> {editButton} <i className={ visible ? style.visibleButtonOn : style.visibleButtonOff } onClick={this.toggleVisibility} /> <i className={ hasDropDown ? style.dropDownButtonOn : style.dropDownButtonOff } onClick={this.toggleDropDown} /> <div onClick={this.updateColorBy} className={this.state.dropDown ? style.menu : style.hidden} > {model.getColor(layer).map((color) => ( <div key={color} data-color={color} className={ model.isActiveColor(layer, color) ? style.selectedMenuItem : style.menuItem } > {model.getColorToLabel(color)} </div> ))} </div> </div> </div> <div className={hasOpacity && !hasChildren ? style.item : style.hidden}> <input className={style.opacity} type="range" min="0" max="100" value={model.getOpacity(layer)} onChange={this.updateOpacity} /> </div> <div className={style.children}> {children.map((item, idx) => ( <ChildItem key={idx} item={item} layer={item.ids.join('')} model={model} /> ))} </div> </div> ); } } CompositePipelineWidgetRootItem.propTypes = { item: PropTypes.object, layer: PropTypes.string, model: PropTypes.object, }; CompositePipelineWidgetRootItem.defaultProps = { item: undefined, layer: undefined, model: undefined, };
}
random_line_split