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
ast.rs
use std::cell::Cell; use std::fmt; use std::vec::Vec; pub type Var = String; pub type Atom = String; pub enum TopLevel { Fact(Term), Query(Term) } #[derive(Clone, Copy)] pub enum Level { Shallow, Deep } impl fmt::Display for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Level::Shallow => write!(f, "A"), &Level::Deep => write!(f, "X") } } } #[derive(Clone, Copy)] pub enum Reg { ArgAndNorm(usize, usize), Norm(usize) } impl Reg { pub fn has_arg(&self) -> bool { match self { &Reg::ArgAndNorm(_, _) => true, _ => false } } pub fn norm(&self) -> usize { match self { &Reg::ArgAndNorm(_, norm) | &Reg::Norm(norm) => norm } } } pub enum Term { Atom(Cell<usize>, Atom), Clause(Cell<usize>, Atom, Vec<Box<Term>>), Var(Cell<Reg>, Var) } pub enum TermRef<'a> { Atom(Level, &'a Cell<usize>, &'a Atom), Clause(Level, &'a Cell<usize>, &'a Atom, &'a Vec<Box<Term>>), Var(Level, &'a Cell<Reg>, &'a Var) } #[derive(Clone)] pub enum FactInstruction { GetStructure(Level, Atom, usize, usize), GetValue(usize, usize), GetVariable(usize, usize), Proceed, UnifyVariable(usize), UnifyValue(usize) } pub enum QueryInstruction { Call(Atom, usize), PutStructure(Level, Atom, usize, usize), PutValue(usize, usize), PutVariable(usize, usize), SetVariable(usize), SetValue(usize), } pub type CompiledFact = Vec<FactInstruction>; pub type CompiledQuery = Vec<QueryInstruction>; #[derive(Clone, Copy, PartialEq)] pub enum Addr { HeapCell(usize), RegNum(usize) } #[derive(Clone)] pub enum HeapCellValue { NamedStr(usize, Atom), Ref(usize), Str(usize), } pub type Heap = Vec<HeapCellValue>; pub type Registers = Vec<HeapCellValue>; impl Term { pub fn subterms(&self) -> usize { match self { &Term::Clause(_, _, ref terms) => terms.len(), _ => 1 } } pub fn name(&self) -> &Atom { match self { &Term::Atom(_, ref atom) | &Term::Var(_, ref atom) | &Term::Clause(_, ref atom, _) => atom } } pub fn arity(&self) -> usize {
match self { &Term::Atom(_, _) | &Term::Var(_, _) => 0, &Term::Clause(_, _, ref child_terms) => child_terms.len() } } }
random_line_split
lib.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! A library for interacting with Twitter. //! //! [Repository](https://github.com/QuietMisdreavus/twitter-rs) //! //! egg-mode is a Twitter library that aims to make as few assumptions about the user's codebase as //! possible. Endpoints are exposed as bare functions where authentication details are passed in as //! arguments, rather than as builder functions of a root "service" manager. The only exceptions to //! this guideline are endpoints with many optional parameters, like posting a status update or //! updating the metadata of a list. //! //! # About the examples in this documentation //! //! There are a couple prerequisites to using egg-mode, which its examples also assume: //! //! * All methods that hit the twitter API are `async` and should be awaited with the `.await` syntax. //! All such calls return a result type with the `Error` enum as their Error value. //! The resulting future must be executed on a `tokio` executor. //! For more information, check out the [Rust `async` book][rust-futures] and the //! [Tokio documentation guides][]. //! //! * Twitter tracks API use through "tokens" which are managed by Twitter and processed separately //! for each "authenticated user" you wish to connect to your app. egg-mode's [Token] //! documentation describes how you can obtain one of these, but each example outside of the //! authentication documentation brings in a `Token` "offscreen", to avoid distracting from the //! rest of the example. //! //! [Token]: enum.Token.html //! [tokio]: https://tokio.rs //! [rust-futures]: https://rust-lang.github.io/async-book/ //! [Tokio documentation guides]: https://tokio.rs/docs/overview //! //! To load the profile information of a single user: //! //! ```rust,no_run //! # use egg_mode::Token; //! # #[tokio::main] //! # async fn main() { //! # let token: Token = unimplemented!(); //! let rustlang = egg_mode::user::show("rustlang", &token).await.unwrap(); //! //! println!("{} (@{})", rustlang.name, rustlang.screen_name); //! # } //! ```
//! //! ```rust,no_run //! # use egg_mode::Token; //! use egg_mode::tweet::DraftTweet; //! # #[tokio::main] //! # async fn main() { //! # let token: Token = unimplemented!(); //! //! let post = DraftTweet::new("Hey Twitter!").send(&token).await.unwrap(); //! # } //! ``` //! //! # Types and Functions //! //! All of the main content of egg-mode is in submodules, but there are a few things here in the //! crate root. To wit, it contains items related to authentication and a couple items that all the //! submodules use. //! //! ## `Response<T>` //! //! Every method that calls Twitter and carries rate-limit information wraps its return value in a //! [`Response`][] struct, that transmits this information to your app. From there, you can handle //! the rate-limit information to hold off on that kind of request, or simply grab its `response` //! field to get the output of whatever method you called. `Response` also implements `Deref`, so //! for the most part you can access fields of the final result without having to grab the //! `response` field directly. //! //! [`Response`]: struct.Response.html //! //! ## Authentication //! //! The remaining types and methods are explained as part of the [authentication overview][Token], //! with the exception of `verify_tokens`, which is a simple method to ensure a given token is //! still valid. //! //! # Modules //! //! As there are many actions available in the Twitter API, egg-mode divides them roughly into //! several modules by their shared purpose. Here's a sort of high-level overview, in rough order //! from "most important" to "less directly used": //! //! ## Primary actions //! //! These could be considered the "core" actions within the Twitter API that egg-mode has made //! available. //! //! * `tweet`: This module lets you act on tweets. Here you can find actions to load a user's //! timeline, post a new tweet, or like and retweet individual posts. //! * `user`: This module lets you act on users, be it by following or unfollowing them, loading //! their profile information, blocking or muting them, or showing the relationship between two //! users. //! * `search`: Due to the complexity of searching for tweets, it gets its own module. //! * `direct`: Here you can work with a user's Direct Messages, either by loading DMs they've sent //! or received, or by sending new ones. //! * `list`: This module lets you act on lists, from creating and deleting them, adding and //! removing users, or loading the posts made by their members. //! * `media`: This module lets you upload images, GIFs, and videos to Twitter so you can attach //! them to tweets. //! //! ## Secondary actions //! //! These modules still contain direct actions for Twitter, but they can be considered as having //! more of a helper role than something you might use directly. //! //! * `place`: Here are actions that look up physical locations that can be attached to tweets, as //! well at the `Place` struct that appears on tweets with locations attached. //! * `service`: These are some miscellaneous methods that show information about the Twitter //! service as a whole, like loading the maximum length of t.co URLs or loading the current Terms //! of Service or Privacy Policy. //! //! ## Helper structs //! //! These modules contain some implementations that wrap some pattern seen in multiple "action" //! modules. //! //! * `cursor`: This contains a helper trait and some helper structs that allow effective cursoring //! through certain collections of results from Twitter. //! * `entities`: Whenever some text can be returned that may contain links, hashtags, media, or //! user mentions, its metadata is parsed into something that lives in this module. //! * `error`: Any interaction with Twitter may result in an error condition, be it from finding a //! tweet or user that doesn't exist or the network connection being unavailable. All the error //! types are aggregated into an enum in this module. #![warn(missing_docs)] #![warn(unused_extern_crates)] #![warn(unused_qualifications)] #[macro_use] mod common; mod auth; pub mod cursor; pub mod direct; pub mod entities; pub mod error; mod links; pub mod list; pub mod media; pub mod place; pub mod search; pub mod service; pub mod stream; pub mod tweet; pub mod user; pub use crate::auth::{ access_token, authenticate_url, authorize_url, bearer_token, invalidate_bearer, request_token, verify_tokens, KeyPair, Token, }; pub use crate::common::Response;
//! //! To post a new tweet:
random_line_split
auth.service.js
'use strict'; angular.module('terminaaliApp') .factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) { var currentUser = {}; if($cookieStore.get('token')) { currentUser = User.get(); } return { /** * Authenticate user and save token * * @param {Object} user - login info * @param {Function} callback - optional * @return {Promise} */ login: function(user, callback) { var cb = callback || angular.noop; var deferred = $q.defer(); $http.post('/auth/local', { email: user.email, password: user.password }). success(function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); deferred.resolve(data); return cb(); }). error(function(err) { this.logout(); deferred.reject(err); return cb(err); }.bind(this)); return deferred.promise; }, /** * Delete access token and user info * * @param {Function} */ logout: function() { $cookieStore.remove('token'); currentUser = {}; }, /** * Create a new user * * @param {Object} user - user info * @param {Function} callback - optional * @return {Promise} */ createUser: function(user, callback) { var cb = callback || angular.noop; return User.save(user, function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); return cb(user); }, function(err) { this.logout(); return cb(err); }.bind(this)).$promise; }, /** * Change password * * @param {String} oldPassword * @param {String} newPassword * @param {Function} callback - optional * @return {Promise} */ changePassword: function(oldPassword, newPassword, callback) { var cb = callback || angular.noop; return User.changePassword({ id: currentUser._id }, { oldPassword: oldPassword, newPassword: newPassword
}, function(err) { return cb(err); }).$promise; }, /** * Gets all available info on authenticated user * * @return {Object} user */ getCurrentUser: function() { return currentUser; }, /** * Check if a user is logged in * * @return {Boolean} */ isLoggedIn: function() { return currentUser.hasOwnProperty('role'); }, /** * Waits for currentUser to resolve before checking if user is logged in */ isLoggedInAsync: function(cb) { if(currentUser.hasOwnProperty('$promise')) { currentUser.$promise.then(function() { cb(true); }).catch(function() { cb(false); }); } else if(currentUser.hasOwnProperty('role')) { cb(true); } else { cb(false); } }, /** * Check if a user is an admin * * @return {Boolean} */ isAdmin: function() { return currentUser.role === 'admin'; }, /** * Get auth token */ getToken: function() { return $cookieStore.get('token'); } }; });
}, function(user) { return cb(user);
random_line_split
auth.service.js
'use strict'; angular.module('terminaaliApp') .factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) { var currentUser = {}; if($cookieStore.get('token')) { currentUser = User.get(); } return { /** * Authenticate user and save token * * @param {Object} user - login info * @param {Function} callback - optional * @return {Promise} */ login: function(user, callback) { var cb = callback || angular.noop; var deferred = $q.defer(); $http.post('/auth/local', { email: user.email, password: user.password }). success(function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); deferred.resolve(data); return cb(); }). error(function(err) { this.logout(); deferred.reject(err); return cb(err); }.bind(this)); return deferred.promise; }, /** * Delete access token and user info * * @param {Function} */ logout: function() { $cookieStore.remove('token'); currentUser = {}; }, /** * Create a new user * * @param {Object} user - user info * @param {Function} callback - optional * @return {Promise} */ createUser: function(user, callback) { var cb = callback || angular.noop; return User.save(user, function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); return cb(user); }, function(err) { this.logout(); return cb(err); }.bind(this)).$promise; }, /** * Change password * * @param {String} oldPassword * @param {String} newPassword * @param {Function} callback - optional * @return {Promise} */ changePassword: function(oldPassword, newPassword, callback) { var cb = callback || angular.noop; return User.changePassword({ id: currentUser._id }, { oldPassword: oldPassword, newPassword: newPassword }, function(user) { return cb(user); }, function(err) { return cb(err); }).$promise; }, /** * Gets all available info on authenticated user * * @return {Object} user */ getCurrentUser: function() { return currentUser; }, /** * Check if a user is logged in * * @return {Boolean} */ isLoggedIn: function() { return currentUser.hasOwnProperty('role'); }, /** * Waits for currentUser to resolve before checking if user is logged in */ isLoggedInAsync: function(cb) { if(currentUser.hasOwnProperty('$promise')) { currentUser.$promise.then(function() { cb(true); }).catch(function() { cb(false); }); } else if(currentUser.hasOwnProperty('role')) { cb(true); } else
}, /** * Check if a user is an admin * * @return {Boolean} */ isAdmin: function() { return currentUser.role === 'admin'; }, /** * Get auth token */ getToken: function() { return $cookieStore.get('token'); } }; });
{ cb(false); }
conditional_block
UserDirBlock.py
import time from Block import Block from ..ProtectFlags import ProtectFlags class UserDirBlock(Block): def __init__(self, blkdev, blk_num): Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR) def set(self, data): self._set_data(data) self._read() def read(self): self._read_data() self._read() def _read(self): Block.read(self) if not self.valid:
# UserDir fields self.own_key = self._get_long(1) self.protect = self._get_long(-48) self.comment = self._get_bstr(-46, 79) self.mod_ts = self._get_timestamp(-23) self.name = self._get_bstr(-20, 30) self.hash_chain = self._get_long(-4) self.parent = self._get_long(-3) self.extension = self._get_long(-2) # hash table of entries self.hash_table = [] self.hash_size = self.blkdev.block_longs - 56 for i in xrange(self.hash_size): self.hash_table.append(self._get_long(6+i)) self.valid = (self.own_key == self.blk_num) return self.valid def create(self, parent, name, protect=0, comment=None, mod_ts=None, hash_chain=0, extension=0): Block.create(self) self.own_key = self.blk_num self.protect = protect if comment == None: self.comment = '' else: self.comment = comment # timestamps self.mod_ts = mod_ts self.name = name self.hash_chain = hash_chain self.parent = parent self.extension = extension # empty hash table self.hash_table = [] self.hash_size = self.blkdev.block_longs - 56 for i in xrange(self.hash_size): self.hash_table.append(0) self.valid = True return True def write(self): Block._create_data(self) self._put_long(1, self.own_key) self._put_long(-48, self.protect) self._put_bstr(-46, 79, self.comment) self._put_timestamp(-23, self.mod_ts) self._put_bstr(-20, 30, self.name) self._put_long(-4, self.hash_chain) self._put_long(-3, self.parent) self._put_long(-2, self.extension) # hash table for i in xrange(self.hash_size): self._put_long(6+i, self.hash_table[i]) Block.write(self) def dump(self): Block.dump(self,"UserDir") print " own_key: %d" % (self.own_key) pf = ProtectFlags(self.protect) print " protect: 0x%x 0b%s %s" % (self.protect, pf.bin_str(), pf) print " comment: '%s'" % self.comment print " mod_ts: %s" % self.mod_ts print " name: '%s'" % self.name print " hash_chain: %d" % self.hash_chain print " parent: %d" % self.parent print " extension: %s" % self.extension
return False
conditional_block
UserDirBlock.py
import time from Block import Block from ..ProtectFlags import ProtectFlags class UserDirBlock(Block): def __init__(self, blkdev, blk_num):
def set(self, data): self._set_data(data) self._read() def read(self): self._read_data() self._read() def _read(self): Block.read(self) if not self.valid: return False # UserDir fields self.own_key = self._get_long(1) self.protect = self._get_long(-48) self.comment = self._get_bstr(-46, 79) self.mod_ts = self._get_timestamp(-23) self.name = self._get_bstr(-20, 30) self.hash_chain = self._get_long(-4) self.parent = self._get_long(-3) self.extension = self._get_long(-2) # hash table of entries self.hash_table = [] self.hash_size = self.blkdev.block_longs - 56 for i in xrange(self.hash_size): self.hash_table.append(self._get_long(6+i)) self.valid = (self.own_key == self.blk_num) return self.valid def create(self, parent, name, protect=0, comment=None, mod_ts=None, hash_chain=0, extension=0): Block.create(self) self.own_key = self.blk_num self.protect = protect if comment == None: self.comment = '' else: self.comment = comment # timestamps self.mod_ts = mod_ts self.name = name self.hash_chain = hash_chain self.parent = parent self.extension = extension # empty hash table self.hash_table = [] self.hash_size = self.blkdev.block_longs - 56 for i in xrange(self.hash_size): self.hash_table.append(0) self.valid = True return True def write(self): Block._create_data(self) self._put_long(1, self.own_key) self._put_long(-48, self.protect) self._put_bstr(-46, 79, self.comment) self._put_timestamp(-23, self.mod_ts) self._put_bstr(-20, 30, self.name) self._put_long(-4, self.hash_chain) self._put_long(-3, self.parent) self._put_long(-2, self.extension) # hash table for i in xrange(self.hash_size): self._put_long(6+i, self.hash_table[i]) Block.write(self) def dump(self): Block.dump(self,"UserDir") print " own_key: %d" % (self.own_key) pf = ProtectFlags(self.protect) print " protect: 0x%x 0b%s %s" % (self.protect, pf.bin_str(), pf) print " comment: '%s'" % self.comment print " mod_ts: %s" % self.mod_ts print " name: '%s'" % self.name print " hash_chain: %d" % self.hash_chain print " parent: %d" % self.parent print " extension: %s" % self.extension
Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR)
identifier_body
UserDirBlock.py
import time from Block import Block from ..ProtectFlags import ProtectFlags class UserDirBlock(Block): def __init__(self, blkdev, blk_num): Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR) def set(self, data): self._set_data(data) self._read() def read(self): self._read_data() self._read() def _read(self): Block.read(self) if not self.valid: return False # UserDir fields self.own_key = self._get_long(1) self.protect = self._get_long(-48) self.comment = self._get_bstr(-46, 79) self.mod_ts = self._get_timestamp(-23) self.name = self._get_bstr(-20, 30) self.hash_chain = self._get_long(-4) self.parent = self._get_long(-3) self.extension = self._get_long(-2) # hash table of entries self.hash_table = [] self.hash_size = self.blkdev.block_longs - 56 for i in xrange(self.hash_size): self.hash_table.append(self._get_long(6+i)) self.valid = (self.own_key == self.blk_num) return self.valid
self.comment = '' else: self.comment = comment # timestamps self.mod_ts = mod_ts self.name = name self.hash_chain = hash_chain self.parent = parent self.extension = extension # empty hash table self.hash_table = [] self.hash_size = self.blkdev.block_longs - 56 for i in xrange(self.hash_size): self.hash_table.append(0) self.valid = True return True def write(self): Block._create_data(self) self._put_long(1, self.own_key) self._put_long(-48, self.protect) self._put_bstr(-46, 79, self.comment) self._put_timestamp(-23, self.mod_ts) self._put_bstr(-20, 30, self.name) self._put_long(-4, self.hash_chain) self._put_long(-3, self.parent) self._put_long(-2, self.extension) # hash table for i in xrange(self.hash_size): self._put_long(6+i, self.hash_table[i]) Block.write(self) def dump(self): Block.dump(self,"UserDir") print " own_key: %d" % (self.own_key) pf = ProtectFlags(self.protect) print " protect: 0x%x 0b%s %s" % (self.protect, pf.bin_str(), pf) print " comment: '%s'" % self.comment print " mod_ts: %s" % self.mod_ts print " name: '%s'" % self.name print " hash_chain: %d" % self.hash_chain print " parent: %d" % self.parent print " extension: %s" % self.extension
def create(self, parent, name, protect=0, comment=None, mod_ts=None, hash_chain=0, extension=0): Block.create(self) self.own_key = self.blk_num self.protect = protect if comment == None:
random_line_split
UserDirBlock.py
import time from Block import Block from ..ProtectFlags import ProtectFlags class
(Block): def __init__(self, blkdev, blk_num): Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR) def set(self, data): self._set_data(data) self._read() def read(self): self._read_data() self._read() def _read(self): Block.read(self) if not self.valid: return False # UserDir fields self.own_key = self._get_long(1) self.protect = self._get_long(-48) self.comment = self._get_bstr(-46, 79) self.mod_ts = self._get_timestamp(-23) self.name = self._get_bstr(-20, 30) self.hash_chain = self._get_long(-4) self.parent = self._get_long(-3) self.extension = self._get_long(-2) # hash table of entries self.hash_table = [] self.hash_size = self.blkdev.block_longs - 56 for i in xrange(self.hash_size): self.hash_table.append(self._get_long(6+i)) self.valid = (self.own_key == self.blk_num) return self.valid def create(self, parent, name, protect=0, comment=None, mod_ts=None, hash_chain=0, extension=0): Block.create(self) self.own_key = self.blk_num self.protect = protect if comment == None: self.comment = '' else: self.comment = comment # timestamps self.mod_ts = mod_ts self.name = name self.hash_chain = hash_chain self.parent = parent self.extension = extension # empty hash table self.hash_table = [] self.hash_size = self.blkdev.block_longs - 56 for i in xrange(self.hash_size): self.hash_table.append(0) self.valid = True return True def write(self): Block._create_data(self) self._put_long(1, self.own_key) self._put_long(-48, self.protect) self._put_bstr(-46, 79, self.comment) self._put_timestamp(-23, self.mod_ts) self._put_bstr(-20, 30, self.name) self._put_long(-4, self.hash_chain) self._put_long(-3, self.parent) self._put_long(-2, self.extension) # hash table for i in xrange(self.hash_size): self._put_long(6+i, self.hash_table[i]) Block.write(self) def dump(self): Block.dump(self,"UserDir") print " own_key: %d" % (self.own_key) pf = ProtectFlags(self.protect) print " protect: 0x%x 0b%s %s" % (self.protect, pf.bin_str(), pf) print " comment: '%s'" % self.comment print " mod_ts: %s" % self.mod_ts print " name: '%s'" % self.name print " hash_chain: %d" % self.hash_chain print " parent: %d" % self.parent print " extension: %s" % self.extension
UserDirBlock
identifier_name
twilio.js
var twilio = require('twilio');
// REST client will handle authentication and response serialzation for you. client.sms.messages.create({ to:'+19162218736', from:'+12097819195', body:'Testing text message capabilities for app!' }, function(error, message) { // The HTTP request to Twilio will run asynchronously. This callback // function will be called when a response is received from Twilio // The "error" variable will contain error information, if any. // If the request was successful, this value will be "false" if (!error) { // The second argument to the callback will contain the information // sent back by Twilio for the request. In this case, it is the // information about the text messsage you just sent: console.log('Success! The SID for this SMS message is:'); console.log(message.sid); console.log('Message sent on:'); console.log(message.dateCreated); } else { console.log('Oops! There was an error.'); } });
var accountSid = 'ACd07fa19be220015c1f623bc38c1785e7'; var authToken = '78b4e06ced50c8cc150dbccbf0880ab9'; var client = new twilio.RestClient(accountSid, authToken); // Pass in parameters to the REST API using an object literal notation. The
random_line_split
twilio.js
var twilio = require('twilio'); var accountSid = 'ACd07fa19be220015c1f623bc38c1785e7'; var authToken = '78b4e06ced50c8cc150dbccbf0880ab9'; var client = new twilio.RestClient(accountSid, authToken); // Pass in parameters to the REST API using an object literal notation. The // REST client will handle authentication and response serialzation for you. client.sms.messages.create({ to:'+19162218736', from:'+12097819195', body:'Testing text message capabilities for app!' }, function(error, message) { // The HTTP request to Twilio will run asynchronously. This callback // function will be called when a response is received from Twilio // The "error" variable will contain error information, if any. // If the request was successful, this value will be "false" if (!error) { // The second argument to the callback will contain the information // sent back by Twilio for the request. In this case, it is the // information about the text messsage you just sent: console.log('Success! The SID for this SMS message is:'); console.log(message.sid); console.log('Message sent on:'); console.log(message.dateCreated); } else
});
{ console.log('Oops! There was an error.'); }
conditional_block
brunch-config.js
exports.config = { // See http://brunch.io/#documentation for docs. files: { javascripts: { joinTo: "js/app.js" // To use a separate vendor.js bundle, specify two files path // https://github.com/brunch/brunch/blob/master/docs/config.md#files // joinTo: { // "js/app.js": /^(js)/, // "js/vendor.js": /^(vendor)|(deps)/ // } // // To change the order of concatenation of files, explicitly mention here // https://github.com/brunch/brunch/tree/master/docs#concatenation // order: { // before: [ // "vendor/js/jquery-2.1.1.js", // "vendor/js/bootstrap.min.js" // ] // } }, stylesheets: { joinTo: "css/app.css" } }, conventions: { // This option sets where we should place non-css and non-js assets in. // By default, we set this to "/assets/static". Files in this directory // will be copied to `paths.public`, which is set below to "../public". assets: /^(static)/, // Don't scan for js files inside elm-stuff folders ignored: [/elm-stuff/] }, // paths configuration paths: { // Dependencies and current project directories to watch watched: ["static", "scss", "js", "vendor", "elm"], // Where to compile files to public: "../public"
// Do not use ES6 compiler in vendor code ignore: [/vendor/, /node_modules/] }, elmBrunch: { elmFolder: "elm", mainModules: ["Main.elm"], makeParameters: ["--warn", "--debug"], outputFolder: "../js" }, sass: { options: { includePaths: ["node_modules/bootstrap/scss"], precision: 8 } } }, modules: { autoRequire: { "js/app.js": ["js/app"] } } }; exports.npm = { globals: { $: 'jquery', jQuery: 'jquery', Popper: 'popper.js', } }
}, // Configure your plugins plugins: { babel: {
random_line_split
minimum_window_substring.rs
use std::collections::hash_map::Entry::Occupied; use std::collections::HashMap; struct Solution {} impl Solution { pub fn min_window(&self, s: String, t: String) -> String { if s.len() < t.len() { return String::from(""); } let target_hm = t.chars().fold(HashMap::new(), |mut acc, c| { *acc.entry(c).or_insert(0) += 1; acc }); let s_vec: Vec<char> = s.chars().collect(); let filtered_s: Vec<(usize, char)> = s .chars() .enumerate() .collect::<Vec<(usize, char)>>() .into_iter() .filter(|(_, c)| target_hm.get(c).is_some()) .collect(); let mut min_window_chars: Option<(usize, usize)> = None; let mut curr_hm: HashMap<char, u32> = HashMap::new(); let mut l_idx = 0 as usize; let mut r_idx = 0 as usize; while r_idx < filtered_s.len() { let curr_char = filtered_s[r_idx]; *curr_hm.entry(curr_char.1).or_insert(0) += 1; // we move the l_idx til we still have a complete set of letters with occurences while hm_is_valid(&target_hm, &curr_hm) && l_idx <= r_idx { // if we don't have a window yet, or the length of the curr window is too small match min_window_chars { None => { min_window_chars = Some((filtered_s[l_idx].0, filtered_s[r_idx].0)); } Some(mwc) => { if (mwc.1 - mwc.0) > (filtered_s[r_idx].0 - filtered_s[l_idx].0) { min_window_chars = Some((filtered_s[l_idx].0, filtered_s[r_idx].0)); } } } match curr_hm.entry(filtered_s[l_idx].1) { Occupied(mut e) => { let v = e.get_mut(); if v > &mut 1 { *v -= 1; } else { e.remove(); } } _ => panic!("char vec curr_hm filled the wrong way"), }; // dbg!( // &l_idx, // &s_vec[filtered_s[l_idx].0..=filtered_s[r_idx].0] // .to_vec() // .iter() // .collect::<String>(), // &curr_hm, // ); l_idx += 1; } r_idx += 1; } match min_window_chars { None => String::from(""), Some(mwc) => s_vec[mwc.0..=mwc.1].to_vec().iter().collect(), } } } pub fn hm_is_valid(target_hm: &HashMap<char, u32>, test_hm: &HashMap<char, u32>) -> bool { if target_hm == test_hm { return true; } for (c, count) in target_hm.iter() { match test_hm.get(c) { None => return false, Some(test_count) if test_count < count => return false, _ => (), } } true }
#[test] fn solution() { let sol = Solution {}; assert_eq!( sol.min_window(String::from("ADOBECODEBANC"), String::from("ABC")), "BANC" ); assert_eq!(sol.min_window(String::from(""), String::from("ABC")), ""); assert_eq!(sol.min_window(String::from("RTY"), String::from("ABC")), ""); assert_eq!( sol.min_window(String::from("AAAAAAAAA"), String::from("A")), "A" ); assert_eq!(sol.min_window(String::from("a"), String::from("aa")), ""); assert_eq!(sol.min_window(String::from("aa"), String::from("aa")), "aa"); assert_eq!( sol.min_window(String::from("bba"), String::from("ab")), "ba" ); } }
#[cfg(test)] mod tests { use super::Solution;
random_line_split
minimum_window_substring.rs
use std::collections::hash_map::Entry::Occupied; use std::collections::HashMap; struct Solution {} impl Solution { pub fn min_window(&self, s: String, t: String) -> String
} pub fn hm_is_valid(target_hm: &HashMap<char, u32>, test_hm: &HashMap<char, u32>) -> bool { if target_hm == test_hm { return true; } for (c, count) in target_hm.iter() { match test_hm.get(c) { None => return false, Some(test_count) if test_count < count => return false, _ => (), } } true } #[cfg(test)] mod tests { use super::Solution; #[test] fn solution() { let sol = Solution {}; assert_eq!( sol.min_window(String::from("ADOBECODEBANC"), String::from("ABC")), "BANC" ); assert_eq!(sol.min_window(String::from(""), String::from("ABC")), ""); assert_eq!(sol.min_window(String::from("RTY"), String::from("ABC")), ""); assert_eq!( sol.min_window(String::from("AAAAAAAAA"), String::from("A")), "A" ); assert_eq!(sol.min_window(String::from("a"), String::from("aa")), ""); assert_eq!(sol.min_window(String::from("aa"), String::from("aa")), "aa"); assert_eq!( sol.min_window(String::from("bba"), String::from("ab")), "ba" ); } }
{ if s.len() < t.len() { return String::from(""); } let target_hm = t.chars().fold(HashMap::new(), |mut acc, c| { *acc.entry(c).or_insert(0) += 1; acc }); let s_vec: Vec<char> = s.chars().collect(); let filtered_s: Vec<(usize, char)> = s .chars() .enumerate() .collect::<Vec<(usize, char)>>() .into_iter() .filter(|(_, c)| target_hm.get(c).is_some()) .collect(); let mut min_window_chars: Option<(usize, usize)> = None; let mut curr_hm: HashMap<char, u32> = HashMap::new(); let mut l_idx = 0 as usize; let mut r_idx = 0 as usize; while r_idx < filtered_s.len() { let curr_char = filtered_s[r_idx]; *curr_hm.entry(curr_char.1).or_insert(0) += 1; // we move the l_idx til we still have a complete set of letters with occurences while hm_is_valid(&target_hm, &curr_hm) && l_idx <= r_idx { // if we don't have a window yet, or the length of the curr window is too small match min_window_chars { None => { min_window_chars = Some((filtered_s[l_idx].0, filtered_s[r_idx].0)); } Some(mwc) => { if (mwc.1 - mwc.0) > (filtered_s[r_idx].0 - filtered_s[l_idx].0) { min_window_chars = Some((filtered_s[l_idx].0, filtered_s[r_idx].0)); } } } match curr_hm.entry(filtered_s[l_idx].1) { Occupied(mut e) => { let v = e.get_mut(); if v > &mut 1 { *v -= 1; } else { e.remove(); } } _ => panic!("char vec curr_hm filled the wrong way"), }; // dbg!( // &l_idx, // &s_vec[filtered_s[l_idx].0..=filtered_s[r_idx].0] // .to_vec() // .iter() // .collect::<String>(), // &curr_hm, // ); l_idx += 1; } r_idx += 1; } match min_window_chars { None => String::from(""), Some(mwc) => s_vec[mwc.0..=mwc.1].to_vec().iter().collect(), } }
identifier_body
minimum_window_substring.rs
use std::collections::hash_map::Entry::Occupied; use std::collections::HashMap; struct Solution {} impl Solution { pub fn min_window(&self, s: String, t: String) -> String { if s.len() < t.len() { return String::from(""); } let target_hm = t.chars().fold(HashMap::new(), |mut acc, c| { *acc.entry(c).or_insert(0) += 1; acc }); let s_vec: Vec<char> = s.chars().collect(); let filtered_s: Vec<(usize, char)> = s .chars() .enumerate() .collect::<Vec<(usize, char)>>() .into_iter() .filter(|(_, c)| target_hm.get(c).is_some()) .collect(); let mut min_window_chars: Option<(usize, usize)> = None; let mut curr_hm: HashMap<char, u32> = HashMap::new(); let mut l_idx = 0 as usize; let mut r_idx = 0 as usize; while r_idx < filtered_s.len() { let curr_char = filtered_s[r_idx]; *curr_hm.entry(curr_char.1).or_insert(0) += 1; // we move the l_idx til we still have a complete set of letters with occurences while hm_is_valid(&target_hm, &curr_hm) && l_idx <= r_idx { // if we don't have a window yet, or the length of the curr window is too small match min_window_chars { None => { min_window_chars = Some((filtered_s[l_idx].0, filtered_s[r_idx].0)); } Some(mwc) => { if (mwc.1 - mwc.0) > (filtered_s[r_idx].0 - filtered_s[l_idx].0) { min_window_chars = Some((filtered_s[l_idx].0, filtered_s[r_idx].0)); } } } match curr_hm.entry(filtered_s[l_idx].1) { Occupied(mut e) => { let v = e.get_mut(); if v > &mut 1 { *v -= 1; } else { e.remove(); } } _ => panic!("char vec curr_hm filled the wrong way"), }; // dbg!( // &l_idx, // &s_vec[filtered_s[l_idx].0..=filtered_s[r_idx].0] // .to_vec() // .iter() // .collect::<String>(), // &curr_hm, // ); l_idx += 1; } r_idx += 1; } match min_window_chars { None => String::from(""), Some(mwc) => s_vec[mwc.0..=mwc.1].to_vec().iter().collect(), } } } pub fn hm_is_valid(target_hm: &HashMap<char, u32>, test_hm: &HashMap<char, u32>) -> bool { if target_hm == test_hm { return true; } for (c, count) in target_hm.iter() { match test_hm.get(c) { None => return false, Some(test_count) if test_count < count => return false, _ => (), } } true } #[cfg(test)] mod tests { use super::Solution; #[test] fn
() { let sol = Solution {}; assert_eq!( sol.min_window(String::from("ADOBECODEBANC"), String::from("ABC")), "BANC" ); assert_eq!(sol.min_window(String::from(""), String::from("ABC")), ""); assert_eq!(sol.min_window(String::from("RTY"), String::from("ABC")), ""); assert_eq!( sol.min_window(String::from("AAAAAAAAA"), String::from("A")), "A" ); assert_eq!(sol.min_window(String::from("a"), String::from("aa")), ""); assert_eq!(sol.min_window(String::from("aa"), String::from("aa")), "aa"); assert_eq!( sol.min_window(String::from("bba"), String::from("ab")), "ba" ); } }
solution
identifier_name
slide-to-accept.ts
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, Renderer, ViewChild } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @Component({ selector: 'page-slide-to-accept', templateUrl: 'slide-to-accept.html', }) export class SlideToAcceptPage implements AfterViewInit { @Output() slideDone = new EventEmitter<boolean>(); @Input() buttonText: string; @Input() set disabled(disabled: boolean) { this.isDisabled = (disabled !== undefined) ? disabled : false; }; get disabled() { return this.isDisabled; } @Input() set slideButtonDone(done: boolean) { this.done = (done !== undefined) ? done : false; }; get slideButtonDone() { return this.done; } @ViewChild('slideButton', { read: ElementRef }) private buttonElement: ElementRef; @ViewChild('slideButtonContainer') private containerElement: ElementRef; private isPressed: boolean = false; private clickPosition: any; private xMax: number; private delta: number = 8; private htmlButtonElem; private htmlContainerElem; private isConfirm: boolean = false; private containerWidth: number; private origin; private callbackDone: boolean = false; private done: boolean = false; private isDisabled: boolean = false; public animation: boolean; constructor(public navCtrl: NavController, public navParams: NavParams, public renderer: Renderer) { this.animation = false; } ngAfterViewInit() { setTimeout(() => { this.htmlButtonElem = this.buttonElement.nativeElement; this.htmlContainerElem = this.containerElement.nativeElement; let buttonConstraints = this.htmlButtonElem.getBoundingClientRect(); let containerConstraints = this.htmlContainerElem.getBoundingClientRect(); this.origin = { left: buttonConstraints.left, top: buttonConstraints.top, width: buttonConstraints.width }; this.containerWidth = this.htmlContainerElem.clientWidth; const subtract = this.containerWidth < 800 ? 75 : 200; this.xMax = this.containerWidth - subtract; }, 0); } activateButton(event: TouchEvent) { this.isPressed = true; if (typeof event.touches != "undefined") { this.clickPosition = event.touches[0].pageX; } } dragButton(event: TouchEvent) { if (typeof event.touches != "undefined") { let xTranslate = event.touches[0].pageX; let xDisplacement = (this.isPressed) ? xTranslate - this.clickPosition : 0; // Adjust displacement to consider the delta value xDisplacement -= this.delta; // Use resource inexpensive translation to perform the sliding let posCss = { "transform": "translateX(" + xDisplacement + "px)", "-webkit-transform": "translateX(" + xDisplacement + "px)" }; // Move the element while the drag position is less than xMax // -delta/2 is a necessary adjustment if (xDisplacement >= 0 && xDisplacement < this.containerWidth - this.origin.width * 15 / 100 + 30 && this.isPressed) { // Set element styles this.renderer.setElementStyle(this.htmlButtonElem, 'transform', posCss['transform']); this.renderer.setElementStyle(this.htmlButtonElem, '-webkit-transform', posCss['-webkit-transform']); } // If the max displacement position is reached this.slideButtonDone = xDisplacement >= this.xMax - this.delta / 2 ? true : false; } } resetButton() { // Only reset if button sliding is not done yet if (!this.slideButtonDone || this.isDisabled) { this.isConfirm = false; // Reset state variables // Resets button position let posCss = { "transform": "translateX(0px)", "-webkit-transform": "translateX(0px)" }; this.renderer.setElementStyle( this.htmlButtonElem, 'transform', posCss['transform']); this.renderer.setElementStyle( this.htmlButtonElem, '-webkit-transform', posCss['-webkit-transform']); this.ngAfterViewInit(); } else if (this.slideButtonDone && !this.isDisabled) { this.isConfirm = true; this.slideButtonDone = false; this.slideDone.emit(true); } } isConfirmed(boolean)
public toggleAnimation(): void { if (this.isDisabled) return; this.animation = true; setTimeout(() => { this.animation = false; }, 300); } }
{ if (!boolean) { this.resetButton(); } }
identifier_body
slide-to-accept.ts
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, Renderer, ViewChild } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @Component({ selector: 'page-slide-to-accept', templateUrl: 'slide-to-accept.html', }) export class SlideToAcceptPage implements AfterViewInit { @Output() slideDone = new EventEmitter<boolean>(); @Input() buttonText: string; @Input() set disabled(disabled: boolean) { this.isDisabled = (disabled !== undefined) ? disabled : false; }; get disabled() { return this.isDisabled; } @Input() set slideButtonDone(done: boolean) { this.done = (done !== undefined) ? done : false; }; get slideButtonDone() { return this.done; } @ViewChild('slideButton', { read: ElementRef }) private buttonElement: ElementRef; @ViewChild('slideButtonContainer') private containerElement: ElementRef; private isPressed: boolean = false; private clickPosition: any; private xMax: number; private delta: number = 8; private htmlButtonElem; private htmlContainerElem; private isConfirm: boolean = false; private containerWidth: number; private origin; private callbackDone: boolean = false; private done: boolean = false; private isDisabled: boolean = false; public animation: boolean; constructor(public navCtrl: NavController, public navParams: NavParams, public renderer: Renderer) { this.animation = false; } ngAfterViewInit() { setTimeout(() => { this.htmlButtonElem = this.buttonElement.nativeElement; this.htmlContainerElem = this.containerElement.nativeElement; let buttonConstraints = this.htmlButtonElem.getBoundingClientRect(); let containerConstraints = this.htmlContainerElem.getBoundingClientRect(); this.origin = { left: buttonConstraints.left, top: buttonConstraints.top, width: buttonConstraints.width }; this.containerWidth = this.htmlContainerElem.clientWidth; const subtract = this.containerWidth < 800 ? 75 : 200; this.xMax = this.containerWidth - subtract; }, 0); } activateButton(event: TouchEvent) { this.isPressed = true; if (typeof event.touches != "undefined") { this.clickPosition = event.touches[0].pageX; } } dragButton(event: TouchEvent) { if (typeof event.touches != "undefined") { let xTranslate = event.touches[0].pageX; let xDisplacement = (this.isPressed) ? xTranslate - this.clickPosition : 0; // Adjust displacement to consider the delta value xDisplacement -= this.delta; // Use resource inexpensive translation to perform the sliding let posCss = { "transform": "translateX(" + xDisplacement + "px)", "-webkit-transform": "translateX(" + xDisplacement + "px)" }; // Move the element while the drag position is less than xMax // -delta/2 is a necessary adjustment if (xDisplacement >= 0 && xDisplacement < this.containerWidth - this.origin.width * 15 / 100 + 30 && this.isPressed) { // Set element styles this.renderer.setElementStyle(this.htmlButtonElem, 'transform', posCss['transform']); this.renderer.setElementStyle(this.htmlButtonElem, '-webkit-transform', posCss['-webkit-transform']); } // If the max displacement position is reached this.slideButtonDone = xDisplacement >= this.xMax - this.delta / 2 ? true : false; } } resetButton() {
this.isConfirm = false; // Reset state variables // Resets button position let posCss = { "transform": "translateX(0px)", "-webkit-transform": "translateX(0px)" }; this.renderer.setElementStyle( this.htmlButtonElem, 'transform', posCss['transform']); this.renderer.setElementStyle( this.htmlButtonElem, '-webkit-transform', posCss['-webkit-transform']); this.ngAfterViewInit(); } else if (this.slideButtonDone && !this.isDisabled) { this.isConfirm = true; this.slideButtonDone = false; this.slideDone.emit(true); } } isConfirmed(boolean) { if (!boolean) { this.resetButton(); } } public toggleAnimation(): void { if (this.isDisabled) return; this.animation = true; setTimeout(() => { this.animation = false; }, 300); } }
// Only reset if button sliding is not done yet if (!this.slideButtonDone || this.isDisabled) {
random_line_split
slide-to-accept.ts
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, Renderer, ViewChild } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @Component({ selector: 'page-slide-to-accept', templateUrl: 'slide-to-accept.html', }) export class SlideToAcceptPage implements AfterViewInit { @Output() slideDone = new EventEmitter<boolean>(); @Input() buttonText: string; @Input() set disabled(disabled: boolean) { this.isDisabled = (disabled !== undefined) ? disabled : false; }; get disabled() { return this.isDisabled; } @Input() set slideButtonDone(done: boolean) { this.done = (done !== undefined) ? done : false; }; get slideButtonDone() { return this.done; } @ViewChild('slideButton', { read: ElementRef }) private buttonElement: ElementRef; @ViewChild('slideButtonContainer') private containerElement: ElementRef; private isPressed: boolean = false; private clickPosition: any; private xMax: number; private delta: number = 8; private htmlButtonElem; private htmlContainerElem; private isConfirm: boolean = false; private containerWidth: number; private origin; private callbackDone: boolean = false; private done: boolean = false; private isDisabled: boolean = false; public animation: boolean; constructor(public navCtrl: NavController, public navParams: NavParams, public renderer: Renderer) { this.animation = false; } ngAfterViewInit() { setTimeout(() => { this.htmlButtonElem = this.buttonElement.nativeElement; this.htmlContainerElem = this.containerElement.nativeElement; let buttonConstraints = this.htmlButtonElem.getBoundingClientRect(); let containerConstraints = this.htmlContainerElem.getBoundingClientRect(); this.origin = { left: buttonConstraints.left, top: buttonConstraints.top, width: buttonConstraints.width }; this.containerWidth = this.htmlContainerElem.clientWidth; const subtract = this.containerWidth < 800 ? 75 : 200; this.xMax = this.containerWidth - subtract; }, 0); } activateButton(event: TouchEvent) { this.isPressed = true; if (typeof event.touches != "undefined") { this.clickPosition = event.touches[0].pageX; } } dragButton(event: TouchEvent) { if (typeof event.touches != "undefined") { let xTranslate = event.touches[0].pageX; let xDisplacement = (this.isPressed) ? xTranslate - this.clickPosition : 0; // Adjust displacement to consider the delta value xDisplacement -= this.delta; // Use resource inexpensive translation to perform the sliding let posCss = { "transform": "translateX(" + xDisplacement + "px)", "-webkit-transform": "translateX(" + xDisplacement + "px)" }; // Move the element while the drag position is less than xMax // -delta/2 is a necessary adjustment if (xDisplacement >= 0 && xDisplacement < this.containerWidth - this.origin.width * 15 / 100 + 30 && this.isPressed) { // Set element styles this.renderer.setElementStyle(this.htmlButtonElem, 'transform', posCss['transform']); this.renderer.setElementStyle(this.htmlButtonElem, '-webkit-transform', posCss['-webkit-transform']); } // If the max displacement position is reached this.slideButtonDone = xDisplacement >= this.xMax - this.delta / 2 ? true : false; } } resetButton() { // Only reset if button sliding is not done yet if (!this.slideButtonDone || this.isDisabled) { this.isConfirm = false; // Reset state variables // Resets button position let posCss = { "transform": "translateX(0px)", "-webkit-transform": "translateX(0px)" }; this.renderer.setElementStyle( this.htmlButtonElem, 'transform', posCss['transform']); this.renderer.setElementStyle( this.htmlButtonElem, '-webkit-transform', posCss['-webkit-transform']); this.ngAfterViewInit(); } else if (this.slideButtonDone && !this.isDisabled)
} isConfirmed(boolean) { if (!boolean) { this.resetButton(); } } public toggleAnimation(): void { if (this.isDisabled) return; this.animation = true; setTimeout(() => { this.animation = false; }, 300); } }
{ this.isConfirm = true; this.slideButtonDone = false; this.slideDone.emit(true); }
conditional_block
slide-to-accept.ts
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, Renderer, ViewChild } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @Component({ selector: 'page-slide-to-accept', templateUrl: 'slide-to-accept.html', }) export class
implements AfterViewInit { @Output() slideDone = new EventEmitter<boolean>(); @Input() buttonText: string; @Input() set disabled(disabled: boolean) { this.isDisabled = (disabled !== undefined) ? disabled : false; }; get disabled() { return this.isDisabled; } @Input() set slideButtonDone(done: boolean) { this.done = (done !== undefined) ? done : false; }; get slideButtonDone() { return this.done; } @ViewChild('slideButton', { read: ElementRef }) private buttonElement: ElementRef; @ViewChild('slideButtonContainer') private containerElement: ElementRef; private isPressed: boolean = false; private clickPosition: any; private xMax: number; private delta: number = 8; private htmlButtonElem; private htmlContainerElem; private isConfirm: boolean = false; private containerWidth: number; private origin; private callbackDone: boolean = false; private done: boolean = false; private isDisabled: boolean = false; public animation: boolean; constructor(public navCtrl: NavController, public navParams: NavParams, public renderer: Renderer) { this.animation = false; } ngAfterViewInit() { setTimeout(() => { this.htmlButtonElem = this.buttonElement.nativeElement; this.htmlContainerElem = this.containerElement.nativeElement; let buttonConstraints = this.htmlButtonElem.getBoundingClientRect(); let containerConstraints = this.htmlContainerElem.getBoundingClientRect(); this.origin = { left: buttonConstraints.left, top: buttonConstraints.top, width: buttonConstraints.width }; this.containerWidth = this.htmlContainerElem.clientWidth; const subtract = this.containerWidth < 800 ? 75 : 200; this.xMax = this.containerWidth - subtract; }, 0); } activateButton(event: TouchEvent) { this.isPressed = true; if (typeof event.touches != "undefined") { this.clickPosition = event.touches[0].pageX; } } dragButton(event: TouchEvent) { if (typeof event.touches != "undefined") { let xTranslate = event.touches[0].pageX; let xDisplacement = (this.isPressed) ? xTranslate - this.clickPosition : 0; // Adjust displacement to consider the delta value xDisplacement -= this.delta; // Use resource inexpensive translation to perform the sliding let posCss = { "transform": "translateX(" + xDisplacement + "px)", "-webkit-transform": "translateX(" + xDisplacement + "px)" }; // Move the element while the drag position is less than xMax // -delta/2 is a necessary adjustment if (xDisplacement >= 0 && xDisplacement < this.containerWidth - this.origin.width * 15 / 100 + 30 && this.isPressed) { // Set element styles this.renderer.setElementStyle(this.htmlButtonElem, 'transform', posCss['transform']); this.renderer.setElementStyle(this.htmlButtonElem, '-webkit-transform', posCss['-webkit-transform']); } // If the max displacement position is reached this.slideButtonDone = xDisplacement >= this.xMax - this.delta / 2 ? true : false; } } resetButton() { // Only reset if button sliding is not done yet if (!this.slideButtonDone || this.isDisabled) { this.isConfirm = false; // Reset state variables // Resets button position let posCss = { "transform": "translateX(0px)", "-webkit-transform": "translateX(0px)" }; this.renderer.setElementStyle( this.htmlButtonElem, 'transform', posCss['transform']); this.renderer.setElementStyle( this.htmlButtonElem, '-webkit-transform', posCss['-webkit-transform']); this.ngAfterViewInit(); } else if (this.slideButtonDone && !this.isDisabled) { this.isConfirm = true; this.slideButtonDone = false; this.slideDone.emit(true); } } isConfirmed(boolean) { if (!boolean) { this.resetButton(); } } public toggleAnimation(): void { if (this.isDisabled) return; this.animation = true; setTimeout(() => { this.animation = false; }, 300); } }
SlideToAcceptPage
identifier_name
small-enum-range-edge.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. /*! * Tests the range assertion wraparound case in trans::middle::adt::load_discr. */ #[repr(u8)] #[derive(Copy)] enum
{ Lu = 0, Hu = 255 } static CLu: Eu = Eu::Lu; static CHu: Eu = Eu::Hu; #[repr(i8)] #[derive(Copy)] enum Es { Ls = -128, Hs = 127 } static CLs: Es = Es::Ls; static CHs: Es = Es::Hs; pub fn main() { assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8); assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8); assert_eq!(CLu as u8, Eu::Lu as u8); assert_eq!(CHu as u8, Eu::Hu as u8); assert_eq!(CLs as i8, Es::Ls as i8); assert_eq!(CHs as i8, Es::Hs as i8); }
Eu
identifier_name
small-enum-range-edge.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. /*! * Tests the range assertion wraparound case in trans::middle::adt::load_discr. */ #[repr(u8)] #[derive(Copy)] enum Eu { Lu = 0, Hu = 255 } static CLu: Eu = Eu::Lu; static CHu: Eu = Eu::Hu; #[repr(i8)] #[derive(Copy)] enum Es { Ls = -128, Hs = 127 } static CLs: Es = Es::Ls; static CHs: Es = Es::Hs; pub fn main()
{ assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8); assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8); assert_eq!(CLu as u8, Eu::Lu as u8); assert_eq!(CHu as u8, Eu::Hu as u8); assert_eq!(CLs as i8, Es::Ls as i8); assert_eq!(CHs as i8, Es::Hs as i8); }
identifier_body
small-enum-range-edge.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. /*! * Tests the range assertion wraparound case in trans::middle::adt::load_discr.
#[repr(u8)] #[derive(Copy)] enum Eu { Lu = 0, Hu = 255 } static CLu: Eu = Eu::Lu; static CHu: Eu = Eu::Hu; #[repr(i8)] #[derive(Copy)] enum Es { Ls = -128, Hs = 127 } static CLs: Es = Es::Ls; static CHs: Es = Es::Hs; pub fn main() { assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8); assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8); assert_eq!(CLu as u8, Eu::Lu as u8); assert_eq!(CHu as u8, Eu::Hu as u8); assert_eq!(CLs as i8, Es::Ls as i8); assert_eq!(CHs as i8, Es::Hs as i8); }
*/
random_line_split
uio.rs
//! Vectored I/O use crate::Result; use crate::errno::Errno; use libc::{self, c_int, c_void, size_t, off_t}; use std::marker::PhantomData; use std::os::unix::io::RawFd; /// Low-level vectored write to a raw file descriptor /// /// See also [writev(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.html) pub fn writev(fd: RawFd, iov: &[IoVec<&[u8]>]) -> Result<usize> { let res = unsafe { libc::writev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) }; Errno::result(res).map(|r| r as usize) } /// Low-level vectored read from a raw file descriptor /// /// See also [readv(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readv.html) pub fn readv(fd: RawFd, iov: &mut [IoVec<&mut [u8]>]) -> Result<usize> { let res = unsafe { libc::readv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) }; Errno::result(res).map(|r| r as usize) } /// Write to `fd` at `offset` from buffers in `iov`. /// /// Buffers in `iov` will be written in order until all buffers have been written /// or an error occurs. The file offset is not changed. /// /// See also: [`writev`](fn.writev.html) and [`pwrite`](fn.pwrite.html) #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn pwritev(fd: RawFd, iov: &[IoVec<&[u8]>], offset: off_t) -> Result<usize> { #[cfg(target_env = "uclibc")] let offset = offset as libc::off64_t; // uclibc doesn't use off_t let res = unsafe { libc::pwritev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset) }; Errno::result(res).map(|r| r as usize) } /// Read from `fd` at `offset` filling buffers in `iov`. /// /// Buffers in `iov` will be filled in order until all buffers have been filled, /// no more bytes are available, or an error occurs. The file offset is not /// changed. /// /// See also: [`readv`](fn.readv.html) and [`pread`](fn.pread.html) #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn preadv(fd: RawFd, iov: &[IoVec<&mut [u8]>], offset: off_t) -> Result<usize> { #[cfg(target_env = "uclibc")] let offset = offset as libc::off64_t; // uclibc doesn't use off_t let res = unsafe { libc::preadv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset) }; Errno::result(res).map(|r| r as usize) } /// Low-level write to a file, with specified offset. /// /// See also [pwrite(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pwrite.html) // TODO: move to unistd pub fn pwrite(fd: RawFd, buf: &[u8], offset: off_t) -> Result<usize> { let res = unsafe { libc::pwrite(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, offset) }; Errno::result(res).map(|r| r as usize) } /// Low-level read from a file, with specified offset. /// /// See also [pread(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pread.html) // TODO: move to unistd pub fn pread(fd: RawFd, buf: &mut [u8], offset: off_t) -> Result<usize>{ let res = unsafe { libc::pread(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t, offset) }; Errno::result(res).map(|r| r as usize) } /// A slice of memory in a remote process, starting at address `base` /// and consisting of `len` bytes. /// /// This is the same underlying C structure as [`IoVec`](struct.IoVec.html), /// except that it refers to memory in some other process, and is /// therefore not represented in Rust by an actual slice as `IoVec` is. It /// is used with [`process_vm_readv`](fn.process_vm_readv.html) /// and [`process_vm_writev`](fn.process_vm_writev.html). #[cfg(any(target_os = "linux", target_os = "android"))] #[cfg_attr(docsrs, doc(cfg(all())))] #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct RemoteIoVec { /// The starting address of this slice (`iov_base`). pub base: usize, /// The number of bytes in this slice (`iov_len`). pub len: usize, } feature! { #![feature = "process"] /// Write data directly to another process's virtual memory /// (see [`process_vm_writev`(2)]). /// /// `local_iov` is a list of [`IoVec`]s containing the data to be written, /// and `remote_iov` is a list of [`RemoteIoVec`]s identifying where the /// data should be written in the target process. On success, returns the /// number of bytes written, which will always be a whole /// number of `remote_iov` chunks. /// /// This requires the same permissions as debugging the process using /// [ptrace]: you must either be a privileged process (with /// `CAP_SYS_PTRACE`), or you must be running as the same user as the /// target process and the OS must have unprivileged debugging enabled. /// /// This function is only available on Linux and Android(SDK23+). /// /// [`process_vm_writev`(2)]: https://man7.org/linux/man-pages/man2/process_vm_writev.2.html /// [ptrace]: ../ptrace/index.html /// [`IoVec`]: struct.IoVec.html /// [`RemoteIoVec`]: struct.RemoteIoVec.html #[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))] pub fn process_vm_writev( pid: crate::unistd::Pid, local_iov: &[IoVec<&[u8]>], remote_iov: &[RemoteIoVec]) -> Result<usize> { let res = unsafe { libc::process_vm_writev(pid.into(), local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong, remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0) }; Errno::result(res).map(|r| r as usize) } /// Read data directly from another process's virtual memory /// (see [`process_vm_readv`(2)]). /// /// `local_iov` is a list of [`IoVec`]s containing the buffer to copy /// data into, and `remote_iov` is a list of [`RemoteIoVec`]s identifying /// where the source data is in the target process. On success, /// returns the number of bytes written, which will always be a whole /// number of `remote_iov` chunks. /// /// This requires the same permissions as debugging the process using /// [`ptrace`]: you must either be a privileged process (with /// `CAP_SYS_PTRACE`), or you must be running as the same user as the /// target process and the OS must have unprivileged debugging enabled. /// /// This function is only available on Linux and Android(SDK23+). /// /// [`process_vm_readv`(2)]: https://man7.org/linux/man-pages/man2/process_vm_readv.2.html /// [`ptrace`]: ../ptrace/index.html /// [`IoVec`]: struct.IoVec.html /// [`RemoteIoVec`]: struct.RemoteIoVec.html #[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))] pub fn process_vm_readv( pid: crate::unistd::Pid, local_iov: &[IoVec<&mut [u8]>], remote_iov: &[RemoteIoVec]) -> Result<usize> { let res = unsafe { libc::process_vm_readv(pid.into(), local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong, remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0) }; Errno::result(res).map(|r| r as usize) } } /// A vector of buffers. /// /// Vectored I/O methods like [`writev`] and [`readv`] use this structure for /// both reading and writing. Each `IoVec` specifies the base address and /// length of an area in memory. #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct IoVec<T>(pub(crate) libc::iovec, PhantomData<T>); impl<T> IoVec<T> { /// View the `IoVec` as a Rust slice. #[inline] pub fn as_slice(&self) -> &[u8] { use std::slice; unsafe { slice::from_raw_parts( self.0.iov_base as *const u8, self.0.iov_len as usize) } } } impl<'a> IoVec<&'a [u8]> { #[cfg(all(feature = "mount", target_os = "freebsd"))] pub(crate) fn from_raw_parts(base: *mut c_void, len: usize) -> Self { IoVec(libc::iovec { iov_base: base, iov_len: len }, PhantomData) } /// Create an `IoVec` from a Rust slice. pub fn from_slice(buf: &'a [u8]) -> IoVec<&'a [u8]> { IoVec(libc::iovec {
}, PhantomData) } } impl<'a> IoVec<&'a mut [u8]> { /// Create an `IoVec` from a mutable Rust slice. pub fn from_mut_slice(buf: &'a mut [u8]) -> IoVec<&'a mut [u8]> { IoVec(libc::iovec { iov_base: buf.as_ptr() as *mut c_void, iov_len: buf.len() as size_t, }, PhantomData) } } // The only reason IoVec isn't automatically Send+Sync is because libc::iovec // contains raw pointers. unsafe impl<T> Send for IoVec<T> where T: Send {} unsafe impl<T> Sync for IoVec<T> where T: Sync {}
iov_base: buf.as_ptr() as *mut c_void, iov_len: buf.len() as size_t,
random_line_split
uio.rs
//! Vectored I/O use crate::Result; use crate::errno::Errno; use libc::{self, c_int, c_void, size_t, off_t}; use std::marker::PhantomData; use std::os::unix::io::RawFd; /// Low-level vectored write to a raw file descriptor /// /// See also [writev(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.html) pub fn writev(fd: RawFd, iov: &[IoVec<&[u8]>]) -> Result<usize> { let res = unsafe { libc::writev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) }; Errno::result(res).map(|r| r as usize) } /// Low-level vectored read from a raw file descriptor /// /// See also [readv(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readv.html) pub fn readv(fd: RawFd, iov: &mut [IoVec<&mut [u8]>]) -> Result<usize> { let res = unsafe { libc::readv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) }; Errno::result(res).map(|r| r as usize) } /// Write to `fd` at `offset` from buffers in `iov`. /// /// Buffers in `iov` will be written in order until all buffers have been written /// or an error occurs. The file offset is not changed. /// /// See also: [`writev`](fn.writev.html) and [`pwrite`](fn.pwrite.html) #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn
(fd: RawFd, iov: &[IoVec<&[u8]>], offset: off_t) -> Result<usize> { #[cfg(target_env = "uclibc")] let offset = offset as libc::off64_t; // uclibc doesn't use off_t let res = unsafe { libc::pwritev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset) }; Errno::result(res).map(|r| r as usize) } /// Read from `fd` at `offset` filling buffers in `iov`. /// /// Buffers in `iov` will be filled in order until all buffers have been filled, /// no more bytes are available, or an error occurs. The file offset is not /// changed. /// /// See also: [`readv`](fn.readv.html) and [`pread`](fn.pread.html) #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn preadv(fd: RawFd, iov: &[IoVec<&mut [u8]>], offset: off_t) -> Result<usize> { #[cfg(target_env = "uclibc")] let offset = offset as libc::off64_t; // uclibc doesn't use off_t let res = unsafe { libc::preadv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset) }; Errno::result(res).map(|r| r as usize) } /// Low-level write to a file, with specified offset. /// /// See also [pwrite(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pwrite.html) // TODO: move to unistd pub fn pwrite(fd: RawFd, buf: &[u8], offset: off_t) -> Result<usize> { let res = unsafe { libc::pwrite(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, offset) }; Errno::result(res).map(|r| r as usize) } /// Low-level read from a file, with specified offset. /// /// See also [pread(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pread.html) // TODO: move to unistd pub fn pread(fd: RawFd, buf: &mut [u8], offset: off_t) -> Result<usize>{ let res = unsafe { libc::pread(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t, offset) }; Errno::result(res).map(|r| r as usize) } /// A slice of memory in a remote process, starting at address `base` /// and consisting of `len` bytes. /// /// This is the same underlying C structure as [`IoVec`](struct.IoVec.html), /// except that it refers to memory in some other process, and is /// therefore not represented in Rust by an actual slice as `IoVec` is. It /// is used with [`process_vm_readv`](fn.process_vm_readv.html) /// and [`process_vm_writev`](fn.process_vm_writev.html). #[cfg(any(target_os = "linux", target_os = "android"))] #[cfg_attr(docsrs, doc(cfg(all())))] #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct RemoteIoVec { /// The starting address of this slice (`iov_base`). pub base: usize, /// The number of bytes in this slice (`iov_len`). pub len: usize, } feature! { #![feature = "process"] /// Write data directly to another process's virtual memory /// (see [`process_vm_writev`(2)]). /// /// `local_iov` is a list of [`IoVec`]s containing the data to be written, /// and `remote_iov` is a list of [`RemoteIoVec`]s identifying where the /// data should be written in the target process. On success, returns the /// number of bytes written, which will always be a whole /// number of `remote_iov` chunks. /// /// This requires the same permissions as debugging the process using /// [ptrace]: you must either be a privileged process (with /// `CAP_SYS_PTRACE`), or you must be running as the same user as the /// target process and the OS must have unprivileged debugging enabled. /// /// This function is only available on Linux and Android(SDK23+). /// /// [`process_vm_writev`(2)]: https://man7.org/linux/man-pages/man2/process_vm_writev.2.html /// [ptrace]: ../ptrace/index.html /// [`IoVec`]: struct.IoVec.html /// [`RemoteIoVec`]: struct.RemoteIoVec.html #[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))] pub fn process_vm_writev( pid: crate::unistd::Pid, local_iov: &[IoVec<&[u8]>], remote_iov: &[RemoteIoVec]) -> Result<usize> { let res = unsafe { libc::process_vm_writev(pid.into(), local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong, remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0) }; Errno::result(res).map(|r| r as usize) } /// Read data directly from another process's virtual memory /// (see [`process_vm_readv`(2)]). /// /// `local_iov` is a list of [`IoVec`]s containing the buffer to copy /// data into, and `remote_iov` is a list of [`RemoteIoVec`]s identifying /// where the source data is in the target process. On success, /// returns the number of bytes written, which will always be a whole /// number of `remote_iov` chunks. /// /// This requires the same permissions as debugging the process using /// [`ptrace`]: you must either be a privileged process (with /// `CAP_SYS_PTRACE`), or you must be running as the same user as the /// target process and the OS must have unprivileged debugging enabled. /// /// This function is only available on Linux and Android(SDK23+). /// /// [`process_vm_readv`(2)]: https://man7.org/linux/man-pages/man2/process_vm_readv.2.html /// [`ptrace`]: ../ptrace/index.html /// [`IoVec`]: struct.IoVec.html /// [`RemoteIoVec`]: struct.RemoteIoVec.html #[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))] pub fn process_vm_readv( pid: crate::unistd::Pid, local_iov: &[IoVec<&mut [u8]>], remote_iov: &[RemoteIoVec]) -> Result<usize> { let res = unsafe { libc::process_vm_readv(pid.into(), local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong, remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0) }; Errno::result(res).map(|r| r as usize) } } /// A vector of buffers. /// /// Vectored I/O methods like [`writev`] and [`readv`] use this structure for /// both reading and writing. Each `IoVec` specifies the base address and /// length of an area in memory. #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct IoVec<T>(pub(crate) libc::iovec, PhantomData<T>); impl<T> IoVec<T> { /// View the `IoVec` as a Rust slice. #[inline] pub fn as_slice(&self) -> &[u8] { use std::slice; unsafe { slice::from_raw_parts( self.0.iov_base as *const u8, self.0.iov_len as usize) } } } impl<'a> IoVec<&'a [u8]> { #[cfg(all(feature = "mount", target_os = "freebsd"))] pub(crate) fn from_raw_parts(base: *mut c_void, len: usize) -> Self { IoVec(libc::iovec { iov_base: base, iov_len: len }, PhantomData) } /// Create an `IoVec` from a Rust slice. pub fn from_slice(buf: &'a [u8]) -> IoVec<&'a [u8]> { IoVec(libc::iovec { iov_base: buf.as_ptr() as *mut c_void, iov_len: buf.len() as size_t, }, PhantomData) } } impl<'a> IoVec<&'a mut [u8]> { /// Create an `IoVec` from a mutable Rust slice. pub fn from_mut_slice(buf: &'a mut [u8]) -> IoVec<&'a mut [u8]> { IoVec(libc::iovec { iov_base: buf.as_ptr() as *mut c_void, iov_len: buf.len() as size_t, }, PhantomData) } } // The only reason IoVec isn't automatically Send+Sync is because libc::iovec // contains raw pointers. unsafe impl<T> Send for IoVec<T> where T: Send {} unsafe impl<T> Sync for IoVec<T> where T: Sync {}
pwritev
identifier_name
test_logger.py
from io import StringIO from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent def test_filtered_value():
def test_pprint_with_indent(): """Test pprint_with_indent does indentation.""" out = StringIO() data = { 12: 34, 'confirm_password': '12345qwerty', 'credentials': ['abc', 'def'], 'key': 'value', 'nested_dict': {'password': 'not_filtered'}, 'password': '12345qwerty', } pprint_with_indent(data, out) assert ( out.getvalue() == '''\ {12: 34, 'confirm_password': [Filtered], 'credentials': [Filtered], 'key': 'value', 'nested_dict': {'password': 'not_filtered'}, 'password': [Filtered]} ''' ) def test_repeat_value_indicator(): """Test RepeatValueIndicator class.""" assert repr(RepeatValueIndicator('key')) == "<same as prior 'key'>" assert str(RepeatValueIndicator('key')) == "<same as prior 'key'>"
"""Test for filtered values.""" # Doesn't touch normal key/value pairs assert filtered_value('normal', 'value') == 'value' assert filtered_value('also_normal', 123) == 123 # But does redact sensitive keys assert filtered_value('password', '123pass') != '123pass' # The returned value is an object that renders via repr and str as '[Filtered]' assert repr(filtered_value('password', '123pass')) == '[Filtered]' assert str(filtered_value('password', '123pass')) == '[Filtered]' # Also works on partial matches in the keys assert repr(filtered_value('confirm_password', '123pass')) == '[Filtered]' # The filter uses a verbose regex. Words in the middle of the regex also work assert repr(filtered_value('access_token', 'secret-here')) == '[Filtered]' # Filters are case insensitive assert repr(filtered_value('TELEGRAM_ERROR_APIKEY', 'api:key')) == '[Filtered]' # Keys with 'token' as a word are also filtered assert repr(filtered_value('SMS_TWILIO_TOKEN', 'api:key')) == '[Filtered]' # Numbers that look like card numbers are filtered assert ( filtered_value('anything', 'My number is 1234 5678 9012 3456') == 'My number is [Filtered]' ) # This works with any combination of spaces and dashes within the number assert ( filtered_value('anything', 'My number is 1234 5678-90123456') == 'My number is [Filtered]' )
identifier_body
test_logger.py
from io import StringIO from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent def test_filtered_value(): """Test for filtered values.""" # Doesn't touch normal key/value pairs assert filtered_value('normal', 'value') == 'value' assert filtered_value('also_normal', 123) == 123 # But does redact sensitive keys assert filtered_value('password', '123pass') != '123pass' # The returned value is an object that renders via repr and str as '[Filtered]' assert repr(filtered_value('password', '123pass')) == '[Filtered]' assert str(filtered_value('password', '123pass')) == '[Filtered]' # Also works on partial matches in the keys assert repr(filtered_value('confirm_password', '123pass')) == '[Filtered]' # The filter uses a verbose regex. Words in the middle of the regex also work assert repr(filtered_value('access_token', 'secret-here')) == '[Filtered]' # Filters are case insensitive assert repr(filtered_value('TELEGRAM_ERROR_APIKEY', 'api:key')) == '[Filtered]' # Keys with 'token' as a word are also filtered assert repr(filtered_value('SMS_TWILIO_TOKEN', 'api:key')) == '[Filtered]' # Numbers that look like card numbers are filtered assert ( filtered_value('anything', 'My number is 1234 5678 9012 3456') == 'My number is [Filtered]' ) # This works with any combination of spaces and dashes within the number assert ( filtered_value('anything', 'My number is 1234 5678-90123456') == 'My number is [Filtered]' ) def test_pprint_with_indent(): """Test pprint_with_indent does indentation.""" out = StringIO() data = {
12: 34, 'confirm_password': '12345qwerty', 'credentials': ['abc', 'def'], 'key': 'value', 'nested_dict': {'password': 'not_filtered'}, 'password': '12345qwerty', } pprint_with_indent(data, out) assert ( out.getvalue() == '''\ {12: 34, 'confirm_password': [Filtered], 'credentials': [Filtered], 'key': 'value', 'nested_dict': {'password': 'not_filtered'}, 'password': [Filtered]} ''' ) def test_repeat_value_indicator(): """Test RepeatValueIndicator class.""" assert repr(RepeatValueIndicator('key')) == "<same as prior 'key'>" assert str(RepeatValueIndicator('key')) == "<same as prior 'key'>"
random_line_split
test_logger.py
from io import StringIO from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent def test_filtered_value(): """Test for filtered values.""" # Doesn't touch normal key/value pairs assert filtered_value('normal', 'value') == 'value' assert filtered_value('also_normal', 123) == 123 # But does redact sensitive keys assert filtered_value('password', '123pass') != '123pass' # The returned value is an object that renders via repr and str as '[Filtered]' assert repr(filtered_value('password', '123pass')) == '[Filtered]' assert str(filtered_value('password', '123pass')) == '[Filtered]' # Also works on partial matches in the keys assert repr(filtered_value('confirm_password', '123pass')) == '[Filtered]' # The filter uses a verbose regex. Words in the middle of the regex also work assert repr(filtered_value('access_token', 'secret-here')) == '[Filtered]' # Filters are case insensitive assert repr(filtered_value('TELEGRAM_ERROR_APIKEY', 'api:key')) == '[Filtered]' # Keys with 'token' as a word are also filtered assert repr(filtered_value('SMS_TWILIO_TOKEN', 'api:key')) == '[Filtered]' # Numbers that look like card numbers are filtered assert ( filtered_value('anything', 'My number is 1234 5678 9012 3456') == 'My number is [Filtered]' ) # This works with any combination of spaces and dashes within the number assert ( filtered_value('anything', 'My number is 1234 5678-90123456') == 'My number is [Filtered]' ) def
(): """Test pprint_with_indent does indentation.""" out = StringIO() data = { 12: 34, 'confirm_password': '12345qwerty', 'credentials': ['abc', 'def'], 'key': 'value', 'nested_dict': {'password': 'not_filtered'}, 'password': '12345qwerty', } pprint_with_indent(data, out) assert ( out.getvalue() == '''\ {12: 34, 'confirm_password': [Filtered], 'credentials': [Filtered], 'key': 'value', 'nested_dict': {'password': 'not_filtered'}, 'password': [Filtered]} ''' ) def test_repeat_value_indicator(): """Test RepeatValueIndicator class.""" assert repr(RepeatValueIndicator('key')) == "<same as prior 'key'>" assert str(RepeatValueIndicator('key')) == "<same as prior 'key'>"
test_pprint_with_indent
identifier_name
main.js
/* * jQuery File Upload Plugin JS Example 8.9.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* global $, window */ $(function () { 'use strict'; // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: root_url + '/media/upload' }); // Enable iframe cross-domain access via redirect option: $('#fileupload').fileupload( 'option', 'redirect', window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ) ); if (window.location.hostname === 'blueimp.github.io') { // Demo settings: $('#fileupload').fileupload('option', { url: '//jquery-file-upload.appspot.com/', // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i }); // Upload server status check for browsers with CORS support: if ($.support.cors)
} else { // Load existing files: $('#fileupload').addClass('fileupload-processing'); $.ajax({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: $('#fileupload').fileupload('option', 'url'), dataType: 'json', context: $('#fileupload')[0] }).always(function () { $(this).removeClass('fileupload-processing'); }).done(function (result) { $(this).fileupload('option', 'done') .call(this, $.Event('done'), {result: result}); }); } /////////////////////////////////////////////// });
{ $.ajax({ url: '//jquery-file-upload.appspot.com/', type: 'HEAD' }).fail(function () { $('<div class="alert alert-danger"/>') .text('Upload server currently unavailable - ' + new Date()) .appendTo('#fileupload'); }); }
conditional_block
main.js
/* * jQuery File Upload Plugin JS Example 8.9.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* global $, window */ $(function () { 'use strict'; // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: root_url + '/media/upload' }); // Enable iframe cross-domain access via redirect option: $('#fileupload').fileupload( 'option', 'redirect', window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ) ); if (window.location.hostname === 'blueimp.github.io') { // Demo settings: $('#fileupload').fileupload('option', { url: '//jquery-file-upload.appspot.com/', // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent),
// Upload server status check for browsers with CORS support: if ($.support.cors) { $.ajax({ url: '//jquery-file-upload.appspot.com/', type: 'HEAD' }).fail(function () { $('<div class="alert alert-danger"/>') .text('Upload server currently unavailable - ' + new Date()) .appendTo('#fileupload'); }); } } else { // Load existing files: $('#fileupload').addClass('fileupload-processing'); $.ajax({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: $('#fileupload').fileupload('option', 'url'), dataType: 'json', context: $('#fileupload')[0] }).always(function () { $(this).removeClass('fileupload-processing'); }).done(function (result) { $(this).fileupload('option', 'done') .call(this, $.Event('done'), {result: result}); }); } /////////////////////////////////////////////// });
maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i });
random_line_split
getGeneDescLocal_Illumina.py
import pandas as pd def closeFunc():
def oligosList(): oligosPath = input('Path to the file containing the list of probes: ') oligos = open(oligosPath) oligos = oligos.readlines() oligosList = [] for oligo in oligos: item = oligo.strip() oligosList.append(item) return oligosList def main(oligosList, fullData = False): db = pd.read_csv('probes_illumina.txt', sep = '\t', header = 0, low_memory = False, index_col = 11) output = db.ix[oligosList] if fullData == False: output = output['Definition'] print(output) else: output = output[['Accession', 'Symbol', 'Definition']] output.to_csv('getGeneDescLocal_results.txt', sep = '\t') closeFunc() if __name__ == "__main__": oligosList = oligosList() answer = input('Do you want full data? (yes/no) ') if answer == 'no': main(oligosList) elif answer == 'yes': main(oligosList, True) else: print('Wrong answer') closeFunc()
print('''Type 'quit' and press enter to exit program''') answer = input(': ') if answer == 'quit': quit() else: closeFunc()
identifier_body
getGeneDescLocal_Illumina.py
import pandas as pd def closeFunc(): print('''Type 'quit' and press enter to exit program''') answer = input(': ') if answer == 'quit': quit() else: closeFunc() def
(): oligosPath = input('Path to the file containing the list of probes: ') oligos = open(oligosPath) oligos = oligos.readlines() oligosList = [] for oligo in oligos: item = oligo.strip() oligosList.append(item) return oligosList def main(oligosList, fullData = False): db = pd.read_csv('probes_illumina.txt', sep = '\t', header = 0, low_memory = False, index_col = 11) output = db.ix[oligosList] if fullData == False: output = output['Definition'] print(output) else: output = output[['Accession', 'Symbol', 'Definition']] output.to_csv('getGeneDescLocal_results.txt', sep = '\t') closeFunc() if __name__ == "__main__": oligosList = oligosList() answer = input('Do you want full data? (yes/no) ') if answer == 'no': main(oligosList) elif answer == 'yes': main(oligosList, True) else: print('Wrong answer') closeFunc()
oligosList
identifier_name
getGeneDescLocal_Illumina.py
import pandas as pd def closeFunc(): print('''Type 'quit' and press enter to exit program''') answer = input(': ') if answer == 'quit': quit() else: closeFunc() def oligosList(): oligosPath = input('Path to the file containing the list of probes: ') oligos = open(oligosPath) oligos = oligos.readlines() oligosList = [] for oligo in oligos: item = oligo.strip() oligosList.append(item) return oligosList def main(oligosList, fullData = False): db = pd.read_csv('probes_illumina.txt', sep = '\t', header = 0, low_memory = False, index_col = 11) output = db.ix[oligosList] if fullData == False: output = output['Definition'] print(output) else: output = output[['Accession', 'Symbol', 'Definition']] output.to_csv('getGeneDescLocal_results.txt', sep = '\t') closeFunc() if __name__ == "__main__": oligosList = oligosList() answer = input('Do you want full data? (yes/no) ') if answer == 'no':
elif answer == 'yes': main(oligosList, True) else: print('Wrong answer') closeFunc()
main(oligosList)
conditional_block
getGeneDescLocal_Illumina.py
import pandas as pd def closeFunc(): print('''Type 'quit' and press enter to exit program''') answer = input(': ') if answer == 'quit': quit() else: closeFunc() def oligosList(): oligosPath = input('Path to the file containing the list of probes: ') oligos = open(oligosPath) oligos = oligos.readlines() oligosList = [] for oligo in oligos: item = oligo.strip() oligosList.append(item) return oligosList def main(oligosList, fullData = False): db = pd.read_csv('probes_illumina.txt', sep = '\t', header = 0, low_memory = False, index_col = 11) output = db.ix[oligosList] if fullData == False: output = output['Definition'] print(output) else: output = output[['Accession', 'Symbol', 'Definition']] output.to_csv('getGeneDescLocal_results.txt', sep = '\t')
if __name__ == "__main__": oligosList = oligosList() answer = input('Do you want full data? (yes/no) ') if answer == 'no': main(oligosList) elif answer == 'yes': main(oligosList, True) else: print('Wrong answer') closeFunc()
closeFunc()
random_line_split
lib.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, // TODO: Falsely triggers for async/await: // see https://github.com/rust-lang/rust-clippy/issues/5360 // clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] // We only use unsafe pointer dereferences in our no_mangle exposed API, but it is nicer to list // just the one minor call as unsafe, than to mark the whole function as unsafe which may hide // other unsafeness. #![allow(clippy::not_unsafe_ptr_arg_deref)] #![type_length_limit = "43757804"]
mod core; mod externs; mod interning; mod intrinsics; mod nodes; mod scheduler; mod selectors; mod session; mod tasks; mod types; pub use crate::context::{Core, ExecutionStrategyOptions, RemotingOptions}; pub use crate::core::{Failure, Function, Key, Params, TypeId, Value}; pub use crate::intrinsics::Intrinsics; pub use crate::scheduler::{ExecutionRequest, ExecutionTermination, Scheduler}; pub use crate::session::Session; pub use crate::tasks::{Rule, Tasks}; pub use crate::types::Types;
mod context;
random_line_split
pending.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use interrupt::Hardware; #[derive(Copy, Clone, Debug)] pub struct ISPR(u32); #[derive(Copy, Clone, Debug)] pub struct ICPR(u32); impl ISPR { pub fn set_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } pub fn
(&self, hardware: Hardware) -> bool { let interrupt = hardware as u8; self.0 & (0b1 << interrupt) != 0 } } impl ICPR { pub fn clear_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ispr_set_pending() { let mut ispr = ISPR(0); ispr.set_pending(Hardware::Flash); assert_eq!(ispr.0, 0b1 << 3); } #[test] fn test_ispr_interrupt_is_pending() { let ispr = ISPR(0b1 << 5); assert!(ispr.interrupt_is_pending(Hardware::Exti01)); assert!(!ispr.interrupt_is_pending(Hardware::Usb)); } #[test] fn test_icpr_clear_pending() { let mut icpr = ICPR(0); icpr.clear_pending(Hardware::Flash); assert_eq!(icpr.0, 0b1 << 3); } }
interrupt_is_pending
identifier_name
pending.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use interrupt::Hardware; #[derive(Copy, Clone, Debug)] pub struct ISPR(u32); #[derive(Copy, Clone, Debug)] pub struct ICPR(u32); impl ISPR { pub fn set_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } pub fn interrupt_is_pending(&self, hardware: Hardware) -> bool
} impl ICPR { pub fn clear_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ispr_set_pending() { let mut ispr = ISPR(0); ispr.set_pending(Hardware::Flash); assert_eq!(ispr.0, 0b1 << 3); } #[test] fn test_ispr_interrupt_is_pending() { let ispr = ISPR(0b1 << 5); assert!(ispr.interrupt_is_pending(Hardware::Exti01)); assert!(!ispr.interrupt_is_pending(Hardware::Usb)); } #[test] fn test_icpr_clear_pending() { let mut icpr = ICPR(0); icpr.clear_pending(Hardware::Flash); assert_eq!(icpr.0, 0b1 << 3); } }
{ let interrupt = hardware as u8; self.0 & (0b1 << interrupt) != 0 }
identifier_body
pending.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use interrupt::Hardware; #[derive(Copy, Clone, Debug)] pub struct ISPR(u32); #[derive(Copy, Clone, Debug)] pub struct ICPR(u32); impl ISPR { pub fn set_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } pub fn interrupt_is_pending(&self, hardware: Hardware) -> bool {
} impl ICPR { pub fn clear_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ispr_set_pending() { let mut ispr = ISPR(0); ispr.set_pending(Hardware::Flash); assert_eq!(ispr.0, 0b1 << 3); } #[test] fn test_ispr_interrupt_is_pending() { let ispr = ISPR(0b1 << 5); assert!(ispr.interrupt_is_pending(Hardware::Exti01)); assert!(!ispr.interrupt_is_pending(Hardware::Usb)); } #[test] fn test_icpr_clear_pending() { let mut icpr = ICPR(0); icpr.clear_pending(Hardware::Flash); assert_eq!(icpr.0, 0b1 << 3); } }
let interrupt = hardware as u8; self.0 & (0b1 << interrupt) != 0 }
random_line_split
gas_schedule.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module lays out the basic abstract costing schedule for bytecode instructions. //! //! It is important to note that the cost schedule defined in this file does not track hashing //! operations or other native operations; the cost of each native operation will be returned by the //! native function itself. use mirai_annotations::*; use serde::{Deserialize, Serialize}; use std::{ ops::{Add, Div, Mul, Sub}, u64, }; /// The underlying carrier for gas-related units and costs. Data with this type should not be /// manipulated directly, but instead be manipulated using the newtype wrappers defined around /// them and the functions defined in the `GasAlgebra` trait. pub type GasCarrier = u64; /// A trait encoding the operations permitted on the underlying carrier for the gas unit, and how /// other gas-related units can interact with other units -- operations can only be performed /// across units with the same underlying carrier (i.e. as long as the underlying data is /// the same). pub trait GasAlgebra<GasCarrier>: Sized where GasCarrier: Add<Output = GasCarrier> + Sub<Output = GasCarrier> + Div<Output = GasCarrier> + Mul<Output = GasCarrier> + Copy, { /// Project a value into the gas algebra. fn new(carrier: GasCarrier) -> Self; /// Get the carrier. fn get(&self) -> GasCarrier; /// Map a function `f` of one argument over the underlying data. fn map<F: Fn(GasCarrier) -> GasCarrier>(self, f: F) -> Self { Self::new(f(self.get())) } /// Map a function `f` of two arguments over the underlying carrier. Note that this function /// can take two different implementations of the trait -- one for `self` the other for the /// second argument. But, we enforce that they have the same underlying carrier. fn map2<F: Fn(GasCarrier, GasCarrier) -> GasCarrier>( self, other: impl GasAlgebra<GasCarrier>, f: F, ) -> Self { Self::new(f(self.get(), other.get())) } /// Apply a function `f` of two arguments to the carrier. Since `f` is not an endomorphism, we /// return the resulting value, as opposed to the result wrapped up in ourselves. fn app<T, F: Fn(GasCarrier, GasCarrier) -> T>( &self, other: &impl GasAlgebra<GasCarrier>, f: F, ) -> T { f(self.get(), other.get()) } /// We allow casting between GasAlgebras as long as they have the same underlying carrier -- /// i.e. they use the same type to store the underlying value. fn unitary_cast<T: GasAlgebra<GasCarrier>>(self) -> T { T::new(self.get()) } /// Add the two `GasAlgebra`s together. fn add(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Add::add) } /// Subtract one `GasAlgebra` from the other. fn sub(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Sub::sub) } /// Multiply two `GasAlgebra`s together. fn mul(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Mul::mul) } /// Divide one `GasAlgebra` by the other. fn div(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Div::div) } } // We would really like to be able to implement the standard arithmetic traits over the GasAlgebra // trait, but that isn't possible. macro_rules! define_gas_unit { { name: $name: ident, carrier: $carrier: ty, doc: $comment: literal } => { #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] #[doc=$comment] pub struct $name<GasCarrier>(GasCarrier); impl GasAlgebra<$carrier> for $name<$carrier> { fn new(c: GasCarrier) -> Self { Self(c) } fn get(&self) -> GasCarrier { self.0 } } } } define_gas_unit! { name: AbstractMemorySize, carrier: GasCarrier, doc: "A newtype wrapper that represents the (abstract) memory size that the instruction will take up." } define_gas_unit! { name: GasUnits, carrier: GasCarrier, doc: "Units of gas as seen by clients of the Move VM." } define_gas_unit! { name: InternalGasUnits, carrier: GasCarrier, doc: "Units of gas used within the Move VM, scaled for fine-grained accounting." } define_gas_unit! { name: GasPrice, carrier: GasCarrier, doc: "A newtype wrapper around the gas price for each unit of gas consumed." } /// One unit of gas pub const ONE_GAS_UNIT: InternalGasUnits<GasCarrier> = InternalGasUnits(1); /// The maximum size representable by AbstractMemorySize pub const MAX_ABSTRACT_MEMORY_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(std::u64::MAX); /// The size in bytes for a non-string or address constant on the stack pub const CONST_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(16); /// The size in bytes for a reference on the stack pub const REFERENCE_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(8); /// The size of a struct in bytes pub const STRUCT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(2); /// For V1 all accounts will be ~800 bytes pub const DEFAULT_ACCOUNT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(800); /// Any transaction over this size will be charged `INTRINSIC_GAS_PER_BYTE` per byte pub const LARGE_TRANSACTION_CUTOFF: AbstractMemorySize<GasCarrier> = AbstractMemorySize(600); /// For exists checks on data that doesn't exists this is the multiplier that is used. pub const MIN_EXISTS_DATA_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(100); pub const MAX_TRANSACTION_SIZE_IN_BYTES: GasCarrier = 4096; #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct GasConstants { /// The cost per-byte read from global storage. pub global_memory_per_byte_cost: InternalGasUnits<GasCarrier>, /// The cost per-byte written to storage. pub global_memory_per_byte_write_cost: InternalGasUnits<GasCarrier>, /// The flat minimum amount of gas required for any transaction. /// Charged at the start of execution. pub min_transaction_gas_units: InternalGasUnits<GasCarrier>, /// Any transaction over this size will be charged an additional amount per byte. pub large_transaction_cutoff: AbstractMemorySize<GasCarrier>, /// The units of gas that to be charged per byte over the `large_transaction_cutoff` in addition to /// `min_transaction_gas_units` for transactions whose size exceeds `large_transaction_cutoff`. pub intrinsic_gas_per_byte: InternalGasUnits<GasCarrier>, /// ~5 microseconds should equal one unit of computational gas. We bound the maximum /// computational time of any given transaction at roughly 20 seconds. We want this number and /// `MAX_PRICE_PER_GAS_UNIT` to always satisfy the inequality that /// MAXIMUM_NUMBER_OF_GAS_UNITS * MAX_PRICE_PER_GAS_UNIT < min(u64::MAX, GasUnits<GasCarrier>::MAX) /// NB: The bound is set quite high since custom scripts aren't allowed except from predefined /// and vetted senders. pub maximum_number_of_gas_units: GasUnits<GasCarrier>, /// The minimum gas price that a transaction can be submitted with. pub min_price_per_gas_unit: GasPrice<GasCarrier>, /// The maximum gas unit price that a transaction can be submitted with. pub max_price_per_gas_unit: GasPrice<GasCarrier>, pub max_transaction_size_in_bytes: GasCarrier, pub gas_unit_scaling_factor: GasCarrier, pub default_account_size: AbstractMemorySize<GasCarrier>, } impl GasConstants { pub fn to_internal_units(&self, units: GasUnits<GasCarrier>) -> InternalGasUnits<GasCarrier> { InternalGasUnits::new(units.get() * self.gas_unit_scaling_factor) } pub fn to_external_units(&self, units: InternalGasUnits<GasCarrier>) -> GasUnits<GasCarrier> { GasUnits::new(units.get() / self.gas_unit_scaling_factor) } } impl Default for GasConstants { fn default() -> Self { Self { global_memory_per_byte_cost: InternalGasUnits(4), global_memory_per_byte_write_cost: InternalGasUnits(9), min_transaction_gas_units: InternalGasUnits(600), large_transaction_cutoff: LARGE_TRANSACTION_CUTOFF, intrinsic_gas_per_byte: InternalGasUnits(8), maximum_number_of_gas_units: GasUnits(4_000_000), min_price_per_gas_unit: GasPrice(0), max_price_per_gas_unit: GasPrice(10_000), max_transaction_size_in_bytes: MAX_TRANSACTION_SIZE_IN_BYTES, gas_unit_scaling_factor: 1000, default_account_size: DEFAULT_ACCOUNT_SIZE, } } } /// The cost tables, keyed by the serialized form of the bytecode instruction. We use the /// serialized form as opposed to the instruction enum itself as the key since this will be the /// on-chain representation of bytecode instructions in the future. #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct CostTable { pub instruction_table: Vec<GasCost>, pub native_table: Vec<GasCost>, pub gas_constants: GasConstants, } impl CostTable { #[inline] pub fn instruction_cost(&self, instr_index: u8) -> &GasCost { precondition!(instr_index > 0 && instr_index <= (self.instruction_table.len() as u8)); &self.instruction_table[(instr_index - 1) as usize] } #[inline] pub fn native_cost(&self, native_index: u8) -> &GasCost { precondition!(native_index < (self.native_table.len() as u8)); &self.native_table[native_index as usize] } } /// The `GasCost` tracks: /// - instruction cost: how much time/computational power is needed to perform the instruction /// - memory cost: how much memory is required for the instruction, and storage overhead #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct GasCost { pub instruction_gas: InternalGasUnits<GasCarrier>, pub memory_gas: InternalGasUnits<GasCarrier>, } impl GasCost { pub fn
(instr_gas: GasCarrier, mem_gas: GasCarrier) -> Self { Self { instruction_gas: InternalGasUnits::new(instr_gas), memory_gas: InternalGasUnits::new(mem_gas), } } /// Convert a GasCost to a total gas charge in `InternalGasUnits`. #[inline] pub fn total(&self) -> InternalGasUnits<GasCarrier> { self.instruction_gas.add(self.memory_gas) } }
new
identifier_name
gas_schedule.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module lays out the basic abstract costing schedule for bytecode instructions. //! //! It is important to note that the cost schedule defined in this file does not track hashing //! operations or other native operations; the cost of each native operation will be returned by the //! native function itself. use mirai_annotations::*; use serde::{Deserialize, Serialize}; use std::{ ops::{Add, Div, Mul, Sub}, u64, }; /// The underlying carrier for gas-related units and costs. Data with this type should not be /// manipulated directly, but instead be manipulated using the newtype wrappers defined around /// them and the functions defined in the `GasAlgebra` trait. pub type GasCarrier = u64; /// A trait encoding the operations permitted on the underlying carrier for the gas unit, and how /// other gas-related units can interact with other units -- operations can only be performed /// across units with the same underlying carrier (i.e. as long as the underlying data is /// the same). pub trait GasAlgebra<GasCarrier>: Sized where GasCarrier: Add<Output = GasCarrier> + Sub<Output = GasCarrier> + Div<Output = GasCarrier> + Mul<Output = GasCarrier> + Copy, { /// Project a value into the gas algebra. fn new(carrier: GasCarrier) -> Self; /// Get the carrier. fn get(&self) -> GasCarrier; /// Map a function `f` of one argument over the underlying data. fn map<F: Fn(GasCarrier) -> GasCarrier>(self, f: F) -> Self { Self::new(f(self.get())) } /// Map a function `f` of two arguments over the underlying carrier. Note that this function /// can take two different implementations of the trait -- one for `self` the other for the /// second argument. But, we enforce that they have the same underlying carrier. fn map2<F: Fn(GasCarrier, GasCarrier) -> GasCarrier>( self, other: impl GasAlgebra<GasCarrier>, f: F, ) -> Self { Self::new(f(self.get(), other.get())) } /// Apply a function `f` of two arguments to the carrier. Since `f` is not an endomorphism, we /// return the resulting value, as opposed to the result wrapped up in ourselves. fn app<T, F: Fn(GasCarrier, GasCarrier) -> T>( &self, other: &impl GasAlgebra<GasCarrier>, f: F, ) -> T { f(self.get(), other.get()) } /// We allow casting between GasAlgebras as long as they have the same underlying carrier -- /// i.e. they use the same type to store the underlying value. fn unitary_cast<T: GasAlgebra<GasCarrier>>(self) -> T { T::new(self.get()) } /// Add the two `GasAlgebra`s together. fn add(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Add::add) } /// Subtract one `GasAlgebra` from the other. fn sub(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Sub::sub) } /// Multiply two `GasAlgebra`s together. fn mul(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Mul::mul) } /// Divide one `GasAlgebra` by the other. fn div(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Div::div) } } // We would really like to be able to implement the standard arithmetic traits over the GasAlgebra // trait, but that isn't possible. macro_rules! define_gas_unit { { name: $name: ident, carrier: $carrier: ty, doc: $comment: literal } => { #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] #[doc=$comment] pub struct $name<GasCarrier>(GasCarrier); impl GasAlgebra<$carrier> for $name<$carrier> { fn new(c: GasCarrier) -> Self { Self(c) } fn get(&self) -> GasCarrier { self.0 } } } } define_gas_unit! { name: AbstractMemorySize, carrier: GasCarrier, doc: "A newtype wrapper that represents the (abstract) memory size that the instruction will take up." }
doc: "Units of gas as seen by clients of the Move VM." } define_gas_unit! { name: InternalGasUnits, carrier: GasCarrier, doc: "Units of gas used within the Move VM, scaled for fine-grained accounting." } define_gas_unit! { name: GasPrice, carrier: GasCarrier, doc: "A newtype wrapper around the gas price for each unit of gas consumed." } /// One unit of gas pub const ONE_GAS_UNIT: InternalGasUnits<GasCarrier> = InternalGasUnits(1); /// The maximum size representable by AbstractMemorySize pub const MAX_ABSTRACT_MEMORY_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(std::u64::MAX); /// The size in bytes for a non-string or address constant on the stack pub const CONST_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(16); /// The size in bytes for a reference on the stack pub const REFERENCE_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(8); /// The size of a struct in bytes pub const STRUCT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(2); /// For V1 all accounts will be ~800 bytes pub const DEFAULT_ACCOUNT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(800); /// Any transaction over this size will be charged `INTRINSIC_GAS_PER_BYTE` per byte pub const LARGE_TRANSACTION_CUTOFF: AbstractMemorySize<GasCarrier> = AbstractMemorySize(600); /// For exists checks on data that doesn't exists this is the multiplier that is used. pub const MIN_EXISTS_DATA_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(100); pub const MAX_TRANSACTION_SIZE_IN_BYTES: GasCarrier = 4096; #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct GasConstants { /// The cost per-byte read from global storage. pub global_memory_per_byte_cost: InternalGasUnits<GasCarrier>, /// The cost per-byte written to storage. pub global_memory_per_byte_write_cost: InternalGasUnits<GasCarrier>, /// The flat minimum amount of gas required for any transaction. /// Charged at the start of execution. pub min_transaction_gas_units: InternalGasUnits<GasCarrier>, /// Any transaction over this size will be charged an additional amount per byte. pub large_transaction_cutoff: AbstractMemorySize<GasCarrier>, /// The units of gas that to be charged per byte over the `large_transaction_cutoff` in addition to /// `min_transaction_gas_units` for transactions whose size exceeds `large_transaction_cutoff`. pub intrinsic_gas_per_byte: InternalGasUnits<GasCarrier>, /// ~5 microseconds should equal one unit of computational gas. We bound the maximum /// computational time of any given transaction at roughly 20 seconds. We want this number and /// `MAX_PRICE_PER_GAS_UNIT` to always satisfy the inequality that /// MAXIMUM_NUMBER_OF_GAS_UNITS * MAX_PRICE_PER_GAS_UNIT < min(u64::MAX, GasUnits<GasCarrier>::MAX) /// NB: The bound is set quite high since custom scripts aren't allowed except from predefined /// and vetted senders. pub maximum_number_of_gas_units: GasUnits<GasCarrier>, /// The minimum gas price that a transaction can be submitted with. pub min_price_per_gas_unit: GasPrice<GasCarrier>, /// The maximum gas unit price that a transaction can be submitted with. pub max_price_per_gas_unit: GasPrice<GasCarrier>, pub max_transaction_size_in_bytes: GasCarrier, pub gas_unit_scaling_factor: GasCarrier, pub default_account_size: AbstractMemorySize<GasCarrier>, } impl GasConstants { pub fn to_internal_units(&self, units: GasUnits<GasCarrier>) -> InternalGasUnits<GasCarrier> { InternalGasUnits::new(units.get() * self.gas_unit_scaling_factor) } pub fn to_external_units(&self, units: InternalGasUnits<GasCarrier>) -> GasUnits<GasCarrier> { GasUnits::new(units.get() / self.gas_unit_scaling_factor) } } impl Default for GasConstants { fn default() -> Self { Self { global_memory_per_byte_cost: InternalGasUnits(4), global_memory_per_byte_write_cost: InternalGasUnits(9), min_transaction_gas_units: InternalGasUnits(600), large_transaction_cutoff: LARGE_TRANSACTION_CUTOFF, intrinsic_gas_per_byte: InternalGasUnits(8), maximum_number_of_gas_units: GasUnits(4_000_000), min_price_per_gas_unit: GasPrice(0), max_price_per_gas_unit: GasPrice(10_000), max_transaction_size_in_bytes: MAX_TRANSACTION_SIZE_IN_BYTES, gas_unit_scaling_factor: 1000, default_account_size: DEFAULT_ACCOUNT_SIZE, } } } /// The cost tables, keyed by the serialized form of the bytecode instruction. We use the /// serialized form as opposed to the instruction enum itself as the key since this will be the /// on-chain representation of bytecode instructions in the future. #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct CostTable { pub instruction_table: Vec<GasCost>, pub native_table: Vec<GasCost>, pub gas_constants: GasConstants, } impl CostTable { #[inline] pub fn instruction_cost(&self, instr_index: u8) -> &GasCost { precondition!(instr_index > 0 && instr_index <= (self.instruction_table.len() as u8)); &self.instruction_table[(instr_index - 1) as usize] } #[inline] pub fn native_cost(&self, native_index: u8) -> &GasCost { precondition!(native_index < (self.native_table.len() as u8)); &self.native_table[native_index as usize] } } /// The `GasCost` tracks: /// - instruction cost: how much time/computational power is needed to perform the instruction /// - memory cost: how much memory is required for the instruction, and storage overhead #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct GasCost { pub instruction_gas: InternalGasUnits<GasCarrier>, pub memory_gas: InternalGasUnits<GasCarrier>, } impl GasCost { pub fn new(instr_gas: GasCarrier, mem_gas: GasCarrier) -> Self { Self { instruction_gas: InternalGasUnits::new(instr_gas), memory_gas: InternalGasUnits::new(mem_gas), } } /// Convert a GasCost to a total gas charge in `InternalGasUnits`. #[inline] pub fn total(&self) -> InternalGasUnits<GasCarrier> { self.instruction_gas.add(self.memory_gas) } }
define_gas_unit! { name: GasUnits, carrier: GasCarrier,
random_line_split
gas_schedule.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module lays out the basic abstract costing schedule for bytecode instructions. //! //! It is important to note that the cost schedule defined in this file does not track hashing //! operations or other native operations; the cost of each native operation will be returned by the //! native function itself. use mirai_annotations::*; use serde::{Deserialize, Serialize}; use std::{ ops::{Add, Div, Mul, Sub}, u64, }; /// The underlying carrier for gas-related units and costs. Data with this type should not be /// manipulated directly, but instead be manipulated using the newtype wrappers defined around /// them and the functions defined in the `GasAlgebra` trait. pub type GasCarrier = u64; /// A trait encoding the operations permitted on the underlying carrier for the gas unit, and how /// other gas-related units can interact with other units -- operations can only be performed /// across units with the same underlying carrier (i.e. as long as the underlying data is /// the same). pub trait GasAlgebra<GasCarrier>: Sized where GasCarrier: Add<Output = GasCarrier> + Sub<Output = GasCarrier> + Div<Output = GasCarrier> + Mul<Output = GasCarrier> + Copy, { /// Project a value into the gas algebra. fn new(carrier: GasCarrier) -> Self; /// Get the carrier. fn get(&self) -> GasCarrier; /// Map a function `f` of one argument over the underlying data. fn map<F: Fn(GasCarrier) -> GasCarrier>(self, f: F) -> Self { Self::new(f(self.get())) } /// Map a function `f` of two arguments over the underlying carrier. Note that this function /// can take two different implementations of the trait -- one for `self` the other for the /// second argument. But, we enforce that they have the same underlying carrier. fn map2<F: Fn(GasCarrier, GasCarrier) -> GasCarrier>( self, other: impl GasAlgebra<GasCarrier>, f: F, ) -> Self { Self::new(f(self.get(), other.get())) } /// Apply a function `f` of two arguments to the carrier. Since `f` is not an endomorphism, we /// return the resulting value, as opposed to the result wrapped up in ourselves. fn app<T, F: Fn(GasCarrier, GasCarrier) -> T>( &self, other: &impl GasAlgebra<GasCarrier>, f: F, ) -> T { f(self.get(), other.get()) } /// We allow casting between GasAlgebras as long as they have the same underlying carrier -- /// i.e. they use the same type to store the underlying value. fn unitary_cast<T: GasAlgebra<GasCarrier>>(self) -> T { T::new(self.get()) } /// Add the two `GasAlgebra`s together. fn add(self, right: impl GasAlgebra<GasCarrier>) -> Self
/// Subtract one `GasAlgebra` from the other. fn sub(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Sub::sub) } /// Multiply two `GasAlgebra`s together. fn mul(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Mul::mul) } /// Divide one `GasAlgebra` by the other. fn div(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Div::div) } } // We would really like to be able to implement the standard arithmetic traits over the GasAlgebra // trait, but that isn't possible. macro_rules! define_gas_unit { { name: $name: ident, carrier: $carrier: ty, doc: $comment: literal } => { #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] #[doc=$comment] pub struct $name<GasCarrier>(GasCarrier); impl GasAlgebra<$carrier> for $name<$carrier> { fn new(c: GasCarrier) -> Self { Self(c) } fn get(&self) -> GasCarrier { self.0 } } } } define_gas_unit! { name: AbstractMemorySize, carrier: GasCarrier, doc: "A newtype wrapper that represents the (abstract) memory size that the instruction will take up." } define_gas_unit! { name: GasUnits, carrier: GasCarrier, doc: "Units of gas as seen by clients of the Move VM." } define_gas_unit! { name: InternalGasUnits, carrier: GasCarrier, doc: "Units of gas used within the Move VM, scaled for fine-grained accounting." } define_gas_unit! { name: GasPrice, carrier: GasCarrier, doc: "A newtype wrapper around the gas price for each unit of gas consumed." } /// One unit of gas pub const ONE_GAS_UNIT: InternalGasUnits<GasCarrier> = InternalGasUnits(1); /// The maximum size representable by AbstractMemorySize pub const MAX_ABSTRACT_MEMORY_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(std::u64::MAX); /// The size in bytes for a non-string or address constant on the stack pub const CONST_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(16); /// The size in bytes for a reference on the stack pub const REFERENCE_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(8); /// The size of a struct in bytes pub const STRUCT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(2); /// For V1 all accounts will be ~800 bytes pub const DEFAULT_ACCOUNT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(800); /// Any transaction over this size will be charged `INTRINSIC_GAS_PER_BYTE` per byte pub const LARGE_TRANSACTION_CUTOFF: AbstractMemorySize<GasCarrier> = AbstractMemorySize(600); /// For exists checks on data that doesn't exists this is the multiplier that is used. pub const MIN_EXISTS_DATA_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(100); pub const MAX_TRANSACTION_SIZE_IN_BYTES: GasCarrier = 4096; #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct GasConstants { /// The cost per-byte read from global storage. pub global_memory_per_byte_cost: InternalGasUnits<GasCarrier>, /// The cost per-byte written to storage. pub global_memory_per_byte_write_cost: InternalGasUnits<GasCarrier>, /// The flat minimum amount of gas required for any transaction. /// Charged at the start of execution. pub min_transaction_gas_units: InternalGasUnits<GasCarrier>, /// Any transaction over this size will be charged an additional amount per byte. pub large_transaction_cutoff: AbstractMemorySize<GasCarrier>, /// The units of gas that to be charged per byte over the `large_transaction_cutoff` in addition to /// `min_transaction_gas_units` for transactions whose size exceeds `large_transaction_cutoff`. pub intrinsic_gas_per_byte: InternalGasUnits<GasCarrier>, /// ~5 microseconds should equal one unit of computational gas. We bound the maximum /// computational time of any given transaction at roughly 20 seconds. We want this number and /// `MAX_PRICE_PER_GAS_UNIT` to always satisfy the inequality that /// MAXIMUM_NUMBER_OF_GAS_UNITS * MAX_PRICE_PER_GAS_UNIT < min(u64::MAX, GasUnits<GasCarrier>::MAX) /// NB: The bound is set quite high since custom scripts aren't allowed except from predefined /// and vetted senders. pub maximum_number_of_gas_units: GasUnits<GasCarrier>, /// The minimum gas price that a transaction can be submitted with. pub min_price_per_gas_unit: GasPrice<GasCarrier>, /// The maximum gas unit price that a transaction can be submitted with. pub max_price_per_gas_unit: GasPrice<GasCarrier>, pub max_transaction_size_in_bytes: GasCarrier, pub gas_unit_scaling_factor: GasCarrier, pub default_account_size: AbstractMemorySize<GasCarrier>, } impl GasConstants { pub fn to_internal_units(&self, units: GasUnits<GasCarrier>) -> InternalGasUnits<GasCarrier> { InternalGasUnits::new(units.get() * self.gas_unit_scaling_factor) } pub fn to_external_units(&self, units: InternalGasUnits<GasCarrier>) -> GasUnits<GasCarrier> { GasUnits::new(units.get() / self.gas_unit_scaling_factor) } } impl Default for GasConstants { fn default() -> Self { Self { global_memory_per_byte_cost: InternalGasUnits(4), global_memory_per_byte_write_cost: InternalGasUnits(9), min_transaction_gas_units: InternalGasUnits(600), large_transaction_cutoff: LARGE_TRANSACTION_CUTOFF, intrinsic_gas_per_byte: InternalGasUnits(8), maximum_number_of_gas_units: GasUnits(4_000_000), min_price_per_gas_unit: GasPrice(0), max_price_per_gas_unit: GasPrice(10_000), max_transaction_size_in_bytes: MAX_TRANSACTION_SIZE_IN_BYTES, gas_unit_scaling_factor: 1000, default_account_size: DEFAULT_ACCOUNT_SIZE, } } } /// The cost tables, keyed by the serialized form of the bytecode instruction. We use the /// serialized form as opposed to the instruction enum itself as the key since this will be the /// on-chain representation of bytecode instructions in the future. #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct CostTable { pub instruction_table: Vec<GasCost>, pub native_table: Vec<GasCost>, pub gas_constants: GasConstants, } impl CostTable { #[inline] pub fn instruction_cost(&self, instr_index: u8) -> &GasCost { precondition!(instr_index > 0 && instr_index <= (self.instruction_table.len() as u8)); &self.instruction_table[(instr_index - 1) as usize] } #[inline] pub fn native_cost(&self, native_index: u8) -> &GasCost { precondition!(native_index < (self.native_table.len() as u8)); &self.native_table[native_index as usize] } } /// The `GasCost` tracks: /// - instruction cost: how much time/computational power is needed to perform the instruction /// - memory cost: how much memory is required for the instruction, and storage overhead #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct GasCost { pub instruction_gas: InternalGasUnits<GasCarrier>, pub memory_gas: InternalGasUnits<GasCarrier>, } impl GasCost { pub fn new(instr_gas: GasCarrier, mem_gas: GasCarrier) -> Self { Self { instruction_gas: InternalGasUnits::new(instr_gas), memory_gas: InternalGasUnits::new(mem_gas), } } /// Convert a GasCost to a total gas charge in `InternalGasUnits`. #[inline] pub fn total(&self) -> InternalGasUnits<GasCarrier> { self.instruction_gas.add(self.memory_gas) } }
{ self.map2(right, Add::add) }
identifier_body
list-view.ts
import Service from '@ember/service'; import Store from '@ember-data/store'; import FieldInformationService from '@getflights/ember-field-components/services/field-information'; import { inject as service } from '@ember/service'; import { assert } from '@ember/debug'; import { isBlank } from '@ember/utils'; import ListViewModel from '@getflights/ember-mist-components/models/list-view'; // A ModelListview is an object that can be defined as a static POJO on the Model itself export interface ListViewInterface { rows?: number; columns: string[]; sortOrder?: { field: string; dir: 'ASC' | 'DESC'; }; } export default class ListViewService extends Service { @service store!: Store; @service storage!: any; @service router!: any; @service fieldInformation!: FieldInformationService; /** * Find the List View in the store, or if not found the default list view on the model will be returned. * * @param modelName The name of the model you want a list view for * @param key The key of the list view (can be numeric, an id from the store, or All) */ getListViewByKey(modelName: string, key: string | number): ListViewInterface { if (this.store.hasRecordForId('list-view', key)) { const listViewModel = <ListViewModel>( this.store.peekRecord('list-view', key) ); return this.transformListViewModelToInterface(listViewModel); } return this.getDefaultListView(modelName); } /** * Transforms the given list view model, to an POJO following the ListViewInterface * @param model The model you wish to transform */ transformListViewModelToInterface(model: ListViewModel): ListViewInterface { const returnValue: ListViewInterface = { columns: [], }; returnValue.rows = model.rows; model .hasMany('columns') .ids() .forEach((fieldId) => { const fieldArray = fieldId.toString().split('.'); fieldArray.shift(); returnValue.columns.push(fieldArray.join('.')); }); returnValue.sortOrder = model.sortOrder; return returnValue; } /** * Returns the default list view for the model * @param modelName For the model */ getDefaultListView(modelName: string): ListViewInterface { return this.getModelListView(modelName, 'default'); } /** * Returns a model list view by name * @param modelName For the model */ getModelListView(modelName: string, listViewName: string): ListViewInterface { const modelClass = this.fieldInformation.getModelClass(modelName); assert( `No list view (${listViewName}) defined on the modelclass ${modelName}`, modelClass.hasOwnProperty('settings') && modelClass.settings.hasOwnProperty('listViews') && modelClass.settings.listViews.hasOwnProperty(listViewName) ); return modelClass.settings.listViews[listViewName]; } /** * Returns the active list view for the current route */ getActiveListViewForCurrentRoute(modelName: string): ListViewInterface { const key = this.getActiveListViewKeyForCurrentRoute(modelName); return this.getListViewByKey(modelName, key); } /** * Returns the list view that should be selected for the current route * @param modelName The name of the model */ getActiveListViewKeyForCurrentRoute(modelName: string): string | number { const currentRoute = this.router.currentRouteName; return this.getActiveListViewForRoute(modelName, currentRoute); } /** * Returns the list view that should be selected * @param modelName The name of the model * @param routeName The name of the route */
( modelName: string, routeName: string ): string | number { const listViewSelections = this.storage.get('listViewSelections'); let selection = 'All'; if ( !isBlank(listViewSelections) && listViewSelections.hasOwnProperty(routeName) && listViewSelections[routeName].hasOwnProperty(modelName) ) { selection = listViewSelections[routeName][modelName]; } return selection; } /** * Sets the list view for the current route */ setListViewSelectionForCurrentRoute( modelName: string, selection: number | string ): void { this.setListViewSelectionForRoute( modelName, selection, this.router.currentRouteName ); } /** * Sets the list view selection and saves it in local storage * @param modelName The model name * @param selection the new selection * @param route the route */ setListViewSelectionForRoute( modelName: string, selection: number | string, route: string ): void { let listViewSelections = this.storage.get('listViewSelections'); if (isBlank(listViewSelections)) { listViewSelections = {}; } if (!listViewSelections.hasOwnProperty(route)) { listViewSelections[route] = {}; } listViewSelections[route][modelName] = selection; this.storage.set('listViewSelections', listViewSelections); } }
getActiveListViewForRoute
identifier_name
list-view.ts
import Service from '@ember/service'; import Store from '@ember-data/store'; import FieldInformationService from '@getflights/ember-field-components/services/field-information'; import { inject as service } from '@ember/service'; import { assert } from '@ember/debug'; import { isBlank } from '@ember/utils'; import ListViewModel from '@getflights/ember-mist-components/models/list-view'; // A ModelListview is an object that can be defined as a static POJO on the Model itself export interface ListViewInterface { rows?: number; columns: string[]; sortOrder?: { field: string; dir: 'ASC' | 'DESC'; }; } export default class ListViewService extends Service { @service store!: Store; @service storage!: any; @service router!: any; @service fieldInformation!: FieldInformationService; /** * Find the List View in the store, or if not found the default list view on the model will be returned. * * @param modelName The name of the model you want a list view for * @param key The key of the list view (can be numeric, an id from the store, or All) */ getListViewByKey(modelName: string, key: string | number): ListViewInterface { if (this.store.hasRecordForId('list-view', key)) { const listViewModel = <ListViewModel>( this.store.peekRecord('list-view', key) ); return this.transformListViewModelToInterface(listViewModel); } return this.getDefaultListView(modelName); } /** * Transforms the given list view model, to an POJO following the ListViewInterface * @param model The model you wish to transform */ transformListViewModelToInterface(model: ListViewModel): ListViewInterface { const returnValue: ListViewInterface = { columns: [], }; returnValue.rows = model.rows; model .hasMany('columns') .ids() .forEach((fieldId) => { const fieldArray = fieldId.toString().split('.'); fieldArray.shift(); returnValue.columns.push(fieldArray.join('.')); }); returnValue.sortOrder = model.sortOrder; return returnValue; } /** * Returns the default list view for the model * @param modelName For the model */ getDefaultListView(modelName: string): ListViewInterface { return this.getModelListView(modelName, 'default'); } /** * Returns a model list view by name * @param modelName For the model */ getModelListView(modelName: string, listViewName: string): ListViewInterface { const modelClass = this.fieldInformation.getModelClass(modelName); assert( `No list view (${listViewName}) defined on the modelclass ${modelName}`, modelClass.hasOwnProperty('settings') && modelClass.settings.hasOwnProperty('listViews') && modelClass.settings.listViews.hasOwnProperty(listViewName) ); return modelClass.settings.listViews[listViewName]; } /** * Returns the active list view for the current route */ getActiveListViewForCurrentRoute(modelName: string): ListViewInterface { const key = this.getActiveListViewKeyForCurrentRoute(modelName); return this.getListViewByKey(modelName, key); } /** * Returns the list view that should be selected for the current route * @param modelName The name of the model */ getActiveListViewKeyForCurrentRoute(modelName: string): string | number { const currentRoute = this.router.currentRouteName; return this.getActiveListViewForRoute(modelName, currentRoute); } /** * Returns the list view that should be selected * @param modelName The name of the model * @param routeName The name of the route */ getActiveListViewForRoute( modelName: string, routeName: string ): string | number { const listViewSelections = this.storage.get('listViewSelections'); let selection = 'All'; if ( !isBlank(listViewSelections) && listViewSelections.hasOwnProperty(routeName) && listViewSelections[routeName].hasOwnProperty(modelName) ) { selection = listViewSelections[routeName][modelName]; } return selection; } /** * Sets the list view for the current route */ setListViewSelectionForCurrentRoute( modelName: string, selection: number | string ): void { this.setListViewSelectionForRoute( modelName, selection, this.router.currentRouteName ); } /** * Sets the list view selection and saves it in local storage
* @param route the route */ setListViewSelectionForRoute( modelName: string, selection: number | string, route: string ): void { let listViewSelections = this.storage.get('listViewSelections'); if (isBlank(listViewSelections)) { listViewSelections = {}; } if (!listViewSelections.hasOwnProperty(route)) { listViewSelections[route] = {}; } listViewSelections[route][modelName] = selection; this.storage.set('listViewSelections', listViewSelections); } }
* @param modelName The model name * @param selection the new selection
random_line_split
list-view.ts
import Service from '@ember/service'; import Store from '@ember-data/store'; import FieldInformationService from '@getflights/ember-field-components/services/field-information'; import { inject as service } from '@ember/service'; import { assert } from '@ember/debug'; import { isBlank } from '@ember/utils'; import ListViewModel from '@getflights/ember-mist-components/models/list-view'; // A ModelListview is an object that can be defined as a static POJO on the Model itself export interface ListViewInterface { rows?: number; columns: string[]; sortOrder?: { field: string; dir: 'ASC' | 'DESC'; }; } export default class ListViewService extends Service { @service store!: Store; @service storage!: any; @service router!: any; @service fieldInformation!: FieldInformationService; /** * Find the List View in the store, or if not found the default list view on the model will be returned. * * @param modelName The name of the model you want a list view for * @param key The key of the list view (can be numeric, an id from the store, or All) */ getListViewByKey(modelName: string, key: string | number): ListViewInterface { if (this.store.hasRecordForId('list-view', key)) { const listViewModel = <ListViewModel>( this.store.peekRecord('list-view', key) ); return this.transformListViewModelToInterface(listViewModel); } return this.getDefaultListView(modelName); } /** * Transforms the given list view model, to an POJO following the ListViewInterface * @param model The model you wish to transform */ transformListViewModelToInterface(model: ListViewModel): ListViewInterface { const returnValue: ListViewInterface = { columns: [], }; returnValue.rows = model.rows; model .hasMany('columns') .ids() .forEach((fieldId) => { const fieldArray = fieldId.toString().split('.'); fieldArray.shift(); returnValue.columns.push(fieldArray.join('.')); }); returnValue.sortOrder = model.sortOrder; return returnValue; } /** * Returns the default list view for the model * @param modelName For the model */ getDefaultListView(modelName: string): ListViewInterface { return this.getModelListView(modelName, 'default'); } /** * Returns a model list view by name * @param modelName For the model */ getModelListView(modelName: string, listViewName: string): ListViewInterface { const modelClass = this.fieldInformation.getModelClass(modelName); assert( `No list view (${listViewName}) defined on the modelclass ${modelName}`, modelClass.hasOwnProperty('settings') && modelClass.settings.hasOwnProperty('listViews') && modelClass.settings.listViews.hasOwnProperty(listViewName) ); return modelClass.settings.listViews[listViewName]; } /** * Returns the active list view for the current route */ getActiveListViewForCurrentRoute(modelName: string): ListViewInterface { const key = this.getActiveListViewKeyForCurrentRoute(modelName); return this.getListViewByKey(modelName, key); } /** * Returns the list view that should be selected for the current route * @param modelName The name of the model */ getActiveListViewKeyForCurrentRoute(modelName: string): string | number { const currentRoute = this.router.currentRouteName; return this.getActiveListViewForRoute(modelName, currentRoute); } /** * Returns the list view that should be selected * @param modelName The name of the model * @param routeName The name of the route */ getActiveListViewForRoute( modelName: string, routeName: string ): string | number { const listViewSelections = this.storage.get('listViewSelections'); let selection = 'All'; if ( !isBlank(listViewSelections) && listViewSelections.hasOwnProperty(routeName) && listViewSelections[routeName].hasOwnProperty(modelName) )
return selection; } /** * Sets the list view for the current route */ setListViewSelectionForCurrentRoute( modelName: string, selection: number | string ): void { this.setListViewSelectionForRoute( modelName, selection, this.router.currentRouteName ); } /** * Sets the list view selection and saves it in local storage * @param modelName The model name * @param selection the new selection * @param route the route */ setListViewSelectionForRoute( modelName: string, selection: number | string, route: string ): void { let listViewSelections = this.storage.get('listViewSelections'); if (isBlank(listViewSelections)) { listViewSelections = {}; } if (!listViewSelections.hasOwnProperty(route)) { listViewSelections[route] = {}; } listViewSelections[route][modelName] = selection; this.storage.set('listViewSelections', listViewSelections); } }
{ selection = listViewSelections[routeName][modelName]; }
conditional_block
list-view.ts
import Service from '@ember/service'; import Store from '@ember-data/store'; import FieldInformationService from '@getflights/ember-field-components/services/field-information'; import { inject as service } from '@ember/service'; import { assert } from '@ember/debug'; import { isBlank } from '@ember/utils'; import ListViewModel from '@getflights/ember-mist-components/models/list-view'; // A ModelListview is an object that can be defined as a static POJO on the Model itself export interface ListViewInterface { rows?: number; columns: string[]; sortOrder?: { field: string; dir: 'ASC' | 'DESC'; }; } export default class ListViewService extends Service { @service store!: Store; @service storage!: any; @service router!: any; @service fieldInformation!: FieldInformationService; /** * Find the List View in the store, or if not found the default list view on the model will be returned. * * @param modelName The name of the model you want a list view for * @param key The key of the list view (can be numeric, an id from the store, or All) */ getListViewByKey(modelName: string, key: string | number): ListViewInterface { if (this.store.hasRecordForId('list-view', key)) { const listViewModel = <ListViewModel>( this.store.peekRecord('list-view', key) ); return this.transformListViewModelToInterface(listViewModel); } return this.getDefaultListView(modelName); } /** * Transforms the given list view model, to an POJO following the ListViewInterface * @param model The model you wish to transform */ transformListViewModelToInterface(model: ListViewModel): ListViewInterface { const returnValue: ListViewInterface = { columns: [], }; returnValue.rows = model.rows; model .hasMany('columns') .ids() .forEach((fieldId) => { const fieldArray = fieldId.toString().split('.'); fieldArray.shift(); returnValue.columns.push(fieldArray.join('.')); }); returnValue.sortOrder = model.sortOrder; return returnValue; } /** * Returns the default list view for the model * @param modelName For the model */ getDefaultListView(modelName: string): ListViewInterface { return this.getModelListView(modelName, 'default'); } /** * Returns a model list view by name * @param modelName For the model */ getModelListView(modelName: string, listViewName: string): ListViewInterface
/** * Returns the active list view for the current route */ getActiveListViewForCurrentRoute(modelName: string): ListViewInterface { const key = this.getActiveListViewKeyForCurrentRoute(modelName); return this.getListViewByKey(modelName, key); } /** * Returns the list view that should be selected for the current route * @param modelName The name of the model */ getActiveListViewKeyForCurrentRoute(modelName: string): string | number { const currentRoute = this.router.currentRouteName; return this.getActiveListViewForRoute(modelName, currentRoute); } /** * Returns the list view that should be selected * @param modelName The name of the model * @param routeName The name of the route */ getActiveListViewForRoute( modelName: string, routeName: string ): string | number { const listViewSelections = this.storage.get('listViewSelections'); let selection = 'All'; if ( !isBlank(listViewSelections) && listViewSelections.hasOwnProperty(routeName) && listViewSelections[routeName].hasOwnProperty(modelName) ) { selection = listViewSelections[routeName][modelName]; } return selection; } /** * Sets the list view for the current route */ setListViewSelectionForCurrentRoute( modelName: string, selection: number | string ): void { this.setListViewSelectionForRoute( modelName, selection, this.router.currentRouteName ); } /** * Sets the list view selection and saves it in local storage * @param modelName The model name * @param selection the new selection * @param route the route */ setListViewSelectionForRoute( modelName: string, selection: number | string, route: string ): void { let listViewSelections = this.storage.get('listViewSelections'); if (isBlank(listViewSelections)) { listViewSelections = {}; } if (!listViewSelections.hasOwnProperty(route)) { listViewSelections[route] = {}; } listViewSelections[route][modelName] = selection; this.storage.set('listViewSelections', listViewSelections); } }
{ const modelClass = this.fieldInformation.getModelClass(modelName); assert( `No list view (${listViewName}) defined on the modelclass ${modelName}`, modelClass.hasOwnProperty('settings') && modelClass.settings.hasOwnProperty('listViews') && modelClass.settings.listViews.hasOwnProperty(listViewName) ); return modelClass.settings.listViews[listViewName]; }
identifier_body
async_test.py
# import asyncio # # async def compute(x, y): # print("Compute %s + %s ..." % (x, y)) # await asyncio.sleep(1.0) # return x + y #
# for i in range(10): # result = await compute(x, y) # print("%s + %s = %s" % (x, y, result)) # # loop = asyncio.get_event_loop() # loop.run_until_complete(print_sum(1,2)) # asyncio.ensure_future(print_sum(1, 2)) # asyncio.ensure_future(print_sum(3, 4)) # asyncio.ensure_future(print_sum(5, 6)) # loop.run_forever() import asyncio async def display_date(who, num): i = 0 while True: if i > num: return print('{}: Before loop {}'.format(who, i)) await asyncio.sleep(1) i += 1 loop = asyncio.get_event_loop() asyncio.ensure_future(display_date('AAA', 4)) asyncio.ensure_future(display_date('BBB', 6)) loop.run_forever()
# async def print_sum(x, y):
random_line_split
async_test.py
# import asyncio # # async def compute(x, y): # print("Compute %s + %s ..." % (x, y)) # await asyncio.sleep(1.0) # return x + y # # async def print_sum(x, y): # for i in range(10): # result = await compute(x, y) # print("%s + %s = %s" % (x, y, result)) # # loop = asyncio.get_event_loop() # loop.run_until_complete(print_sum(1,2)) # asyncio.ensure_future(print_sum(1, 2)) # asyncio.ensure_future(print_sum(3, 4)) # asyncio.ensure_future(print_sum(5, 6)) # loop.run_forever() import asyncio async def
(who, num): i = 0 while True: if i > num: return print('{}: Before loop {}'.format(who, i)) await asyncio.sleep(1) i += 1 loop = asyncio.get_event_loop() asyncio.ensure_future(display_date('AAA', 4)) asyncio.ensure_future(display_date('BBB', 6)) loop.run_forever()
display_date
identifier_name
async_test.py
# import asyncio # # async def compute(x, y): # print("Compute %s + %s ..." % (x, y)) # await asyncio.sleep(1.0) # return x + y # # async def print_sum(x, y): # for i in range(10): # result = await compute(x, y) # print("%s + %s = %s" % (x, y, result)) # # loop = asyncio.get_event_loop() # loop.run_until_complete(print_sum(1,2)) # asyncio.ensure_future(print_sum(1, 2)) # asyncio.ensure_future(print_sum(3, 4)) # asyncio.ensure_future(print_sum(5, 6)) # loop.run_forever() import asyncio async def display_date(who, num):
loop = asyncio.get_event_loop() asyncio.ensure_future(display_date('AAA', 4)) asyncio.ensure_future(display_date('BBB', 6)) loop.run_forever()
i = 0 while True: if i > num: return print('{}: Before loop {}'.format(who, i)) await asyncio.sleep(1) i += 1
identifier_body
async_test.py
# import asyncio # # async def compute(x, y): # print("Compute %s + %s ..." % (x, y)) # await asyncio.sleep(1.0) # return x + y # # async def print_sum(x, y): # for i in range(10): # result = await compute(x, y) # print("%s + %s = %s" % (x, y, result)) # # loop = asyncio.get_event_loop() # loop.run_until_complete(print_sum(1,2)) # asyncio.ensure_future(print_sum(1, 2)) # asyncio.ensure_future(print_sum(3, 4)) # asyncio.ensure_future(print_sum(5, 6)) # loop.run_forever() import asyncio async def display_date(who, num): i = 0 while True: if i > num:
print('{}: Before loop {}'.format(who, i)) await asyncio.sleep(1) i += 1 loop = asyncio.get_event_loop() asyncio.ensure_future(display_date('AAA', 4)) asyncio.ensure_future(display_date('BBB', 6)) loop.run_forever()
return
conditional_block
per_worker_gaussian_noise.py
from gym.spaces import Space from typing import Optional from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise from ray.rllib.utils.schedules import ConstantSchedule class PerWorkerGaussianNoise(GaussianNoise): """A per-worker Gaussian noise class for distributed algorithms. Sets the `scale` schedules of individual workers to a constant: 0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7) See Ape-X paper. """ def
(self, action_space: Space, *, framework: Optional[str], num_workers: Optional[int], worker_index: Optional[int], **kwargs): """ Args: action_space (Space): The gym action space used by the environment. num_workers (Optional[int]): The overall number of workers used. worker_index (Optional[int]): The index of the Worker using this Exploration. framework (Optional[str]): One of None, "tf", "torch". """ scale_schedule = None # Use a fixed, different epsilon per worker. See: Ape-X paper. if num_workers > 0: if worker_index > 0: num_workers_minus_1 = float(num_workers - 1) \ if num_workers > 1 else 1.0 exponent = (1 + (worker_index / num_workers_minus_1) * 7) scale_schedule = ConstantSchedule( 0.4**exponent, framework=framework) # Local worker should have zero exploration so that eval # rollouts run properly. else: scale_schedule = ConstantSchedule(0.0, framework=framework) super().__init__( action_space, scale_schedule=scale_schedule, framework=framework, **kwargs)
__init__
identifier_name
per_worker_gaussian_noise.py
from gym.spaces import Space from typing import Optional from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise from ray.rllib.utils.schedules import ConstantSchedule class PerWorkerGaussianNoise(GaussianNoise):
"""A per-worker Gaussian noise class for distributed algorithms. Sets the `scale` schedules of individual workers to a constant: 0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7) See Ape-X paper. """ def __init__(self, action_space: Space, *, framework: Optional[str], num_workers: Optional[int], worker_index: Optional[int], **kwargs): """ Args: action_space (Space): The gym action space used by the environment. num_workers (Optional[int]): The overall number of workers used. worker_index (Optional[int]): The index of the Worker using this Exploration. framework (Optional[str]): One of None, "tf", "torch". """ scale_schedule = None # Use a fixed, different epsilon per worker. See: Ape-X paper. if num_workers > 0: if worker_index > 0: num_workers_minus_1 = float(num_workers - 1) \ if num_workers > 1 else 1.0 exponent = (1 + (worker_index / num_workers_minus_1) * 7) scale_schedule = ConstantSchedule( 0.4**exponent, framework=framework) # Local worker should have zero exploration so that eval # rollouts run properly. else: scale_schedule = ConstantSchedule(0.0, framework=framework) super().__init__( action_space, scale_schedule=scale_schedule, framework=framework, **kwargs)
identifier_body
per_worker_gaussian_noise.py
from gym.spaces import Space from typing import Optional from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise from ray.rllib.utils.schedules import ConstantSchedule class PerWorkerGaussianNoise(GaussianNoise):
See Ape-X paper. """ def __init__(self, action_space: Space, *, framework: Optional[str], num_workers: Optional[int], worker_index: Optional[int], **kwargs): """ Args: action_space (Space): The gym action space used by the environment. num_workers (Optional[int]): The overall number of workers used. worker_index (Optional[int]): The index of the Worker using this Exploration. framework (Optional[str]): One of None, "tf", "torch". """ scale_schedule = None # Use a fixed, different epsilon per worker. See: Ape-X paper. if num_workers > 0: if worker_index > 0: num_workers_minus_1 = float(num_workers - 1) \ if num_workers > 1 else 1.0 exponent = (1 + (worker_index / num_workers_minus_1) * 7) scale_schedule = ConstantSchedule( 0.4**exponent, framework=framework) # Local worker should have zero exploration so that eval # rollouts run properly. else: scale_schedule = ConstantSchedule(0.0, framework=framework) super().__init__( action_space, scale_schedule=scale_schedule, framework=framework, **kwargs)
"""A per-worker Gaussian noise class for distributed algorithms. Sets the `scale` schedules of individual workers to a constant: 0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7)
random_line_split
per_worker_gaussian_noise.py
from gym.spaces import Space from typing import Optional from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise from ray.rllib.utils.schedules import ConstantSchedule class PerWorkerGaussianNoise(GaussianNoise): """A per-worker Gaussian noise class for distributed algorithms. Sets the `scale` schedules of individual workers to a constant: 0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7) See Ape-X paper. """ def __init__(self, action_space: Space, *, framework: Optional[str], num_workers: Optional[int], worker_index: Optional[int], **kwargs): """ Args: action_space (Space): The gym action space used by the environment. num_workers (Optional[int]): The overall number of workers used. worker_index (Optional[int]): The index of the Worker using this Exploration. framework (Optional[str]): One of None, "tf", "torch". """ scale_schedule = None # Use a fixed, different epsilon per worker. See: Ape-X paper. if num_workers > 0: if worker_index > 0:
# Local worker should have zero exploration so that eval # rollouts run properly. else: scale_schedule = ConstantSchedule(0.0, framework=framework) super().__init__( action_space, scale_schedule=scale_schedule, framework=framework, **kwargs)
num_workers_minus_1 = float(num_workers - 1) \ if num_workers > 1 else 1.0 exponent = (1 + (worker_index / num_workers_minus_1) * 7) scale_schedule = ConstantSchedule( 0.4**exponent, framework=framework)
conditional_block
results.py
""" query or callproc Results """ import logging import psycopg2 LOGGER = logging.getLogger(__name__) class Results(object): """The :py:class:`Results` class contains the results returned from :py:meth:`Session.query <queries.Session.query>` and :py:meth:`Session.callproc <queries.Session.callproc>`. It is able to act as an iterator and provides many different methods for accessing the information about and results from a query. :param psycopg2.extensions.cursor cursor: The cursor for the results """ def __init__(self, cursor): self.cursor = cursor def __getitem__(self, item): """Fetch an individual row from the result set :rtype: mixed :raises: IndexError """ try: self.cursor.scroll(item, 'absolute') except psycopg2.ProgrammingError: raise IndexError('No such row') else: return self.cursor.fetchone() def __iter__(self): """Iterate through the result set :rtype: mixed """ if self.cursor.rowcount: self._rewind() for row in self.cursor: yield row def __len__(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0 def __nonzero__(self):
def __bool__(self): return self.__nonzero__() def __repr__(self): return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self)) def as_dict(self): """Return a single row result as a dictionary. If the results contain multiple rows, a :py:class:`ValueError` will be raised. :return: dict :raises: ValueError """ if not self.cursor.rowcount: return {} self._rewind() if self.cursor.rowcount == 1: return dict(self.cursor.fetchone()) else: raise ValueError('More than one row') def count(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount def free(self): """Used in asynchronous sessions for freeing results and their locked connections. """ LOGGER.debug('Invoking synchronous free has no effect') def items(self): """Return all of the rows that are in the result set. :rtype: list """ if not self.cursor.rowcount: return [] self.cursor.scroll(0, 'absolute') return self.cursor.fetchall() @property def rownumber(self): """Return the current offset of the result set :rtype: int """ return self.cursor.rownumber @property def query(self): """Return a read-only value of the query that was submitted to PostgreSQL. :rtype: str """ return self.cursor.query @property def status(self): """Return the status message returned by PostgreSQL after the query was executed. :rtype: str """ return self.cursor.statusmessage def _rewind(self): """Rewind the cursor to the first row""" self.cursor.scroll(0, 'absolute')
return bool(self.cursor.rowcount)
identifier_body
results.py
""" query or callproc Results """ import logging import psycopg2 LOGGER = logging.getLogger(__name__) class Results(object): """The :py:class:`Results` class contains the results returned from :py:meth:`Session.query <queries.Session.query>` and :py:meth:`Session.callproc <queries.Session.callproc>`. It is able to act as an iterator and provides many different methods for accessing the information about and results from a query. :param psycopg2.extensions.cursor cursor: The cursor for the results """ def __init__(self, cursor): self.cursor = cursor def __getitem__(self, item): """Fetch an individual row from the result set :rtype: mixed :raises: IndexError """ try: self.cursor.scroll(item, 'absolute') except psycopg2.ProgrammingError: raise IndexError('No such row') else: return self.cursor.fetchone() def __iter__(self): """Iterate through the result set :rtype: mixed """ if self.cursor.rowcount:
def __len__(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0 def __nonzero__(self): return bool(self.cursor.rowcount) def __bool__(self): return self.__nonzero__() def __repr__(self): return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self)) def as_dict(self): """Return a single row result as a dictionary. If the results contain multiple rows, a :py:class:`ValueError` will be raised. :return: dict :raises: ValueError """ if not self.cursor.rowcount: return {} self._rewind() if self.cursor.rowcount == 1: return dict(self.cursor.fetchone()) else: raise ValueError('More than one row') def count(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount def free(self): """Used in asynchronous sessions for freeing results and their locked connections. """ LOGGER.debug('Invoking synchronous free has no effect') def items(self): """Return all of the rows that are in the result set. :rtype: list """ if not self.cursor.rowcount: return [] self.cursor.scroll(0, 'absolute') return self.cursor.fetchall() @property def rownumber(self): """Return the current offset of the result set :rtype: int """ return self.cursor.rownumber @property def query(self): """Return a read-only value of the query that was submitted to PostgreSQL. :rtype: str """ return self.cursor.query @property def status(self): """Return the status message returned by PostgreSQL after the query was executed. :rtype: str """ return self.cursor.statusmessage def _rewind(self): """Rewind the cursor to the first row""" self.cursor.scroll(0, 'absolute')
self._rewind() for row in self.cursor: yield row
conditional_block
results.py
""" query or callproc Results """ import logging import psycopg2 LOGGER = logging.getLogger(__name__) class Results(object): """The :py:class:`Results` class contains the results returned from :py:meth:`Session.query <queries.Session.query>` and :py:meth:`Session.callproc <queries.Session.callproc>`. It is able to act as an iterator and provides many different methods for accessing the information about and results from a query. :param psycopg2.extensions.cursor cursor: The cursor for the results """ def __init__(self, cursor): self.cursor = cursor def __getitem__(self, item): """Fetch an individual row from the result set :rtype: mixed :raises: IndexError """ try: self.cursor.scroll(item, 'absolute') except psycopg2.ProgrammingError: raise IndexError('No such row') else: return self.cursor.fetchone() def __iter__(self): """Iterate through the result set :rtype: mixed """ if self.cursor.rowcount: self._rewind() for row in self.cursor: yield row def __len__(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0 def __nonzero__(self): return bool(self.cursor.rowcount) def __bool__(self): return self.__nonzero__() def __repr__(self): return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self)) def as_dict(self): """Return a single row result as a dictionary. If the results contain multiple rows, a :py:class:`ValueError` will be raised. :return: dict :raises: ValueError """ if not self.cursor.rowcount: return {} self._rewind() if self.cursor.rowcount == 1: return dict(self.cursor.fetchone()) else: raise ValueError('More than one row') def count(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount def free(self): """Used in asynchronous sessions for freeing results and their locked connections. """ LOGGER.debug('Invoking synchronous free has no effect') def items(self): """Return all of the rows that are in the result set. :rtype: list """ if not self.cursor.rowcount: return [] self.cursor.scroll(0, 'absolute') return self.cursor.fetchall() @property def rownumber(self): """Return the current offset of the result set :rtype: int """ return self.cursor.rownumber @property def query(self): """Return a read-only value of the query that was submitted to PostgreSQL. :rtype: str """
"""Return the status message returned by PostgreSQL after the query was executed. :rtype: str """ return self.cursor.statusmessage def _rewind(self): """Rewind the cursor to the first row""" self.cursor.scroll(0, 'absolute')
return self.cursor.query @property def status(self):
random_line_split
results.py
""" query or callproc Results """ import logging import psycopg2 LOGGER = logging.getLogger(__name__) class Results(object): """The :py:class:`Results` class contains the results returned from :py:meth:`Session.query <queries.Session.query>` and :py:meth:`Session.callproc <queries.Session.callproc>`. It is able to act as an iterator and provides many different methods for accessing the information about and results from a query. :param psycopg2.extensions.cursor cursor: The cursor for the results """ def __init__(self, cursor): self.cursor = cursor def __getitem__(self, item): """Fetch an individual row from the result set :rtype: mixed :raises: IndexError """ try: self.cursor.scroll(item, 'absolute') except psycopg2.ProgrammingError: raise IndexError('No such row') else: return self.cursor.fetchone() def __iter__(self): """Iterate through the result set :rtype: mixed """ if self.cursor.rowcount: self._rewind() for row in self.cursor: yield row def __len__(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0 def __nonzero__(self): return bool(self.cursor.rowcount) def __bool__(self): return self.__nonzero__() def __repr__(self): return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self)) def as_dict(self): """Return a single row result as a dictionary. If the results contain multiple rows, a :py:class:`ValueError` will be raised. :return: dict :raises: ValueError """ if not self.cursor.rowcount: return {} self._rewind() if self.cursor.rowcount == 1: return dict(self.cursor.fetchone()) else: raise ValueError('More than one row') def count(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount def free(self): """Used in asynchronous sessions for freeing results and their locked connections. """ LOGGER.debug('Invoking synchronous free has no effect') def items(self): """Return all of the rows that are in the result set. :rtype: list """ if not self.cursor.rowcount: return [] self.cursor.scroll(0, 'absolute') return self.cursor.fetchall() @property def rownumber(self): """Return the current offset of the result set :rtype: int """ return self.cursor.rownumber @property def query(self): """Return a read-only value of the query that was submitted to PostgreSQL. :rtype: str """ return self.cursor.query @property def
(self): """Return the status message returned by PostgreSQL after the query was executed. :rtype: str """ return self.cursor.statusmessage def _rewind(self): """Rewind the cursor to the first row""" self.cursor.scroll(0, 'absolute')
status
identifier_name
utils.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ComponentFactoryResolver, Injector, Type} from '@angular/core'; /** * Provide methods for scheduling the execution of a callback. */ export const scheduler = { /** * Schedule a callback to be called after some delay. * * Returns a function that when executed will cancel the scheduled function. */
(taskFn: () => void, delay: number): () => void { const id = setTimeout(taskFn, delay); return () => clearTimeout(id); }, /** * Schedule a callback to be called before the next render. * (If `window.requestAnimationFrame()` is not available, use `scheduler.schedule()` instead.) * * Returns a function that when executed will cancel the scheduled function. */ scheduleBeforeRender(taskFn: () => void): () => void { // TODO(gkalpak): Implement a better way of accessing `requestAnimationFrame()` // (e.g. accounting for vendor prefix, SSR-compatibility, etc). if (typeof window === 'undefined') { // For SSR just schedule immediately. return scheduler.schedule(taskFn, 0); } if (typeof window.requestAnimationFrame === 'undefined') { const frameMs = 16; return scheduler.schedule(taskFn, frameMs); } const id = window.requestAnimationFrame(taskFn); return () => window.cancelAnimationFrame(id); }, }; /** * Convert a camelCased string to kebab-cased. */ export function camelToDashCase(input: string): string { return input.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`); } /** * Check whether the input is an `Element`. */ export function isElement(node: Node|null): node is Element { return !!node && node.nodeType === Node.ELEMENT_NODE; } /** * Check whether the input is a function. */ export function isFunction(value: any): value is Function { return typeof value === 'function'; } /** * Convert a kebab-cased string to camelCased. */ export function kebabToCamelCase(input: string): string { return input.replace(/-([a-z\d])/g, (_, char) => char.toUpperCase()); } let _matches: (this: any, selector: string) => boolean; /** * Check whether an `Element` matches a CSS selector. * NOTE: this is duplicated from @angular/upgrade, and can * be consolidated in the future */ export function matchesSelector(el: any, selector: string): boolean { if (!_matches) { const elProto = <any>Element.prototype; _matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector; } return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false; } /** * Test two values for strict equality, accounting for the fact that `NaN !== NaN`. */ export function strictEquals(value1: any, value2: any): boolean { return value1 === value2 || (value1 !== value1 && value2 !== value2); } /** Gets a map of default set of attributes to observe and the properties they affect. */ export function getDefaultAttributeToPropertyInputs( inputs: {propName: string, templateName: string}[]) { const attributeToPropertyInputs: {[key: string]: string} = {}; inputs.forEach(({propName, templateName}) => { attributeToPropertyInputs[camelToDashCase(templateName)] = propName; }); return attributeToPropertyInputs; } /** * Gets a component's set of inputs. Uses the injector to get the component factory where the inputs * are defined. */ export function getComponentInputs( component: Type<any>, injector: Injector): {propName: string, templateName: string}[] { const componentFactoryResolver: ComponentFactoryResolver = injector.get(ComponentFactoryResolver); const componentFactory = componentFactoryResolver.resolveComponentFactory(component); return componentFactory.inputs; }
schedule
identifier_name
utils.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ComponentFactoryResolver, Injector, Type} from '@angular/core'; /** * Provide methods for scheduling the execution of a callback. */ export const scheduler = { /** * Schedule a callback to be called after some delay. * * Returns a function that when executed will cancel the scheduled function. */ schedule(taskFn: () => void, delay: number): () => void { const id = setTimeout(taskFn, delay); return () => clearTimeout(id); }, /** * Schedule a callback to be called before the next render. * (If `window.requestAnimationFrame()` is not available, use `scheduler.schedule()` instead.) * * Returns a function that when executed will cancel the scheduled function. */ scheduleBeforeRender(taskFn: () => void): () => void { // TODO(gkalpak): Implement a better way of accessing `requestAnimationFrame()` // (e.g. accounting for vendor prefix, SSR-compatibility, etc). if (typeof window === 'undefined') { // For SSR just schedule immediately. return scheduler.schedule(taskFn, 0); } if (typeof window.requestAnimationFrame === 'undefined') { const frameMs = 16; return scheduler.schedule(taskFn, frameMs); } const id = window.requestAnimationFrame(taskFn); return () => window.cancelAnimationFrame(id); }, }; /** * Convert a camelCased string to kebab-cased. */ export function camelToDashCase(input: string): string { return input.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`); } /** * Check whether the input is an `Element`. */ export function isElement(node: Node|null): node is Element { return !!node && node.nodeType === Node.ELEMENT_NODE; } /** * Check whether the input is a function. */ export function isFunction(value: any): value is Function { return typeof value === 'function'; } /** * Convert a kebab-cased string to camelCased. */ export function kebabToCamelCase(input: string): string { return input.replace(/-([a-z\d])/g, (_, char) => char.toUpperCase()); } let _matches: (this: any, selector: string) => boolean; /** * Check whether an `Element` matches a CSS selector. * NOTE: this is duplicated from @angular/upgrade, and can * be consolidated in the future */ export function matchesSelector(el: any, selector: string): boolean { if (!_matches)
return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false; } /** * Test two values for strict equality, accounting for the fact that `NaN !== NaN`. */ export function strictEquals(value1: any, value2: any): boolean { return value1 === value2 || (value1 !== value1 && value2 !== value2); } /** Gets a map of default set of attributes to observe and the properties they affect. */ export function getDefaultAttributeToPropertyInputs( inputs: {propName: string, templateName: string}[]) { const attributeToPropertyInputs: {[key: string]: string} = {}; inputs.forEach(({propName, templateName}) => { attributeToPropertyInputs[camelToDashCase(templateName)] = propName; }); return attributeToPropertyInputs; } /** * Gets a component's set of inputs. Uses the injector to get the component factory where the inputs * are defined. */ export function getComponentInputs( component: Type<any>, injector: Injector): {propName: string, templateName: string}[] { const componentFactoryResolver: ComponentFactoryResolver = injector.get(ComponentFactoryResolver); const componentFactory = componentFactoryResolver.resolveComponentFactory(component); return componentFactory.inputs; }
{ const elProto = <any>Element.prototype; _matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector; }
conditional_block
utils.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ComponentFactoryResolver, Injector, Type} from '@angular/core'; /** * Provide methods for scheduling the execution of a callback. */ export const scheduler = { /** * Schedule a callback to be called after some delay. * * Returns a function that when executed will cancel the scheduled function. */ schedule(taskFn: () => void, delay: number): () => void { const id = setTimeout(taskFn, delay); return () => clearTimeout(id); }, /** * Schedule a callback to be called before the next render. * (If `window.requestAnimationFrame()` is not available, use `scheduler.schedule()` instead.) * * Returns a function that when executed will cancel the scheduled function. */ scheduleBeforeRender(taskFn: () => void): () => void { // TODO(gkalpak): Implement a better way of accessing `requestAnimationFrame()` // (e.g. accounting for vendor prefix, SSR-compatibility, etc). if (typeof window === 'undefined') { // For SSR just schedule immediately. return scheduler.schedule(taskFn, 0); } if (typeof window.requestAnimationFrame === 'undefined') { const frameMs = 16; return scheduler.schedule(taskFn, frameMs); } const id = window.requestAnimationFrame(taskFn); return () => window.cancelAnimationFrame(id); }, }; /** * Convert a camelCased string to kebab-cased. */ export function camelToDashCase(input: string): string { return input.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`); } /** * Check whether the input is an `Element`. */ export function isElement(node: Node|null): node is Element { return !!node && node.nodeType === Node.ELEMENT_NODE; } /** * Check whether the input is a function.
return typeof value === 'function'; } /** * Convert a kebab-cased string to camelCased. */ export function kebabToCamelCase(input: string): string { return input.replace(/-([a-z\d])/g, (_, char) => char.toUpperCase()); } let _matches: (this: any, selector: string) => boolean; /** * Check whether an `Element` matches a CSS selector. * NOTE: this is duplicated from @angular/upgrade, and can * be consolidated in the future */ export function matchesSelector(el: any, selector: string): boolean { if (!_matches) { const elProto = <any>Element.prototype; _matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector; } return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false; } /** * Test two values for strict equality, accounting for the fact that `NaN !== NaN`. */ export function strictEquals(value1: any, value2: any): boolean { return value1 === value2 || (value1 !== value1 && value2 !== value2); } /** Gets a map of default set of attributes to observe and the properties they affect. */ export function getDefaultAttributeToPropertyInputs( inputs: {propName: string, templateName: string}[]) { const attributeToPropertyInputs: {[key: string]: string} = {}; inputs.forEach(({propName, templateName}) => { attributeToPropertyInputs[camelToDashCase(templateName)] = propName; }); return attributeToPropertyInputs; } /** * Gets a component's set of inputs. Uses the injector to get the component factory where the inputs * are defined. */ export function getComponentInputs( component: Type<any>, injector: Injector): {propName: string, templateName: string}[] { const componentFactoryResolver: ComponentFactoryResolver = injector.get(ComponentFactoryResolver); const componentFactory = componentFactoryResolver.resolveComponentFactory(component); return componentFactory.inputs; }
*/ export function isFunction(value: any): value is Function {
random_line_split
utils.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ComponentFactoryResolver, Injector, Type} from '@angular/core'; /** * Provide methods for scheduling the execution of a callback. */ export const scheduler = { /** * Schedule a callback to be called after some delay. * * Returns a function that when executed will cancel the scheduled function. */ schedule(taskFn: () => void, delay: number): () => void { const id = setTimeout(taskFn, delay); return () => clearTimeout(id); }, /** * Schedule a callback to be called before the next render. * (If `window.requestAnimationFrame()` is not available, use `scheduler.schedule()` instead.) * * Returns a function that when executed will cancel the scheduled function. */ scheduleBeforeRender(taskFn: () => void): () => void { // TODO(gkalpak): Implement a better way of accessing `requestAnimationFrame()` // (e.g. accounting for vendor prefix, SSR-compatibility, etc). if (typeof window === 'undefined') { // For SSR just schedule immediately. return scheduler.schedule(taskFn, 0); } if (typeof window.requestAnimationFrame === 'undefined') { const frameMs = 16; return scheduler.schedule(taskFn, frameMs); } const id = window.requestAnimationFrame(taskFn); return () => window.cancelAnimationFrame(id); }, }; /** * Convert a camelCased string to kebab-cased. */ export function camelToDashCase(input: string): string { return input.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`); } /** * Check whether the input is an `Element`. */ export function isElement(node: Node|null): node is Element { return !!node && node.nodeType === Node.ELEMENT_NODE; } /** * Check whether the input is a function. */ export function isFunction(value: any): value is Function
/** * Convert a kebab-cased string to camelCased. */ export function kebabToCamelCase(input: string): string { return input.replace(/-([a-z\d])/g, (_, char) => char.toUpperCase()); } let _matches: (this: any, selector: string) => boolean; /** * Check whether an `Element` matches a CSS selector. * NOTE: this is duplicated from @angular/upgrade, and can * be consolidated in the future */ export function matchesSelector(el: any, selector: string): boolean { if (!_matches) { const elProto = <any>Element.prototype; _matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector; } return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false; } /** * Test two values for strict equality, accounting for the fact that `NaN !== NaN`. */ export function strictEquals(value1: any, value2: any): boolean { return value1 === value2 || (value1 !== value1 && value2 !== value2); } /** Gets a map of default set of attributes to observe and the properties they affect. */ export function getDefaultAttributeToPropertyInputs( inputs: {propName: string, templateName: string}[]) { const attributeToPropertyInputs: {[key: string]: string} = {}; inputs.forEach(({propName, templateName}) => { attributeToPropertyInputs[camelToDashCase(templateName)] = propName; }); return attributeToPropertyInputs; } /** * Gets a component's set of inputs. Uses the injector to get the component factory where the inputs * are defined. */ export function getComponentInputs( component: Type<any>, injector: Injector): {propName: string, templateName: string}[] { const componentFactoryResolver: ComponentFactoryResolver = injector.get(ComponentFactoryResolver); const componentFactory = componentFactoryResolver.resolveComponentFactory(component); return componentFactory.inputs; }
{ return typeof value === 'function'; }
identifier_body
construct.py
"""Functions to construct sparse matrices """ __docformat__ = "restructuredtext en" __all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum', 'hstack', 'vstack', 'bmat', 'rand'] from warnings import warn import numpy as np from sputils import upcast from csr import csr_matrix from csc import csc_matrix from bsr import bsr_matrix from coo import coo_matrix from lil import lil_matrix from dia import dia_matrix def spdiags(data, diags, m, n, format=None): """ Return a sparse matrix from diagonals. Parameters ---------- data : array_like matrix diagonals stored row-wise diags : diagonals to set - k = 0 the main diagonal - k > 0 the k-th upper diagonal - k < 0 the k-th lower diagonal m, n : int shape of the result format : format of the result (e.g. "csr") By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- dia_matrix : the sparse DIAgonal format. Examples -------- >>> data = array([[1,2,3,4],[1,2,3,4],[1,2,3,4]]) >>> diags = array([0,-1,2]) >>> spdiags(data, diags, 4, 4).todense() matrix([[1, 0, 3, 0], [1, 2, 0, 4], [0, 2, 3, 0], [0, 0, 3, 4]]) """ return dia_matrix((data, diags), shape=(m,n)).asformat(format) def identity(n, dtype='d', format=None): """Identity matrix in sparse format Returns an identity matrix with shape (n,n) using a given sparse format and dtype. Parameters ---------- n : integer Shape of the identity matrix. dtype : Data type of the matrix format : string Sparse format of the result, e.g. format="csr", etc. Examples -------- >>> identity(3).todense() matrix([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> identity(3, dtype='int8', format='dia') <3x3 sparse matrix of type '<type 'numpy.int8'>' with 3 stored elements (1 diagonals) in DIAgonal format> """ if format in ['csr','csc']: indptr = np.arange(n+1, dtype=np.intc) indices = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) cls = eval('%s_matrix' % format) return cls((data,indices,indptr),(n,n)) elif format == 'coo':
elif format == 'dia': data = np.ones(n, dtype=dtype) diags = [0] return dia_matrix((data,diags), shape=(n,n)) else: return identity(n, dtype=dtype, format='csr').asformat(format) def eye(m, n, k=0, dtype='d', format=None): """eye(m, n) returns a sparse (m x n) matrix where the k-th diagonal is all ones and everything else is zeros. """ m,n = int(m),int(n) diags = np.ones((1, max(0, min(m + k, n))), dtype=dtype) return spdiags(diags, k, m, n).asformat(format) def kron(A, B, format=None): """kronecker product of sparse matrices A and B Parameters ---------- A : sparse or dense matrix first matrix of the product B : sparse or dense matrix second matrix of the product format : string format of the result (e.g. "csr") Returns ------- kronecker product in a sparse matrix format Examples -------- >>> A = csr_matrix(array([[0,2],[5,0]])) >>> B = csr_matrix(array([[1,2],[3,4]])) >>> kron(A,B).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) >>> kron(A,[[1,2],[3,4]]).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) """ B = coo_matrix(B) if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: #B is fairly dense, use BSR A = csr_matrix(A,copy=True) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) B = B.toarray() data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1]) data = data * B return bsr_matrix((data,A.indices,A.indptr), shape=output_shape) else: #use COO A = coo_matrix(A) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) # expand entries of a into blocks row = A.row.repeat(B.nnz) col = A.col.repeat(B.nnz) data = A.data.repeat(B.nnz) row *= B.shape[0] col *= B.shape[1] # increment block indices row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) row += B.row col += B.col row,col = row.reshape(-1),col.reshape(-1) # compute block entries data = data.reshape(-1,B.nnz) * B.data data = data.reshape(-1) return coo_matrix((data,(row,col)), shape=output_shape).asformat(format) def kronsum(A, B, format=None): """kronecker sum of sparse matrices A and B Kronecker sum of two sparse matrices is a sum of two Kronecker products kron(I_n,A) + kron(B,I_m) where A has shape (m,m) and B has shape (n,n) and I_m and I_n are identity matrices of shape (m,m) and (n,n) respectively. Parameters ---------- A square matrix B square matrix format : string format of the result (e.g. "csr") Returns ------- kronecker sum in a sparse matrix format Examples -------- """ A = coo_matrix(A) B = coo_matrix(B) if A.shape[0] != A.shape[1]: raise ValueError('A is not square') if B.shape[0] != B.shape[1]: raise ValueError('B is not square') dtype = upcast(A.dtype, B.dtype) L = kron(identity(B.shape[0],dtype=dtype), A, format=format) R = kron(B, identity(A.shape[0],dtype=dtype), format=format) return (L+R).asformat(format) #since L + R is not always same format def hstack(blocks, format=None, dtype=None): """ Stack sparse matrices horizontally (column wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- vstack : stack sparse matrices vertically (row wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> hstack( [A,B] ).todense() matrix([[1, 2, 5], [3, 4, 6]]) """ return bmat([blocks], format=format, dtype=dtype) def vstack(blocks, format=None, dtype=None): """ Stack sparse matrices vertically (row wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- hstack : stack sparse matrices horizontally (column wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5,6]]) >>> vstack( [A,B] ).todense() matrix([[1, 2], [3, 4], [5, 6]]) """ return bmat([ [b] for b in blocks ], format=format, dtype=dtype) def bmat(blocks, format=None, dtype=None): """ Build a sparse matrix from sparse sub-blocks Parameters ---------- blocks grid of sparse matrices with compatible shapes an entry of None implies an all-zero matrix format : sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. Examples -------- >>> from scipy.sparse import coo_matrix, bmat >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> C = coo_matrix([[7]]) >>> bmat( [[A,B],[None,C]] ).todense() matrix([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> bmat( [[A,None],[None,C]] ).todense() matrix([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) """ blocks = np.asarray(blocks, dtype='object') if np.rank(blocks) != 2: raise ValueError('blocks must have rank 2') M,N = blocks.shape block_mask = np.zeros(blocks.shape, dtype=np.bool) brow_lengths = np.zeros(blocks.shape[0], dtype=np.intc) bcol_lengths = np.zeros(blocks.shape[1], dtype=np.intc) # convert everything to COO format for i in range(M): for j in range(N): if blocks[i,j] is not None: A = coo_matrix(blocks[i,j]) blocks[i,j] = A block_mask[i,j] = True if brow_lengths[i] == 0: brow_lengths[i] = A.shape[0] else: if brow_lengths[i] != A.shape[0]: raise ValueError('blocks[%d,:] has incompatible row dimensions' % i) if bcol_lengths[j] == 0: bcol_lengths[j] = A.shape[1] else: if bcol_lengths[j] != A.shape[1]: raise ValueError('blocks[:,%d] has incompatible column dimensions' % j) # ensure that at least one value in each row and col is not None if brow_lengths.min() == 0: raise ValueError('blocks[%d,:] is all None' % brow_lengths.argmin() ) if bcol_lengths.min() == 0: raise ValueError('blocks[:,%d] is all None' % bcol_lengths.argmin() ) nnz = sum([ A.nnz for A in blocks[block_mask] ]) if dtype is None: dtype = upcast( *tuple([A.dtype for A in blocks[block_mask]]) ) row_offsets = np.concatenate(([0], np.cumsum(brow_lengths))) col_offsets = np.concatenate(([0], np.cumsum(bcol_lengths))) data = np.empty(nnz, dtype=dtype) row = np.empty(nnz, dtype=np.intc) col = np.empty(nnz, dtype=np.intc) nnz = 0 for i in range(M): for j in range(N): if blocks[i,j] is not None: A = blocks[i,j] data[nnz:nnz + A.nnz] = A.data row[nnz:nnz + A.nnz] = A.row col[nnz:nnz + A.nnz] = A.col row[nnz:nnz + A.nnz] += row_offsets[i] col[nnz:nnz + A.nnz] += col_offsets[j] nnz += A.nnz shape = (np.sum(brow_lengths), np.sum(bcol_lengths)) return coo_matrix((data, (row, col)), shape=shape).asformat(format) def rand(m, n, density=0.01, format="coo", dtype=None): """Generate a sparse matrix of the given shape and density with uniformely distributed values. Parameters ---------- m, n: int shape of the matrix density: real density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items. format: str sparse matrix format. dtype: dtype type of the returned matrix values. Notes ----- Only float types are supported for now. """ if density < 0 or density > 1: raise ValueError("density expected to be 0 <= density <= 1") if dtype and not dtype in [np.float32, np.float64, np.longdouble]: raise NotImplementedError("type %s not supported" % dtype) mn = m * n # XXX: sparse uses intc instead of intp... tp = np.intp if mn > np.iinfo(tp).max: msg = """\ Trying to generate a random sparse matrix such as the product of dimensions is greater than %d - this is not supported on this machine """ raise ValueError(msg % np.iinfo(tp).max) # Number of non zero values k = long(density * m * n) # Generate a few more values than k so that we can get unique values # afterwards. # XXX: one could be smarter here mlow = 5 fac = 1.02 gk = min(k + mlow, fac * k) def _gen_unique_rand(_gk): id = np.random.rand(_gk) return np.unique(np.floor(id * mn))[:k] id = _gen_unique_rand(gk) while id.size < k: gk *= 1.05 id = _gen_unique_rand(gk) j = np.floor(id * 1. / m).astype(tp) i = (id - j * m).astype(tp) vals = np.random.rand(k).astype(dtype) return coo_matrix((vals, (i, j)), shape=(m, n)).asformat(format)
row = np.arange(n, dtype=np.intc) col = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) return coo_matrix((data,(row,col)),(n,n))
conditional_block
construct.py
"""Functions to construct sparse matrices """ __docformat__ = "restructuredtext en" __all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum', 'hstack', 'vstack', 'bmat', 'rand'] from warnings import warn import numpy as np from sputils import upcast from csr import csr_matrix from csc import csc_matrix from bsr import bsr_matrix from coo import coo_matrix from lil import lil_matrix from dia import dia_matrix def spdiags(data, diags, m, n, format=None): """ Return a sparse matrix from diagonals. Parameters ---------- data : array_like matrix diagonals stored row-wise diags : diagonals to set - k = 0 the main diagonal - k > 0 the k-th upper diagonal - k < 0 the k-th lower diagonal m, n : int shape of the result format : format of the result (e.g. "csr") By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- dia_matrix : the sparse DIAgonal format. Examples -------- >>> data = array([[1,2,3,4],[1,2,3,4],[1,2,3,4]]) >>> diags = array([0,-1,2]) >>> spdiags(data, diags, 4, 4).todense() matrix([[1, 0, 3, 0], [1, 2, 0, 4], [0, 2, 3, 0], [0, 0, 3, 4]]) """ return dia_matrix((data, diags), shape=(m,n)).asformat(format) def identity(n, dtype='d', format=None): """Identity matrix in sparse format Returns an identity matrix with shape (n,n) using a given sparse format and dtype. Parameters ---------- n : integer Shape of the identity matrix. dtype : Data type of the matrix format : string Sparse format of the result, e.g. format="csr", etc. Examples -------- >>> identity(3).todense() matrix([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> identity(3, dtype='int8', format='dia') <3x3 sparse matrix of type '<type 'numpy.int8'>' with 3 stored elements (1 diagonals) in DIAgonal format> """ if format in ['csr','csc']: indptr = np.arange(n+1, dtype=np.intc) indices = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) cls = eval('%s_matrix' % format) return cls((data,indices,indptr),(n,n)) elif format == 'coo': row = np.arange(n, dtype=np.intc) col = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) return coo_matrix((data,(row,col)),(n,n)) elif format == 'dia': data = np.ones(n, dtype=dtype) diags = [0] return dia_matrix((data,diags), shape=(n,n)) else: return identity(n, dtype=dtype, format='csr').asformat(format) def eye(m, n, k=0, dtype='d', format=None): """eye(m, n) returns a sparse (m x n) matrix where the k-th diagonal is all ones and everything else is zeros. """ m,n = int(m),int(n) diags = np.ones((1, max(0, min(m + k, n))), dtype=dtype) return spdiags(diags, k, m, n).asformat(format) def kron(A, B, format=None): """kronecker product of sparse matrices A and B Parameters ---------- A : sparse or dense matrix first matrix of the product B : sparse or dense matrix second matrix of the product format : string format of the result (e.g. "csr") Returns ------- kronecker product in a sparse matrix format Examples -------- >>> A = csr_matrix(array([[0,2],[5,0]])) >>> B = csr_matrix(array([[1,2],[3,4]])) >>> kron(A,B).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) >>> kron(A,[[1,2],[3,4]]).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) """ B = coo_matrix(B) if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: #B is fairly dense, use BSR A = csr_matrix(A,copy=True) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) B = B.toarray() data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1]) data = data * B return bsr_matrix((data,A.indices,A.indptr), shape=output_shape) else: #use COO A = coo_matrix(A) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) # expand entries of a into blocks row = A.row.repeat(B.nnz) col = A.col.repeat(B.nnz) data = A.data.repeat(B.nnz) row *= B.shape[0] col *= B.shape[1] # increment block indices row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) row += B.row col += B.col row,col = row.reshape(-1),col.reshape(-1) # compute block entries data = data.reshape(-1,B.nnz) * B.data data = data.reshape(-1) return coo_matrix((data,(row,col)), shape=output_shape).asformat(format) def kronsum(A, B, format=None): """kronecker sum of sparse matrices A and B Kronecker sum of two sparse matrices is a sum of two Kronecker products kron(I_n,A) + kron(B,I_m) where A has shape (m,m) and B has shape (n,n) and I_m and I_n are identity matrices of shape (m,m) and (n,n) respectively. Parameters ---------- A square matrix B square matrix format : string format of the result (e.g. "csr") Returns ------- kronecker sum in a sparse matrix format Examples -------- """ A = coo_matrix(A) B = coo_matrix(B) if A.shape[0] != A.shape[1]: raise ValueError('A is not square') if B.shape[0] != B.shape[1]: raise ValueError('B is not square') dtype = upcast(A.dtype, B.dtype) L = kron(identity(B.shape[0],dtype=dtype), A, format=format) R = kron(B, identity(A.shape[0],dtype=dtype), format=format) return (L+R).asformat(format) #since L + R is not always same format def hstack(blocks, format=None, dtype=None): """ Stack sparse matrices horizontally (column wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- vstack : stack sparse matrices vertically (row wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> hstack( [A,B] ).todense() matrix([[1, 2, 5], [3, 4, 6]]) """ return bmat([blocks], format=format, dtype=dtype) def vstack(blocks, format=None, dtype=None): """ Stack sparse matrices vertically (row wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- hstack : stack sparse matrices horizontally (column wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5,6]]) >>> vstack( [A,B] ).todense() matrix([[1, 2], [3, 4], [5, 6]]) """ return bmat([ [b] for b in blocks ], format=format, dtype=dtype) def bmat(blocks, format=None, dtype=None):
def rand(m, n, density=0.01, format="coo", dtype=None): """Generate a sparse matrix of the given shape and density with uniformely distributed values. Parameters ---------- m, n: int shape of the matrix density: real density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items. format: str sparse matrix format. dtype: dtype type of the returned matrix values. Notes ----- Only float types are supported for now. """ if density < 0 or density > 1: raise ValueError("density expected to be 0 <= density <= 1") if dtype and not dtype in [np.float32, np.float64, np.longdouble]: raise NotImplementedError("type %s not supported" % dtype) mn = m * n # XXX: sparse uses intc instead of intp... tp = np.intp if mn > np.iinfo(tp).max: msg = """\ Trying to generate a random sparse matrix such as the product of dimensions is greater than %d - this is not supported on this machine """ raise ValueError(msg % np.iinfo(tp).max) # Number of non zero values k = long(density * m * n) # Generate a few more values than k so that we can get unique values # afterwards. # XXX: one could be smarter here mlow = 5 fac = 1.02 gk = min(k + mlow, fac * k) def _gen_unique_rand(_gk): id = np.random.rand(_gk) return np.unique(np.floor(id * mn))[:k] id = _gen_unique_rand(gk) while id.size < k: gk *= 1.05 id = _gen_unique_rand(gk) j = np.floor(id * 1. / m).astype(tp) i = (id - j * m).astype(tp) vals = np.random.rand(k).astype(dtype) return coo_matrix((vals, (i, j)), shape=(m, n)).asformat(format)
""" Build a sparse matrix from sparse sub-blocks Parameters ---------- blocks grid of sparse matrices with compatible shapes an entry of None implies an all-zero matrix format : sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. Examples -------- >>> from scipy.sparse import coo_matrix, bmat >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> C = coo_matrix([[7]]) >>> bmat( [[A,B],[None,C]] ).todense() matrix([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> bmat( [[A,None],[None,C]] ).todense() matrix([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) """ blocks = np.asarray(blocks, dtype='object') if np.rank(blocks) != 2: raise ValueError('blocks must have rank 2') M,N = blocks.shape block_mask = np.zeros(blocks.shape, dtype=np.bool) brow_lengths = np.zeros(blocks.shape[0], dtype=np.intc) bcol_lengths = np.zeros(blocks.shape[1], dtype=np.intc) # convert everything to COO format for i in range(M): for j in range(N): if blocks[i,j] is not None: A = coo_matrix(blocks[i,j]) blocks[i,j] = A block_mask[i,j] = True if brow_lengths[i] == 0: brow_lengths[i] = A.shape[0] else: if brow_lengths[i] != A.shape[0]: raise ValueError('blocks[%d,:] has incompatible row dimensions' % i) if bcol_lengths[j] == 0: bcol_lengths[j] = A.shape[1] else: if bcol_lengths[j] != A.shape[1]: raise ValueError('blocks[:,%d] has incompatible column dimensions' % j) # ensure that at least one value in each row and col is not None if brow_lengths.min() == 0: raise ValueError('blocks[%d,:] is all None' % brow_lengths.argmin() ) if bcol_lengths.min() == 0: raise ValueError('blocks[:,%d] is all None' % bcol_lengths.argmin() ) nnz = sum([ A.nnz for A in blocks[block_mask] ]) if dtype is None: dtype = upcast( *tuple([A.dtype for A in blocks[block_mask]]) ) row_offsets = np.concatenate(([0], np.cumsum(brow_lengths))) col_offsets = np.concatenate(([0], np.cumsum(bcol_lengths))) data = np.empty(nnz, dtype=dtype) row = np.empty(nnz, dtype=np.intc) col = np.empty(nnz, dtype=np.intc) nnz = 0 for i in range(M): for j in range(N): if blocks[i,j] is not None: A = blocks[i,j] data[nnz:nnz + A.nnz] = A.data row[nnz:nnz + A.nnz] = A.row col[nnz:nnz + A.nnz] = A.col row[nnz:nnz + A.nnz] += row_offsets[i] col[nnz:nnz + A.nnz] += col_offsets[j] nnz += A.nnz shape = (np.sum(brow_lengths), np.sum(bcol_lengths)) return coo_matrix((data, (row, col)), shape=shape).asformat(format)
identifier_body
construct.py
"""Functions to construct sparse matrices """ __docformat__ = "restructuredtext en" __all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum', 'hstack', 'vstack', 'bmat', 'rand'] from warnings import warn import numpy as np from sputils import upcast from csr import csr_matrix from csc import csc_matrix from bsr import bsr_matrix from coo import coo_matrix from lil import lil_matrix from dia import dia_matrix def spdiags(data, diags, m, n, format=None): """ Return a sparse matrix from diagonals. Parameters ---------- data : array_like matrix diagonals stored row-wise diags : diagonals to set - k = 0 the main diagonal - k > 0 the k-th upper diagonal - k < 0 the k-th lower diagonal m, n : int shape of the result format : format of the result (e.g. "csr") By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- dia_matrix : the sparse DIAgonal format. Examples -------- >>> data = array([[1,2,3,4],[1,2,3,4],[1,2,3,4]]) >>> diags = array([0,-1,2]) >>> spdiags(data, diags, 4, 4).todense() matrix([[1, 0, 3, 0], [1, 2, 0, 4], [0, 2, 3, 0], [0, 0, 3, 4]]) """ return dia_matrix((data, diags), shape=(m,n)).asformat(format) def
(n, dtype='d', format=None): """Identity matrix in sparse format Returns an identity matrix with shape (n,n) using a given sparse format and dtype. Parameters ---------- n : integer Shape of the identity matrix. dtype : Data type of the matrix format : string Sparse format of the result, e.g. format="csr", etc. Examples -------- >>> identity(3).todense() matrix([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> identity(3, dtype='int8', format='dia') <3x3 sparse matrix of type '<type 'numpy.int8'>' with 3 stored elements (1 diagonals) in DIAgonal format> """ if format in ['csr','csc']: indptr = np.arange(n+1, dtype=np.intc) indices = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) cls = eval('%s_matrix' % format) return cls((data,indices,indptr),(n,n)) elif format == 'coo': row = np.arange(n, dtype=np.intc) col = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) return coo_matrix((data,(row,col)),(n,n)) elif format == 'dia': data = np.ones(n, dtype=dtype) diags = [0] return dia_matrix((data,diags), shape=(n,n)) else: return identity(n, dtype=dtype, format='csr').asformat(format) def eye(m, n, k=0, dtype='d', format=None): """eye(m, n) returns a sparse (m x n) matrix where the k-th diagonal is all ones and everything else is zeros. """ m,n = int(m),int(n) diags = np.ones((1, max(0, min(m + k, n))), dtype=dtype) return spdiags(diags, k, m, n).asformat(format) def kron(A, B, format=None): """kronecker product of sparse matrices A and B Parameters ---------- A : sparse or dense matrix first matrix of the product B : sparse or dense matrix second matrix of the product format : string format of the result (e.g. "csr") Returns ------- kronecker product in a sparse matrix format Examples -------- >>> A = csr_matrix(array([[0,2],[5,0]])) >>> B = csr_matrix(array([[1,2],[3,4]])) >>> kron(A,B).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) >>> kron(A,[[1,2],[3,4]]).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) """ B = coo_matrix(B) if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: #B is fairly dense, use BSR A = csr_matrix(A,copy=True) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) B = B.toarray() data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1]) data = data * B return bsr_matrix((data,A.indices,A.indptr), shape=output_shape) else: #use COO A = coo_matrix(A) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) # expand entries of a into blocks row = A.row.repeat(B.nnz) col = A.col.repeat(B.nnz) data = A.data.repeat(B.nnz) row *= B.shape[0] col *= B.shape[1] # increment block indices row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) row += B.row col += B.col row,col = row.reshape(-1),col.reshape(-1) # compute block entries data = data.reshape(-1,B.nnz) * B.data data = data.reshape(-1) return coo_matrix((data,(row,col)), shape=output_shape).asformat(format) def kronsum(A, B, format=None): """kronecker sum of sparse matrices A and B Kronecker sum of two sparse matrices is a sum of two Kronecker products kron(I_n,A) + kron(B,I_m) where A has shape (m,m) and B has shape (n,n) and I_m and I_n are identity matrices of shape (m,m) and (n,n) respectively. Parameters ---------- A square matrix B square matrix format : string format of the result (e.g. "csr") Returns ------- kronecker sum in a sparse matrix format Examples -------- """ A = coo_matrix(A) B = coo_matrix(B) if A.shape[0] != A.shape[1]: raise ValueError('A is not square') if B.shape[0] != B.shape[1]: raise ValueError('B is not square') dtype = upcast(A.dtype, B.dtype) L = kron(identity(B.shape[0],dtype=dtype), A, format=format) R = kron(B, identity(A.shape[0],dtype=dtype), format=format) return (L+R).asformat(format) #since L + R is not always same format def hstack(blocks, format=None, dtype=None): """ Stack sparse matrices horizontally (column wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- vstack : stack sparse matrices vertically (row wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> hstack( [A,B] ).todense() matrix([[1, 2, 5], [3, 4, 6]]) """ return bmat([blocks], format=format, dtype=dtype) def vstack(blocks, format=None, dtype=None): """ Stack sparse matrices vertically (row wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- hstack : stack sparse matrices horizontally (column wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5,6]]) >>> vstack( [A,B] ).todense() matrix([[1, 2], [3, 4], [5, 6]]) """ return bmat([ [b] for b in blocks ], format=format, dtype=dtype) def bmat(blocks, format=None, dtype=None): """ Build a sparse matrix from sparse sub-blocks Parameters ---------- blocks grid of sparse matrices with compatible shapes an entry of None implies an all-zero matrix format : sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. Examples -------- >>> from scipy.sparse import coo_matrix, bmat >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> C = coo_matrix([[7]]) >>> bmat( [[A,B],[None,C]] ).todense() matrix([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> bmat( [[A,None],[None,C]] ).todense() matrix([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) """ blocks = np.asarray(blocks, dtype='object') if np.rank(blocks) != 2: raise ValueError('blocks must have rank 2') M,N = blocks.shape block_mask = np.zeros(blocks.shape, dtype=np.bool) brow_lengths = np.zeros(blocks.shape[0], dtype=np.intc) bcol_lengths = np.zeros(blocks.shape[1], dtype=np.intc) # convert everything to COO format for i in range(M): for j in range(N): if blocks[i,j] is not None: A = coo_matrix(blocks[i,j]) blocks[i,j] = A block_mask[i,j] = True if brow_lengths[i] == 0: brow_lengths[i] = A.shape[0] else: if brow_lengths[i] != A.shape[0]: raise ValueError('blocks[%d,:] has incompatible row dimensions' % i) if bcol_lengths[j] == 0: bcol_lengths[j] = A.shape[1] else: if bcol_lengths[j] != A.shape[1]: raise ValueError('blocks[:,%d] has incompatible column dimensions' % j) # ensure that at least one value in each row and col is not None if brow_lengths.min() == 0: raise ValueError('blocks[%d,:] is all None' % brow_lengths.argmin() ) if bcol_lengths.min() == 0: raise ValueError('blocks[:,%d] is all None' % bcol_lengths.argmin() ) nnz = sum([ A.nnz for A in blocks[block_mask] ]) if dtype is None: dtype = upcast( *tuple([A.dtype for A in blocks[block_mask]]) ) row_offsets = np.concatenate(([0], np.cumsum(brow_lengths))) col_offsets = np.concatenate(([0], np.cumsum(bcol_lengths))) data = np.empty(nnz, dtype=dtype) row = np.empty(nnz, dtype=np.intc) col = np.empty(nnz, dtype=np.intc) nnz = 0 for i in range(M): for j in range(N): if blocks[i,j] is not None: A = blocks[i,j] data[nnz:nnz + A.nnz] = A.data row[nnz:nnz + A.nnz] = A.row col[nnz:nnz + A.nnz] = A.col row[nnz:nnz + A.nnz] += row_offsets[i] col[nnz:nnz + A.nnz] += col_offsets[j] nnz += A.nnz shape = (np.sum(brow_lengths), np.sum(bcol_lengths)) return coo_matrix((data, (row, col)), shape=shape).asformat(format) def rand(m, n, density=0.01, format="coo", dtype=None): """Generate a sparse matrix of the given shape and density with uniformely distributed values. Parameters ---------- m, n: int shape of the matrix density: real density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items. format: str sparse matrix format. dtype: dtype type of the returned matrix values. Notes ----- Only float types are supported for now. """ if density < 0 or density > 1: raise ValueError("density expected to be 0 <= density <= 1") if dtype and not dtype in [np.float32, np.float64, np.longdouble]: raise NotImplementedError("type %s not supported" % dtype) mn = m * n # XXX: sparse uses intc instead of intp... tp = np.intp if mn > np.iinfo(tp).max: msg = """\ Trying to generate a random sparse matrix such as the product of dimensions is greater than %d - this is not supported on this machine """ raise ValueError(msg % np.iinfo(tp).max) # Number of non zero values k = long(density * m * n) # Generate a few more values than k so that we can get unique values # afterwards. # XXX: one could be smarter here mlow = 5 fac = 1.02 gk = min(k + mlow, fac * k) def _gen_unique_rand(_gk): id = np.random.rand(_gk) return np.unique(np.floor(id * mn))[:k] id = _gen_unique_rand(gk) while id.size < k: gk *= 1.05 id = _gen_unique_rand(gk) j = np.floor(id * 1. / m).astype(tp) i = (id - j * m).astype(tp) vals = np.random.rand(k).astype(dtype) return coo_matrix((vals, (i, j)), shape=(m, n)).asformat(format)
identity
identifier_name
construct.py
"""Functions to construct sparse matrices """ __docformat__ = "restructuredtext en" __all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum', 'hstack', 'vstack', 'bmat', 'rand'] from warnings import warn import numpy as np from sputils import upcast from csr import csr_matrix from csc import csc_matrix from bsr import bsr_matrix from coo import coo_matrix from lil import lil_matrix from dia import dia_matrix def spdiags(data, diags, m, n, format=None): """ Return a sparse matrix from diagonals. Parameters ---------- data : array_like matrix diagonals stored row-wise diags : diagonals to set - k = 0 the main diagonal - k > 0 the k-th upper diagonal - k < 0 the k-th lower diagonal m, n : int shape of the result format : format of the result (e.g. "csr") By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- dia_matrix : the sparse DIAgonal format. Examples -------- >>> data = array([[1,2,3,4],[1,2,3,4],[1,2,3,4]]) >>> diags = array([0,-1,2]) >>> spdiags(data, diags, 4, 4).todense() matrix([[1, 0, 3, 0], [1, 2, 0, 4], [0, 2, 3, 0], [0, 0, 3, 4]]) """ return dia_matrix((data, diags), shape=(m,n)).asformat(format) def identity(n, dtype='d', format=None): """Identity matrix in sparse format Returns an identity matrix with shape (n,n) using a given sparse format and dtype. Parameters ---------- n : integer Shape of the identity matrix. dtype : Data type of the matrix format : string Sparse format of the result, e.g. format="csr", etc. Examples -------- >>> identity(3).todense() matrix([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> identity(3, dtype='int8', format='dia') <3x3 sparse matrix of type '<type 'numpy.int8'>' with 3 stored elements (1 diagonals) in DIAgonal format> """ if format in ['csr','csc']: indptr = np.arange(n+1, dtype=np.intc) indices = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) cls = eval('%s_matrix' % format) return cls((data,indices,indptr),(n,n)) elif format == 'coo': row = np.arange(n, dtype=np.intc) col = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) return coo_matrix((data,(row,col)),(n,n)) elif format == 'dia': data = np.ones(n, dtype=dtype) diags = [0] return dia_matrix((data,diags), shape=(n,n)) else: return identity(n, dtype=dtype, format='csr').asformat(format) def eye(m, n, k=0, dtype='d', format=None): """eye(m, n) returns a sparse (m x n) matrix where the k-th diagonal is all ones and everything else is zeros. """ m,n = int(m),int(n) diags = np.ones((1, max(0, min(m + k, n))), dtype=dtype) return spdiags(diags, k, m, n).asformat(format) def kron(A, B, format=None): """kronecker product of sparse matrices A and B Parameters ---------- A : sparse or dense matrix first matrix of the product B : sparse or dense matrix second matrix of the product format : string format of the result (e.g. "csr") Returns ------- kronecker product in a sparse matrix format Examples -------- >>> A = csr_matrix(array([[0,2],[5,0]])) >>> B = csr_matrix(array([[1,2],[3,4]])) >>> kron(A,B).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) >>> kron(A,[[1,2],[3,4]]).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) """ B = coo_matrix(B) if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: #B is fairly dense, use BSR A = csr_matrix(A,copy=True) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) B = B.toarray() data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1]) data = data * B return bsr_matrix((data,A.indices,A.indptr), shape=output_shape) else: #use COO A = coo_matrix(A) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) # expand entries of a into blocks row = A.row.repeat(B.nnz) col = A.col.repeat(B.nnz) data = A.data.repeat(B.nnz) row *= B.shape[0] col *= B.shape[1] # increment block indices row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) row += B.row col += B.col row,col = row.reshape(-1),col.reshape(-1) # compute block entries data = data.reshape(-1,B.nnz) * B.data data = data.reshape(-1) return coo_matrix((data,(row,col)), shape=output_shape).asformat(format) def kronsum(A, B, format=None): """kronecker sum of sparse matrices A and B Kronecker sum of two sparse matrices is a sum of two Kronecker products kron(I_n,A) + kron(B,I_m) where A has shape (m,m) and B has shape (n,n) and I_m and I_n are identity matrices of shape (m,m) and (n,n) respectively. Parameters ---------- A square matrix B square matrix format : string format of the result (e.g. "csr")
------- kronecker sum in a sparse matrix format Examples -------- """ A = coo_matrix(A) B = coo_matrix(B) if A.shape[0] != A.shape[1]: raise ValueError('A is not square') if B.shape[0] != B.shape[1]: raise ValueError('B is not square') dtype = upcast(A.dtype, B.dtype) L = kron(identity(B.shape[0],dtype=dtype), A, format=format) R = kron(B, identity(A.shape[0],dtype=dtype), format=format) return (L+R).asformat(format) #since L + R is not always same format def hstack(blocks, format=None, dtype=None): """ Stack sparse matrices horizontally (column wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- vstack : stack sparse matrices vertically (row wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> hstack( [A,B] ).todense() matrix([[1, 2, 5], [3, 4, 6]]) """ return bmat([blocks], format=format, dtype=dtype) def vstack(blocks, format=None, dtype=None): """ Stack sparse matrices vertically (row wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- hstack : stack sparse matrices horizontally (column wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5,6]]) >>> vstack( [A,B] ).todense() matrix([[1, 2], [3, 4], [5, 6]]) """ return bmat([ [b] for b in blocks ], format=format, dtype=dtype) def bmat(blocks, format=None, dtype=None): """ Build a sparse matrix from sparse sub-blocks Parameters ---------- blocks grid of sparse matrices with compatible shapes an entry of None implies an all-zero matrix format : sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. Examples -------- >>> from scipy.sparse import coo_matrix, bmat >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> C = coo_matrix([[7]]) >>> bmat( [[A,B],[None,C]] ).todense() matrix([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> bmat( [[A,None],[None,C]] ).todense() matrix([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) """ blocks = np.asarray(blocks, dtype='object') if np.rank(blocks) != 2: raise ValueError('blocks must have rank 2') M,N = blocks.shape block_mask = np.zeros(blocks.shape, dtype=np.bool) brow_lengths = np.zeros(blocks.shape[0], dtype=np.intc) bcol_lengths = np.zeros(blocks.shape[1], dtype=np.intc) # convert everything to COO format for i in range(M): for j in range(N): if blocks[i,j] is not None: A = coo_matrix(blocks[i,j]) blocks[i,j] = A block_mask[i,j] = True if brow_lengths[i] == 0: brow_lengths[i] = A.shape[0] else: if brow_lengths[i] != A.shape[0]: raise ValueError('blocks[%d,:] has incompatible row dimensions' % i) if bcol_lengths[j] == 0: bcol_lengths[j] = A.shape[1] else: if bcol_lengths[j] != A.shape[1]: raise ValueError('blocks[:,%d] has incompatible column dimensions' % j) # ensure that at least one value in each row and col is not None if brow_lengths.min() == 0: raise ValueError('blocks[%d,:] is all None' % brow_lengths.argmin() ) if bcol_lengths.min() == 0: raise ValueError('blocks[:,%d] is all None' % bcol_lengths.argmin() ) nnz = sum([ A.nnz for A in blocks[block_mask] ]) if dtype is None: dtype = upcast( *tuple([A.dtype for A in blocks[block_mask]]) ) row_offsets = np.concatenate(([0], np.cumsum(brow_lengths))) col_offsets = np.concatenate(([0], np.cumsum(bcol_lengths))) data = np.empty(nnz, dtype=dtype) row = np.empty(nnz, dtype=np.intc) col = np.empty(nnz, dtype=np.intc) nnz = 0 for i in range(M): for j in range(N): if blocks[i,j] is not None: A = blocks[i,j] data[nnz:nnz + A.nnz] = A.data row[nnz:nnz + A.nnz] = A.row col[nnz:nnz + A.nnz] = A.col row[nnz:nnz + A.nnz] += row_offsets[i] col[nnz:nnz + A.nnz] += col_offsets[j] nnz += A.nnz shape = (np.sum(brow_lengths), np.sum(bcol_lengths)) return coo_matrix((data, (row, col)), shape=shape).asformat(format) def rand(m, n, density=0.01, format="coo", dtype=None): """Generate a sparse matrix of the given shape and density with uniformely distributed values. Parameters ---------- m, n: int shape of the matrix density: real density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items. format: str sparse matrix format. dtype: dtype type of the returned matrix values. Notes ----- Only float types are supported for now. """ if density < 0 or density > 1: raise ValueError("density expected to be 0 <= density <= 1") if dtype and not dtype in [np.float32, np.float64, np.longdouble]: raise NotImplementedError("type %s not supported" % dtype) mn = m * n # XXX: sparse uses intc instead of intp... tp = np.intp if mn > np.iinfo(tp).max: msg = """\ Trying to generate a random sparse matrix such as the product of dimensions is greater than %d - this is not supported on this machine """ raise ValueError(msg % np.iinfo(tp).max) # Number of non zero values k = long(density * m * n) # Generate a few more values than k so that we can get unique values # afterwards. # XXX: one could be smarter here mlow = 5 fac = 1.02 gk = min(k + mlow, fac * k) def _gen_unique_rand(_gk): id = np.random.rand(_gk) return np.unique(np.floor(id * mn))[:k] id = _gen_unique_rand(gk) while id.size < k: gk *= 1.05 id = _gen_unique_rand(gk) j = np.floor(id * 1. / m).astype(tp) i = (id - j * m).astype(tp) vals = np.random.rand(k).astype(dtype) return coo_matrix((vals, (i, j)), shape=(m, n)).asformat(format)
Returns
random_line_split
StepLabel.d.ts
import * as React from 'react'; import { SxProps } from '@material-ui/system'; import { InternalStandardProps as StandardProps } from '..'; import { StepIconProps } from '../StepIcon'; import { Theme } from '../styles'; import { StepLabelClasses } from './stepLabelClasses'; export interface StepLabelProps extends StandardProps<React.HTMLAttributes<HTMLDivElement>> { /** * In most cases will simply be a string containing a title for the label. */ children?: React.ReactNode; /** * Override or extend the styles applied to the component. */
* @default false */ error?: boolean; /** * Override the default label of the step icon. */ icon?: React.ReactNode; /** * The optional node to display. */ optional?: React.ReactNode; /** * The component to render in place of the [`StepIcon`](/api/step-icon/). */ StepIconComponent?: React.ElementType; /** * Props applied to the [`StepIcon`](/api/step-icon/) element. */ StepIconProps?: Partial<StepIconProps>; /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx?: SxProps<Theme>; } export type StepLabelClasskey = keyof NonNullable<StepLabelProps['classes']>; /** * * Demos: * * - [Steppers](https://material-ui.com/components/steppers/) * * API: * * - [StepLabel API](https://material-ui.com/api/step-label/) */ declare const StepLabel: ((props: StepLabelProps) => JSX.Element) & { muiName: string }; export default StepLabel;
classes?: Partial<StepLabelClasses>; /** * If `true`, the step is marked as failed.
random_line_split
setup.py
import os from setuptools import setup from setuptools import find_packages version_file = 'VERSION.txt' version = open(version_file).read().strip() description_file = 'README.txt' description = open(description_file).read().split('\n\n')[0].strip() description = description.replace('\n', ' ') long_description_file = os.path.join('doc', 'README.txt') long_description = open(long_description_file).read().strip() setup( name='ximenez', version=version, packages=find_packages('src'), namespace_packages=(), package_dir={'': 'src'}, include_package_data=True,
'console_scripts': ('ximenez=ximenez.xim:main', ) }, author='Damien Baty', author_email='damien.baty@remove-me.gmail.com', description=description, long_description=long_description, license='GNU GPL', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: System', 'Topic :: Utilities'], keywords='collector action plug-in plugin', url='http://code.noherring.com/ximenez', download_url='http://cheeseshop.python.org/pypi/ximenez', )
zip_safe=False, entry_points={
random_line_split
effects.pulsate.js
/* * jQuery UI Effects Pulsate 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Effects/Pulsate * * Depends: * effects.core.js */ (function($) { $.effects.pulsate = function(o) { return this.queue(function() { // Create element var el = $(this); // Set options var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode var times = o.options.times || 5; // Default # of times var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2; // Adjust if (mode == 'hide') times--;
el.animate({opacity: 1}, duration, o.options.easing); times = times-2; } // Animate for (var i = 0; i < times; i++) { // Pulsate el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing); }; if (mode == 'hide') { // Last Pulse el.animate({opacity: 0}, duration, o.options.easing, function(){ el.hide(); // Hide if(o.callback) o.callback.apply(this, arguments); // Callback }); } else { el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing, function(){ if(o.callback) o.callback.apply(this, arguments); // Callback }); }; el.queue('fx', function() { el.dequeue(); }); el.dequeue(); }); }; })(jQuery);
if (el.is(':hidden')) { // Show fadeIn el.css('opacity', 0); el.show(); // Show
random_line_split
icon.rs
use image::{Rgba, RgbaImage}; use imageproc::drawing::draw_text_mut; use image::imageops::resize; use rusttype::{Scale, Font}; use std::ptr::null_mut; use std::collections::HashMap; pub type GeneratedIcon = *mut winapi::shared::windef::HICON__; pub struct IconGenerator { icon_cache: HashMap<u8, GeneratedIcon>, } impl IconGenerator { pub fn new() -> Self { IconGenerator { icon_cache: HashMap::with_capacity(100), } } pub fn generate(&mut self, value: u8) -> GeneratedIcon
fn scale_params(n: usize) -> ((u32, u32), Scale) { match n { 1 => { ((24, 0), Scale { x: 128.0, y: 128.0 }) } 2 => { ((0, 0), Scale { x: 120.0, y: 120.0 }) } _ => { ((0, 20), Scale { x: 80.0, y: 80.0 }) } } } fn create_icon(value: u8) -> GeneratedIcon { let value_to_draw = value.to_string(); let mut image = RgbaImage::new(128, 128); let font = Font::try_from_bytes(include_bytes!("fonts/Arial.ttf")).unwrap(); let scale_params = IconGenerator::scale_params(value_to_draw.len()); let coord = scale_params.0; draw_text_mut( &mut image, Rgba([255u8, 255u8, 255u8, 255u8]), coord.0, coord.1, scale_params.1, &font, &value_to_draw, ); let resized_image = resize( &mut image, 32, 32, image::imageops::FilterType::Lanczos3, ); unsafe { let hbm_mask = winapi::um::wingdi::CreateCompatibleBitmap( winapi::um::winuser::GetDC(null_mut()), 32, 32, ); let bytes_raw = resized_image.into_raw().as_mut_ptr(); let transmuted = std::mem::transmute::<*mut u8, *mut winapi::ctypes::c_void>(bytes_raw); let bitmap: winapi::shared::windef::HBITMAP = winapi::um::wingdi::CreateBitmap(32, 32, 2, 16, transmuted); let mut h_icon = winapi::um::winuser::ICONINFO { fIcon: 1, hbmColor: bitmap, hbmMask: hbm_mask, xHotspot: 0, yHotspot: 0, }; winapi::um::winuser::CreateIconIndirect(&mut h_icon) } } }
{ if self.icon_cache.contains_key(&value) && value != 0 { return self.icon_cache[&value]; } else { let new_icon = IconGenerator::create_icon(value); self.icon_cache.insert(value, new_icon); new_icon } }
identifier_body
icon.rs
use image::{Rgba, RgbaImage}; use imageproc::drawing::draw_text_mut; use image::imageops::resize; use rusttype::{Scale, Font}; use std::ptr::null_mut; use std::collections::HashMap; pub type GeneratedIcon = *mut winapi::shared::windef::HICON__; pub struct IconGenerator { icon_cache: HashMap<u8, GeneratedIcon>, } impl IconGenerator { pub fn new() -> Self { IconGenerator { icon_cache: HashMap::with_capacity(100), } } pub fn generate(&mut self, value: u8) -> GeneratedIcon { if self.icon_cache.contains_key(&value) && value != 0 { return self.icon_cache[&value]; } else { let new_icon = IconGenerator::create_icon(value); self.icon_cache.insert(value, new_icon); new_icon } } fn scale_params(n: usize) -> ((u32, u32), Scale) { match n { 1 => { ((24, 0), Scale { x: 128.0, y: 128.0 }) } 2 => {
} _ => { ((0, 20), Scale { x: 80.0, y: 80.0 }) } } } fn create_icon(value: u8) -> GeneratedIcon { let value_to_draw = value.to_string(); let mut image = RgbaImage::new(128, 128); let font = Font::try_from_bytes(include_bytes!("fonts/Arial.ttf")).unwrap(); let scale_params = IconGenerator::scale_params(value_to_draw.len()); let coord = scale_params.0; draw_text_mut( &mut image, Rgba([255u8, 255u8, 255u8, 255u8]), coord.0, coord.1, scale_params.1, &font, &value_to_draw, ); let resized_image = resize( &mut image, 32, 32, image::imageops::FilterType::Lanczos3, ); unsafe { let hbm_mask = winapi::um::wingdi::CreateCompatibleBitmap( winapi::um::winuser::GetDC(null_mut()), 32, 32, ); let bytes_raw = resized_image.into_raw().as_mut_ptr(); let transmuted = std::mem::transmute::<*mut u8, *mut winapi::ctypes::c_void>(bytes_raw); let bitmap: winapi::shared::windef::HBITMAP = winapi::um::wingdi::CreateBitmap(32, 32, 2, 16, transmuted); let mut h_icon = winapi::um::winuser::ICONINFO { fIcon: 1, hbmColor: bitmap, hbmMask: hbm_mask, xHotspot: 0, yHotspot: 0, }; winapi::um::winuser::CreateIconIndirect(&mut h_icon) } } }
((0, 0), Scale { x: 120.0, y: 120.0 })
random_line_split
icon.rs
use image::{Rgba, RgbaImage}; use imageproc::drawing::draw_text_mut; use image::imageops::resize; use rusttype::{Scale, Font}; use std::ptr::null_mut; use std::collections::HashMap; pub type GeneratedIcon = *mut winapi::shared::windef::HICON__; pub struct IconGenerator { icon_cache: HashMap<u8, GeneratedIcon>, } impl IconGenerator { pub fn new() -> Self { IconGenerator { icon_cache: HashMap::with_capacity(100), } } pub fn
(&mut self, value: u8) -> GeneratedIcon { if self.icon_cache.contains_key(&value) && value != 0 { return self.icon_cache[&value]; } else { let new_icon = IconGenerator::create_icon(value); self.icon_cache.insert(value, new_icon); new_icon } } fn scale_params(n: usize) -> ((u32, u32), Scale) { match n { 1 => { ((24, 0), Scale { x: 128.0, y: 128.0 }) } 2 => { ((0, 0), Scale { x: 120.0, y: 120.0 }) } _ => { ((0, 20), Scale { x: 80.0, y: 80.0 }) } } } fn create_icon(value: u8) -> GeneratedIcon { let value_to_draw = value.to_string(); let mut image = RgbaImage::new(128, 128); let font = Font::try_from_bytes(include_bytes!("fonts/Arial.ttf")).unwrap(); let scale_params = IconGenerator::scale_params(value_to_draw.len()); let coord = scale_params.0; draw_text_mut( &mut image, Rgba([255u8, 255u8, 255u8, 255u8]), coord.0, coord.1, scale_params.1, &font, &value_to_draw, ); let resized_image = resize( &mut image, 32, 32, image::imageops::FilterType::Lanczos3, ); unsafe { let hbm_mask = winapi::um::wingdi::CreateCompatibleBitmap( winapi::um::winuser::GetDC(null_mut()), 32, 32, ); let bytes_raw = resized_image.into_raw().as_mut_ptr(); let transmuted = std::mem::transmute::<*mut u8, *mut winapi::ctypes::c_void>(bytes_raw); let bitmap: winapi::shared::windef::HBITMAP = winapi::um::wingdi::CreateBitmap(32, 32, 2, 16, transmuted); let mut h_icon = winapi::um::winuser::ICONINFO { fIcon: 1, hbmColor: bitmap, hbmMask: hbm_mask, xHotspot: 0, yHotspot: 0, }; winapi::um::winuser::CreateIconIndirect(&mut h_icon) } } }
generate
identifier_name
ResliceBSpline.py
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # this script tests vtkImageReslice with different interpolation modes, # with the wrap-pad feature turned on and with a rotation # Image pipeline reader = vtk.vtkImageReader() reader.ReleaseDataFlagOff() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter") reader.SetDataMask(0x7fff) transform = vtk.vtkTransform() # rotate about the center of the image transform.Translate(+100.8,+100.8,+69.0) transform.RotateWXYZ(10,1,1,0) transform.Translate(-100.8,-100.8,-69.0) bspline3 = vtk.vtkImageBSplineInterpolator() bspline3.SetSplineDegree(3) bspline9 = vtk.vtkImageBSplineInterpolator() bspline9.SetSplineDegree(9) coeffs1 = vtk.vtkImageBSplineCoefficients() coeffs1.SetInputConnection(reader.GetOutputPort()) coeffs1.SetSplineDegree(3) coeffs2 = vtk.vtkImageBSplineCoefficients() coeffs2.SetInputConnection(reader.GetOutputPort()) coeffs2.SetSplineDegree(9) reslice1 = vtk.vtkImageReslice() reslice1.SetInputConnection(coeffs1.GetOutputPort()) reslice1.SetResliceTransform(transform) reslice1.SetInterpolator(bspline3) reslice1.SetOutputSpacing(2.0,2.0,1.5) reslice1.SetOutputOrigin(-32,-32,40) reslice1.SetOutputExtent(0,127,0,127,0,0) reslice2 = vtk.vtkImageReslice() reslice2.SetInputConnection(coeffs1.GetOutputPort()) reslice2.SetInterpolator(bspline3) reslice2.SetOutputSpacing(2.0,2.0,1.5) reslice2.SetOutputOrigin(-32,-32,40) reslice2.SetOutputExtent(0,127,0,127,0,0) reslice3 = vtk.vtkImageReslice() reslice3.SetInputConnection(coeffs2.GetOutputPort()) reslice3.SetResliceTransform(transform) reslice3.SetInterpolator(bspline9) reslice3.SetOutputSpacing(2.0,2.0,1.5) reslice3.SetOutputOrigin(-32,-32,40) reslice3.SetOutputExtent(0,127,0,127,0,0) reslice4 = vtk.vtkImageReslice() reslice4.SetInputConnection(coeffs2.GetOutputPort()) reslice4.SetInterpolator(bspline9) reslice4.SetOutputSpacing(2.0,2.0,1.5) reslice4.SetOutputOrigin(-32,-32,40) reslice4.SetOutputExtent(0,127,0,127,0,0) mapper1 = vtk.vtkImageMapper() mapper1.SetInputConnection(reslice1.GetOutputPort()) mapper1.SetColorWindow(2000) mapper1.SetColorLevel(1000) mapper1.SetZSlice(0) mapper2 = vtk.vtkImageMapper() mapper2.SetInputConnection(reslice2.GetOutputPort()) mapper2.SetColorWindow(2000) mapper2.SetColorLevel(1000) mapper2.SetZSlice(0) mapper3 = vtk.vtkImageMapper() mapper3.SetInputConnection(reslice3.GetOutputPort()) mapper3.SetColorWindow(2000) mapper3.SetColorLevel(1000)
mapper4.SetInputConnection(reslice4.GetOutputPort()) mapper4.SetColorWindow(2000) mapper4.SetColorLevel(1000) mapper4.SetZSlice(0) actor1 = vtk.vtkActor2D() actor1.SetMapper(mapper1) actor2 = vtk.vtkActor2D() actor2.SetMapper(mapper2) actor3 = vtk.vtkActor2D() actor3.SetMapper(mapper3) actor4 = vtk.vtkActor2D() actor4.SetMapper(mapper4) imager1 = vtk.vtkRenderer() imager1.AddActor2D(actor1) imager1.SetViewport(0.5,0.0,1.0,0.5) imager2 = vtk.vtkRenderer() imager2.AddActor2D(actor2) imager2.SetViewport(0.0,0.0,0.5,0.5) imager3 = vtk.vtkRenderer() imager3.AddActor2D(actor3) imager3.SetViewport(0.5,0.5,1.0,1.0) imager4 = vtk.vtkRenderer() imager4.AddActor2D(actor4) imager4.SetViewport(0.0,0.5,0.5,1.0) imgWin = vtk.vtkRenderWindow() imgWin.AddRenderer(imager1) imgWin.AddRenderer(imager2) imgWin.AddRenderer(imager3) imgWin.AddRenderer(imager4) imgWin.SetSize(256,256) imgWin.Render() # --- end of script --
mapper3.SetZSlice(0) mapper4 = vtk.vtkImageMapper()
random_line_split
userFilter.ts
import { SyncService } from '../storage/sync.service'; import { D1ItemUserReview } from '../item-review/d1-dtr-api-types'; import { D2ItemUserReview } from '../item-review/d2-dtr-api-types'; /** * Note a problem user's membership ID so that we can ignore their reviews in the future. * Persists the list of ignored users across sessions. */ export function ignoreUser(reportedMembershipId: string) { return getIgnoredUsers().then((ignoredUsers) => { ignoredUsers.push(reportedMembershipId); return SyncService.set({ ignoredUsers }); }); } /** * Conditionally set the isIgnored flag on a review. * Sets it if the review was written by someone that's already on the ignore list. */ export function conditionallyIgnoreReviews(reviews: (D1ItemUserReview | D2ItemUserReview)[]) { return getIgnoredUsers().then((ignoredUsers) => { for (const review of reviews) { review.isIgnored = ignoredUsers.includes(review.reviewer.membershipId); } }); } /** * Resets the list of ignored users. * This is in for development, but maybe someone else will eventually want? */ export function clearIgnoredUsers() { return SyncService.set({ ignoredUsers: [] }); } function
() { const ignoredUsersKey = 'ignoredUsers'; return SyncService.get().then((data) => data[ignoredUsersKey] || []); }
getIgnoredUsers
identifier_name
userFilter.ts
import { SyncService } from '../storage/sync.service'; import { D1ItemUserReview } from '../item-review/d1-dtr-api-types'; import { D2ItemUserReview } from '../item-review/d2-dtr-api-types'; /** * Note a problem user's membership ID so that we can ignore their reviews in the future. * Persists the list of ignored users across sessions. */ export function ignoreUser(reportedMembershipId: string) { return getIgnoredUsers().then((ignoredUsers) => { ignoredUsers.push(reportedMembershipId); return SyncService.set({ ignoredUsers }); }); } /** * Conditionally set the isIgnored flag on a review. * Sets it if the review was written by someone that's already on the ignore list. */ export function conditionallyIgnoreReviews(reviews: (D1ItemUserReview | D2ItemUserReview)[]) { return getIgnoredUsers().then((ignoredUsers) => { for (const review of reviews) { review.isIgnored = ignoredUsers.includes(review.reviewer.membershipId); } }); } /** * Resets the list of ignored users. * This is in for development, but maybe someone else will eventually want? */ export function clearIgnoredUsers() { return SyncService.set({ ignoredUsers: [] }); }
}
function getIgnoredUsers() { const ignoredUsersKey = 'ignoredUsers'; return SyncService.get().then((data) => data[ignoredUsersKey] || []);
random_line_split
userFilter.ts
import { SyncService } from '../storage/sync.service'; import { D1ItemUserReview } from '../item-review/d1-dtr-api-types'; import { D2ItemUserReview } from '../item-review/d2-dtr-api-types'; /** * Note a problem user's membership ID so that we can ignore their reviews in the future. * Persists the list of ignored users across sessions. */ export function ignoreUser(reportedMembershipId: string) { return getIgnoredUsers().then((ignoredUsers) => { ignoredUsers.push(reportedMembershipId); return SyncService.set({ ignoredUsers }); }); } /** * Conditionally set the isIgnored flag on a review. * Sets it if the review was written by someone that's already on the ignore list. */ export function conditionallyIgnoreReviews(reviews: (D1ItemUserReview | D2ItemUserReview)[]) { return getIgnoredUsers().then((ignoredUsers) => { for (const review of reviews) { review.isIgnored = ignoredUsers.includes(review.reviewer.membershipId); } }); } /** * Resets the list of ignored users. * This is in for development, but maybe someone else will eventually want? */ export function clearIgnoredUsers()
function getIgnoredUsers() { const ignoredUsersKey = 'ignoredUsers'; return SyncService.get().then((data) => data[ignoredUsersKey] || []); }
{ return SyncService.set({ ignoredUsers: [] }); }
identifier_body
Link.tsx
import { h, Component, prop } from 'skatejs'; import { ColorType, cssClassForColorType } from '../_helpers/colorTypes'; import style from './Link.scss'; import { css } from '../_helpers/css'; const LinkTargets = { _self: '_self', _blank: '_blank', _parent: '_parent', _top: '_top', }; interface LinkProps {
hreflang?: string, rel?: string, target?: keyof typeof LinkTargets | string, type?: string, color?: ColorType, } export class Link extends Component<LinkProps> { static get is() { return 'bl-link'; } static get props() { return { href: prop.string( { attribute: true } ), download: prop.string( { attribute: true } ), hreflang: prop.string( { attribute: true } ), referrerpolicy: prop.string( { attribute: true } ), rel: prop.string( { attribute: true } ), target: prop.string( { attribute: true } ), type: prop.string( { attribute: true } ), color: prop.string( { attribute: true } ) }; } href: string; download: string; hreflang: string; rel: string; target: string; type: string; color: ColorType; renderCallback() { const { href, download, hreflang, rel, target, type, color } = this; const colorClass = cssClassForColorType( 'c-link', color ); const className = css( 'c-link', colorClass ); return [ <style>{style}</style>, <a className={className} href={href} download={download} hreflang={hreflang} rel={rel} target={target} type={type} > <slot /> </a> ]; } } customElements.define( Link.is, Link );
href?: string, download?: string,
random_line_split
Link.tsx
import { h, Component, prop } from 'skatejs'; import { ColorType, cssClassForColorType } from '../_helpers/colorTypes'; import style from './Link.scss'; import { css } from '../_helpers/css'; const LinkTargets = { _self: '_self', _blank: '_blank', _parent: '_parent', _top: '_top', }; interface LinkProps { href?: string, download?: string, hreflang?: string, rel?: string, target?: keyof typeof LinkTargets | string, type?: string, color?: ColorType, } export class Link extends Component<LinkProps> { static get is() { return 'bl-link'; } static get
() { return { href: prop.string( { attribute: true } ), download: prop.string( { attribute: true } ), hreflang: prop.string( { attribute: true } ), referrerpolicy: prop.string( { attribute: true } ), rel: prop.string( { attribute: true } ), target: prop.string( { attribute: true } ), type: prop.string( { attribute: true } ), color: prop.string( { attribute: true } ) }; } href: string; download: string; hreflang: string; rel: string; target: string; type: string; color: ColorType; renderCallback() { const { href, download, hreflang, rel, target, type, color } = this; const colorClass = cssClassForColorType( 'c-link', color ); const className = css( 'c-link', colorClass ); return [ <style>{style}</style>, <a className={className} href={href} download={download} hreflang={hreflang} rel={rel} target={target} type={type} > <slot /> </a> ]; } } customElements.define( Link.is, Link );
props
identifier_name
Link.tsx
import { h, Component, prop } from 'skatejs'; import { ColorType, cssClassForColorType } from '../_helpers/colorTypes'; import style from './Link.scss'; import { css } from '../_helpers/css'; const LinkTargets = { _self: '_self', _blank: '_blank', _parent: '_parent', _top: '_top', }; interface LinkProps { href?: string, download?: string, hreflang?: string, rel?: string, target?: keyof typeof LinkTargets | string, type?: string, color?: ColorType, } export class Link extends Component<LinkProps> { static get is() { return 'bl-link'; } static get props()
href: string; download: string; hreflang: string; rel: string; target: string; type: string; color: ColorType; renderCallback() { const { href, download, hreflang, rel, target, type, color } = this; const colorClass = cssClassForColorType( 'c-link', color ); const className = css( 'c-link', colorClass ); return [ <style>{style}</style>, <a className={className} href={href} download={download} hreflang={hreflang} rel={rel} target={target} type={type} > <slot /> </a> ]; } } customElements.define( Link.is, Link );
{ return { href: prop.string( { attribute: true } ), download: prop.string( { attribute: true } ), hreflang: prop.string( { attribute: true } ), referrerpolicy: prop.string( { attribute: true } ), rel: prop.string( { attribute: true } ), target: prop.string( { attribute: true } ), type: prop.string( { attribute: true } ), color: prop.string( { attribute: true } ) }; }
identifier_body
vz-projector.ts
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or 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. ==============================================================================*/ import {ColorOption, ColumnStats, DataPoint, DataProto, DataSet, PointAccessors3D, PointMetadata, Projection, SpriteAndMetadataInfo, State, stateGetAccessorDimensions} from './data'; import {DataProvider, EmbeddingInfo, ServingMode} from './data-provider'; import {DemoDataProvider} from './data-provider-demo'; import {ProtoDataProvider} from './data-provider-proto'; import {ServerDataProvider} from './data-provider-server'; import {HoverContext, HoverListener} from './hoverContext'; import * as knn from './knn'; import * as logging from './logging'; import {ProjectorScatterPlotAdapter} from './projectorScatterPlotAdapter'; import {Mode, ScatterPlot} from './scatterPlot'; import {ScatterPlotVisualizer3DLabels} from './scatterPlotVisualizer3DLabels'; import {ScatterPlotVisualizerCanvasLabels} from './scatterPlotVisualizerCanvasLabels'; import {ScatterPlotVisualizerSprites} from './scatterPlotVisualizerSprites'; import {ScatterPlotVisualizerTraces} from './scatterPlotVisualizerTraces'; import {SelectionChangedListener, SelectionContext} from './selectionContext'; import {BookmarkPanel} from './vz-projector-bookmark-panel'; import {DataPanel} from './vz-projector-data-panel'; import {InspectorPanel} from './vz-projector-inspector-panel'; import {MetadataCard} from './vz-projector-metadata-card'; import {ProjectionsPanel} from './vz-projector-projections-panel'; // tslint:disable-next-line:no-unused-variable import {PolymerElement, PolymerHTMLElement} from './vz-projector-util'; /** * The minimum number of dimensions the data should have to automatically * decide to normalize the data. */ const THRESHOLD_DIM_NORMALIZE = 50; const POINT_COLOR_MISSING = 'black'; export let ProjectorPolymer = PolymerElement({ is: 'vz-projector', properties: { routePrefix: String, dataProto: {type: String, observer: '_dataProtoChanged'}, servingMode: String, projectorConfigJsonPath: String } }); const INDEX_METADATA_FIELD = '__index__'; export class Projector extends ProjectorPolymer implements SelectionContext, HoverContext { // The working subset of the data source's original data set. dataSet: DataSet; servingMode: ServingMode; // The path to the projector config JSON file for demo mode. projectorConfigJsonPath: string; private selectionChangedListeners: SelectionChangedListener[]; private hoverListeners: HoverListener[]; private originalDataSet: DataSet; private dom: d3.Selection<any>; private projectorScatterPlotAdapter: ProjectorScatterPlotAdapter; private scatterPlot: ScatterPlot; private dim: number; private selectedPointIndices: number[]; private neighborsOfFirstPoint: knn.NearestEntry[]; private hoverPointIndex: number; private dataProvider: DataProvider; private inspectorPanel: InspectorPanel; private selectedColorOption: ColorOption; private selectedLabelOption: string; private routePrefix: string; private normalizeData: boolean; private selectedProjection: Projection; private selectedProjectionPointAccessors: PointAccessors3D; /** Polymer component panels */ private dataPanel: DataPanel; private bookmarkPanel: BookmarkPanel; private projectionsPanel: ProjectionsPanel; private metadataCard: MetadataCard; private statusBar: d3.Selection<HTMLElement>; ready() { this.selectionChangedListeners = []; this.hoverListeners = []; this.selectedPointIndices = []; this.neighborsOfFirstPoint = []; this.dom = d3.select(this); logging.setDomContainer(this); this.dataPanel = this.$['data-panel'] as DataPanel; this.inspectorPanel = this.$['inspector-panel'] as InspectorPanel; this.inspectorPanel.initialize(this); this.projectionsPanel = this.$['projections-panel'] as ProjectionsPanel; this.projectionsPanel.initialize(this); this.metadataCard = this.$['metadata-card'] as MetadataCard; this.statusBar = this.dom.select('#status-bar'); this.bookmarkPanel = this.$['bookmark-panel'] as BookmarkPanel; this.scopeSubtree(this.$$('#wrapper-notify-msg'), true); this.setupUIControls(); this.initializeDataProvider(); } setSelectedLabelOption(labelOption: string) { this.selectedLabelOption = labelOption; let labelAccessor = (i: number): string => { return this.dataSet.points[i] .metadata[this.selectedLabelOption] as string; }; this.metadataCard.setLabelOption(this.selectedLabelOption); this.scatterPlot.setLabelAccessor(labelAccessor); this.scatterPlot.render(); } setSelectedColorOption(colorOption: ColorOption) { this.selectedColorOption = colorOption; this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setNormalizeData(normalizeData: boolean) { this.normalizeData = normalizeData; this.setCurrentDataSet(this.originalDataSet.getSubset()); } updateDataSet( ds: DataSet, spriteAndMetadata?: SpriteAndMetadataInfo, metadataFile?: string) { this.originalDataSet = ds; if (this.scatterPlot == null || this.originalDataSet == null) { // We are not ready yet. return; } this.normalizeData = this.originalDataSet.dim[1] >= THRESHOLD_DIM_NORMALIZE; spriteAndMetadata = spriteAndMetadata || {}; if (spriteAndMetadata.pointsInfo == null)
ds.mergeMetadata(spriteAndMetadata); this.dataPanel.setNormalizeData(this.normalizeData); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.inspectorPanel.datasetChanged(); this.inspectorPanel.metadataChanged(spriteAndMetadata); this.projectionsPanel.metadataChanged(spriteAndMetadata); this.dataPanel.metadataChanged(spriteAndMetadata, metadataFile); // Set the container to a fixed height, otherwise in Colab the // height can grow indefinitely. let container = this.dom.select('#container'); container.style('height', container.property('clientHeight') + 'px'); } setSelectedTensor(run: string, tensorInfo: EmbeddingInfo) { this.bookmarkPanel.setSelectedTensor(run, tensorInfo); } /** * Registers a listener to be called any time the selected point set changes. */ registerSelectionChangedListener(listener: SelectionChangedListener) { this.selectionChangedListeners.push(listener); } filterDataset() { let indices = this.selectedPointIndices.concat( this.neighborsOfFirstPoint.map(n => n.index)); let selectionSize = this.selectedPointIndices.length; this.setCurrentDataSet(this.dataSet.getSubset(indices)); this.adjustSelectionAndHover(d3.range(selectionSize)); } resetFilterDataset() { let originalPointIndices = this.selectedPointIndices.map(localIndex => { return this.dataSet.points[localIndex].index; }); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.updateScatterPlotPositions(); this.adjustSelectionAndHover(originalPointIndices); } /** * Used by clients to indicate that a selection has occurred. */ notifySelectionChanged(newSelectedPointIndices: number[]) { this.selectedPointIndices = newSelectedPointIndices; let neighbors: knn.NearestEntry[] = []; if (newSelectedPointIndices.length === 1) { neighbors = this.dataSet.findNeighbors( newSelectedPointIndices[0], this.inspectorPanel.distFunc, this.inspectorPanel.numNN); this.metadataCard.updateMetadata( this.dataSet.points[newSelectedPointIndices[0]].metadata); } else { this.metadataCard.updateMetadata(null); } this.selectionChangedListeners.forEach( l => l(this.selectedPointIndices, neighbors)); } /** * Registers a listener to be called any time the mouse hovers over a point. */ registerHoverListener(listener: HoverListener) { this.hoverListeners.push(listener); } /** * Used by clients to indicate that a hover is occurring. */ notifyHoverOverPoint(pointIndex: number) { this.hoverListeners.forEach(l => l(pointIndex)); } _dataProtoChanged(dataProtoString: string) { let dataProto = dataProtoString ? JSON.parse(dataProtoString) as DataProto : null; this.initializeDataProvider(dataProto); } private makeDefaultPointsInfoAndStats(points: DataPoint[]): [PointMetadata[], ColumnStats[]] { let pointsInfo: PointMetadata[] = []; points.forEach(p => { let pointInfo: PointMetadata = {}; pointInfo[INDEX_METADATA_FIELD] = p.index; pointsInfo.push(pointInfo); }); let stats: ColumnStats[] = [{ name: INDEX_METADATA_FIELD, isNumeric: false, tooManyUniqueValues: true, min: 0, max: pointsInfo.length - 1 }]; return [pointsInfo, stats]; } private initializeDataProvider(dataProto?: DataProto) { if (this.servingMode === 'demo') { this.dataProvider = new DemoDataProvider(this.projectorConfigJsonPath); } else if (this.servingMode === 'server') { if (!this.routePrefix) { throw 'route-prefix is a required parameter'; } this.dataProvider = new ServerDataProvider(this.routePrefix); } else if (this.servingMode === 'proto' && dataProto != null) { this.dataProvider = new ProtoDataProvider(dataProto); } this.dataPanel.initialize(this, this.dataProvider); this.bookmarkPanel.initialize(this, this.dataProvider); } private getLegendPointColorer(colorOption: ColorOption): (index: number) => string { if ((colorOption == null) || (colorOption.map == null)) { return null; } const colorer = (i: number) => { let value = this.dataSet.points[i].metadata[this.selectedColorOption.name]; if (value == null) { return POINT_COLOR_MISSING; } return colorOption.map(value); }; return colorer; } private get3DLabelModeButton(): any { return this.querySelector('#labels3DMode'); } private get3DLabelMode(): boolean { const label3DModeButton = this.get3DLabelModeButton(); return (label3DModeButton as any).active; } private getSpriteImageMode(): boolean { return this.dataSet && this.dataSet.spriteAndMetadataInfo && this.dataSet.spriteAndMetadataInfo.spriteImage != null; } adjustSelectionAndHover(selectedPointIndices: number[], hoverIndex?: number) { this.notifySelectionChanged(selectedPointIndices); this.notifyHoverOverPoint(hoverIndex); this.scatterPlot.setMode(Mode.HOVER); } private unsetCurrentDataSet() { this.dataSet.stopTSNE(); } private setCurrentDataSet(ds: DataSet) { this.adjustSelectionAndHover([]); if (this.dataSet != null) { this.unsetCurrentDataSet(); } this.dataSet = ds; if (this.normalizeData) { this.dataSet.normalize(); } this.dim = this.dataSet.dim[1]; this.dom.select('span.numDataPoints').text(this.dataSet.dim[0]); this.dom.select('span.dim').text(this.dataSet.dim[1]); this.selectedProjectionPointAccessors = null; this.projectionsPanel.dataSetUpdated( this.dataSet, this.originalDataSet, this.dim); this.scatterPlot.setCameraParametersForNextCameraCreation(null, true); } private setupUIControls() { // View controls this.querySelector('#reset-zoom').addEventListener('click', () => { this.scatterPlot.resetZoom(); this.scatterPlot.startOrbitAnimation(); }); let selectModeButton = this.querySelector('#selectMode'); selectModeButton.addEventListener('click', (event) => { this.scatterPlot.setMode( (selectModeButton as any).active ? Mode.SELECT : Mode.HOVER); }); let nightModeButton = this.querySelector('#nightDayMode'); nightModeButton.addEventListener('click', () => { this.scatterPlot.setDayNightMode((nightModeButton as any).active); }); const labels3DModeButton = this.get3DLabelModeButton(); labels3DModeButton.addEventListener('click', () => { this.createVisualizers(this.get3DLabelMode()); this.updateScatterPlotAttributes(); this.scatterPlot.render(); }); window.addEventListener('resize', () => { let container = this.dom.select('#container'); let parentHeight = (container.node().parentNode as HTMLElement).clientHeight; container.style('height', parentHeight + 'px'); this.scatterPlot.resize(); }); this.projectorScatterPlotAdapter = new ProjectorScatterPlotAdapter(); this.scatterPlot = new ScatterPlot( this.getScatterContainer(), i => '' + this.dataSet.points[i].metadata[this.selectedLabelOption], this, this); this.createVisualizers(false); this.scatterPlot.onCameraMove( (cameraPosition: THREE.Vector3, cameraTarget: THREE.Vector3) => this.bookmarkPanel.clearStateSelection()); this.registerHoverListener( (hoverIndex: number) => this.onHover(hoverIndex)); this.registerSelectionChangedListener( (selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) => this.onSelectionChanged( selectedPointIndices, neighborsOfFirstPoint)); this.scatterPlot.resize(); this.scatterPlot.render(); } private onHover(hoverIndex: number) { this.hoverPointIndex = hoverIndex; let hoverText = null; if (hoverIndex != null) { const point = this.dataSet.points[hoverIndex]; if (point.metadata[this.selectedLabelOption]) { hoverText = point.metadata[this.selectedLabelOption].toString(); } } this.updateScatterPlotAttributes(); this.scatterPlot.render(); if (this.selectedPointIndices.length === 0) { this.statusBar.style('display', hoverText ? null : 'none'); this.statusBar.text(hoverText); } } private updateScatterPlotPositions() { if (this.dataSet == null) { return; } if (this.selectedProjectionPointAccessors == null) { return; } const newPositions = this.projectorScatterPlotAdapter.generatePointPositionArray( this.dataSet, this.selectedProjectionPointAccessors); this.scatterPlot.setPointPositions(this.dataSet, newPositions); } private updateScatterPlotAttributes() { const dataSet = this.dataSet; const selectedSet = this.selectedPointIndices; const hoverIndex = this.hoverPointIndex; const neighbors = this.neighborsOfFirstPoint; const pointColorer = this.getLegendPointColorer(this.selectedColorOption); const adapter = this.projectorScatterPlotAdapter; const pointColors = adapter.generatePointColorArray( dataSet, pointColorer, selectedSet, neighbors, hoverIndex, this.get3DLabelMode(), this.getSpriteImageMode()); const pointScaleFactors = adapter.generatePointScaleFactorArray( dataSet, selectedSet, neighbors, hoverIndex); const labels = adapter.generateVisibleLabelRenderParams( dataSet, selectedSet, neighbors, hoverIndex); const traceColors = adapter.generateLineSegmentColorMap(dataSet, pointColorer); const traceOpacities = adapter.generateLineSegmentOpacityArray(dataSet, selectedSet); const traceWidths = adapter.generateLineSegmentWidthArray(dataSet, selectedSet); this.scatterPlot.setPointColors(pointColors); this.scatterPlot.setPointScaleFactors(pointScaleFactors); this.scatterPlot.setLabels(labels); this.scatterPlot.setTraceColors(traceColors); this.scatterPlot.setTraceOpacities(traceOpacities); this.scatterPlot.setTraceWidths(traceWidths); } private getScatterContainer(): d3.Selection<any> { return this.dom.select('#scatter'); } private createVisualizers(inLabels3DMode: boolean) { const scatterPlot = this.scatterPlot; scatterPlot.removeAllVisualizers(); if (inLabels3DMode) { scatterPlot.addVisualizer(new ScatterPlotVisualizer3DLabels()); } else { scatterPlot.addVisualizer(new ScatterPlotVisualizerSprites()); scatterPlot.addVisualizer( new ScatterPlotVisualizerCanvasLabels(this.getScatterContainer())); } scatterPlot.addVisualizer(new ScatterPlotVisualizerTraces()); } private onSelectionChanged( selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) { this.selectedPointIndices = selectedPointIndices; this.neighborsOfFirstPoint = neighborsOfFirstPoint; let totalNumPoints = this.selectedPointIndices.length + neighborsOfFirstPoint.length; this.statusBar.text(`Selected ${totalNumPoints} points`) .style('display', totalNumPoints > 0 ? null : 'none'); this.inspectorPanel.updateInspectorPane( selectedPointIndices, neighborsOfFirstPoint); this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setProjection( projection: Projection, dimensionality: number, pointAccessors: PointAccessors3D) { this.selectedProjection = projection; this.selectedProjectionPointAccessors = pointAccessors; this.scatterPlot.setDimensions(dimensionality); if (this.dataSet.projectionCanBeRendered(projection)) { this.updateScatterPlotAttributes(); this.notifyProjectionsUpdated(); } this.scatterPlot.setCameraParametersForNextCameraCreation(null, false); } notifyProjectionsUpdated() { this.updateScatterPlotPositions(); this.scatterPlot.render(); } /** * Gets the current view of the embedding and saves it as a State object. */ getCurrentState(): State { const state = new State(); // Save the individual datapoint projections. state.projections = []; for (let i = 0; i < this.dataSet.points.length; i++) { const point = this.dataSet.points[i]; const projections: {[key: string]: number} = {}; const keys = Object.keys(point.projections); for (let j = 0; j < keys.length; ++j) { projections[keys[j]] = point.projections[keys[j]]; } state.projections.push(projections); } state.selectedProjection = this.selectedProjection; state.dataSetDimensions = this.dataSet.dim; state.tSNEIteration = this.dataSet.tSNEIteration; state.selectedPoints = this.selectedPointIndices; state.cameraDef = this.scatterPlot.getCameraDef(); state.selectedColorOptionName = this.dataPanel.selectedColorOptionName; state.selectedLabelOption = this.selectedLabelOption; this.projectionsPanel.populateBookmarkFromUI(state); return state; } /** Loads a State object into the world. */ loadState(state: State) { for (let i = 0; i < state.projections.length; i++) { const point = this.dataSet.points[i]; const projection = state.projections[i]; const keys = Object.keys(projection); for (let j = 0; j < keys.length; ++j) { point.projections[keys[j]] = projection[keys[j]]; } } this.dataSet.hasTSNERun = (state.selectedProjection === 'tsne'); this.dataSet.tSNEIteration = state.tSNEIteration; this.projectionsPanel.restoreUIFromBookmark(state); this.dataPanel.selectedColorOptionName = state.selectedColorOptionName; this.selectedLabelOption = state.selectedLabelOption; this.scatterPlot.setCameraParametersForNextCameraCreation( state.cameraDef, false); { const dimensions = stateGetAccessorDimensions(state); const accessors = this.dataSet.getPointAccessors(state.selectedProjection, dimensions); this.setProjection( state.selectedProjection, dimensions.length, accessors); } this.notifySelectionChanged(state.selectedPoints); } } document.registerElement(Projector.prototype.is, Projector);
{ let [pointsInfo, stats] = this.makeDefaultPointsInfoAndStats(ds.points); spriteAndMetadata.pointsInfo = pointsInfo; spriteAndMetadata.stats = stats; }
conditional_block
vz-projector.ts
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or 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. ==============================================================================*/ import {ColorOption, ColumnStats, DataPoint, DataProto, DataSet, PointAccessors3D, PointMetadata, Projection, SpriteAndMetadataInfo, State, stateGetAccessorDimensions} from './data'; import {DataProvider, EmbeddingInfo, ServingMode} from './data-provider'; import {DemoDataProvider} from './data-provider-demo'; import {ProtoDataProvider} from './data-provider-proto'; import {ServerDataProvider} from './data-provider-server'; import {HoverContext, HoverListener} from './hoverContext'; import * as knn from './knn'; import * as logging from './logging'; import {ProjectorScatterPlotAdapter} from './projectorScatterPlotAdapter'; import {Mode, ScatterPlot} from './scatterPlot'; import {ScatterPlotVisualizer3DLabels} from './scatterPlotVisualizer3DLabels'; import {ScatterPlotVisualizerCanvasLabels} from './scatterPlotVisualizerCanvasLabels'; import {ScatterPlotVisualizerSprites} from './scatterPlotVisualizerSprites'; import {ScatterPlotVisualizerTraces} from './scatterPlotVisualizerTraces'; import {SelectionChangedListener, SelectionContext} from './selectionContext'; import {BookmarkPanel} from './vz-projector-bookmark-panel'; import {DataPanel} from './vz-projector-data-panel'; import {InspectorPanel} from './vz-projector-inspector-panel'; import {MetadataCard} from './vz-projector-metadata-card'; import {ProjectionsPanel} from './vz-projector-projections-panel'; // tslint:disable-next-line:no-unused-variable import {PolymerElement, PolymerHTMLElement} from './vz-projector-util'; /** * The minimum number of dimensions the data should have to automatically * decide to normalize the data. */ const THRESHOLD_DIM_NORMALIZE = 50; const POINT_COLOR_MISSING = 'black'; export let ProjectorPolymer = PolymerElement({ is: 'vz-projector', properties: { routePrefix: String, dataProto: {type: String, observer: '_dataProtoChanged'}, servingMode: String, projectorConfigJsonPath: String } }); const INDEX_METADATA_FIELD = '__index__'; export class Projector extends ProjectorPolymer implements SelectionContext, HoverContext { // The working subset of the data source's original data set. dataSet: DataSet; servingMode: ServingMode; // The path to the projector config JSON file for demo mode. projectorConfigJsonPath: string; private selectionChangedListeners: SelectionChangedListener[]; private hoverListeners: HoverListener[]; private originalDataSet: DataSet; private dom: d3.Selection<any>; private projectorScatterPlotAdapter: ProjectorScatterPlotAdapter; private scatterPlot: ScatterPlot; private dim: number; private selectedPointIndices: number[]; private neighborsOfFirstPoint: knn.NearestEntry[]; private hoverPointIndex: number; private dataProvider: DataProvider; private inspectorPanel: InspectorPanel; private selectedColorOption: ColorOption; private selectedLabelOption: string; private routePrefix: string; private normalizeData: boolean; private selectedProjection: Projection; private selectedProjectionPointAccessors: PointAccessors3D; /** Polymer component panels */ private dataPanel: DataPanel; private bookmarkPanel: BookmarkPanel; private projectionsPanel: ProjectionsPanel; private metadataCard: MetadataCard; private statusBar: d3.Selection<HTMLElement>; ready() { this.selectionChangedListeners = []; this.hoverListeners = []; this.selectedPointIndices = []; this.neighborsOfFirstPoint = []; this.dom = d3.select(this); logging.setDomContainer(this); this.dataPanel = this.$['data-panel'] as DataPanel; this.inspectorPanel = this.$['inspector-panel'] as InspectorPanel; this.inspectorPanel.initialize(this); this.projectionsPanel = this.$['projections-panel'] as ProjectionsPanel; this.projectionsPanel.initialize(this); this.metadataCard = this.$['metadata-card'] as MetadataCard; this.statusBar = this.dom.select('#status-bar'); this.bookmarkPanel = this.$['bookmark-panel'] as BookmarkPanel; this.scopeSubtree(this.$$('#wrapper-notify-msg'), true); this.setupUIControls(); this.initializeDataProvider(); } setSelectedLabelOption(labelOption: string) { this.selectedLabelOption = labelOption; let labelAccessor = (i: number): string => { return this.dataSet.points[i] .metadata[this.selectedLabelOption] as string; }; this.metadataCard.setLabelOption(this.selectedLabelOption); this.scatterPlot.setLabelAccessor(labelAccessor); this.scatterPlot.render(); } setSelectedColorOption(colorOption: ColorOption) { this.selectedColorOption = colorOption; this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setNormalizeData(normalizeData: boolean) { this.normalizeData = normalizeData; this.setCurrentDataSet(this.originalDataSet.getSubset()); } updateDataSet( ds: DataSet, spriteAndMetadata?: SpriteAndMetadataInfo, metadataFile?: string) { this.originalDataSet = ds; if (this.scatterPlot == null || this.originalDataSet == null) { // We are not ready yet. return; } this.normalizeData = this.originalDataSet.dim[1] >= THRESHOLD_DIM_NORMALIZE; spriteAndMetadata = spriteAndMetadata || {}; if (spriteAndMetadata.pointsInfo == null) { let [pointsInfo, stats] = this.makeDefaultPointsInfoAndStats(ds.points); spriteAndMetadata.pointsInfo = pointsInfo; spriteAndMetadata.stats = stats; } ds.mergeMetadata(spriteAndMetadata); this.dataPanel.setNormalizeData(this.normalizeData); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.inspectorPanel.datasetChanged(); this.inspectorPanel.metadataChanged(spriteAndMetadata); this.projectionsPanel.metadataChanged(spriteAndMetadata); this.dataPanel.metadataChanged(spriteAndMetadata, metadataFile); // Set the container to a fixed height, otherwise in Colab the // height can grow indefinitely. let container = this.dom.select('#container'); container.style('height', container.property('clientHeight') + 'px'); } setSelectedTensor(run: string, tensorInfo: EmbeddingInfo) { this.bookmarkPanel.setSelectedTensor(run, tensorInfo); } /** * Registers a listener to be called any time the selected point set changes. */ registerSelectionChangedListener(listener: SelectionChangedListener) { this.selectionChangedListeners.push(listener); } filterDataset() { let indices = this.selectedPointIndices.concat( this.neighborsOfFirstPoint.map(n => n.index)); let selectionSize = this.selectedPointIndices.length; this.setCurrentDataSet(this.dataSet.getSubset(indices)); this.adjustSelectionAndHover(d3.range(selectionSize)); } resetFilterDataset() { let originalPointIndices = this.selectedPointIndices.map(localIndex => { return this.dataSet.points[localIndex].index; }); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.updateScatterPlotPositions(); this.adjustSelectionAndHover(originalPointIndices); } /** * Used by clients to indicate that a selection has occurred. */ notifySelectionChanged(newSelectedPointIndices: number[]) { this.selectedPointIndices = newSelectedPointIndices; let neighbors: knn.NearestEntry[] = []; if (newSelectedPointIndices.length === 1) { neighbors = this.dataSet.findNeighbors( newSelectedPointIndices[0], this.inspectorPanel.distFunc, this.inspectorPanel.numNN); this.metadataCard.updateMetadata( this.dataSet.points[newSelectedPointIndices[0]].metadata); } else { this.metadataCard.updateMetadata(null); } this.selectionChangedListeners.forEach( l => l(this.selectedPointIndices, neighbors)); } /** * Registers a listener to be called any time the mouse hovers over a point. */ registerHoverListener(listener: HoverListener) { this.hoverListeners.push(listener); } /** * Used by clients to indicate that a hover is occurring. */ notifyHoverOverPoint(pointIndex: number) { this.hoverListeners.forEach(l => l(pointIndex)); } _dataProtoChanged(dataProtoString: string) { let dataProto = dataProtoString ? JSON.parse(dataProtoString) as DataProto : null; this.initializeDataProvider(dataProto); } private makeDefaultPointsInfoAndStats(points: DataPoint[]): [PointMetadata[], ColumnStats[]] { let pointsInfo: PointMetadata[] = []; points.forEach(p => { let pointInfo: PointMetadata = {}; pointInfo[INDEX_METADATA_FIELD] = p.index; pointsInfo.push(pointInfo); }); let stats: ColumnStats[] = [{ name: INDEX_METADATA_FIELD, isNumeric: false, tooManyUniqueValues: true, min: 0, max: pointsInfo.length - 1 }]; return [pointsInfo, stats]; } private initializeDataProvider(dataProto?: DataProto) { if (this.servingMode === 'demo') { this.dataProvider = new DemoDataProvider(this.projectorConfigJsonPath); } else if (this.servingMode === 'server') { if (!this.routePrefix) { throw 'route-prefix is a required parameter'; } this.dataProvider = new ServerDataProvider(this.routePrefix); } else if (this.servingMode === 'proto' && dataProto != null) { this.dataProvider = new ProtoDataProvider(dataProto); } this.dataPanel.initialize(this, this.dataProvider); this.bookmarkPanel.initialize(this, this.dataProvider); } private getLegendPointColorer(colorOption: ColorOption): (index: number) => string { if ((colorOption == null) || (colorOption.map == null)) { return null; } const colorer = (i: number) => { let value = this.dataSet.points[i].metadata[this.selectedColorOption.name]; if (value == null) { return POINT_COLOR_MISSING; } return colorOption.map(value); }; return colorer; } private get3DLabelModeButton(): any { return this.querySelector('#labels3DMode'); } private get3DLabelMode(): boolean { const label3DModeButton = this.get3DLabelModeButton(); return (label3DModeButton as any).active; } private getSpriteImageMode(): boolean { return this.dataSet && this.dataSet.spriteAndMetadataInfo && this.dataSet.spriteAndMetadataInfo.spriteImage != null; } adjustSelectionAndHover(selectedPointIndices: number[], hoverIndex?: number) { this.notifySelectionChanged(selectedPointIndices); this.notifyHoverOverPoint(hoverIndex); this.scatterPlot.setMode(Mode.HOVER); } private unsetCurrentDataSet() { this.dataSet.stopTSNE(); } private setCurrentDataSet(ds: DataSet) { this.adjustSelectionAndHover([]); if (this.dataSet != null) { this.unsetCurrentDataSet(); } this.dataSet = ds; if (this.normalizeData) { this.dataSet.normalize(); } this.dim = this.dataSet.dim[1]; this.dom.select('span.numDataPoints').text(this.dataSet.dim[0]); this.dom.select('span.dim').text(this.dataSet.dim[1]); this.selectedProjectionPointAccessors = null; this.projectionsPanel.dataSetUpdated( this.dataSet, this.originalDataSet, this.dim); this.scatterPlot.setCameraParametersForNextCameraCreation(null, true); } private setupUIControls() { // View controls this.querySelector('#reset-zoom').addEventListener('click', () => { this.scatterPlot.resetZoom(); this.scatterPlot.startOrbitAnimation(); }); let selectModeButton = this.querySelector('#selectMode'); selectModeButton.addEventListener('click', (event) => { this.scatterPlot.setMode( (selectModeButton as any).active ? Mode.SELECT : Mode.HOVER); }); let nightModeButton = this.querySelector('#nightDayMode'); nightModeButton.addEventListener('click', () => { this.scatterPlot.setDayNightMode((nightModeButton as any).active); }); const labels3DModeButton = this.get3DLabelModeButton(); labels3DModeButton.addEventListener('click', () => { this.createVisualizers(this.get3DLabelMode()); this.updateScatterPlotAttributes(); this.scatterPlot.render(); }); window.addEventListener('resize', () => { let container = this.dom.select('#container'); let parentHeight = (container.node().parentNode as HTMLElement).clientHeight; container.style('height', parentHeight + 'px'); this.scatterPlot.resize(); }); this.projectorScatterPlotAdapter = new ProjectorScatterPlotAdapter(); this.scatterPlot = new ScatterPlot( this.getScatterContainer(), i => '' + this.dataSet.points[i].metadata[this.selectedLabelOption], this, this); this.createVisualizers(false); this.scatterPlot.onCameraMove( (cameraPosition: THREE.Vector3, cameraTarget: THREE.Vector3) => this.bookmarkPanel.clearStateSelection()); this.registerHoverListener( (hoverIndex: number) => this.onHover(hoverIndex)); this.registerSelectionChangedListener( (selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) => this.onSelectionChanged( selectedPointIndices, neighborsOfFirstPoint)); this.scatterPlot.resize(); this.scatterPlot.render(); } private onHover(hoverIndex: number) { this.hoverPointIndex = hoverIndex; let hoverText = null; if (hoverIndex != null) { const point = this.dataSet.points[hoverIndex]; if (point.metadata[this.selectedLabelOption]) { hoverText = point.metadata[this.selectedLabelOption].toString(); } } this.updateScatterPlotAttributes(); this.scatterPlot.render(); if (this.selectedPointIndices.length === 0) { this.statusBar.style('display', hoverText ? null : 'none'); this.statusBar.text(hoverText); } } private updateScatterPlotPositions() { if (this.dataSet == null) { return; } if (this.selectedProjectionPointAccessors == null) { return; } const newPositions = this.projectorScatterPlotAdapter.generatePointPositionArray( this.dataSet, this.selectedProjectionPointAccessors); this.scatterPlot.setPointPositions(this.dataSet, newPositions); } private updateScatterPlotAttributes() { const dataSet = this.dataSet; const selectedSet = this.selectedPointIndices; const hoverIndex = this.hoverPointIndex; const neighbors = this.neighborsOfFirstPoint; const pointColorer = this.getLegendPointColorer(this.selectedColorOption); const adapter = this.projectorScatterPlotAdapter; const pointColors = adapter.generatePointColorArray( dataSet, pointColorer, selectedSet, neighbors, hoverIndex, this.get3DLabelMode(), this.getSpriteImageMode()); const pointScaleFactors = adapter.generatePointScaleFactorArray( dataSet, selectedSet, neighbors, hoverIndex); const labels = adapter.generateVisibleLabelRenderParams( dataSet, selectedSet, neighbors, hoverIndex); const traceColors = adapter.generateLineSegmentColorMap(dataSet, pointColorer); const traceOpacities = adapter.generateLineSegmentOpacityArray(dataSet, selectedSet); const traceWidths = adapter.generateLineSegmentWidthArray(dataSet, selectedSet); this.scatterPlot.setPointColors(pointColors); this.scatterPlot.setPointScaleFactors(pointScaleFactors); this.scatterPlot.setLabels(labels); this.scatterPlot.setTraceColors(traceColors); this.scatterPlot.setTraceOpacities(traceOpacities); this.scatterPlot.setTraceWidths(traceWidths); } private getScatterContainer(): d3.Selection<any> { return this.dom.select('#scatter'); } private createVisualizers(inLabels3DMode: boolean) { const scatterPlot = this.scatterPlot; scatterPlot.removeAllVisualizers(); if (inLabels3DMode) { scatterPlot.addVisualizer(new ScatterPlotVisualizer3DLabels()); } else { scatterPlot.addVisualizer(new ScatterPlotVisualizerSprites()); scatterPlot.addVisualizer( new ScatterPlotVisualizerCanvasLabels(this.getScatterContainer())); } scatterPlot.addVisualizer(new ScatterPlotVisualizerTraces()); } private onSelectionChanged( selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) { this.selectedPointIndices = selectedPointIndices; this.neighborsOfFirstPoint = neighborsOfFirstPoint; let totalNumPoints = this.selectedPointIndices.length + neighborsOfFirstPoint.length; this.statusBar.text(`Selected ${totalNumPoints} points`) .style('display', totalNumPoints > 0 ? null : 'none'); this.inspectorPanel.updateInspectorPane( selectedPointIndices, neighborsOfFirstPoint); this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setProjection( projection: Projection, dimensionality: number, pointAccessors: PointAccessors3D)
notifyProjectionsUpdated() { this.updateScatterPlotPositions(); this.scatterPlot.render(); } /** * Gets the current view of the embedding and saves it as a State object. */ getCurrentState(): State { const state = new State(); // Save the individual datapoint projections. state.projections = []; for (let i = 0; i < this.dataSet.points.length; i++) { const point = this.dataSet.points[i]; const projections: {[key: string]: number} = {}; const keys = Object.keys(point.projections); for (let j = 0; j < keys.length; ++j) { projections[keys[j]] = point.projections[keys[j]]; } state.projections.push(projections); } state.selectedProjection = this.selectedProjection; state.dataSetDimensions = this.dataSet.dim; state.tSNEIteration = this.dataSet.tSNEIteration; state.selectedPoints = this.selectedPointIndices; state.cameraDef = this.scatterPlot.getCameraDef(); state.selectedColorOptionName = this.dataPanel.selectedColorOptionName; state.selectedLabelOption = this.selectedLabelOption; this.projectionsPanel.populateBookmarkFromUI(state); return state; } /** Loads a State object into the world. */ loadState(state: State) { for (let i = 0; i < state.projections.length; i++) { const point = this.dataSet.points[i]; const projection = state.projections[i]; const keys = Object.keys(projection); for (let j = 0; j < keys.length; ++j) { point.projections[keys[j]] = projection[keys[j]]; } } this.dataSet.hasTSNERun = (state.selectedProjection === 'tsne'); this.dataSet.tSNEIteration = state.tSNEIteration; this.projectionsPanel.restoreUIFromBookmark(state); this.dataPanel.selectedColorOptionName = state.selectedColorOptionName; this.selectedLabelOption = state.selectedLabelOption; this.scatterPlot.setCameraParametersForNextCameraCreation( state.cameraDef, false); { const dimensions = stateGetAccessorDimensions(state); const accessors = this.dataSet.getPointAccessors(state.selectedProjection, dimensions); this.setProjection( state.selectedProjection, dimensions.length, accessors); } this.notifySelectionChanged(state.selectedPoints); } } document.registerElement(Projector.prototype.is, Projector);
{ this.selectedProjection = projection; this.selectedProjectionPointAccessors = pointAccessors; this.scatterPlot.setDimensions(dimensionality); if (this.dataSet.projectionCanBeRendered(projection)) { this.updateScatterPlotAttributes(); this.notifyProjectionsUpdated(); } this.scatterPlot.setCameraParametersForNextCameraCreation(null, false); }
identifier_body
vz-projector.ts
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or 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. ==============================================================================*/ import {ColorOption, ColumnStats, DataPoint, DataProto, DataSet, PointAccessors3D, PointMetadata, Projection, SpriteAndMetadataInfo, State, stateGetAccessorDimensions} from './data'; import {DataProvider, EmbeddingInfo, ServingMode} from './data-provider'; import {DemoDataProvider} from './data-provider-demo'; import {ProtoDataProvider} from './data-provider-proto'; import {ServerDataProvider} from './data-provider-server'; import {HoverContext, HoverListener} from './hoverContext'; import * as knn from './knn'; import * as logging from './logging'; import {ProjectorScatterPlotAdapter} from './projectorScatterPlotAdapter'; import {Mode, ScatterPlot} from './scatterPlot'; import {ScatterPlotVisualizer3DLabels} from './scatterPlotVisualizer3DLabels'; import {ScatterPlotVisualizerCanvasLabels} from './scatterPlotVisualizerCanvasLabels'; import {ScatterPlotVisualizerSprites} from './scatterPlotVisualizerSprites'; import {ScatterPlotVisualizerTraces} from './scatterPlotVisualizerTraces'; import {SelectionChangedListener, SelectionContext} from './selectionContext'; import {BookmarkPanel} from './vz-projector-bookmark-panel'; import {DataPanel} from './vz-projector-data-panel'; import {InspectorPanel} from './vz-projector-inspector-panel'; import {MetadataCard} from './vz-projector-metadata-card'; import {ProjectionsPanel} from './vz-projector-projections-panel'; // tslint:disable-next-line:no-unused-variable import {PolymerElement, PolymerHTMLElement} from './vz-projector-util'; /** * The minimum number of dimensions the data should have to automatically * decide to normalize the data. */ const THRESHOLD_DIM_NORMALIZE = 50; const POINT_COLOR_MISSING = 'black'; export let ProjectorPolymer = PolymerElement({ is: 'vz-projector', properties: { routePrefix: String, dataProto: {type: String, observer: '_dataProtoChanged'}, servingMode: String, projectorConfigJsonPath: String } }); const INDEX_METADATA_FIELD = '__index__'; export class Projector extends ProjectorPolymer implements SelectionContext, HoverContext { // The working subset of the data source's original data set. dataSet: DataSet; servingMode: ServingMode; // The path to the projector config JSON file for demo mode. projectorConfigJsonPath: string; private selectionChangedListeners: SelectionChangedListener[]; private hoverListeners: HoverListener[]; private originalDataSet: DataSet; private dom: d3.Selection<any>; private projectorScatterPlotAdapter: ProjectorScatterPlotAdapter; private scatterPlot: ScatterPlot; private dim: number; private selectedPointIndices: number[]; private neighborsOfFirstPoint: knn.NearestEntry[]; private hoverPointIndex: number; private dataProvider: DataProvider; private inspectorPanel: InspectorPanel; private selectedColorOption: ColorOption; private selectedLabelOption: string; private routePrefix: string; private normalizeData: boolean; private selectedProjection: Projection; private selectedProjectionPointAccessors: PointAccessors3D; /** Polymer component panels */ private dataPanel: DataPanel; private bookmarkPanel: BookmarkPanel; private projectionsPanel: ProjectionsPanel; private metadataCard: MetadataCard; private statusBar: d3.Selection<HTMLElement>; ready() { this.selectionChangedListeners = []; this.hoverListeners = []; this.selectedPointIndices = []; this.neighborsOfFirstPoint = []; this.dom = d3.select(this); logging.setDomContainer(this); this.dataPanel = this.$['data-panel'] as DataPanel; this.inspectorPanel = this.$['inspector-panel'] as InspectorPanel; this.inspectorPanel.initialize(this); this.projectionsPanel = this.$['projections-panel'] as ProjectionsPanel; this.projectionsPanel.initialize(this); this.metadataCard = this.$['metadata-card'] as MetadataCard; this.statusBar = this.dom.select('#status-bar'); this.bookmarkPanel = this.$['bookmark-panel'] as BookmarkPanel; this.scopeSubtree(this.$$('#wrapper-notify-msg'), true); this.setupUIControls(); this.initializeDataProvider(); } setSelectedLabelOption(labelOption: string) { this.selectedLabelOption = labelOption; let labelAccessor = (i: number): string => { return this.dataSet.points[i] .metadata[this.selectedLabelOption] as string; }; this.metadataCard.setLabelOption(this.selectedLabelOption); this.scatterPlot.setLabelAccessor(labelAccessor); this.scatterPlot.render(); } setSelectedColorOption(colorOption: ColorOption) { this.selectedColorOption = colorOption; this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setNormalizeData(normalizeData: boolean) { this.normalizeData = normalizeData; this.setCurrentDataSet(this.originalDataSet.getSubset()); } updateDataSet( ds: DataSet, spriteAndMetadata?: SpriteAndMetadataInfo, metadataFile?: string) { this.originalDataSet = ds; if (this.scatterPlot == null || this.originalDataSet == null) { // We are not ready yet. return; } this.normalizeData = this.originalDataSet.dim[1] >= THRESHOLD_DIM_NORMALIZE; spriteAndMetadata = spriteAndMetadata || {}; if (spriteAndMetadata.pointsInfo == null) { let [pointsInfo, stats] = this.makeDefaultPointsInfoAndStats(ds.points); spriteAndMetadata.pointsInfo = pointsInfo; spriteAndMetadata.stats = stats; } ds.mergeMetadata(spriteAndMetadata); this.dataPanel.setNormalizeData(this.normalizeData); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.inspectorPanel.datasetChanged(); this.inspectorPanel.metadataChanged(spriteAndMetadata); this.projectionsPanel.metadataChanged(spriteAndMetadata); this.dataPanel.metadataChanged(spriteAndMetadata, metadataFile); // Set the container to a fixed height, otherwise in Colab the // height can grow indefinitely. let container = this.dom.select('#container'); container.style('height', container.property('clientHeight') + 'px'); } setSelectedTensor(run: string, tensorInfo: EmbeddingInfo) { this.bookmarkPanel.setSelectedTensor(run, tensorInfo); } /** * Registers a listener to be called any time the selected point set changes. */ registerSelectionChangedListener(listener: SelectionChangedListener) { this.selectionChangedListeners.push(listener); } filterDataset() { let indices = this.selectedPointIndices.concat( this.neighborsOfFirstPoint.map(n => n.index)); let selectionSize = this.selectedPointIndices.length; this.setCurrentDataSet(this.dataSet.getSubset(indices)); this.adjustSelectionAndHover(d3.range(selectionSize)); } resetFilterDataset() { let originalPointIndices = this.selectedPointIndices.map(localIndex => { return this.dataSet.points[localIndex].index; }); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.updateScatterPlotPositions(); this.adjustSelectionAndHover(originalPointIndices); } /** * Used by clients to indicate that a selection has occurred. */ notifySelectionChanged(newSelectedPointIndices: number[]) { this.selectedPointIndices = newSelectedPointIndices; let neighbors: knn.NearestEntry[] = []; if (newSelectedPointIndices.length === 1) { neighbors = this.dataSet.findNeighbors( newSelectedPointIndices[0], this.inspectorPanel.distFunc, this.inspectorPanel.numNN); this.metadataCard.updateMetadata( this.dataSet.points[newSelectedPointIndices[0]].metadata); } else { this.metadataCard.updateMetadata(null); } this.selectionChangedListeners.forEach( l => l(this.selectedPointIndices, neighbors)); } /** * Registers a listener to be called any time the mouse hovers over a point. */ registerHoverListener(listener: HoverListener) { this.hoverListeners.push(listener); } /** * Used by clients to indicate that a hover is occurring. */ notifyHoverOverPoint(pointIndex: number) { this.hoverListeners.forEach(l => l(pointIndex)); } _dataProtoChanged(dataProtoString: string) { let dataProto = dataProtoString ? JSON.parse(dataProtoString) as DataProto : null; this.initializeDataProvider(dataProto); } private makeDefaultPointsInfoAndStats(points: DataPoint[]): [PointMetadata[], ColumnStats[]] { let pointsInfo: PointMetadata[] = []; points.forEach(p => { let pointInfo: PointMetadata = {}; pointInfo[INDEX_METADATA_FIELD] = p.index; pointsInfo.push(pointInfo); }); let stats: ColumnStats[] = [{ name: INDEX_METADATA_FIELD, isNumeric: false, tooManyUniqueValues: true, min: 0, max: pointsInfo.length - 1 }]; return [pointsInfo, stats]; } private initializeDataProvider(dataProto?: DataProto) { if (this.servingMode === 'demo') { this.dataProvider = new DemoDataProvider(this.projectorConfigJsonPath); } else if (this.servingMode === 'server') { if (!this.routePrefix) { throw 'route-prefix is a required parameter'; } this.dataProvider = new ServerDataProvider(this.routePrefix); } else if (this.servingMode === 'proto' && dataProto != null) { this.dataProvider = new ProtoDataProvider(dataProto); } this.dataPanel.initialize(this, this.dataProvider); this.bookmarkPanel.initialize(this, this.dataProvider); } private
(colorOption: ColorOption): (index: number) => string { if ((colorOption == null) || (colorOption.map == null)) { return null; } const colorer = (i: number) => { let value = this.dataSet.points[i].metadata[this.selectedColorOption.name]; if (value == null) { return POINT_COLOR_MISSING; } return colorOption.map(value); }; return colorer; } private get3DLabelModeButton(): any { return this.querySelector('#labels3DMode'); } private get3DLabelMode(): boolean { const label3DModeButton = this.get3DLabelModeButton(); return (label3DModeButton as any).active; } private getSpriteImageMode(): boolean { return this.dataSet && this.dataSet.spriteAndMetadataInfo && this.dataSet.spriteAndMetadataInfo.spriteImage != null; } adjustSelectionAndHover(selectedPointIndices: number[], hoverIndex?: number) { this.notifySelectionChanged(selectedPointIndices); this.notifyHoverOverPoint(hoverIndex); this.scatterPlot.setMode(Mode.HOVER); } private unsetCurrentDataSet() { this.dataSet.stopTSNE(); } private setCurrentDataSet(ds: DataSet) { this.adjustSelectionAndHover([]); if (this.dataSet != null) { this.unsetCurrentDataSet(); } this.dataSet = ds; if (this.normalizeData) { this.dataSet.normalize(); } this.dim = this.dataSet.dim[1]; this.dom.select('span.numDataPoints').text(this.dataSet.dim[0]); this.dom.select('span.dim').text(this.dataSet.dim[1]); this.selectedProjectionPointAccessors = null; this.projectionsPanel.dataSetUpdated( this.dataSet, this.originalDataSet, this.dim); this.scatterPlot.setCameraParametersForNextCameraCreation(null, true); } private setupUIControls() { // View controls this.querySelector('#reset-zoom').addEventListener('click', () => { this.scatterPlot.resetZoom(); this.scatterPlot.startOrbitAnimation(); }); let selectModeButton = this.querySelector('#selectMode'); selectModeButton.addEventListener('click', (event) => { this.scatterPlot.setMode( (selectModeButton as any).active ? Mode.SELECT : Mode.HOVER); }); let nightModeButton = this.querySelector('#nightDayMode'); nightModeButton.addEventListener('click', () => { this.scatterPlot.setDayNightMode((nightModeButton as any).active); }); const labels3DModeButton = this.get3DLabelModeButton(); labels3DModeButton.addEventListener('click', () => { this.createVisualizers(this.get3DLabelMode()); this.updateScatterPlotAttributes(); this.scatterPlot.render(); }); window.addEventListener('resize', () => { let container = this.dom.select('#container'); let parentHeight = (container.node().parentNode as HTMLElement).clientHeight; container.style('height', parentHeight + 'px'); this.scatterPlot.resize(); }); this.projectorScatterPlotAdapter = new ProjectorScatterPlotAdapter(); this.scatterPlot = new ScatterPlot( this.getScatterContainer(), i => '' + this.dataSet.points[i].metadata[this.selectedLabelOption], this, this); this.createVisualizers(false); this.scatterPlot.onCameraMove( (cameraPosition: THREE.Vector3, cameraTarget: THREE.Vector3) => this.bookmarkPanel.clearStateSelection()); this.registerHoverListener( (hoverIndex: number) => this.onHover(hoverIndex)); this.registerSelectionChangedListener( (selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) => this.onSelectionChanged( selectedPointIndices, neighborsOfFirstPoint)); this.scatterPlot.resize(); this.scatterPlot.render(); } private onHover(hoverIndex: number) { this.hoverPointIndex = hoverIndex; let hoverText = null; if (hoverIndex != null) { const point = this.dataSet.points[hoverIndex]; if (point.metadata[this.selectedLabelOption]) { hoverText = point.metadata[this.selectedLabelOption].toString(); } } this.updateScatterPlotAttributes(); this.scatterPlot.render(); if (this.selectedPointIndices.length === 0) { this.statusBar.style('display', hoverText ? null : 'none'); this.statusBar.text(hoverText); } } private updateScatterPlotPositions() { if (this.dataSet == null) { return; } if (this.selectedProjectionPointAccessors == null) { return; } const newPositions = this.projectorScatterPlotAdapter.generatePointPositionArray( this.dataSet, this.selectedProjectionPointAccessors); this.scatterPlot.setPointPositions(this.dataSet, newPositions); } private updateScatterPlotAttributes() { const dataSet = this.dataSet; const selectedSet = this.selectedPointIndices; const hoverIndex = this.hoverPointIndex; const neighbors = this.neighborsOfFirstPoint; const pointColorer = this.getLegendPointColorer(this.selectedColorOption); const adapter = this.projectorScatterPlotAdapter; const pointColors = adapter.generatePointColorArray( dataSet, pointColorer, selectedSet, neighbors, hoverIndex, this.get3DLabelMode(), this.getSpriteImageMode()); const pointScaleFactors = adapter.generatePointScaleFactorArray( dataSet, selectedSet, neighbors, hoverIndex); const labels = adapter.generateVisibleLabelRenderParams( dataSet, selectedSet, neighbors, hoverIndex); const traceColors = adapter.generateLineSegmentColorMap(dataSet, pointColorer); const traceOpacities = adapter.generateLineSegmentOpacityArray(dataSet, selectedSet); const traceWidths = adapter.generateLineSegmentWidthArray(dataSet, selectedSet); this.scatterPlot.setPointColors(pointColors); this.scatterPlot.setPointScaleFactors(pointScaleFactors); this.scatterPlot.setLabels(labels); this.scatterPlot.setTraceColors(traceColors); this.scatterPlot.setTraceOpacities(traceOpacities); this.scatterPlot.setTraceWidths(traceWidths); } private getScatterContainer(): d3.Selection<any> { return this.dom.select('#scatter'); } private createVisualizers(inLabels3DMode: boolean) { const scatterPlot = this.scatterPlot; scatterPlot.removeAllVisualizers(); if (inLabels3DMode) { scatterPlot.addVisualizer(new ScatterPlotVisualizer3DLabels()); } else { scatterPlot.addVisualizer(new ScatterPlotVisualizerSprites()); scatterPlot.addVisualizer( new ScatterPlotVisualizerCanvasLabels(this.getScatterContainer())); } scatterPlot.addVisualizer(new ScatterPlotVisualizerTraces()); } private onSelectionChanged( selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) { this.selectedPointIndices = selectedPointIndices; this.neighborsOfFirstPoint = neighborsOfFirstPoint; let totalNumPoints = this.selectedPointIndices.length + neighborsOfFirstPoint.length; this.statusBar.text(`Selected ${totalNumPoints} points`) .style('display', totalNumPoints > 0 ? null : 'none'); this.inspectorPanel.updateInspectorPane( selectedPointIndices, neighborsOfFirstPoint); this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setProjection( projection: Projection, dimensionality: number, pointAccessors: PointAccessors3D) { this.selectedProjection = projection; this.selectedProjectionPointAccessors = pointAccessors; this.scatterPlot.setDimensions(dimensionality); if (this.dataSet.projectionCanBeRendered(projection)) { this.updateScatterPlotAttributes(); this.notifyProjectionsUpdated(); } this.scatterPlot.setCameraParametersForNextCameraCreation(null, false); } notifyProjectionsUpdated() { this.updateScatterPlotPositions(); this.scatterPlot.render(); } /** * Gets the current view of the embedding and saves it as a State object. */ getCurrentState(): State { const state = new State(); // Save the individual datapoint projections. state.projections = []; for (let i = 0; i < this.dataSet.points.length; i++) { const point = this.dataSet.points[i]; const projections: {[key: string]: number} = {}; const keys = Object.keys(point.projections); for (let j = 0; j < keys.length; ++j) { projections[keys[j]] = point.projections[keys[j]]; } state.projections.push(projections); } state.selectedProjection = this.selectedProjection; state.dataSetDimensions = this.dataSet.dim; state.tSNEIteration = this.dataSet.tSNEIteration; state.selectedPoints = this.selectedPointIndices; state.cameraDef = this.scatterPlot.getCameraDef(); state.selectedColorOptionName = this.dataPanel.selectedColorOptionName; state.selectedLabelOption = this.selectedLabelOption; this.projectionsPanel.populateBookmarkFromUI(state); return state; } /** Loads a State object into the world. */ loadState(state: State) { for (let i = 0; i < state.projections.length; i++) { const point = this.dataSet.points[i]; const projection = state.projections[i]; const keys = Object.keys(projection); for (let j = 0; j < keys.length; ++j) { point.projections[keys[j]] = projection[keys[j]]; } } this.dataSet.hasTSNERun = (state.selectedProjection === 'tsne'); this.dataSet.tSNEIteration = state.tSNEIteration; this.projectionsPanel.restoreUIFromBookmark(state); this.dataPanel.selectedColorOptionName = state.selectedColorOptionName; this.selectedLabelOption = state.selectedLabelOption; this.scatterPlot.setCameraParametersForNextCameraCreation( state.cameraDef, false); { const dimensions = stateGetAccessorDimensions(state); const accessors = this.dataSet.getPointAccessors(state.selectedProjection, dimensions); this.setProjection( state.selectedProjection, dimensions.length, accessors); } this.notifySelectionChanged(state.selectedPoints); } } document.registerElement(Projector.prototype.is, Projector);
getLegendPointColorer
identifier_name
vz-projector.ts
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or 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. ==============================================================================*/ import {ColorOption, ColumnStats, DataPoint, DataProto, DataSet, PointAccessors3D, PointMetadata, Projection, SpriteAndMetadataInfo, State, stateGetAccessorDimensions} from './data'; import {DataProvider, EmbeddingInfo, ServingMode} from './data-provider'; import {DemoDataProvider} from './data-provider-demo'; import {ProtoDataProvider} from './data-provider-proto'; import {ServerDataProvider} from './data-provider-server'; import {HoverContext, HoverListener} from './hoverContext'; import * as knn from './knn'; import * as logging from './logging'; import {ProjectorScatterPlotAdapter} from './projectorScatterPlotAdapter'; import {Mode, ScatterPlot} from './scatterPlot'; import {ScatterPlotVisualizer3DLabels} from './scatterPlotVisualizer3DLabels'; import {ScatterPlotVisualizerCanvasLabels} from './scatterPlotVisualizerCanvasLabels'; import {ScatterPlotVisualizerSprites} from './scatterPlotVisualizerSprites'; import {ScatterPlotVisualizerTraces} from './scatterPlotVisualizerTraces'; import {SelectionChangedListener, SelectionContext} from './selectionContext'; import {BookmarkPanel} from './vz-projector-bookmark-panel'; import {DataPanel} from './vz-projector-data-panel'; import {InspectorPanel} from './vz-projector-inspector-panel'; import {MetadataCard} from './vz-projector-metadata-card'; import {ProjectionsPanel} from './vz-projector-projections-panel'; // tslint:disable-next-line:no-unused-variable import {PolymerElement, PolymerHTMLElement} from './vz-projector-util'; /** * The minimum number of dimensions the data should have to automatically * decide to normalize the data. */ const THRESHOLD_DIM_NORMALIZE = 50; const POINT_COLOR_MISSING = 'black'; export let ProjectorPolymer = PolymerElement({ is: 'vz-projector', properties: { routePrefix: String, dataProto: {type: String, observer: '_dataProtoChanged'}, servingMode: String, projectorConfigJsonPath: String } }); const INDEX_METADATA_FIELD = '__index__'; export class Projector extends ProjectorPolymer implements SelectionContext, HoverContext { // The working subset of the data source's original data set. dataSet: DataSet; servingMode: ServingMode; // The path to the projector config JSON file for demo mode. projectorConfigJsonPath: string; private selectionChangedListeners: SelectionChangedListener[]; private hoverListeners: HoverListener[]; private originalDataSet: DataSet; private dom: d3.Selection<any>; private projectorScatterPlotAdapter: ProjectorScatterPlotAdapter; private scatterPlot: ScatterPlot; private dim: number; private selectedPointIndices: number[]; private neighborsOfFirstPoint: knn.NearestEntry[]; private hoverPointIndex: number; private dataProvider: DataProvider; private inspectorPanel: InspectorPanel; private selectedColorOption: ColorOption; private selectedLabelOption: string; private routePrefix: string; private normalizeData: boolean; private selectedProjection: Projection; private selectedProjectionPointAccessors: PointAccessors3D; /** Polymer component panels */ private dataPanel: DataPanel; private bookmarkPanel: BookmarkPanel; private projectionsPanel: ProjectionsPanel; private metadataCard: MetadataCard; private statusBar: d3.Selection<HTMLElement>; ready() { this.selectionChangedListeners = []; this.hoverListeners = []; this.selectedPointIndices = []; this.neighborsOfFirstPoint = []; this.dom = d3.select(this); logging.setDomContainer(this); this.dataPanel = this.$['data-panel'] as DataPanel; this.inspectorPanel = this.$['inspector-panel'] as InspectorPanel; this.inspectorPanel.initialize(this); this.projectionsPanel = this.$['projections-panel'] as ProjectionsPanel; this.projectionsPanel.initialize(this); this.metadataCard = this.$['metadata-card'] as MetadataCard; this.statusBar = this.dom.select('#status-bar'); this.bookmarkPanel = this.$['bookmark-panel'] as BookmarkPanel; this.scopeSubtree(this.$$('#wrapper-notify-msg'), true); this.setupUIControls(); this.initializeDataProvider(); } setSelectedLabelOption(labelOption: string) { this.selectedLabelOption = labelOption; let labelAccessor = (i: number): string => { return this.dataSet.points[i] .metadata[this.selectedLabelOption] as string; }; this.metadataCard.setLabelOption(this.selectedLabelOption); this.scatterPlot.setLabelAccessor(labelAccessor); this.scatterPlot.render(); } setSelectedColorOption(colorOption: ColorOption) { this.selectedColorOption = colorOption; this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setNormalizeData(normalizeData: boolean) { this.normalizeData = normalizeData; this.setCurrentDataSet(this.originalDataSet.getSubset()); } updateDataSet( ds: DataSet, spriteAndMetadata?: SpriteAndMetadataInfo, metadataFile?: string) { this.originalDataSet = ds; if (this.scatterPlot == null || this.originalDataSet == null) { // We are not ready yet. return; } this.normalizeData = this.originalDataSet.dim[1] >= THRESHOLD_DIM_NORMALIZE; spriteAndMetadata = spriteAndMetadata || {}; if (spriteAndMetadata.pointsInfo == null) { let [pointsInfo, stats] = this.makeDefaultPointsInfoAndStats(ds.points); spriteAndMetadata.pointsInfo = pointsInfo; spriteAndMetadata.stats = stats; } ds.mergeMetadata(spriteAndMetadata); this.dataPanel.setNormalizeData(this.normalizeData); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.inspectorPanel.datasetChanged(); this.inspectorPanel.metadataChanged(spriteAndMetadata); this.projectionsPanel.metadataChanged(spriteAndMetadata); this.dataPanel.metadataChanged(spriteAndMetadata, metadataFile); // Set the container to a fixed height, otherwise in Colab the // height can grow indefinitely. let container = this.dom.select('#container'); container.style('height', container.property('clientHeight') + 'px'); } setSelectedTensor(run: string, tensorInfo: EmbeddingInfo) { this.bookmarkPanel.setSelectedTensor(run, tensorInfo); } /** * Registers a listener to be called any time the selected point set changes. */ registerSelectionChangedListener(listener: SelectionChangedListener) { this.selectionChangedListeners.push(listener); } filterDataset() { let indices = this.selectedPointIndices.concat( this.neighborsOfFirstPoint.map(n => n.index)); let selectionSize = this.selectedPointIndices.length; this.setCurrentDataSet(this.dataSet.getSubset(indices)); this.adjustSelectionAndHover(d3.range(selectionSize)); } resetFilterDataset() { let originalPointIndices = this.selectedPointIndices.map(localIndex => { return this.dataSet.points[localIndex].index; }); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.updateScatterPlotPositions(); this.adjustSelectionAndHover(originalPointIndices); } /** * Used by clients to indicate that a selection has occurred. */ notifySelectionChanged(newSelectedPointIndices: number[]) { this.selectedPointIndices = newSelectedPointIndices; let neighbors: knn.NearestEntry[] = []; if (newSelectedPointIndices.length === 1) { neighbors = this.dataSet.findNeighbors( newSelectedPointIndices[0], this.inspectorPanel.distFunc, this.inspectorPanel.numNN); this.metadataCard.updateMetadata( this.dataSet.points[newSelectedPointIndices[0]].metadata); } else { this.metadataCard.updateMetadata(null); } this.selectionChangedListeners.forEach( l => l(this.selectedPointIndices, neighbors)); } /** * Registers a listener to be called any time the mouse hovers over a point. */ registerHoverListener(listener: HoverListener) { this.hoverListeners.push(listener); } /** * Used by clients to indicate that a hover is occurring. */ notifyHoverOverPoint(pointIndex: number) { this.hoverListeners.forEach(l => l(pointIndex)); } _dataProtoChanged(dataProtoString: string) { let dataProto = dataProtoString ? JSON.parse(dataProtoString) as DataProto : null; this.initializeDataProvider(dataProto); } private makeDefaultPointsInfoAndStats(points: DataPoint[]): [PointMetadata[], ColumnStats[]] { let pointsInfo: PointMetadata[] = []; points.forEach(p => { let pointInfo: PointMetadata = {}; pointInfo[INDEX_METADATA_FIELD] = p.index; pointsInfo.push(pointInfo); }); let stats: ColumnStats[] = [{ name: INDEX_METADATA_FIELD, isNumeric: false, tooManyUniqueValues: true, min: 0, max: pointsInfo.length - 1 }]; return [pointsInfo, stats]; } private initializeDataProvider(dataProto?: DataProto) { if (this.servingMode === 'demo') { this.dataProvider = new DemoDataProvider(this.projectorConfigJsonPath); } else if (this.servingMode === 'server') { if (!this.routePrefix) { throw 'route-prefix is a required parameter'; } this.dataProvider = new ServerDataProvider(this.routePrefix); } else if (this.servingMode === 'proto' && dataProto != null) { this.dataProvider = new ProtoDataProvider(dataProto); } this.dataPanel.initialize(this, this.dataProvider); this.bookmarkPanel.initialize(this, this.dataProvider); } private getLegendPointColorer(colorOption: ColorOption): (index: number) => string { if ((colorOption == null) || (colorOption.map == null)) { return null; } const colorer = (i: number) => { let value = this.dataSet.points[i].metadata[this.selectedColorOption.name]; if (value == null) { return POINT_COLOR_MISSING; } return colorOption.map(value); }; return colorer; } private get3DLabelModeButton(): any { return this.querySelector('#labels3DMode'); } private get3DLabelMode(): boolean { const label3DModeButton = this.get3DLabelModeButton(); return (label3DModeButton as any).active; } private getSpriteImageMode(): boolean { return this.dataSet && this.dataSet.spriteAndMetadataInfo && this.dataSet.spriteAndMetadataInfo.spriteImage != null; } adjustSelectionAndHover(selectedPointIndices: number[], hoverIndex?: number) { this.notifySelectionChanged(selectedPointIndices); this.notifyHoverOverPoint(hoverIndex); this.scatterPlot.setMode(Mode.HOVER); } private unsetCurrentDataSet() { this.dataSet.stopTSNE(); } private setCurrentDataSet(ds: DataSet) { this.adjustSelectionAndHover([]); if (this.dataSet != null) { this.unsetCurrentDataSet(); } this.dataSet = ds; if (this.normalizeData) { this.dataSet.normalize(); } this.dim = this.dataSet.dim[1]; this.dom.select('span.numDataPoints').text(this.dataSet.dim[0]); this.dom.select('span.dim').text(this.dataSet.dim[1]); this.selectedProjectionPointAccessors = null; this.projectionsPanel.dataSetUpdated( this.dataSet, this.originalDataSet, this.dim); this.scatterPlot.setCameraParametersForNextCameraCreation(null, true); } private setupUIControls() { // View controls this.querySelector('#reset-zoom').addEventListener('click', () => { this.scatterPlot.resetZoom();
let selectModeButton = this.querySelector('#selectMode'); selectModeButton.addEventListener('click', (event) => { this.scatterPlot.setMode( (selectModeButton as any).active ? Mode.SELECT : Mode.HOVER); }); let nightModeButton = this.querySelector('#nightDayMode'); nightModeButton.addEventListener('click', () => { this.scatterPlot.setDayNightMode((nightModeButton as any).active); }); const labels3DModeButton = this.get3DLabelModeButton(); labels3DModeButton.addEventListener('click', () => { this.createVisualizers(this.get3DLabelMode()); this.updateScatterPlotAttributes(); this.scatterPlot.render(); }); window.addEventListener('resize', () => { let container = this.dom.select('#container'); let parentHeight = (container.node().parentNode as HTMLElement).clientHeight; container.style('height', parentHeight + 'px'); this.scatterPlot.resize(); }); this.projectorScatterPlotAdapter = new ProjectorScatterPlotAdapter(); this.scatterPlot = new ScatterPlot( this.getScatterContainer(), i => '' + this.dataSet.points[i].metadata[this.selectedLabelOption], this, this); this.createVisualizers(false); this.scatterPlot.onCameraMove( (cameraPosition: THREE.Vector3, cameraTarget: THREE.Vector3) => this.bookmarkPanel.clearStateSelection()); this.registerHoverListener( (hoverIndex: number) => this.onHover(hoverIndex)); this.registerSelectionChangedListener( (selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) => this.onSelectionChanged( selectedPointIndices, neighborsOfFirstPoint)); this.scatterPlot.resize(); this.scatterPlot.render(); } private onHover(hoverIndex: number) { this.hoverPointIndex = hoverIndex; let hoverText = null; if (hoverIndex != null) { const point = this.dataSet.points[hoverIndex]; if (point.metadata[this.selectedLabelOption]) { hoverText = point.metadata[this.selectedLabelOption].toString(); } } this.updateScatterPlotAttributes(); this.scatterPlot.render(); if (this.selectedPointIndices.length === 0) { this.statusBar.style('display', hoverText ? null : 'none'); this.statusBar.text(hoverText); } } private updateScatterPlotPositions() { if (this.dataSet == null) { return; } if (this.selectedProjectionPointAccessors == null) { return; } const newPositions = this.projectorScatterPlotAdapter.generatePointPositionArray( this.dataSet, this.selectedProjectionPointAccessors); this.scatterPlot.setPointPositions(this.dataSet, newPositions); } private updateScatterPlotAttributes() { const dataSet = this.dataSet; const selectedSet = this.selectedPointIndices; const hoverIndex = this.hoverPointIndex; const neighbors = this.neighborsOfFirstPoint; const pointColorer = this.getLegendPointColorer(this.selectedColorOption); const adapter = this.projectorScatterPlotAdapter; const pointColors = adapter.generatePointColorArray( dataSet, pointColorer, selectedSet, neighbors, hoverIndex, this.get3DLabelMode(), this.getSpriteImageMode()); const pointScaleFactors = adapter.generatePointScaleFactorArray( dataSet, selectedSet, neighbors, hoverIndex); const labels = adapter.generateVisibleLabelRenderParams( dataSet, selectedSet, neighbors, hoverIndex); const traceColors = adapter.generateLineSegmentColorMap(dataSet, pointColorer); const traceOpacities = adapter.generateLineSegmentOpacityArray(dataSet, selectedSet); const traceWidths = adapter.generateLineSegmentWidthArray(dataSet, selectedSet); this.scatterPlot.setPointColors(pointColors); this.scatterPlot.setPointScaleFactors(pointScaleFactors); this.scatterPlot.setLabels(labels); this.scatterPlot.setTraceColors(traceColors); this.scatterPlot.setTraceOpacities(traceOpacities); this.scatterPlot.setTraceWidths(traceWidths); } private getScatterContainer(): d3.Selection<any> { return this.dom.select('#scatter'); } private createVisualizers(inLabels3DMode: boolean) { const scatterPlot = this.scatterPlot; scatterPlot.removeAllVisualizers(); if (inLabels3DMode) { scatterPlot.addVisualizer(new ScatterPlotVisualizer3DLabels()); } else { scatterPlot.addVisualizer(new ScatterPlotVisualizerSprites()); scatterPlot.addVisualizer( new ScatterPlotVisualizerCanvasLabels(this.getScatterContainer())); } scatterPlot.addVisualizer(new ScatterPlotVisualizerTraces()); } private onSelectionChanged( selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) { this.selectedPointIndices = selectedPointIndices; this.neighborsOfFirstPoint = neighborsOfFirstPoint; let totalNumPoints = this.selectedPointIndices.length + neighborsOfFirstPoint.length; this.statusBar.text(`Selected ${totalNumPoints} points`) .style('display', totalNumPoints > 0 ? null : 'none'); this.inspectorPanel.updateInspectorPane( selectedPointIndices, neighborsOfFirstPoint); this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setProjection( projection: Projection, dimensionality: number, pointAccessors: PointAccessors3D) { this.selectedProjection = projection; this.selectedProjectionPointAccessors = pointAccessors; this.scatterPlot.setDimensions(dimensionality); if (this.dataSet.projectionCanBeRendered(projection)) { this.updateScatterPlotAttributes(); this.notifyProjectionsUpdated(); } this.scatterPlot.setCameraParametersForNextCameraCreation(null, false); } notifyProjectionsUpdated() { this.updateScatterPlotPositions(); this.scatterPlot.render(); } /** * Gets the current view of the embedding and saves it as a State object. */ getCurrentState(): State { const state = new State(); // Save the individual datapoint projections. state.projections = []; for (let i = 0; i < this.dataSet.points.length; i++) { const point = this.dataSet.points[i]; const projections: {[key: string]: number} = {}; const keys = Object.keys(point.projections); for (let j = 0; j < keys.length; ++j) { projections[keys[j]] = point.projections[keys[j]]; } state.projections.push(projections); } state.selectedProjection = this.selectedProjection; state.dataSetDimensions = this.dataSet.dim; state.tSNEIteration = this.dataSet.tSNEIteration; state.selectedPoints = this.selectedPointIndices; state.cameraDef = this.scatterPlot.getCameraDef(); state.selectedColorOptionName = this.dataPanel.selectedColorOptionName; state.selectedLabelOption = this.selectedLabelOption; this.projectionsPanel.populateBookmarkFromUI(state); return state; } /** Loads a State object into the world. */ loadState(state: State) { for (let i = 0; i < state.projections.length; i++) { const point = this.dataSet.points[i]; const projection = state.projections[i]; const keys = Object.keys(projection); for (let j = 0; j < keys.length; ++j) { point.projections[keys[j]] = projection[keys[j]]; } } this.dataSet.hasTSNERun = (state.selectedProjection === 'tsne'); this.dataSet.tSNEIteration = state.tSNEIteration; this.projectionsPanel.restoreUIFromBookmark(state); this.dataPanel.selectedColorOptionName = state.selectedColorOptionName; this.selectedLabelOption = state.selectedLabelOption; this.scatterPlot.setCameraParametersForNextCameraCreation( state.cameraDef, false); { const dimensions = stateGetAccessorDimensions(state); const accessors = this.dataSet.getPointAccessors(state.selectedProjection, dimensions); this.setProjection( state.selectedProjection, dimensions.length, accessors); } this.notifySelectionChanged(state.selectedPoints); } } document.registerElement(Projector.prototype.is, Projector);
this.scatterPlot.startOrbitAnimation(); });
random_line_split
index.d.ts
declare const figureSet: { readonly tick: string; readonly cross: string; readonly star: string; readonly square: string; readonly squareSmall: string; readonly squareSmallFilled: string; readonly play: string; readonly circle: string; readonly circleFilled: string; readonly circleDotted: string; readonly circleDouble: string; readonly circleCircle: string; readonly circleCross: string; readonly circlePipe: string; readonly circleQuestionMark: string; readonly bullet: string; readonly dot: string; readonly line: string; readonly ellipsis: string; readonly pointer: string; readonly pointerSmall: string; readonly info: string; readonly warning: string; readonly hamburger: string; readonly smiley: string; readonly mustache: string; readonly heart: string; readonly nodejs: string; readonly arrowUp: string; readonly arrowDown: string; readonly arrowLeft: string; readonly arrowRight: string; readonly radioOn: string; readonly radioOff: string; readonly checkboxOn: string; readonly checkboxOff: string; readonly checkboxCircleOn: string; readonly checkboxCircleOff: string; readonly questionMarkPrefix: string; readonly oneHalf: string; readonly oneThird: string; readonly oneQuarter: string; readonly oneFifth: string; readonly oneSixth: string; readonly oneSeventh: string; readonly oneEighth: string; readonly oneNinth: string; readonly oneTenth: string; readonly twoThirds: string; readonly twoFifths: string; readonly threeQuarters: string; readonly threeFifths: string; readonly threeEighths: string; readonly fourFifths: string; readonly fiveSixths: string; readonly fiveEighths: string; readonly sevenEighth: string; }
type FigureSet = typeof figureSet declare const figures: { /** Replace Unicode symbols depending on the OS. @param string - String where the Unicode symbols will be replaced with fallback symbols depending on the OS. @returns The input with replaced fallback Unicode symbols on Windows. @example ``` import figures = require('figures'); console.log(figures('✔︎ check')); // On non-Windows OSes: ✔︎ check // On Windows: √ check console.log(figures.tick); // On non-Windows OSes: ✔︎ // On Windows: √ ``` */ (string: string): string; /** Symbols to use when not running on Windows. */ readonly main: FigureSet; /** Symbols to use when running on Windows. */ readonly windows: FigureSet; } & FigureSet; export = figures;
random_line_split
test_migration.py
import unittest import os from unittest.mock import patch import migration from configuration import Builder import configuration from tests import testhelper class MigrationTestCase(unittest.TestCase): def setUp(self): self.rootfolder = os.path.dirname(os.path.realpath(__file__))
@patch('migration.Commiter') @patch('migration.Initializer') @patch('migration.RTCInitializer') @patch('migration.os') @patch('configuration.shutil') def testDeletionOfLogFolderOnInitalization(self, shutil_mock, os_mock, rtc_initializer_mock, git_initializer_mock, git_comitter_mock): config = Builder().setrootfolder(self.rootfolder).build() anylogpath = config.getlogpath("testDeletionOfLogFolderOnInitalization") os_mock.path.exists.return_value = False configuration.config = config migration.initialize() expectedlogfolder = self.rootfolder + os.sep + "Logs" shutil_mock.rmtree.assert_called_once_with(expectedlogfolder) def testExistRepo_Exists_ShouldReturnTrue(self): with testhelper.createrepo(folderprefix="test_migration"): self.assertTrue(migration.existsrepo()) def testExistRepo_DoesntExist_ShouldReturnFalse(self): configuration.config = Builder().setworkdirectory(self.rootfolder).setgitreponame("test.git").build() self.assertFalse(migration.existsrepo())
random_line_split
test_migration.py
import unittest import os from unittest.mock import patch import migration from configuration import Builder import configuration from tests import testhelper class MigrationTestCase(unittest.TestCase): def setUp(self):
@patch('migration.Commiter') @patch('migration.Initializer') @patch('migration.RTCInitializer') @patch('migration.os') @patch('configuration.shutil') def testDeletionOfLogFolderOnInitalization(self, shutil_mock, os_mock, rtc_initializer_mock, git_initializer_mock, git_comitter_mock): config = Builder().setrootfolder(self.rootfolder).build() anylogpath = config.getlogpath("testDeletionOfLogFolderOnInitalization") os_mock.path.exists.return_value = False configuration.config = config migration.initialize() expectedlogfolder = self.rootfolder + os.sep + "Logs" shutil_mock.rmtree.assert_called_once_with(expectedlogfolder) def testExistRepo_Exists_ShouldReturnTrue(self): with testhelper.createrepo(folderprefix="test_migration"): self.assertTrue(migration.existsrepo()) def testExistRepo_DoesntExist_ShouldReturnFalse(self): configuration.config = Builder().setworkdirectory(self.rootfolder).setgitreponame("test.git").build() self.assertFalse(migration.existsrepo())
self.rootfolder = os.path.dirname(os.path.realpath(__file__))
identifier_body
test_migration.py
import unittest import os from unittest.mock import patch import migration from configuration import Builder import configuration from tests import testhelper class
(unittest.TestCase): def setUp(self): self.rootfolder = os.path.dirname(os.path.realpath(__file__)) @patch('migration.Commiter') @patch('migration.Initializer') @patch('migration.RTCInitializer') @patch('migration.os') @patch('configuration.shutil') def testDeletionOfLogFolderOnInitalization(self, shutil_mock, os_mock, rtc_initializer_mock, git_initializer_mock, git_comitter_mock): config = Builder().setrootfolder(self.rootfolder).build() anylogpath = config.getlogpath("testDeletionOfLogFolderOnInitalization") os_mock.path.exists.return_value = False configuration.config = config migration.initialize() expectedlogfolder = self.rootfolder + os.sep + "Logs" shutil_mock.rmtree.assert_called_once_with(expectedlogfolder) def testExistRepo_Exists_ShouldReturnTrue(self): with testhelper.createrepo(folderprefix="test_migration"): self.assertTrue(migration.existsrepo()) def testExistRepo_DoesntExist_ShouldReturnFalse(self): configuration.config = Builder().setworkdirectory(self.rootfolder).setgitreponame("test.git").build() self.assertFalse(migration.existsrepo())
MigrationTestCase
identifier_name
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use crate::values::{Either, None_}; use cssparser::Parser; use style_traits::{ParseError, StyleParseErrorKind}; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub struct SVGPaint<ColorType, UrlPaintServer> { /// The paint source pub kind: SVGPaintKind<ColorType, UrlPaintServer>, /// The fallback color. It would be empty, the `none` keyword or <color>. pub fallback: Option<Either<ColorType, None_>>, } /// An SVG paint value without the fallback /// /// Whereas the spec only allows PaintServer /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGPaintKind<ColorType, UrlPaintServer> { /// `none` #[animation(error)] None, /// `<color>` Color(ColorType), /// `url(...)` #[animation(error)] PaintServer(UrlPaintServer), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> { /// Parse a keyword value only fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { try_match_ident_ignore_ascii_case! { input, "none" => Ok(SVGPaintKind::None), "context-fill" => Ok(SVGPaintKind::ContextFill), "context-stroke" => Ok(SVGPaintKind::ContextStroke), } } } /// Parse SVGPaint's fallback. /// fallback is keyword(none), Color or empty. /// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint> fn parse_fallback<'i, 't, ColorType: Parse>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Option<Either<ColorType, None_>> { if input.try(|i| i.expect_ident_matching("none")).is_ok() { Some(Either::Second(None_)) } else { if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Some(Either::First(color)) } else { None } } } impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::PaintServer(url), fallback: parse_fallback(context, input), }) } else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) { if let SVGPaintKind::None = kind { Ok(SVGPaint { kind: kind, fallback: None, }) } else { Ok(SVGPaint { kind: kind, fallback: parse_fallback(context, input), }) } } else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::Color(color), fallback: None, }) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum
<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] Vec<L>), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, }
SVGStrokeDashArray
identifier_name
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use crate::values::{Either, None_}; use cssparser::Parser; use style_traits::{ParseError, StyleParseErrorKind}; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub struct SVGPaint<ColorType, UrlPaintServer> { /// The paint source pub kind: SVGPaintKind<ColorType, UrlPaintServer>, /// The fallback color. It would be empty, the `none` keyword or <color>. pub fallback: Option<Either<ColorType, None_>>, } /// An SVG paint value without the fallback /// /// Whereas the spec only allows PaintServer /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGPaintKind<ColorType, UrlPaintServer> { /// `none` #[animation(error)] None, /// `<color>` Color(ColorType), /// `url(...)` #[animation(error)] PaintServer(UrlPaintServer), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> { /// Parse a keyword value only fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { try_match_ident_ignore_ascii_case! { input, "none" => Ok(SVGPaintKind::None), "context-fill" => Ok(SVGPaintKind::ContextFill), "context-stroke" => Ok(SVGPaintKind::ContextStroke), } } } /// Parse SVGPaint's fallback. /// fallback is keyword(none), Color or empty. /// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint> fn parse_fallback<'i, 't, ColorType: Parse>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Option<Either<ColorType, None_>> { if input.try(|i| i.expect_ident_matching("none")).is_ok() { Some(Either::Second(None_)) } else { if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Some(Either::First(color)) } else { None } } } impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::PaintServer(url), fallback: parse_fallback(context, input), }) } else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) { if let SVGPaintKind::None = kind { Ok(SVGPaint { kind: kind, fallback: None, }) } else
} else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::Color(color), fallback: None, }) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGStrokeDashArray<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] Vec<L>), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, }
{ Ok(SVGPaint { kind: kind, fallback: parse_fallback(context, input), }) }
conditional_block
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use crate::values::{Either, None_}; use cssparser::Parser; use style_traits::{ParseError, StyleParseErrorKind}; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub struct SVGPaint<ColorType, UrlPaintServer> { /// The paint source pub kind: SVGPaintKind<ColorType, UrlPaintServer>, /// The fallback color. It would be empty, the `none` keyword or <color>. pub fallback: Option<Either<ColorType, None_>>, } /// An SVG paint value without the fallback /// /// Whereas the spec only allows PaintServer /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGPaintKind<ColorType, UrlPaintServer> { /// `none` #[animation(error)] None, /// `<color>` Color(ColorType), /// `url(...)` #[animation(error)] PaintServer(UrlPaintServer), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> { /// Parse a keyword value only fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { try_match_ident_ignore_ascii_case! { input, "none" => Ok(SVGPaintKind::None), "context-fill" => Ok(SVGPaintKind::ContextFill), "context-stroke" => Ok(SVGPaintKind::ContextStroke), } } } /// Parse SVGPaint's fallback. /// fallback is keyword(none), Color or empty. /// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint> fn parse_fallback<'i, 't, ColorType: Parse>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Option<Either<ColorType, None_>> { if input.try(|i| i.expect_ident_matching("none")).is_ok() { Some(Either::Second(None_)) } else { if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Some(Either::First(color)) } else { None } } } impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::PaintServer(url), fallback: parse_fallback(context, input), }) } else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) { if let SVGPaintKind::None = kind { Ok(SVGPaint { kind: kind, fallback: None, }) } else { Ok(SVGPaint { kind: kind, fallback: parse_fallback(context, input), }) } } else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::Color(color), fallback: None, }) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone,
MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGStrokeDashArray<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] Vec<L>), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, }
ComputeSquaredDistance, Copy, Debug,
random_line_split
overloaded-autoderef-count.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell;
struct DerefCounter<T> { count_imm: Cell<uint>, count_mut: uint, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts(&self) -> (uint, uint) { (self.count_imm.get(), self.count_mut) } } impl<T> Deref<T> for DerefCounter<T> { fn deref(&self) -> &T { self.count_imm.set(self.count_imm.get() + 1); &self.value } } impl<T> DerefMut<T> for DerefCounter<T> { fn deref_mut(&mut self) -> &mut T { self.count_mut += 1; &mut self.value } } #[deriving(PartialEq, Show)] struct Point { x: int, y: int } impl Point { fn get(&self) -> (int, int) { (self.x, self.y) } } pub fn main() { let mut p = DerefCounter::new(Point {x: 0, y: 0}); let _ = p.x; assert_eq!(p.counts(), (1, 0)); let _ = &p.x; assert_eq!(p.counts(), (2, 0)); let _ = &mut p.y; assert_eq!(p.counts(), (2, 1)); p.x += 3; assert_eq!(p.counts(), (2, 2)); p.get(); assert_eq!(p.counts(), (3, 2)); // Check the final state. assert_eq!(*p, Point {x: 3, y: 0}); }
use std::ops::{Deref, DerefMut}; #[deriving(PartialEq)]
random_line_split
overloaded-autoderef-count.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; use std::ops::{Deref, DerefMut}; #[deriving(PartialEq)] struct DerefCounter<T> { count_imm: Cell<uint>, count_mut: uint, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts(&self) -> (uint, uint) { (self.count_imm.get(), self.count_mut) } } impl<T> Deref<T> for DerefCounter<T> { fn
(&self) -> &T { self.count_imm.set(self.count_imm.get() + 1); &self.value } } impl<T> DerefMut<T> for DerefCounter<T> { fn deref_mut(&mut self) -> &mut T { self.count_mut += 1; &mut self.value } } #[deriving(PartialEq, Show)] struct Point { x: int, y: int } impl Point { fn get(&self) -> (int, int) { (self.x, self.y) } } pub fn main() { let mut p = DerefCounter::new(Point {x: 0, y: 0}); let _ = p.x; assert_eq!(p.counts(), (1, 0)); let _ = &p.x; assert_eq!(p.counts(), (2, 0)); let _ = &mut p.y; assert_eq!(p.counts(), (2, 1)); p.x += 3; assert_eq!(p.counts(), (2, 2)); p.get(); assert_eq!(p.counts(), (3, 2)); // Check the final state. assert_eq!(*p, Point {x: 3, y: 0}); }
deref
identifier_name
lpo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Serkr is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Serkr. If not, see <http://www.gnu.org/licenses/>. // use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; /// Checks if s is greater than t according to the ordering. pub fn lpo_gt(precedence: &Precedence, s: &Term, t: &Term) -> bool { if s.is_function() && t.is_function()
else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool { s == t || lpo_gt(precedence, s, t) } fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity() { if lpo_gt(precedence, &s[i], &t[i]) { return true; } else if s[i] != t[i] { return false; } } false } #[cfg(test)] mod test { use super::{lpo_gt, lpo_ge}; use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; #[test] fn lpo_gt_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); assert!(!lpo_gt(&precedence, &x, &y)); assert!(!lpo_gt(&precedence, &y, &x)); } #[test] fn lpo_gt_2() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); assert!(lpo_gt(&precedence, &f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_x)); } #[test] fn lpo_gt_3() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); let f_y = Term::new_function(1, vec![y]); assert!(!lpo_gt(&precedence, &f_y, &x)); assert!(!lpo_gt(&precedence, &x, &f_y)); } #[test] fn lpo_gt_4() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(lpo_gt(&precedence, &f_f_x, &f_x)); assert!(!lpo_gt(&precedence, &f_x, &f_f_x)); assert!(lpo_gt(&precedence, &f_f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_f_x)); } #[test] fn lpo_gt_5() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_g_x = Term::new_function(1, vec![Term::new_function(2, vec![x.clone()])]); assert!(lpo_gt(&precedence, &f_g_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_g_x)); } #[test] fn lpo_gt_6() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x_x = Term::new_function(1, vec![x.clone(), x]); let t = Term::new_truth(); assert!(lpo_gt(&precedence, &f_x_x, &t)); assert!(!lpo_gt(&precedence, &t, &f_x_x)); } #[test] fn lpo_ge_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x]); assert!(!lpo_gt(&precedence, &f_x, &f_x)); assert!(lpo_ge(&precedence, &f_x, &f_x)); } }
{ if s.iter().any(|arg| lpo_ge(precedence, arg, t)) { true } else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) { if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) { true } else { precedence.gt(s, t) } } else { false } }
conditional_block
lpo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Serkr is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Serkr. If not, see <http://www.gnu.org/licenses/>. // use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; /// Checks if s is greater than t according to the ordering. pub fn lpo_gt(precedence: &Precedence, s: &Term, t: &Term) -> bool { if s.is_function() && t.is_function() { if s.iter().any(|arg| lpo_ge(precedence, arg, t)) { true } else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) { if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) { true } else { precedence.gt(s, t) } } else { false } } else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool { s == t || lpo_gt(precedence, s, t) } fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity() { if lpo_gt(precedence, &s[i], &t[i]) { return true; } else if s[i] != t[i] { return false; } } false } #[cfg(test)] mod test { use super::{lpo_gt, lpo_ge}; use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; #[test] fn lpo_gt_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); assert!(!lpo_gt(&precedence, &x, &y)); assert!(!lpo_gt(&precedence, &y, &x)); } #[test] fn
() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); assert!(lpo_gt(&precedence, &f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_x)); } #[test] fn lpo_gt_3() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); let f_y = Term::new_function(1, vec![y]); assert!(!lpo_gt(&precedence, &f_y, &x)); assert!(!lpo_gt(&precedence, &x, &f_y)); } #[test] fn lpo_gt_4() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(lpo_gt(&precedence, &f_f_x, &f_x)); assert!(!lpo_gt(&precedence, &f_x, &f_f_x)); assert!(lpo_gt(&precedence, &f_f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_f_x)); } #[test] fn lpo_gt_5() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_g_x = Term::new_function(1, vec![Term::new_function(2, vec![x.clone()])]); assert!(lpo_gt(&precedence, &f_g_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_g_x)); } #[test] fn lpo_gt_6() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x_x = Term::new_function(1, vec![x.clone(), x]); let t = Term::new_truth(); assert!(lpo_gt(&precedence, &f_x_x, &t)); assert!(!lpo_gt(&precedence, &t, &f_x_x)); } #[test] fn lpo_ge_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x]); assert!(!lpo_gt(&precedence, &f_x, &f_x)); assert!(lpo_ge(&precedence, &f_x, &f_x)); } }
lpo_gt_2
identifier_name
lpo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Serkr is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Serkr. If not, see <http://www.gnu.org/licenses/>. // use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; /// Checks if s is greater than t according to the ordering. pub fn lpo_gt(precedence: &Precedence, s: &Term, t: &Term) -> bool { if s.is_function() && t.is_function() { if s.iter().any(|arg| lpo_ge(precedence, arg, t)) { true } else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) { if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) { true } else { precedence.gt(s, t) } } else { false } } else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool { s == t || lpo_gt(precedence, s, t) } fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity() { if lpo_gt(precedence, &s[i], &t[i]) { return true; } else if s[i] != t[i] { return false; } } false } #[cfg(test)] mod test { use super::{lpo_gt, lpo_ge}; use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; #[test] fn lpo_gt_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); assert!(!lpo_gt(&precedence, &x, &y)); assert!(!lpo_gt(&precedence, &y, &x)); } #[test] fn lpo_gt_2() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); assert!(lpo_gt(&precedence, &f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_x)); } #[test] fn lpo_gt_3() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); let f_y = Term::new_function(1, vec![y]);
#[test] fn lpo_gt_4() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(lpo_gt(&precedence, &f_f_x, &f_x)); assert!(!lpo_gt(&precedence, &f_x, &f_f_x)); assert!(lpo_gt(&precedence, &f_f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_f_x)); } #[test] fn lpo_gt_5() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_g_x = Term::new_function(1, vec![Term::new_function(2, vec![x.clone()])]); assert!(lpo_gt(&precedence, &f_g_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_g_x)); } #[test] fn lpo_gt_6() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x_x = Term::new_function(1, vec![x.clone(), x]); let t = Term::new_truth(); assert!(lpo_gt(&precedence, &f_x_x, &t)); assert!(!lpo_gt(&precedence, &t, &f_x_x)); } #[test] fn lpo_ge_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x]); assert!(!lpo_gt(&precedence, &f_x, &f_x)); assert!(lpo_ge(&precedence, &f_x, &f_x)); } }
assert!(!lpo_gt(&precedence, &f_y, &x)); assert!(!lpo_gt(&precedence, &x, &f_y)); }
random_line_split
lpo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Serkr is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Serkr. If not, see <http://www.gnu.org/licenses/>. // use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; /// Checks if s is greater than t according to the ordering. pub fn lpo_gt(precedence: &Precedence, s: &Term, t: &Term) -> bool { if s.is_function() && t.is_function() { if s.iter().any(|arg| lpo_ge(precedence, arg, t)) { true } else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) { if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) { true } else { precedence.gt(s, t) } } else { false } } else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool
fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity() { if lpo_gt(precedence, &s[i], &t[i]) { return true; } else if s[i] != t[i] { return false; } } false } #[cfg(test)] mod test { use super::{lpo_gt, lpo_ge}; use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; #[test] fn lpo_gt_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); assert!(!lpo_gt(&precedence, &x, &y)); assert!(!lpo_gt(&precedence, &y, &x)); } #[test] fn lpo_gt_2() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); assert!(lpo_gt(&precedence, &f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_x)); } #[test] fn lpo_gt_3() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); let f_y = Term::new_function(1, vec![y]); assert!(!lpo_gt(&precedence, &f_y, &x)); assert!(!lpo_gt(&precedence, &x, &f_y)); } #[test] fn lpo_gt_4() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(lpo_gt(&precedence, &f_f_x, &f_x)); assert!(!lpo_gt(&precedence, &f_x, &f_f_x)); assert!(lpo_gt(&precedence, &f_f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_f_x)); } #[test] fn lpo_gt_5() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_g_x = Term::new_function(1, vec![Term::new_function(2, vec![x.clone()])]); assert!(lpo_gt(&precedence, &f_g_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_g_x)); } #[test] fn lpo_gt_6() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x_x = Term::new_function(1, vec![x.clone(), x]); let t = Term::new_truth(); assert!(lpo_gt(&precedence, &f_x_x, &t)); assert!(!lpo_gt(&precedence, &t, &f_x_x)); } #[test] fn lpo_ge_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x]); assert!(!lpo_gt(&precedence, &f_x, &f_x)); assert!(lpo_ge(&precedence, &f_x, &f_x)); } }
{ s == t || lpo_gt(precedence, s, t) }
identifier_body
app-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { DashboardComponent } from './dashboard'; import { CommunityDetailsComponent, CommunityComponent } from './community'; import { ArtifactDetailsComponent, ArtifactComponent } from './artifact'; @NgModule({ imports: [ RouterModule.forRoot([ { path: '', redirectTo: '/dashboard', pathMatch: 'full', }, { path: 'dashboard', component: DashboardComponent }, { path: 'members', loadChildren: './member/member.module#MemberModule' }, { path: 'communities', component: CommunityComponent }, { path: 'artifacts', component: ArtifactComponent }, { path: 'communities/:id', component: CommunityDetailsComponent }, { path: 'artifacts/:id', component: ArtifactDetailsComponent } ]) ], exports: [ RouterModule ] }) export class
{ }
AppRoutingModule
identifier_name
app-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { DashboardComponent } from './dashboard'; import { CommunityDetailsComponent, CommunityComponent } from './community'; import { ArtifactDetailsComponent, ArtifactComponent } from './artifact'; @NgModule({ imports: [ RouterModule.forRoot([ { path: '', redirectTo: '/dashboard', pathMatch: 'full',
path: 'dashboard', component: DashboardComponent }, { path: 'members', loadChildren: './member/member.module#MemberModule' }, { path: 'communities', component: CommunityComponent }, { path: 'artifacts', component: ArtifactComponent }, { path: 'communities/:id', component: CommunityDetailsComponent }, { path: 'artifacts/:id', component: ArtifactDetailsComponent } ]) ], exports: [ RouterModule ] }) export class AppRoutingModule { }
}, {
random_line_split
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::fetch; use headers_core::HeaderMapExt; use headers_ext::ContentType; use hyper_serde::Serde; use mime::{self, Mime}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use servo_url::ServoUrl; use std::ops::Deref; #[cfg(test)] fn assert_parse( url: &'static str, content_type: Option<ContentType>, charset: Option<&str>, data: Option<&[u8]>, ) { let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); let response = fetch(&mut request, None); match data { Some(data) => { assert!(!response.is_network_error()); assert_eq!(response.headers.len(), 1); let header_content_type = response.headers.typed_get::<ContentType>(); assert_eq!(header_content_type, content_type); let metadata = match response.metadata() { Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m, result => panic!(result), }; assert_eq!(metadata.content_type.map(Serde::into_inner), content_type); assert_eq!(metadata.charset.as_ref().map(String::deref), charset); let resp_body = response.body.lock().unwrap(); match *resp_body { ResponseBody::Done(ref val) => { assert_eq!(val, &data); }, _ => panic!(), } }, None => { assert!(response.is_network_error()); assert_eq!( response.metadata().err(), Some(NetworkError::Internal( "Decoding data URL failed".to_owned() )) ); }, } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(b"hello world"), ); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType::from(mime::TEXT_PLAIN)), None, Some(b"hello"), ); } #[test] fn plain_html() { assert_parse( "data:text/html,<p>Servo</p>", Some(ContentType::from(mime::TEXT_HTML)), None, Some(b"<p>Servo</p>"), ); } #[test] fn
() { assert_parse( "data:text/plain;charset=latin1,hello", Some(ContentType::from( "text/plain; charset=latin1".parse::<Mime>().unwrap(), )), Some("latin1"), Some(b"hello"), ); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)), Some("utf-8"), Some(b"hello"), ); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_ct() { assert_parse( "data:application/octet-stream;base64,C62+7w==", Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)), None, Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_charset() { assert_parse( "data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType::from( "text/plain; charset=koi8-r".parse::<Mime>().unwrap(), )), Some("koi8-r"), Some(&[ 0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4, ]), ); }
plain_charset
identifier_name
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::fetch; use headers_core::HeaderMapExt; use headers_ext::ContentType; use hyper_serde::Serde; use mime::{self, Mime}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use servo_url::ServoUrl; use std::ops::Deref; #[cfg(test)] fn assert_parse( url: &'static str, content_type: Option<ContentType>, charset: Option<&str>, data: Option<&[u8]>, ) { let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); let response = fetch(&mut request, None); match data { Some(data) => { assert!(!response.is_network_error()); assert_eq!(response.headers.len(), 1); let header_content_type = response.headers.typed_get::<ContentType>(); assert_eq!(header_content_type, content_type); let metadata = match response.metadata() { Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m, result => panic!(result), }; assert_eq!(metadata.content_type.map(Serde::into_inner), content_type); assert_eq!(metadata.charset.as_ref().map(String::deref), charset); let resp_body = response.body.lock().unwrap(); match *resp_body { ResponseBody::Done(ref val) => { assert_eq!(val, &data); }, _ => panic!(), } }, None => { assert!(response.is_network_error()); assert_eq!( response.metadata().err(), Some(NetworkError::Internal( "Decoding data URL failed".to_owned() )) ); }, } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(b"hello world"), ); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType::from(mime::TEXT_PLAIN)), None, Some(b"hello"), ); } #[test] fn plain_html() { assert_parse( "data:text/html,<p>Servo</p>", Some(ContentType::from(mime::TEXT_HTML)), None, Some(b"<p>Servo</p>"), ); } #[test] fn plain_charset() { assert_parse( "data:text/plain;charset=latin1,hello", Some(ContentType::from( "text/plain; charset=latin1".parse::<Mime>().unwrap(), )), Some("latin1"), Some(b"hello"), ); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)), Some("utf-8"), Some(b"hello"), ); } #[test] fn base64()
#[test] fn base64_ct() { assert_parse( "data:application/octet-stream;base64,C62+7w==", Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)), None, Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_charset() { assert_parse( "data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType::from( "text/plain; charset=koi8-r".parse::<Mime>().unwrap(), )), Some("koi8-r"), Some(&[ 0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4, ]), ); }
{ assert_parse( "data:;base64,C62+7w==", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); }
identifier_body
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::fetch; use headers_core::HeaderMapExt; use headers_ext::ContentType; use hyper_serde::Serde; use mime::{self, Mime}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use servo_url::ServoUrl; use std::ops::Deref; #[cfg(test)] fn assert_parse( url: &'static str, content_type: Option<ContentType>, charset: Option<&str>, data: Option<&[u8]>, ) { let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); let response = fetch(&mut request, None); match data { Some(data) => { assert!(!response.is_network_error()); assert_eq!(response.headers.len(), 1); let header_content_type = response.headers.typed_get::<ContentType>(); assert_eq!(header_content_type, content_type); let metadata = match response.metadata() { Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m, result => panic!(result), }; assert_eq!(metadata.content_type.map(Serde::into_inner), content_type); assert_eq!(metadata.charset.as_ref().map(String::deref), charset); let resp_body = response.body.lock().unwrap(); match *resp_body { ResponseBody::Done(ref val) => { assert_eq!(val, &data); }, _ => panic!(), } }, None => { assert!(response.is_network_error()); assert_eq!( response.metadata().err(), Some(NetworkError::Internal( "Decoding data URL failed".to_owned() )) ); }, } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(b"hello world"), ); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType::from(mime::TEXT_PLAIN)), None, Some(b"hello"), ); } #[test] fn plain_html() { assert_parse( "data:text/html,<p>Servo</p>", Some(ContentType::from(mime::TEXT_HTML)), None, Some(b"<p>Servo</p>"), ); } #[test] fn plain_charset() { assert_parse( "data:text/plain;charset=latin1,hello", Some(ContentType::from( "text/plain; charset=latin1".parse::<Mime>().unwrap(), )), Some("latin1"), Some(b"hello"), ); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)), Some("utf-8"), Some(b"hello"), ); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==",
Some("us-ascii"), Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_ct() { assert_parse( "data:application/octet-stream;base64,C62+7w==", Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)), None, Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_charset() { assert_parse( "data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType::from( "text/plain; charset=koi8-r".parse::<Mime>().unwrap(), )), Some("koi8-r"), Some(&[ 0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4, ]), ); }
Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )),
random_line_split
public_api.js
/** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export { AnimationDriver, ɵAnimation, ɵAnimationStyleNormalizer, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsStyleNormalizer, ɵAnimationDriver, ɵNoopAnimationDriver, ɵAnimationEngine, ɵCssKeyframesDriver, ɵCssKeyframesPlayer, ɵcontainsElement, ɵinvokeQuery, ɵmatchesElement, ɵvalidateStyleProperty, ɵWebAnimationsDriver, ɵsupportsWebAnimations, ɵWebAnimationsPlayer, ɵallowPreviousPlayerStylesMerge } from './src/browser'; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2FuaW1hdGlvbnMvYnJvd3Nlci9wdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7QUFhQSx1WkFBYyxlQUFlLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbi8qKlxuICogQG1vZHVsZVxuICogQGRlc2NyaXB0aW9uXG4gKiBFbnRyeSBwb2ludCBmb3IgYWxsIHB1YmxpYyBBUElzIG9mIHRoaXMgcGFja2FnZS5cbiAqL1xuZXhwb3J0ICogZnJvbSAnLi9zcmMvYnJvd3Nlcic7XG4iXX0=
random_line_split
dom_adapter.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { isBlank } from '../facade/lang'; var _DOM = null; export function getDOM() { return _DOM; } export function setDOM(adapter) { _DOM = adapter; } export function setRootDomAdapter(adapter) { if (isBlank(_DOM)) { _DOM = adapter; } } /* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. */ export class DomAdapter { constructor() { this.xhrType = null; } /** @deprecated */ getXHR() { return this.xhrType; } /** * Maps attribute names to their corresponding property names for cases * where attribute name doesn't match property name. */ get attrToPropMap() { return this._attrToPropMap; } ; set attrToPropMap(value)
; } //# sourceMappingURL=dom_adapter.js.map
{ this._attrToPropMap = value; }
identifier_body