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
data.py
import itertools import os
import zipfile import numpy as np import requests import scipy.sparse as sp def _get_movielens_path(): """ Get path to the movielens dataset file. """ return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'movielens.zip') def _download_movielens(dest_path): """ Download the dataset. """ url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip' req = requests.get(url, stream=True) with open(dest_path, 'wb') as fd: for chunk in req.iter_content(): fd.write(chunk) def _get_raw_movielens_data(): """ Return the raw lines of the train and test files. """ path = _get_movielens_path() if not os.path.isfile(path): _download_movielens(path) with zipfile.ZipFile(path) as datafile: return (datafile.read('ml-100k/ua.base').decode().split('\n'), datafile.read('ml-100k/ua.test').decode().split('\n')) def _parse(data): """ Parse movielens dataset lines. """ for line in data: if not line: continue uid, iid, rating, timestamp = [int(x) for x in line.split('\t')] yield uid, iid, rating, timestamp def _build_interaction_matrix(rows, cols, data): """ Build the training matrix (no_users, no_items), with ratings >= 4.0 being marked as positive and the rest as negative. """ mat = sp.lil_matrix((rows, cols), dtype=np.int32) for uid, iid, rating, timestamp in data: if rating >= 4.0: mat[uid, iid] = 1.0 else: mat[uid, iid] = -1.0 return mat.tocoo() def _get_movie_raw_metadata(): """ Get raw lines of the genre file. """ path = _get_movielens_path() if not os.path.isfile(path): _download_movielens(path) with zipfile.ZipFile(path) as datafile: return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') def get_movielens_item_metadata(use_item_ids): """ Build a matrix of genre features (no_items, no_features). If use_item_ids is True, per-item features will also be used. """ features = {} genre_set = set() for line in _get_movie_raw_metadata(): if not line: continue splt = line.split('|') item_id = int(splt[0]) genres = [idx for idx, val in zip(range(len(splt[5:])), splt[5:]) if int(val) > 0] if use_item_ids: # Add item-specific features too genres.append(item_id) for genre_id in genres: genre_set.add(genre_id) features[item_id] = genres mat = sp.lil_matrix((len(features) + 1, len(genre_set)), dtype=np.int32) for item_id, genre_ids in features.items(): for genre_id in genre_ids: mat[item_id, genre_id] = 1 return mat def get_movielens_data(): """ Return (train_interactions, test_interactions). """ train_data, test_data = _get_raw_movielens_data() uids = set() iids = set() for uid, iid, rating, timestamp in itertools.chain(_parse(train_data), _parse(test_data)): uids.add(uid) iids.add(iid) rows = max(uids) + 1 cols = max(iids) + 1 return (_build_interaction_matrix(rows, cols, _parse(train_data)), _build_interaction_matrix(rows, cols, _parse(test_data)))
random_line_split
data.py
import itertools import os import zipfile import numpy as np import requests import scipy.sparse as sp def _get_movielens_path(): """ Get path to the movielens dataset file. """ return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'movielens.zip') def _download_movielens(dest_path): """ Download the dataset. """ url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip' req = requests.get(url, stream=True) with open(dest_path, 'wb') as fd: for chunk in req.iter_content(): fd.write(chunk) def _get_raw_movielens_data(): """ Return the raw lines of the train and test files. """ path = _get_movielens_path() if not os.path.isfile(path): _download_movielens(path) with zipfile.ZipFile(path) as datafile: return (datafile.read('ml-100k/ua.base').decode().split('\n'), datafile.read('ml-100k/ua.test').decode().split('\n')) def _parse(data):
def _build_interaction_matrix(rows, cols, data): """ Build the training matrix (no_users, no_items), with ratings >= 4.0 being marked as positive and the rest as negative. """ mat = sp.lil_matrix((rows, cols), dtype=np.int32) for uid, iid, rating, timestamp in data: if rating >= 4.0: mat[uid, iid] = 1.0 else: mat[uid, iid] = -1.0 return mat.tocoo() def _get_movie_raw_metadata(): """ Get raw lines of the genre file. """ path = _get_movielens_path() if not os.path.isfile(path): _download_movielens(path) with zipfile.ZipFile(path) as datafile: return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') def get_movielens_item_metadata(use_item_ids): """ Build a matrix of genre features (no_items, no_features). If use_item_ids is True, per-item features will also be used. """ features = {} genre_set = set() for line in _get_movie_raw_metadata(): if not line: continue splt = line.split('|') item_id = int(splt[0]) genres = [idx for idx, val in zip(range(len(splt[5:])), splt[5:]) if int(val) > 0] if use_item_ids: # Add item-specific features too genres.append(item_id) for genre_id in genres: genre_set.add(genre_id) features[item_id] = genres mat = sp.lil_matrix((len(features) + 1, len(genre_set)), dtype=np.int32) for item_id, genre_ids in features.items(): for genre_id in genre_ids: mat[item_id, genre_id] = 1 return mat def get_movielens_data(): """ Return (train_interactions, test_interactions). """ train_data, test_data = _get_raw_movielens_data() uids = set() iids = set() for uid, iid, rating, timestamp in itertools.chain(_parse(train_data), _parse(test_data)): uids.add(uid) iids.add(iid) rows = max(uids) + 1 cols = max(iids) + 1 return (_build_interaction_matrix(rows, cols, _parse(train_data)), _build_interaction_matrix(rows, cols, _parse(test_data)))
""" Parse movielens dataset lines. """ for line in data: if not line: continue uid, iid, rating, timestamp = [int(x) for x in line.split('\t')] yield uid, iid, rating, timestamp
identifier_body
signal.ts
module Retrieve { interface SignalCallbackItem { callback:(...args:any[]) => void; context?:any; } export class Signal { private callbacks:SignalCallbackItem[]; add(callback:(...args:any[]) => void, context?:any) { this.callbacks || (this.callbacks = []); if (this.getCallbackIndex(callback, context) == -1) this.callbacks.push({callback: callback, context: context}); } remove(callback:(...args:any[]) => void, context?:any) { var index:number = this.getCallbackIndex(callback, context); if (index >= 0) this.callbacks.splice(index, 1); } trigger(...args:any[]) { if (this.callbacks) { for (var i:number = 0; i < this.callbacks.length; i++) { var item:SignalCallbackItem = this.callbacks[i]; if (item && typeof item.callback === "function") item.callback.apply(item.context || this, args); } } } private getCallbackIndex(callback:(...args:any[]) => void, context?:any):number { if (this.callbacks && (callback || context)) {
} } return -1; } } }
for (var i:number = 0; i < this.callbacks.length; i++) { var item:SignalCallbackItem = this.callbacks[i]; if (item && (!callback || item.callback === callback) && (!context || item.context === context)) return i;
random_line_split
signal.ts
module Retrieve { interface SignalCallbackItem { callback:(...args:any[]) => void; context?:any; } export class Signal { private callbacks:SignalCallbackItem[]; add(callback:(...args:any[]) => void, context?:any) { this.callbacks || (this.callbacks = []); if (this.getCallbackIndex(callback, context) == -1) this.callbacks.push({callback: callback, context: context}); } remove(callback:(...args:any[]) => void, context?:any) { var index:number = this.getCallbackIndex(callback, context); if (index >= 0) this.callbacks.splice(index, 1); } trigger(...args:any[]) { if (this.callbacks)
} private getCallbackIndex(callback:(...args:any[]) => void, context?:any):number { if (this.callbacks && (callback || context)) { for (var i:number = 0; i < this.callbacks.length; i++) { var item:SignalCallbackItem = this.callbacks[i]; if (item && (!callback || item.callback === callback) && (!context || item.context === context)) return i; } } return -1; } } }
{ for (var i:number = 0; i < this.callbacks.length; i++) { var item:SignalCallbackItem = this.callbacks[i]; if (item && typeof item.callback === "function") item.callback.apply(item.context || this, args); } }
conditional_block
signal.ts
module Retrieve { interface SignalCallbackItem { callback:(...args:any[]) => void; context?:any; } export class Signal { private callbacks:SignalCallbackItem[]; add(callback:(...args:any[]) => void, context?:any) { this.callbacks || (this.callbacks = []); if (this.getCallbackIndex(callback, context) == -1) this.callbacks.push({callback: callback, context: context}); } remove(callback:(...args:any[]) => void, context?:any) { var index:number = this.getCallbackIndex(callback, context); if (index >= 0) this.callbacks.splice(index, 1); }
(...args:any[]) { if (this.callbacks) { for (var i:number = 0; i < this.callbacks.length; i++) { var item:SignalCallbackItem = this.callbacks[i]; if (item && typeof item.callback === "function") item.callback.apply(item.context || this, args); } } } private getCallbackIndex(callback:(...args:any[]) => void, context?:any):number { if (this.callbacks && (callback || context)) { for (var i:number = 0; i < this.callbacks.length; i++) { var item:SignalCallbackItem = this.callbacks[i]; if (item && (!callback || item.callback === callback) && (!context || item.context === context)) return i; } } return -1; } } }
trigger
identifier_name
signal.ts
module Retrieve { interface SignalCallbackItem { callback:(...args:any[]) => void; context?:any; } export class Signal { private callbacks:SignalCallbackItem[]; add(callback:(...args:any[]) => void, context?:any) { this.callbacks || (this.callbacks = []); if (this.getCallbackIndex(callback, context) == -1) this.callbacks.push({callback: callback, context: context}); } remove(callback:(...args:any[]) => void, context?:any)
trigger(...args:any[]) { if (this.callbacks) { for (var i:number = 0; i < this.callbacks.length; i++) { var item:SignalCallbackItem = this.callbacks[i]; if (item && typeof item.callback === "function") item.callback.apply(item.context || this, args); } } } private getCallbackIndex(callback:(...args:any[]) => void, context?:any):number { if (this.callbacks && (callback || context)) { for (var i:number = 0; i < this.callbacks.length; i++) { var item:SignalCallbackItem = this.callbacks[i]; if (item && (!callback || item.callback === callback) && (!context || item.context === context)) return i; } } return -1; } } }
{ var index:number = this.getCallbackIndex(callback, context); if (index >= 0) this.callbacks.splice(index, 1); }
identifier_body
angular-loading-bar.js
/*! * angular-loading-bar v0.8.0 * https://chieffancypants.github.io/angular-loading-bar * Copyright (c) 2015 Wes Cruver * License: MIT */ /* * angular-loading-bar * * intercepts XHR requests and creates a loading bar. * Based on the excellent nprogress work by rstacruz (more info in readme) * * (c) 2013 Wes Cruver * License: MIT */ (function() { 'use strict'; // Alias the loading bar for various backwards compatibilities since the project has matured: angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']); angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']); /** * loadingBarInterceptor service * * Registers itself as an Angular interceptor and listens for XHR requests. */ angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar']) .config(['$httpProvider', function ($httpProvider) { var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) { /** * The total number of requests made */ var reqsTotal = 0; /** * The number of requests completed (either successfully or not) */ var reqsCompleted = 0; /** * The amount of time spent fetching before showing the loading bar */ var latencyThreshold = cfpLoadingBar.latencyThreshold; /** * $timeout handle for latencyThreshold */ var startTimeout; /** * calls cfpLoadingBar.complete() which removes the * loading bar from the DOM. */ function setComplete() { $timeout.cancel(startTimeout); cfpLoadingBar.complete(); reqsCompleted = 0; reqsTotal = 0; } /** * Determine if the response has already been cached * @param {Object} config the config option from the request * @return {Boolean} retrns true if cached, otherwise false */ function isCached(config) { var cache; var defaultCache = $cacheFactory.get('$http'); var defaults = $httpProvider.defaults; // Choose the proper cache source. Borrowed from angular: $http service if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = angular.isObject(config.cache) ? config.cache : angular.isObject(defaults.cache) ? defaults.cache : defaultCache; } var cached = cache !== undefined ? cache.get(config.url) !== undefined : false; if (config.cached !== undefined && cached !== config.cached)
config.cached = cached; return cached; } return { 'request': function(config) { // Check to make sure this request hasn't already been cached and that // the requester didn't explicitly ask us to ignore this request: if (!config.ignoreLoadingBar && !isCached(config)) { $rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url}); if (reqsTotal === 0) { startTimeout = $timeout(function() { cfpLoadingBar.start(); }, latencyThreshold); } reqsTotal++; cfpLoadingBar.set(reqsCompleted / reqsTotal); } return config; }, 'response': function(response) { if (!response || !response.config) { $log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return response; } if (!response.config.ignoreLoadingBar && !isCached(response.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return response; }, 'responseError': function(rejection) { if (!rejection || !rejection.config) { $log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return $q.reject(rejection); } if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return $q.reject(rejection); } }; }]; $httpProvider.interceptors.push(interceptor); }]); /** * Loading Bar * * This service handles adding and removing the actual element in the DOM. * Generally, best practices for DOM manipulation is to take place in a * directive, but because the element itself is injected in the DOM only upon * XHR requests, and it's likely needed on every view, the best option is to * use a service. */ angular.module('cfp.loadingBar', []) .provider('cfpLoadingBar', function() { this.autoIncrement = true; this.includeSpinner = true; this.includeBar = true; this.latencyThreshold = 100; this.startSize = 0.02; this.parentSelector = 'body'; this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>'; this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>'; this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) { var $animate; var $parentSelector = this.parentSelector, loadingBarContainer = angular.element(this.loadingBarTemplate), loadingBar = loadingBarContainer.find('div').eq(0), spinner = angular.element(this.spinnerTemplate); var incTimeout, completeTimeout, started = false, status = 0; var autoIncrement = this.autoIncrement; var includeSpinner = this.includeSpinner; var includeBar = this.includeBar; var startSize = this.startSize; /** * Inserts the loading bar element into the dom, and sets it to 2% */ function _start() { if (!$animate) { $animate = $injector.get('$animate'); } var $parent = $document.find($parentSelector).eq(0); $timeout.cancel(completeTimeout); // do not continually broadcast the started event: if (started) { return; } $rootScope.$broadcast('cfpLoadingBar:started'); started = true; if (includeBar) { $animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild)); } if (includeSpinner) { $animate.enter(spinner, $parent, angular.element($parent[0].lastChild)); } _set(startSize); } /** * Set the loading bar's width to a certain percent. * * @param n any value between 0 and 1 */ function _set(n) { if (!started) { return; } var pct = (n * 100) + '%'; loadingBar.css('width', pct); status = n; // increment loadingbar to give the illusion that there is always // progress but make sure to cancel the previous timeouts so we don't // have multiple incs running at the same time. if (autoIncrement) { $timeout.cancel(incTimeout); incTimeout = $timeout(function() { _inc(); }, 250); } } /** * Increments the loading bar by a random amount * but slows down as it progresses */ function _inc() { if (_status() >= 1) { return; } var rnd = 0; // TODO: do this mathmatically instead of through conditions var stat = _status(); if (stat >= 0 && stat < 0.25) { // Start out between 3 - 6% increments rnd = (Math.random() * (5 - 3 + 1) + 3) / 100; } else if (stat >= 0.25 && stat < 0.65) { // increment between 0 - 3% rnd = (Math.random() * 3) / 100; } else if (stat >= 0.65 && stat < 0.9) { // increment between 0 - 2% rnd = (Math.random() * 2) / 100; } else if (stat >= 0.9 && stat < 0.99) { // finally, increment it .5 % rnd = 0.005; } else { // after 99%, don't increment: rnd = 0; } var pct = _status() + rnd; _set(pct); } function _status() { return status; } function _completeAnimation() { status = 0; started = false; } function _complete() { if (!$animate) { $animate = $injector.get('$animate'); } $rootScope.$broadcast('cfpLoadingBar:completed'); _set(1); $timeout.cancel(completeTimeout); // Attempt to aggregate any start/complete calls within 500ms: completeTimeout = $timeout(function() { var promise = $animate.leave(loadingBarContainer, _completeAnimation); if (promise && promise.then) { promise.then(_completeAnimation); } $animate.leave(spinner); }, 500); } return { start : _start, set : _set, status : _status, inc : _inc, complete : _complete, autoIncrement : this.autoIncrement, includeSpinner : this.includeSpinner, latencyThreshold : this.latencyThreshold, parentSelector : this.parentSelector, startSize : this.startSize }; }]; // }); // wtf javascript. srsly })(); //
{ return config.cached; }
conditional_block
angular-loading-bar.js
/*! * angular-loading-bar v0.8.0 * https://chieffancypants.github.io/angular-loading-bar * Copyright (c) 2015 Wes Cruver * License: MIT */ /* * angular-loading-bar * * intercepts XHR requests and creates a loading bar. * Based on the excellent nprogress work by rstacruz (more info in readme) * * (c) 2013 Wes Cruver * License: MIT */ (function() { 'use strict'; // Alias the loading bar for various backwards compatibilities since the project has matured: angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']); angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']); /** * loadingBarInterceptor service * * Registers itself as an Angular interceptor and listens for XHR requests. */ angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar']) .config(['$httpProvider', function ($httpProvider) { var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) { /** * The total number of requests made */ var reqsTotal = 0; /** * The number of requests completed (either successfully or not) */ var reqsCompleted = 0; /** * The amount of time spent fetching before showing the loading bar */ var latencyThreshold = cfpLoadingBar.latencyThreshold; /** * $timeout handle for latencyThreshold */ var startTimeout; /** * calls cfpLoadingBar.complete() which removes the * loading bar from the DOM. */ function
() { $timeout.cancel(startTimeout); cfpLoadingBar.complete(); reqsCompleted = 0; reqsTotal = 0; } /** * Determine if the response has already been cached * @param {Object} config the config option from the request * @return {Boolean} retrns true if cached, otherwise false */ function isCached(config) { var cache; var defaultCache = $cacheFactory.get('$http'); var defaults = $httpProvider.defaults; // Choose the proper cache source. Borrowed from angular: $http service if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = angular.isObject(config.cache) ? config.cache : angular.isObject(defaults.cache) ? defaults.cache : defaultCache; } var cached = cache !== undefined ? cache.get(config.url) !== undefined : false; if (config.cached !== undefined && cached !== config.cached) { return config.cached; } config.cached = cached; return cached; } return { 'request': function(config) { // Check to make sure this request hasn't already been cached and that // the requester didn't explicitly ask us to ignore this request: if (!config.ignoreLoadingBar && !isCached(config)) { $rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url}); if (reqsTotal === 0) { startTimeout = $timeout(function() { cfpLoadingBar.start(); }, latencyThreshold); } reqsTotal++; cfpLoadingBar.set(reqsCompleted / reqsTotal); } return config; }, 'response': function(response) { if (!response || !response.config) { $log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return response; } if (!response.config.ignoreLoadingBar && !isCached(response.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return response; }, 'responseError': function(rejection) { if (!rejection || !rejection.config) { $log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return $q.reject(rejection); } if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return $q.reject(rejection); } }; }]; $httpProvider.interceptors.push(interceptor); }]); /** * Loading Bar * * This service handles adding and removing the actual element in the DOM. * Generally, best practices for DOM manipulation is to take place in a * directive, but because the element itself is injected in the DOM only upon * XHR requests, and it's likely needed on every view, the best option is to * use a service. */ angular.module('cfp.loadingBar', []) .provider('cfpLoadingBar', function() { this.autoIncrement = true; this.includeSpinner = true; this.includeBar = true; this.latencyThreshold = 100; this.startSize = 0.02; this.parentSelector = 'body'; this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>'; this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>'; this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) { var $animate; var $parentSelector = this.parentSelector, loadingBarContainer = angular.element(this.loadingBarTemplate), loadingBar = loadingBarContainer.find('div').eq(0), spinner = angular.element(this.spinnerTemplate); var incTimeout, completeTimeout, started = false, status = 0; var autoIncrement = this.autoIncrement; var includeSpinner = this.includeSpinner; var includeBar = this.includeBar; var startSize = this.startSize; /** * Inserts the loading bar element into the dom, and sets it to 2% */ function _start() { if (!$animate) { $animate = $injector.get('$animate'); } var $parent = $document.find($parentSelector).eq(0); $timeout.cancel(completeTimeout); // do not continually broadcast the started event: if (started) { return; } $rootScope.$broadcast('cfpLoadingBar:started'); started = true; if (includeBar) { $animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild)); } if (includeSpinner) { $animate.enter(spinner, $parent, angular.element($parent[0].lastChild)); } _set(startSize); } /** * Set the loading bar's width to a certain percent. * * @param n any value between 0 and 1 */ function _set(n) { if (!started) { return; } var pct = (n * 100) + '%'; loadingBar.css('width', pct); status = n; // increment loadingbar to give the illusion that there is always // progress but make sure to cancel the previous timeouts so we don't // have multiple incs running at the same time. if (autoIncrement) { $timeout.cancel(incTimeout); incTimeout = $timeout(function() { _inc(); }, 250); } } /** * Increments the loading bar by a random amount * but slows down as it progresses */ function _inc() { if (_status() >= 1) { return; } var rnd = 0; // TODO: do this mathmatically instead of through conditions var stat = _status(); if (stat >= 0 && stat < 0.25) { // Start out between 3 - 6% increments rnd = (Math.random() * (5 - 3 + 1) + 3) / 100; } else if (stat >= 0.25 && stat < 0.65) { // increment between 0 - 3% rnd = (Math.random() * 3) / 100; } else if (stat >= 0.65 && stat < 0.9) { // increment between 0 - 2% rnd = (Math.random() * 2) / 100; } else if (stat >= 0.9 && stat < 0.99) { // finally, increment it .5 % rnd = 0.005; } else { // after 99%, don't increment: rnd = 0; } var pct = _status() + rnd; _set(pct); } function _status() { return status; } function _completeAnimation() { status = 0; started = false; } function _complete() { if (!$animate) { $animate = $injector.get('$animate'); } $rootScope.$broadcast('cfpLoadingBar:completed'); _set(1); $timeout.cancel(completeTimeout); // Attempt to aggregate any start/complete calls within 500ms: completeTimeout = $timeout(function() { var promise = $animate.leave(loadingBarContainer, _completeAnimation); if (promise && promise.then) { promise.then(_completeAnimation); } $animate.leave(spinner); }, 500); } return { start : _start, set : _set, status : _status, inc : _inc, complete : _complete, autoIncrement : this.autoIncrement, includeSpinner : this.includeSpinner, latencyThreshold : this.latencyThreshold, parentSelector : this.parentSelector, startSize : this.startSize }; }]; // }); // wtf javascript. srsly })(); //
setComplete
identifier_name
angular-loading-bar.js
/*! * angular-loading-bar v0.8.0 * https://chieffancypants.github.io/angular-loading-bar * Copyright (c) 2015 Wes Cruver * License: MIT */ /* * angular-loading-bar * * intercepts XHR requests and creates a loading bar. * Based on the excellent nprogress work by rstacruz (more info in readme) * * (c) 2013 Wes Cruver * License: MIT */ (function() { 'use strict'; // Alias the loading bar for various backwards compatibilities since the project has matured: angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']); angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']); /** * loadingBarInterceptor service * * Registers itself as an Angular interceptor and listens for XHR requests. */ angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar']) .config(['$httpProvider', function ($httpProvider) { var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) { /** * The total number of requests made */ var reqsTotal = 0; /** * The number of requests completed (either successfully or not) */ var reqsCompleted = 0; /** * The amount of time spent fetching before showing the loading bar */ var latencyThreshold = cfpLoadingBar.latencyThreshold; /** * $timeout handle for latencyThreshold */ var startTimeout; /** * calls cfpLoadingBar.complete() which removes the * loading bar from the DOM. */ function setComplete() { $timeout.cancel(startTimeout); cfpLoadingBar.complete(); reqsCompleted = 0; reqsTotal = 0; } /** * Determine if the response has already been cached * @param {Object} config the config option from the request * @return {Boolean} retrns true if cached, otherwise false */ function isCached(config) { var cache; var defaultCache = $cacheFactory.get('$http'); var defaults = $httpProvider.defaults; // Choose the proper cache source. Borrowed from angular: $http service if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = angular.isObject(config.cache) ? config.cache : angular.isObject(defaults.cache) ? defaults.cache : defaultCache; } var cached = cache !== undefined ? cache.get(config.url) !== undefined : false; if (config.cached !== undefined && cached !== config.cached) { return config.cached; } config.cached = cached; return cached; } return { 'request': function(config) { // Check to make sure this request hasn't already been cached and that // the requester didn't explicitly ask us to ignore this request: if (!config.ignoreLoadingBar && !isCached(config)) { $rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url}); if (reqsTotal === 0) { startTimeout = $timeout(function() { cfpLoadingBar.start(); }, latencyThreshold); } reqsTotal++; cfpLoadingBar.set(reqsCompleted / reqsTotal); } return config; }, 'response': function(response) { if (!response || !response.config) { $log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return response; } if (!response.config.ignoreLoadingBar && !isCached(response.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return response; }, 'responseError': function(rejection) { if (!rejection || !rejection.config) { $log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return $q.reject(rejection); } if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return $q.reject(rejection); } }; }]; $httpProvider.interceptors.push(interceptor); }]); /** * Loading Bar * * This service handles adding and removing the actual element in the DOM. * Generally, best practices for DOM manipulation is to take place in a * directive, but because the element itself is injected in the DOM only upon * XHR requests, and it's likely needed on every view, the best option is to * use a service. */ angular.module('cfp.loadingBar', []) .provider('cfpLoadingBar', function() { this.autoIncrement = true; this.includeSpinner = true; this.includeBar = true; this.latencyThreshold = 100; this.startSize = 0.02; this.parentSelector = 'body'; this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>'; this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>'; this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) { var $animate; var $parentSelector = this.parentSelector, loadingBarContainer = angular.element(this.loadingBarTemplate), loadingBar = loadingBarContainer.find('div').eq(0), spinner = angular.element(this.spinnerTemplate); var incTimeout, completeTimeout, started = false, status = 0; var autoIncrement = this.autoIncrement; var includeSpinner = this.includeSpinner; var includeBar = this.includeBar; var startSize = this.startSize; /** * Inserts the loading bar element into the dom, and sets it to 2% */ function _start() { if (!$animate) { $animate = $injector.get('$animate'); } var $parent = $document.find($parentSelector).eq(0); $timeout.cancel(completeTimeout); // do not continually broadcast the started event: if (started) { return; }
if (includeBar) { $animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild)); } if (includeSpinner) { $animate.enter(spinner, $parent, angular.element($parent[0].lastChild)); } _set(startSize); } /** * Set the loading bar's width to a certain percent. * * @param n any value between 0 and 1 */ function _set(n) { if (!started) { return; } var pct = (n * 100) + '%'; loadingBar.css('width', pct); status = n; // increment loadingbar to give the illusion that there is always // progress but make sure to cancel the previous timeouts so we don't // have multiple incs running at the same time. if (autoIncrement) { $timeout.cancel(incTimeout); incTimeout = $timeout(function() { _inc(); }, 250); } } /** * Increments the loading bar by a random amount * but slows down as it progresses */ function _inc() { if (_status() >= 1) { return; } var rnd = 0; // TODO: do this mathmatically instead of through conditions var stat = _status(); if (stat >= 0 && stat < 0.25) { // Start out between 3 - 6% increments rnd = (Math.random() * (5 - 3 + 1) + 3) / 100; } else if (stat >= 0.25 && stat < 0.65) { // increment between 0 - 3% rnd = (Math.random() * 3) / 100; } else if (stat >= 0.65 && stat < 0.9) { // increment between 0 - 2% rnd = (Math.random() * 2) / 100; } else if (stat >= 0.9 && stat < 0.99) { // finally, increment it .5 % rnd = 0.005; } else { // after 99%, don't increment: rnd = 0; } var pct = _status() + rnd; _set(pct); } function _status() { return status; } function _completeAnimation() { status = 0; started = false; } function _complete() { if (!$animate) { $animate = $injector.get('$animate'); } $rootScope.$broadcast('cfpLoadingBar:completed'); _set(1); $timeout.cancel(completeTimeout); // Attempt to aggregate any start/complete calls within 500ms: completeTimeout = $timeout(function() { var promise = $animate.leave(loadingBarContainer, _completeAnimation); if (promise && promise.then) { promise.then(_completeAnimation); } $animate.leave(spinner); }, 500); } return { start : _start, set : _set, status : _status, inc : _inc, complete : _complete, autoIncrement : this.autoIncrement, includeSpinner : this.includeSpinner, latencyThreshold : this.latencyThreshold, parentSelector : this.parentSelector, startSize : this.startSize }; }]; // }); // wtf javascript. srsly })(); //
$rootScope.$broadcast('cfpLoadingBar:started'); started = true;
random_line_split
angular-loading-bar.js
/*! * angular-loading-bar v0.8.0 * https://chieffancypants.github.io/angular-loading-bar * Copyright (c) 2015 Wes Cruver * License: MIT */ /* * angular-loading-bar * * intercepts XHR requests and creates a loading bar. * Based on the excellent nprogress work by rstacruz (more info in readme) * * (c) 2013 Wes Cruver * License: MIT */ (function() { 'use strict'; // Alias the loading bar for various backwards compatibilities since the project has matured: angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']); angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']); /** * loadingBarInterceptor service * * Registers itself as an Angular interceptor and listens for XHR requests. */ angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar']) .config(['$httpProvider', function ($httpProvider) { var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) { /** * The total number of requests made */ var reqsTotal = 0; /** * The number of requests completed (either successfully or not) */ var reqsCompleted = 0; /** * The amount of time spent fetching before showing the loading bar */ var latencyThreshold = cfpLoadingBar.latencyThreshold; /** * $timeout handle for latencyThreshold */ var startTimeout; /** * calls cfpLoadingBar.complete() which removes the * loading bar from the DOM. */ function setComplete() { $timeout.cancel(startTimeout); cfpLoadingBar.complete(); reqsCompleted = 0; reqsTotal = 0; } /** * Determine if the response has already been cached * @param {Object} config the config option from the request * @return {Boolean} retrns true if cached, otherwise false */ function isCached(config) { var cache; var defaultCache = $cacheFactory.get('$http'); var defaults = $httpProvider.defaults; // Choose the proper cache source. Borrowed from angular: $http service if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = angular.isObject(config.cache) ? config.cache : angular.isObject(defaults.cache) ? defaults.cache : defaultCache; } var cached = cache !== undefined ? cache.get(config.url) !== undefined : false; if (config.cached !== undefined && cached !== config.cached) { return config.cached; } config.cached = cached; return cached; } return { 'request': function(config) { // Check to make sure this request hasn't already been cached and that // the requester didn't explicitly ask us to ignore this request: if (!config.ignoreLoadingBar && !isCached(config)) { $rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url}); if (reqsTotal === 0) { startTimeout = $timeout(function() { cfpLoadingBar.start(); }, latencyThreshold); } reqsTotal++; cfpLoadingBar.set(reqsCompleted / reqsTotal); } return config; }, 'response': function(response) { if (!response || !response.config) { $log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return response; } if (!response.config.ignoreLoadingBar && !isCached(response.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return response; }, 'responseError': function(rejection) { if (!rejection || !rejection.config) { $log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return $q.reject(rejection); } if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return $q.reject(rejection); } }; }]; $httpProvider.interceptors.push(interceptor); }]); /** * Loading Bar * * This service handles adding and removing the actual element in the DOM. * Generally, best practices for DOM manipulation is to take place in a * directive, but because the element itself is injected in the DOM only upon * XHR requests, and it's likely needed on every view, the best option is to * use a service. */ angular.module('cfp.loadingBar', []) .provider('cfpLoadingBar', function() { this.autoIncrement = true; this.includeSpinner = true; this.includeBar = true; this.latencyThreshold = 100; this.startSize = 0.02; this.parentSelector = 'body'; this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>'; this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>'; this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) { var $animate; var $parentSelector = this.parentSelector, loadingBarContainer = angular.element(this.loadingBarTemplate), loadingBar = loadingBarContainer.find('div').eq(0), spinner = angular.element(this.spinnerTemplate); var incTimeout, completeTimeout, started = false, status = 0; var autoIncrement = this.autoIncrement; var includeSpinner = this.includeSpinner; var includeBar = this.includeBar; var startSize = this.startSize; /** * Inserts the loading bar element into the dom, and sets it to 2% */ function _start() { if (!$animate) { $animate = $injector.get('$animate'); } var $parent = $document.find($parentSelector).eq(0); $timeout.cancel(completeTimeout); // do not continually broadcast the started event: if (started) { return; } $rootScope.$broadcast('cfpLoadingBar:started'); started = true; if (includeBar) { $animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild)); } if (includeSpinner) { $animate.enter(spinner, $parent, angular.element($parent[0].lastChild)); } _set(startSize); } /** * Set the loading bar's width to a certain percent. * * @param n any value between 0 and 1 */ function _set(n) { if (!started) { return; } var pct = (n * 100) + '%'; loadingBar.css('width', pct); status = n; // increment loadingbar to give the illusion that there is always // progress but make sure to cancel the previous timeouts so we don't // have multiple incs running at the same time. if (autoIncrement) { $timeout.cancel(incTimeout); incTimeout = $timeout(function() { _inc(); }, 250); } } /** * Increments the loading bar by a random amount * but slows down as it progresses */ function _inc()
function _status() { return status; } function _completeAnimation() { status = 0; started = false; } function _complete() { if (!$animate) { $animate = $injector.get('$animate'); } $rootScope.$broadcast('cfpLoadingBar:completed'); _set(1); $timeout.cancel(completeTimeout); // Attempt to aggregate any start/complete calls within 500ms: completeTimeout = $timeout(function() { var promise = $animate.leave(loadingBarContainer, _completeAnimation); if (promise && promise.then) { promise.then(_completeAnimation); } $animate.leave(spinner); }, 500); } return { start : _start, set : _set, status : _status, inc : _inc, complete : _complete, autoIncrement : this.autoIncrement, includeSpinner : this.includeSpinner, latencyThreshold : this.latencyThreshold, parentSelector : this.parentSelector, startSize : this.startSize }; }]; // }); // wtf javascript. srsly })(); //
{ if (_status() >= 1) { return; } var rnd = 0; // TODO: do this mathmatically instead of through conditions var stat = _status(); if (stat >= 0 && stat < 0.25) { // Start out between 3 - 6% increments rnd = (Math.random() * (5 - 3 + 1) + 3) / 100; } else if (stat >= 0.25 && stat < 0.65) { // increment between 0 - 3% rnd = (Math.random() * 3) / 100; } else if (stat >= 0.65 && stat < 0.9) { // increment between 0 - 2% rnd = (Math.random() * 2) / 100; } else if (stat >= 0.9 && stat < 0.99) { // finally, increment it .5 % rnd = 0.005; } else { // after 99%, don't increment: rnd = 0; } var pct = _status() + rnd; _set(pct); }
identifier_body
contents.spec.tsx
import React from 'react'; import {shallow} from 'enzyme'; import toJson from 'enzyme-to-json'; import ShallowDropDownContents, {ShallowDropDownContentsProps} from './contents'; describe('<ShallowDropDownContents/>', () => { const props: ShallowDropDownContentsProps = { ...ShallowDropDownContents.defaultProps, children: 'Foo children', isOpen: false, closeDropDown: jest.fn(), theme: { 'dropDown__contents': 'baseDropDownContentsClassName', 'dropDown__contents--isOpen': 'openDropDownContentsClassName', 'dropDown__contents--scrollable': 'scrollDropDownContentsClassName' }, wrapperRef: React.createRef(), }; it('should not render when having no children.', () => { const wrapper = shallow(<ShallowDropDownContents {...props}/>);
const wrapper = shallow(<ShallowDropDownContents {...props} isOpen={true} className="fooClassName"/>); expect(wrapper.prop('className')).toContain('fooClassName'); }); it('should render the themes "dropDown__contents--isOpen" className in case the "isOpen" prop is true.', () => { const wrapper = shallow(<ShallowDropDownContents {...props} isOpen={true}/>); expect(wrapper.hasClass('openDropDownContentsClassName')).toBe(true); }); it('should render a aria-hidden="false" attribute in the wrapper in case the "isOpen" prop is true.', () => { const wrapper = shallow(<ShallowDropDownContents {...props} isOpen={true}/>); expect(wrapper.html().includes('aria-hidden="false"')).toBe(true); }); it('should render a aria-label="dropdown" and role="button" attribute in the wrapper in case the "isOpen" prop is true.', () => { const wrapper = shallow(<ShallowDropDownContents {...props} isOpen={true}/>); expect(wrapper.html().includes('aria-label="dropdown"')).toBe(true); }); it('should call the "closeDropDown" prop when clicking on the wrapper.', () => { const closeDropDown = jest.fn(); const wrapper = shallow(<ShallowDropDownContents {...props} isOpen={true} closeDropDown={closeDropDown}/>); wrapper.simulate('click'); expect(closeDropDown.mock.calls.length).toBe(1); }); });
expect(toJson(wrapper)).toBeFalsy(); }); it('should allow the propagation of "className" with the "className" prop.', () => {
random_line_split
filesystem.d.ts
/// <reference types="node" />
* 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 { Path, PathFragment } from '@angular-devkit/core'; import { DirEntry, FileEntry } from './interface'; import { VirtualDirEntry, VirtualTree } from './virtual'; export interface FileSystemTreeHost { listDirectory: (path: string) => string[]; isDirectory: (path: string) => boolean; readFile: (path: string) => Buffer; join: (path1: string, other: string) => string; } export declare class FileSystemDirEntry extends VirtualDirEntry { protected _host: FileSystemTreeHost; protected _systemPath: string; constructor(_host: FileSystemTreeHost, tree: FileSystemTree, _systemPath?: string, path?: Path); protected _createDir(name: PathFragment): DirEntry; readonly parent: DirEntry | null; readonly subdirs: PathFragment[]; readonly subfiles: PathFragment[]; file(name: PathFragment): FileEntry | null; } export declare class FileSystemTree extends VirtualTree { private _host; protected _initialized: boolean; constructor(_host: FileSystemTreeHost); readonly tree: Map<Path, FileEntry>; get(path: string): FileEntry | null; protected _copyTo<T extends VirtualTree>(tree: T): void; protected _recursiveFileList(): [string, Path][]; } export declare class FileSystemCreateTree extends FileSystemTree { constructor(host: FileSystemTreeHost); }
/** * @license
random_line_split
filesystem.d.ts
/// <reference types="node" /> /** * @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 { Path, PathFragment } from '@angular-devkit/core'; import { DirEntry, FileEntry } from './interface'; import { VirtualDirEntry, VirtualTree } from './virtual'; export interface FileSystemTreeHost { listDirectory: (path: string) => string[]; isDirectory: (path: string) => boolean; readFile: (path: string) => Buffer; join: (path1: string, other: string) => string; } export declare class FileSystemDirEntry extends VirtualDirEntry { protected _host: FileSystemTreeHost; protected _systemPath: string; constructor(_host: FileSystemTreeHost, tree: FileSystemTree, _systemPath?: string, path?: Path); protected _createDir(name: PathFragment): DirEntry; readonly parent: DirEntry | null; readonly subdirs: PathFragment[]; readonly subfiles: PathFragment[]; file(name: PathFragment): FileEntry | null; } export declare class FileSystemTree extends VirtualTree { private _host; protected _initialized: boolean; constructor(_host: FileSystemTreeHost); readonly tree: Map<Path, FileEntry>; get(path: string): FileEntry | null; protected _copyTo<T extends VirtualTree>(tree: T): void; protected _recursiveFileList(): [string, Path][]; } export declare class
extends FileSystemTree { constructor(host: FileSystemTreeHost); }
FileSystemCreateTree
identifier_name
projecteuler6.py
# -*- coding: UTF-8 -*- #The sum of the squares of the first ten natural numbers is, #1² + 2² + ... + 10² = 385 #The square of the sum of the first ten natural numbers is, #(1 + 2 + ... + 10)² = 552 = 3025 #Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
sumsquare = sumsquare + i*i for j in range(1, 101): sum = sum + j print(sum) print(sum*sum) print(sum*sum - sumsquare)
sumsquare = 0 sum = 0 for i in range(1, 101):
random_line_split
projecteuler6.py
# -*- coding: UTF-8 -*- #The sum of the squares of the first ten natural numbers is, #1² + 2² + ... + 10² = 385 #The square of the sum of the first ten natural numbers is, #(1 + 2 + ... + 10)² = 552 = 3025 #Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. sumsquare = 0 sum = 0 for i in range(1, 101): sumsqu
j in range(1, 101): sum = sum + j print(sum) print(sum*sum) print(sum*sum - sumsquare)
are = sumsquare + i*i for
conditional_block
gtest_attribute.rs
use proc_macro::TokenStream; use quote::{format_ident, quote, quote_spanned}; use syn::spanned::Spanned; /// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked /// into a C++ binary that invokes Gtest. /// /// The `gtest` macro takes two arguments, which are Rust identifiers. The first is the name of the /// test suite and the second is the name of the test, each of which are converted to a string and /// given to Gtest. The name of the test function itself does not matter, and need not be unique /// (it's placed into a unique module based on the Gtest suite + test names. /// /// The test function must have no arguments. The return value must be either `()` or /// `std::result::Result<(), E>`. If another return type is found, the test will fail when run. If /// the return type is a `Result`, then an `Err` is treated as a test failure. /// /// # Examples /// ``` /// #[gtest(MathTest, Addition)] /// fn my_test() { /// expect_eq!(1 + 1, 2); /// } /// ``` /// /// The above adds the function to the Gtest binary as `MathTest.Addtition`: /// ``` /// [ RUN ] MathTest.Addition /// [ OK ] MathTest.Addition (0 ms) /// ``` /// /// A test with a Result return type, and which uses the `?` operator. It will fail if the test /// returns an `Err`, and print the resulting error string: /// ``` /// #[gtest(ResultTest, CheckThingWithResult)] /// fn my_test() -> std::result::Result<(), String> { /// call_thing_with_result()?; /// } /// ``` #[proc_macro_attribute] pub fn gtest(arg_stream: TokenStream, input: TokenStream) -> TokenStream { enum GtestAttributeArgument { TestSuite, TestName, } // Returns a string representation of an identifier argument to the attribute. For example, for // #[gtest(Foo, Bar)], this function would return "Foo" for position 0 and "Bar" for position 1. // If the argument is not a Rust identifier or not present, it returns a compiler error as a // TokenStream to be emitted. fn get_arg_string( args: &syn::AttributeArgs, which: GtestAttributeArgument, ) -> Result<String, TokenStream> { let pos = match which { GtestAttributeArgument::TestSuite => 0, GtestAttributeArgument::TestName => 1, }; match &args[pos] { syn::NestedMeta::Meta(syn::Meta::Path(path)) if path.segments.len() == 1 => { Ok(path.segments[0].ident.to_string()) } _ => { let error_stream = match which { GtestAttributeArgument::TestSuite => { quote_spanned! { args[pos].span() => compile_error!( "Expected a test suite name, written as an identifier." ); } } GtestAttributeArgument::TestName => { quote_spanned! { args[pos].span() => compile_error!( "Expected a test name, written as an identifier." ); } } }; Err(error_stream.into()) } } } let args = syn::parse_macro_input!(arg_stream as syn::AttributeArgs); let input_fn = syn::parse_macro_input!(input as syn::ItemFn); if let Some(asyncness) = input_fn.sig.asyncness { // TODO(crbug.com/1288947): We can support async functions once we have block_on() support // which will run a RunLoop until the async test completes. The run_test_fn just needs to be // generated to `block_on(|| #test_fn)` instead of calling `#test_fn` synchronously. return quote_spanned! { asyncness.span => compile_error!("async functions are not supported."); } .into(); } let (test_suite_name, test_name) = match args.len() { 2 => { let suite = match get_arg_string(&args, GtestAttributeArgument::TestSuite) { Ok(ok) => ok, Err(error_stream) => return error_stream, }; let test = match get_arg_string(&args, GtestAttributeArgument::TestName) { Ok(ok) => ok, Err(error_stream) => return error_stream, }; (suite, test) } 0 | 1 => { return quote! { compile_error!( "Expected two arguments. For example: #[gtest(TestSuite, TestName)]."); } .into(); } x => { return quote_spanned! { args[x.min(2)].span() => compile_error!( "Expected two arguments. For example: #[gtest(TestSuite, TestName)]."); } .into(); } }; // We put the test function and all the code we generate around it into a submodule which is // uniquely named for the super module based on the Gtest suite and test names. A result of this // is that if two tests have the same test suite + name, a compiler error would report the // conflict. let test_mod = format_ident!("__test_{}_{}", test_suite_name, test_name); // The run_test_fn identifier is marked #[no_mangle] to work around a codegen bug where the // function is seen as dead and the compiler omits it from the object files. Since it's // #[no_mangle], the identifier must be globally unique or we have an ODR violation. To produce // a unique identifier, we roll our own name mangling by combining the file name and path from // the source tree root with the Gtest suite and test names and the function itself. // // Note that an adversary could still produce a bug here by placing two equal Gtest suite and // names in a single .rs file but in separate inline submodules. // // TODO(danakj): Build a repro and file upstream bug to refer to. let mangled_function_name = |f: &syn::ItemFn| -> syn::Ident { let file_name = file!().replace(|c: char| !c.is_ascii_alphanumeric(), "_");
let test_fn = &input_fn.sig.ident; // Implements ToTokens to generate a reference to a static-lifetime, null-terminated, C-String // literal. It is represented as an array of type std::os::raw::c_char which can be either // signed or unsigned depending on the platform, and it can be passed directly to C++. This // differs from byte strings and CStr which work with `u8`. // // TODO(crbug.com/1298175): Would it make sense to write a c_str_literal!() macro that takes a // Rust string literal and produces a null-terminated array of `c_char`? Then you could write // `c_str_literal!(file!())` for example, or implement a `file_c_str!()` in this way. Explore // using https://crates.io/crates/cstr. // // TODO(danakj): Write unit tests for this, and consider pulling this out into its own crate, // if we don't replace it with c_str_literal!() or the "cstr" crate. struct CStringLiteral<'a>(&'a str); impl quote::ToTokens for CStringLiteral<'_> { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let mut c_chars = self.0.chars().map(|c| c as std::os::raw::c_char).collect::<Vec<_>>(); c_chars.push(0); // Verify there's no embedded nulls as that would be invalid if the literal were put in // a std::ffi::CString. assert_eq!(c_chars.iter().filter(|x| **x == 0).count(), 1); let comment = format!("\"{}\" as [c_char]", self.0); tokens.extend(quote! { { #[doc=#comment] &[#(#c_chars as std::os::raw::c_char),*] } }); } } // C-compatible string literals, that can be inserted into the quote! macro. let test_suite_name_c_bytes = CStringLiteral(&test_suite_name); let test_name_c_bytes = CStringLiteral(&test_name); let file_c_bytes = CStringLiteral(file!()); let output = quote! { mod #test_mod { use super::*; use std::error::Error; use std::fmt::Display; use std::result::Result; #[::rust_gtest_interop::small_ctor::ctor] unsafe fn register_test() { let r = ::rust_gtest_interop::__private::TestRegistration { func: #run_test_fn, test_suite_name: #test_suite_name_c_bytes, test_name: #test_name_c_bytes, file: #file_c_bytes, line: line!(), }; ::rust_gtest_interop::__private::register_test(r); } // The function is extern "C" so `register_test()` can pass this fn as a pointer to C++ // where it's registered with gtest. // // TODO(crbug.com/1296284): Removing #[no_mangle] makes rustc drop the symbol for the // test function in the generated rlib which produces linker errors. If we resolve the // linked bug and emit real object files from rustc for linking, then all the required // symbols are present and `#[no_mangle]` should go away along with the custom-mangling // of `run_test_fn`. We can not use `pub` to resolve this unfortunately. When `#[used]` // is fixed in https://github.com/rust-lang/rust/issues/47384, this may also be // resolved as well. #[no_mangle] extern "C" fn #run_test_fn() { let catch_result = std::panic::catch_unwind(|| #test_fn()); use ::rust_gtest_interop::TestResult; let err_message: Option<String> = match catch_result { Ok(fn_result) => TestResult::into_error_message(fn_result), Err(_) => Some("Test panicked".to_string()), }; if let Some(m) = err_message.as_ref() { ::rust_gtest_interop::__private::add_failure_at(file!(), line!(), &m); } } #input_fn } }; output.into() }
format_ident!("{}_{}_{}_{}", file_name, test_suite_name, test_name, f.sig.ident) }; let run_test_fn = format_ident!("run_test_{}", mangled_function_name(&input_fn)); // The identifier of the function which contains the body of the test.
random_line_split
gtest_attribute.rs
use proc_macro::TokenStream; use quote::{format_ident, quote, quote_spanned}; use syn::spanned::Spanned; /// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked /// into a C++ binary that invokes Gtest. /// /// The `gtest` macro takes two arguments, which are Rust identifiers. The first is the name of the /// test suite and the second is the name of the test, each of which are converted to a string and /// given to Gtest. The name of the test function itself does not matter, and need not be unique /// (it's placed into a unique module based on the Gtest suite + test names. /// /// The test function must have no arguments. The return value must be either `()` or /// `std::result::Result<(), E>`. If another return type is found, the test will fail when run. If /// the return type is a `Result`, then an `Err` is treated as a test failure. /// /// # Examples /// ``` /// #[gtest(MathTest, Addition)] /// fn my_test() { /// expect_eq!(1 + 1, 2); /// } /// ``` /// /// The above adds the function to the Gtest binary as `MathTest.Addtition`: /// ``` /// [ RUN ] MathTest.Addition /// [ OK ] MathTest.Addition (0 ms) /// ``` /// /// A test with a Result return type, and which uses the `?` operator. It will fail if the test /// returns an `Err`, and print the resulting error string: /// ``` /// #[gtest(ResultTest, CheckThingWithResult)] /// fn my_test() -> std::result::Result<(), String> { /// call_thing_with_result()?; /// } /// ``` #[proc_macro_attribute] pub fn gtest(arg_stream: TokenStream, input: TokenStream) -> TokenStream { enum
{ TestSuite, TestName, } // Returns a string representation of an identifier argument to the attribute. For example, for // #[gtest(Foo, Bar)], this function would return "Foo" for position 0 and "Bar" for position 1. // If the argument is not a Rust identifier or not present, it returns a compiler error as a // TokenStream to be emitted. fn get_arg_string( args: &syn::AttributeArgs, which: GtestAttributeArgument, ) -> Result<String, TokenStream> { let pos = match which { GtestAttributeArgument::TestSuite => 0, GtestAttributeArgument::TestName => 1, }; match &args[pos] { syn::NestedMeta::Meta(syn::Meta::Path(path)) if path.segments.len() == 1 => { Ok(path.segments[0].ident.to_string()) } _ => { let error_stream = match which { GtestAttributeArgument::TestSuite => { quote_spanned! { args[pos].span() => compile_error!( "Expected a test suite name, written as an identifier." ); } } GtestAttributeArgument::TestName => { quote_spanned! { args[pos].span() => compile_error!( "Expected a test name, written as an identifier." ); } } }; Err(error_stream.into()) } } } let args = syn::parse_macro_input!(arg_stream as syn::AttributeArgs); let input_fn = syn::parse_macro_input!(input as syn::ItemFn); if let Some(asyncness) = input_fn.sig.asyncness { // TODO(crbug.com/1288947): We can support async functions once we have block_on() support // which will run a RunLoop until the async test completes. The run_test_fn just needs to be // generated to `block_on(|| #test_fn)` instead of calling `#test_fn` synchronously. return quote_spanned! { asyncness.span => compile_error!("async functions are not supported."); } .into(); } let (test_suite_name, test_name) = match args.len() { 2 => { let suite = match get_arg_string(&args, GtestAttributeArgument::TestSuite) { Ok(ok) => ok, Err(error_stream) => return error_stream, }; let test = match get_arg_string(&args, GtestAttributeArgument::TestName) { Ok(ok) => ok, Err(error_stream) => return error_stream, }; (suite, test) } 0 | 1 => { return quote! { compile_error!( "Expected two arguments. For example: #[gtest(TestSuite, TestName)]."); } .into(); } x => { return quote_spanned! { args[x.min(2)].span() => compile_error!( "Expected two arguments. For example: #[gtest(TestSuite, TestName)]."); } .into(); } }; // We put the test function and all the code we generate around it into a submodule which is // uniquely named for the super module based on the Gtest suite and test names. A result of this // is that if two tests have the same test suite + name, a compiler error would report the // conflict. let test_mod = format_ident!("__test_{}_{}", test_suite_name, test_name); // The run_test_fn identifier is marked #[no_mangle] to work around a codegen bug where the // function is seen as dead and the compiler omits it from the object files. Since it's // #[no_mangle], the identifier must be globally unique or we have an ODR violation. To produce // a unique identifier, we roll our own name mangling by combining the file name and path from // the source tree root with the Gtest suite and test names and the function itself. // // Note that an adversary could still produce a bug here by placing two equal Gtest suite and // names in a single .rs file but in separate inline submodules. // // TODO(danakj): Build a repro and file upstream bug to refer to. let mangled_function_name = |f: &syn::ItemFn| -> syn::Ident { let file_name = file!().replace(|c: char| !c.is_ascii_alphanumeric(), "_"); format_ident!("{}_{}_{}_{}", file_name, test_suite_name, test_name, f.sig.ident) }; let run_test_fn = format_ident!("run_test_{}", mangled_function_name(&input_fn)); // The identifier of the function which contains the body of the test. let test_fn = &input_fn.sig.ident; // Implements ToTokens to generate a reference to a static-lifetime, null-terminated, C-String // literal. It is represented as an array of type std::os::raw::c_char which can be either // signed or unsigned depending on the platform, and it can be passed directly to C++. This // differs from byte strings and CStr which work with `u8`. // // TODO(crbug.com/1298175): Would it make sense to write a c_str_literal!() macro that takes a // Rust string literal and produces a null-terminated array of `c_char`? Then you could write // `c_str_literal!(file!())` for example, or implement a `file_c_str!()` in this way. Explore // using https://crates.io/crates/cstr. // // TODO(danakj): Write unit tests for this, and consider pulling this out into its own crate, // if we don't replace it with c_str_literal!() or the "cstr" crate. struct CStringLiteral<'a>(&'a str); impl quote::ToTokens for CStringLiteral<'_> { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let mut c_chars = self.0.chars().map(|c| c as std::os::raw::c_char).collect::<Vec<_>>(); c_chars.push(0); // Verify there's no embedded nulls as that would be invalid if the literal were put in // a std::ffi::CString. assert_eq!(c_chars.iter().filter(|x| **x == 0).count(), 1); let comment = format!("\"{}\" as [c_char]", self.0); tokens.extend(quote! { { #[doc=#comment] &[#(#c_chars as std::os::raw::c_char),*] } }); } } // C-compatible string literals, that can be inserted into the quote! macro. let test_suite_name_c_bytes = CStringLiteral(&test_suite_name); let test_name_c_bytes = CStringLiteral(&test_name); let file_c_bytes = CStringLiteral(file!()); let output = quote! { mod #test_mod { use super::*; use std::error::Error; use std::fmt::Display; use std::result::Result; #[::rust_gtest_interop::small_ctor::ctor] unsafe fn register_test() { let r = ::rust_gtest_interop::__private::TestRegistration { func: #run_test_fn, test_suite_name: #test_suite_name_c_bytes, test_name: #test_name_c_bytes, file: #file_c_bytes, line: line!(), }; ::rust_gtest_interop::__private::register_test(r); } // The function is extern "C" so `register_test()` can pass this fn as a pointer to C++ // where it's registered with gtest. // // TODO(crbug.com/1296284): Removing #[no_mangle] makes rustc drop the symbol for the // test function in the generated rlib which produces linker errors. If we resolve the // linked bug and emit real object files from rustc for linking, then all the required // symbols are present and `#[no_mangle]` should go away along with the custom-mangling // of `run_test_fn`. We can not use `pub` to resolve this unfortunately. When `#[used]` // is fixed in https://github.com/rust-lang/rust/issues/47384, this may also be // resolved as well. #[no_mangle] extern "C" fn #run_test_fn() { let catch_result = std::panic::catch_unwind(|| #test_fn()); use ::rust_gtest_interop::TestResult; let err_message: Option<String> = match catch_result { Ok(fn_result) => TestResult::into_error_message(fn_result), Err(_) => Some("Test panicked".to_string()), }; if let Some(m) = err_message.as_ref() { ::rust_gtest_interop::__private::add_failure_at(file!(), line!(), &m); } } #input_fn } }; output.into() }
GtestAttributeArgument
identifier_name
gtest_attribute.rs
use proc_macro::TokenStream; use quote::{format_ident, quote, quote_spanned}; use syn::spanned::Spanned; /// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked /// into a C++ binary that invokes Gtest. /// /// The `gtest` macro takes two arguments, which are Rust identifiers. The first is the name of the /// test suite and the second is the name of the test, each of which are converted to a string and /// given to Gtest. The name of the test function itself does not matter, and need not be unique /// (it's placed into a unique module based on the Gtest suite + test names. /// /// The test function must have no arguments. The return value must be either `()` or /// `std::result::Result<(), E>`. If another return type is found, the test will fail when run. If /// the return type is a `Result`, then an `Err` is treated as a test failure. /// /// # Examples /// ``` /// #[gtest(MathTest, Addition)] /// fn my_test() { /// expect_eq!(1 + 1, 2); /// } /// ``` /// /// The above adds the function to the Gtest binary as `MathTest.Addtition`: /// ``` /// [ RUN ] MathTest.Addition /// [ OK ] MathTest.Addition (0 ms) /// ``` /// /// A test with a Result return type, and which uses the `?` operator. It will fail if the test /// returns an `Err`, and print the resulting error string: /// ``` /// #[gtest(ResultTest, CheckThingWithResult)] /// fn my_test() -> std::result::Result<(), String> { /// call_thing_with_result()?; /// } /// ``` #[proc_macro_attribute] pub fn gtest(arg_stream: TokenStream, input: TokenStream) -> TokenStream { enum GtestAttributeArgument { TestSuite, TestName, } // Returns a string representation of an identifier argument to the attribute. For example, for // #[gtest(Foo, Bar)], this function would return "Foo" for position 0 and "Bar" for position 1. // If the argument is not a Rust identifier or not present, it returns a compiler error as a // TokenStream to be emitted. fn get_arg_string( args: &syn::AttributeArgs, which: GtestAttributeArgument, ) -> Result<String, TokenStream> { let pos = match which { GtestAttributeArgument::TestSuite => 0, GtestAttributeArgument::TestName => 1, }; match &args[pos] { syn::NestedMeta::Meta(syn::Meta::Path(path)) if path.segments.len() == 1 => { Ok(path.segments[0].ident.to_string()) } _ =>
} } let args = syn::parse_macro_input!(arg_stream as syn::AttributeArgs); let input_fn = syn::parse_macro_input!(input as syn::ItemFn); if let Some(asyncness) = input_fn.sig.asyncness { // TODO(crbug.com/1288947): We can support async functions once we have block_on() support // which will run a RunLoop until the async test completes. The run_test_fn just needs to be // generated to `block_on(|| #test_fn)` instead of calling `#test_fn` synchronously. return quote_spanned! { asyncness.span => compile_error!("async functions are not supported."); } .into(); } let (test_suite_name, test_name) = match args.len() { 2 => { let suite = match get_arg_string(&args, GtestAttributeArgument::TestSuite) { Ok(ok) => ok, Err(error_stream) => return error_stream, }; let test = match get_arg_string(&args, GtestAttributeArgument::TestName) { Ok(ok) => ok, Err(error_stream) => return error_stream, }; (suite, test) } 0 | 1 => { return quote! { compile_error!( "Expected two arguments. For example: #[gtest(TestSuite, TestName)]."); } .into(); } x => { return quote_spanned! { args[x.min(2)].span() => compile_error!( "Expected two arguments. For example: #[gtest(TestSuite, TestName)]."); } .into(); } }; // We put the test function and all the code we generate around it into a submodule which is // uniquely named for the super module based on the Gtest suite and test names. A result of this // is that if two tests have the same test suite + name, a compiler error would report the // conflict. let test_mod = format_ident!("__test_{}_{}", test_suite_name, test_name); // The run_test_fn identifier is marked #[no_mangle] to work around a codegen bug where the // function is seen as dead and the compiler omits it from the object files. Since it's // #[no_mangle], the identifier must be globally unique or we have an ODR violation. To produce // a unique identifier, we roll our own name mangling by combining the file name and path from // the source tree root with the Gtest suite and test names and the function itself. // // Note that an adversary could still produce a bug here by placing two equal Gtest suite and // names in a single .rs file but in separate inline submodules. // // TODO(danakj): Build a repro and file upstream bug to refer to. let mangled_function_name = |f: &syn::ItemFn| -> syn::Ident { let file_name = file!().replace(|c: char| !c.is_ascii_alphanumeric(), "_"); format_ident!("{}_{}_{}_{}", file_name, test_suite_name, test_name, f.sig.ident) }; let run_test_fn = format_ident!("run_test_{}", mangled_function_name(&input_fn)); // The identifier of the function which contains the body of the test. let test_fn = &input_fn.sig.ident; // Implements ToTokens to generate a reference to a static-lifetime, null-terminated, C-String // literal. It is represented as an array of type std::os::raw::c_char which can be either // signed or unsigned depending on the platform, and it can be passed directly to C++. This // differs from byte strings and CStr which work with `u8`. // // TODO(crbug.com/1298175): Would it make sense to write a c_str_literal!() macro that takes a // Rust string literal and produces a null-terminated array of `c_char`? Then you could write // `c_str_literal!(file!())` for example, or implement a `file_c_str!()` in this way. Explore // using https://crates.io/crates/cstr. // // TODO(danakj): Write unit tests for this, and consider pulling this out into its own crate, // if we don't replace it with c_str_literal!() or the "cstr" crate. struct CStringLiteral<'a>(&'a str); impl quote::ToTokens for CStringLiteral<'_> { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let mut c_chars = self.0.chars().map(|c| c as std::os::raw::c_char).collect::<Vec<_>>(); c_chars.push(0); // Verify there's no embedded nulls as that would be invalid if the literal were put in // a std::ffi::CString. assert_eq!(c_chars.iter().filter(|x| **x == 0).count(), 1); let comment = format!("\"{}\" as [c_char]", self.0); tokens.extend(quote! { { #[doc=#comment] &[#(#c_chars as std::os::raw::c_char),*] } }); } } // C-compatible string literals, that can be inserted into the quote! macro. let test_suite_name_c_bytes = CStringLiteral(&test_suite_name); let test_name_c_bytes = CStringLiteral(&test_name); let file_c_bytes = CStringLiteral(file!()); let output = quote! { mod #test_mod { use super::*; use std::error::Error; use std::fmt::Display; use std::result::Result; #[::rust_gtest_interop::small_ctor::ctor] unsafe fn register_test() { let r = ::rust_gtest_interop::__private::TestRegistration { func: #run_test_fn, test_suite_name: #test_suite_name_c_bytes, test_name: #test_name_c_bytes, file: #file_c_bytes, line: line!(), }; ::rust_gtest_interop::__private::register_test(r); } // The function is extern "C" so `register_test()` can pass this fn as a pointer to C++ // where it's registered with gtest. // // TODO(crbug.com/1296284): Removing #[no_mangle] makes rustc drop the symbol for the // test function in the generated rlib which produces linker errors. If we resolve the // linked bug and emit real object files from rustc for linking, then all the required // symbols are present and `#[no_mangle]` should go away along with the custom-mangling // of `run_test_fn`. We can not use `pub` to resolve this unfortunately. When `#[used]` // is fixed in https://github.com/rust-lang/rust/issues/47384, this may also be // resolved as well. #[no_mangle] extern "C" fn #run_test_fn() { let catch_result = std::panic::catch_unwind(|| #test_fn()); use ::rust_gtest_interop::TestResult; let err_message: Option<String> = match catch_result { Ok(fn_result) => TestResult::into_error_message(fn_result), Err(_) => Some("Test panicked".to_string()), }; if let Some(m) = err_message.as_ref() { ::rust_gtest_interop::__private::add_failure_at(file!(), line!(), &m); } } #input_fn } }; output.into() }
{ let error_stream = match which { GtestAttributeArgument::TestSuite => { quote_spanned! { args[pos].span() => compile_error!( "Expected a test suite name, written as an identifier." ); } } GtestAttributeArgument::TestName => { quote_spanned! { args[pos].span() => compile_error!( "Expected a test name, written as an identifier." ); } } }; Err(error_stream.into()) }
conditional_block
testutils.py
from __future__ import absolute_import, print_function, division from pony.py23compat import basestring from functools import wraps from contextlib import contextmanager from pony.orm.core import Database from pony.utils import import_module def raises_exception(exc_class, msg=None): def decorator(func): def wrapper(self, *args, **kwargs): try: func(self, *args, **kwargs) self.fail("expected exception %s wasn't raised" % exc_class.__name__) except exc_class as e: if not e.args: self.assertEqual(msg, None) elif msg is not None: self.assertEqual(e.args[0], msg, "incorrect exception message. expected '%s', got '%s'" % (msg, e.args[0])) wrapper.__name__ = func.__name__ return wrapper return decorator @contextmanager def raises_if(test, cond, exc_class, exc_msg=None): try: yield except exc_class as e: test.assertTrue(cond) if exc_msg is None: pass elif exc_msg.startswith('...') and exc_msg != '...': if exc_msg.endswith('...'): test.assertIn(exc_msg[3:-3], str(e)) else: test.assertTrue(str(e).endswith(exc_msg[3:])) elif exc_msg.endswith('...'): test.assertTrue(str(e).startswith(exc_msg[:-3])) else: test.assertEqual(str(e), exc_msg) else: test.assertFalse(cond) def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result class TestConnection(object): def __init__(con, database):
def commit(con): pass def rollback(con): pass def cursor(con): return test_cursor class TestCursor(object): def __init__(cursor): cursor.description = [] cursor.rowcount = 0 def execute(cursor, sql, args=None): pass def fetchone(cursor): return None def fetchmany(cursor, size): return [] def fetchall(cursor): return [] test_cursor = TestCursor() class TestPool(object): def __init__(pool, database): pool.database = database def connect(pool): return TestConnection(pool.database) def release(pool, con): pass def drop(pool, con): pass def disconnect(pool): pass class TestDatabase(Database): real_provider_name = None raw_server_version = None sql = None def bind(self, provider_name, *args, **kwargs): if self.real_provider_name is not None: provider_name = self.real_provider_name self.provider_name = provider_name provider_module = import_module('pony.orm.dbproviders.' + provider_name) provider_cls = provider_module.provider_cls raw_server_version = self.raw_server_version if raw_server_version is None: if provider_name == 'sqlite': raw_server_version = '3.7.17' elif provider_name in ('postgres', 'pygresql'): raw_server_version = '9.2' elif provider_name == 'oracle': raw_server_version = '11.2.0.2.0' elif provider_name == 'mysql': raw_server_version = '5.6.11' else: assert False, provider_name # pragma: no cover t = [ int(component) for component in raw_server_version.split('.') ] if len(t) == 2: t.append(0) server_version = tuple(t) if provider_name in ('postgres', 'pygresql'): server_version = int('%d%02d%02d' % server_version) class TestProvider(provider_cls): def inspect_connection(provider, connection): pass TestProvider.server_version = server_version kwargs['pony_check_connection'] = False kwargs['pony_pool_mockup'] = TestPool(self) Database.bind(self, TestProvider, *args, **kwargs) def _execute(database, sql, globals, locals, frame_depth): assert False # pragma: no cover def _exec_sql(database, sql, arguments=None, returning_id=False): assert type(arguments) is not list and not returning_id database.sql = sql database.arguments = arguments return test_cursor def generate_mapping(database, filename=None, check_tables=True, create_tables=False): return Database.generate_mapping(database, filename, create_tables=False)
con.database = database if database and database.provider_name == 'postgres': con.autocommit = True
identifier_body
testutils.py
from __future__ import absolute_import, print_function, division from pony.py23compat import basestring from functools import wraps from contextlib import contextmanager from pony.orm.core import Database from pony.utils import import_module def raises_exception(exc_class, msg=None): def decorator(func): def wrapper(self, *args, **kwargs): try: func(self, *args, **kwargs) self.fail("expected exception %s wasn't raised" % exc_class.__name__) except exc_class as e: if not e.args: self.assertEqual(msg, None) elif msg is not None: self.assertEqual(e.args[0], msg, "incorrect exception message. expected '%s', got '%s'" % (msg, e.args[0])) wrapper.__name__ = func.__name__ return wrapper return decorator @contextmanager def raises_if(test, cond, exc_class, exc_msg=None): try: yield except exc_class as e: test.assertTrue(cond) if exc_msg is None: pass elif exc_msg.startswith('...') and exc_msg != '...': if exc_msg.endswith('...'): test.assertIn(exc_msg[3:-3], str(e)) else: test.assertTrue(str(e).endswith(exc_msg[3:])) elif exc_msg.endswith('...'): test.assertTrue(str(e).startswith(exc_msg[:-3])) else: test.assertEqual(str(e), exc_msg) else: test.assertFalse(cond) def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result class
(object): def __init__(con, database): con.database = database if database and database.provider_name == 'postgres': con.autocommit = True def commit(con): pass def rollback(con): pass def cursor(con): return test_cursor class TestCursor(object): def __init__(cursor): cursor.description = [] cursor.rowcount = 0 def execute(cursor, sql, args=None): pass def fetchone(cursor): return None def fetchmany(cursor, size): return [] def fetchall(cursor): return [] test_cursor = TestCursor() class TestPool(object): def __init__(pool, database): pool.database = database def connect(pool): return TestConnection(pool.database) def release(pool, con): pass def drop(pool, con): pass def disconnect(pool): pass class TestDatabase(Database): real_provider_name = None raw_server_version = None sql = None def bind(self, provider_name, *args, **kwargs): if self.real_provider_name is not None: provider_name = self.real_provider_name self.provider_name = provider_name provider_module = import_module('pony.orm.dbproviders.' + provider_name) provider_cls = provider_module.provider_cls raw_server_version = self.raw_server_version if raw_server_version is None: if provider_name == 'sqlite': raw_server_version = '3.7.17' elif provider_name in ('postgres', 'pygresql'): raw_server_version = '9.2' elif provider_name == 'oracle': raw_server_version = '11.2.0.2.0' elif provider_name == 'mysql': raw_server_version = '5.6.11' else: assert False, provider_name # pragma: no cover t = [ int(component) for component in raw_server_version.split('.') ] if len(t) == 2: t.append(0) server_version = tuple(t) if provider_name in ('postgres', 'pygresql'): server_version = int('%d%02d%02d' % server_version) class TestProvider(provider_cls): def inspect_connection(provider, connection): pass TestProvider.server_version = server_version kwargs['pony_check_connection'] = False kwargs['pony_pool_mockup'] = TestPool(self) Database.bind(self, TestProvider, *args, **kwargs) def _execute(database, sql, globals, locals, frame_depth): assert False # pragma: no cover def _exec_sql(database, sql, arguments=None, returning_id=False): assert type(arguments) is not list and not returning_id database.sql = sql database.arguments = arguments return test_cursor def generate_mapping(database, filename=None, check_tables=True, create_tables=False): return Database.generate_mapping(database, filename, create_tables=False)
TestConnection
identifier_name
testutils.py
from __future__ import absolute_import, print_function, division from pony.py23compat import basestring from functools import wraps from contextlib import contextmanager from pony.orm.core import Database from pony.utils import import_module def raises_exception(exc_class, msg=None): def decorator(func): def wrapper(self, *args, **kwargs): try: func(self, *args, **kwargs) self.fail("expected exception %s wasn't raised" % exc_class.__name__) except exc_class as e: if not e.args: self.assertEqual(msg, None) elif msg is not None: self.assertEqual(e.args[0], msg, "incorrect exception message. expected '%s', got '%s'" % (msg, e.args[0])) wrapper.__name__ = func.__name__ return wrapper return decorator @contextmanager def raises_if(test, cond, exc_class, exc_msg=None): try: yield except exc_class as e: test.assertTrue(cond) if exc_msg is None: pass elif exc_msg.startswith('...') and exc_msg != '...': if exc_msg.endswith('...'):
else: test.assertTrue(str(e).endswith(exc_msg[3:])) elif exc_msg.endswith('...'): test.assertTrue(str(e).startswith(exc_msg[:-3])) else: test.assertEqual(str(e), exc_msg) else: test.assertFalse(cond) def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result class TestConnection(object): def __init__(con, database): con.database = database if database and database.provider_name == 'postgres': con.autocommit = True def commit(con): pass def rollback(con): pass def cursor(con): return test_cursor class TestCursor(object): def __init__(cursor): cursor.description = [] cursor.rowcount = 0 def execute(cursor, sql, args=None): pass def fetchone(cursor): return None def fetchmany(cursor, size): return [] def fetchall(cursor): return [] test_cursor = TestCursor() class TestPool(object): def __init__(pool, database): pool.database = database def connect(pool): return TestConnection(pool.database) def release(pool, con): pass def drop(pool, con): pass def disconnect(pool): pass class TestDatabase(Database): real_provider_name = None raw_server_version = None sql = None def bind(self, provider_name, *args, **kwargs): if self.real_provider_name is not None: provider_name = self.real_provider_name self.provider_name = provider_name provider_module = import_module('pony.orm.dbproviders.' + provider_name) provider_cls = provider_module.provider_cls raw_server_version = self.raw_server_version if raw_server_version is None: if provider_name == 'sqlite': raw_server_version = '3.7.17' elif provider_name in ('postgres', 'pygresql'): raw_server_version = '9.2' elif provider_name == 'oracle': raw_server_version = '11.2.0.2.0' elif provider_name == 'mysql': raw_server_version = '5.6.11' else: assert False, provider_name # pragma: no cover t = [ int(component) for component in raw_server_version.split('.') ] if len(t) == 2: t.append(0) server_version = tuple(t) if provider_name in ('postgres', 'pygresql'): server_version = int('%d%02d%02d' % server_version) class TestProvider(provider_cls): def inspect_connection(provider, connection): pass TestProvider.server_version = server_version kwargs['pony_check_connection'] = False kwargs['pony_pool_mockup'] = TestPool(self) Database.bind(self, TestProvider, *args, **kwargs) def _execute(database, sql, globals, locals, frame_depth): assert False # pragma: no cover def _exec_sql(database, sql, arguments=None, returning_id=False): assert type(arguments) is not list and not returning_id database.sql = sql database.arguments = arguments return test_cursor def generate_mapping(database, filename=None, check_tables=True, create_tables=False): return Database.generate_mapping(database, filename, create_tables=False)
test.assertIn(exc_msg[3:-3], str(e))
conditional_block
testutils.py
from __future__ import absolute_import, print_function, division from pony.py23compat import basestring from functools import wraps from contextlib import contextmanager from pony.orm.core import Database from pony.utils import import_module def raises_exception(exc_class, msg=None): def decorator(func): def wrapper(self, *args, **kwargs): try: func(self, *args, **kwargs) self.fail("expected exception %s wasn't raised" % exc_class.__name__) except exc_class as e: if not e.args: self.assertEqual(msg, None) elif msg is not None: self.assertEqual(e.args[0], msg, "incorrect exception message. expected '%s', got '%s'" % (msg, e.args[0])) wrapper.__name__ = func.__name__ return wrapper return decorator @contextmanager def raises_if(test, cond, exc_class, exc_msg=None): try: yield except exc_class as e: test.assertTrue(cond) if exc_msg is None: pass elif exc_msg.startswith('...') and exc_msg != '...': if exc_msg.endswith('...'): test.assertIn(exc_msg[3:-3], str(e)) else: test.assertTrue(str(e).endswith(exc_msg[3:])) elif exc_msg.endswith('...'): test.assertTrue(str(e).startswith(exc_msg[:-3])) else: test.assertEqual(str(e), exc_msg) else: test.assertFalse(cond) def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result class TestConnection(object): def __init__(con, database): con.database = database if database and database.provider_name == 'postgres': con.autocommit = True def commit(con): pass def rollback(con): pass def cursor(con): return test_cursor class TestCursor(object): def __init__(cursor): cursor.description = [] cursor.rowcount = 0 def execute(cursor, sql, args=None): pass def fetchone(cursor): return None
def fetchmany(cursor, size): return [] def fetchall(cursor): return [] test_cursor = TestCursor() class TestPool(object): def __init__(pool, database): pool.database = database def connect(pool): return TestConnection(pool.database) def release(pool, con): pass def drop(pool, con): pass def disconnect(pool): pass class TestDatabase(Database): real_provider_name = None raw_server_version = None sql = None def bind(self, provider_name, *args, **kwargs): if self.real_provider_name is not None: provider_name = self.real_provider_name self.provider_name = provider_name provider_module = import_module('pony.orm.dbproviders.' + provider_name) provider_cls = provider_module.provider_cls raw_server_version = self.raw_server_version if raw_server_version is None: if provider_name == 'sqlite': raw_server_version = '3.7.17' elif provider_name in ('postgres', 'pygresql'): raw_server_version = '9.2' elif provider_name == 'oracle': raw_server_version = '11.2.0.2.0' elif provider_name == 'mysql': raw_server_version = '5.6.11' else: assert False, provider_name # pragma: no cover t = [ int(component) for component in raw_server_version.split('.') ] if len(t) == 2: t.append(0) server_version = tuple(t) if provider_name in ('postgres', 'pygresql'): server_version = int('%d%02d%02d' % server_version) class TestProvider(provider_cls): def inspect_connection(provider, connection): pass TestProvider.server_version = server_version kwargs['pony_check_connection'] = False kwargs['pony_pool_mockup'] = TestPool(self) Database.bind(self, TestProvider, *args, **kwargs) def _execute(database, sql, globals, locals, frame_depth): assert False # pragma: no cover def _exec_sql(database, sql, arguments=None, returning_id=False): assert type(arguments) is not list and not returning_id database.sql = sql database.arguments = arguments return test_cursor def generate_mapping(database, filename=None, check_tables=True, create_tables=False): return Database.generate_mapping(database, filename, create_tables=False)
random_line_split
__init__.py
# # Copyright (C) 2010-2017 Samuel Abels
# Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import absolute_import from .parser import Parser import inspect __all__ = [name for name, obj in list(locals().items()) if not (name.startswith('_') or inspect.ismodule(obj))]
# The MIT License (MIT) #
random_line_split
directory_watcher.py
"""Contains the implementation for the DirectoryWatcher class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.python.platform import gfile from tensorflow.python.platform import logging class DirectoryWatcher(object):
"""A DirectoryWatcher wraps a loader to load from a directory. A loader reads a file on disk and produces some kind of values as an iterator. A DirectoryWatcher takes a directory with one file at a time being written to and a factory for loaders and watches all the files at once. This class is *only* valid under the assumption that files are never removed and the only file ever changed is whichever one is lexicographically last. """ def __init__(self, directory, loader_factory, path_filter=lambda x: True): """Constructs a new DirectoryWatcher. Args: directory: The directory to watch. The directory doesn't have to exist. loader_factory: A factory for creating loaders. The factory should take a file path and return an object that has a Load method returning an iterator that will yield all events that have not been yielded yet. path_filter: Only files whose full path matches this predicate will be loaded. If not specified, all files are loaded. Raises: ValueError: If directory or loader_factory is None. """ if directory is None: raise ValueError('A directory is required') if loader_factory is None: raise ValueError('A loader factory is required') self._directory = directory self._loader_factory = loader_factory self._loader = None self._path = None self._path_filter = path_filter def Load(self): """Loads new values from disk. The watcher will load from one file at a time; as soon as that file stops yielding events, it will move on to the next file. We assume that old files are never modified after a newer file has been written. As a result, Load() can be called multiple times in a row without losing events that have not been yielded yet. In other words, we guarantee that every event will be yielded exactly once. Yields: All values that were written to disk that have not been yielded yet. """ # If the loader exists, check it for a value. if not self._loader: self._InitializeLoader() while True: # Yield all the new events in the file we're currently loading from. for event in self._loader.Load(): yield event next_path = self._GetNextPath() if not next_path: logging.info('No more files in %s', self._directory) # Current file is empty and there are no new files, so we're done. return # There's a new file, so check to make sure there weren't any events # written between when we finished reading the current file and when we # checked for the new one. The sequence of events might look something # like this: # # 1. Event #1 written to file #1. # 2. We check for events and yield event #1 from file #1 # 3. We check for events and see that there are no more events in file #1. # 4. Event #2 is written to file #1. # 5. Event #3 is written to file #2. # 6. We check for a new file and see that file #2 exists. # # Without this loop, we would miss event #2. We're also guaranteed by the # loader contract that no more events will be written to file #1 after # events start being written to file #2, so we don't have to worry about # that. for event in self._loader.Load(): yield event logging.info('Directory watcher for %s advancing to file %s', self._directory, next_path) # Advance to the next file and start over. self._SetPath(next_path) def _InitializeLoader(self): path = self._GetNextPath() if path: self._SetPath(path) else: raise StopIteration def _SetPath(self, path): self._path = path self._loader = self._loader_factory(path) def _GetNextPath(self): """Returns the path of the next file to use or None if no file exists.""" sorted_paths = [os.path.join(self._directory, path) for path in sorted(gfile.ListDirectory(self._directory))] # We filter here so the filter gets the full directory name. filtered_paths = (path for path in sorted_paths if self._path_filter(path) and path > self._path) return next(filtered_paths, None)
identifier_body
directory_watcher.py
"""Contains the implementation for the DirectoryWatcher class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.python.platform import gfile from tensorflow.python.platform import logging class DirectoryWatcher(object): """A DirectoryWatcher wraps a loader to load from a directory. A loader reads a file on disk and produces some kind of values as an iterator. A DirectoryWatcher takes a directory with one file at a time being written to and a factory for loaders and watches all the files at once. This class is *only* valid under the assumption that files are never removed and the only file ever changed is whichever one is lexicographically last. """ def __init__(self, directory, loader_factory, path_filter=lambda x: True): """Constructs a new DirectoryWatcher. Args: directory: The directory to watch. The directory doesn't have to exist. loader_factory: A factory for creating loaders. The factory should take a file path and return an object that has a Load method returning an iterator that will yield all events that have not been yielded yet. path_filter: Only files whose full path matches this predicate will be loaded. If not specified, all files are loaded. Raises: ValueError: If directory or loader_factory is None. """ if directory is None: raise ValueError('A directory is required') if loader_factory is None:
self._directory = directory self._loader_factory = loader_factory self._loader = None self._path = None self._path_filter = path_filter def Load(self): """Loads new values from disk. The watcher will load from one file at a time; as soon as that file stops yielding events, it will move on to the next file. We assume that old files are never modified after a newer file has been written. As a result, Load() can be called multiple times in a row without losing events that have not been yielded yet. In other words, we guarantee that every event will be yielded exactly once. Yields: All values that were written to disk that have not been yielded yet. """ # If the loader exists, check it for a value. if not self._loader: self._InitializeLoader() while True: # Yield all the new events in the file we're currently loading from. for event in self._loader.Load(): yield event next_path = self._GetNextPath() if not next_path: logging.info('No more files in %s', self._directory) # Current file is empty and there are no new files, so we're done. return # There's a new file, so check to make sure there weren't any events # written between when we finished reading the current file and when we # checked for the new one. The sequence of events might look something # like this: # # 1. Event #1 written to file #1. # 2. We check for events and yield event #1 from file #1 # 3. We check for events and see that there are no more events in file #1. # 4. Event #2 is written to file #1. # 5. Event #3 is written to file #2. # 6. We check for a new file and see that file #2 exists. # # Without this loop, we would miss event #2. We're also guaranteed by the # loader contract that no more events will be written to file #1 after # events start being written to file #2, so we don't have to worry about # that. for event in self._loader.Load(): yield event logging.info('Directory watcher for %s advancing to file %s', self._directory, next_path) # Advance to the next file and start over. self._SetPath(next_path) def _InitializeLoader(self): path = self._GetNextPath() if path: self._SetPath(path) else: raise StopIteration def _SetPath(self, path): self._path = path self._loader = self._loader_factory(path) def _GetNextPath(self): """Returns the path of the next file to use or None if no file exists.""" sorted_paths = [os.path.join(self._directory, path) for path in sorted(gfile.ListDirectory(self._directory))] # We filter here so the filter gets the full directory name. filtered_paths = (path for path in sorted_paths if self._path_filter(path) and path > self._path) return next(filtered_paths, None)
raise ValueError('A loader factory is required')
conditional_block
directory_watcher.py
"""Contains the implementation for the DirectoryWatcher class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.python.platform import gfile from tensorflow.python.platform import logging class DirectoryWatcher(object): """A DirectoryWatcher wraps a loader to load from a directory. A loader reads a file on disk and produces some kind of values as an iterator. A DirectoryWatcher takes a directory with one file at a time being written to and a factory for loaders and watches all the files at once. This class is *only* valid under the assumption that files are never removed and the only file ever changed is whichever one is lexicographically last. """ def __init__(self, directory, loader_factory, path_filter=lambda x: True): """Constructs a new DirectoryWatcher. Args: directory: The directory to watch. The directory doesn't have to exist. loader_factory: A factory for creating loaders. The factory should take a file path and return an object that has a Load method returning an iterator that will yield all events that have not been yielded yet. path_filter: Only files whose full path matches this predicate will be loaded. If not specified, all files are loaded. Raises: ValueError: If directory or loader_factory is None. """ if directory is None: raise ValueError('A directory is required') if loader_factory is None: raise ValueError('A loader factory is required') self._directory = directory self._loader_factory = loader_factory self._loader = None self._path = None self._path_filter = path_filter def
(self): """Loads new values from disk. The watcher will load from one file at a time; as soon as that file stops yielding events, it will move on to the next file. We assume that old files are never modified after a newer file has been written. As a result, Load() can be called multiple times in a row without losing events that have not been yielded yet. In other words, we guarantee that every event will be yielded exactly once. Yields: All values that were written to disk that have not been yielded yet. """ # If the loader exists, check it for a value. if not self._loader: self._InitializeLoader() while True: # Yield all the new events in the file we're currently loading from. for event in self._loader.Load(): yield event next_path = self._GetNextPath() if not next_path: logging.info('No more files in %s', self._directory) # Current file is empty and there are no new files, so we're done. return # There's a new file, so check to make sure there weren't any events # written between when we finished reading the current file and when we # checked for the new one. The sequence of events might look something # like this: # # 1. Event #1 written to file #1. # 2. We check for events and yield event #1 from file #1 # 3. We check for events and see that there are no more events in file #1. # 4. Event #2 is written to file #1. # 5. Event #3 is written to file #2. # 6. We check for a new file and see that file #2 exists. # # Without this loop, we would miss event #2. We're also guaranteed by the # loader contract that no more events will be written to file #1 after # events start being written to file #2, so we don't have to worry about # that. for event in self._loader.Load(): yield event logging.info('Directory watcher for %s advancing to file %s', self._directory, next_path) # Advance to the next file and start over. self._SetPath(next_path) def _InitializeLoader(self): path = self._GetNextPath() if path: self._SetPath(path) else: raise StopIteration def _SetPath(self, path): self._path = path self._loader = self._loader_factory(path) def _GetNextPath(self): """Returns the path of the next file to use or None if no file exists.""" sorted_paths = [os.path.join(self._directory, path) for path in sorted(gfile.ListDirectory(self._directory))] # We filter here so the filter gets the full directory name. filtered_paths = (path for path in sorted_paths if self._path_filter(path) and path > self._path) return next(filtered_paths, None)
Load
identifier_name
directory_watcher.py
"""Contains the implementation for the DirectoryWatcher class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.python.platform import gfile from tensorflow.python.platform import logging class DirectoryWatcher(object): """A DirectoryWatcher wraps a loader to load from a directory. A loader reads a file on disk and produces some kind of values as an iterator. A DirectoryWatcher takes a directory with one file at a time being written to and a factory for loaders and watches all the files at once. This class is *only* valid under the assumption that files are never removed and the only file ever changed is whichever one is lexicographically last. """ def __init__(self, directory, loader_factory, path_filter=lambda x: True): """Constructs a new DirectoryWatcher. Args: directory: The directory to watch. The directory doesn't have to exist. loader_factory: A factory for creating loaders. The factory should take a file path and return an object that has a Load method returning an iterator that will yield all events that have not been yielded yet. path_filter: Only files whose full path matches this predicate will be loaded. If not specified, all files are loaded. Raises: ValueError: If directory or loader_factory is None. """ if directory is None: raise ValueError('A directory is required') if loader_factory is None: raise ValueError('A loader factory is required') self._directory = directory self._loader_factory = loader_factory self._loader = None self._path = None self._path_filter = path_filter def Load(self): """Loads new values from disk. The watcher will load from one file at a time; as soon as that file stops yielding events, it will move on to the next file. We assume that old files are never modified after a newer file has been written. As a result, Load() can be called multiple times in a row without losing events that have not been yielded yet. In other words, we guarantee that every event will be yielded exactly once. Yields: All values that were written to disk that have not been yielded yet. """ # If the loader exists, check it for a value. if not self._loader: self._InitializeLoader() while True: # Yield all the new events in the file we're currently loading from. for event in self._loader.Load(): yield event next_path = self._GetNextPath() if not next_path: logging.info('No more files in %s', self._directory) # Current file is empty and there are no new files, so we're done. return
# written between when we finished reading the current file and when we # checked for the new one. The sequence of events might look something # like this: # # 1. Event #1 written to file #1. # 2. We check for events and yield event #1 from file #1 # 3. We check for events and see that there are no more events in file #1. # 4. Event #2 is written to file #1. # 5. Event #3 is written to file #2. # 6. We check for a new file and see that file #2 exists. # # Without this loop, we would miss event #2. We're also guaranteed by the # loader contract that no more events will be written to file #1 after # events start being written to file #2, so we don't have to worry about # that. for event in self._loader.Load(): yield event logging.info('Directory watcher for %s advancing to file %s', self._directory, next_path) # Advance to the next file and start over. self._SetPath(next_path) def _InitializeLoader(self): path = self._GetNextPath() if path: self._SetPath(path) else: raise StopIteration def _SetPath(self, path): self._path = path self._loader = self._loader_factory(path) def _GetNextPath(self): """Returns the path of the next file to use or None if no file exists.""" sorted_paths = [os.path.join(self._directory, path) for path in sorted(gfile.ListDirectory(self._directory))] # We filter here so the filter gets the full directory name. filtered_paths = (path for path in sorted_paths if self._path_filter(path) and path > self._path) return next(filtered_paths, None)
# There's a new file, so check to make sure there weren't any events
random_line_split
proto.js
var fs = require('fs'); var protobuf = require('protobufjs'); var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8'); var builder = protobuf.loadProto(protoStr); var ns = 'pb.remote'; function build(type) { return builder.build(ns+'.'+type); } var proto = { MsgType: build('MsgType'), EngineState: build('EngineState'),
Message: build('Message') }; var Message = proto.Message; function getConstName(value, obj) { for (var name in obj) { if (obj[name] === value) { return name; } } return ''; } proto.getMsgTypeName = function (typeIndex) { return getConstName(typeIndex, proto.MsgType); }; proto.getEngineStateName = function (stateIndex) { return getConstName(stateIndex, proto.EngineState); }; proto.getRepeatModeName = function (repeatModeIndex) { return getConstName(repeatModeIndex, proto.RepeatMode); }; proto.getShuffleModeName = function (shuffleModeIndex) { return getConstName(shuffleModeIndex, proto.ShuffleMode); }; proto.getReasonDisconnectName = function (reasonIndex) { return getConstName(reasonIndex, proto.ReasonDisconnect); }; proto.getDownloadItemName = function (downloadItemIndex) { return getConstName(downloadItemIndex, proto.DownloadItem); }; module.exports = proto;
RepeatMode: build('RepeatMode'), ShuffleMode: build('ShuffleMode'), ReasonDisconnect: build('ReasonDisconnect'), DownloadItem: build('DownloadItem'),
random_line_split
proto.js
var fs = require('fs'); var protobuf = require('protobufjs'); var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8'); var builder = protobuf.loadProto(protoStr); var ns = 'pb.remote'; function build(type) { return builder.build(ns+'.'+type); } var proto = { MsgType: build('MsgType'), EngineState: build('EngineState'), RepeatMode: build('RepeatMode'), ShuffleMode: build('ShuffleMode'), ReasonDisconnect: build('ReasonDisconnect'), DownloadItem: build('DownloadItem'), Message: build('Message') }; var Message = proto.Message; function
(value, obj) { for (var name in obj) { if (obj[name] === value) { return name; } } return ''; } proto.getMsgTypeName = function (typeIndex) { return getConstName(typeIndex, proto.MsgType); }; proto.getEngineStateName = function (stateIndex) { return getConstName(stateIndex, proto.EngineState); }; proto.getRepeatModeName = function (repeatModeIndex) { return getConstName(repeatModeIndex, proto.RepeatMode); }; proto.getShuffleModeName = function (shuffleModeIndex) { return getConstName(shuffleModeIndex, proto.ShuffleMode); }; proto.getReasonDisconnectName = function (reasonIndex) { return getConstName(reasonIndex, proto.ReasonDisconnect); }; proto.getDownloadItemName = function (downloadItemIndex) { return getConstName(downloadItemIndex, proto.DownloadItem); }; module.exports = proto;
getConstName
identifier_name
proto.js
var fs = require('fs'); var protobuf = require('protobufjs'); var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8'); var builder = protobuf.loadProto(protoStr); var ns = 'pb.remote'; function build(type) { return builder.build(ns+'.'+type); } var proto = { MsgType: build('MsgType'), EngineState: build('EngineState'), RepeatMode: build('RepeatMode'), ShuffleMode: build('ShuffleMode'), ReasonDisconnect: build('ReasonDisconnect'), DownloadItem: build('DownloadItem'), Message: build('Message') }; var Message = proto.Message; function getConstName(value, obj) { for (var name in obj) { if (obj[name] === value)
} return ''; } proto.getMsgTypeName = function (typeIndex) { return getConstName(typeIndex, proto.MsgType); }; proto.getEngineStateName = function (stateIndex) { return getConstName(stateIndex, proto.EngineState); }; proto.getRepeatModeName = function (repeatModeIndex) { return getConstName(repeatModeIndex, proto.RepeatMode); }; proto.getShuffleModeName = function (shuffleModeIndex) { return getConstName(shuffleModeIndex, proto.ShuffleMode); }; proto.getReasonDisconnectName = function (reasonIndex) { return getConstName(reasonIndex, proto.ReasonDisconnect); }; proto.getDownloadItemName = function (downloadItemIndex) { return getConstName(downloadItemIndex, proto.DownloadItem); }; module.exports = proto;
{ return name; }
conditional_block
proto.js
var fs = require('fs'); var protobuf = require('protobufjs'); var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8'); var builder = protobuf.loadProto(protoStr); var ns = 'pb.remote'; function build(type) { return builder.build(ns+'.'+type); } var proto = { MsgType: build('MsgType'), EngineState: build('EngineState'), RepeatMode: build('RepeatMode'), ShuffleMode: build('ShuffleMode'), ReasonDisconnect: build('ReasonDisconnect'), DownloadItem: build('DownloadItem'), Message: build('Message') }; var Message = proto.Message; function getConstName(value, obj)
proto.getMsgTypeName = function (typeIndex) { return getConstName(typeIndex, proto.MsgType); }; proto.getEngineStateName = function (stateIndex) { return getConstName(stateIndex, proto.EngineState); }; proto.getRepeatModeName = function (repeatModeIndex) { return getConstName(repeatModeIndex, proto.RepeatMode); }; proto.getShuffleModeName = function (shuffleModeIndex) { return getConstName(shuffleModeIndex, proto.ShuffleMode); }; proto.getReasonDisconnectName = function (reasonIndex) { return getConstName(reasonIndex, proto.ReasonDisconnect); }; proto.getDownloadItemName = function (downloadItemIndex) { return getConstName(downloadItemIndex, proto.DownloadItem); }; module.exports = proto;
{ for (var name in obj) { if (obj[name] === value) { return name; } } return ''; }
identifier_body
SsidChartSharp.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M21 5.47 12 12 7.62 7.62 3 11V8.52L7.83 5l4.38 4.38L21 3v2.47zM21 15h-4.7l-4.17 3.34L6 12.41l-3 2.13V17l2.8-2 6.2 6 5-4h4v-2z" }), 'SsidChartSharp');
exports.default = _default;
random_line_split
filter.ts
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { IIterator, IterableOrArrayLike, iter } from './iter'; /** * Filter an iterable for values which pass a test. * * @param object - The iterable or array-like object of interest. * * @param fn - The predicate function to invoke for each value. * * @returns An iterator which yields the values which pass the test. * * #### Example * ```typescript * import { filter, toArray } from '@phosphor/algorithm'; * * let data = [1, 2, 3, 4, 5, 6]; * * let stream = filter(data, value => value % 2 === 0); * * toArray(stream); // [2, 4, 6] * ``` */ export function filter<T>(object: IterableOrArrayLike<T>, fn: (value: T, index: number) => boolean): IIterator<T> { return new FilterIterator<T>(iter(object), fn); } /** * An iterator which yields values which pass a test. */ export class FilterIterator<T> implements IIterator<T> { /** * Construct a new filter iterator. * * @param source - The iterator of values of interest. * * @param fn - The predicate function to invoke for each value. */ constructor(source: IIterator<T>, fn: (value: T, index: number) => boolean) { this._source = source; this._fn = fn; } /** * Get an iterator over the object's values. * * @returns An iterator which yields the object's values. */ iter(): IIterator<T>
/** * Create an independent clone of the iterator. * * @returns A new independent clone of the iterator. */ clone(): IIterator<T> { let result = new FilterIterator<T>(this._source.clone(), this._fn); result._index = this._index; return result; } /** * Get the next value from the iterator. * * @returns The next value from the iterator, or `undefined`. */ next(): T | undefined { let fn = this._fn; let it = this._source; let value: T | undefined; while ((value = it.next()) !== undefined) { if (fn(value, this._index++)) { return value; } } return undefined; } private _index = 0; private _source: IIterator<T>; private _fn: (value: T, index: number) => boolean; }
{ return this; }
identifier_body
filter.ts
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { IIterator, IterableOrArrayLike, iter } from './iter'; /** * Filter an iterable for values which pass a test. * * @param object - The iterable or array-like object of interest. * * @param fn - The predicate function to invoke for each value. * * @returns An iterator which yields the values which pass the test. * * #### Example * ```typescript * import { filter, toArray } from '@phosphor/algorithm'; * * let data = [1, 2, 3, 4, 5, 6]; * * let stream = filter(data, value => value % 2 === 0); * * toArray(stream); // [2, 4, 6] * ``` */ export function filter<T>(object: IterableOrArrayLike<T>, fn: (value: T, index: number) => boolean): IIterator<T> { return new FilterIterator<T>(iter(object), fn); } /** * An iterator which yields values which pass a test. */ export class FilterIterator<T> implements IIterator<T> { /** * Construct a new filter iterator. * * @param source - The iterator of values of interest. * * @param fn - The predicate function to invoke for each value. */ constructor(source: IIterator<T>, fn: (value: T, index: number) => boolean) { this._source = source; this._fn = fn; } /** * Get an iterator over the object's values. * * @returns An iterator which yields the object's values. */ iter(): IIterator<T> { return this; } /** * Create an independent clone of the iterator. * * @returns A new independent clone of the iterator. */ clone(): IIterator<T> { let result = new FilterIterator<T>(this._source.clone(), this._fn); result._index = this._index; return result; } /** * Get the next value from the iterator. * * @returns The next value from the iterator, or `undefined`. */ next(): T | undefined { let fn = this._fn; let it = this._source; let value: T | undefined; while ((value = it.next()) !== undefined) { if (fn(value, this._index++))
} return undefined; } private _index = 0; private _source: IIterator<T>; private _fn: (value: T, index: number) => boolean; }
{ return value; }
conditional_block
filter.ts
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { IIterator, IterableOrArrayLike, iter } from './iter'; /** * Filter an iterable for values which pass a test. * * @param object - The iterable or array-like object of interest. * * @param fn - The predicate function to invoke for each value. * * @returns An iterator which yields the values which pass the test. * * #### Example * ```typescript * import { filter, toArray } from '@phosphor/algorithm'; * * let data = [1, 2, 3, 4, 5, 6]; * * let stream = filter(data, value => value % 2 === 0); * * toArray(stream); // [2, 4, 6] * ``` */ export function filter<T>(object: IterableOrArrayLike<T>, fn: (value: T, index: number) => boolean): IIterator<T> { return new FilterIterator<T>(iter(object), fn); } /** * An iterator which yields values which pass a test. */ export class FilterIterator<T> implements IIterator<T> { /** * Construct a new filter iterator. * * @param source - The iterator of values of interest. * * @param fn - The predicate function to invoke for each value. */ constructor(source: IIterator<T>, fn: (value: T, index: number) => boolean) { this._source = source; this._fn = fn; } /** * Get an iterator over the object's values. * * @returns An iterator which yields the object's values. */ iter(): IIterator<T> { return this; } /** * Create an independent clone of the iterator. * * @returns A new independent clone of the iterator. */
(): IIterator<T> { let result = new FilterIterator<T>(this._source.clone(), this._fn); result._index = this._index; return result; } /** * Get the next value from the iterator. * * @returns The next value from the iterator, or `undefined`. */ next(): T | undefined { let fn = this._fn; let it = this._source; let value: T | undefined; while ((value = it.next()) !== undefined) { if (fn(value, this._index++)) { return value; } } return undefined; } private _index = 0; private _source: IIterator<T>; private _fn: (value: T, index: number) => boolean; }
clone
identifier_name
filter.ts
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { IIterator, IterableOrArrayLike, iter } from './iter'; /** * Filter an iterable for values which pass a test. * * @param object - The iterable or array-like object of interest. * * @param fn - The predicate function to invoke for each value. * * @returns An iterator which yields the values which pass the test. * * #### Example * ```typescript * import { filter, toArray } from '@phosphor/algorithm'; * * let data = [1, 2, 3, 4, 5, 6]; * * let stream = filter(data, value => value % 2 === 0); * * toArray(stream); // [2, 4, 6] * ``` */ export function filter<T>(object: IterableOrArrayLike<T>, fn: (value: T, index: number) => boolean): IIterator<T> {
return new FilterIterator<T>(iter(object), fn); } /** * An iterator which yields values which pass a test. */ export class FilterIterator<T> implements IIterator<T> { /** * Construct a new filter iterator. * * @param source - The iterator of values of interest. * * @param fn - The predicate function to invoke for each value. */ constructor(source: IIterator<T>, fn: (value: T, index: number) => boolean) { this._source = source; this._fn = fn; } /** * Get an iterator over the object's values. * * @returns An iterator which yields the object's values. */ iter(): IIterator<T> { return this; } /** * Create an independent clone of the iterator. * * @returns A new independent clone of the iterator. */ clone(): IIterator<T> { let result = new FilterIterator<T>(this._source.clone(), this._fn); result._index = this._index; return result; } /** * Get the next value from the iterator. * * @returns The next value from the iterator, or `undefined`. */ next(): T | undefined { let fn = this._fn; let it = this._source; let value: T | undefined; while ((value = it.next()) !== undefined) { if (fn(value, this._index++)) { return value; } } return undefined; } private _index = 0; private _source: IIterator<T>; private _fn: (value: T, index: number) => boolean; }
random_line_split
interfaces.ts
import type { DataEntity } from './entities/data-entity'; export type { Omit, Overwrite, Override, Required, Optional, Nil, WithoutNil, Many, RecursiveArray, ListOfRecursiveArraysOrValues, EmptyObject, AnyObject, PartialDeep, Diff, Filter, ValueOf,
FilteredResult, Unpacked } from '@terascope/types'; /** * Used for sending data to particular index/topic/file/table in a storage system. * This is used by the routed sender in the standard-assets */ export interface RouteSenderAPI { /** * Sends the records to the respective storage backend * * @returns the number of affected records/rows */ send(records: Iterable<DataEntity>): Promise<number>; /** * This is used to verify and create an resources * required for this particular route * * This is optional to implement */ verify?(route?: string): Promise<void>; }
random_line_split
event_dispatcher.ts
import { RenderViewRef, RenderEventDispatcher, } from 'angular2/src/render/api'; import {Serializer} from 'angular2/src/web_workers/shared/serializer'; import { serializeMouseEvent, serializeKeyboardEvent, serializeGenericEvent, serializeEventWithTarget } from 'angular2/src/web_workers/ui/event_serializer'; import {BaseException} from "angular2/src/facade/lang"; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; export class
implements RenderEventDispatcher { constructor(private _viewRef: RenderViewRef, private _sink: EventEmitter, private _serializer: Serializer) {} dispatchRenderEvent(elementIndex: number, eventName: string, locals: Map<string, any>) { var e = locals.get('$event'); var serializedEvent; // TODO (jteplitz602): support custom events #3350 switch (e.type) { case "click": case "mouseup": case "mousedown": case "dblclick": case "contextmenu": case "mouseenter": case "mouseleave": case "mousemove": case "mouseout": case "mouseover": case "show": serializedEvent = serializeMouseEvent(e); break; case "keydown": case "keypress": case "keyup": serializedEvent = serializeKeyboardEvent(e); break; case "input": case "change": case "blur": serializedEvent = serializeEventWithTarget(e); break; case "abort": case "afterprint": case "beforeprint": case "cached": case "canplay": case "canplaythrough": case "chargingchange": case "chargingtimechange": case "close": case "dischargingtimechange": case "DOMContentLoaded": case "downloading": case "durationchange": case "emptied": case "ended": case "error": case "fullscreenchange": case "fullscreenerror": case "invalid": case "languagechange": case "levelfchange": case "loadeddata": case "loadedmetadata": case "obsolete": case "offline": case "online": case "open": case "orientatoinchange": case "pause": case "pointerlockchange": case "pointerlockerror": case "play": case "playing": case "ratechange": case "readystatechange": case "reset": case "seeked": case "seeking": case "stalled": case "submit": case "success": case "suspend": case "timeupdate": case "updateready": case "visibilitychange": case "volumechange": case "waiting": serializedEvent = serializeGenericEvent(e); break; default: throw new BaseException(eventName + " not supported on WebWorkers"); } var serializedLocals = StringMapWrapper.create(); StringMapWrapper.set(serializedLocals, '$event', serializedEvent); ObservableWrapper.callNext(this._sink, { "viewRef": this._serializer.serialize(this._viewRef, RenderViewRef), "elementIndex": elementIndex, "eventName": eventName, "locals": serializedLocals }); } }
EventDispatcher
identifier_name
event_dispatcher.ts
import { RenderViewRef, RenderEventDispatcher, } from 'angular2/src/render/api'; import {Serializer} from 'angular2/src/web_workers/shared/serializer'; import { serializeMouseEvent, serializeKeyboardEvent, serializeGenericEvent, serializeEventWithTarget } from 'angular2/src/web_workers/ui/event_serializer'; import {BaseException} from "angular2/src/facade/lang"; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; export class EventDispatcher implements RenderEventDispatcher { constructor(private _viewRef: RenderViewRef, private _sink: EventEmitter, private _serializer: Serializer) {} dispatchRenderEvent(elementIndex: number, eventName: string, locals: Map<string, any>) { var e = locals.get('$event'); var serializedEvent; // TODO (jteplitz602): support custom events #3350 switch (e.type) { case "click": case "mouseup": case "mousedown": case "dblclick": case "contextmenu": case "mouseenter":
serializedEvent = serializeMouseEvent(e); break; case "keydown": case "keypress": case "keyup": serializedEvent = serializeKeyboardEvent(e); break; case "input": case "change": case "blur": serializedEvent = serializeEventWithTarget(e); break; case "abort": case "afterprint": case "beforeprint": case "cached": case "canplay": case "canplaythrough": case "chargingchange": case "chargingtimechange": case "close": case "dischargingtimechange": case "DOMContentLoaded": case "downloading": case "durationchange": case "emptied": case "ended": case "error": case "fullscreenchange": case "fullscreenerror": case "invalid": case "languagechange": case "levelfchange": case "loadeddata": case "loadedmetadata": case "obsolete": case "offline": case "online": case "open": case "orientatoinchange": case "pause": case "pointerlockchange": case "pointerlockerror": case "play": case "playing": case "ratechange": case "readystatechange": case "reset": case "seeked": case "seeking": case "stalled": case "submit": case "success": case "suspend": case "timeupdate": case "updateready": case "visibilitychange": case "volumechange": case "waiting": serializedEvent = serializeGenericEvent(e); break; default: throw new BaseException(eventName + " not supported on WebWorkers"); } var serializedLocals = StringMapWrapper.create(); StringMapWrapper.set(serializedLocals, '$event', serializedEvent); ObservableWrapper.callNext(this._sink, { "viewRef": this._serializer.serialize(this._viewRef, RenderViewRef), "elementIndex": elementIndex, "eventName": eventName, "locals": serializedLocals }); } }
case "mouseleave": case "mousemove": case "mouseout": case "mouseover": case "show":
random_line_split
event_dispatcher.ts
import { RenderViewRef, RenderEventDispatcher, } from 'angular2/src/render/api'; import {Serializer} from 'angular2/src/web_workers/shared/serializer'; import { serializeMouseEvent, serializeKeyboardEvent, serializeGenericEvent, serializeEventWithTarget } from 'angular2/src/web_workers/ui/event_serializer'; import {BaseException} from "angular2/src/facade/lang"; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; export class EventDispatcher implements RenderEventDispatcher { constructor(private _viewRef: RenderViewRef, private _sink: EventEmitter, private _serializer: Serializer)
dispatchRenderEvent(elementIndex: number, eventName: string, locals: Map<string, any>) { var e = locals.get('$event'); var serializedEvent; // TODO (jteplitz602): support custom events #3350 switch (e.type) { case "click": case "mouseup": case "mousedown": case "dblclick": case "contextmenu": case "mouseenter": case "mouseleave": case "mousemove": case "mouseout": case "mouseover": case "show": serializedEvent = serializeMouseEvent(e); break; case "keydown": case "keypress": case "keyup": serializedEvent = serializeKeyboardEvent(e); break; case "input": case "change": case "blur": serializedEvent = serializeEventWithTarget(e); break; case "abort": case "afterprint": case "beforeprint": case "cached": case "canplay": case "canplaythrough": case "chargingchange": case "chargingtimechange": case "close": case "dischargingtimechange": case "DOMContentLoaded": case "downloading": case "durationchange": case "emptied": case "ended": case "error": case "fullscreenchange": case "fullscreenerror": case "invalid": case "languagechange": case "levelfchange": case "loadeddata": case "loadedmetadata": case "obsolete": case "offline": case "online": case "open": case "orientatoinchange": case "pause": case "pointerlockchange": case "pointerlockerror": case "play": case "playing": case "ratechange": case "readystatechange": case "reset": case "seeked": case "seeking": case "stalled": case "submit": case "success": case "suspend": case "timeupdate": case "updateready": case "visibilitychange": case "volumechange": case "waiting": serializedEvent = serializeGenericEvent(e); break; default: throw new BaseException(eventName + " not supported on WebWorkers"); } var serializedLocals = StringMapWrapper.create(); StringMapWrapper.set(serializedLocals, '$event', serializedEvent); ObservableWrapper.callNext(this._sink, { "viewRef": this._serializer.serialize(this._viewRef, RenderViewRef), "elementIndex": elementIndex, "eventName": eventName, "locals": serializedLocals }); } }
{}
identifier_body
no_0064_minimum_path_sum.rs
struct Solution; impl Solution { pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 { if grid.is_empty() { return 0; } let (m, n) = (grid.len(), grid[0].len()); let mut arr = vec![std::i32::MAX; n]; arr[0] = 0; for i in 0..m { for j in 0..n { // 选择上面(arr[j])和左面(arr[j-1])最小的那个 if j == 0 { // 左边没有,只有上面的元素 arr[j] = arr[j] + grid[i][j]; } else { // 有左边和上边 arr[j] = arr[j].min(arr[j - 1]) + grid[i][j]; } } } arr[n - 1]
} #[cfg(test)] mod tests { use super::*; #[test] fn test_min_path_sum() { let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]]; assert_eq!(Solution::min_path_sum(grid), 7); } }
}
random_line_split
no_0064_minimum_path_sum.rs
struct Solution; impl Solution { pub fn
(grid: Vec<Vec<i32>>) -> i32 { if grid.is_empty() { return 0; } let (m, n) = (grid.len(), grid[0].len()); let mut arr = vec![std::i32::MAX; n]; arr[0] = 0; for i in 0..m { for j in 0..n { // 选择上面(arr[j])和左面(arr[j-1])最小的那个 if j == 0 { // 左边没有,只有上面的元素 arr[j] = arr[j] + grid[i][j]; } else { // 有左边和上边 arr[j] = arr[j].min(arr[j - 1]) + grid[i][j]; } } } arr[n - 1] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_path_sum() { let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]]; assert_eq!(Solution::min_path_sum(grid), 7); } }
min_path_sum
identifier_name
no_0064_minimum_path_sum.rs
struct Solution; impl Solution { pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32
fn test_min_path_sum() { let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]]; assert_eq!(Solution::min_path_sum(grid), 7); } }
{ if grid.is_empty() { return 0; } let (m, n) = (grid.len(), grid[0].len()); let mut arr = vec![std::i32::MAX; n]; arr[0] = 0; for i in 0..m { for j in 0..n { // 选择上面(arr[j])和左面(arr[j-1])最小的那个 if j == 0 { // 左边没有,只有上面的元素 arr[j] = arr[j] + grid[i][j]; } else { // 有左边和上边 arr[j] = arr[j].min(arr[j - 1]) + grid[i][j]; } } } arr[n - 1] } } #[cfg(test)] mod tests { use super::*; #[test]
identifier_body
no_0064_minimum_path_sum.rs
struct Solution; impl Solution { pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 { if grid.is_empty()
let (m, n) = (grid.len(), grid[0].len()); let mut arr = vec![std::i32::MAX; n]; arr[0] = 0; for i in 0..m { for j in 0..n { // 选择上面(arr[j])和左面(arr[j-1])最小的那个 if j == 0 { // 左边没有,只有上面的元素 arr[j] = arr[j] + grid[i][j]; } else { // 有左边和上边 arr[j] = arr[j].min(arr[j - 1]) + grid[i][j]; } } } arr[n - 1] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_path_sum() { let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]]; assert_eq!(Solution::min_path_sum(grid), 7); } }
{ return 0; }
conditional_block
issue-59494.rs
fn
<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C { move |a: A| -> C { f(g(a)) } } fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C) where A: Copy, { move |a: A| -> (B, C) { let b = a; let fa = f(a); let ga = g(b); (fa, ga) } } fn main() { let f = |(_, _)| {}; let g = |(a, _)| a; let t7 = |env| |a| |b| t7p(f, g)(((env, a), b)); let t8 = t8n(t7, t7p(f, g)); //~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)> }
t7p
identifier_name
issue-59494.rs
fn t7p<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C) where A: Copy, { move |a: A| -> (B, C) { let b = a; let fa = f(a); let ga = g(b); (fa, ga) } } fn main() { let f = |(_, _)| {}; let g = |(a, _)| a; let t7 = |env| |a| |b| t7p(f, g)(((env, a), b)); let t8 = t8n(t7, t7p(f, g)); //~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)> }
{ move |a: A| -> C { f(g(a)) } }
identifier_body
issue-59494.rs
fn t7p<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C { move |a: A| -> C { f(g(a)) } } fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C) where A: Copy, { move |a: A| -> (B, C) { let b = a; let fa = f(a); let ga = g(b); (fa, ga) } } fn main() {
let g = |(a, _)| a; let t7 = |env| |a| |b| t7p(f, g)(((env, a), b)); let t8 = t8n(t7, t7p(f, g)); //~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)> }
let f = |(_, _)| {};
random_line_split
bst.rs
// Copyright 2020 Google LLC // // 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 // // https://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. use log::debug; #[derive(Debug)] struct Node<T> { v: T, left: NodePtr<T>, right: NodePtr<T>, } type NodePtr<T> = Option<Box<Node<T>>>; #[derive(Debug)] pub struct BinarySearchTree<T> { root: NodePtr<T>, } impl<T> Node<T> { fn new(v: T) -> NodePtr<T> { Some(Box::new(Self { v, left: None, right: None, })) } } impl<T> BinarySearchTree<T> { pub fn new() -> Self { Self { root: None } } fn find_slot(&mut self, v: &T) -> &mut NodePtr<T> where T: Ord, { let mut current = &mut self.root; while current.is_some() { if &current.as_ref().unwrap().v == v { break; } use std::cmp::Ordering; let inner = current.as_mut().unwrap(); match v.cmp(&inner.v) { Ordering::Less => current = &mut inner.left, Ordering::Greater => current = &mut inner.right, Ordering::Equal => unreachable!(), } } current } pub fn insert(&mut self, v: T) where T: Ord, { let slot = self.find_slot(&v); if slot.is_none() { *slot = Node::new(v); } } pub fn contains(&self, v: &T) -> bool where T: Ord + std::fmt::Debug, { let mut current = &self.root; while let Some(inner) = current { debug!("Stepping through {:?}", inner.v); use std::cmp::Ordering; match v.cmp(&inner.v) { Ordering::Less => current = &inner.left, Ordering::Greater => current = &inner.right, Ordering::Equal => return true, } } false } } impl<T: Ord> std::iter::FromIterator<T> for BinarySearchTree<T> { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { let mut tree = BinarySearchTree::default(); tree.extend(iter); tree } } impl<T> Default for BinarySearchTree<T> { fn default() -> Self { Self::new() } } impl<T: Ord> std::iter::Extend<T> for BinarySearchTree<T> { fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { for i in iter { self.insert(i); } } } #[cfg(test)] mod tests { use super::*; #[test]
let mut x = BinarySearchTree::new(); x.insert(5); x.insert(6); assert!(x.contains(&5)); assert!(x.contains(&6)); assert!(!x.contains(&7)); } #[test] fn test_structure() { let mut x = BinarySearchTree::new(); x.insert(10); x.insert(15); x.insert(17); x.insert(13); x.insert(5); assert!(x.root.as_ref().unwrap().v == 10); assert!(x.root.as_ref().unwrap().left.as_ref().unwrap().v == 5); assert!(x.root.as_ref().unwrap().right.as_ref().unwrap().v == 15); assert!( x.root .as_ref() .unwrap() .right .as_ref() .unwrap() .left .as_ref() .unwrap() .v == 13 ); assert!( x.root .as_ref() .unwrap() .right .as_ref() .unwrap() .right .as_ref() .unwrap() .v == 17 ); } }
fn test_insert_contains() {
random_line_split
bst.rs
// Copyright 2020 Google LLC // // 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 // // https://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. use log::debug; #[derive(Debug)] struct
<T> { v: T, left: NodePtr<T>, right: NodePtr<T>, } type NodePtr<T> = Option<Box<Node<T>>>; #[derive(Debug)] pub struct BinarySearchTree<T> { root: NodePtr<T>, } impl<T> Node<T> { fn new(v: T) -> NodePtr<T> { Some(Box::new(Self { v, left: None, right: None, })) } } impl<T> BinarySearchTree<T> { pub fn new() -> Self { Self { root: None } } fn find_slot(&mut self, v: &T) -> &mut NodePtr<T> where T: Ord, { let mut current = &mut self.root; while current.is_some() { if &current.as_ref().unwrap().v == v { break; } use std::cmp::Ordering; let inner = current.as_mut().unwrap(); match v.cmp(&inner.v) { Ordering::Less => current = &mut inner.left, Ordering::Greater => current = &mut inner.right, Ordering::Equal => unreachable!(), } } current } pub fn insert(&mut self, v: T) where T: Ord, { let slot = self.find_slot(&v); if slot.is_none() { *slot = Node::new(v); } } pub fn contains(&self, v: &T) -> bool where T: Ord + std::fmt::Debug, { let mut current = &self.root; while let Some(inner) = current { debug!("Stepping through {:?}", inner.v); use std::cmp::Ordering; match v.cmp(&inner.v) { Ordering::Less => current = &inner.left, Ordering::Greater => current = &inner.right, Ordering::Equal => return true, } } false } } impl<T: Ord> std::iter::FromIterator<T> for BinarySearchTree<T> { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { let mut tree = BinarySearchTree::default(); tree.extend(iter); tree } } impl<T> Default for BinarySearchTree<T> { fn default() -> Self { Self::new() } } impl<T: Ord> std::iter::Extend<T> for BinarySearchTree<T> { fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { for i in iter { self.insert(i); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_insert_contains() { let mut x = BinarySearchTree::new(); x.insert(5); x.insert(6); assert!(x.contains(&5)); assert!(x.contains(&6)); assert!(!x.contains(&7)); } #[test] fn test_structure() { let mut x = BinarySearchTree::new(); x.insert(10); x.insert(15); x.insert(17); x.insert(13); x.insert(5); assert!(x.root.as_ref().unwrap().v == 10); assert!(x.root.as_ref().unwrap().left.as_ref().unwrap().v == 5); assert!(x.root.as_ref().unwrap().right.as_ref().unwrap().v == 15); assert!( x.root .as_ref() .unwrap() .right .as_ref() .unwrap() .left .as_ref() .unwrap() .v == 13 ); assert!( x.root .as_ref() .unwrap() .right .as_ref() .unwrap() .right .as_ref() .unwrap() .v == 17 ); } }
Node
identifier_name
bst.rs
// Copyright 2020 Google LLC // // 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 // // https://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. use log::debug; #[derive(Debug)] struct Node<T> { v: T, left: NodePtr<T>, right: NodePtr<T>, } type NodePtr<T> = Option<Box<Node<T>>>; #[derive(Debug)] pub struct BinarySearchTree<T> { root: NodePtr<T>, } impl<T> Node<T> { fn new(v: T) -> NodePtr<T> { Some(Box::new(Self { v, left: None, right: None, })) } } impl<T> BinarySearchTree<T> { pub fn new() -> Self { Self { root: None } } fn find_slot(&mut self, v: &T) -> &mut NodePtr<T> where T: Ord,
pub fn insert(&mut self, v: T) where T: Ord, { let slot = self.find_slot(&v); if slot.is_none() { *slot = Node::new(v); } } pub fn contains(&self, v: &T) -> bool where T: Ord + std::fmt::Debug, { let mut current = &self.root; while let Some(inner) = current { debug!("Stepping through {:?}", inner.v); use std::cmp::Ordering; match v.cmp(&inner.v) { Ordering::Less => current = &inner.left, Ordering::Greater => current = &inner.right, Ordering::Equal => return true, } } false } } impl<T: Ord> std::iter::FromIterator<T> for BinarySearchTree<T> { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { let mut tree = BinarySearchTree::default(); tree.extend(iter); tree } } impl<T> Default for BinarySearchTree<T> { fn default() -> Self { Self::new() } } impl<T: Ord> std::iter::Extend<T> for BinarySearchTree<T> { fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { for i in iter { self.insert(i); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_insert_contains() { let mut x = BinarySearchTree::new(); x.insert(5); x.insert(6); assert!(x.contains(&5)); assert!(x.contains(&6)); assert!(!x.contains(&7)); } #[test] fn test_structure() { let mut x = BinarySearchTree::new(); x.insert(10); x.insert(15); x.insert(17); x.insert(13); x.insert(5); assert!(x.root.as_ref().unwrap().v == 10); assert!(x.root.as_ref().unwrap().left.as_ref().unwrap().v == 5); assert!(x.root.as_ref().unwrap().right.as_ref().unwrap().v == 15); assert!( x.root .as_ref() .unwrap() .right .as_ref() .unwrap() .left .as_ref() .unwrap() .v == 13 ); assert!( x.root .as_ref() .unwrap() .right .as_ref() .unwrap() .right .as_ref() .unwrap() .v == 17 ); } }
{ let mut current = &mut self.root; while current.is_some() { if &current.as_ref().unwrap().v == v { break; } use std::cmp::Ordering; let inner = current.as_mut().unwrap(); match v.cmp(&inner.v) { Ordering::Less => current = &mut inner.left, Ordering::Greater => current = &mut inner.right, Ordering::Equal => unreachable!(), } } current }
identifier_body
ContinuousMonitoringUtils.ts
import tl = require('vsts-task-lib/task'); import { AzureEndpoint } from 'azure-arm-rest/azureModels'; import {AzureAppService } from 'azure-arm-rest/azure-arm-app-service'; import { AzureApplicationInsights } from 'azure-arm-rest/azure-arm-appinsights'; import { Kudu } from 'azure-arm-rest/azure-arm-app-service-kudu'; import { ApplicationInsightsWebTests } from 'azure-arm-rest/azure-arm-appinsights-webtests'; import { AzureAppServiceUtils } from './AzureAppServiceUtils'; import { AzureApplicationInsightsWebTestsUtils } from './AzureApplicationInsightsWebTestsUtils'; const APPLICATION_INSIGHTS_EXTENSION_NAME: string = "Microsoft.ApplicationInsights.AzureWebSites"; export async function enableContinuousMonitoring(endpoint: AzureEndpoint, appService: AzureAppService, appInsights: AzureApplicationInsights) { try { console.log(tl.loc('EnablingContinousMonitoring', appService.getName())); var appDetails = await appService.get(); var appServiceUtils = new AzureAppServiceUtils(appService); var appInsightsResource = await appInsights.get(); var appInsightsWebTests = new ApplicationInsightsWebTests(endpoint, appInsights.getResourceGroupName()); var webDeployPublishingProfile = await appServiceUtils.getWebDeployPublishingProfile(); var applicationUrl = webDeployPublishingProfile.destinationAppUrl; if(appDetails.kind.indexOf("linux") == -1) { var appKuduService: Kudu = await appServiceUtils.getKuduService(); await appKuduService.installSiteExtension(APPLICATION_INSIGHTS_EXTENSION_NAME); } appInsightsResource.tags["hidden-link:" + appDetails.id] = "Resource"; tl.debug('Link app insights with app service via tag'); await appInsights.update(appInsightsResource); tl.debug('Link app service with app insights via instrumentation key'); await appService.patchApplicationSettings({ "APPINSIGHTS_INSTRUMENTATIONKEY": appInsightsResource.properties['InstrumentationKey'] }); try { tl.debug('Enable alwaysOn property for app service.');
catch(error) { tl.warning(error); } try { tl.debug('add web test for app service - app insights'); var appInsightsWebTestsUtils: AzureApplicationInsightsWebTestsUtils = new AzureApplicationInsightsWebTestsUtils(appInsightsWebTests); await appInsightsWebTestsUtils.addWebTest(appInsightsResource, applicationUrl); } catch(error) { tl.warning(error); } console.log(tl.loc("ContinousMonitoringEnabled", appService.getName())); } catch(error) { throw new Error(tl.loc('FailedToEnableContinuousMonitoring', error)); } }
await appService.patchConfiguration({ "properties" :{"alwaysOn": true}}); }
random_line_split
ContinuousMonitoringUtils.ts
import tl = require('vsts-task-lib/task'); import { AzureEndpoint } from 'azure-arm-rest/azureModels'; import {AzureAppService } from 'azure-arm-rest/azure-arm-app-service'; import { AzureApplicationInsights } from 'azure-arm-rest/azure-arm-appinsights'; import { Kudu } from 'azure-arm-rest/azure-arm-app-service-kudu'; import { ApplicationInsightsWebTests } from 'azure-arm-rest/azure-arm-appinsights-webtests'; import { AzureAppServiceUtils } from './AzureAppServiceUtils'; import { AzureApplicationInsightsWebTestsUtils } from './AzureApplicationInsightsWebTestsUtils'; const APPLICATION_INSIGHTS_EXTENSION_NAME: string = "Microsoft.ApplicationInsights.AzureWebSites"; export async function enableContinuousMonitoring(endpoint: AzureEndpoint, appService: AzureAppService, appInsights: AzureApplicationInsights) { try { console.log(tl.loc('EnablingContinousMonitoring', appService.getName())); var appDetails = await appService.get(); var appServiceUtils = new AzureAppServiceUtils(appService); var appInsightsResource = await appInsights.get(); var appInsightsWebTests = new ApplicationInsightsWebTests(endpoint, appInsights.getResourceGroupName()); var webDeployPublishingProfile = await appServiceUtils.getWebDeployPublishingProfile(); var applicationUrl = webDeployPublishingProfile.destinationAppUrl; if(appDetails.kind.indexOf("linux") == -1)
appInsightsResource.tags["hidden-link:" + appDetails.id] = "Resource"; tl.debug('Link app insights with app service via tag'); await appInsights.update(appInsightsResource); tl.debug('Link app service with app insights via instrumentation key'); await appService.patchApplicationSettings({ "APPINSIGHTS_INSTRUMENTATIONKEY": appInsightsResource.properties['InstrumentationKey'] }); try { tl.debug('Enable alwaysOn property for app service.'); await appService.patchConfiguration({ "properties" :{"alwaysOn": true}}); } catch(error) { tl.warning(error); } try { tl.debug('add web test for app service - app insights'); var appInsightsWebTestsUtils: AzureApplicationInsightsWebTestsUtils = new AzureApplicationInsightsWebTestsUtils(appInsightsWebTests); await appInsightsWebTestsUtils.addWebTest(appInsightsResource, applicationUrl); } catch(error) { tl.warning(error); } console.log(tl.loc("ContinousMonitoringEnabled", appService.getName())); } catch(error) { throw new Error(tl.loc('FailedToEnableContinuousMonitoring', error)); } }
{ var appKuduService: Kudu = await appServiceUtils.getKuduService(); await appKuduService.installSiteExtension(APPLICATION_INSIGHTS_EXTENSION_NAME); }
conditional_block
ContinuousMonitoringUtils.ts
import tl = require('vsts-task-lib/task'); import { AzureEndpoint } from 'azure-arm-rest/azureModels'; import {AzureAppService } from 'azure-arm-rest/azure-arm-app-service'; import { AzureApplicationInsights } from 'azure-arm-rest/azure-arm-appinsights'; import { Kudu } from 'azure-arm-rest/azure-arm-app-service-kudu'; import { ApplicationInsightsWebTests } from 'azure-arm-rest/azure-arm-appinsights-webtests'; import { AzureAppServiceUtils } from './AzureAppServiceUtils'; import { AzureApplicationInsightsWebTestsUtils } from './AzureApplicationInsightsWebTestsUtils'; const APPLICATION_INSIGHTS_EXTENSION_NAME: string = "Microsoft.ApplicationInsights.AzureWebSites"; export async function enableContinuousMonitoring(endpoint: AzureEndpoint, appService: AzureAppService, appInsights: AzureApplicationInsights)
{ try { console.log(tl.loc('EnablingContinousMonitoring', appService.getName())); var appDetails = await appService.get(); var appServiceUtils = new AzureAppServiceUtils(appService); var appInsightsResource = await appInsights.get(); var appInsightsWebTests = new ApplicationInsightsWebTests(endpoint, appInsights.getResourceGroupName()); var webDeployPublishingProfile = await appServiceUtils.getWebDeployPublishingProfile(); var applicationUrl = webDeployPublishingProfile.destinationAppUrl; if(appDetails.kind.indexOf("linux") == -1) { var appKuduService: Kudu = await appServiceUtils.getKuduService(); await appKuduService.installSiteExtension(APPLICATION_INSIGHTS_EXTENSION_NAME); } appInsightsResource.tags["hidden-link:" + appDetails.id] = "Resource"; tl.debug('Link app insights with app service via tag'); await appInsights.update(appInsightsResource); tl.debug('Link app service with app insights via instrumentation key'); await appService.patchApplicationSettings({ "APPINSIGHTS_INSTRUMENTATIONKEY": appInsightsResource.properties['InstrumentationKey'] }); try { tl.debug('Enable alwaysOn property for app service.'); await appService.patchConfiguration({ "properties" :{"alwaysOn": true}}); } catch(error) { tl.warning(error); } try { tl.debug('add web test for app service - app insights'); var appInsightsWebTestsUtils: AzureApplicationInsightsWebTestsUtils = new AzureApplicationInsightsWebTestsUtils(appInsightsWebTests); await appInsightsWebTestsUtils.addWebTest(appInsightsResource, applicationUrl); } catch(error) { tl.warning(error); } console.log(tl.loc("ContinousMonitoringEnabled", appService.getName())); } catch(error) { throw new Error(tl.loc('FailedToEnableContinuousMonitoring', error)); } }
identifier_body
ContinuousMonitoringUtils.ts
import tl = require('vsts-task-lib/task'); import { AzureEndpoint } from 'azure-arm-rest/azureModels'; import {AzureAppService } from 'azure-arm-rest/azure-arm-app-service'; import { AzureApplicationInsights } from 'azure-arm-rest/azure-arm-appinsights'; import { Kudu } from 'azure-arm-rest/azure-arm-app-service-kudu'; import { ApplicationInsightsWebTests } from 'azure-arm-rest/azure-arm-appinsights-webtests'; import { AzureAppServiceUtils } from './AzureAppServiceUtils'; import { AzureApplicationInsightsWebTestsUtils } from './AzureApplicationInsightsWebTestsUtils'; const APPLICATION_INSIGHTS_EXTENSION_NAME: string = "Microsoft.ApplicationInsights.AzureWebSites"; export async function
(endpoint: AzureEndpoint, appService: AzureAppService, appInsights: AzureApplicationInsights) { try { console.log(tl.loc('EnablingContinousMonitoring', appService.getName())); var appDetails = await appService.get(); var appServiceUtils = new AzureAppServiceUtils(appService); var appInsightsResource = await appInsights.get(); var appInsightsWebTests = new ApplicationInsightsWebTests(endpoint, appInsights.getResourceGroupName()); var webDeployPublishingProfile = await appServiceUtils.getWebDeployPublishingProfile(); var applicationUrl = webDeployPublishingProfile.destinationAppUrl; if(appDetails.kind.indexOf("linux") == -1) { var appKuduService: Kudu = await appServiceUtils.getKuduService(); await appKuduService.installSiteExtension(APPLICATION_INSIGHTS_EXTENSION_NAME); } appInsightsResource.tags["hidden-link:" + appDetails.id] = "Resource"; tl.debug('Link app insights with app service via tag'); await appInsights.update(appInsightsResource); tl.debug('Link app service with app insights via instrumentation key'); await appService.patchApplicationSettings({ "APPINSIGHTS_INSTRUMENTATIONKEY": appInsightsResource.properties['InstrumentationKey'] }); try { tl.debug('Enable alwaysOn property for app service.'); await appService.patchConfiguration({ "properties" :{"alwaysOn": true}}); } catch(error) { tl.warning(error); } try { tl.debug('add web test for app service - app insights'); var appInsightsWebTestsUtils: AzureApplicationInsightsWebTestsUtils = new AzureApplicationInsightsWebTestsUtils(appInsightsWebTests); await appInsightsWebTestsUtils.addWebTest(appInsightsResource, applicationUrl); } catch(error) { tl.warning(error); } console.log(tl.loc("ContinousMonitoringEnabled", appService.getName())); } catch(error) { throw new Error(tl.loc('FailedToEnableContinuousMonitoring', error)); } }
enableContinuousMonitoring
identifier_name
setup.py
from setuptools import setup, Extension with open('README.md') as istream: long_description = istream.read() tests_require = ['pytest'] libReQL = Extension( 'libReQL', include_dirs=['src'], sources=[ 'src/Python/connection.c', 'src/Python/cursor.c', 'src/Python/query.c', 'src/Python/ReQL.c', 'src/Python/types.c', 'src/reql/char.c', 'src/reql/connection.c', 'src/reql/cursor.c', 'src/reql/decode.c', 'src/reql/encode.c', 'src/reql/error.c', 'src/reql/query.c' ] ) setup( author='Adam Grandquist', author_email='grandquista@gmail.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Programming Language :: C', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Database :: Front-Ends' ], description='A Python driver for RethinkDB.', entry_points={ 'console_scripts': [ ]
'testing': tests_require }, ext_modules=[libReQL], keywords='', license='Apache', long_description=long_description, name='libReQL', package_data={ }, tests_require=tests_require, url='https://github.com/grandquista/ReQL-Core', version='1.0.0', zip_safe=True )
}, extras_require={
random_line_split
parsertestcase.py
# # Walldo - A wallpaper downloader # Copyright (C) 2012 Fernando Castillo # # 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 2 # 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import unittest from walldo.parser import Parser; class ParserTestCase(unittest.TestCase): lines = ['<select class="select" style="margin: 0 2px 0 0; margin-top: 4px; float: left; width: 145px; max-width: 145px;" name="resolution" onChange="javascript:imgload(\'ithilien\', this,\'2949\')">'] expected = ['/wallpaper/7yz4ma1/2949_ithilien_1024x768.jpg'] def setUp(self): self.parser = Parser() def testParse(self):
current = self.parser.parse(self.lines, '1024x768') for i in range(len(current)): self.assertEquals(self.expected[i], current[i], 'Entry incorrect')
identifier_body
parsertestcase.py
# # Walldo - A wallpaper downloader # Copyright (C) 2012 Fernando Castillo # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License
# 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import unittest from walldo.parser import Parser; class ParserTestCase(unittest.TestCase): lines = ['<select class="select" style="margin: 0 2px 0 0; margin-top: 4px; float: left; width: 145px; max-width: 145px;" name="resolution" onChange="javascript:imgload(\'ithilien\', this,\'2949\')">'] expected = ['/wallpaper/7yz4ma1/2949_ithilien_1024x768.jpg'] def setUp(self): self.parser = Parser() def testParse(self): current = self.parser.parse(self.lines, '1024x768') for i in range(len(current)): self.assertEquals(self.expected[i], current[i], 'Entry incorrect')
# as published by the Free Software Foundation; either version 2 # 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
random_line_split
parsertestcase.py
# # Walldo - A wallpaper downloader # Copyright (C) 2012 Fernando Castillo # # 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 2 # 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import unittest from walldo.parser import Parser; class ParserTestCase(unittest.TestCase): lines = ['<select class="select" style="margin: 0 2px 0 0; margin-top: 4px; float: left; width: 145px; max-width: 145px;" name="resolution" onChange="javascript:imgload(\'ithilien\', this,\'2949\')">'] expected = ['/wallpaper/7yz4ma1/2949_ithilien_1024x768.jpg'] def setUp(self): self.parser = Parser() def testParse(self): current = self.parser.parse(self.lines, '1024x768') for i in range(len(current)):
self.assertEquals(self.expected[i], current[i], 'Entry incorrect')
conditional_block
parsertestcase.py
# # Walldo - A wallpaper downloader # Copyright (C) 2012 Fernando Castillo # # 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 2 # 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import unittest from walldo.parser import Parser; class ParserTestCase(unittest.TestCase): lines = ['<select class="select" style="margin: 0 2px 0 0; margin-top: 4px; float: left; width: 145px; max-width: 145px;" name="resolution" onChange="javascript:imgload(\'ithilien\', this,\'2949\')">'] expected = ['/wallpaper/7yz4ma1/2949_ithilien_1024x768.jpg'] def setUp(self): self.parser = Parser() def
(self): current = self.parser.parse(self.lines, '1024x768') for i in range(len(current)): self.assertEquals(self.expected[i], current[i], 'Entry incorrect')
testParse
identifier_name
taskbar_ui.js
(function ($) { /** * Move a block in the blocks table from one region to another via select list. * * This behavior is dependent on the tableDrag behavior, since it uses the * objects initialized in that behavior to update the row. */ Drupal.behaviors.taskbarUIDrag = { attach: function (context, settings) { // tableDrag is required and we should be on the Taskbar UI admin page. if (typeof Drupal.tableDrag == 'undefined' || typeof Drupal.tableDrag.items == 'undefined') { return; } var table = $('table#items'); var tableDrag = Drupal.tableDrag.items; // Get the items tableDrag object. // Add a handler for when a row is swapped, update empty regions. tableDrag.row.prototype.onSwap = function(swappedRow) { checkEmptyRegions(table, this); }; // A custom message for the blocks page specifically. Drupal.theme.tableDragChangedWarning = function () { return '<div class="messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t("The changes to these items will not be saved until the <em>Save items</em> button is clicked.") + '</div>'; }; // Add a handler so when a row is dropped, update fields dropped into new regions. tableDrag.onDrop = function() { dragObject = this; var regionRow = $(dragObject.rowObject.element).prevAll('tr.region-message').get(0); var regionName = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2'); var regionField = $('select.item-region-select', dragObject.rowObject.element); if ($('option[value=' + regionName + ']', regionField).length == 0) { alert(Drupal.t('The item cannot be placed in this region.')); // Simulate that there was a selected element change, so the row is put // back to from where the user tried to drag it. regionField.change(); } else if ($(dragObject.rowObject.element).prev('tr').is('.region-message')) { var weightField = $('select.item-weight', dragObject.rowObject.element); var oldRegionName = weightField[0].className.replace(/([^ ]+[ ]+)*item-weight-([^ ]+)([ ]+[^ ]+)*/, '$2'); if (!regionField.is('.item-region-'+ regionName)) { regionField.removeClass('item-region-' + oldRegionName).addClass('item-region-' + regionName); weightField.removeClass('item-weight-' + oldRegionName).addClass('item-weight-' + regionName); regionField.val(regionName); } } }; // Add the behavior to each region select list. $('select.item-region-select', context).once('item-region-select', function() { $(this).change(function(event) { // Make our new row and select field. var row = $(this).parents('tr:first'); var select = $(this); tableDrag.rowObject = new tableDrag.row(row); // Find the correct region and insert the row as the first in the region. $('tr.region-message', table).each(function() { if ($(this).is('.region-' + select[0].value + '-message')) { // Add the new row and remove the old one. $(this).after(row); // Manually update weights and restripe. tableDrag.updateFields(row.get(0)); tableDrag.rowObject.changed = true; if (tableDrag.oldRowElement) { $(tableDrag.oldRowElement).removeClass('drag-previous'); } tableDrag.oldRowElement = row.get(0); tableDrag.restripeTable(); tableDrag.rowObject.markChanged(); tableDrag.oldRowElement = row; $(row).addClass('drag-previous'); } }); // Modify empty regions with added or removed fields. checkEmptyRegions(table, row); // Remove focus from selectbox. select.get(0).blur(); }); $(this).addClass('itemregionselect-processed'); }); var checkEmptyRegions = function(table, rowObject) { $('tr.region-message', table).each(function() { // If the dragged row is in this region, but above the message row, swap it down one space. if ($(this).prev('tr').get(0) == rowObject.element)
// This region has become empty if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').size() == 0) { $(this).removeClass('region-populated').addClass('region-empty'); } // This region has become populated. else if ($(this).is('.region-empty')) { $(this).removeClass('region-empty').addClass('region-populated'); } }); }; } }; })(jQuery);
{ // Prevent a recursion problem when using the keyboard to move rows up. if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) { rowObject.swap('after', this); } }
conditional_block
taskbar_ui.js
(function ($) { /** * Move a block in the blocks table from one region to another via select list. * * This behavior is dependent on the tableDrag behavior, since it uses the * objects initialized in that behavior to update the row. */ Drupal.behaviors.taskbarUIDrag = { attach: function (context, settings) { // tableDrag is required and we should be on the Taskbar UI admin page. if (typeof Drupal.tableDrag == 'undefined' || typeof Drupal.tableDrag.items == 'undefined') { return; } var table = $('table#items'); var tableDrag = Drupal.tableDrag.items; // Get the items tableDrag object. // Add a handler for when a row is swapped, update empty regions. tableDrag.row.prototype.onSwap = function(swappedRow) { checkEmptyRegions(table, this); }; // A custom message for the blocks page specifically. Drupal.theme.tableDragChangedWarning = function () { return '<div class="messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t("The changes to these items will not be saved until the <em>Save items</em> button is clicked.") + '</div>'; }; // Add a handler so when a row is dropped, update fields dropped into new regions. tableDrag.onDrop = function() { dragObject = this; var regionRow = $(dragObject.rowObject.element).prevAll('tr.region-message').get(0); var regionName = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2'); var regionField = $('select.item-region-select', dragObject.rowObject.element); if ($('option[value=' + regionName + ']', regionField).length == 0) { alert(Drupal.t('The item cannot be placed in this region.')); // Simulate that there was a selected element change, so the row is put // back to from where the user tried to drag it. regionField.change(); } else if ($(dragObject.rowObject.element).prev('tr').is('.region-message')) { var weightField = $('select.item-weight', dragObject.rowObject.element); var oldRegionName = weightField[0].className.replace(/([^ ]+[ ]+)*item-weight-([^ ]+)([ ]+[^ ]+)*/, '$2'); if (!regionField.is('.item-region-'+ regionName)) { regionField.removeClass('item-region-' + oldRegionName).addClass('item-region-' + regionName); weightField.removeClass('item-weight-' + oldRegionName).addClass('item-weight-' + regionName); regionField.val(regionName); } }
// Add the behavior to each region select list. $('select.item-region-select', context).once('item-region-select', function() { $(this).change(function(event) { // Make our new row and select field. var row = $(this).parents('tr:first'); var select = $(this); tableDrag.rowObject = new tableDrag.row(row); // Find the correct region and insert the row as the first in the region. $('tr.region-message', table).each(function() { if ($(this).is('.region-' + select[0].value + '-message')) { // Add the new row and remove the old one. $(this).after(row); // Manually update weights and restripe. tableDrag.updateFields(row.get(0)); tableDrag.rowObject.changed = true; if (tableDrag.oldRowElement) { $(tableDrag.oldRowElement).removeClass('drag-previous'); } tableDrag.oldRowElement = row.get(0); tableDrag.restripeTable(); tableDrag.rowObject.markChanged(); tableDrag.oldRowElement = row; $(row).addClass('drag-previous'); } }); // Modify empty regions with added or removed fields. checkEmptyRegions(table, row); // Remove focus from selectbox. select.get(0).blur(); }); $(this).addClass('itemregionselect-processed'); }); var checkEmptyRegions = function(table, rowObject) { $('tr.region-message', table).each(function() { // If the dragged row is in this region, but above the message row, swap it down one space. if ($(this).prev('tr').get(0) == rowObject.element) { // Prevent a recursion problem when using the keyboard to move rows up. if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) { rowObject.swap('after', this); } } // This region has become empty if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').size() == 0) { $(this).removeClass('region-populated').addClass('region-empty'); } // This region has become populated. else if ($(this).is('.region-empty')) { $(this).removeClass('region-empty').addClass('region-populated'); } }); }; } }; })(jQuery);
};
random_line_split
hypothesis_testing_kolmogorov_smirnov_test_example.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function from pyspark import SparkContext # $example on$ from pyspark.mllib.stat import Statistics # $example off$ if __name__ == "__main__":
sc = SparkContext(appName="HypothesisTestingKolmogorovSmirnovTestExample") # $example on$ parallelData = sc.parallelize([0.1, 0.15, 0.2, 0.3, 0.25]) # run a KS test for the sample versus a standard normal distribution testResult = Statistics.kolmogorovSmirnovTest(parallelData, "norm", 0, 1) # summary of the test including the p-value, test statistic, and null hypothesis # if our p-value indicates significance, we can reject the null hypothesis # Note that the Scala functionality of calling Statistics.kolmogorovSmirnovTest with # a lambda to calculate the CDF is not made available in the Python API print(testResult) # $example off$ sc.stop()
conditional_block
hypothesis_testing_kolmogorov_smirnov_test_example.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function from pyspark import SparkContext # $example on$ from pyspark.mllib.stat import Statistics # $example off$ if __name__ == "__main__": sc = SparkContext(appName="HypothesisTestingKolmogorovSmirnovTestExample") # $example on$ parallelData = sc.parallelize([0.1, 0.15, 0.2, 0.3, 0.25])
# Note that the Scala functionality of calling Statistics.kolmogorovSmirnovTest with # a lambda to calculate the CDF is not made available in the Python API print(testResult) # $example off$ sc.stop()
# run a KS test for the sample versus a standard normal distribution testResult = Statistics.kolmogorovSmirnovTest(parallelData, "norm", 0, 1) # summary of the test including the p-value, test statistic, and null hypothesis # if our p-value indicates significance, we can reject the null hypothesis
random_line_split
vote-taker.componet.ts
import {Component} from '@angular/core'; import { HEROES } from './mock-heroes'; @Component({ selector: 'vote-taker', template: ` <h2>Should mankind colonize the Universe?</h2> <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3> <my-voter *ngFor="let voter of heroes" length=5 [name]="voter.name" (onVoted)="onVoted($event)"> </my-voter> ` }) export class VoteTakerComponent { public agreed = 0; public disagreed = 0; // public voters = ['Mr. IQ', 'Ms. Universe aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal', 'Bombasto']; public heroes = HEROES; public on
greed: boolean) { agreed ? this.agreed++ : this.disagreed++; } }
Voted(a
identifier_name
vote-taker.componet.ts
selector: 'vote-taker', template: ` <h2>Should mankind colonize the Universe?</h2> <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3> <my-voter *ngFor="let voter of heroes" length=5 [name]="voter.name" (onVoted)="onVoted($event)"> </my-voter> ` }) export class VoteTakerComponent { public agreed = 0; public disagreed = 0; // public voters = ['Mr. IQ', 'Ms. Universe aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal', 'Bombasto']; public heroes = HEROES; public onVoted(agreed: boolean) { agreed ? this.agreed++ : this.disagreed++; } }
import {Component} from '@angular/core'; import { HEROES } from './mock-heroes'; @Component({
random_line_split
vote-taker.componet.ts
import {Component} from '@angular/core'; import { HEROES } from './mock-heroes'; @Component({ selector: 'vote-taker', template: ` <h2>Should mankind colonize the Universe?</h2> <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3> <my-voter *ngFor="let voter of heroes" length=5 [name]="voter.name" (onVoted)="onVoted($event)"> </my-voter> ` }) export class VoteTakerComponent { public agreed = 0; public disagreed = 0; // public voters = ['Mr. IQ', 'Ms. Universe aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal', 'Bombasto']; public heroes = HEROES; public onVoted(agreed: boolean) {
agreed ? this.agreed++ : this.disagreed++; } }
identifier_body
minters.py
# -*- coding: utf-8 -*- # # This file is part of CERN Analysis Preservation Framework. # Copyright (C) 2018 CERN. # # CERN Analysis Preservation Framework 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 2 of the # License, or (at your option) any later version. # # CERN Analysis Preservation Framework 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 CERN Analysis Preservation Framework; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. # or submit itself to any jurisdiction. """PID minters for drafts.""" from __future__ import absolute_import, print_function import uuid from invenio_pidstore.models import PersistentIdentifier, PIDStatus def cap_deposit_minter(record_uuid, data): """Mint deposit's identifier.""" try: pid_value = data['_deposit']['id'] except KeyError: pid_value = uuid.uuid4().hex pid = PersistentIdentifier.create( 'depid',
object_uuid=record_uuid, status=PIDStatus.REGISTERED ) data['_deposit'] = { 'id': pid.pid_value, 'status': 'draft', } return pid
pid_value, object_type='rec',
random_line_split
minters.py
# -*- coding: utf-8 -*- # # This file is part of CERN Analysis Preservation Framework. # Copyright (C) 2018 CERN. # # CERN Analysis Preservation Framework 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 2 of the # License, or (at your option) any later version. # # CERN Analysis Preservation Framework 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 CERN Analysis Preservation Framework; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. # or submit itself to any jurisdiction. """PID minters for drafts.""" from __future__ import absolute_import, print_function import uuid from invenio_pidstore.models import PersistentIdentifier, PIDStatus def
(record_uuid, data): """Mint deposit's identifier.""" try: pid_value = data['_deposit']['id'] except KeyError: pid_value = uuid.uuid4().hex pid = PersistentIdentifier.create( 'depid', pid_value, object_type='rec', object_uuid=record_uuid, status=PIDStatus.REGISTERED ) data['_deposit'] = { 'id': pid.pid_value, 'status': 'draft', } return pid
cap_deposit_minter
identifier_name
minters.py
# -*- coding: utf-8 -*- # # This file is part of CERN Analysis Preservation Framework. # Copyright (C) 2018 CERN. # # CERN Analysis Preservation Framework 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 2 of the # License, or (at your option) any later version. # # CERN Analysis Preservation Framework 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 CERN Analysis Preservation Framework; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. # or submit itself to any jurisdiction. """PID minters for drafts.""" from __future__ import absolute_import, print_function import uuid from invenio_pidstore.models import PersistentIdentifier, PIDStatus def cap_deposit_minter(record_uuid, data):
"""Mint deposit's identifier.""" try: pid_value = data['_deposit']['id'] except KeyError: pid_value = uuid.uuid4().hex pid = PersistentIdentifier.create( 'depid', pid_value, object_type='rec', object_uuid=record_uuid, status=PIDStatus.REGISTERED ) data['_deposit'] = { 'id': pid.pid_value, 'status': 'draft', } return pid
identifier_body
widget_QTableView_edit_print_signal_when_data_changed.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table import sys from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant from PyQt5.QtWidgets import QApplication, QTableView class MyData: def __init__(self): self._num_rows = 3 self._num_columns = 2 self._data = [["hello" for j in range(self._num_columns)] for i in range(self._num_rows)] def get_num_rows(self): return self._num_rows def get_num_columns(self): return self._num_columns def get_data(self, row_index, column_index): value = self._data[row_index][column_index] return value def set_data(self, row_index, column_index, value): self._data[row_index][column_index] = value ############################################################################### class MyModel(QAbstractTableModel): def __init__(self, data, parent=None): super().__init__(parent) self._data = data # DON'T CALL THIS ATTRIBUTE "data", A QAbstractItemModel METHOD ALREADY HAVE THIS NAME (model.data(index, role)) !!! def rowCount(self, parent): return self._data.get_num_rows() def columnCount(self, parent): return self._data.get_num_columns() def data(self, index, role): if role == Qt.DisplayRole: return self._data.get_data(index.row(), index.column()) return QVariant() def setData(self, index, value, role): if role == Qt.EditRole: try: self._data.set_data(index.row(), index.column(), value) # The following line are necessary e.g. to dynamically update the QSortFilterProxyModel self.dataChanged.emit(index, index, [Qt.EditRole]) except Exception as e: print(e) return False return True def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled def changedCallback(): print("changed") if __name__ == '__main__': app = QApplication(sys.argv)
my_model = MyModel(data) my_model.dataChanged.connect(changedCallback) my_model.rowsInserted.connect(changedCallback) my_model.rowsRemoved.connect(changedCallback) table_view.setModel(my_model) table_view.show() # The mainloop of the application. The event handling starts from this point. # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead. exit_code = app.exec_() # The sys.exit() method ensures a clean exit. # The environment will be informed, how the application ended. sys.exit(exit_code)
data = MyData() table_view = QTableView()
random_line_split
widget_QTableView_edit_print_signal_when_data_changed.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table import sys from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant from PyQt5.QtWidgets import QApplication, QTableView class
: def __init__(self): self._num_rows = 3 self._num_columns = 2 self._data = [["hello" for j in range(self._num_columns)] for i in range(self._num_rows)] def get_num_rows(self): return self._num_rows def get_num_columns(self): return self._num_columns def get_data(self, row_index, column_index): value = self._data[row_index][column_index] return value def set_data(self, row_index, column_index, value): self._data[row_index][column_index] = value ############################################################################### class MyModel(QAbstractTableModel): def __init__(self, data, parent=None): super().__init__(parent) self._data = data # DON'T CALL THIS ATTRIBUTE "data", A QAbstractItemModel METHOD ALREADY HAVE THIS NAME (model.data(index, role)) !!! def rowCount(self, parent): return self._data.get_num_rows() def columnCount(self, parent): return self._data.get_num_columns() def data(self, index, role): if role == Qt.DisplayRole: return self._data.get_data(index.row(), index.column()) return QVariant() def setData(self, index, value, role): if role == Qt.EditRole: try: self._data.set_data(index.row(), index.column(), value) # The following line are necessary e.g. to dynamically update the QSortFilterProxyModel self.dataChanged.emit(index, index, [Qt.EditRole]) except Exception as e: print(e) return False return True def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled def changedCallback(): print("changed") if __name__ == '__main__': app = QApplication(sys.argv) data = MyData() table_view = QTableView() my_model = MyModel(data) my_model.dataChanged.connect(changedCallback) my_model.rowsInserted.connect(changedCallback) my_model.rowsRemoved.connect(changedCallback) table_view.setModel(my_model) table_view.show() # The mainloop of the application. The event handling starts from this point. # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead. exit_code = app.exec_() # The sys.exit() method ensures a clean exit. # The environment will be informed, how the application ended. sys.exit(exit_code)
MyData
identifier_name
widget_QTableView_edit_print_signal_when_data_changed.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table import sys from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant from PyQt5.QtWidgets import QApplication, QTableView class MyData: def __init__(self): self._num_rows = 3 self._num_columns = 2 self._data = [["hello" for j in range(self._num_columns)] for i in range(self._num_rows)] def get_num_rows(self): return self._num_rows def get_num_columns(self): return self._num_columns def get_data(self, row_index, column_index): value = self._data[row_index][column_index] return value def set_data(self, row_index, column_index, value): self._data[row_index][column_index] = value ############################################################################### class MyModel(QAbstractTableModel): def __init__(self, data, parent=None): super().__init__(parent) self._data = data # DON'T CALL THIS ATTRIBUTE "data", A QAbstractItemModel METHOD ALREADY HAVE THIS NAME (model.data(index, role)) !!! def rowCount(self, parent): return self._data.get_num_rows() def columnCount(self, parent): return self._data.get_num_columns() def data(self, index, role): if role == Qt.DisplayRole: return self._data.get_data(index.row(), index.column()) return QVariant() def setData(self, index, value, role): if role == Qt.EditRole: try: self._data.set_data(index.row(), index.column(), value) # The following line are necessary e.g. to dynamically update the QSortFilterProxyModel self.dataChanged.emit(index, index, [Qt.EditRole]) except Exception as e: print(e) return False return True def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled def changedCallback(): print("changed") if __name__ == '__main__':
app = QApplication(sys.argv) data = MyData() table_view = QTableView() my_model = MyModel(data) my_model.dataChanged.connect(changedCallback) my_model.rowsInserted.connect(changedCallback) my_model.rowsRemoved.connect(changedCallback) table_view.setModel(my_model) table_view.show() # The mainloop of the application. The event handling starts from this point. # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead. exit_code = app.exec_() # The sys.exit() method ensures a clean exit. # The environment will be informed, how the application ended. sys.exit(exit_code)
conditional_block
widget_QTableView_edit_print_signal_when_data_changed.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table import sys from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant from PyQt5.QtWidgets import QApplication, QTableView class MyData: def __init__(self): self._num_rows = 3 self._num_columns = 2 self._data = [["hello" for j in range(self._num_columns)] for i in range(self._num_rows)] def get_num_rows(self): return self._num_rows def get_num_columns(self): return self._num_columns def get_data(self, row_index, column_index): value = self._data[row_index][column_index] return value def set_data(self, row_index, column_index, value): self._data[row_index][column_index] = value ############################################################################### class MyModel(QAbstractTableModel): def __init__(self, data, parent=None): super().__init__(parent) self._data = data # DON'T CALL THIS ATTRIBUTE "data", A QAbstractItemModel METHOD ALREADY HAVE THIS NAME (model.data(index, role)) !!! def rowCount(self, parent): return self._data.get_num_rows() def columnCount(self, parent): return self._data.get_num_columns() def data(self, index, role): if role == Qt.DisplayRole: return self._data.get_data(index.row(), index.column()) return QVariant() def setData(self, index, value, role): if role == Qt.EditRole: try: self._data.set_data(index.row(), index.column(), value) # The following line are necessary e.g. to dynamically update the QSortFilterProxyModel self.dataChanged.emit(index, index, [Qt.EditRole]) except Exception as e: print(e) return False return True def flags(self, index):
def changedCallback(): print("changed") if __name__ == '__main__': app = QApplication(sys.argv) data = MyData() table_view = QTableView() my_model = MyModel(data) my_model.dataChanged.connect(changedCallback) my_model.rowsInserted.connect(changedCallback) my_model.rowsRemoved.connect(changedCallback) table_view.setModel(my_model) table_view.show() # The mainloop of the application. The event handling starts from this point. # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead. exit_code = app.exec_() # The sys.exit() method ensures a clean exit. # The environment will be informed, how the application ended. sys.exit(exit_code)
return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled
identifier_body
dlg_github_login_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/colin/dev/QCrash/forms/dlg_github_login.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from qcrash.qt import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(366, 248) Dialog.setMinimumSize(QtCore.QSize(350, 0)) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.lbl_html = QtWidgets.QLabel(Dialog) self.lbl_html.setObjectName("lbl_html") self.verticalLayout.addWidget(self.lbl_html) self.formLayout = QtWidgets.QFormLayout() self.formLayout.setContentsMargins(-1, 0, -1, -1) self.formLayout.setObjectName("formLayout") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setObjectName("label_2") self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label_2) self.le_username = QtWidgets.QLineEdit(Dialog) self.le_username.setObjectName("le_username") self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.le_username) self.label_3 = QtWidgets.QLabel(Dialog) self.label_3.setObjectName("label_3") self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_3) self.le_password = QtWidgets.QLineEdit(Dialog) self.le_password.setEchoMode(QtWidgets.QLineEdit.Password) self.le_password.setObjectName("le_password") self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.le_password) self.verticalLayout.addLayout(self.formLayout) self.cb_remember = QtWidgets.QCheckBox(Dialog) self.cb_remember.setObjectName("cb_remember") self.verticalLayout.addWidget(self.cb_remember) self.cb_remember_password = QtWidgets.QCheckBox(Dialog) self.cb_remember_password.setObjectName("cb_remember_password") self.verticalLayout.addWidget(self.cb_remember_password) self.bt_sign_in = QtWidgets.QPushButton(Dialog) self.bt_sign_in.setObjectName("bt_sign_in") self.verticalLayout.addWidget(self.bt_sign_in) self.retranslateUi(Dialog) self.cb_remember.toggled['bool'].connect(self.cb_remember_password.setEnabled) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog):
from . import qcrash_rc
_translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Sign in to github")) self.lbl_html.setText(_translate("Dialog", "<html><head/><body><p align=\"center\"><img src=\":/rc/GitHub-Mark.png\"/></p><p align=\"center\">Sign in to GitHub</p></body></html>")) self.label_2.setText(_translate("Dialog", "Username:")) self.label_3.setText(_translate("Dialog", "Password: ")) self.cb_remember.setText(_translate("Dialog", "Remember me")) self.cb_remember_password.setText(_translate("Dialog", "Remember password")) self.bt_sign_in.setText(_translate("Dialog", "Sign in"))
identifier_body
dlg_github_login_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/colin/dev/QCrash/forms/dlg_github_login.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from qcrash.qt import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def
(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(366, 248) Dialog.setMinimumSize(QtCore.QSize(350, 0)) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.lbl_html = QtWidgets.QLabel(Dialog) self.lbl_html.setObjectName("lbl_html") self.verticalLayout.addWidget(self.lbl_html) self.formLayout = QtWidgets.QFormLayout() self.formLayout.setContentsMargins(-1, 0, -1, -1) self.formLayout.setObjectName("formLayout") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setObjectName("label_2") self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label_2) self.le_username = QtWidgets.QLineEdit(Dialog) self.le_username.setObjectName("le_username") self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.le_username) self.label_3 = QtWidgets.QLabel(Dialog) self.label_3.setObjectName("label_3") self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_3) self.le_password = QtWidgets.QLineEdit(Dialog) self.le_password.setEchoMode(QtWidgets.QLineEdit.Password) self.le_password.setObjectName("le_password") self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.le_password) self.verticalLayout.addLayout(self.formLayout) self.cb_remember = QtWidgets.QCheckBox(Dialog) self.cb_remember.setObjectName("cb_remember") self.verticalLayout.addWidget(self.cb_remember) self.cb_remember_password = QtWidgets.QCheckBox(Dialog) self.cb_remember_password.setObjectName("cb_remember_password") self.verticalLayout.addWidget(self.cb_remember_password) self.bt_sign_in = QtWidgets.QPushButton(Dialog) self.bt_sign_in.setObjectName("bt_sign_in") self.verticalLayout.addWidget(self.bt_sign_in) self.retranslateUi(Dialog) self.cb_remember.toggled['bool'].connect(self.cb_remember_password.setEnabled) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Sign in to github")) self.lbl_html.setText(_translate("Dialog", "<html><head/><body><p align=\"center\"><img src=\":/rc/GitHub-Mark.png\"/></p><p align=\"center\">Sign in to GitHub</p></body></html>")) self.label_2.setText(_translate("Dialog", "Username:")) self.label_3.setText(_translate("Dialog", "Password: ")) self.cb_remember.setText(_translate("Dialog", "Remember me")) self.cb_remember_password.setText(_translate("Dialog", "Remember password")) self.bt_sign_in.setText(_translate("Dialog", "Sign in")) from . import qcrash_rc
setupUi
identifier_name
dlg_github_login_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/colin/dev/QCrash/forms/dlg_github_login.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost!
def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(366, 248) Dialog.setMinimumSize(QtCore.QSize(350, 0)) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.lbl_html = QtWidgets.QLabel(Dialog) self.lbl_html.setObjectName("lbl_html") self.verticalLayout.addWidget(self.lbl_html) self.formLayout = QtWidgets.QFormLayout() self.formLayout.setContentsMargins(-1, 0, -1, -1) self.formLayout.setObjectName("formLayout") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setObjectName("label_2") self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label_2) self.le_username = QtWidgets.QLineEdit(Dialog) self.le_username.setObjectName("le_username") self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.le_username) self.label_3 = QtWidgets.QLabel(Dialog) self.label_3.setObjectName("label_3") self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_3) self.le_password = QtWidgets.QLineEdit(Dialog) self.le_password.setEchoMode(QtWidgets.QLineEdit.Password) self.le_password.setObjectName("le_password") self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.le_password) self.verticalLayout.addLayout(self.formLayout) self.cb_remember = QtWidgets.QCheckBox(Dialog) self.cb_remember.setObjectName("cb_remember") self.verticalLayout.addWidget(self.cb_remember) self.cb_remember_password = QtWidgets.QCheckBox(Dialog) self.cb_remember_password.setObjectName("cb_remember_password") self.verticalLayout.addWidget(self.cb_remember_password) self.bt_sign_in = QtWidgets.QPushButton(Dialog) self.bt_sign_in.setObjectName("bt_sign_in") self.verticalLayout.addWidget(self.bt_sign_in) self.retranslateUi(Dialog) self.cb_remember.toggled['bool'].connect(self.cb_remember_password.setEnabled) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Sign in to github")) self.lbl_html.setText(_translate("Dialog", "<html><head/><body><p align=\"center\"><img src=\":/rc/GitHub-Mark.png\"/></p><p align=\"center\">Sign in to GitHub</p></body></html>")) self.label_2.setText(_translate("Dialog", "Username:")) self.label_3.setText(_translate("Dialog", "Password: ")) self.cb_remember.setText(_translate("Dialog", "Remember me")) self.cb_remember_password.setText(_translate("Dialog", "Remember password")) self.bt_sign_in.setText(_translate("Dialog", "Sign in")) from . import qcrash_rc
from qcrash.qt import QtCore, QtGui, QtWidgets class Ui_Dialog(object):
random_line_split
accounts.py
""" sentry.web.frontend.accounts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import itertools from django.contrib import messages from django.contrib.auth import login as login_user, authenticate from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.db import transaction from django.http import HttpResponseRedirect from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.utils import timezone from sudo.decorators import sudo_required from sentry import features from sentry.models import ( AuthProvider, LostPasswordHash, Organization, OrganizationMemberType, Project, Team, UserOption ) from sentry.plugins import plugins from sentry.web.decorators import login_required from sentry.web.forms.accounts import ( AccountSettingsForm, NotificationSettingsForm, AppearanceSettingsForm, RegistrationForm, RecoverPasswordForm, ChangePasswordRecoverForm, ProjectEmailOptionsForm) from sentry.web.helpers import render_to_response from sentry.utils.auth import get_auth_providers, get_login_redirect from sentry.utils.safe import safe_execute @csrf_protect @never_cache @transaction.atomic def register(request): from django.conf import settings if not (features.has('auth:register') or request.session.get('can_register')): return HttpResponseRedirect(reverse('sentry')) form = RegistrationForm(request.POST or None, captcha=bool(request.session.get('needs_captcha'))) if form.is_valid(): user = form.save() # TODO(dcramer): ideally this would be handled by a special view # specifically for organization registration if settings.SENTRY_SINGLE_ORGANIZATION: org = Organization.get_default() defaults = { 'has_global_access': True, 'type': OrganizationMemberType.MEMBER, } try: auth_provider = AuthProvider.objects.get( organization=org.id, ) except AuthProvider.DoesNotExist: pass else: defaults.update({ 'has_global_access': auth_provider.default_global_access, 'type': auth_provider.default_role, }) org.member_set.create( user=user, **defaults ) # can_register should only allow a single registration request.session.pop('can_register', None) # HACK: grab whatever the first backend is and assume it works user.backend = settings.AUTHENTICATION_BACKENDS[0] login_user(request, user) request.session.pop('needs_captcha', None) return login_redirect(request) elif request.POST and not request.session.get('needs_captcha'): request.session['needs_captcha'] = 1 form = RegistrationForm(request.POST or None, captcha=True) form.errors.pop('captcha', None) return render_to_response('sentry/register.html', { 'form': form, }, request) @login_required def login_redirect(request): login_url = get_login_redirect(request) return HttpResponseRedirect(login_url) def recover(request): form = RecoverPasswordForm(request.POST or None, captcha=bool(request.session.get('needs_captcha'))) if form.is_valid(): password_hash, created = LostPasswordHash.objects.get_or_create( user=form.cleaned_data['user'] ) if not password_hash.is_valid(): password_hash.date_added = timezone.now() password_hash.set_hash() password_hash.save() password_hash.send_recover_mail() request.session.pop('needs_captcha', None) return render_to_response('sentry/account/recover/sent.html', { 'email': password_hash.user.email, }, request) elif request.POST and not request.session.get('needs_captcha'): request.session['needs_captcha'] = 1 form = RecoverPasswordForm(request.POST or None, captcha=True) form.errors.pop('captcha', None) context = { 'form': form, } return render_to_response('sentry/account/recover/index.html', context, request) def recover_confirm(request, user_id, hash): try: password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash) if not password_hash.is_valid(): password_hash.delete() raise LostPasswordHash.DoesNotExist user = password_hash.user except LostPasswordHash.DoesNotExist: context = {} tpl = 'sentry/account/recover/failure.html' else: tpl = 'sentry/account/recover/confirm.html' if request.method == 'POST': form = ChangePasswordRecoverForm(request.POST) if form.is_valid(): user.set_password(form.cleaned_data['password']) user.save() # Ugly way of doing this, but Django requires the backend be set user = authenticate( username=user.username, password=form.cleaned_data['password'], ) login_user(request, user) password_hash.delete() return login_redirect(request) else: form = ChangePasswordRecoverForm() context = { 'form': form, } return render_to_response(tpl, context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def settings(request): form = AccountSettingsForm(request.user, request.POST or None, initial={ 'email': request.user.email, 'username': request.user.username, 'first_name': request.user.first_name, }) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'form': form, 'page': 'settings', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/settings.html', context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def appearance_settings(request): from django.conf import settings options = UserOption.objects.get_all_values(user=request.user, project=None) form = AppearanceSettingsForm(request.user, request.POST or None, initial={ 'language': options.get('language') or request.LANGUAGE_CODE, 'stacktrace_order': int(options.get('stacktrace_order', -1) or -1), 'timezone': options.get('timezone') or settings.SENTRY_DEFAULT_TIME_ZONE, }) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'form': form, 'page': 'appearance', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/appearance.html', context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic
settings_form = NotificationSettingsForm(request.user, request.POST or None) # TODO(dcramer): this is an extremely bad pattern and we need a more optimal # solution for rendering this (that ideally plays well with the org data) project_list = [] organization_list = Organization.objects.get_for_user( user=request.user, ) for organization in organization_list: team_list = Team.objects.get_for_user( user=request.user, organization=organization, ) for team in team_list: project_list.extend( Project.objects.get_for_user( user=request.user, team=team, ) ) project_forms = [ (project, ProjectEmailOptionsForm( project, request.user, request.POST or None, prefix='project-%s' % (project.id,) )) for project in sorted(project_list, key=lambda x: (x.team.name, x.name)) ] ext_forms = [] for plugin in plugins.all(): for form in safe_execute(plugin.get_notification_forms) or (): form = safe_execute(form, plugin, request.user, request.POST or None, prefix=plugin.slug) if not form: continue ext_forms.append(form) if request.POST: all_forms = list(itertools.chain( [settings_form], ext_forms, (f for _, f in project_forms) )) if all(f.is_valid() for f in all_forms): for form in all_forms: form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'settings_form': settings_form, 'project_forms': project_forms, 'ext_forms': ext_forms, 'page': 'notifications', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/notifications.html', context, request) @csrf_protect @never_cache @login_required def list_identities(request): from social_auth.models import UserSocialAuth identity_list = list(UserSocialAuth.objects.filter(user=request.user)) AUTH_PROVIDERS = get_auth_providers() context = csrf(request) context.update({ 'identity_list': identity_list, 'page': 'identities', 'AUTH_PROVIDERS': AUTH_PROVIDERS, }) return render_to_response('sentry/account/identities.html', context, request)
def notification_settings(request):
random_line_split
accounts.py
""" sentry.web.frontend.accounts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import itertools from django.contrib import messages from django.contrib.auth import login as login_user, authenticate from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.db import transaction from django.http import HttpResponseRedirect from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.utils import timezone from sudo.decorators import sudo_required from sentry import features from sentry.models import ( AuthProvider, LostPasswordHash, Organization, OrganizationMemberType, Project, Team, UserOption ) from sentry.plugins import plugins from sentry.web.decorators import login_required from sentry.web.forms.accounts import ( AccountSettingsForm, NotificationSettingsForm, AppearanceSettingsForm, RegistrationForm, RecoverPasswordForm, ChangePasswordRecoverForm, ProjectEmailOptionsForm) from sentry.web.helpers import render_to_response from sentry.utils.auth import get_auth_providers, get_login_redirect from sentry.utils.safe import safe_execute @csrf_protect @never_cache @transaction.atomic def register(request): from django.conf import settings if not (features.has('auth:register') or request.session.get('can_register')): return HttpResponseRedirect(reverse('sentry')) form = RegistrationForm(request.POST or None, captcha=bool(request.session.get('needs_captcha'))) if form.is_valid(): user = form.save() # TODO(dcramer): ideally this would be handled by a special view # specifically for organization registration if settings.SENTRY_SINGLE_ORGANIZATION: org = Organization.get_default() defaults = { 'has_global_access': True, 'type': OrganizationMemberType.MEMBER, } try: auth_provider = AuthProvider.objects.get( organization=org.id, ) except AuthProvider.DoesNotExist: pass else: defaults.update({ 'has_global_access': auth_provider.default_global_access, 'type': auth_provider.default_role, }) org.member_set.create( user=user, **defaults ) # can_register should only allow a single registration request.session.pop('can_register', None) # HACK: grab whatever the first backend is and assume it works user.backend = settings.AUTHENTICATION_BACKENDS[0] login_user(request, user) request.session.pop('needs_captcha', None) return login_redirect(request) elif request.POST and not request.session.get('needs_captcha'): request.session['needs_captcha'] = 1 form = RegistrationForm(request.POST or None, captcha=True) form.errors.pop('captcha', None) return render_to_response('sentry/register.html', { 'form': form, }, request) @login_required def login_redirect(request): login_url = get_login_redirect(request) return HttpResponseRedirect(login_url) def recover(request): form = RecoverPasswordForm(request.POST or None, captcha=bool(request.session.get('needs_captcha'))) if form.is_valid(): password_hash, created = LostPasswordHash.objects.get_or_create( user=form.cleaned_data['user'] ) if not password_hash.is_valid(): password_hash.date_added = timezone.now() password_hash.set_hash() password_hash.save() password_hash.send_recover_mail() request.session.pop('needs_captcha', None) return render_to_response('sentry/account/recover/sent.html', { 'email': password_hash.user.email, }, request) elif request.POST and not request.session.get('needs_captcha'): request.session['needs_captcha'] = 1 form = RecoverPasswordForm(request.POST or None, captcha=True) form.errors.pop('captcha', None) context = { 'form': form, } return render_to_response('sentry/account/recover/index.html', context, request) def recover_confirm(request, user_id, hash): try: password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash) if not password_hash.is_valid(): password_hash.delete() raise LostPasswordHash.DoesNotExist user = password_hash.user except LostPasswordHash.DoesNotExist: context = {} tpl = 'sentry/account/recover/failure.html' else: tpl = 'sentry/account/recover/confirm.html' if request.method == 'POST': form = ChangePasswordRecoverForm(request.POST) if form.is_valid():
else: form = ChangePasswordRecoverForm() context = { 'form': form, } return render_to_response(tpl, context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def settings(request): form = AccountSettingsForm(request.user, request.POST or None, initial={ 'email': request.user.email, 'username': request.user.username, 'first_name': request.user.first_name, }) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'form': form, 'page': 'settings', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/settings.html', context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def appearance_settings(request): from django.conf import settings options = UserOption.objects.get_all_values(user=request.user, project=None) form = AppearanceSettingsForm(request.user, request.POST or None, initial={ 'language': options.get('language') or request.LANGUAGE_CODE, 'stacktrace_order': int(options.get('stacktrace_order', -1) or -1), 'timezone': options.get('timezone') or settings.SENTRY_DEFAULT_TIME_ZONE, }) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'form': form, 'page': 'appearance', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/appearance.html', context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def notification_settings(request): settings_form = NotificationSettingsForm(request.user, request.POST or None) # TODO(dcramer): this is an extremely bad pattern and we need a more optimal # solution for rendering this (that ideally plays well with the org data) project_list = [] organization_list = Organization.objects.get_for_user( user=request.user, ) for organization in organization_list: team_list = Team.objects.get_for_user( user=request.user, organization=organization, ) for team in team_list: project_list.extend( Project.objects.get_for_user( user=request.user, team=team, ) ) project_forms = [ (project, ProjectEmailOptionsForm( project, request.user, request.POST or None, prefix='project-%s' % (project.id,) )) for project in sorted(project_list, key=lambda x: (x.team.name, x.name)) ] ext_forms = [] for plugin in plugins.all(): for form in safe_execute(plugin.get_notification_forms) or (): form = safe_execute(form, plugin, request.user, request.POST or None, prefix=plugin.slug) if not form: continue ext_forms.append(form) if request.POST: all_forms = list(itertools.chain( [settings_form], ext_forms, (f for _, f in project_forms) )) if all(f.is_valid() for f in all_forms): for form in all_forms: form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'settings_form': settings_form, 'project_forms': project_forms, 'ext_forms': ext_forms, 'page': 'notifications', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/notifications.html', context, request) @csrf_protect @never_cache @login_required def list_identities(request): from social_auth.models import UserSocialAuth identity_list = list(UserSocialAuth.objects.filter(user=request.user)) AUTH_PROVIDERS = get_auth_providers() context = csrf(request) context.update({ 'identity_list': identity_list, 'page': 'identities', 'AUTH_PROVIDERS': AUTH_PROVIDERS, }) return render_to_response('sentry/account/identities.html', context, request)
user.set_password(form.cleaned_data['password']) user.save() # Ugly way of doing this, but Django requires the backend be set user = authenticate( username=user.username, password=form.cleaned_data['password'], ) login_user(request, user) password_hash.delete() return login_redirect(request)
conditional_block
accounts.py
""" sentry.web.frontend.accounts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import itertools from django.contrib import messages from django.contrib.auth import login as login_user, authenticate from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.db import transaction from django.http import HttpResponseRedirect from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.utils import timezone from sudo.decorators import sudo_required from sentry import features from sentry.models import ( AuthProvider, LostPasswordHash, Organization, OrganizationMemberType, Project, Team, UserOption ) from sentry.plugins import plugins from sentry.web.decorators import login_required from sentry.web.forms.accounts import ( AccountSettingsForm, NotificationSettingsForm, AppearanceSettingsForm, RegistrationForm, RecoverPasswordForm, ChangePasswordRecoverForm, ProjectEmailOptionsForm) from sentry.web.helpers import render_to_response from sentry.utils.auth import get_auth_providers, get_login_redirect from sentry.utils.safe import safe_execute @csrf_protect @never_cache @transaction.atomic def register(request): from django.conf import settings if not (features.has('auth:register') or request.session.get('can_register')): return HttpResponseRedirect(reverse('sentry')) form = RegistrationForm(request.POST or None, captcha=bool(request.session.get('needs_captcha'))) if form.is_valid(): user = form.save() # TODO(dcramer): ideally this would be handled by a special view # specifically for organization registration if settings.SENTRY_SINGLE_ORGANIZATION: org = Organization.get_default() defaults = { 'has_global_access': True, 'type': OrganizationMemberType.MEMBER, } try: auth_provider = AuthProvider.objects.get( organization=org.id, ) except AuthProvider.DoesNotExist: pass else: defaults.update({ 'has_global_access': auth_provider.default_global_access, 'type': auth_provider.default_role, }) org.member_set.create( user=user, **defaults ) # can_register should only allow a single registration request.session.pop('can_register', None) # HACK: grab whatever the first backend is and assume it works user.backend = settings.AUTHENTICATION_BACKENDS[0] login_user(request, user) request.session.pop('needs_captcha', None) return login_redirect(request) elif request.POST and not request.session.get('needs_captcha'): request.session['needs_captcha'] = 1 form = RegistrationForm(request.POST or None, captcha=True) form.errors.pop('captcha', None) return render_to_response('sentry/register.html', { 'form': form, }, request) @login_required def login_redirect(request): login_url = get_login_redirect(request) return HttpResponseRedirect(login_url) def recover(request): form = RecoverPasswordForm(request.POST or None, captcha=bool(request.session.get('needs_captcha'))) if form.is_valid(): password_hash, created = LostPasswordHash.objects.get_or_create( user=form.cleaned_data['user'] ) if not password_hash.is_valid(): password_hash.date_added = timezone.now() password_hash.set_hash() password_hash.save() password_hash.send_recover_mail() request.session.pop('needs_captcha', None) return render_to_response('sentry/account/recover/sent.html', { 'email': password_hash.user.email, }, request) elif request.POST and not request.session.get('needs_captcha'): request.session['needs_captcha'] = 1 form = RecoverPasswordForm(request.POST or None, captcha=True) form.errors.pop('captcha', None) context = { 'form': form, } return render_to_response('sentry/account/recover/index.html', context, request) def recover_confirm(request, user_id, hash):
@csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def settings(request): form = AccountSettingsForm(request.user, request.POST or None, initial={ 'email': request.user.email, 'username': request.user.username, 'first_name': request.user.first_name, }) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'form': form, 'page': 'settings', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/settings.html', context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def appearance_settings(request): from django.conf import settings options = UserOption.objects.get_all_values(user=request.user, project=None) form = AppearanceSettingsForm(request.user, request.POST or None, initial={ 'language': options.get('language') or request.LANGUAGE_CODE, 'stacktrace_order': int(options.get('stacktrace_order', -1) or -1), 'timezone': options.get('timezone') or settings.SENTRY_DEFAULT_TIME_ZONE, }) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'form': form, 'page': 'appearance', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/appearance.html', context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def notification_settings(request): settings_form = NotificationSettingsForm(request.user, request.POST or None) # TODO(dcramer): this is an extremely bad pattern and we need a more optimal # solution for rendering this (that ideally plays well with the org data) project_list = [] organization_list = Organization.objects.get_for_user( user=request.user, ) for organization in organization_list: team_list = Team.objects.get_for_user( user=request.user, organization=organization, ) for team in team_list: project_list.extend( Project.objects.get_for_user( user=request.user, team=team, ) ) project_forms = [ (project, ProjectEmailOptionsForm( project, request.user, request.POST or None, prefix='project-%s' % (project.id,) )) for project in sorted(project_list, key=lambda x: (x.team.name, x.name)) ] ext_forms = [] for plugin in plugins.all(): for form in safe_execute(plugin.get_notification_forms) or (): form = safe_execute(form, plugin, request.user, request.POST or None, prefix=plugin.slug) if not form: continue ext_forms.append(form) if request.POST: all_forms = list(itertools.chain( [settings_form], ext_forms, (f for _, f in project_forms) )) if all(f.is_valid() for f in all_forms): for form in all_forms: form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'settings_form': settings_form, 'project_forms': project_forms, 'ext_forms': ext_forms, 'page': 'notifications', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/notifications.html', context, request) @csrf_protect @never_cache @login_required def list_identities(request): from social_auth.models import UserSocialAuth identity_list = list(UserSocialAuth.objects.filter(user=request.user)) AUTH_PROVIDERS = get_auth_providers() context = csrf(request) context.update({ 'identity_list': identity_list, 'page': 'identities', 'AUTH_PROVIDERS': AUTH_PROVIDERS, }) return render_to_response('sentry/account/identities.html', context, request)
try: password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash) if not password_hash.is_valid(): password_hash.delete() raise LostPasswordHash.DoesNotExist user = password_hash.user except LostPasswordHash.DoesNotExist: context = {} tpl = 'sentry/account/recover/failure.html' else: tpl = 'sentry/account/recover/confirm.html' if request.method == 'POST': form = ChangePasswordRecoverForm(request.POST) if form.is_valid(): user.set_password(form.cleaned_data['password']) user.save() # Ugly way of doing this, but Django requires the backend be set user = authenticate( username=user.username, password=form.cleaned_data['password'], ) login_user(request, user) password_hash.delete() return login_redirect(request) else: form = ChangePasswordRecoverForm() context = { 'form': form, } return render_to_response(tpl, context, request)
identifier_body
accounts.py
""" sentry.web.frontend.accounts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import itertools from django.contrib import messages from django.contrib.auth import login as login_user, authenticate from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.db import transaction from django.http import HttpResponseRedirect from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.utils import timezone from sudo.decorators import sudo_required from sentry import features from sentry.models import ( AuthProvider, LostPasswordHash, Organization, OrganizationMemberType, Project, Team, UserOption ) from sentry.plugins import plugins from sentry.web.decorators import login_required from sentry.web.forms.accounts import ( AccountSettingsForm, NotificationSettingsForm, AppearanceSettingsForm, RegistrationForm, RecoverPasswordForm, ChangePasswordRecoverForm, ProjectEmailOptionsForm) from sentry.web.helpers import render_to_response from sentry.utils.auth import get_auth_providers, get_login_redirect from sentry.utils.safe import safe_execute @csrf_protect @never_cache @transaction.atomic def register(request): from django.conf import settings if not (features.has('auth:register') or request.session.get('can_register')): return HttpResponseRedirect(reverse('sentry')) form = RegistrationForm(request.POST or None, captcha=bool(request.session.get('needs_captcha'))) if form.is_valid(): user = form.save() # TODO(dcramer): ideally this would be handled by a special view # specifically for organization registration if settings.SENTRY_SINGLE_ORGANIZATION: org = Organization.get_default() defaults = { 'has_global_access': True, 'type': OrganizationMemberType.MEMBER, } try: auth_provider = AuthProvider.objects.get( organization=org.id, ) except AuthProvider.DoesNotExist: pass else: defaults.update({ 'has_global_access': auth_provider.default_global_access, 'type': auth_provider.default_role, }) org.member_set.create( user=user, **defaults ) # can_register should only allow a single registration request.session.pop('can_register', None) # HACK: grab whatever the first backend is and assume it works user.backend = settings.AUTHENTICATION_BACKENDS[0] login_user(request, user) request.session.pop('needs_captcha', None) return login_redirect(request) elif request.POST and not request.session.get('needs_captcha'): request.session['needs_captcha'] = 1 form = RegistrationForm(request.POST or None, captcha=True) form.errors.pop('captcha', None) return render_to_response('sentry/register.html', { 'form': form, }, request) @login_required def
(request): login_url = get_login_redirect(request) return HttpResponseRedirect(login_url) def recover(request): form = RecoverPasswordForm(request.POST or None, captcha=bool(request.session.get('needs_captcha'))) if form.is_valid(): password_hash, created = LostPasswordHash.objects.get_or_create( user=form.cleaned_data['user'] ) if not password_hash.is_valid(): password_hash.date_added = timezone.now() password_hash.set_hash() password_hash.save() password_hash.send_recover_mail() request.session.pop('needs_captcha', None) return render_to_response('sentry/account/recover/sent.html', { 'email': password_hash.user.email, }, request) elif request.POST and not request.session.get('needs_captcha'): request.session['needs_captcha'] = 1 form = RecoverPasswordForm(request.POST or None, captcha=True) form.errors.pop('captcha', None) context = { 'form': form, } return render_to_response('sentry/account/recover/index.html', context, request) def recover_confirm(request, user_id, hash): try: password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash) if not password_hash.is_valid(): password_hash.delete() raise LostPasswordHash.DoesNotExist user = password_hash.user except LostPasswordHash.DoesNotExist: context = {} tpl = 'sentry/account/recover/failure.html' else: tpl = 'sentry/account/recover/confirm.html' if request.method == 'POST': form = ChangePasswordRecoverForm(request.POST) if form.is_valid(): user.set_password(form.cleaned_data['password']) user.save() # Ugly way of doing this, but Django requires the backend be set user = authenticate( username=user.username, password=form.cleaned_data['password'], ) login_user(request, user) password_hash.delete() return login_redirect(request) else: form = ChangePasswordRecoverForm() context = { 'form': form, } return render_to_response(tpl, context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def settings(request): form = AccountSettingsForm(request.user, request.POST or None, initial={ 'email': request.user.email, 'username': request.user.username, 'first_name': request.user.first_name, }) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'form': form, 'page': 'settings', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/settings.html', context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def appearance_settings(request): from django.conf import settings options = UserOption.objects.get_all_values(user=request.user, project=None) form = AppearanceSettingsForm(request.user, request.POST or None, initial={ 'language': options.get('language') or request.LANGUAGE_CODE, 'stacktrace_order': int(options.get('stacktrace_order', -1) or -1), 'timezone': options.get('timezone') or settings.SENTRY_DEFAULT_TIME_ZONE, }) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'form': form, 'page': 'appearance', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/appearance.html', context, request) @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic def notification_settings(request): settings_form = NotificationSettingsForm(request.user, request.POST or None) # TODO(dcramer): this is an extremely bad pattern and we need a more optimal # solution for rendering this (that ideally plays well with the org data) project_list = [] organization_list = Organization.objects.get_for_user( user=request.user, ) for organization in organization_list: team_list = Team.objects.get_for_user( user=request.user, organization=organization, ) for team in team_list: project_list.extend( Project.objects.get_for_user( user=request.user, team=team, ) ) project_forms = [ (project, ProjectEmailOptionsForm( project, request.user, request.POST or None, prefix='project-%s' % (project.id,) )) for project in sorted(project_list, key=lambda x: (x.team.name, x.name)) ] ext_forms = [] for plugin in plugins.all(): for form in safe_execute(plugin.get_notification_forms) or (): form = safe_execute(form, plugin, request.user, request.POST or None, prefix=plugin.slug) if not form: continue ext_forms.append(form) if request.POST: all_forms = list(itertools.chain( [settings_form], ext_forms, (f for _, f in project_forms) )) if all(f.is_valid() for f in all_forms): for form in all_forms: form.save() messages.add_message(request, messages.SUCCESS, 'Your settings were saved.') return HttpResponseRedirect(request.path) context = csrf(request) context.update({ 'settings_form': settings_form, 'project_forms': project_forms, 'ext_forms': ext_forms, 'page': 'notifications', 'AUTH_PROVIDERS': get_auth_providers(), }) return render_to_response('sentry/account/notifications.html', context, request) @csrf_protect @never_cache @login_required def list_identities(request): from social_auth.models import UserSocialAuth identity_list = list(UserSocialAuth.objects.filter(user=request.user)) AUTH_PROVIDERS = get_auth_providers() context = csrf(request) context.update({ 'identity_list': identity_list, 'page': 'identities', 'AUTH_PROVIDERS': AUTH_PROVIDERS, }) return render_to_response('sentry/account/identities.html', context, request)
login_redirect
identifier_name
mod.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/. mod bindings; use std::{collections::HashMap, ffi::CString, io}; use log::Record; use crate::stratis::{StratisError, StratisResult}; fn serialize_pairs(pairs: HashMap<String, String>) -> String
/// Notify systemd that a daemon has started. #[allow(clippy::implicit_hasher)] pub fn notify(unset_variable: bool, key_value_pairs: HashMap<String, String>) -> StratisResult<()> { let serialized_pairs = serialize_pairs(key_value_pairs); let cstring = CString::new(serialized_pairs)?; let ret = unsafe { bindings::sd_notify(libc::c_int::from(unset_variable), cstring.as_ptr()) }; if ret < 0 { Err(StratisError::Io(io::Error::from_raw_os_error(-ret))) } else { Ok(()) } } /// Send a message to the system log generated from the Rust log crate Record input. pub fn syslog(record: &Record<'_>) { let cstring = match CString::new(record.args().to_string()) { Ok(s) => s, Err(_) => return, }; unsafe { bindings::syslog(record.level() as libc::c_int, cstring.as_ptr()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_key_value_pair_serialization() { let mut hash_map = HashMap::new(); hash_map.insert("READY".to_string(), "1".to_string()); assert_eq!("READY=1\n".to_string(), serialize_pairs(hash_map)); } }
{ pairs .iter() .map(|(key, value)| format!("{}={}", key, value)) .fold(String::new(), |mut string, key_value_pair| { string += key_value_pair.as_str(); string += "\n"; string }) }
identifier_body
mod.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/. mod bindings; use std::{collections::HashMap, ffi::CString, io};
use log::Record; use crate::stratis::{StratisError, StratisResult}; fn serialize_pairs(pairs: HashMap<String, String>) -> String { pairs .iter() .map(|(key, value)| format!("{}={}", key, value)) .fold(String::new(), |mut string, key_value_pair| { string += key_value_pair.as_str(); string += "\n"; string }) } /// Notify systemd that a daemon has started. #[allow(clippy::implicit_hasher)] pub fn notify(unset_variable: bool, key_value_pairs: HashMap<String, String>) -> StratisResult<()> { let serialized_pairs = serialize_pairs(key_value_pairs); let cstring = CString::new(serialized_pairs)?; let ret = unsafe { bindings::sd_notify(libc::c_int::from(unset_variable), cstring.as_ptr()) }; if ret < 0 { Err(StratisError::Io(io::Error::from_raw_os_error(-ret))) } else { Ok(()) } } /// Send a message to the system log generated from the Rust log crate Record input. pub fn syslog(record: &Record<'_>) { let cstring = match CString::new(record.args().to_string()) { Ok(s) => s, Err(_) => return, }; unsafe { bindings::syslog(record.level() as libc::c_int, cstring.as_ptr()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_key_value_pair_serialization() { let mut hash_map = HashMap::new(); hash_map.insert("READY".to_string(), "1".to_string()); assert_eq!("READY=1\n".to_string(), serialize_pairs(hash_map)); } }
random_line_split
mod.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/. mod bindings; use std::{collections::HashMap, ffi::CString, io}; use log::Record; use crate::stratis::{StratisError, StratisResult}; fn
(pairs: HashMap<String, String>) -> String { pairs .iter() .map(|(key, value)| format!("{}={}", key, value)) .fold(String::new(), |mut string, key_value_pair| { string += key_value_pair.as_str(); string += "\n"; string }) } /// Notify systemd that a daemon has started. #[allow(clippy::implicit_hasher)] pub fn notify(unset_variable: bool, key_value_pairs: HashMap<String, String>) -> StratisResult<()> { let serialized_pairs = serialize_pairs(key_value_pairs); let cstring = CString::new(serialized_pairs)?; let ret = unsafe { bindings::sd_notify(libc::c_int::from(unset_variable), cstring.as_ptr()) }; if ret < 0 { Err(StratisError::Io(io::Error::from_raw_os_error(-ret))) } else { Ok(()) } } /// Send a message to the system log generated from the Rust log crate Record input. pub fn syslog(record: &Record<'_>) { let cstring = match CString::new(record.args().to_string()) { Ok(s) => s, Err(_) => return, }; unsafe { bindings::syslog(record.level() as libc::c_int, cstring.as_ptr()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_key_value_pair_serialization() { let mut hash_map = HashMap::new(); hash_map.insert("READY".to_string(), "1".to_string()); assert_eq!("READY=1\n".to_string(), serialize_pairs(hash_map)); } }
serialize_pairs
identifier_name
message.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress}; use app_units::Au; use euclid::{Point2D, Rect}; use gfx_traits::Epoch; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use metrics::PaintTimeMetrics; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use profile_traits::mem::ReportsChan; use rpc::LayoutRPC; use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg}; use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData}; use script_traits::Painter; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; use servo_channel::{Receiver, Sender}; use servo_url::ServoUrl; use std::sync::Arc; use style::context::QuirksMode; use style::properties::PropertyId; use style::selector_parser::PseudoElement; use style::stylesheets::Stylesheet; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. The second stylesheet is the /// insertion point (if it exists, the sheet needs to be inserted before /// it). AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>), /// Removes a stylesheet from the document. RemoveStylesheet(ServoArc<Stylesheet>), /// Change the quirks mode. SetQuirksMode(QuirksMode), /// Requests a reflow. Reflow(ScriptReflow), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout thread render the next frame of all animations. TickAnimations, /// Updates layout's timer for animation testing from script. /// /// The inner field is the number of *milliseconds* to advance, and the bool /// field is whether animations should be force-ticked. AdvanceClockMs(i32, bool), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapStyleAndLayoutData(OpaqueStyleAndLayoutData), /// Requests that the layout thread measure its memory usage. The resulting reports are sent back /// via the supplied channel. CollectReports(ReportsChan), /// Requests that the layout thread enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout thread immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow, /// Get the last epoch counter for this layout thread. GetCurrentEpoch(IpcSender<Epoch>), /// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending; /// false otherwise). GetWebFontLoadState(IpcSender<bool>), /// Creates a new layout thread. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutThread(NewLayoutThreadInfo), /// Set the final Url. SetFinalUrl(ServoUrl), /// Tells layout about the new scrolling offsets of each scrollable stacking context. SetScrollStates(Vec<ScrollState>), /// Tells layout about a single new scrolling offset from the script. The rest will /// remain untouched and layout won't forward this back to script. UpdateScrollStateFromScript(ScrollState), /// Tells layout that script has added some paint worklet modules. RegisterPaint(Atom, Vec<Atom>, Box<Painter>), /// Send to layout the precise time when the navigation started. SetNavigationStart(u64), } #[derive(Debug, PartialEq)] pub enum NodesFromPointQueryType { All, Topmost, } #[derive(Debug, PartialEq)] pub enum QueryMsg { ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeScrollIdQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), NodeScrollGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId), OffsetParentQuery(TrustedNodeAddress), StyleQuery(TrustedNodeAddress), TextIndexQuery(TrustedNodeAddress, Point2D<f32>), NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType), ElementInnerTextQuery(TrustedNodeAddress), } /// Any query to perform with this reflow. #[derive(Debug, PartialEq)] pub enum ReflowGoal { Full, TickAnimations, LayoutQuery(QueryMsg, u64), } impl ReflowGoal { /// Returns true if the given ReflowQuery needs a full, up-to-date display list to /// be present or false if it only needs stacking-relative positions. pub fn needs_display_list(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } /// Returns true if the given ReflowQuery needs its display list send to WebRender or /// false if a layout_thread display list is sufficient. pub fn needs_display(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } } /// Information needed for a reflow. pub struct Reflow { /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information derived from a layout pass that needs to be returned to the script thread. #[derive(Default)] pub struct ReflowComplete { /// The list of images that were encountered that are in progress. pub pending_images: Vec<PendingImage>, /// The list of nodes that initiated a CSS transition. pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>, } /// Information needed for a script-initiated reflow. pub struct ScriptReflow { /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document: TrustedNodeAddress, /// Whether the document's stylesheets have changed since the last script reflow. pub stylesheets_changed: bool, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<ReflowComplete>, /// The goal of this reflow. pub reflow_goal: ReflowGoal, /// The number of objects in the dom #10110 pub dom_count: u32, } pub struct
{ pub id: PipelineId, pub url: ServoUrl, pub is_parent: bool, pub layout_pair: (Sender<Msg>, Receiver<Msg>), pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: IpcSender<ConstellationMsg>, pub script_chan: IpcSender<ConstellationControlMsg>, pub image_cache: Arc<ImageCache>, pub content_process_shutdown_chan: Option<IpcSender<()>>, pub layout_threads: usize, pub paint_time_metrics: PaintTimeMetrics, }
NewLayoutThreadInfo
identifier_name
message.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress}; use app_units::Au; use euclid::{Point2D, Rect}; use gfx_traits::Epoch; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use metrics::PaintTimeMetrics; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use profile_traits::mem::ReportsChan; use rpc::LayoutRPC; use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg};
use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData}; use script_traits::Painter; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; use servo_channel::{Receiver, Sender}; use servo_url::ServoUrl; use std::sync::Arc; use style::context::QuirksMode; use style::properties::PropertyId; use style::selector_parser::PseudoElement; use style::stylesheets::Stylesheet; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. The second stylesheet is the /// insertion point (if it exists, the sheet needs to be inserted before /// it). AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>), /// Removes a stylesheet from the document. RemoveStylesheet(ServoArc<Stylesheet>), /// Change the quirks mode. SetQuirksMode(QuirksMode), /// Requests a reflow. Reflow(ScriptReflow), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout thread render the next frame of all animations. TickAnimations, /// Updates layout's timer for animation testing from script. /// /// The inner field is the number of *milliseconds* to advance, and the bool /// field is whether animations should be force-ticked. AdvanceClockMs(i32, bool), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapStyleAndLayoutData(OpaqueStyleAndLayoutData), /// Requests that the layout thread measure its memory usage. The resulting reports are sent back /// via the supplied channel. CollectReports(ReportsChan), /// Requests that the layout thread enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout thread immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow, /// Get the last epoch counter for this layout thread. GetCurrentEpoch(IpcSender<Epoch>), /// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending; /// false otherwise). GetWebFontLoadState(IpcSender<bool>), /// Creates a new layout thread. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutThread(NewLayoutThreadInfo), /// Set the final Url. SetFinalUrl(ServoUrl), /// Tells layout about the new scrolling offsets of each scrollable stacking context. SetScrollStates(Vec<ScrollState>), /// Tells layout about a single new scrolling offset from the script. The rest will /// remain untouched and layout won't forward this back to script. UpdateScrollStateFromScript(ScrollState), /// Tells layout that script has added some paint worklet modules. RegisterPaint(Atom, Vec<Atom>, Box<Painter>), /// Send to layout the precise time when the navigation started. SetNavigationStart(u64), } #[derive(Debug, PartialEq)] pub enum NodesFromPointQueryType { All, Topmost, } #[derive(Debug, PartialEq)] pub enum QueryMsg { ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeScrollIdQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), NodeScrollGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId), OffsetParentQuery(TrustedNodeAddress), StyleQuery(TrustedNodeAddress), TextIndexQuery(TrustedNodeAddress, Point2D<f32>), NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType), ElementInnerTextQuery(TrustedNodeAddress), } /// Any query to perform with this reflow. #[derive(Debug, PartialEq)] pub enum ReflowGoal { Full, TickAnimations, LayoutQuery(QueryMsg, u64), } impl ReflowGoal { /// Returns true if the given ReflowQuery needs a full, up-to-date display list to /// be present or false if it only needs stacking-relative positions. pub fn needs_display_list(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } /// Returns true if the given ReflowQuery needs its display list send to WebRender or /// false if a layout_thread display list is sufficient. pub fn needs_display(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } } /// Information needed for a reflow. pub struct Reflow { /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information derived from a layout pass that needs to be returned to the script thread. #[derive(Default)] pub struct ReflowComplete { /// The list of images that were encountered that are in progress. pub pending_images: Vec<PendingImage>, /// The list of nodes that initiated a CSS transition. pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>, } /// Information needed for a script-initiated reflow. pub struct ScriptReflow { /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document: TrustedNodeAddress, /// Whether the document's stylesheets have changed since the last script reflow. pub stylesheets_changed: bool, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<ReflowComplete>, /// The goal of this reflow. pub reflow_goal: ReflowGoal, /// The number of objects in the dom #10110 pub dom_count: u32, } pub struct NewLayoutThreadInfo { pub id: PipelineId, pub url: ServoUrl, pub is_parent: bool, pub layout_pair: (Sender<Msg>, Receiver<Msg>), pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: IpcSender<ConstellationMsg>, pub script_chan: IpcSender<ConstellationControlMsg>, pub image_cache: Arc<ImageCache>, pub content_process_shutdown_chan: Option<IpcSender<()>>, pub layout_threads: usize, pub paint_time_metrics: PaintTimeMetrics, }
random_line_split
message.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress}; use app_units::Au; use euclid::{Point2D, Rect}; use gfx_traits::Epoch; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use metrics::PaintTimeMetrics; use msg::constellation_msg::PipelineId; use net_traits::image_cache::ImageCache; use profile_traits::mem::ReportsChan; use rpc::LayoutRPC; use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg}; use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData}; use script_traits::Painter; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; use servo_channel::{Receiver, Sender}; use servo_url::ServoUrl; use std::sync::Arc; use style::context::QuirksMode; use style::properties::PropertyId; use style::selector_parser::PseudoElement; use style::stylesheets::Stylesheet; /// Asynchronous messages that script can send to layout. pub enum Msg { /// Adds the given stylesheet to the document. The second stylesheet is the /// insertion point (if it exists, the sheet needs to be inserted before /// it). AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>), /// Removes a stylesheet from the document. RemoveStylesheet(ServoArc<Stylesheet>), /// Change the quirks mode. SetQuirksMode(QuirksMode), /// Requests a reflow. Reflow(ScriptReflow), /// Get an RPC interface. GetRPC(Sender<Box<LayoutRPC + Send>>), /// Requests that the layout thread render the next frame of all animations. TickAnimations, /// Updates layout's timer for animation testing from script. /// /// The inner field is the number of *milliseconds* to advance, and the bool /// field is whether animations should be force-ticked. AdvanceClockMs(i32, bool), /// Destroys layout data associated with a DOM node. /// /// TODO(pcwalton): Maybe think about batching to avoid message traffic. ReapStyleAndLayoutData(OpaqueStyleAndLayoutData), /// Requests that the layout thread measure its memory usage. The resulting reports are sent back /// via the supplied channel. CollectReports(ReportsChan), /// Requests that the layout thread enter a quiescent state in which no more messages are /// accepted except `ExitMsg`. A response message will be sent on the supplied channel when /// this happens. PrepareToExit(Sender<()>), /// Requests that the layout thread immediately shut down. There must be no more nodes left after /// this, or layout will crash. ExitNow, /// Get the last epoch counter for this layout thread. GetCurrentEpoch(IpcSender<Epoch>), /// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending; /// false otherwise). GetWebFontLoadState(IpcSender<bool>), /// Creates a new layout thread. /// /// This basically exists to keep the script-layout dependency one-way. CreateLayoutThread(NewLayoutThreadInfo), /// Set the final Url. SetFinalUrl(ServoUrl), /// Tells layout about the new scrolling offsets of each scrollable stacking context. SetScrollStates(Vec<ScrollState>), /// Tells layout about a single new scrolling offset from the script. The rest will /// remain untouched and layout won't forward this back to script. UpdateScrollStateFromScript(ScrollState), /// Tells layout that script has added some paint worklet modules. RegisterPaint(Atom, Vec<Atom>, Box<Painter>), /// Send to layout the precise time when the navigation started. SetNavigationStart(u64), } #[derive(Debug, PartialEq)] pub enum NodesFromPointQueryType { All, Topmost, } #[derive(Debug, PartialEq)] pub enum QueryMsg { ContentBoxQuery(TrustedNodeAddress), ContentBoxesQuery(TrustedNodeAddress), NodeScrollIdQuery(TrustedNodeAddress), NodeGeometryQuery(TrustedNodeAddress), NodeScrollGeometryQuery(TrustedNodeAddress), ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId), OffsetParentQuery(TrustedNodeAddress), StyleQuery(TrustedNodeAddress), TextIndexQuery(TrustedNodeAddress, Point2D<f32>), NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType), ElementInnerTextQuery(TrustedNodeAddress), } /// Any query to perform with this reflow. #[derive(Debug, PartialEq)] pub enum ReflowGoal { Full, TickAnimations, LayoutQuery(QueryMsg, u64), } impl ReflowGoal { /// Returns true if the given ReflowQuery needs a full, up-to-date display list to /// be present or false if it only needs stacking-relative positions. pub fn needs_display_list(&self) -> bool { match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } } /// Returns true if the given ReflowQuery needs its display list send to WebRender or /// false if a layout_thread display list is sufficient. pub fn needs_display(&self) -> bool
} /// Information needed for a reflow. pub struct Reflow { /// A clipping rectangle for the page, an enlarged rectangle containing the viewport. pub page_clip_rect: Rect<Au>, } /// Information derived from a layout pass that needs to be returned to the script thread. #[derive(Default)] pub struct ReflowComplete { /// The list of images that were encountered that are in progress. pub pending_images: Vec<PendingImage>, /// The list of nodes that initiated a CSS transition. pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>, } /// Information needed for a script-initiated reflow. pub struct ScriptReflow { /// General reflow data. pub reflow_info: Reflow, /// The document node. pub document: TrustedNodeAddress, /// Whether the document's stylesheets have changed since the last script reflow. pub stylesheets_changed: bool, /// The current window size. pub window_size: WindowSizeData, /// The channel that we send a notification to. pub script_join_chan: Sender<ReflowComplete>, /// The goal of this reflow. pub reflow_goal: ReflowGoal, /// The number of objects in the dom #10110 pub dom_count: u32, } pub struct NewLayoutThreadInfo { pub id: PipelineId, pub url: ServoUrl, pub is_parent: bool, pub layout_pair: (Sender<Msg>, Receiver<Msg>), pub pipeline_port: IpcReceiver<LayoutControlMsg>, pub constellation_chan: IpcSender<ConstellationMsg>, pub script_chan: IpcSender<ConstellationControlMsg>, pub image_cache: Arc<ImageCache>, pub content_process_shutdown_chan: Option<IpcSender<()>>, pub layout_threads: usize, pub paint_time_metrics: PaintTimeMetrics, }
{ match *self { ReflowGoal::Full | ReflowGoal::TickAnimations => true, ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg { &QueryMsg::NodesFromPointQuery(..) | &QueryMsg::TextIndexQuery(..) | &QueryMsg::ElementInnerTextQuery(_) => true, &QueryMsg::ContentBoxQuery(_) | &QueryMsg::ContentBoxesQuery(_) | &QueryMsg::NodeGeometryQuery(_) | &QueryMsg::NodeScrollGeometryQuery(_) | &QueryMsg::NodeScrollIdQuery(_) | &QueryMsg::ResolvedStyleQuery(..) | &QueryMsg::OffsetParentQuery(_) | &QueryMsg::StyleQuery(_) => false, }, } }
identifier_body
linkedList.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IIterator } from 'vs/base/common/iterator'; class
<E> { element: E; next: Node<E>; prev: Node<E>; constructor(element: E) { this.element = element; } } export class LinkedList<E> { private _first: Node<E>; private _last: Node<E>; isEmpty(): boolean { return !this._first; } clear(): void { this._first = undefined; this._last = undefined; } unshift(element: E) { return this.insert(element, false); } push(element: E) { return this.insert(element, true); } private insert(element: E, atTheEnd: boolean) { const newNode = new Node(element); if (!this._first) { this._first = newNode; this._last = newNode; } else if (atTheEnd) { // push const oldLast = this._last; this._last = newNode; newNode.prev = oldLast; oldLast.next = newNode; } else { // unshift const oldFirst = this._first; this._first = newNode; newNode.next = oldFirst; oldFirst.prev = newNode; } return () => { for (let candidate = this._first; candidate instanceof Node; candidate = candidate.next) { if (candidate !== newNode) { continue; } if (candidate.prev && candidate.next) { // middle let anchor = candidate.prev; anchor.next = candidate.next; candidate.next.prev = anchor; } else if (!candidate.prev && !candidate.next) { // only node this._first = undefined; this._last = undefined; } else if (!candidate.next) { // last this._last = this._last.prev; this._last.next = undefined; } else if (!candidate.prev) { // first this._first = this._first.next; this._first.prev = undefined; } // done break; } }; } iterator(): IIterator<E> { let _done: boolean; let _value: E; let element = { get done() { return _done; }, get value() { return _value; } }; let node = this._first; return { next(): { done: boolean; value: E } { if (!node) { _done = true; _value = undefined; } else { _done = false; _value = node.element; node = node.next; } return element; } }; } toArray(): E[] { let result: E[] = []; for (let node = this._first; node instanceof Node; node = node.next) { result.push(node.element); } return result; } }
Node
identifier_name
linkedList.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IIterator } from 'vs/base/common/iterator'; class Node<E> { element: E; next: Node<E>; prev: Node<E>; constructor(element: E) { this.element = element; } } export class LinkedList<E> { private _first: Node<E>; private _last: Node<E>; isEmpty(): boolean { return !this._first; } clear(): void
unshift(element: E) { return this.insert(element, false); } push(element: E) { return this.insert(element, true); } private insert(element: E, atTheEnd: boolean) { const newNode = new Node(element); if (!this._first) { this._first = newNode; this._last = newNode; } else if (atTheEnd) { // push const oldLast = this._last; this._last = newNode; newNode.prev = oldLast; oldLast.next = newNode; } else { // unshift const oldFirst = this._first; this._first = newNode; newNode.next = oldFirst; oldFirst.prev = newNode; } return () => { for (let candidate = this._first; candidate instanceof Node; candidate = candidate.next) { if (candidate !== newNode) { continue; } if (candidate.prev && candidate.next) { // middle let anchor = candidate.prev; anchor.next = candidate.next; candidate.next.prev = anchor; } else if (!candidate.prev && !candidate.next) { // only node this._first = undefined; this._last = undefined; } else if (!candidate.next) { // last this._last = this._last.prev; this._last.next = undefined; } else if (!candidate.prev) { // first this._first = this._first.next; this._first.prev = undefined; } // done break; } }; } iterator(): IIterator<E> { let _done: boolean; let _value: E; let element = { get done() { return _done; }, get value() { return _value; } }; let node = this._first; return { next(): { done: boolean; value: E } { if (!node) { _done = true; _value = undefined; } else { _done = false; _value = node.element; node = node.next; } return element; } }; } toArray(): E[] { let result: E[] = []; for (let node = this._first; node instanceof Node; node = node.next) { result.push(node.element); } return result; } }
{ this._first = undefined; this._last = undefined; }
identifier_body
linkedList.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IIterator } from 'vs/base/common/iterator'; class Node<E> { element: E; next: Node<E>; prev: Node<E>; constructor(element: E) { this.element = element; } } export class LinkedList<E> { private _first: Node<E>; private _last: Node<E>; isEmpty(): boolean { return !this._first; } clear(): void { this._first = undefined; this._last = undefined; } unshift(element: E) { return this.insert(element, false); } push(element: E) { return this.insert(element, true); } private insert(element: E, atTheEnd: boolean) { const newNode = new Node(element); if (!this._first) { this._first = newNode; this._last = newNode; } else if (atTheEnd) { // push const oldLast = this._last; this._last = newNode; newNode.prev = oldLast; oldLast.next = newNode; } else { // unshift const oldFirst = this._first; this._first = newNode; newNode.next = oldFirst; oldFirst.prev = newNode; } return () => { for (let candidate = this._first; candidate instanceof Node; candidate = candidate.next) { if (candidate !== newNode) { continue; } if (candidate.prev && candidate.next) { // middle let anchor = candidate.prev; anchor.next = candidate.next; candidate.next.prev = anchor; } else if (!candidate.prev && !candidate.next) { // only node this._first = undefined; this._last = undefined; } else if (!candidate.next) { // last this._last = this._last.prev; this._last.next = undefined; } else if (!candidate.prev) { // first this._first = this._first.next; this._first.prev = undefined; } // done break;
} }; } iterator(): IIterator<E> { let _done: boolean; let _value: E; let element = { get done() { return _done; }, get value() { return _value; } }; let node = this._first; return { next(): { done: boolean; value: E } { if (!node) { _done = true; _value = undefined; } else { _done = false; _value = node.element; node = node.next; } return element; } }; } toArray(): E[] { let result: E[] = []; for (let node = this._first; node instanceof Node; node = node.next) { result.push(node.element); } return result; } }
random_line_split
linkedList.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IIterator } from 'vs/base/common/iterator'; class Node<E> { element: E; next: Node<E>; prev: Node<E>; constructor(element: E) { this.element = element; } } export class LinkedList<E> { private _first: Node<E>; private _last: Node<E>; isEmpty(): boolean { return !this._first; } clear(): void { this._first = undefined; this._last = undefined; } unshift(element: E) { return this.insert(element, false); } push(element: E) { return this.insert(element, true); } private insert(element: E, atTheEnd: boolean) { const newNode = new Node(element); if (!this._first) { this._first = newNode; this._last = newNode; } else if (atTheEnd) { // push const oldLast = this._last; this._last = newNode; newNode.prev = oldLast; oldLast.next = newNode; } else
return () => { for (let candidate = this._first; candidate instanceof Node; candidate = candidate.next) { if (candidate !== newNode) { continue; } if (candidate.prev && candidate.next) { // middle let anchor = candidate.prev; anchor.next = candidate.next; candidate.next.prev = anchor; } else if (!candidate.prev && !candidate.next) { // only node this._first = undefined; this._last = undefined; } else if (!candidate.next) { // last this._last = this._last.prev; this._last.next = undefined; } else if (!candidate.prev) { // first this._first = this._first.next; this._first.prev = undefined; } // done break; } }; } iterator(): IIterator<E> { let _done: boolean; let _value: E; let element = { get done() { return _done; }, get value() { return _value; } }; let node = this._first; return { next(): { done: boolean; value: E } { if (!node) { _done = true; _value = undefined; } else { _done = false; _value = node.element; node = node.next; } return element; } }; } toArray(): E[] { let result: E[] = []; for (let node = this._first; node instanceof Node; node = node.next) { result.push(node.element); } return result; } }
{ // unshift const oldFirst = this._first; this._first = newNode; newNode.next = oldFirst; oldFirst.prev = newNode; }
conditional_block
pin_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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. use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; use super::pinmap; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); for port_node in node.subnodes().iter() { port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(&node, port_node); for pin_node in port_node.subnodes().iter() { pin_node.materializer.set(Some(build_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(port_node, pin_node); super::add_node_dependency_on_clock(builder, pin_node); } } } pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { node.expect_no_attributes(cx); } fn build_pin(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { let port_node = node.parent.clone().unwrap().upgrade().unwrap(); let ref port_path = port_node.path; let port_str = format!("Port{}", match port_path.as_str().parse::<usize>().unwrap() { 0...4 => port_path, other => { cx.parse_sess().span_diagnostic.span_err(port_node.path_span, format!("unknown port `{}`, allowed values: 0...4", other).as_str()); return; } }); let port = TokenString(port_str); if node.name.is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "pin node must have a name"); return; } let direction_str = if node.get_string_attr("function").is_some() { "core::option::Option::None" } else { match node.get_string_attr("direction").unwrap().as_str() { "out" => "core::option::Option::Some(zinc::hal::pin::Out)", "in" => "core::option::Option::Some(zinc::hal::pin::In)", other => { let attr = node.get_attr("direction"); cx.parse_sess().span_diagnostic.span_err(attr.value_span, format!("unknown direction `{}`, allowed values: `in`, `out`", other).as_str()); return; } } }; let direction = TokenString(direction_str.to_string()); let pin_str = match node.path.as_str().parse::<usize>().unwrap() { 0...31 => &node.path, other => { cx.parse_sess().span_diagnostic.span_err(node.path_span, format!("unknown pin `{}`, allowed values: 0...31", other).as_str()); return; } }; let port_def = pinmap::port_def(); let function_str = match node.get_string_attr("function") { None => "Gpio".to_string(), Some(fun) => { let pins = &port_def[port_path]; let maybe_pin_index: usize = node.path.as_str().parse().unwrap(); let maybe_pin: &Option<pinmap::PinDef> = pins.get(maybe_pin_index).unwrap(); match maybe_pin { &None => { cx.parse_sess().span_diagnostic.span_err( node.get_attr("function").value_span, format!("unknown pin function `{}`, only GPIO avaliable on this pin", fun).as_str()); return; } &Some(ref pin_funcs) => { let maybe_func = pin_funcs.get(&fun);
format!("unknown pin function `{}`, allowed functions: {}", fun, avaliable.join(", ")).as_str()); return; }, Some(func_idx) => { format!("AltFunction{}", func_idx) } } } } } }; let function = TokenString(function_str); let pin = TokenString(format!("{}u8", pin_str)); let pin_name = TokenString(node.name.clone().unwrap()); node.set_type_name("zinc::hal::lpc43xx::pin::Pin".to_string()); let st = quote_stmt!(&*cx, let $pin_name = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::$port, $pin, zinc::hal::lpc43xx::pin::Function::$function, $direction); ).unwrap(); builder.add_main_statement(st); } #[cfg(test)] mod test { use builder::Builder; use test_helpers::{assert_equal_source, with_parsed}; #[test] fn builds_input_gpio() { with_parsed(" gpio { 0 { p1@1 { direction = \"in\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p1").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p1 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 1u8, zinc::hal::lpc43xx::pin::Function::Gpio, core::option::Option::Some(zinc::hal::pin::In));"); }); } #[test] fn builds_output_gpio() { with_parsed(" gpio { 0 { p2@2 { direction = \"out\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p2 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 2u8, zinc::hal::lpc43xx::pin::Function::Gpio, core::option::Option::Some(zinc::hal::pin::Out));"); }); } #[test] fn builds_altfn_gpio() { with_parsed(" gpio { 0 { p3@3 { direction = \"out\"; function = \"ad0_6\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p3 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 3u8, zinc::hal::lpc43xx::pin::Function::AltFunction2, core::option::Option::None);"); }); } }
match maybe_func { None => { let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect(); cx.parse_sess().span_diagnostic.span_err( node.get_attr("function").value_span,
random_line_split
pin_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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. use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; use super::pinmap; pub fn
(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); for port_node in node.subnodes().iter() { port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(&node, port_node); for pin_node in port_node.subnodes().iter() { pin_node.materializer.set(Some(build_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(port_node, pin_node); super::add_node_dependency_on_clock(builder, pin_node); } } } pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { node.expect_no_attributes(cx); } fn build_pin(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { let port_node = node.parent.clone().unwrap().upgrade().unwrap(); let ref port_path = port_node.path; let port_str = format!("Port{}", match port_path.as_str().parse::<usize>().unwrap() { 0...4 => port_path, other => { cx.parse_sess().span_diagnostic.span_err(port_node.path_span, format!("unknown port `{}`, allowed values: 0...4", other).as_str()); return; } }); let port = TokenString(port_str); if node.name.is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "pin node must have a name"); return; } let direction_str = if node.get_string_attr("function").is_some() { "core::option::Option::None" } else { match node.get_string_attr("direction").unwrap().as_str() { "out" => "core::option::Option::Some(zinc::hal::pin::Out)", "in" => "core::option::Option::Some(zinc::hal::pin::In)", other => { let attr = node.get_attr("direction"); cx.parse_sess().span_diagnostic.span_err(attr.value_span, format!("unknown direction `{}`, allowed values: `in`, `out`", other).as_str()); return; } } }; let direction = TokenString(direction_str.to_string()); let pin_str = match node.path.as_str().parse::<usize>().unwrap() { 0...31 => &node.path, other => { cx.parse_sess().span_diagnostic.span_err(node.path_span, format!("unknown pin `{}`, allowed values: 0...31", other).as_str()); return; } }; let port_def = pinmap::port_def(); let function_str = match node.get_string_attr("function") { None => "Gpio".to_string(), Some(fun) => { let pins = &port_def[port_path]; let maybe_pin_index: usize = node.path.as_str().parse().unwrap(); let maybe_pin: &Option<pinmap::PinDef> = pins.get(maybe_pin_index).unwrap(); match maybe_pin { &None => { cx.parse_sess().span_diagnostic.span_err( node.get_attr("function").value_span, format!("unknown pin function `{}`, only GPIO avaliable on this pin", fun).as_str()); return; } &Some(ref pin_funcs) => { let maybe_func = pin_funcs.get(&fun); match maybe_func { None => { let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect(); cx.parse_sess().span_diagnostic.span_err( node.get_attr("function").value_span, format!("unknown pin function `{}`, allowed functions: {}", fun, avaliable.join(", ")).as_str()); return; }, Some(func_idx) => { format!("AltFunction{}", func_idx) } } } } } }; let function = TokenString(function_str); let pin = TokenString(format!("{}u8", pin_str)); let pin_name = TokenString(node.name.clone().unwrap()); node.set_type_name("zinc::hal::lpc43xx::pin::Pin".to_string()); let st = quote_stmt!(&*cx, let $pin_name = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::$port, $pin, zinc::hal::lpc43xx::pin::Function::$function, $direction); ).unwrap(); builder.add_main_statement(st); } #[cfg(test)] mod test { use builder::Builder; use test_helpers::{assert_equal_source, with_parsed}; #[test] fn builds_input_gpio() { with_parsed(" gpio { 0 { p1@1 { direction = \"in\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p1").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p1 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 1u8, zinc::hal::lpc43xx::pin::Function::Gpio, core::option::Option::Some(zinc::hal::pin::In));"); }); } #[test] fn builds_output_gpio() { with_parsed(" gpio { 0 { p2@2 { direction = \"out\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p2 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 2u8, zinc::hal::lpc43xx::pin::Function::Gpio, core::option::Option::Some(zinc::hal::pin::Out));"); }); } #[test] fn builds_altfn_gpio() { with_parsed(" gpio { 0 { p3@3 { direction = \"out\"; function = \"ad0_6\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p3 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 3u8, zinc::hal::lpc43xx::pin::Function::AltFunction2, core::option::Option::None);"); }); } }
attach
identifier_name
pin_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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. use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; use super::pinmap; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); for port_node in node.subnodes().iter() { port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(&node, port_node); for pin_node in port_node.subnodes().iter() { pin_node.materializer.set(Some(build_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(port_node, pin_node); super::add_node_dependency_on_clock(builder, pin_node); } } } pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { node.expect_no_attributes(cx); } fn build_pin(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { let port_node = node.parent.clone().unwrap().upgrade().unwrap(); let ref port_path = port_node.path; let port_str = format!("Port{}", match port_path.as_str().parse::<usize>().unwrap() { 0...4 => port_path, other => { cx.parse_sess().span_diagnostic.span_err(port_node.path_span, format!("unknown port `{}`, allowed values: 0...4", other).as_str()); return; } }); let port = TokenString(port_str); if node.name.is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "pin node must have a name"); return; } let direction_str = if node.get_string_attr("function").is_some() { "core::option::Option::None" } else { match node.get_string_attr("direction").unwrap().as_str() { "out" => "core::option::Option::Some(zinc::hal::pin::Out)", "in" => "core::option::Option::Some(zinc::hal::pin::In)", other => { let attr = node.get_attr("direction"); cx.parse_sess().span_diagnostic.span_err(attr.value_span, format!("unknown direction `{}`, allowed values: `in`, `out`", other).as_str()); return; } } }; let direction = TokenString(direction_str.to_string()); let pin_str = match node.path.as_str().parse::<usize>().unwrap() { 0...31 => &node.path, other => { cx.parse_sess().span_diagnostic.span_err(node.path_span, format!("unknown pin `{}`, allowed values: 0...31", other).as_str()); return; } }; let port_def = pinmap::port_def(); let function_str = match node.get_string_attr("function") { None => "Gpio".to_string(), Some(fun) => { let pins = &port_def[port_path]; let maybe_pin_index: usize = node.path.as_str().parse().unwrap(); let maybe_pin: &Option<pinmap::PinDef> = pins.get(maybe_pin_index).unwrap(); match maybe_pin { &None => { cx.parse_sess().span_diagnostic.span_err( node.get_attr("function").value_span, format!("unknown pin function `{}`, only GPIO avaliable on this pin", fun).as_str()); return; } &Some(ref pin_funcs) => { let maybe_func = pin_funcs.get(&fun); match maybe_func { None => { let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect(); cx.parse_sess().span_diagnostic.span_err( node.get_attr("function").value_span, format!("unknown pin function `{}`, allowed functions: {}", fun, avaliable.join(", ")).as_str()); return; }, Some(func_idx) => { format!("AltFunction{}", func_idx) } } } } } }; let function = TokenString(function_str); let pin = TokenString(format!("{}u8", pin_str)); let pin_name = TokenString(node.name.clone().unwrap()); node.set_type_name("zinc::hal::lpc43xx::pin::Pin".to_string()); let st = quote_stmt!(&*cx, let $pin_name = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::$port, $pin, zinc::hal::lpc43xx::pin::Function::$function, $direction); ).unwrap(); builder.add_main_statement(st); } #[cfg(test)] mod test { use builder::Builder; use test_helpers::{assert_equal_source, with_parsed}; #[test] fn builds_input_gpio() { with_parsed(" gpio { 0 { p1@1 { direction = \"in\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p1").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p1 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 1u8, zinc::hal::lpc43xx::pin::Function::Gpio, core::option::Option::Some(zinc::hal::pin::In));"); }); } #[test] fn builds_output_gpio()
#[test] fn builds_altfn_gpio() { with_parsed(" gpio { 0 { p3@3 { direction = \"out\"; function = \"ad0_6\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p3 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 3u8, zinc::hal::lpc43xx::pin::Function::AltFunction2, core::option::Option::None);"); }); } }
{ with_parsed(" gpio { 0 { p2@2 { direction = \"out\"; } } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts().len() == 1); assert_equal_source(&builder.main_stmts()[0], "let p2 = zinc::hal::lpc43xx::pin::Pin::new( zinc::hal::lpc43xx::pin::Port::Port0, 2u8, zinc::hal::lpc43xx::pin::Function::Gpio, core::option::Option::Some(zinc::hal::pin::Out));"); }); }
identifier_body
live.spec.ts
import {TestBed, ComponentFixture, inject} from '@angular/core/testing'; import {Component} from '@angular/core'; import {By} from '@angular/platform-browser'; import {Live, ARIA_LIVE_DELAY} from './live'; function getLiveElement(): HTMLElement { return document.body.querySelector('#ngb-live') !as HTMLElement; } describe('LiveAnnouncer', () => { let live: Live; let fixture: ComponentFixture<TestComponent>; const say = () => { fixture.debugElement.query(By.css('button')).nativeElement.click(); }; describe('live announcer', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [Live, {provide: ARIA_LIVE_DELAY, useValue: null}], declarations: [TestComponent], })); beforeEach(inject([Live], (_live: Live) => { live = _live; fixture = TestBed.createComponent(TestComponent); })); it('should correctly update the text message', () => { say(); const liveElement = getLiveElement(); expect(liveElement.textContent).toBe('test'); expect(liveElement.id).toBe('ngb-live'); }); it('should remove the used element from the DOM on destroy', () => { say(); live.ngOnDestroy(); expect(getLiveElement()).toBeFalsy(); }); }); }); @Component({template: `<button (click)="say()">say</button>`}) class TestComponent { constructor(public live: Live) {} say()
}
{ this.live.say('test'); }
identifier_body
live.spec.ts
import {TestBed, ComponentFixture, inject} from '@angular/core/testing'; import {Component} from '@angular/core'; import {By} from '@angular/platform-browser'; import {Live, ARIA_LIVE_DELAY} from './live'; function getLiveElement(): HTMLElement { return document.body.querySelector('#ngb-live') !as HTMLElement; } describe('LiveAnnouncer', () => { let live: Live; let fixture: ComponentFixture<TestComponent>; const say = () => { fixture.debugElement.query(By.css('button')).nativeElement.click(); }; describe('live announcer', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [Live, {provide: ARIA_LIVE_DELAY, useValue: null}], declarations: [TestComponent], })); beforeEach(inject([Live], (_live: Live) => { live = _live; fixture = TestBed.createComponent(TestComponent); })); it('should correctly update the text message', () => { say(); const liveElement = getLiveElement(); expect(liveElement.textContent).toBe('test'); expect(liveElement.id).toBe('ngb-live'); }); it('should remove the used element from the DOM on destroy', () => { say(); live.ngOnDestroy(); expect(getLiveElement()).toBeFalsy(); }); }); }); @Component({template: `<button (click)="say()">say</button>`}) class
{ constructor(public live: Live) {} say() { this.live.say('test'); } }
TestComponent
identifier_name
live.spec.ts
import {TestBed, ComponentFixture, inject} from '@angular/core/testing'; import {Component} from '@angular/core'; import {By} from '@angular/platform-browser'; import {Live, ARIA_LIVE_DELAY} from './live'; function getLiveElement(): HTMLElement { return document.body.querySelector('#ngb-live') !as HTMLElement; } describe('LiveAnnouncer', () => { let live: Live; let fixture: ComponentFixture<TestComponent>; const say = () => { fixture.debugElement.query(By.css('button')).nativeElement.click(); }; describe('live announcer', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [Live, {provide: ARIA_LIVE_DELAY, useValue: null}], declarations: [TestComponent], })); beforeEach(inject([Live], (_live: Live) => { live = _live; fixture = TestBed.createComponent(TestComponent); })); it('should correctly update the text message', () => { say();
it('should remove the used element from the DOM on destroy', () => { say(); live.ngOnDestroy(); expect(getLiveElement()).toBeFalsy(); }); }); }); @Component({template: `<button (click)="say()">say</button>`}) class TestComponent { constructor(public live: Live) {} say() { this.live.say('test'); } }
const liveElement = getLiveElement(); expect(liveElement.textContent).toBe('test'); expect(liveElement.id).toBe('ngb-live'); });
random_line_split
transaction.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! View onto transaction rlp use util::{U256, Bytes, Hashable, H256}; use rlp::{Rlp, View}; /// View onto transaction rlp. pub struct TransactionView<'a> { rlp: Rlp<'a> } impl<'a> TransactionView<'a> { /// Creates new view onto block from raw bytes. pub fn new(bytes: &'a [u8]) -> TransactionView<'a>
/// Creates new view onto block from rlp. pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> { TransactionView { rlp: rlp } } /// Return reference to underlaying rlp. pub fn rlp(&self) -> &Rlp<'a> { &self.rlp } /// Get the nonce field of the transaction. pub fn nonce(&self) -> U256 { self.rlp.val_at(0) } /// Get the gas_price field of the transaction. pub fn gas_price(&self) -> U256 { self.rlp.val_at(1) } /// Get the gas field of the transaction. pub fn gas(&self) -> U256 { self.rlp.val_at(2) } /// Get the value field of the transaction. pub fn value(&self) -> U256 { self.rlp.val_at(4) } /// Get the data field of the transaction. pub fn data(&self) -> Bytes { self.rlp.val_at(5) } /// Get the v field of the transaction. pub fn v(&self) -> u8 { let r: u16 = self.rlp.val_at(6); r as u8 } /// Get the r field of the transaction. pub fn r(&self) -> U256 { self.rlp.val_at(7) } /// Get the s field of the transaction. pub fn s(&self) -> U256 { self.rlp.val_at(8) } } impl<'a> Hashable for TransactionView<'a> { fn sha3(&self) -> H256 { self.rlp.as_raw().sha3() } } #[cfg(test)] mod tests { use std::str::FromStr; use rustc_serialize::hex::FromHex; use util::U256; use super::TransactionView; #[test] fn test_transaction_view() { let rlp = "f87c80018261a894095e7baea6a6c7c4c2dfeb977efac326af552d870a9d00000000000000000000000000000000000000000000000000000000001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804".from_hex().unwrap(); let view = TransactionView::new(&rlp); assert_eq!(view.nonce(), U256::from(0)); assert_eq!(view.gas_price(), U256::from(1)); assert_eq!(view.gas(), U256::from(0x61a8)); assert_eq!(view.value(), U256::from(0xa)); assert_eq!(view.data(), "0000000000000000000000000000000000000000000000000000000000".from_hex().unwrap()); assert_eq!(view.r(), U256::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353").unwrap()); assert_eq!(view.s(), U256::from_str("efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(view.v(), 0x1b); } }
{ TransactionView { rlp: Rlp::new(bytes) } }
identifier_body
transaction.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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.
// GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! View onto transaction rlp use util::{U256, Bytes, Hashable, H256}; use rlp::{Rlp, View}; /// View onto transaction rlp. pub struct TransactionView<'a> { rlp: Rlp<'a> } impl<'a> TransactionView<'a> { /// Creates new view onto block from raw bytes. pub fn new(bytes: &'a [u8]) -> TransactionView<'a> { TransactionView { rlp: Rlp::new(bytes) } } /// Creates new view onto block from rlp. pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> { TransactionView { rlp: rlp } } /// Return reference to underlaying rlp. pub fn rlp(&self) -> &Rlp<'a> { &self.rlp } /// Get the nonce field of the transaction. pub fn nonce(&self) -> U256 { self.rlp.val_at(0) } /// Get the gas_price field of the transaction. pub fn gas_price(&self) -> U256 { self.rlp.val_at(1) } /// Get the gas field of the transaction. pub fn gas(&self) -> U256 { self.rlp.val_at(2) } /// Get the value field of the transaction. pub fn value(&self) -> U256 { self.rlp.val_at(4) } /// Get the data field of the transaction. pub fn data(&self) -> Bytes { self.rlp.val_at(5) } /// Get the v field of the transaction. pub fn v(&self) -> u8 { let r: u16 = self.rlp.val_at(6); r as u8 } /// Get the r field of the transaction. pub fn r(&self) -> U256 { self.rlp.val_at(7) } /// Get the s field of the transaction. pub fn s(&self) -> U256 { self.rlp.val_at(8) } } impl<'a> Hashable for TransactionView<'a> { fn sha3(&self) -> H256 { self.rlp.as_raw().sha3() } } #[cfg(test)] mod tests { use std::str::FromStr; use rustc_serialize::hex::FromHex; use util::U256; use super::TransactionView; #[test] fn test_transaction_view() { let rlp = "f87c80018261a894095e7baea6a6c7c4c2dfeb977efac326af552d870a9d00000000000000000000000000000000000000000000000000000000001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804".from_hex().unwrap(); let view = TransactionView::new(&rlp); assert_eq!(view.nonce(), U256::from(0)); assert_eq!(view.gas_price(), U256::from(1)); assert_eq!(view.gas(), U256::from(0x61a8)); assert_eq!(view.value(), U256::from(0xa)); assert_eq!(view.data(), "0000000000000000000000000000000000000000000000000000000000".from_hex().unwrap()); assert_eq!(view.r(), U256::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353").unwrap()); assert_eq!(view.s(), U256::from_str("efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(view.v(), 0x1b); } }
// Parity 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
random_line_split
transaction.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! View onto transaction rlp use util::{U256, Bytes, Hashable, H256}; use rlp::{Rlp, View}; /// View onto transaction rlp. pub struct TransactionView<'a> { rlp: Rlp<'a> } impl<'a> TransactionView<'a> { /// Creates new view onto block from raw bytes. pub fn
(bytes: &'a [u8]) -> TransactionView<'a> { TransactionView { rlp: Rlp::new(bytes) } } /// Creates new view onto block from rlp. pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> { TransactionView { rlp: rlp } } /// Return reference to underlaying rlp. pub fn rlp(&self) -> &Rlp<'a> { &self.rlp } /// Get the nonce field of the transaction. pub fn nonce(&self) -> U256 { self.rlp.val_at(0) } /// Get the gas_price field of the transaction. pub fn gas_price(&self) -> U256 { self.rlp.val_at(1) } /// Get the gas field of the transaction. pub fn gas(&self) -> U256 { self.rlp.val_at(2) } /// Get the value field of the transaction. pub fn value(&self) -> U256 { self.rlp.val_at(4) } /// Get the data field of the transaction. pub fn data(&self) -> Bytes { self.rlp.val_at(5) } /// Get the v field of the transaction. pub fn v(&self) -> u8 { let r: u16 = self.rlp.val_at(6); r as u8 } /// Get the r field of the transaction. pub fn r(&self) -> U256 { self.rlp.val_at(7) } /// Get the s field of the transaction. pub fn s(&self) -> U256 { self.rlp.val_at(8) } } impl<'a> Hashable for TransactionView<'a> { fn sha3(&self) -> H256 { self.rlp.as_raw().sha3() } } #[cfg(test)] mod tests { use std::str::FromStr; use rustc_serialize::hex::FromHex; use util::U256; use super::TransactionView; #[test] fn test_transaction_view() { let rlp = "f87c80018261a894095e7baea6a6c7c4c2dfeb977efac326af552d870a9d00000000000000000000000000000000000000000000000000000000001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804".from_hex().unwrap(); let view = TransactionView::new(&rlp); assert_eq!(view.nonce(), U256::from(0)); assert_eq!(view.gas_price(), U256::from(1)); assert_eq!(view.gas(), U256::from(0x61a8)); assert_eq!(view.value(), U256::from(0xa)); assert_eq!(view.data(), "0000000000000000000000000000000000000000000000000000000000".from_hex().unwrap()); assert_eq!(view.r(), U256::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353").unwrap()); assert_eq!(view.s(), U256::from_str("efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(view.v(), 0x1b); } }
new
identifier_name
luhn_test.rs
// Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers struct
{ m: u64 } impl Iterator for Digits { type Item = u64; fn next(&mut self) -> Option<u64> { match self.m { 0 => None, n => { let ret = n % 10; self.m = n / 10; Some(ret) } } } } #[derive(Copy, Clone)] enum LuhnState { Even, Odd, } fn digits(n: u64) -> Digits { Digits{m: n} } fn luhn_test(n: u64) -> bool { let odd_even = [LuhnState::Odd, LuhnState::Even]; let numbers = digits(n).zip(odd_even.iter().cycle().map(|&s| s)); let sum = numbers.fold(0u64, |s, n| { s + match n { (n, LuhnState::Odd) => n, (n, LuhnState::Even) => digits(n * 2).fold(0, |s, n| s + n), } }); sum % 10 == 0 } #[cfg(not(test))] fn main() { let nos = [49927398716, 49927398717, 1234567812345678, 1234567812345670]; for n in &nos { if luhn_test(*n) { println!("{} passes." , n); } else { println!("{} fails." , n); } } } #[test] fn test_inputs() { assert!(luhn_test(49927398716)); assert!(!luhn_test(49927398717)); assert!(!luhn_test(1234567812345678)); assert!(luhn_test(1234567812345670)); }
Digits
identifier_name