text
stringlengths
2
1.04M
meta
dict
const path = require("path"); module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: path.resolve('.'), // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ "tests/spec/*.ts" ], mime: { 'text/javascript': ['ts','tsx'] }, // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { "tests/spec/*.ts": ["webpack"] }, webpack: { output: { filename: "file.js" }, module: { rules: [ { test: /\.tsx?$/, use: "ts-loader", exclude: /node_modules/ } ] }, resolve: { extensions: [".ts", ".tsx", ".js"] } }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_DEBUG, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) };
{ "content_hash": "e7413278c8d4452374e15e7e71e1bf83", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 120, "avg_line_length": 22.483516483516482, "alnum_prop": 0.5992179863147605, "repo_name": "LGabAnnell/lazyload-inferno-component", "id": "549f249618271b2582d8ef1fb32ff485caa93f6d", "size": "2127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "karma.conf.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2181" }, { "name": "TypeScript", "bytes": "4282" } ], "symlink_target": "" }
package examples import ( "net/http" "net/http/httptest" "testing" "github.com/gavv/httpexpect/v2" ) func TestFruits(t *testing.T) { handler := FruitsHandler() server := httptest.NewServer(handler) defer server.Close() e := httpexpect.Default(t, server.URL) e.GET("/fruits"). Expect(). Status(http.StatusOK).JSON().Array().Empty() orange := map[string]interface{}{ "weight": 100, } e.PUT("/fruits/orange").WithJSON(orange). Expect(). Status(http.StatusNoContent).NoContent() apple := map[string]interface{}{ "colors": []interface{}{"green", "red"}, "weight": 200, } e.PUT("/fruits/apple").WithJSON(apple). Expect(). Status(http.StatusNoContent).NoContent() e.GET("/fruits"). Expect(). Status(http.StatusOK).JSON().Array().ContainsOnly("orange", "apple") e.GET("/fruits/orange"). Expect(). Status(http.StatusOK).JSON().Object().Equal(orange).NotEqual(apple) e.GET("/fruits/orange"). Expect(). Status(http.StatusOK). JSON().Object().ContainsKey("weight").ValueEqual("weight", 100) obj := e.GET("/fruits/apple"). Expect(). Status(http.StatusOK).JSON().Object() obj.Keys().ContainsOnly("colors", "weight") obj.Value("colors").Array().Elements("green", "red") obj.Value("colors").Array().Element(0).String().Equal("green") obj.Value("colors").Array().Element(1).String().Equal("red") obj.Value("weight").Number().Equal(200) e.GET("/fruits/melon"). Expect(). Status(http.StatusNotFound) }
{ "content_hash": "00cd08016f37d702143ef23d08b4fd63", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 70, "avg_line_length": 21.558823529411764, "alnum_prop": 0.6596180081855388, "repo_name": "gavv/httpexpect", "id": "6e09f1e1d827c4264390c91e27664a371ada3365", "size": "1466", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_examples/fruits_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "551219" }, { "name": "Makefile", "bytes": "487" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>API 文档 [zTree -- jQuery 树插件]</title> <link rel="stylesheet" href="apiCss/common.css" type="text/css"> <link rel='stylesheet' href='apiCss/zTreeStyleForApi.css' type='text/css'> <script type="text/javascript"> var ie = (function(){ var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); return v > 4 ? v : undef; }()), ie6 = (ie === 6), path = window.location.pathname.replace(/.*\/([^\/\.]*)\..*/g,"$1"), langLib = []; ie = ie<9; if(ie) { document.write('<link rel="stylesheet" href="apiCss/common_ie6.css" type="text/css">'); } var lang = "cn", ajaxMsg = "如果你使用的是 Chrome 浏览器,那么请把 API 文档发布到 web 服务目录下访问。\n\n(Chrome 浏览器不支持本地 ajax 访问, 即:file://)"; </script> </head> <body> <div id="header_wrap" class="header_wrap" style="padding-top: 30px;"> <div id="header" class="header round"> <div class="light-bulb" alt=""></div> <div class="ieSuggest">浏览本网站建议您使用 Chrome、FireFox、Opera、IE9 等浏览器(只要不是 IE6 7 8 就行), 速度会更快,画面会更炫!</div> <div class="google_plus"><g:plusone></g:plusone></div> <div class="header-text"> <h1><em>zTree v3.5.27 API 文档</em></h1><p></p> <p>all.js = core + excheck + exedit ( 不包括 exhide ); 发现错误请及时通知,谢谢。</p> </div> <ul class="shortcuts language" style="top:0;"> <li><a href="API_en.html" onclick="window.location.href='API_en.html'"><button class="ico en" title="英文版" type="button"></button><span class=""></span></a></li> </ul> </div> </div> <div id="content_wrap" class="content_wrap"> <div id="content" class="content"> <div class="nav_section"> <ul> <li class="first">注释:</li> <li><button class="ico16 z_core" onfocus="this.blur();"></button><span>core 核心包</span></li> <li><button class="ico16 z_check" onfocus="this.blur();"></button><span>excheck 扩展</span></li> <li><button class="ico16 z_edit" onfocus="this.blur();"></button><span>exedit 扩展</span></li> <li><button class="ico16 z_hide" onfocus="this.blur();"></button><span>exhide 扩展</span></li> <li class="noline"> <button class="ico16 z_search" onfocus="this.blur();" title="Enter 以及 左、右键可以快速定位查找结果"></button> <input type="text" class="searchKey search empty" value=""><input type="text" class="searchResult search" value=""> <button class="ico16 searchPrev disabled" onfocus="this.blur();" title="Enter 以及 左、右键可以快速定位查找结果"></button><button class="ico16 searchNext disabled" onfocus="this.blur();" title="Enter 以及 左、右键可以快速定位查找结果"></button> </li> </ul> </div> <div id="contentBox" class="contentBox round clearfix"> <div id="apiContent" class="apiContent"> <div id="api_setting" class="api_setting left"> <ul class="api_content_title"><li>setting 配置详解</li></ul> <ul id="settingTree" class="ztree"></ul> </div> <div id="api_function" class="api_function right"> <ul class="api_content_title"><li>zTree 方法详解</li></ul> <ul id="functionTree" class="ztree"></ul> <ul class="api_content_title"><li>treeNode 节点数据详解</li></ul> <ul id="treenodeTree" class="ztree"></ul> </div> </div> </div> <div class="clear"></div> </div> </div> <!-- overlayed --> <div id="overlayDiv" class="baby_overlay"> <div id="overlayContent" class="content round clearfix"> <div class="overlaySearch"> <button class="ico16 z_search" onfocus="this.blur();" title="Enter 以及 左、右键可以快速定位查找结果"></button> <input type="text" class="searchKey search empty" value=""><input type="text" class="searchResult search" value=""> <button class="ico16 searchPrev disabled" onfocus="this.blur();" title="Enter 以及 左、右键可以快速定位查找结果"></button><button class="ico16 searchNext disabled" onfocus="this.blur();" title="Enter 以及 左、右键可以快速定位查找结果"></button> </div> <a id="overlayDivCloseBtn" class="close"></a> <div id="overlayDetailDiv" class="details"></div> </div> <div id="overlayDivArrow" class="baby_overlay_arrow"></div> </div> <script type="text/javascript" src="apiCss/jquery-1.6.2.min.js"></script> <script type='text/javascript' src='apiCss/jquery.ztree.core.js'></script> <script type='text/javascript' src='apiCss/api.js'></script> <script type="text/javascript"> $(document).ready(function(){ apiContent._init(); }); </script> </body> </html>
{ "content_hash": "ed3ff306157b27416de12dd12d660774", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 219, "avg_line_length": 44.359223300970875, "alnum_prop": 0.620267016852703, "repo_name": "ammeyjohn/boss", "id": "2bd4d1b145c6dbaca24f01e2a6fd9eb788ae8f5e", "size": "5023", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "web/assets/vendor/ztree_v3/api/API_cn.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "119610" }, { "name": "HTML", "bytes": "42383" }, { "name": "JavaScript", "bytes": "2326769" } ], "symlink_target": "" }
package org.apache.accumulo.core.client.lexicoder; import java.util.Arrays; import org.apache.accumulo.core.clientImpl.lexicoder.AbstractLexicoderTest; import org.junit.Test; public class DoubleLexicoderTest extends AbstractLexicoderTest { @Test public void testSortOrder() { assertSortOrder(new DoubleLexicoder(), Arrays.asList(Double.MIN_VALUE, Double.MAX_VALUE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 0.0, 0.01, 0.001, 1.0, -1.0, -1.1, -1.01, Math.nextUp(Double.NEGATIVE_INFINITY), Math.nextAfter(0.0, Double.NEGATIVE_INFINITY), Math.nextAfter(Double.MAX_VALUE, Double.NEGATIVE_INFINITY), Math.pow(10.0, 30.0) * -1.0, Math.pow(10.0, 30.0), Math.pow(10.0, -30.0) * -1.0, Math.pow(10.0, -30.0))); } @Test public void testDecode() { assertDecodes(new DoubleLexicoder(), Double.MIN_VALUE); assertDecodes(new DoubleLexicoder(), -1.0); assertDecodes(new DoubleLexicoder(), -Math.pow(10.0, -30.0)); assertDecodes(new DoubleLexicoder(), 0.0); assertDecodes(new DoubleLexicoder(), Math.pow(10.0, -30.0)); assertDecodes(new DoubleLexicoder(), 1.0); assertDecodes(new DoubleLexicoder(), Double.MAX_VALUE); } }
{ "content_hash": "852ee1891d9cd1c6a719f9495d569564", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 100, "avg_line_length": 38.1875, "alnum_prop": 0.6898527004909983, "repo_name": "phrocker/accumulo-1", "id": "af770a0ffd29208cbf4d9baa21be8f04a32da265", "size": "2029", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/src/test/java/org/apache/accumulo/core/client/lexicoder/DoubleLexicoderTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2465" }, { "name": "C++", "bytes": "37312" }, { "name": "CSS", "bytes": "6443" }, { "name": "FreeMarker", "bytes": "57422" }, { "name": "HTML", "bytes": "5454" }, { "name": "Java", "bytes": "18447889" }, { "name": "JavaScript", "bytes": "71755" }, { "name": "Makefile", "bytes": "2872" }, { "name": "Python", "bytes": "7344" }, { "name": "Shell", "bytes": "61899" }, { "name": "Thrift", "bytes": "40724" } ], "symlink_target": "" }
CONTAINER_NAME=obevo-postgresql-instance OLD_CONTAINER_ID=$(docker ps -aqf "name=$CONTAINER_NAME") if [ ! -z "$OLD_CONTAINER_ID" ] then echo "Shutting down old container" docker stop $OLD_CONTAINER_ID docker rm $OLD_CONTAINER_ID fi docker run --name $CONTAINER_NAME -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres
{ "content_hash": "a8598f8c4a4e746eeb06d52889400cab", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 96, "avg_line_length": 31.181818181818183, "alnum_prop": 0.7346938775510204, "repo_name": "goldmansachs/obevo", "id": "7be6f51299b17666ca2279762e19d327d2123bdf", "size": "935", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "obevo-db-impls/obevo-db-postgresql/postgresql-setup.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2302" }, { "name": "FreeMarker", "bytes": "11604" }, { "name": "Java", "bytes": "2571967" }, { "name": "JavaScript", "bytes": "4632" }, { "name": "Kotlin", "bytes": "396753" }, { "name": "PLSQL", "bytes": "11219" }, { "name": "PLpgSQL", "bytes": "50409" }, { "name": "PowerShell", "bytes": "3967" }, { "name": "SQLPL", "bytes": "4923" }, { "name": "Shell", "bytes": "19127" }, { "name": "TSQL", "bytes": "186190" } ], "symlink_target": "" }
/** * A helper module for AngularUI Router, which allows you to handle redirect chains */ (function() { 'use strict'; angular.module('ui.router.redirect', ['ui.router']) .provider('$redirect', redirectProvider); redirectProvider.$inject = ['$urlRouterProvider']; function redirectProvider($urlRouterProvider) { var otherwiseCallback = angular.noop, notFoundCallback = angular.noop, debug = false; Redirect.$inject = ['$rootScope', '$state', '$q', '$timeout', '$injector', '$location']; return { otherwise: otherwise, notFound: notFound, setDebug: setDebug, $get: Redirect }; /** * Callback if the redirection was rejected * @params {function} callback */ function otherwise(callback) { otherwiseCallback = callback; } /** * Callback if the state was not found * @params {function} callback */ function notFound(callback) { notFoundCallback = callback; $urlRouterProvider.otherwise(callback); } /** * Turn on/off the debugger * @params {boolean} debug */ function setDebug(_debug) { debug = !!_debug; } function Redirect($rootScope, $state, $q, $timeout, $injector, $location) { var callbackQueue = [], redirectQueue = [], redirectAccepted = false, callIndex = 0, cache = {}, initiated = false, redirectScope = { add: add, _go: go, set: set, get: get }, defaultOptions = { inherit: true, location: true, notify: true, reload: false }; $rootScope.$on('$stateChangeStart', stateChangeStart); return redirectScope; /** * Approve / Deny the ui-router's change */ function stateChangeStart(event, toState, toParams, fromState, fromParams, options) { //Initiate checks if(!redirectAccepted) { event.preventDefault(); $rootScope.$broadcast('$redirectStart', toState, toParams); if(options) { //Handle history options.location = options.relative ? options.location : true; delete options.$retry; delete options.relative; } go({ name: toState.name, params: toParams, options: options || {} }); } } /** * Define new redirect handler * @params callback {function} * Redirect handler. First param is the targeted route. * Possible options to return: * * Basic options: * false {boolean}: Deny the change * true {boolean}: Approve the change * route {object}: Redirect to this route * * promise {object}: * Resolve with a basic option * Reject: Deny the change */ function add() { var callback = angular.noop, condition = ''; if(arguments.length === 1) { callback = arguments[0]; } else if(arguments.length === 2) { condition = arguments[0]; callback = arguments[1]; } if(!angular.isString(condition)) { throw new Error('Condition should be string'); } if(!angular.isFunction(callback)) { throw new Error('Callback should be function'); } callbackQueue.push({ condition: condition, callback: callback }); return this; } /** * Initiate the redirection of the specified route * @params {object} route * name * params * options */ function go(route) { var deferred = $q.defer(); //Doesn't exist in the redirect chain if(!isProcessed(route)) { redirectQueue = []; var result = checkRedirectQueue(route, ++callIndex); if(!result) { deferred.reject(); } else if(result.then) { return result; } else { deferred.resolve(result); } } else { deferred.resolve(true); } return deferred.promise; } /** * Cache setter * @params {string} key * @params {mixed} value */ function set(key, value) { cache[key] = value; return cache[key]; } /** * Cache getter * @params {string} key */ function get(key) { return cache[key]; } /** * Check the targeted route in the redirect chain * @params {object} route */ function isProcessed(route) { var i = 0, redirectQueueLength = redirectQueue.length; for(; i < redirectQueueLength; i++) { if(angular.equals(route, redirectQueue[i])) { return true; } } return false; } /** * New item into the redirect chain * @params {object} route */ function addToRedirectQueue(route) { var i = 0, redirectQueueLength = redirectQueue.length, _route = angular.copy(route); if(debug) { console.info('Redirect to:', _route); } for(; i < redirectQueueLength; i++) { if(angular.equals(_route, redirectQueue[i])) { console.info('Redirect queue:', redirectQueue); throw new Error('Infinite redirect loop'); } } redirectQueue.push(_route); } /** * Check every redirect function and resolve them * @params {object} route * @params {object} _callIndex * Private callcounter */ function checkRedirectQueue(route, _callIndex) { var i = 0, result = true, check = function(route, ignoreRedirectQueue) { route.params = route.params || {}; route.options = route.options || {}; //New redirect was triggered - cancel the current one if(callIndex !== _callIndex) { return false; } //Approved and every callback was checked if(i === callbackQueue.length) { if(route && route.name) { _go(route); } return route; } if(!ignoreRedirectQueue) { addToRedirectQueue(route); } var condition = callbackQueue[i].condition, callback = callbackQueue[i].callback; if( !condition || new RegExp('^' + condition + '$').test(route.name) ) { result = callback.call(redirectScope, route); } else { //Approved - next callback result = true; } return handle(route, result); }, handle = function(route, result) { //Promise if(result && result.then) { var deferred = $q.defer(); result.then(function(_result) { deferred.resolve(handle(route, _result)); }, function(_result) { $timeout(function() { otherwiseCallback($injector); }); deferred.reject(); }); return deferred.promise; //Redirect } else if(result && result.name) { return checkRedirectQueue(result, _callIndex); //Approved - next callback } else if(result === true) { i++; return check(route, true); //Don't go } else if(!result) { reset(); $timeout(function() { otherwiseCallback($injector); }); return false; //Wrong format } else { throw new Error('Wrong redirect format'); } }; route.options = angular.extend({}, defaultOptions, route.options); return check(route); } /** * Reset the service */ function reset() { redirectQueue = []; callIndex = 0; } /** * Enable and redirect * @param {object} route */ function _go(route) { var stateFound = $state.get(route.name), currentName = $state.current.name, hash = '', search = $location.search(), _callIndex = callIndex; reset(); if(!stateFound) { $rootScope.$broadcast('$redirectNotFound', route); } if(!stateFound && notFoundCallback !== angular.noop) { notFoundCallback($injector); } else { redirectAccepted = true; //First load if(!initiated) { initiated = true; hash = $location.hash(); } $state.go(route.name, route.params, route.options).then(function() { if(hash && !currentName) { $location.hash(hash); } if(_callIndex === 1 && Object.keys(search).length) { $location.search(search).replace(); } }); redirectAccepted = false; } } } } })();
{ "content_hash": "0f632584397590ce402c63e4dd95559f", "timestamp": "", "source": "github", "line_count": 356, "max_line_length": 92, "avg_line_length": 26.837078651685392, "alnum_prop": 0.48869583420556834, "repo_name": "leonuh/ui-router.redirect", "id": "f582bf5fc3ccf5b88ab17e1328574d585c71bc8e", "size": "9554", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dist/angular-ui-router.redirect.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "26625" } ], "symlink_target": "" }
/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.airavata.cloud.aurora.client.sdk; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-10-21") public class ResponseDetail implements org.apache.thrift.TBase<ResponseDetail, ResponseDetail._Fields>, java.io.Serializable, Cloneable, Comparable<ResponseDetail> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ResponseDetail"); private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("message", org.apache.thrift.protocol.TType.STRING, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new ResponseDetailStandardSchemeFactory()); schemes.put(TupleScheme.class, new ResponseDetailTupleSchemeFactory()); } public String message; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { MESSAGE((short)1, "message"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // MESSAGE return MESSAGE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData("message", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ResponseDetail.class, metaDataMap); } public ResponseDetail() { } public ResponseDetail( String message) { this(); this.message = message; } /** * Performs a deep copy on <i>other</i>. */ public ResponseDetail(ResponseDetail other) { if (other.isSetMessage()) { this.message = other.message; } } public ResponseDetail deepCopy() { return new ResponseDetail(this); } @Override public void clear() { this.message = null; } public String getMessage() { return this.message; } public ResponseDetail setMessage(String message) { this.message = message; return this; } public void unsetMessage() { this.message = null; } /** Returns true if field message is set (has been assigned a value) and false otherwise */ public boolean isSetMessage() { return this.message != null; } public void setMessageIsSet(boolean value) { if (!value) { this.message = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case MESSAGE: if (value == null) { unsetMessage(); } else { setMessage((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case MESSAGE: return getMessage(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case MESSAGE: return isSetMessage(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof ResponseDetail) return this.equals((ResponseDetail)that); return false; } public boolean equals(ResponseDetail that) { if (that == null) return false; boolean this_present_message = true && this.isSetMessage(); boolean that_present_message = true && that.isSetMessage(); if (this_present_message || that_present_message) { if (!(this_present_message && that_present_message)) return false; if (!this.message.equals(that.message)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_message = true && (isSetMessage()); list.add(present_message); if (present_message) list.add(message); return list.hashCode(); } @Override public int compareTo(ResponseDetail other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage()); if (lastComparison != 0) { return lastComparison; } if (isSetMessage()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("ResponseDetail("); boolean first = true; sb.append("message:"); if (this.message == null) { sb.append("null"); } else { sb.append(this.message); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class ResponseDetailStandardSchemeFactory implements SchemeFactory { public ResponseDetailStandardScheme getScheme() { return new ResponseDetailStandardScheme(); } } private static class ResponseDetailStandardScheme extends StandardScheme<ResponseDetail> { public void read(org.apache.thrift.protocol.TProtocol iprot, ResponseDetail struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // MESSAGE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.message = iprot.readString(); struct.setMessageIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, ResponseDetail struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.message != null) { oprot.writeFieldBegin(MESSAGE_FIELD_DESC); oprot.writeString(struct.message); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class ResponseDetailTupleSchemeFactory implements SchemeFactory { public ResponseDetailTupleScheme getScheme() { return new ResponseDetailTupleScheme(); } } private static class ResponseDetailTupleScheme extends TupleScheme<ResponseDetail> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, ResponseDetail struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetMessage()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetMessage()) { oprot.writeString(struct.message); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, ResponseDetail struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.message = iprot.readString(); struct.setMessageIsSet(true); } } } }
{ "content_hash": "08aa27b4f1fe853c02477a4e48c022e1", "timestamp": "", "source": "github", "line_count": 399, "max_line_length": 178, "avg_line_length": 29.959899749373434, "alnum_prop": 0.6811109252133177, "repo_name": "gouravshenoy/airavata", "id": "5d83590c1f2cce58ad611f6b864c420b42f0be17", "size": "12765", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/ResponseDetail.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5598" }, { "name": "C", "bytes": "53885" }, { "name": "C++", "bytes": "7147253" }, { "name": "CSS", "bytes": "26656" }, { "name": "HTML", "bytes": "84328" }, { "name": "Java", "bytes": "34853075" }, { "name": "PHP", "bytes": "294193" }, { "name": "Python", "bytes": "295765" }, { "name": "Shell", "bytes": "58504" }, { "name": "Thrift", "bytes": "423314" }, { "name": "XSLT", "bytes": "34643" } ], "symlink_target": "" }
#include <dae.h> #include <dae/daeDom.h> #include <dom/domTranslate.h> #include <dae/daeMetaCMPolicy.h> #include <dae/daeMetaSequence.h> #include <dae/daeMetaChoice.h> #include <dae/daeMetaGroup.h> #include <dae/daeMetaAny.h> #include <dae/daeMetaElementAttribute.h> daeElementRef domTranslate::create(DAE& dae) { domTranslateRef ref = new domTranslate(dae); return ref; } daeMetaElement * domTranslate::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "translate" ); meta->registerClass(domTranslate::create); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaArrayAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("Float3")); ma->setOffset( daeOffsetOf( domTranslate , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } // Add attribute: sid { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "sid" ); ma->setType( dae.getAtomicTypes().get("xsNCName")); ma->setOffset( daeOffsetOf( domTranslate , attrSid )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domTranslate)); meta->validate(); return meta; }
{ "content_hash": "8e953f26f5ec0d00d9822cec5baa5a49", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 56, "avg_line_length": 22.137931034482758, "alnum_prop": 0.7040498442367601, "repo_name": "veter-team/daeview", "id": "2d3e0582a16cc4c9d5fc980f27c9b8ab05c8ed0a", "size": "1492", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/collada-dom/1.4/dom/domTranslate.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2402158" }, { "name": "C++", "bytes": "8792611" }, { "name": "Objective-C", "bytes": "100424" }, { "name": "Python", "bytes": "949" } ], "symlink_target": "" }
/*! Lightning Design System 2.16.0-beta.2 */ @charset "UTF-8"; @media (pointer: coarse) and (hover: none){ body{ font-size:1rem; } .slds-button.slds-accordion__summary-action{ line-height:1.875rem; } .slds-button{ --sds-c-button-line-height:2.625rem; font-weight:700; } .slds-button_icon, .slds-button--icon, .slds-button_icon-inverse, .slds-button--icon-inverse, .slds-button_icon-container, .slds-button--icon-container, .slds-button_icon-border, .slds-button--icon-border, .slds-button_icon-border-filled, .slds-button--icon-border-filled, .slds-button_icon-border-inverse, .slds-button--icon-border-inverse, .slds-button_icon-more, .slds-button--icon-more, .slds-button_icon-error, .slds-button--icon-error{ width:2.75rem; height:2.75rem; } .slds-button_icon-container, .slds-button--icon-container, .slds-button_icon-border, .slds-button--icon-border, .slds-button_icon-border-filled, .slds-button--icon-border-filled, .slds-button_icon-border-inverse, .slds-button--icon-border-inverse, .slds-button_icon-brand, .slds-button_icon-more, .slds-button--icon-more, .slds-button_icon-container-more, .slds-button--icon-container-more{ width:2.75rem; height:2.75rem; } .slds-button_icon-small, .slds-button--icon-small{ width:2.75rem; height:2.75rem; } .slds-button_icon-x-small, .slds-button--icon-x-small{ width:2.75rem; height:2.75rem; } .slds-button_icon-xx-small, .slds-button--icon-xx-small{ width:2.75rem; height:2.75rem; } .slds-button_icon-more, .slds-button--icon-more{ width:2.75rem; height:2.75rem; } .slds-card{ border-color:transparent; border-radius:0; } .slds-card__header-title{ font-size:1.125rem; font-weight:700; } .slds-checkbox_button-group, .slds-checkbox--button-group{ display:block; } .slds-checkbox_button-group .slds-checkbox_button, .slds-checkbox_button-group .slds-checkbox--button, .slds-checkbox--button-group .slds-checkbox_button, .slds-checkbox--button-group .slds-checkbox--button{ display:block; } .slds-checkbox_button-group .slds-checkbox_button + .slds-checkbox_button, .slds-checkbox_button-group .slds-checkbox--button + .slds-checkbox--button, .slds-checkbox--button-group .slds-checkbox_button + .slds-checkbox_button, .slds-checkbox--button-group .slds-checkbox--button + .slds-checkbox--button{ border-left:0; border-top:1px solid #dddbda; } .slds-checkbox_button-group .slds-checkbox_button:first-child > .slds-checkbox_button__label, .slds-checkbox_button-group .slds-checkbox--button:first-child > .slds-checkbox--button__label, .slds-checkbox--button-group .slds-checkbox_button:first-child > .slds-checkbox_button__label, .slds-checkbox--button-group .slds-checkbox--button:first-child > .slds-checkbox--button__label{ border-radius:0.25rem 0.25rem 0 0; } .slds-checkbox_button-group .slds-checkbox_button:last-child > .slds-checkbox_button__label, .slds-checkbox_button-group .slds-checkbox--button:last-child > .slds-checkbox--button__label, .slds-checkbox--button-group .slds-checkbox_button:last-child > .slds-checkbox_button__label, .slds-checkbox--button-group .slds-checkbox--button:last-child > .slds-checkbox--button__label{ border-radius:0 0 0.25rem 0.25rem; } .slds-checkbox_button-group .slds-checkbox_button__label, .slds-checkbox_button-group .slds-checkbox--button__label, .slds-checkbox--button-group .slds-checkbox_button__label, .slds-checkbox--button-group .slds-checkbox--button__label{ display:block; text-align:center; } .slds-checkbox_button, .slds-checkbox--button{ line-height:2.625rem; } .slds-checkbox-button{ width:2.75rem; height:2.75rem; } .slds-checkbox_add-button, .slds-checkbox--add-button{ width:2.75rem; height:2.75rem; display:-webkit-box; display:-ms-flexbox; display:flex; -webkit-box-align:center; -ms-flex-align:center; align-items:center; -webkit-box-pack:center; -ms-flex-pack:center; justify-content:center; } .slds-checkbox_add-button .slds-checkbox_faux, .slds-checkbox_add-button .slds-checkbox--faux, .slds-checkbox--add-button .slds-checkbox_faux, .slds-checkbox--add-button .slds-checkbox--faux{ width:2rem; height:2rem; } .slds-checkbox_toggle, .slds-checkbox--toggle{ padding:0.125rem 0; } .slds-checkbox_toggle .slds-form-element__label, .slds-checkbox--toggle .slds-form-element__label{ -webkit-box-align:start; -ms-flex-align:start; align-items:flex-start; font-size:1rem; } .slds-checkbox_toggle [type=checkbox] + .slds-checkbox_faux_container, .slds-checkbox_toggle [type=checkbox] + .slds-checkbox--faux_container, .slds-checkbox--toggle [type=checkbox] + .slds-checkbox_faux_container, .slds-checkbox--toggle [type=checkbox] + .slds-checkbox--faux_container{ font-size:0.75rem; } .slds-checkbox .slds-checkbox_faux, .slds-checkbox .slds-checkbox--faux{ width:1.5rem; height:1.5rem; -ms-flex-negative:0; flex-shrink:0; } .slds-checkbox .slds-checkbox__label{ display:-webkit-inline-box; display:-ms-inline-flexbox; display:inline-flex; -webkit-box-align:center; -ms-flex-align:center; align-items:center; vertical-align:middle; min-height:2.75rem; } .slds-checkbox .slds-checkbox__label .slds-form-element__label{ display:-webkit-inline-box; display:-ms-inline-flexbox; display:inline-flex; font-size:1rem; } .slds-checkbox [type=checkbox]:checked + .slds-checkbox_faux:after, .slds-checkbox [type=checkbox]:checked + .slds-checkbox--faux:after, .slds-checkbox [type=checkbox]:checked ~ .slds-checkbox_faux:after, .slds-checkbox [type=checkbox]:checked ~ .slds-checkbox--faux:after, .slds-checkbox [type=checkbox]:checked + .slds-checkbox__label .slds-checkbox_faux:after, .slds-checkbox [type=checkbox]:checked + .slds-checkbox__label .slds-checkbox--faux:after{ height:0.375rem; width:0.75rem; margin-top:-1px; } .slds-checkbox [type=checkbox]:indeterminate + .slds-checkbox_faux:after, .slds-checkbox [type=checkbox]:indeterminate + .slds-checkbox--faux:after, .slds-checkbox [type=checkbox]:indeterminate ~ .slds-checkbox_faux:after, .slds-checkbox [type=checkbox]:indeterminate ~ .slds-checkbox--faux:after, .slds-checkbox [type=checkbox]:indeterminate + .slds-checkbox__label .slds-checkbox_faux:after, .slds-checkbox [type=checkbox]:indeterminate + .slds-checkbox__label .slds-checkbox--faux:after{ width:0.75rem; } .slds-checkbox.slds-checkbox_stacked .slds-form-element__label{ font-size:0.875rem; } .slds-checkbox_standalone{ min-height:2.75rem; } .slds-checkbox_standalone [type=checkbox]{ width:2.75rem; height:2.75rem; position:absolute; top:50%; -webkit-transform:translateY(-50%); transform:translateY(-50%); } .slds-checkbox_standalone .slds-checkbox_faux{ position:absolute; top:50%; -webkit-transform:translateY(-50%); transform:translateY(-50%); } .slds-listbox_horizontal li + li, .slds-listbox--horizontal li + li{ padding-left:0.25rem; } .slds-listbox__option-header{ font-size:1rem; } .slds-listbox_vertical .slds-listbox__option_plain, .slds-listbox_vertical .slds-listbox__option--plain, .slds-listbox--vertical .slds-listbox__option_plain, .slds-listbox--vertical .slds-listbox__option--plain{ line-height:2.75rem; padding-top:0; padding-bottom:0; -webkit-box-align:center; -ms-flex-align:center; align-items:center; } .slds-listbox_vertical .slds-listbox__option_plain .slds-media__figure, .slds-listbox_vertical .slds-listbox__option--plain .slds-media__figure, .slds-listbox--vertical .slds-listbox__option_plain .slds-media__figure, .slds-listbox--vertical .slds-listbox__option--plain .slds-media__figure{ margin-right:0.5rem; } .slds-listbox_object-switcher, .slds-listbox--object-switcher{ padding:0; } .slds-combobox_object-switcher .slds-combobox__input{ font-size:1rem; } .slds-listbox_selection-group{ height:2.75rem; } .slds-listbox_selection-group .slds-listbox{ padding:0 0.25rem 0.375rem; } .slds-listbox_selection-group .slds-listbox-item{ padding:0.375rem 0.125rem 0; } .slds-has-inline-listbox .slds-combobox__input, .slds-has-object-switcher .slds-combobox__input{ line-height:2.5rem; min-height:2.75rem; } .slds-has-inline-listbox [role=listbox]{ padding:0 0.375rem; } .slds-th__action{ padding-right:1.25rem; } .slds-form-element__label{ display:-webkit-inline-box; display:-ms-inline-flexbox; display:inline-flex; -webkit-box-align:center; -ms-flex-align:center; align-items:center; min-height:2rem; padding-top:0; padding-right:0; margin-bottom:0; font-size:0.875rem; } .slds-form-element__icon .slds-button_icon{ height:2rem; } .slds-form-element__control .slds-form-element__icon .slds-button_icon{ height:2.75rem; } .slds-form-element__icon{ padding-top:0; } .slds-form-element_edit .slds-form-element__static, .slds-form-element--edit .slds-form-element__static{ width:calc(100% - 2.75rem); } .slds-form-element_readonly .slds-icon{ width:1.5rem; height:1.5rem; } .slds-form-element__static{ font-size:1rem; } .slds-form-element_horizontal .slds-button_icon, .slds-form_horizontal .slds-form-element .slds-button_icon, .slds-form_stacked .slds-form-element_horizontal .slds-button_icon{ vertical-align:top; } .slds-form-element_stacked .slds-form-element__icon, .slds-form_stacked .slds-form-element .slds-form-element__icon, .slds-form_horizontal .slds-form-element_stacked .slds-form-element__icon{ padding-top:0; } .slds-input, .slds-input_faux{ line-height:2.625rem; } .slds-input{ line-height:2.625rem; } .slds-input[readonly]{ font-size:1rem; } .slds-input[type=text], .slds-input[type=email], .slds-input[type=url], .slds-input[type=tel]{ -webkit-appearance:none; } .slds-input[type=date], .slds-input[type=datetime], .slds-input[type=datetime-local], .slds-input[type=time], .slds-input[type=week], .slds-input[type=month]{ display:-webkit-inline-box; display:-ms-inline-flexbox; display:inline-flex; } .slds-input[type=date], .slds-input[type=datetime-local], .slds-input[type=month], .slds-input[type=time]{ height:2.75rem; } .slds-input-has-icon .slds-input__icon{ width:1rem; height:1rem; margin-top:-0.5rem; } .slds-input-has-icon_left .slds-input__icon, .slds-input-has-icon--left .slds-input__icon{ left:0.5rem; } .slds-input-has-icon_right .slds-input__icon, .slds-input-has-icon--right .slds-input__icon{ right:0.5rem; } .slds-input-has-icon_left-right .slds-input__icon_left, .slds-input-has-icon_left-right .slds-input__icon--left, .slds-input-has-icon--left-right .slds-input__icon_left, .slds-input-has-icon--left-right .slds-input__icon--left{ left:0.5rem; } .slds-input-has-icon_left-right .slds-input__icon_right, .slds-input-has-icon_left-right .slds-input__icon--right, .slds-input-has-icon--left-right .slds-input__icon_right, .slds-input-has-icon--left-right .slds-input__icon--right{ right:0.5rem; } .slds-input__icon-group_right .slds-input__spinner{ right:calc(1.5rem + 0.25rem); } .slds-map_container{ padding:1rem 1rem 0; } .slds-map{ min-width:21.75rem; } .slds-has-coordinates{ max-height:none; } .slds-coordinates__title{ font-size:1.125rem; } .slds-dropdown{ padding:0; font-size:1rem; } .slds-dropdown__item > a{ line-height:2.75rem; padding:0 0.75rem; } .slds-dropdown__header{ font-size:1rem; } .slds-modal .slds-modal__title{ font-weight:700; } .slds-modal__close{ width:2.75rem; height:2.75rem; top:-2.75rem; right:0; } .slds-path__nav .slds-is-current:first-child .slds-path__link{ height:calc(2.75rem - 0.25rem); } .slds-path__nav .slds-is-active:first-child .slds-path__link{ height:2.75rem; } .slds-path__item{ margin-left:0.5rem; margin-right:0.5625rem; } .slds-path__item:before, .slds-path__item:after{ left:-0.3125rem; right:-0.375rem; } .slds-path__item:before{ height:calc((2.75rem / 2) + 0.0625rem); } .slds-path__item:after{ height:1.375rem; } .slds-path__item:first-child:before, .slds-path__item:first-child:after{ left:1.625rem; } .slds-path__item:last-child:before, .slds-path__item:last-child:after{ right:1.125rem; } .slds-path__link{ height:2.75rem; } .slds-pill{ line-height:1.875rem; padding:0 0.5rem; } .slds-pill + .slds-pill{ margin-left:0.25rem; } .slds-pill__container, .slds-pill-container, .slds-pill_container{ padding:0.25rem; } .slds-pill__label{ font-size:0.875rem; } .slds-pill__icon ~ .slds-pill__action, .slds-pill__icon_container ~ .slds-pill__action{ padding-left:calc(1.25rem + 0.5rem); } .slds-pill_link, .slds-pill--link{ padding:0; } .slds-pill_link .slds-pill__icon_container, .slds-pill--link .slds-pill__icon_container{ left:0.25rem; } .slds-pill_link .slds-pill__remove, .slds-pill--link .slds-pill__remove{ right:0; width:2rem; height:2rem; margin:0; border:0; } .slds-pill_link__icon ~ .slds-pill__action, .slds-pill_link__icon_container ~ .slds-pill__action, .slds-pill--link__icon ~ .slds-pill__action, .slds-pill--link__icon_container ~ .slds-pill__action{ padding-left:calc(1.25rem + 0.5rem); } .slds-pill__action{ padding:0; padding-left:0.5rem; padding-right:2rem; } .slds-popover_prompt__heading{ font-size:1.25rem; } .slds-progress__item{ position:relative; -webkit-box-align:center; -ms-flex-align:center; align-items:center; min-height:2.75rem; } .slds-progress__item .slds-button:before{ position:absolute; width:calc(100% + 8px); height:2.75rem; content:""; } .slds-progress__marker{ width:1.25rem; height:1.25rem; line-height:1; } .slds-progress__marker_icon{ width:2rem; height:2rem; } .slds-progress__marker_icon .slds-button__icon{ width:1.25rem; height:1.25rem; } .slds-progress_vertical .slds-progress__item:before, .slds-progress_vertical .slds-progress__item:after{ left:calc((1.25rem / 2) - 1px); } .slds-progress_vertical .slds-progress__item_content{ font-size:0.875rem; } .slds-progress_vertical .slds-progress__marker{ width:1.25rem; } .slds-progress_vertical .slds-progress__marker .slds-icon{ width:1.25rem; height:1.25rem; } .slds-radio_button-group, .slds-radio--button-group{ display:block; } .slds-radio_button-group .slds-radio_button, .slds-radio_button-group .slds-radio--button, .slds-radio--button-group .slds-radio_button, .slds-radio--button-group .slds-radio--button{ display:block; } .slds-radio_button-group .slds-radio_button + .slds-radio_button, .slds-radio_button-group .slds-radio--button + .slds-radio--button, .slds-radio--button-group .slds-radio_button + .slds-radio_button, .slds-radio--button-group .slds-radio--button + .slds-radio--button{ border-left:0; border-top:1px solid #dddbda; } .slds-radio_button-group .slds-radio_button:first-child > .slds-radio_button__label, .slds-radio_button-group .slds-radio--button:first-child > .slds-radio--button__label, .slds-radio--button-group .slds-radio_button:first-child > .slds-radio_button__label, .slds-radio--button-group .slds-radio--button:first-child > .slds-radio--button__label{ border-radius:0.25rem 0.25rem 0 0; } .slds-radio_button-group .slds-radio_button:last-child > .slds-radio_button__label, .slds-radio_button-group .slds-radio--button:last-child > .slds-radio--button__label, .slds-radio--button-group .slds-radio_button:last-child > .slds-radio_button__label, .slds-radio--button-group .slds-radio--button:last-child > .slds-radio--button__label{ border-radius:0 0 0.25rem 0.25rem; } .slds-radio_button-group .slds-radio_button__label, .slds-radio_button-group .slds-radio--button__label, .slds-radio--button-group .slds-radio_button__label, .slds-radio--button-group .slds-radio--button__label{ display:block; text-align:center; } .slds-radio_button, .slds-radio--button{ line-height:2.69rem; } .slds-radio .slds-radio__label{ display:-webkit-box; display:-ms-flexbox; display:flex; -webkit-box-align:center; -ms-flex-align:center; align-items:center; min-height:2.75rem; } .slds-radio .slds-radio_faux, .slds-radio .slds-radio--faux{ width:1.5rem; height:1.5rem; } .slds-radio .slds-form-element__label{ display:-webkit-inline-box; display:-ms-inline-flexbox; display:inline-flex; font-size:1rem; } .slds-slider{ -webkit-box-align:center; -ms-flex-align:center; align-items:center; margin-top:0.5rem; min-height:2rem; } .slds-slider__range::-webkit-slider-thumb{ height:2rem; width:2rem; margin-top:calc(((2rem / 2) - (4px / 2)) * -1); } .slds-slider__range::-moz-range-thumb{ height:2rem; width:2rem; } .slds-slider__range::-ms-thumb{ height:2rem; width:2rem; } .slds-slider_vertical{ -webkit-box-align:initial; -ms-flex-align:initial; align-items:initial; } .slds-slider_vertical .slds-slider__range{ margin-left:calc((2rem - 1rem) / 2); } .slds-slider_vertical .slds-slider__value{ left:calc((2rem - 1rem) / 2); } .slds-tabs-mobile__item .slds-button:active, .slds-tabs-mobile__item .slds-button:hover{ color:currentColor; } .slds-text-body_regular, .slds-text-body--regular{ font-size:1rem; } .slds-text-body_small, .slds-text-body--small{ font-size:0.875rem; } .slds-text-heading_large, .slds-text-heading--large{ font-size:2rem; } .slds-text-heading_medium, .slds-text-heading--medium{ font-size:1.5rem; } .slds-text-heading_small, .slds-text-heading--small{ font-size:1.25rem; } } @media (pointer: coarse) and (hover: none) and (min-width: 48em){ .slds-form-element_horizontal .slds-form-element__label, .slds-form_horizontal .slds-form-element .slds-form-element__label, .slds-form_stacked .slds-form-element_horizontal .slds-form-element__label{ display:block; max-width:calc(33% - 2.75rem); -ms-flex-preferred-size:calc(33% - 2.75rem); flex-basis:calc(33% - 2.75rem); padding-top:0.25rem; } .slds-form-element_horizontal .slds-form-element__control, .slds-form_horizontal .slds-form-element .slds-form-element__control, .slds-form_stacked .slds-form-element_horizontal .slds-form-element__control{ display:block; min-height:0; } .slds-form-element_horizontal .slds-form-element__icon, .slds-form_horizontal .slds-form-element .slds-form-element__icon, .slds-form_stacked .slds-form-element_horizontal .slds-form-element__icon{ padding-top:0; } .slds-form-element_horizontal .slds-checkbox__label, .slds-form_horizontal .slds-form-element .slds-checkbox__label, .slds-form_stacked .slds-form-element_horizontal .slds-checkbox__label{ display:block; } }
{ "content_hash": "712cb10893f686b910011526e334d8ab", "timestamp": "", "source": "github", "line_count": 668, "max_line_length": 492, "avg_line_length": 29.11676646706587, "alnum_prop": 0.6773264781491003, "repo_name": "cdnjs/cdnjs", "id": "95309b374382127867e5c6dbafa851d7b8895534", "size": "19450", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/design-system/2.16.0-beta.2/styles/salesforce-lightning-design-system_touch.css", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.apache.flink.yarn; import org.apache.flink.configuration.ConfigConstants; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.CoreOptions; import org.apache.flink.core.fs.FileSystem; import org.apache.flink.core.fs.Path; import org.apache.flink.runtime.fs.hdfs.HadoopFileSystem; import org.apache.flink.testutils.junit.RetryOnException; import org.apache.flink.testutils.junit.extensions.retry.RetryExtension; import org.apache.flink.testutils.s3.S3TestCredentials; import org.apache.hadoop.util.VersionUtil; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; import static org.assertj.core.api.Assumptions.assumeThatThrownBy; /** * Tests for verifying file staging during submission to YARN works with the S3A file system. * * <p>Note that the setup is similar to * <tt>org.apache.flink.fs.s3hadoop.HadoopS3FileSystemITCase</tt>. */ @ExtendWith(RetryExtension.class) class YarnFileStageTestS3ITCase { private static final Logger log = LoggerFactory.getLogger(YarnFileStageTestS3ITCase.class); private static final String TEST_DATA_DIR = "tests-" + UUID.randomUUID(); /** Number of tests executed. */ private static int numRecursiveUploadTests = 0; /** Will be updated by {@link #checkCredentialsAndSetup(File)} if the test is not skipped. */ private static boolean skipTest = true; @BeforeAll static void checkCredentialsAndSetup(@TempDir File tempFolder) throws IOException { // check whether credentials exist S3TestCredentials.assumeCredentialsAvailable(); skipTest = false; setupCustomHadoopConfig(tempFolder); } @AfterAll static void resetFileSystemConfiguration() { FileSystem.initialize(new Configuration()); } @AfterAll static void checkAtLeastOneTestRun() { if (!skipTest) { assertThat(numRecursiveUploadTests) .as( "No S3 filesystem upload test executed. Please activate the " + "'include_hadoop_aws' build profile or set '-Dinclude_hadoop_aws' during build " + "(Hadoop >= 2.6 moved S3 filesystems out of hadoop-common).") .isGreaterThan(0); } } /** * Create a Hadoop config file containing S3 access credentials. * * <p>Note that we cannot use them as part of the URL since this may fail if the credentials * contain a "/" (see <a * href="https://issues.apache.org/jira/browse/HADOOP-3733">HADOOP-3733</a>). */ private static void setupCustomHadoopConfig(File tempFolder) throws IOException { File hadoopConfig = Files.createTempFile(tempFolder.toPath(), UUID.randomUUID().toString(), "") .toFile(); Map<String /* key */, String /* value */> parameters = new HashMap<>(); // set all different S3 fs implementation variants' configuration keys parameters.put("fs.s3a.access.key", S3TestCredentials.getS3AccessKey()); parameters.put("fs.s3a.secret.key", S3TestCredentials.getS3SecretKey()); parameters.put("fs.s3.awsAccessKeyId", S3TestCredentials.getS3AccessKey()); parameters.put("fs.s3.awsSecretAccessKey", S3TestCredentials.getS3SecretKey()); parameters.put("fs.s3n.awsAccessKeyId", S3TestCredentials.getS3AccessKey()); parameters.put("fs.s3n.awsSecretAccessKey", S3TestCredentials.getS3SecretKey()); try (PrintStream out = new PrintStream(new FileOutputStream(hadoopConfig))) { out.println("<?xml version=\"1.0\"?>"); out.println("<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>"); out.println("<configuration>"); for (Map.Entry<String, String> entry : parameters.entrySet()) { out.println("\t<property>"); out.println("\t\t<name>" + entry.getKey() + "</name>"); out.println("\t\t<value>" + entry.getValue() + "</value>"); out.println("\t</property>"); } out.println("</configuration>"); } final Configuration conf = new Configuration(); conf.setString(ConfigConstants.HDFS_SITE_CONFIG, hadoopConfig.getAbsolutePath()); conf.set(CoreOptions.ALLOWED_FALLBACK_FILESYSTEMS, "s3;s3a;s3n"); FileSystem.initialize(conf, null); } /** * Verifies that nested directories are properly copied with to the given S3 path (using the * appropriate file system) during resource uploads for YARN. * * @param scheme file system scheme * @param pathSuffix test path suffix which will be the test's target path */ private void testRecursiveUploadForYarn(String scheme, String pathSuffix, File tempFolder) throws Exception { ++numRecursiveUploadTests; final Path basePath = new Path(S3TestCredentials.getTestBucketUriWithScheme(scheme) + TEST_DATA_DIR); final HadoopFileSystem fs = (HadoopFileSystem) basePath.getFileSystem(); assumeThat(fs.exists(basePath)).isTrue(); try { final Path directory = new Path(basePath, pathSuffix); YarnFileStageTest.testRegisterMultipleLocalResources( fs.getHadoopFileSystem(), new org.apache.hadoop.fs.Path(directory.toUri()), Path.CUR_DIR, tempFolder, false, false); } finally { // clean up fs.delete(basePath, true); } } @TestTemplate @RetryOnException(times = 3, exception = Exception.class) void testRecursiveUploadForYarnS3n(@TempDir File tempFolder) throws Exception { // skip test on Hadoop 3: https://issues.apache.org/jira/browse/HADOOP-14738 assumeThat(VersionUtil.compareVersions(System.getProperty("hadoop.version"), "3.0.0") < 0) .as("This test is skipped for Hadoop versions above 3") .isTrue(); assumeThatThrownBy(() -> Class.forName("org.apache.hadoop.fs.s3native.NativeS3FileSystem")) .as("Skipping test because NativeS3FileSystem is not in the class path") .isNull(); testRecursiveUploadForYarn("s3n", "testYarn-s3n", tempFolder); } @TestTemplate @RetryOnException(times = 3, exception = Exception.class) public void testRecursiveUploadForYarnS3a(@TempDir File tempFolder) throws Exception { assumeThatThrownBy(() -> Class.forName("org.apache.hadoop.fs.s3a.S3AFileSystem")) .as("Skipping test because S3AFileSystem is not in the class path") .isNull(); testRecursiveUploadForYarn("s3a", "testYarn-s3a", tempFolder); } }
{ "content_hash": "8bd88b7f9eab7dfc7f02fc8eadb62dc8", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 118, "avg_line_length": 40.83425414364641, "alnum_prop": 0.6647273711270464, "repo_name": "xccui/flink", "id": "de576418d15a6c9d63fc4966c9e60b059949a2f7", "size": "8196", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "flink-yarn/src/test/java/org/apache/flink/yarn/YarnFileStageTestS3ITCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "20596" }, { "name": "Batchfile", "bytes": "1863" }, { "name": "C", "bytes": "847" }, { "name": "Cython", "bytes": "138311" }, { "name": "Dockerfile", "bytes": "5579" }, { "name": "FreeMarker", "bytes": "100031" }, { "name": "GAP", "bytes": "139536" }, { "name": "HTML", "bytes": "188041" }, { "name": "HiveQL", "bytes": "213569" }, { "name": "Java", "bytes": "98600106" }, { "name": "JavaScript", "bytes": "7038" }, { "name": "Less", "bytes": "84321" }, { "name": "Makefile", "bytes": "5134" }, { "name": "Python", "bytes": "3206355" }, { "name": "Scala", "bytes": "10942352" }, { "name": "Shell", "bytes": "528784" }, { "name": "TypeScript", "bytes": "391270" }, { "name": "q", "bytes": "16671" } ], "symlink_target": "" }
from trex_stl_lib.api import * from trex_stl_lib.utils import parsing_opts, text_tables import threading import tempfile import select from distutils import spawn from subprocess import Popen import subprocess # defines a generic monitor writer class CaptureMonitorWriter(object): def deinit(self): # by default - nothing to deinit pass def handle_pkts (self, pkts): raise NotImplementedError def periodic_check (self): # by default - nothing to check pass # a stdout monitor class CaptureMonitorWriterStdout(CaptureMonitorWriter): def __init__ (self, logger, is_brief, start_ts): self.logger = logger self.is_brief = is_brief self.start_ts = start_ts # unicode arrows self.RX_ARROW = u'\u25c0\u2500\u2500' self.TX_ARROW = u'\u2500\u2500\u25b6' # decode issues with Python 2 if sys.version_info < (3,0): self.RX_ARROW = self.RX_ARROW.encode('utf-8') self.TX_ARROW = self.TX_ARROW.encode('utf-8') self.logger.pre_cmd("Starting stdout capture monitor - verbose: '{0}'".format('low' if self.is_brief else 'high')) self.logger.post_cmd(RC_OK()) self.logger.log(format_text("\n*** use 'capture monitor stop' to abort capturing... ***\n", 'bold')) def get_scapy_name (self, pkt_scapy): layer = pkt_scapy while layer.payload and layer.payload.name not in('Padding', 'Raw'): layer = layer.payload return layer.name def format_origin (self, origin): if origin == 'RX': return '{0} {1}'.format(self.RX_ARROW, 'RX') elif origin == 'TX': return '{0} {1}'.format(self.TX_ARROW, 'TX') else: return '{0}'.format(origin) def __handle_pkt (self, pkt): pkt_bin = base64.b64decode(pkt['binary']) pkt_scapy = Ether(pkt_bin) self.logger.log(format_text('\n\n#{} Port: {} {}\n'.format(pkt['index'], pkt['port'], self.format_origin(pkt['origin'])), 'bold', '')) self.logger.log(format_text(' Type: {}, Size: {} B, TS: {:.2f} [sec]\n'.format(self.get_scapy_name(pkt_scapy), len(pkt_bin), pkt['ts'] - self.start_ts), 'bold')) if self.is_brief: self.logger.log(' {0}'.format(pkt_scapy.command())) else: pkt_scapy.show(label_lvl = ' ') self.logger.log('') return len(pkt_bin) def handle_pkts (self, pkts): try: byte_count = 0 for pkt in pkts: byte_count += self.__handle_pkt(pkt) return byte_count finally: # make sure to restore the logger self.logger.prompt_redraw() # a pipe based monitor class CaptureMonitorWriterPipe(CaptureMonitorWriter): def __init__ (self, logger, start_ts): self.logger = logger self.fifo = None self.start_ts = start_ts # generate a temp fifo pipe self.fifo_name = tempfile.mktemp() self.wireshark_pid = None try: self.logger.pre_cmd('Starting pipe capture monitor') os.mkfifo(self.fifo_name) self.logger.post_cmd(RC_OK()) # try to locate wireshark on the machine self.wireshark_exe = self.locate_wireshark() # we found wireshark - try to launch a process if self.wireshark_exe: self.wireshark_pid = self.launch_wireshark() # did we succeed ? if not self.wireshark_pid: self.logger.log(format_text("*** Please manually run 'wireshark -k -i {0}' ***".format(self.fifo_name), 'bold')) # blocks until pipe is connected self.logger.pre_cmd("Waiting for Wireshark pipe connection") self.fifo = os.open(self.fifo_name, os.O_WRONLY) self.logger.post_cmd(RC_OK()) self.logger.log(format_text('\n*** Capture monitoring started ***\n', 'bold')) # open for write using a PCAP writer self.writer = RawPcapWriter(self.fifo_name, linktype = 1, sync = True) self.writer._write_header(None) # register a poller self.poll = select.poll() self.poll.register(self.fifo, select.EPOLLERR) self.is_init = True except KeyboardInterrupt as e: self.deinit() self.logger.post_cmd(RC_ERR("")) raise STLError("*** pipe monitor aborted...cleaning up") except OSError as e: self.deinit() self.logger.post_cmd(RC_ERR("")) raise STLError("failed to create pipe {0}\n{1}".format(self.fifo_name, str(e))) def locate_wireshark (self): self.logger.pre_cmd('Trying to locate Wireshark') wireshark_exe = spawn.find_executable('wireshark') self.logger.post_cmd(RC_OK() if wireshark_exe else RC_ERR()) if not wireshark_exe: return None dumpcap = os.path.join(os.path.dirname(wireshark_exe), 'dumpcap') self.logger.pre_cmd("Checking permissions on '{}'".format(dumpcap)) if not os.access(dumpcap, os.X_OK): self.logger.post_cmd(RC_ERR('bad permissions on dumpcap')) return None self.logger.post_cmd(RC_OK()) return wireshark_exe # try to launch wireshark... returns true on success def launch_wireshark (self): cmd = '{0} -k -i {1}'.format(self.wireshark_exe, self.fifo_name) self.logger.pre_cmd("Launching '{0}'".format(cmd)) try: devnull = open(os.devnull, 'w') self.wireshark_pid = Popen(cmd.split(), stdout = devnull, stderr = devnull, stdin = subprocess.PIPE, preexec_fn = os.setpgrp, close_fds = True) self.logger.post_cmd(RC_OK()) return True except OSError as e: self.wireshark_pid = None self.logger.post_cmd(RC_ERR()) return False def deinit (self): try: if self.fifo: os.close(self.fifo) self.fifo = None if self.fifo_name: os.unlink(self.fifo_name) self.fifo_name = None except OSError: pass def periodic_check (self): self.check_pipe() def check_pipe (self): if self.poll.poll(0): raise STLError('pipe has been disconnected') def handle_pkts (self, pkts): # first check the pipe is alive self.check_pipe() return self.handle_pkts_internal(pkts) def handle_pkts_internal (self, pkts): byte_count = 0 for pkt in pkts: pkt_bin = base64.b64decode(pkt['binary']) ts_sec, ts_usec = sec_split_usec(pkt['ts'] - self.start_ts) try: self.writer._write_packet(pkt_bin, sec = ts_sec, usec = ts_usec) except Exception as e: raise STLError('fail to write packets to pipe: {}'.format(str(e))) byte_count += len(pkt_bin) return byte_count # capture monitor - a live capture class CaptureMonitor(object): def __init__ (self, client, cmd_lock, tx_port_list, rx_port_list, rate_pps, mon_type, bpf_filter): self.client = client self.logger = client.logger self.cmd_lock = cmd_lock self.t = None self.writer = None self.capture_id = None self.tx_port_list = tx_port_list self.rx_port_list = rx_port_list self.rate_pps = rate_pps self.mon_type = mon_type self.bpf_filter = bpf_filter # try to launch try: self.__start() except Exception as e: self.__stop() raise def __start (self): # create a capture on the server with self.logger.supress(): data = self.client.start_capture(self.tx_port_list, self.rx_port_list, limit = self.rate_pps, mode = 'cyclic', bpf_filter = self.bpf_filter) self.capture_id = data['id'] start_ts = data['ts'] # create a writer if self.mon_type == 'compact': self.writer = CaptureMonitorWriterStdout(self.logger, True, start_ts) elif self.mon_type == 'verbose': self.writer = CaptureMonitorWriterStdout(self.logger, False, start_ts) elif self.mon_type == 'pipe': self.writer = CaptureMonitorWriterPipe(self.logger, start_ts) else: raise STLError('Internal error: unknown writer type') # start the fetching thread self.t = threading.Thread(target = self.__thread_cb) self.t.setDaemon(True) self.active = True self.t.start() # internal stop def __stop (self): # stop the thread if self.t and self.t.is_alive(): self.active = False self.t.join() self.t = None # deinit the writer if self.writer: self.writer.deinit() self.writer = None # user call for stop (adds log) def stop (self): self.logger.pre_cmd("Stopping capture monitor") try: self.__stop() except Exception as e: self.logger.post_cmd(RC_ERR("")) raise self.logger.post_cmd(RC_OK()) def get_mon_row (self): return [self.capture_id, format_text('ACTIVE' if self.t.is_alive() else 'DEAD', 'bold'), format_num(self.matched, compact = False), self.pkt_count, format_num(self.byte_count, suffix = 'B'), ', '.join([str(x) for x in self.tx_port_list] if self.tx_port_list else '-'), ', '.join([str(x) for x in self.rx_port_list] if self.rx_port_list else '-'), self.bpf_filter or '-', ] def is_active (self): return self.active def get_capture_id (self): return self.capture_id # sleeps with high freq checks for active def __sleep (self): for _ in range(5): if not self.active: return False time.sleep(0.1) return True def __lock (self): while True: rc = self.cmd_lock.acquire(False) if rc: return True if not self.active: return False time.sleep(0.1) def __unlock (self): self.cmd_lock.release() def __thread_cb (self): try: self.__thread_main_loop() # common errors except STLError as e: self.logger.log(format_text("\n\nMonitor has encountered the following error: '{}'\n".format(e.brief()), 'bold')) self.logger.log(format_text("\n*** monitor is inactive - please restart the monitor ***\n", 'bold')) self.logger.prompt_redraw() # unexpected errors except Exception as e: self.logger.log("\n\n*** A fatal internal error has occurred: '{}'\n".format(str(e))) self.logger.log(format_text("\n*** monitor is inactive - please restart the monitor ***\n", 'bold')) self.logger.prompt_redraw() finally: try: # to remove the capture as best effort with self.logger.supress(): self.client.stop_capture(self.capture_id) except: pass if self.writer: self.writer.deinit() self.writer = None def __thread_main_loop (self): self.pkt_count = 0 self.byte_count = 0 while self.active: # sleep - if interrupt by graceful shutdown - go out if not self.__sleep(): return # check that the writer is ok self.writer.periodic_check() # try to lock - if interrupt by graceful shutdown - go out if not self.__lock(): return try: if not self.client.is_connected(): raise STLError('client has been disconnected') rc = self.client._transmit("capture", params = {'command': 'fetch', 'capture_id': self.capture_id, 'pkt_limit': 10}) if not rc: raise STLError(rc) finally: self.__unlock() # no packets - skip pkts = rc.data()['pkts'] if not pkts: continue byte_count = self.writer.handle_pkts(pkts) self.pkt_count += len(pkts) self.byte_count += byte_count # main class class CaptureManager(object): def __init__ (self, client, cmd_lock): self.c = client self.cmd_lock = cmd_lock self.logger = client.logger self.monitor = None # install parsers self.parser = parsing_opts.gen_parser(self, "capture", self.parse_line_internal.__doc__) self.subparsers = self.parser.add_subparsers(title = "commands", dest="commands") self.install_record_parser() self.install_monitor_parser() # show self.show_parser = self.subparsers.add_parser('show', help = "show all active captures") # reset self.clear_parser = self.subparsers.add_parser('clear', help = "remove all active captures") # register handlers self.cmds = {'record': self.parse_record, 'monitor' : self.parse_monitor, 'clear': self.parse_clear, 'show' : self.parse_show} def install_record_parser (self): # recording self.record_parser = self.subparsers.add_parser('record', help = "PCAP recording") record_sub = self.record_parser.add_subparsers(title = 'commands', dest = 'record_cmd') self.record_start_parser = record_sub.add_parser('start', help = "starts a new buffered capture") self.record_stop_parser = record_sub.add_parser('stop', help = "stops an active buffered capture") # start self.record_start_parser.add_arg_list(parsing_opts.TX_PORT_LIST, parsing_opts.RX_PORT_LIST, parsing_opts.LIMIT, parsing_opts.BPF_FILTER) # stop self.record_stop_parser.add_arg_list(parsing_opts.CAPTURE_ID, parsing_opts.OUTPUT_FILENAME) def install_monitor_parser (self): # monitor self.monitor_parser = self.subparsers.add_parser('monitor', help = 'live monitoring') monitor_sub = self.monitor_parser.add_subparsers(title = 'commands', dest = 'mon_cmd') self.monitor_start_parser = monitor_sub.add_parser('start', help = 'starts a monitor') self.monitor_stop_parser = monitor_sub.add_parser('stop', help = 'stops an active monitor') self.monitor_start_parser.add_arg_list(parsing_opts.TX_PORT_LIST, parsing_opts.RX_PORT_LIST, parsing_opts.MONITOR_TYPE, parsing_opts.BPF_FILTER) def stop (self): if self.monitor: self.monitor.stop() self.monitor = None # main entry point for parsing commands from console def parse_line (self, line): try: self.parse_line_internal(line) except STLError as e: self.logger.log("\nAction has failed with the following error:\n\n" + format_text(e.brief() + "\n", 'bold')) return RC_ERR(e.brief()) def parse_line_internal (self, line): '''Manage PCAP recorders''' # default if not line: line = "show" opts = self.parser.parse_args(line.split()) if not opts: return opts # call the handler self.cmds[opts.commands](opts) # record methods def parse_record (self, opts): if opts.record_cmd == 'start': self.parse_record_start(opts) elif opts.record_cmd == 'stop': self.parse_record_stop(opts) else: self.record_parser.formatted_error("too few arguments") def parse_record_start (self, opts): if not opts.tx_port_list and not opts.rx_port_list: self.record_start_parser.formatted_error('please provide either --tx or --rx') return rc = self.c.start_capture(opts.tx_port_list, opts.rx_port_list, opts.limit, mode = 'fixed', bpf_filter = opts.filter) self.logger.log(format_text("*** Capturing ID is set to '{0}' ***".format(rc['id']), 'bold')) self.logger.log(format_text("*** Please call 'capture record stop --id {0} -o <out.pcap>' when done ***\n".format(rc['id']), 'bold')) def parse_record_stop (self, opts): ids = self.c.get_capture_status().keys() if self.monitor and (opts.capture_id == self.monitor.get_capture_id()): self.record_stop_parser.formatted_error("'{0}' is a monitor, please use 'capture monitor stop'".format(opts.capture_id)) return if opts.capture_id not in ids: self.record_stop_parser.formatted_error("'{0}' is not an active capture ID".format(opts.capture_id)) return self.c.stop_capture(opts.capture_id, opts.output_filename) # monitor methods def parse_monitor (self, opts): if opts.mon_cmd == 'start': self.parse_monitor_start(opts) elif opts.mon_cmd == 'stop': self.parse_monitor_stop(opts) else: self.monitor_parser.formatted_error("too few arguments") def parse_monitor_start (self, opts): mon_type = 'compact' if opts.verbose: mon_type = 'verbose' elif opts.pipe: mon_type = 'pipe' if not opts.tx_port_list and not opts.rx_port_list: self.monitor_start_parser.formatted_error('please provide either --tx or --rx') return if self.monitor: if self.monitor.is_active(): self.logger.log(format_text('*** Stopping old monitor to open new one. ***', 'bold')) self.monitor.stop() self.monitor = None self.monitor = CaptureMonitor(self.c, self.cmd_lock, opts.tx_port_list, opts.rx_port_list, 100, mon_type, opts.filter) def parse_monitor_stop (self, opts): if self.monitor: self.monitor.stop() self.monitor = None def parse_clear (self, opts): if self.monitor: self.monitor.stop() self.monitor = None self.c.remove_all_captures() def parse_show (self, opts): data = self.c.get_capture_status() # captures cap_table = text_tables.TRexTextTable() cap_table.set_cols_align(["c"] * 8) cap_table.set_cols_width([15] * 8) # monitor mon_table = text_tables.TRexTextTable() mon_table.set_cols_align(["c"] * 8) mon_table.set_cols_width([15] * 8) for capture_id, elem in data.items(): if self.monitor and (self.monitor.get_capture_id() == capture_id): self.monitor.matched = elem['matched'] row = self.monitor.get_mon_row() mon_table.add_rows([row], header=False) else: row = [capture_id, format_text(elem['state'], 'bold'), format_num(elem['matched'], compact = False), '[{0}/{1}]'.format(elem['count'], elem['limit']), format_num(elem['bytes'], suffix = 'B'), bitfield_to_str(elem['filter']['tx']), bitfield_to_str(elem['filter']['rx']), elem['filter']['bpf'] or '-'] cap_table.add_rows([row], header=False) cap_table.header(['ID', 'Status', 'Matched', 'Packets', 'Bytes', 'TX Ports', 'RX Ports', 'BPF Filter']) mon_table.header(['ID', 'Status', 'Matched', 'Packets Seen', 'Bytes Seen', 'TX Ports', 'RX Ports', 'BPF Filter']) if cap_table._rows: text_tables.print_table_with_header(cap_table, '\nActive Recorders') if mon_table._rows: text_tables.print_table_with_header(mon_table, '\nActive Monitor')
{ "content_hash": "c48845a61d6e4ec1fed27e216c336f4f", "timestamp": "", "source": "github", "line_count": 655, "max_line_length": 172, "avg_line_length": 33.966412213740455, "alnum_prop": 0.5084501977705861, "repo_name": "kisel/trex-core", "id": "5673adc74bc83cc7e4371e9db32f2480de2ad902", "size": "22248", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "scripts/automation/trex_control_plane/stl/console/trex_capture.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "16355010" }, { "name": "C++", "bytes": "4832431" }, { "name": "CMake", "bytes": "8882" }, { "name": "CSS", "bytes": "333" }, { "name": "HTML", "bytes": "5012" }, { "name": "JavaScript", "bytes": "1234" }, { "name": "Makefile", "bytes": "163741" }, { "name": "Python", "bytes": "12389428" }, { "name": "Shell", "bytes": "22573" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"/> <title>Capabilities</title> <link rel="shortcut icon" href="favicon.ico"> <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css"> <!--[if IE 7]> <link rel="stylesheet" href="font-awesome/css/font-awesome-ie7.min.css"> <![endif]--><!-- JQuery --> <script type="text/javascript" src="scripts/jquery-1.11.1.min.js"></script><!-- Bootstrap --> <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"> <script src="bootstrap/js/bootstrap.min.js"></script><link rel="stylesheet" href="css/core.css"/> <link rel="stylesheet" href="css/link.css"/> <link type="text/css" media="screen" href="css/screen.css" rel="Stylesheet"/><!-- JQuery-UI --> <link type="text/css" href="jqueryui/1.11.2-start/jquery-ui.min.css" rel="Stylesheet" /> <script type="text/javascript" src="jqueryui/1.11.2-start/jquery-ui.min.js"></script><!-- DataTables --> <link type="text/css" href="datatables/1.10.4/media/jqueryui/dataTables.jqueryui.css" rel="Stylesheet"/> <link type="text/css" href="css/tables.css" rel="stylesheet" /> <script type="text/javascript" src="datatables/1.10.4/media/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="datatables/1.10.4/media/jqueryui/dataTables.jqueryui.min.js"></script><!-- jQplot --> <!--[if IE]> <script language="javascript" type="text/javascript" src="excanvas/3/excanvas.compiled.js"></script> <![endif]--><link rel="stylesheet" type="text/css" href="jqplot/1.0.8/jquery.jqplot.min.css"/> <script type="text/javascript" src="jqplot/1.0.8/jquery.jqplot.min.js"></script> <script type="text/javascript" src="jqplot/1.0.8/plugins/jqplot.pieRenderer.min.js"></script> <script class="code" type="text/javascript">$(document).ready(function () { var plot1 = $.jqplot('coverage_pie_chart', [ [ ['Passing', 0], ['Pending', 1], ['Ignored', 0], ['Failing', 0], ['Errors', 0], ['Compromised Tests', 0], ] ], { gridPadding: {top: 0, bottom: 38, left: 0, right: 0}, seriesColors: ['#30cb23', '#a2f2f2', '#eeeadd', '#f8001f', '#fc6e1f', 'fuchsia'], seriesDefaults: { renderer: $.jqplot.PieRenderer, trendline: {show: false}, rendererOptions: {padding: 8, showDataLabels: true} }, legend: { show: true, placement: 'outside', rendererOptions: { numberRows: 3 }, location: 's', marginTop: '15px' }, series: [ {label: '0% requirements tested successfully'}, {label: '100% requirements untested'}, {label: '0%} requirements failing'}, {label: '0%} requirements with errors'}, {label: '0%} requirements with compromised tests'} ] }); // Results table $('#test-results-table').DataTable({ "order": [ [ 1, "asc" ] ], "pageLength": 100, "lengthMenu": [ [50, 100, 200, -1] , [50, 100, 200, "All"] ] }); // Results table $('#req-results-table').DataTable({ "order": [ [ 1, "asc" ] ], "pageLength": 100, "lengthMenu": [ [50, 100, 200, -1] , [50, 100, 200, "All"] ] }); $('#examples-table').DataTable({ "order": [ [2, "asc"] ], "pageLength": 25 }); $("#tabs").tabs(); $("#test-tabs").tabs(); }) ; </script> <script type="text/javascript"> $(document).ready(function () { $(".read-more-link").click(function () { $(this).nextAll("div.read-more-text").toggle(); var isrc = $(this).find("img").attr('src'); if (isrc == 'images/plus.png') { $(this).find("img").attr("src", function () { return "images/minus.png"; }); } else { $(this).find("img").attr("src", function () { return "images/plus.png"; }); } }); }); </script> </head> <body class="results-page"> <div id="topheader"> <div id="topbanner"> <div id="logo"><a href="index.html"><img src="images/serenity-bdd-logo.png" border="0"/></a></div> <div id="projectname-banner" style="float:right"> <span class="projectname"></span> </div> </div> </div> <div class="middlecontent"> <div id="contenttop"> <div class="middlebg"> <span class="breadcrumbs"> <a href='index.html'>Home</a> > Create Shipment </span> </div> <div class="rightbg"></div> </div> <div class="clr"></div> <!--/* starts second table*/--> <div> <ul class="nav nav-tabs" role="tablist"> <li > <a href="index.html"><i class="fa fa-check-square-o"></i> Overall Test Results</a> </li> <li > <a href="capabilities.html"><i class="fa fa-book"></i> Requirements</a> </li> <li class="active"> <a href="#"><i class="fa fa-comments-o"></i> Capabilities</a> </li> <li > <a href="576946480b52ad056d6f5bddf874399c83582ecf90963cc074a14c70580e7d9f.html"><i class="fa fa-comments-o"></i> Features</a> </li> <li > <a href="2a4631d87648e59c428d4cf0e9247f9d286e4679f436ca2ce872e931eb4dfd58.html"><i class="fa fa-comments-o"></i> Stories</a> </li> </ul> <span class="date-and-time"><a href="build-info.html"><i class="fa fa-info-circle"></i></a> Report generated 27-03-2017 15:26</span> <br style="clear:left"/> </div> <div class="clr"></div> <div id="beforetable"></div> <div id="results-dashboard"> <div class="middlb"> <div class="table"> <div> <h2><i class="fa fa-book"></i> Capability: Create Shipment</h2> <div class="requirementNarrativeTitle"> Create shipment </div> </div> <div id="requirements-summary"> <div id="coverage_pie_chart" style="margin-top:10px; margin-left:10px; width:250px; height:250px;"></div> <div id="coverage_summary"> <div> <h4>Requirements Overview</h4> <table class="summary-table"> <head> <tr> <th>Requirement Type</th> <th>Total</th> <th>Pass&nbsp;<i class="icon-check"></i></th> <th>Fail&nbsp;<i class="icon-thumbs-down"></i></th> <th>Pending&nbsp;<i class="icon-calendar"></i></th> <th>Ignored&nbsp;<i class="icon-ban-circle"></i></th> <th>Untested&nbsp;<i class="icon-question"></i></th> </tr> </head> <body> <tr> <td class="summary-leading-column">Features</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <td class="summary-leading-column">Stories</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <td class="summary-leading-column">Acceptance Criteria (tests)</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td></td> </tr> </body> </table> </div> <div> <h4>Test Result Summary</h4> <table class="summary-table"> <head> <tr> <th>Test Type</th> <th>Total</th> <th>Pass&nbsp;<i class="icon-check"/> </th> <th>Fail&nbsp;<i class="icon-thumbs-down"/></th> <th>Pending&nbsp;<i class="icon-calendar"/></th> <th>Ignored&nbsp;<i class="icon-ban-circle"/></th> </tr> </head> <body> <tr> <td class="summary-leading-column">Automated</td> <td>1</td> <td>0 (0%)</td> <td>0 (0%)</td> <td>1 (100%)</td> <td>0 (0%)</td> </tr> <tr> <td class="summary-leading-column">Manual</td> <td>0</td> <td>0 (0%)</td> <td>0 (0%)</td> <td>0 (0%)</td> <td>0 (0%)</td> </tr> <tr> <td class="summary-leading-column">Total</td> <td>1</td> <td>0 (0%)</td> <td>0 (0%)</td> <td>1 (100%)</td> <td>0 (0%)</td> </tr> <tr> <td class="summary-leading-column">Total Duration</td> <td colspan="5">0 seconds</td> </tr> </body> </table> </div> </div> </div> <div class="clr"></div> <div id="tabs"> <ul> <li><a href="#tabs-1"> Features (1) </a></li> </ul> <div id="tabs-1" class="capabilities-table"> <div id="tabs-1" class="capabilities-table"> <div id="req_list_tests" class="table"> <div class="test-results"> <table id="req-results-table"> <thead> <tr> <th width="30" class="test-results-heading">&nbsp;</th> <th width="65" class="test-results-heading">ID</th> <th width="525" class="test-results-heading">Feature</th> <th width="65" class="test-results-heading">Stories</th> <th class="test-results-heading" width="75px">Auto.<br/>Tests</th> <th class="test-results-heading" width="25px"><i class="fa fa-check-square-o" title="Tests passed (automated)"></i> </th> <th class="test-results-heading" width="25px"><i class="fa fa-square-o" title="Tests skipped or pending (automated)"> </th> <th class="test-results-heading" width="25px"><i class="fa fa-times-circle" title="Tests failed (automated)"></th> <th class="test-results-heading" width="25px"><i class="fa fa-exclamation-triangle" title="Tests failed with an error (automated)"></th> <th class="test-results-heading" width="25px"> <i class="fa fa-chain-broken fa-lg" title="Tests compromised"></i> </th> <th class="test-results-heading" width="75px">Manual<br/>Tests</th> <th class="test-results-heading" width="25px"><i class="fa fa-check-square-o" title="Tests passed (manual)"></i> </th> <th class="test-results-heading" width="25px"><i class="fa fa-square-o" title="Tests skipped or pending (manual)"> </th> <th class="test-results-heading" width="25px"><i class="fa fa-times-circle" title="Tests failed (manual)"></th> <th class="test-results-heading" width="25px"><i class="fa fa-exclamation-triangle" title="Tests failed with an error (manual)"></th> <th width="125px" class="test-results-heading">Coverage</th> </tr> <tbody> <tr class="test-PENDING requirementRow"> <td class="requirementRowCell"> <span class="status_icon"><i class='fa fa-square-o pending-icon ' title='PENDING'></i></span> <span style="display:none">2</span> </td> <td class="cardNumber requirementRowCell"></td> <td class="PENDING-text requirementRowCell"> <a href="javaScript:void(0)" class="read-more-link"> <img src="images/plus.png" height="16"/></a> <span class="requirementName"><a href="5e45dd6835c1ee5e3531723e4a269c865d18efe1efb374b31ffe315b20abb719.html">Create new shipment</a></span> <div class="requirementNarrative read-more-text">Create new shipment</div> </td> <td class="bluetext requirementRowCell">1</td> <td class="greentext highlighted-value requirementRowCell">1</td> <td class="greentext requirementRowCell">0</td> <td class="bluetext requirementRowCell">1</td> <td class="redtext requirementRowCell">0</td> <td class="lightorangetext requirementRowCell">0</td> <td class="violettext requirementRowCell">0</td> <td class="greentext highlighted-value requirementRowCell">0</td> <td class="greentext requirementRowCell">0</td> <td class="bluetext requirementRowCell">0</td> <td class="redtext requirementRowCell">0</td> <td class="lightorangetext requirementRowCell">0</td> <td width="125px" class="lightgreentext requirementRowCell"> <table> <tr> <td width="40px"> <div class="small">0%</div> </td> <td width="125px"> <div class="percentagebar" title="Create new shipment Tests implemented: 1 - Passing tests: 0 (0% of specified requirements) - Failing tests: 0 (0% of specified requirements) - Tests with errors: 0 (0% of specified requirements) - Compromised tests 0 (0% of specified requirements) Tests not implemented or not executed: 1 - Pending tests: 1 (100% of specified requirements) - Ignored or skipped tests: 0 (0% of specified requirements) Requirements specified: 2 Requirements with no tests: 0 Estimated unimplemented tests: 0 Estimated unimplemented or pending requirements: 100% Estimated ignored or skipped requirements: 0%" style="width: 125px;"> <div class="ignoredbar" style="width: 0px;" title="Create new shipment Tests implemented: 1 - Passing tests: 0 (0% of specified requirements) - Failing tests: 0 (0% of specified requirements) - Tests with errors: 0 (0% of specified requirements) - Compromised tests 0 (0% of specified requirements) Tests not implemented or not executed: 1 - Pending tests: 1 (100% of specified requirements) - Ignored or skipped tests: 0 (0% of specified requirements) Requirements specified: 2 Requirements with no tests: 0 Estimated unimplemented tests: 0 Estimated unimplemented or pending requirements: 100% Estimated ignored or skipped requirements: 0%"> <div class="compromisedbar" style="width: 0px;" title="Create new shipment Tests implemented: 1 - Passing tests: 0 (0% of specified requirements) - Failing tests: 0 (0% of specified requirements) - Tests with errors: 0 (0% of specified requirements) - Compromised tests 0 (0% of specified requirements) Tests not implemented or not executed: 1 - Pending tests: 1 (100% of specified requirements) - Ignored or skipped tests: 0 (0% of specified requirements) Requirements specified: 2 Requirements with no tests: 0 Estimated unimplemented tests: 0 Estimated unimplemented or pending requirements: 100% Estimated ignored or skipped requirements: 0%"> <div class="errorbar" style="width: 0px;" title="Create new shipment Tests implemented: 1 - Passing tests: 0 (0% of specified requirements) - Failing tests: 0 (0% of specified requirements) - Tests with errors: 0 (0% of specified requirements) - Compromised tests 0 (0% of specified requirements) Tests not implemented or not executed: 1 - Pending tests: 1 (100% of specified requirements) - Ignored or skipped tests: 0 (0% of specified requirements) Requirements specified: 2 Requirements with no tests: 0 Estimated unimplemented tests: 0 Estimated unimplemented or pending requirements: 100% Estimated ignored or skipped requirements: 0%"> <div class="failingbar" style="width: 0px;" title="Create new shipment Tests implemented: 1 - Passing tests: 0 (0% of specified requirements) - Failing tests: 0 (0% of specified requirements) - Tests with errors: 0 (0% of specified requirements) - Compromised tests 0 (0% of specified requirements) Tests not implemented or not executed: 1 - Pending tests: 1 (100% of specified requirements) - Ignored or skipped tests: 0 (0% of specified requirements) Requirements specified: 2 Requirements with no tests: 0 Estimated unimplemented tests: 0 Estimated unimplemented or pending requirements: 100% Estimated ignored or skipped requirements: 0%"> <div class="passingbar" style="width: 0px;" title="Create new shipment Tests implemented: 1 - Passing tests: 0 (0% of specified requirements) - Failing tests: 0 (0% of specified requirements) - Tests with errors: 0 (0% of specified requirements) - Compromised tests 0 (0% of specified requirements) Tests not implemented or not executed: 1 - Pending tests: 1 (100% of specified requirements) - Ignored or skipped tests: 0 (0% of specified requirements) Requirements specified: 2 Requirements with no tests: 0 Estimated unimplemented tests: 0 Estimated unimplemented or pending requirements: 100% Estimated ignored or skipped requirements: 0%"> </div> </div> </div> </div> </div> </div> </td> </tr> </table> </td> </tr> </tbody> </table> </div> </div> </div> </div> <table> <tr> <td> <div><h3>Acceptance Criteria</h3></div> <div id="test_list_tests" class="table"> <div class="test-results"> <table id="test-results-table"> <thead> <tr> <th width="50" class="test-results-heading">&nbsp;</th> <th width="%" class="test-results-heading">Tests</th> <th width="70" class="test-results-heading">Steps</th> <th width="100" class="test-results-heading">Duration<br>(seconds)</th> </tr> </thead> <tbody> <tr class="test-PENDING"> <td><span class="summary-icon"><i class='fa fa-square-o pending-icon ' title='PENDING'></i></span> <span style="display:none">PENDING</span></td> <td class="PENDING-text"> <div class="ellipsis"> <a href="b7eb41812d1dbecdf79b65286b860240e00fc026c2e2828a2e79af9b98e08252.html" class="ellipsis" title=""> Create a new shipment based on minimal required information </a></div> </td> <td class="lightgreentext">5</td> <td class="lightgreentext">0.15</td> </tr> </tbody> </table> </div> </div> </td> </tr> </table> </div> </div> </div> </div> </div> </div> </div> </div> <div id="bottomfooter"> <span class="version">Serenity BDD version 1.1.36</span> </div> </body> </html>
{ "content_hash": "64ede9f776be58ba82d12a7351291e6e", "timestamp": "", "source": "github", "line_count": 577, "max_line_length": 142, "avg_line_length": 40.487001733102254, "alnum_prop": 0.4532768289028723, "repo_name": "EduCaMa/EduCaMa.github.io", "id": "bff29582b9301995090860158579bd36a0105f70", "size": "23361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/serenity/6cbcc5c3eee118ab4dc1607c8ab62b4ab527f0f3cc6be100779377cc4fb25689.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "322339" }, { "name": "HTML", "bytes": "9919955" }, { "name": "JavaScript", "bytes": "1668559" } ], "symlink_target": "" }
{% load i18n %} {% load cache %} {% load pubmantags %} {% cache settings.CACHE_PERIOD featured_stories request.LANGUAGE_CODE %} {% if featured_stories %} <div id="featured-stories" class="featured-content"> {% for featured_story in featured_stories %} <div class="featured-story featured-content-block"> <h1>{{featured_story.story.title}}</h1> {% if featured_story.show_primary_media_object %} <div class="featured-image"> {% display_media featured_story.story.primary_media_object 150 120 %} </div> {% endif %} <p class="featured-lead-in-text">{{featured_story.lead_in_text}}</p> {% if featured_story.show_contents %} {% if featured_story.story.contents_as_ordered_list %} <ol> {% else %} <ul> {% endif %} {% for item in featured_story.story.article_list %} <li> <a href="{% url pubman.views.article_detail item.slug %}?story={{featured_story.story.slug}}"> {{item.title}} </a> </li> {% endfor %} {% if featured_story.contents_as_ordered_list %} </ol> {% else %} </ul> {% endif %} {% endif %} {% if featured_story.read_more_message %} <a href="{{featured_story.story.get_absolute_url}}"> {{featured_story.read_more_message}}</a> {% endif %} </div> {% endfor %} </div> {% endif %} {% endcache %}
{ "content_hash": "1d46b3e2b031dd34d253dfe5804e0afe", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 110, "avg_line_length": 32.09803921568628, "alnum_prop": 0.48930971288943187, "repo_name": "nathangeffen/django-pubman", "id": "900961810dce3715eab4f49a1e2e7519aefaab67", "size": "1637", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pubman/templates/pubman/featured_story_snippet.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "104810" }, { "name": "PHP", "bytes": "286684" }, { "name": "Python", "bytes": "209989" } ], "symlink_target": "" }
> Note: project not maintained anymore. This is a symfony2 project to show you how work the Symfony2 admingenerator https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle # How to install Copy and configure your db connections in paramaters.ini ``` cp app/config/parameters.yml.sample app/config/parameters.yml ``` Run in your schell the nexts commands lines ``` wget http://getcomposer.org/composer.phar php composer.phar install ./rebuild.sh ``` Note: The default login/password is admin/admin # Optionnal dependencies ## Assetic You could install sass and compass if you want to change css : ```shell sudo gem install compass # https://github.com/chriseppstein/compass sudo gem install sass ``` And probably to configure assetic : ```yaml filters: cssrewrite: ~ sass: bin: /var/lib/gems/1.8/gems/sass-3.1.7/bin/sass compass: /var/lib/gems/1.8/gems/compass-0.11.5/bin/compass ``` ## Without assetic Configure your config.yml to use the assetic less template ``` yaml admingenerator_generator: base_admin_template: AdmingeneratorGeneratorBundle::base_admin_assetic_less.html.twig admingenerator_user: login_template: AdmingeneratorGeneratorBundle::base_login_assetic_less.html.twig ``` # With DoctrineODM You've to install pecl/mongo ``` pecl install mongo ``` And install mongodb server & clients package for your distribution
{ "content_hash": "9615d28555ecb8bb5327e2a2f4e74b62", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 89, "avg_line_length": 21.651515151515152, "alnum_prop": 0.7410776766969909, "repo_name": "symfony2admingenerator/AdmingeneratorIpsum", "id": "826bb76384df474acd9ec8888722eee5252ee48e", "size": "1452", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13" }, { "name": "PHP", "bytes": "80705" }, { "name": "Shell", "bytes": "790" } ], "symlink_target": "" }
import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; /** Class containing SqlAgent operations. */ export class SqlAgentImpl { /** * Initialize a new instance of the class SqlAgent class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * Gets current instance sql agent configuration. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param options The options parameters. */ get(resourceGroupName, managedInstanceName, options) { return this.client.sendOperationRequest({ resourceGroupName, managedInstanceName, options }, getOperationSpec); } /** * Puts new sql agent configuration to instance. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param parameters A recoverable managed database resource. * @param options The options parameters. */ createOrUpdate(resourceGroupName, managedInstanceName, parameters, options) { return this.client.sendOperationRequest({ resourceGroupName, managedInstanceName, parameters, options }, createOrUpdateOperationSpec); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const getOperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/sqlAgent/current", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SqlAgentConfiguration }, default: {} }, queryParameters: [Parameters.apiVersion2], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managedInstanceName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/sqlAgent/current", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SqlAgentConfiguration }, default: {} }, requestBody: Parameters.parameters67, queryParameters: [Parameters.apiVersion2], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managedInstanceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; //# sourceMappingURL=sqlAgent.js.map
{ "content_hash": "5346da9f6750a8ca363e6ff24b0f41d4", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 159, "avg_line_length": 40.02564102564103, "alnum_prop": 0.6941063420884048, "repo_name": "ealbertos/dotfiles", "id": "585b4c52e32a6e273ba6e7e41eb24e366cc669e7", "size": "3351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vscode.symlink/extensions/ms-mssql.mssql-1.16.0/node_modules/@azure/arm-sql/dist-esm/src/operations/sqlAgent.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "99972" }, { "name": "EJS", "bytes": "2437" }, { "name": "HTML", "bytes": "47081" }, { "name": "JavaScript", "bytes": "3546995" }, { "name": "Less", "bytes": "183" }, { "name": "Python", "bytes": "134723" }, { "name": "Ruby", "bytes": "127567" }, { "name": "Shell", "bytes": "34790" }, { "name": "TSQL", "bytes": "258" }, { "name": "TypeScript", "bytes": "37162" }, { "name": "Vim Script", "bytes": "60888" }, { "name": "Vim Snippet", "bytes": "11523" } ], "symlink_target": "" }
import copy import os import re import shutil import tempfile import unittest from functools import partial from pathlib import Path import pytest import requests import yaml from huggingface_hub import ( DatasetCard, DatasetCardData, EvalResult, ModelCard, ModelCardData, metadata_eval_result, metadata_load, metadata_save, metadata_update, ) from huggingface_hub.constants import REPOCARD_NAME from huggingface_hub.file_download import hf_hub_download from huggingface_hub.hf_api import HfApi from huggingface_hub.repocard import RepoCard from huggingface_hub.repocard_data import CardData from huggingface_hub.repository import Repository from huggingface_hub.utils import is_jinja_available, logging from .testing_constants import ( ENDPOINT_STAGING, ENDPOINT_STAGING_BASIC_AUTH, TOKEN, USER, ) from .testing_utils import ( expect_deprecation, repo_name, retry_endpoint, set_write_permission_and_retry, ) SAMPLE_CARDS_DIR = Path(__file__).parent / "fixtures/cards" ROUND_TRIP_MODELCARD_CASE = """ --- language: no datasets: CLUECorpusSmall widget: - text: 北京是[MASK]国的首都。 --- # Title """ DUMMY_MODELCARD = """ Hi --- license: mit datasets: - foo - bar --- Hello """ DUMMY_MODELCARD_TARGET = """ Hi --- meaning_of_life: 42 --- Hello """ DUMMY_MODELCARD_TARGET_NO_YAML = """--- meaning_of_life: 42 --- Hello """ DUMMY_NEW_MODELCARD_TARGET = """--- meaning_of_life: 42 --- """ DUMMY_MODELCARD_TARGET_NO_TAGS = """ Hello """ DUMMY_MODELCARD_EVAL_RESULT = """--- model-index: - name: RoBERTa fine-tuned on ReactionGIF results: - task: type: text-classification name: Text Classification dataset: name: ReactionGIF type: julien-c/reactiongif config: default split: test metrics: - type: accuracy value: 0.2662102282047272 name: Accuracy config: default verified: false --- """ DUMMY_MODELCARD_NO_TEXT_CONTENT = """--- license: cc-by-sa-4.0 --- """ DUMMY_MODELCARD_EVAL_RESULT_BOTH_VERIFIED_AND_UNVERIFIED = """--- model-index: - name: RoBERTa fine-tuned on ReactionGIF results: - task: type: text-classification name: Text Classification dataset: name: ReactionGIF type: julien-c/reactiongif config: default split: test metrics: - type: accuracy value: 0.2662102282047272 name: Accuracy config: default verified: false - task: type: text-classification name: Text Classification dataset: name: ReactionGIF type: julien-c/reactiongif config: default split: test metrics: - type: accuracy value: 0.6666666666666666 name: Accuracy config: default verified: true --- This is a test model card. """ logger = logging.get_logger(__name__) REPOCARD_DIR = os.path.join( os.path.dirname(os.path.abspath(__file__)), "fixtures/repocard" ) repo_name = partial(repo_name, prefix="dummy-hf-hub") def require_jinja(test_case): """ Decorator marking a test that requires Jinja2. These tests are skipped when Jinja2 is not installed. """ if not is_jinja_available(): return unittest.skip("test requires Jinja2.")(test_case) else: return test_case class RepocardMetadataTest(unittest.TestCase): def setUp(self): os.makedirs(REPOCARD_DIR, exist_ok=True) def tearDown(self) -> None: if os.path.exists(REPOCARD_DIR): shutil.rmtree(REPOCARD_DIR, onerror=set_write_permission_and_retry) logger.info(f"Does {REPOCARD_DIR} exist: {os.path.exists(REPOCARD_DIR)}") def test_metadata_load(self): filepath = Path(REPOCARD_DIR) / REPOCARD_NAME filepath.write_text(DUMMY_MODELCARD) data = metadata_load(filepath) self.assertDictEqual(data, {"license": "mit", "datasets": ["foo", "bar"]}) def test_metadata_save(self): filename = "dummy_target.md" filepath = Path(REPOCARD_DIR) / filename filepath.write_text(DUMMY_MODELCARD) metadata_save(filepath, {"meaning_of_life": 42}) content = filepath.read_text() self.assertEqual(content, DUMMY_MODELCARD_TARGET) def test_metadata_save_from_file_no_yaml(self): filename = "dummy_target_2.md" filepath = Path(REPOCARD_DIR) / filename filepath.write_text("Hello\n") metadata_save(filepath, {"meaning_of_life": 42}) content = filepath.read_text() self.assertEqual(content, DUMMY_MODELCARD_TARGET_NO_YAML) def test_metadata_save_new_file(self): filename = "new_dummy_target.md" filepath = Path(REPOCARD_DIR) / filename metadata_save(filepath, {"meaning_of_life": 42}) content = filepath.read_text() self.assertEqual(content, DUMMY_NEW_MODELCARD_TARGET) def test_no_metadata_returns_none(self): filename = "dummy_target_3.md" filepath = Path(REPOCARD_DIR) / filename filepath.write_text(DUMMY_MODELCARD_TARGET_NO_TAGS) data = metadata_load(filepath) self.assertEqual(data, None) def test_metadata_eval_result(self): data = metadata_eval_result( model_pretty_name="RoBERTa fine-tuned on ReactionGIF", task_pretty_name="Text Classification", task_id="text-classification", metrics_pretty_name="Accuracy", metrics_id="accuracy", metrics_value=0.2662102282047272, metrics_config="default", metrics_verified=False, dataset_pretty_name="ReactionGIF", dataset_id="julien-c/reactiongif", dataset_config="default", dataset_split="test", ) filename = "eval_results.md" filepath = Path(REPOCARD_DIR) / filename metadata_save(filepath, data) content = filepath.read_text().splitlines() self.assertEqual(content, DUMMY_MODELCARD_EVAL_RESULT.splitlines()) class RepocardMetadataUpdateTest(unittest.TestCase): _api = HfApi(endpoint=ENDPOINT_STAGING, token=TOKEN) @classmethod @expect_deprecation("set_access_token") def setUpClass(cls): """ Share this valid token in all tests below. """ cls._token = TOKEN cls._api.set_access_token(TOKEN) @retry_endpoint def setUp(self) -> None: self.repo_path = Path(tempfile.mkdtemp()) self.REPO_NAME = repo_name() self.repo_id = f"{USER}/{self.REPO_NAME}" self._api.create_repo(self.repo_id) self._api.upload_file( path_or_fileobj=DUMMY_MODELCARD_EVAL_RESULT.encode(), repo_id=self.repo_id, path_in_repo="README.md", commit_message="Add README to main branch", ) self.repo = Repository( self.repo_path / self.REPO_NAME, clone_from=self.repo_id, use_auth_token=self._token, git_user="ci", git_email="ci@dummy.com", ) self.existing_metadata = yaml.safe_load( DUMMY_MODELCARD_EVAL_RESULT.strip().strip("-") ) def tearDown(self) -> None: self._api.delete_repo(repo_id=self.repo_id) shutil.rmtree(self.repo_path) def test_update_dataset_name(self): new_datasets_data = {"datasets": ["test/test_dataset"]} metadata_update(self.repo_id, new_datasets_data, token=self._token) self.repo.git_pull() updated_metadata = metadata_load(self.repo_path / self.REPO_NAME / "README.md") expected_metadata = copy.deepcopy(self.existing_metadata) expected_metadata.update(new_datasets_data) self.assertDictEqual(updated_metadata, expected_metadata) def test_update_existing_result_with_overwrite(self): new_metadata = copy.deepcopy(self.existing_metadata) new_metadata["model-index"][0]["results"][0]["metrics"][0][ "value" ] = 0.2862102282047272 metadata_update(self.repo_id, new_metadata, token=self._token, overwrite=True) self.repo.git_pull() updated_metadata = metadata_load(self.repo_path / self.REPO_NAME / "README.md") self.assertDictEqual(updated_metadata, new_metadata) def test_metadata_update_upstream(self): new_metadata = copy.deepcopy(self.existing_metadata) new_metadata["model-index"][0]["results"][0]["metrics"][0]["value"] = 0.1 path = hf_hub_download( self.repo_id, filename=REPOCARD_NAME, use_auth_token=self._token, ) metadata_update(self.repo_id, new_metadata, token=self._token, overwrite=True) self.assertNotEqual(metadata_load(path), new_metadata) self.assertEqual(metadata_load(path), self.existing_metadata) def test_update_existing_result_without_overwrite(self): new_metadata = copy.deepcopy(self.existing_metadata) new_metadata["model-index"][0]["results"][0]["metrics"][0][ "value" ] = 0.2862102282047272 with pytest.raises( ValueError, match=( "You passed a new value for the existing metric 'name: Accuracy, type:" " accuracy'. Set `overwrite=True` to overwrite existing metrics." ), ): metadata_update( self.repo_id, new_metadata, token=self._token, overwrite=False ) def test_update_existing_field_without_overwrite(self): new_datasets_data = {"datasets": "['test/test_dataset']"} metadata_update(self.repo_id, new_datasets_data, token=self._token) with pytest.raises( ValueError, match=( "You passed a new value for the existing meta data field 'datasets'." " Set `overwrite=True` to overwrite existing metadata." ), ): new_datasets_data = {"datasets": "['test/test_dataset_2']"} metadata_update( self.repo_id, new_datasets_data, token=self._token, overwrite=False, ) def test_update_new_result_existing_dataset(self): new_result = metadata_eval_result( model_pretty_name="RoBERTa fine-tuned on ReactionGIF", task_pretty_name="Text Classification", task_id="text-classification", metrics_pretty_name="Recall", metrics_id="recall", metrics_value=0.7762102282047272, metrics_config="default", metrics_verified=False, dataset_pretty_name="ReactionGIF", dataset_id="julien-c/reactiongif", dataset_config="default", dataset_split="test", ) metadata_update(self.repo_id, new_result, token=self._token, overwrite=False) expected_metadata = copy.deepcopy(self.existing_metadata) expected_metadata["model-index"][0]["results"][0]["metrics"].append( new_result["model-index"][0]["results"][0]["metrics"][0] ) self.repo.git_pull() updated_metadata = metadata_load(self.repo_path / self.REPO_NAME / "README.md") self.assertDictEqual(updated_metadata, expected_metadata) def test_update_new_result_new_dataset(self): new_result = metadata_eval_result( model_pretty_name="RoBERTa fine-tuned on ReactionGIF", task_pretty_name="Text Classification", task_id="text-classification", metrics_pretty_name="Accuracy", metrics_id="accuracy", metrics_value=0.2662102282047272, metrics_config="default", metrics_verified=False, dataset_pretty_name="ReactionJPEG", dataset_id="julien-c/reactionjpeg", dataset_config="default", dataset_split="test", ) metadata_update(self.repo_id, new_result, token=self._token, overwrite=False) expected_metadata = copy.deepcopy(self.existing_metadata) expected_metadata["model-index"][0]["results"].append( new_result["model-index"][0]["results"][0] ) self.repo.git_pull() updated_metadata = metadata_load(self.repo_path / self.REPO_NAME / "README.md") self.assertDictEqual(updated_metadata, expected_metadata) def test_update_metadata_on_empty_text_content(self) -> None: """Test `update_metadata` on a model card that has metadata but no text content Regression test for https://github.com/huggingface/huggingface_hub/issues/1010 """ # Create modelcard with metadata but empty text content with self.repo.commit("Add README to main branch"): with open("README.md", "w") as f: f.write(DUMMY_MODELCARD_NO_TEXT_CONTENT) metadata_update(self.repo_id, {"tag": "test"}, token=self._token) # Check update went fine self.repo.git_pull() updated_metadata = metadata_load(self.repo_path / self.REPO_NAME / "README.md") expected_metadata = {"license": "cc-by-sa-4.0", "tag": "test"} self.assertDictEqual(updated_metadata, expected_metadata) def test_update_with_existing_name(self): new_metadata = copy.deepcopy(self.existing_metadata) new_metadata["model-index"][0].pop("name") new_metadata["model-index"][0]["results"][0]["metrics"][0][ "value" ] = 0.2862102282047272 metadata_update(self.repo_id, new_metadata, token=self._token, overwrite=True) card_data = ModelCard.load(self.repo_id, token=self._token) self.assertEqual( card_data.data.model_name, self.existing_metadata["model-index"][0]["name"] ) def test_update_without_existing_name(self): # delete existing metadata self._api.upload_file( path_or_fileobj="# Test".encode(), repo_id=self.repo_id, path_in_repo="README.md", ) new_metadata = copy.deepcopy(self.existing_metadata) new_metadata["model-index"][0].pop("name") metadata_update(self.repo_id, new_metadata, token=self._token, overwrite=True) card_data = ModelCard.load(self.repo_id, token=self._token) self.assertEqual(card_data.data.model_name, self.repo_id) def test_update_with_both_verified_and_unverified_metric(self): """Regression test for #1185. See https://github.com/huggingface/huggingface_hub/issues/1185. """ self._api.upload_file( path_or_fileobj=DUMMY_MODELCARD_EVAL_RESULT_BOTH_VERIFIED_AND_UNVERIFIED.encode(), repo_id=self.repo_id, path_in_repo="README.md", ) card = ModelCard.load(self.repo_id) metadata = card.data.to_dict() metadata_update(self.repo_id, metadata=metadata, overwrite=True, token=TOKEN) card_data = ModelCard.load(self.repo_id, token=self._token) self.assertEqual(len(card_data.data.eval_results), 2) first_result = card_data.data.eval_results[0] second_result = card_data.data.eval_results[1] # One is verified, the other not self.assertFalse(first_result.verified) self.assertTrue(second_result.verified) # Result values are different self.assertEqual(first_result.metric_value, 0.2662102282047272) self.assertEqual(second_result.metric_value, 0.6666666666666666) class TestMetadataUpdateOnMissingCard(unittest.TestCase): def setUp(self) -> None: """ Share this valid token in all tests below. """ self._token = TOKEN self._api = HfApi(endpoint=ENDPOINT_STAGING, token=TOKEN) self._repo_id = f"{USER}/{repo_name()}" def test_metadata_update_missing_readme_on_model(self) -> None: self._api.create_repo(self._repo_id) metadata_update(self._repo_id, {"tag": "this_is_a_test"}, token=self._token) model_card = ModelCard.load(self._repo_id, token=self._token) # Created a card with default template + metadata self.assertIn("# Model Card for Model ID", str(model_card)) self.assertEqual(model_card.data.to_dict(), {"tag": "this_is_a_test"}) self._api.delete_repo(self._repo_id) def test_metadata_update_missing_readme_on_dataset(self) -> None: self._api.create_repo(self._repo_id, repo_type="dataset") metadata_update( self._repo_id, {"tag": "this is a dataset test"}, token=self._token, repo_type="dataset", ) dataset_card = DatasetCard.load(self._repo_id, token=self._token) # Created a card with default template + metadata self.assertIn("# Dataset Card for Dataset Name", str(dataset_card)) self.assertEqual(dataset_card.data.to_dict(), {"tag": "this is a dataset test"}) self._api.delete_repo(self._repo_id, repo_type="dataset") def test_metadata_update_missing_readme_on_space(self) -> None: self._api.create_repo(self._repo_id, repo_type="space", space_sdk="static") self._api.delete_file("README.md", self._repo_id, repo_type="space") with self.assertRaises(ValueError): # Cannot create a default readme on a space repo (should be automatically # created on the Hub). metadata_update( self._repo_id, {"tag": "this is a space test"}, token=self._token, repo_type="space", ) self._api.delete_repo(self._repo_id, repo_type="space") class TestCaseWithCapLog(unittest.TestCase): _api = HfApi(endpoint=ENDPOINT_STAGING, token=TOKEN) @pytest.fixture(autouse=True) def inject_fixtures(self, caplog): """Assign pytest caplog as attribute so we can use captured log messages in tests below.""" self.caplog = caplog class RepoCardTest(TestCaseWithCapLog): def test_load_repocard_from_file(self): sample_path = SAMPLE_CARDS_DIR / "sample_simple.md" card = RepoCard.load(sample_path) self.assertEqual( card.data.to_dict(), { "language": ["en"], "license": "mit", "library_name": "pytorch-lightning", "tags": ["pytorch", "image-classification"], "datasets": ["beans"], "metrics": ["acc"], }, ) self.assertTrue( card.text.strip().startswith("# my-cool-model"), "Card text not loaded properly", ) def test_change_repocard_data(self): sample_path = SAMPLE_CARDS_DIR / "sample_simple.md" card = RepoCard.load(sample_path) card.data.language = ["fr"] with tempfile.TemporaryDirectory() as tempdir: updated_card_path = Path(tempdir) / "updated.md" card.save(updated_card_path) updated_card = RepoCard.load(updated_card_path) self.assertEqual( updated_card.data.language, ["fr"], "Card data not updated properly" ) @require_jinja def test_repo_card_from_default_template(self): card = RepoCard.from_template( card_data=CardData( language="en", license="mit", library_name="pytorch", tags=["image-classification", "resnet"], datasets="imagenet", metrics=["acc", "f1"], ), model_id=None, ) self.assertIsInstance(card, RepoCard) self.assertTrue( card.text.strip().startswith("# Model Card for Model ID"), "Default model name not set correctly", ) @require_jinja def test_repo_card_from_default_template_with_model_id(self): card = RepoCard.from_template( card_data=CardData( language="en", license="mit", library_name="pytorch", tags=["image-classification", "resnet"], datasets="imagenet", metrics=["acc", "f1"], ), model_id="my-cool-model", ) self.assertTrue( card.text.strip().startswith("# Model Card for my-cool-model"), "model_id not properly set in card template", ) @require_jinja def test_repo_card_from_custom_template(self): template_path = SAMPLE_CARDS_DIR / "sample_template.md" card = RepoCard.from_template( card_data=CardData( language="en", license="mit", library_name="pytorch", tags="text-classification", datasets="glue", metrics="acc", ), template_path=template_path, some_data="asdf", ) self.assertTrue( card.text.endswith("asdf"), "Custom template didn't set jinja variable correctly", ) def test_repo_card_data_must_be_dict(self): sample_path = SAMPLE_CARDS_DIR / "sample_invalid_card_data.md" with pytest.raises( ValueError, match="repo card metadata block should be a dict" ): RepoCard(sample_path.read_text()) def test_repo_card_without_metadata(self): sample_path = SAMPLE_CARDS_DIR / "sample_no_metadata.md" with self.caplog.at_level(logging.WARNING): card = RepoCard(sample_path.read_text()) self.assertIn( "Repo card metadata block was not found. Setting CardData to empty.", self.caplog.text, ) self.assertEqual(card.data, CardData()) def test_validate_repocard(self): sample_path = SAMPLE_CARDS_DIR / "sample_simple.md" card = RepoCard.load(sample_path) card.validate() card.data.license = "asdf" with pytest.raises(ValueError, match='- Error: "license" must be one of'): card.validate() def test_push_to_hub(self): repo_id = f"{USER}/{repo_name('push-card')}" self._api.create_repo(repo_id) card_data = CardData( language="en", license="mit", library_name="pytorch", tags=["text-classification"], datasets="glue", metrics="acc", ) # Mock what RepoCard.from_template does so we can test w/o Jinja2 content = f"---\n{card_data.to_yaml()}\n---\n\n# MyModel\n\nHello, world!" card = RepoCard(content) url = f"{ENDPOINT_STAGING_BASIC_AUTH}/{repo_id}/resolve/main/README.md" # Check this file doesn't exist (sanity check) with pytest.raises(requests.exceptions.HTTPError): r = requests.get(url) r.raise_for_status() # Push the card up to README.md in the repo card.push_to_hub(repo_id, token=TOKEN) # No error should occur now, as README.md should exist r = requests.get(url) r.raise_for_status() self._api.delete_repo(repo_id=repo_id) def test_push_and_create_pr(self): repo_id = f"{USER}/{repo_name('pr-card')}" self._api.create_repo(repo_id) card_data = CardData( language="en", license="mit", library_name="pytorch", tags=["text-classification"], datasets="glue", metrics="acc", ) # Mock what RepoCard.from_template does so we can test w/o Jinja2 content = f"---\n{card_data.to_yaml()}\n---\n\n# MyModel\n\nHello, world!" card = RepoCard(content) url = f"{ENDPOINT_STAGING_BASIC_AUTH}/api/models/{repo_id}/discussions" r = requests.get(url) data = r.json() self.assertEqual(data["count"], 0) card.push_to_hub(repo_id, token=TOKEN, create_pr=True) r = requests.get(url) data = r.json() self.assertEqual(data["count"], 1) self._api.delete_repo(repo_id=repo_id) def test_preserve_windows_linebreaks(self): card_path = SAMPLE_CARDS_DIR / "sample_windows_line_breaks.md" card = RepoCard.load(card_path) self.assertIn("\r\n", str(card)) def test_updating_text_updates_content(self): sample_path = SAMPLE_CARDS_DIR / "sample_simple.md" card = RepoCard.load(sample_path) card.text = "Hello, world!" self.assertEqual( card.content, f"---\n{card.data.to_yaml()}\n---\nHello, world!" ) class ModelCardTest(TestCaseWithCapLog): def test_model_card_with_invalid_model_index(self): """ Test that when loading a card that has invalid model-index, no eval_results are added + it logs a warning """ sample_path = SAMPLE_CARDS_DIR / "sample_invalid_model_index.md" with self.caplog.at_level(logging.WARNING): card = ModelCard.load(sample_path) self.assertIn( "Invalid model-index. Not loading eval results into CardData.", self.caplog.text, ) self.assertIsNone(card.data.eval_results) def test_load_model_card_from_file(self): sample_path = SAMPLE_CARDS_DIR / "sample_simple.md" card = ModelCard.load(sample_path) self.assertIsInstance(card, ModelCard) self.assertEqual( card.data.to_dict(), { "language": ["en"], "license": "mit", "library_name": "pytorch-lightning", "tags": ["pytorch", "image-classification"], "datasets": ["beans"], "metrics": ["acc"], }, ) self.assertTrue( card.text.strip().startswith("# my-cool-model"), "Card text not loaded properly", ) @require_jinja def test_model_card_from_custom_template(self): template_path = SAMPLE_CARDS_DIR / "sample_template.md" card = ModelCard.from_template( card_data=ModelCardData( language="en", license="mit", library_name="pytorch", tags="text-classification", datasets="glue", metrics="acc", ), template_path=template_path, some_data="asdf", ) self.assertIsInstance(card, ModelCard) self.assertTrue( card.text.endswith("asdf"), "Custom template didn't set jinja variable correctly", ) @require_jinja def test_model_card_from_template_eval_results(self): template_path = SAMPLE_CARDS_DIR / "sample_template.md" card = ModelCard.from_template( card_data=ModelCardData( eval_results=[ EvalResult( task_type="text-classification", task_name="Text Classification", dataset_type="julien-c/reactiongif", dataset_name="ReactionGIF", dataset_config="default", dataset_split="test", metric_type="accuracy", metric_value=0.2662102282047272, metric_name="Accuracy", metric_config="default", verified=False, ), ], model_name="RoBERTa fine-tuned on ReactionGIF", ), template_path=template_path, some_data="asdf", ) self.assertIsInstance(card, ModelCard) self.assertTrue(card.text.endswith("asdf")) self.assertTrue(card.data.to_dict().get("eval_results") is None) self.assertEqual( str(card)[: len(DUMMY_MODELCARD_EVAL_RESULT)], DUMMY_MODELCARD_EVAL_RESULT ) class DatasetCardTest(TestCaseWithCapLog): def test_load_datasetcard_from_file(self): sample_path = SAMPLE_CARDS_DIR / "sample_datasetcard_simple.md" card = DatasetCard.load(sample_path) self.assertEqual( card.data.to_dict(), { "annotations_creators": ["crowdsourced", "expert-generated"], "language_creators": ["found"], "language": ["en"], "license": ["bsd-3-clause"], "multilinguality": ["monolingual"], "size_categories": ["n<1K"], "task_categories": ["image-segmentation"], "task_ids": ["semantic-segmentation"], "pretty_name": "Sample Segmentation", }, ) self.assertIsInstance(card, DatasetCard) self.assertIsInstance(card.data, DatasetCardData) self.assertTrue(card.text.strip().startswith("# Dataset Card for")) @require_jinja def test_dataset_card_from_default_template(self): card_data = DatasetCardData( language="en", license="mit", ) # Here we check default title when pretty_name not provided. card = DatasetCard.from_template(card_data) self.assertTrue(card.text.strip().startswith("# Dataset Card for Dataset Name")) card_data = DatasetCardData( language="en", license="mit", pretty_name="My Cool Dataset", ) # Here we pass the card data as kwargs as well so template picks up pretty_name. card = DatasetCard.from_template(card_data, **card_data.to_dict()) self.assertTrue( card.text.strip().startswith("# Dataset Card for My Cool Dataset") ) self.assertIsInstance(card, DatasetCard) @require_jinja def test_dataset_card_from_default_template_with_template_variables(self): card_data = DatasetCardData( language="en", license="mit", pretty_name="My Cool Dataset", ) # Here we pass the card data as kwargs as well so template picks up pretty_name. card = DatasetCard.from_template( card_data, homepage_url="https://huggingface.co", repo_url="https://github.com/huggingface/huggingface_hub", paper_url="https://arxiv.org/pdf/1910.03771.pdf", point_of_contact="https://huggingface.co/nateraw", dataset_summary=( "This is a test dataset card to check if the template variables " "in the dataset card template are working." ), ) self.assertTrue( card.text.strip().startswith("# Dataset Card for My Cool Dataset") ) self.assertIsInstance(card, DatasetCard) matches = re.findall(r"Homepage:\*\* https:\/\/huggingface\.co", str(card)) self.assertEqual(matches[0], "Homepage:** https://huggingface.co") @require_jinja def test_dataset_card_from_custom_template(self): card = DatasetCard.from_template( card_data=DatasetCardData( language="en", license="mit", pretty_name="My Cool Dataset", ), template_path=SAMPLE_CARDS_DIR / "sample_datasetcard_template.md", pretty_name="My Cool Dataset", some_data="asdf", ) self.assertIsInstance(card, DatasetCard) # Title this time is just # {{ pretty_name }} self.assertTrue(card.text.strip().startswith("# My Cool Dataset")) # some_data is at the bottom of the template, so should end with whatever we passed to it self.assertTrue(card.text.strip().endswith("asdf"))
{ "content_hash": "9031b42e907a075e4772932245aab29c", "timestamp": "", "source": "github", "line_count": 923, "max_line_length": 113, "avg_line_length": 34.360780065005414, "alnum_prop": 0.5912659624783225, "repo_name": "huggingface/huggingface_hub", "id": "f035226811d061b57db526c3117679fa7766505b", "size": "32337", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tests/test_repocard.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "338" }, { "name": "Python", "bytes": "1086946" } ], "symlink_target": "" }
package com.me.diankun.drawdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; /** * Created by diankun on 2016/3/15. */ public class MoveViewActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_move); } }
{ "content_hash": "6c60462c25f4d49b48d3304c6059d847", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 57, "avg_line_length": 25, "alnum_prop": 0.7075, "repo_name": "qdiankun/androidbase", "id": "534f146cfc0a6098d968941803e849a4ac64fa10", "size": "400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "andoridbase/drawdemo/src/main/java/com/me/diankun/drawdemo/MoveViewActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "470241" } ], "symlink_target": "" }
package javax.swing.undo; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; /** * <P>StateEdit is a general edit for objects that change state. * Objects being edited must conform to the StateEditable interface.</P> * * <P>This edit class works by asking an object to store it's state in * Hashtables before and after editing occurs. Upon undo or redo the * object is told to restore it's state from these Hashtables.</P> * * A state edit is used as follows: * <PRE> * // Create the edit during the "before" state of the object * StateEdit newEdit = new StateEdit(myObject); * // Modify the object * myObject.someStateModifyingMethod(); * // "end" the edit when you are done modifying the object * newEdit.end(); * </PRE> * * <P><EM>Note that when a StateEdit ends, it removes redundant state from * the Hashtables - A state Hashtable is not guaranteed to contain all * keys/values placed into it when the state is stored!</EM></P> * * @see StateEditable * * @author Ray Ryan */ public class StateEdit extends AbstractUndoableEdit { protected static final String RCSID = "$Id: StateEdit.java,v 1.6 1997/10/01 20:05:51 sandipc Exp $"; // // Attributes // /** * The object being edited */ protected StateEditable object; /** * The state information prior to the edit */ protected Hashtable<Object,Object> preState; /** * The state information after the edit */ protected Hashtable<Object,Object> postState; /** * The undo/redo presentation name */ protected String undoRedoName; // // Constructors // /** * Create and return a new StateEdit. * * @param anObject The object to watch for changing state * * @see StateEdit */ public StateEdit(StateEditable anObject) { super(); init (anObject,null); } /** * Create and return a new StateEdit with a presentation name. * * @param anObject The object to watch for changing state * @param name The presentation name to be used for this edit * * @see StateEdit */ public StateEdit(StateEditable anObject, String name) { super(); init (anObject,name); } protected void init (StateEditable anObject, String name) { this.object = anObject; this.preState = new Hashtable<Object, Object>(11); this.object.storeState(this.preState); this.postState = null; this.undoRedoName = name; } // // Operation // /** * Gets the post-edit state of the StateEditable object and * ends the edit. */ public void end() { this.postState = new Hashtable<Object, Object>(11); this.object.storeState(this.postState); this.removeRedundantState(); } /** * Tells the edited object to apply the state prior to the edit */ public void undo() { super.undo(); this.object.restoreState(preState); } /** * Tells the edited object to apply the state after the edit */ public void redo() { super.redo(); this.object.restoreState(postState); } /** * Gets the presentation name for this edit */ public String getPresentationName() { return this.undoRedoName; } // // Internal support // /** * Remove redundant key/values in state hashtables. */ protected void removeRedundantState() { Vector<Object> uselessKeys = new Vector<Object>(); Enumeration myKeys = preState.keys(); // Locate redundant state while (myKeys.hasMoreElements()) { Object myKey = myKeys.nextElement(); if (postState.containsKey(myKey) && postState.get(myKey).equals(preState.get(myKey))) { uselessKeys.addElement(myKey); } } // Remove redundant state for (int i = uselessKeys.size()-1; i >= 0; i--) { Object myKey = uselessKeys.elementAt(i); preState.remove(myKey); postState.remove(myKey); } } } // End of class StateEdit
{ "content_hash": "ae1a04a58ade6f1f455c66ff6f091e04", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 104, "avg_line_length": 25.064705882352943, "alnum_prop": 0.6076038488617695, "repo_name": "rokn/Count_Words_2015", "id": "8d01282168f0911450c9a15e05cd504f4e6cf4e4", "size": "5473", "binary": false, "copies": "57", "ref": "refs/heads/master", "path": "testing/openjdk2/jdk/src/share/classes/javax/swing/undo/StateEdit.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
<section data-ng-controller="BankController as controller" data-ng-init="controller.fnInitLoadChips()"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h1>Load Chips into Bank</h1> </div> </div> </div> <div class="row"> <div class="col-md-offset-4 col-md-4"> <fieldset> <div class="form-group"> <label class="control-label" for="username">Username</label> <div class="controls"> <input type="text" id="username" name="username" class="form-control" data-ng-model="controller.bank.username" placeholder="Username" disabled> </div> </div> <div class="form-group"> <label class="control-label" for="account_balance">Account balance</label> <div class="controls"> <input type="text" id="account_balance" name="account_balance" class="form-control" data-ng-model="controller.bank.account.balance" jm-rs-number-format placeholder="account_balance" disabled> </div> </div> </fieldset> </div> </div> <div class="row"> <div class="col-md-offset-4 col-md-4"> <fieldset> <div class="form-group"> <label class="control-label" for="chipsAmount">Chips Amount</label> <div class="controls"> <input type="text" id="chipsAmount" name="chipsAmount" class="form-control" data-ng-model="controller.chipsAmount" jm-rs-number-format placeholder="chipsAmount"> </div> </div> <div class="form-group"> <input type="submit" value="Load Chips" data-ng-click="controller.fnLoadChips()" class="btn btn-default"> </div> <div data-ng-show="controller.error" class="text-danger"> <strong data-ng-bind="controller.error"></strong> </div> </fieldset> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading">Load chips transactions</div> <table class="table table-striped"> <thead> <tr> <th>Type</th> <th>Amount</th> <th>State</th> <th>Created Date</th> <th>Updated Date</th> </tr> </thead> <tbody class="searchable"> <tr dir-paginate="obj in controller.listTransaction | filter:controller.filter | itemsPerPage: controller.pageSize" current-page="controller.currentPage"> <td> <span data-ng-bind="obj.type"></span> </td> <td> {{obj.amount | jmRsNumberFormatFilter}} </td> <td> <span data-ng-bind="obj.state"></span> </td> <td> <span data-ng-bind="obj.createdDate | date:'medium'"></span> </td> <td> <span data-ng-bind="obj.updatedDate | date:'medium'"></span> </td> </tr> </tbody> </table> </div> </div> </div> </section>
{ "content_hash": "2e46d625c5d5c58f582b8ae54f1ef8c5", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 197, "avg_line_length": 34.829268292682926, "alnum_prop": 0.5861344537815126, "repo_name": "josephrichard7/runestake", "id": "1279ccdd402430415dfdc1afa658ffa1f41019f6", "size": "2856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/modules/bank/views/loadchips.bank.client.view.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1352" }, { "name": "HTML", "bytes": "116976" }, { "name": "JavaScript", "bytes": "306623" } ], "symlink_target": "" }
package org.elasticsearch.action.delete; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.replication.ShardReplicationOperationRequest; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Required; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.index.VersionType; import java.io.IOException; import static org.elasticsearch.action.ValidateActions.addValidationError; /** * A request to delete a document from an index based on its type and id. Best created using * {@link org.elasticsearch.client.Requests#deleteRequest(String)}. * <p/> * <p>The operation requires the {@link #index()}, {@link #type(String)} and {@link #id(String)} to * be set. * * @see DeleteResponse * @see org.elasticsearch.client.Client#delete(DeleteRequest) * @see org.elasticsearch.client.Requests#deleteRequest(String) */ public class DeleteRequest extends ShardReplicationOperationRequest<DeleteRequest> { private String type; private String id; @Nullable private String routing; private boolean refresh; private long version; private VersionType versionType = VersionType.INTERNAL; /** * Constructs a new delete request against the specified index. The {@link #type(String)} and {@link #id(String)} * must be set. */ public DeleteRequest(String index) { this.index = index; } /** * Constructs a new delete request against the specified index with the type and id. * * @param index The index to get the document from * @param type The type of the document * @param id The id of the document */ public DeleteRequest(String index, String type, String id) { this.index = index; this.type = type; this.id = id; } public DeleteRequest(DeleteRequest request) { super(request); this.type = request.type(); this.id = request.id(); this.routing = request.routing(); this.refresh = request.refresh(); this.version = request.version(); this.versionType = request.versionType(); } public DeleteRequest() { } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (type == null) { validationException = addValidationError("type is missing", validationException); } if (id == null) { validationException = addValidationError("id is missing", validationException); } return validationException; } /** * The type of the document to delete. */ public String type() { return type; } /** * Sets the type of the document to delete. */ @Required public DeleteRequest type(String type) { this.type = type; return this; } /** * The id of the document to delete. */ public String id() { return id; } /** * Sets the id of the document to delete. */ @Required public DeleteRequest id(String id) { this.id = id; return this; } /** * Sets the parent id of this document. Will simply set the routing to this value, as it is only * used for routing with delete requests. */ public DeleteRequest parent(String parent) { if (routing == null) { routing = parent; } return this; } /** * Controls the shard routing of the request. Using this value to hash the shard * and not the id. */ public DeleteRequest routing(String routing) { if (routing != null && routing.length() == 0) { this.routing = null; } else { this.routing = routing; } return this; } /** * Controls the shard routing of the delete request. Using this value to hash the shard * and not the id. */ public String routing() { return this.routing; } /** * Should a refresh be executed post this index operation causing the operation to * be searchable. Note, heavy indexing should not set this to <tt>true</tt>. Defaults * to <tt>false</tt>. */ public DeleteRequest refresh(boolean refresh) { this.refresh = refresh; return this; } public boolean refresh() { return this.refresh; } /** * Sets the version, which will cause the delete operation to only be performed if a matching * version exists and no changes happened on the doc since then. */ public DeleteRequest version(long version) { this.version = version; return this; } public long version() { return this.version; } public DeleteRequest versionType(VersionType versionType) { this.versionType = versionType; return this; } public VersionType versionType() { return this.versionType; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); type = in.readSharedString(); id = in.readString(); routing = in.readOptionalString(); refresh = in.readBoolean(); version = in.readLong(); versionType = VersionType.fromValue(in.readByte()); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeSharedString(type); out.writeString(id); out.writeOptionalString(routing()); out.writeBoolean(refresh); out.writeLong(version); out.writeByte(versionType.getValue()); } @Override public String toString() { return "delete {[" + index + "][" + type + "][" + id + "]}"; } }
{ "content_hash": "17a00a15ef3dee654d6487e94088be02", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 117, "avg_line_length": 28.214285714285715, "alnum_prop": 0.6303797468354431, "repo_name": "lmenezes/elasticsearch", "id": "6cc6ec20a6fd9298147e4a09362530c5ce62e311", "size": "6733", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/elasticsearch/action/delete/DeleteRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18031976" }, { "name": "Shell", "bytes": "25951" } ], "symlink_target": "" }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; /** * This class performs calculation. The connections in hypercube are represents * as binary tree. * * @author Michał Szczygieł <michal.szczygiel@wp.pl> * */ public class Algorithm extends Hypercube { /** * Left branch of the binary tree. */ private final static Integer LEFT = 0; /** * Right branch of the binary tree. */ private final static Integer RIGHT = 1; /** * Chops a list into non-view sublists of length L. * * @param list * The list to be chopped. * @param L * The size of chop. * @return Chopped list. */ static <T> List<List<T>> chopped(List<T> list, final int L) { List<List<T>> parts = new ArrayList<List<T>>(); final int N = list.size(); for (int i = 0; i < N; i += L) { parts.add(new ArrayList<T>(list.subList(i, Math.min(N, i + L)))); } return parts; } /** * This method perform safe operations on the lists. * * @param list * The list to check if is empty. * @return safe list, which avoid {@link NullPointerException} */ @SuppressWarnings("rawtypes") public static List safe(List list) { return list == null ? Collections.EMPTY_LIST : list; } /** * This method perform calculation for count sum. * * @param data * The data for count sum. * @return The result of sum operation for data in {@link List}. */ public static Double sum(List<Double> data) { Double result = 0.0; for (Object value : safe(data)) { result += Double.parseDouble(value.toString()); } return result; } /** * The fields contains data to perform operations in nodes. */ private List<Double> data; /** * The constructor for {@link Algorithm}. Invoke constructor in * {@link Hypercube} class. * * @param data * The data with numbers to calculate sum in hypercube structure. * @param size * The size of hypercube, what mean the amount of nodes. */ public Algorithm(List<Double> data, Integer size) { super(size); setData(data); prepareDistrbuteData(data, 0, 0); } /** * * This method gets local sum for current node. This method overrides an * existing method. * * @see Hypercube#get(java.util.List) */ @Override public Double get(Node node) { return node.getLocalSum(); } /** * This method get data which contains Double numbers. * * @return the data */ public List<Double> getData() { return data; } /** * This method prepares and distribute data in nodes. The algorithm of * propagation data is based on binary tree concept. Distributed operation * uses put method to allocate data in nodes. The node 0 (root-node) is * communicate with outside world. This algorithm based on level in binary * tree and proper identification. Each level(sqrt operation from size of * hypercube round up) can be divided into two branch where first have id * ex. current and seceond have id current + 2^(level -1). * * @param data * The data to propagate in nodes. * @param current * The value to recognize proper node. * @param level * The value represents level in binary tree. */ private void prepareDistrbuteData(List<Double> data, Integer current, Integer level) { if ((current + Math.pow(2, level - 1)) < getSize()) { List<Double> distributeData = data; put(getNodeList().get(current), distributeData); if (level <= Math.ceil(Math.sqrt(getSize()))) { Integer half = (int) (Math.ceil(getData().size() / Math.pow(2, level))); List<List<Double>> parts = Algorithm.chopped(distributeData, half); put(getNodeList().get(current), parts.get(LEFT)); prepareDistrbuteData(parts.get(LEFT), current, level + 1); if (parts.size() > 1) { put(getNodeList().get( (int) (current + Math.pow(2, level - 1))), parts.get(RIGHT)); prepareDistrbuteData(parts.get(RIGHT), (int) (current + Math.pow(2, level - 1)), level + 1); } } } } /** * This method puts data into current node. This method overrides an * existing method. * * @see Hypercube#put(java.util.List, java.lang.Integer) */ @Override public void put(Node node, List<Double> input) { node.setData(input); } /** * This method redistribute data from nodes. The operations is inverse to * distribute data ex. in prepareDistrbuteData() method. The algorithm of * propagation data is based on binary tree concept. Redistributed operation * uses get method to get local sum from nodes. The node 0 (root-node) is * communicate with outside world. This algorithm based on level in binary * tree and proper identification. Each level(sqrt operation from size of * hypercube, round up) can be divided into two branch where first have id * ex. current and seceond have id current - 2^(level -1). * * @param sum * The value from neighbor contains sum of local sums. * @param current * The value to recognize proper node. * @param level * The value represents level in binary tree. * @return The computed sum from hypercube structure. */ private Double redistributeData(Double sum, Integer current, Integer level) { sum = get(getNodeList().get(current)); if ((current - Math.pow(2, level - 1)) >= 0) { redistributeData(sum, current, level + 1); sum += redistributeData(sum, (int) (current - Math.pow(2, level - 1)), level); } return sum; } /** * This method sets data. * * @param data * the data to set */ public void setData(List<Double> data) { this.data = data; } /** * This method return sum from hypercube operations. The value of sum is a * result of redistributed data. The operations are executed in parallel by * each node. * * @return The sum value, for given data. * @throws InterruptedException * @throws ExecutionException */ public Double sum() throws InterruptedException, ExecutionException { run(); return redistributeData(0.0, getSize() - 1, 0); } }
{ "content_hash": "919c8251a57cdac9eaf9251a62a85102", "timestamp": "", "source": "github", "line_count": 221, "max_line_length": 81, "avg_line_length": 31.773755656108598, "alnum_prop": 0.5753346624893193, "repo_name": "M4GiK/ztp-projects", "id": "2138328e70bcf36f790bb7529a58811f29b4b062", "size": "7123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Hypercube/Algorithm.java", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Externs for https://github.com/omichelsen/angular-clipboard * * @externs */ const clipboard = {}; /** * @typedef {{ * supported: boolean, * }} */ clipboard.Clipboard; /** * @param {string} text * @return */ clipboard.Clipboard.prototype.copyText = function(text) {};
{ "content_hash": "b9aa178b100fec914cca08d48b8f9a7f", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 76, "avg_line_length": 26.852941176470587, "alnum_prop": 0.7086527929901424, "repo_name": "danielromlein/dashboard", "id": "c6be488e378a33ee80d24213e0388288c93333ff", "size": "913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/externs/clipboard.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "56783" }, { "name": "Go", "bytes": "795388" }, { "name": "HTML", "bytes": "424688" }, { "name": "JavaScript", "bytes": "1421777" }, { "name": "Shell", "bytes": "7062" }, { "name": "XSLT", "bytes": "1119" } ], "symlink_target": "" }
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "config.h" #include "V8Element.h" #include "CSSMutableStyleDeclaration.h" #include "EventListener.h" #include "ExceptionCode.h" #include "RuntimeEnabledFeatures.h" #include "V8AbstractEventListener.h" #include "V8Attr.h" #include "V8Binding.h" #include "V8BindingMacros.h" #include "V8BindingState.h" #include "V8CSSStyleDeclaration.h" #include "V8ClientRect.h" #include "V8ClientRectList.h" #include "V8DOMStringMap.h" #include "V8DOMWrapper.h" #include "V8IsolatedContext.h" #include "V8Node.h" #include "V8NodeList.h" #include "V8Proxy.h" #include <wtf/GetPtr.h> #include <wtf/RefCounted.h> #include <wtf/RefPtr.h> namespace WebCore { WrapperTypeInfo V8Element::info = { V8Element::GetTemplate, V8Element::derefObject, 0, &V8Node::info }; namespace ElementInternal { template <typename T> void V8_USE(T) { } static v8::Handle<v8::Value> tagNameAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.tagName._get"); Element* imp = V8Element::toNative(info.Holder()); return v8StringOrNull(imp->tagName()); } static v8::Handle<v8::Value> styleAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.style._get"); Element* imp = V8Element::toNative(info.Holder()); return toV8(imp->style()); } static v8::Handle<v8::Value> offsetLeftAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.offsetLeft._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->offsetLeft()); } static v8::Handle<v8::Value> offsetTopAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.offsetTop._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->offsetTop()); } static v8::Handle<v8::Value> offsetWidthAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.offsetWidth._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->offsetWidth()); } static v8::Handle<v8::Value> offsetHeightAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.offsetHeight._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->offsetHeight()); } static v8::Handle<v8::Value> offsetParentAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.offsetParent._get"); Element* imp = V8Element::toNative(info.Holder()); return toV8(imp->offsetParent()); } static v8::Handle<v8::Value> clientLeftAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.clientLeft._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->clientLeft()); } static v8::Handle<v8::Value> clientTopAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.clientTop._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->clientTop()); } static v8::Handle<v8::Value> clientWidthAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.clientWidth._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->clientWidth()); } static v8::Handle<v8::Value> clientHeightAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.clientHeight._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->clientHeight()); } static v8::Handle<v8::Value> scrollLeftAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.scrollLeft._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->scrollLeft()); } static void scrollLeftAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.scrollLeft._set"); Element* imp = V8Element::toNative(info.Holder()); int v = toInt32(value); imp->setScrollLeft(v); return; } static v8::Handle<v8::Value> scrollTopAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.scrollTop._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->scrollTop()); } static void scrollTopAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.scrollTop._set"); Element* imp = V8Element::toNative(info.Holder()); int v = toInt32(value); imp->setScrollTop(v); return; } static v8::Handle<v8::Value> scrollWidthAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.scrollWidth._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->scrollWidth()); } static v8::Handle<v8::Value> scrollHeightAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.scrollHeight._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::New(imp->scrollHeight()); } static v8::Handle<v8::Value> datasetAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.dataset._get"); Element* imp = V8Element::toNative(info.Holder()); return toV8(imp->dataset()); } static v8::Handle<v8::Value> firstElementChildAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.firstElementChild._get"); Element* imp = V8Element::toNative(info.Holder()); return toV8(imp->firstElementChild()); } static v8::Handle<v8::Value> lastElementChildAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.lastElementChild._get"); Element* imp = V8Element::toNative(info.Holder()); return toV8(imp->lastElementChild()); } static v8::Handle<v8::Value> previousElementSiblingAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.previousElementSibling._get"); Element* imp = V8Element::toNative(info.Holder()); return toV8(imp->previousElementSibling()); } static v8::Handle<v8::Value> nextElementSiblingAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.nextElementSibling._get"); Element* imp = V8Element::toNative(info.Holder()); return toV8(imp->nextElementSibling()); } static v8::Handle<v8::Value> childElementCountAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.childElementCount._get"); Element* imp = V8Element::toNative(info.Holder()); return v8::Integer::NewFromUnsigned(imp->childElementCount()); } static v8::Handle<v8::Value> onabortAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onabort._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onabort() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onabort())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onabortAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onabort._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnabort(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onblurAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onblur._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onblur() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onblur())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onblurAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onblur._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnblur(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onchangeAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onchange._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onchange() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onchange())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onchangeAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onchange._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnchange(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onclickAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onclick._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onclick() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onclick())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onclickAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onclick._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnclick(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> oncontextmenuAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oncontextmenu._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->oncontextmenu() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->oncontextmenu())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void oncontextmenuAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oncontextmenu._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOncontextmenu(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> ondblclickAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondblclick._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ondblclick() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ondblclick())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void ondblclickAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondblclick._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOndblclick(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> ondragAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondrag._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ondrag() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ondrag())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void ondragAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondrag._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOndrag(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> ondragendAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragend._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ondragend() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ondragend())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void ondragendAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragend._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOndragend(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> ondragenterAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragenter._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ondragenter() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ondragenter())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void ondragenterAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragenter._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOndragenter(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> ondragleaveAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragleave._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ondragleave() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ondragleave())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void ondragleaveAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragleave._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOndragleave(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> ondragoverAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragover._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ondragover() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ondragover())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void ondragoverAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragover._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOndragover(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> ondragstartAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragstart._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ondragstart() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ondragstart())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void ondragstartAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondragstart._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOndragstart(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> ondropAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondrop._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ondrop() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ondrop())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void ondropAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ondrop._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOndrop(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onerrorAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onerror._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onerror() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onerror())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onerrorAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onerror._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnerror(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onfocusAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onfocus._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onfocus() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onfocus())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onfocusAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onfocus._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnfocus(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> oninputAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oninput._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->oninput() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->oninput())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void oninputAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oninput._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOninput(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> oninvalidAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oninvalid._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->oninvalid() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->oninvalid())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void oninvalidAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oninvalid._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOninvalid(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onkeydownAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onkeydown._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onkeydown() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onkeydown())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onkeydownAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onkeydown._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnkeydown(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onkeypressAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onkeypress._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onkeypress() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onkeypress())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onkeypressAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onkeypress._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnkeypress(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onkeyupAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onkeyup._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onkeyup() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onkeyup())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onkeyupAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onkeyup._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnkeyup(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onloadAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onload._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onload() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onload())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onloadAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onload._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnload(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onmousedownAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmousedown._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onmousedown() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onmousedown())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onmousedownAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmousedown._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnmousedown(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onmousemoveAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmousemove._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onmousemove() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onmousemove())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onmousemoveAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmousemove._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnmousemove(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onmouseoutAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmouseout._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onmouseout() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onmouseout())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onmouseoutAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmouseout._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnmouseout(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onmouseoverAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmouseover._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onmouseover() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onmouseover())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onmouseoverAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmouseover._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnmouseover(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onmouseupAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmouseup._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onmouseup() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onmouseup())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onmouseupAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmouseup._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnmouseup(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onmousewheelAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmousewheel._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onmousewheel() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onmousewheel())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onmousewheelAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onmousewheel._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnmousewheel(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onscrollAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onscroll._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onscroll() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onscroll())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onscrollAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onscroll._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnscroll(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onselectAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onselect._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onselect() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onselect())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onselectAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onselect._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnselect(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onsubmitAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onsubmit._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onsubmit() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onsubmit())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onsubmitAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onsubmit._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnsubmit(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onbeforecutAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onbeforecut._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onbeforecut() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onbeforecut())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onbeforecutAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onbeforecut._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnbeforecut(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> oncutAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oncut._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->oncut() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->oncut())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void oncutAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oncut._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOncut(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onbeforecopyAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onbeforecopy._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onbeforecopy() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onbeforecopy())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onbeforecopyAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onbeforecopy._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnbeforecopy(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> oncopyAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oncopy._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->oncopy() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->oncopy())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void oncopyAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.oncopy._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOncopy(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onbeforepasteAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onbeforepaste._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onbeforepaste() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onbeforepaste())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onbeforepasteAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onbeforepaste._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnbeforepaste(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onpasteAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onpaste._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onpaste() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onpaste())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onpasteAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onpaste._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnpaste(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onresetAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onreset._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onreset() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onreset())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onresetAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onreset._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnreset(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onsearchAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onsearch._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onsearch() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onsearch())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onsearchAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onsearch._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnsearch(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } static v8::Handle<v8::Value> onselectstartAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onselectstart._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onselectstart() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onselectstart())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onselectstartAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onselectstart._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnselectstart(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } #if ENABLE(TOUCH_EVENTS) static v8::Handle<v8::Value> ontouchstartAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ontouchstart._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ontouchstart() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ontouchstart())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) static void ontouchstartAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ontouchstart._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOntouchstart(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) static v8::Handle<v8::Value> ontouchmoveAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ontouchmove._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ontouchmove() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ontouchmove())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) static void ontouchmoveAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ontouchmove._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOntouchmove(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) static v8::Handle<v8::Value> ontouchendAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ontouchend._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ontouchend() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ontouchend())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) static void ontouchendAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ontouchend._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOntouchend(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) static v8::Handle<v8::Value> ontouchcancelAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ontouchcancel._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->ontouchcancel() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->ontouchcancel())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) static void ontouchcancelAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.ontouchcancel._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOntouchcancel(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(FULLSCREEN_API) static v8::Handle<v8::Value> onwebkitfullscreenchangeAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onwebkitfullscreenchange._get"); Element* imp = V8Element::toNative(info.Holder()); return imp->onwebkitfullscreenchange() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onwebkitfullscreenchange())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } #endif // ENABLE(FULLSCREEN_API) #if ENABLE(FULLSCREEN_API) static void onwebkitfullscreenchangeAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.Element.onwebkitfullscreenchange._set"); Element* imp = V8Element::toNative(info.Holder()); imp->setOnwebkitfullscreenchange(V8DOMWrapper::getEventListener(value, true, ListenerFindOrCreate)); return; } #endif // ENABLE(FULLSCREEN_API) static v8::Handle<v8::Value> getAttributeCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getAttribute"); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); return v8StringOrNull(imp->getAttribute(name)); } static v8::Handle<v8::Value> setAttributeCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.setAttribute"); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, value, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); imp->setAttribute(name, value, ec); if (UNLIKELY(ec)) goto fail; return v8::Handle<v8::Value>(); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> removeAttributeCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.removeAttribute"); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); imp->removeAttribute(name, ec); if (UNLIKELY(ec)) goto fail; return v8::Handle<v8::Value>(); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> getAttributeNodeCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getAttributeNode"); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); return toV8(imp->getAttributeNode(name)); } static v8::Handle<v8::Value> setAttributeNodeCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.setAttributeNode"); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { Attr* newAttr = V8Attr::HasInstance(args[0]) ? V8Attr::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0; if (UNLIKELY(!newAttr)) { ec = TYPE_MISMATCH_ERR; goto fail; } RefPtr<Attr> result = imp->setAttributeNode(newAttr, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> removeAttributeNodeCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.removeAttributeNode"); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { Attr* oldAttr = V8Attr::HasInstance(args[0]) ? V8Attr::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0; if (UNLIKELY(!oldAttr)) { ec = TYPE_MISMATCH_ERR; goto fail; } RefPtr<Attr> result = imp->removeAttributeNode(oldAttr, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> getElementsByTagNameCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getElementsByTagName"); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); return toV8(imp->getElementsByTagName(name)); } static v8::Handle<v8::Value> getAttributeNSCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getAttributeNS"); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithNullCheck>, namespaceURI, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, localName, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); return v8String(imp->getAttributeNS(namespaceURI, localName)); } static v8::Handle<v8::Value> setAttributeNSCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.setAttributeNS"); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithNullCheck>, namespaceURI, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, qualifiedName, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, value, MAYBE_MISSING_PARAMETER(args, 2, MissingIsUndefined)); imp->setAttributeNS(namespaceURI, qualifiedName, value, ec); if (UNLIKELY(ec)) goto fail; return v8::Handle<v8::Value>(); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> removeAttributeNSCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.removeAttributeNS"); if (args.Length() < 2) return throwError("Not enough arguments", V8Proxy::TypeError); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithNullCheck>, namespaceURI, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, localName, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); imp->removeAttributeNS(namespaceURI, localName, ec); if (UNLIKELY(ec)) goto fail; return v8::Handle<v8::Value>(); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> getElementsByTagNameNSCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getElementsByTagNameNS"); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithNullCheck>, namespaceURI, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, localName, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); return toV8(imp->getElementsByTagNameNS(namespaceURI, localName)); } static v8::Handle<v8::Value> getAttributeNodeNSCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getAttributeNodeNS"); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithNullCheck>, namespaceURI, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, localName, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); return toV8(imp->getAttributeNodeNS(namespaceURI, localName)); } static v8::Handle<v8::Value> setAttributeNodeNSCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.setAttributeNodeNS"); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { Attr* newAttr = V8Attr::HasInstance(args[0]) ? V8Attr::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0; if (UNLIKELY(!newAttr)) { ec = TYPE_MISMATCH_ERR; goto fail; } RefPtr<Attr> result = imp->setAttributeNodeNS(newAttr, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> hasAttributeCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.hasAttribute"); if (args.Length() < 1) return throwError("Not enough arguments", V8Proxy::TypeError); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); return v8Boolean(imp->hasAttribute(name)); } static v8::Handle<v8::Value> hasAttributeNSCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.hasAttributeNS"); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithNullCheck>, namespaceURI, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, localName, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); return v8Boolean(imp->hasAttributeNS(namespaceURI, localName)); } static v8::Handle<v8::Value> focusCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.focus"); Element* imp = V8Element::toNative(args.Holder()); imp->focus(); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> blurCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.blur"); Element* imp = V8Element::toNative(args.Holder()); imp->blur(); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> scrollIntoViewCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.scrollIntoView"); Element* imp = V8Element::toNative(args.Holder()); if (args.Length() <= 0) { imp->scrollIntoView(); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(bool, alignWithTop, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)->BooleanValue()); imp->scrollIntoView(alignWithTop); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> scrollIntoViewIfNeededCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.scrollIntoViewIfNeeded"); Element* imp = V8Element::toNative(args.Holder()); if (args.Length() <= 0) { imp->scrollIntoViewIfNeeded(); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(bool, centerIfNeeded, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)->BooleanValue()); imp->scrollIntoViewIfNeeded(centerIfNeeded); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> scrollByLinesCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.scrollByLines"); Element* imp = V8Element::toNative(args.Holder()); EXCEPTION_BLOCK(int, lines, toInt32(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined))); imp->scrollByLines(lines); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> scrollByPagesCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.scrollByPages"); Element* imp = V8Element::toNative(args.Holder()); EXCEPTION_BLOCK(int, pages, toInt32(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined))); imp->scrollByPages(pages); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> getElementsByClassNameCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getElementsByClassName"); Element* imp = V8Element::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); return toV8(imp->getElementsByClassName(name)); } static v8::Handle<v8::Value> querySelectorCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.querySelector"); if (args.Length() < 1) return throwError("Not enough arguments", V8Proxy::TypeError); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, selectors, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); RefPtr<Element> result = imp->querySelector(selectors, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> querySelectorAllCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.querySelectorAll"); if (args.Length() < 1) return throwError("Not enough arguments", V8Proxy::TypeError); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, selectors, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); RefPtr<NodeList> result = imp->querySelectorAll(selectors, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> webkitMatchesSelectorCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.webkitMatchesSelector"); Element* imp = V8Element::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, selectors, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); bool result = imp->webkitMatchesSelector(selectors, ec); if (UNLIKELY(ec)) goto fail; return v8Boolean(result); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> getClientRectsCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getClientRects"); Element* imp = V8Element::toNative(args.Holder()); return toV8(imp->getClientRects()); } static v8::Handle<v8::Value> getBoundingClientRectCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.getBoundingClientRect"); Element* imp = V8Element::toNative(args.Holder()); return toV8(imp->getBoundingClientRect()); } static v8::Handle<v8::Value> webkitRequestFullScreenCallback(const v8::Arguments& args) { INC_STATS("DOM.Element.webkitRequestFullScreen"); Element* imp = V8Element::toNative(args.Holder()); EXCEPTION_BLOCK(int, flags, toUInt32(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined))); imp->webkitRequestFullScreen(flags); return v8::Handle<v8::Value>(); } } // namespace ElementInternal static const BatchedAttribute ElementAttrs[] = { // Attribute 'tagName' (Type: 'readonly attribute' ExtAttr: 'ConvertNullStringTo') {"tagName", ElementInternal::tagNameAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'style' (Type: 'readonly attribute' ExtAttr: '') {"style", ElementInternal::styleAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'offsetLeft' (Type: 'readonly attribute' ExtAttr: '') {"offsetLeft", ElementInternal::offsetLeftAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'offsetTop' (Type: 'readonly attribute' ExtAttr: '') {"offsetTop", ElementInternal::offsetTopAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'offsetWidth' (Type: 'readonly attribute' ExtAttr: '') {"offsetWidth", ElementInternal::offsetWidthAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'offsetHeight' (Type: 'readonly attribute' ExtAttr: '') {"offsetHeight", ElementInternal::offsetHeightAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'offsetParent' (Type: 'readonly attribute' ExtAttr: '') {"offsetParent", ElementInternal::offsetParentAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'clientLeft' (Type: 'readonly attribute' ExtAttr: '') {"clientLeft", ElementInternal::clientLeftAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'clientTop' (Type: 'readonly attribute' ExtAttr: '') {"clientTop", ElementInternal::clientTopAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'clientWidth' (Type: 'readonly attribute' ExtAttr: '') {"clientWidth", ElementInternal::clientWidthAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'clientHeight' (Type: 'readonly attribute' ExtAttr: '') {"clientHeight", ElementInternal::clientHeightAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'scrollLeft' (Type: 'attribute' ExtAttr: '') {"scrollLeft", ElementInternal::scrollLeftAttrGetter, ElementInternal::scrollLeftAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'scrollTop' (Type: 'attribute' ExtAttr: '') {"scrollTop", ElementInternal::scrollTopAttrGetter, ElementInternal::scrollTopAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'scrollWidth' (Type: 'readonly attribute' ExtAttr: '') {"scrollWidth", ElementInternal::scrollWidthAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'scrollHeight' (Type: 'readonly attribute' ExtAttr: '') {"scrollHeight", ElementInternal::scrollHeightAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'dataset' (Type: 'readonly attribute' ExtAttr: '') {"dataset", ElementInternal::datasetAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'firstElementChild' (Type: 'readonly attribute' ExtAttr: '') {"firstElementChild", ElementInternal::firstElementChildAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'lastElementChild' (Type: 'readonly attribute' ExtAttr: '') {"lastElementChild", ElementInternal::lastElementChildAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'previousElementSibling' (Type: 'readonly attribute' ExtAttr: '') {"previousElementSibling", ElementInternal::previousElementSiblingAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'nextElementSibling' (Type: 'readonly attribute' ExtAttr: '') {"nextElementSibling", ElementInternal::nextElementSiblingAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'childElementCount' (Type: 'readonly attribute' ExtAttr: '') {"childElementCount", ElementInternal::childElementCountAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'onabort' (Type: 'attribute' ExtAttr: 'DontEnum') {"onabort", ElementInternal::onabortAttrGetter, ElementInternal::onabortAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onblur' (Type: 'attribute' ExtAttr: 'DontEnum') {"onblur", ElementInternal::onblurAttrGetter, ElementInternal::onblurAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onchange' (Type: 'attribute' ExtAttr: 'DontEnum') {"onchange", ElementInternal::onchangeAttrGetter, ElementInternal::onchangeAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onclick' (Type: 'attribute' ExtAttr: 'DontEnum') {"onclick", ElementInternal::onclickAttrGetter, ElementInternal::onclickAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'oncontextmenu' (Type: 'attribute' ExtAttr: 'DontEnum') {"oncontextmenu", ElementInternal::oncontextmenuAttrGetter, ElementInternal::oncontextmenuAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'ondblclick' (Type: 'attribute' ExtAttr: 'DontEnum') {"ondblclick", ElementInternal::ondblclickAttrGetter, ElementInternal::ondblclickAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'ondrag' (Type: 'attribute' ExtAttr: 'DontEnum') {"ondrag", ElementInternal::ondragAttrGetter, ElementInternal::ondragAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'ondragend' (Type: 'attribute' ExtAttr: 'DontEnum') {"ondragend", ElementInternal::ondragendAttrGetter, ElementInternal::ondragendAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'ondragenter' (Type: 'attribute' ExtAttr: 'DontEnum') {"ondragenter", ElementInternal::ondragenterAttrGetter, ElementInternal::ondragenterAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'ondragleave' (Type: 'attribute' ExtAttr: 'DontEnum') {"ondragleave", ElementInternal::ondragleaveAttrGetter, ElementInternal::ondragleaveAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'ondragover' (Type: 'attribute' ExtAttr: 'DontEnum') {"ondragover", ElementInternal::ondragoverAttrGetter, ElementInternal::ondragoverAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'ondragstart' (Type: 'attribute' ExtAttr: 'DontEnum') {"ondragstart", ElementInternal::ondragstartAttrGetter, ElementInternal::ondragstartAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'ondrop' (Type: 'attribute' ExtAttr: 'DontEnum') {"ondrop", ElementInternal::ondropAttrGetter, ElementInternal::ondropAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onerror' (Type: 'attribute' ExtAttr: 'DontEnum') {"onerror", ElementInternal::onerrorAttrGetter, ElementInternal::onerrorAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onfocus' (Type: 'attribute' ExtAttr: 'DontEnum') {"onfocus", ElementInternal::onfocusAttrGetter, ElementInternal::onfocusAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'oninput' (Type: 'attribute' ExtAttr: 'DontEnum') {"oninput", ElementInternal::oninputAttrGetter, ElementInternal::oninputAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'oninvalid' (Type: 'attribute' ExtAttr: 'DontEnum') {"oninvalid", ElementInternal::oninvalidAttrGetter, ElementInternal::oninvalidAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onkeydown' (Type: 'attribute' ExtAttr: 'DontEnum') {"onkeydown", ElementInternal::onkeydownAttrGetter, ElementInternal::onkeydownAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onkeypress' (Type: 'attribute' ExtAttr: 'DontEnum') {"onkeypress", ElementInternal::onkeypressAttrGetter, ElementInternal::onkeypressAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onkeyup' (Type: 'attribute' ExtAttr: 'DontEnum') {"onkeyup", ElementInternal::onkeyupAttrGetter, ElementInternal::onkeyupAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onload' (Type: 'attribute' ExtAttr: 'DontEnum') {"onload", ElementInternal::onloadAttrGetter, ElementInternal::onloadAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onmousedown' (Type: 'attribute' ExtAttr: 'DontEnum') {"onmousedown", ElementInternal::onmousedownAttrGetter, ElementInternal::onmousedownAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onmousemove' (Type: 'attribute' ExtAttr: 'DontEnum') {"onmousemove", ElementInternal::onmousemoveAttrGetter, ElementInternal::onmousemoveAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onmouseout' (Type: 'attribute' ExtAttr: 'DontEnum') {"onmouseout", ElementInternal::onmouseoutAttrGetter, ElementInternal::onmouseoutAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onmouseover' (Type: 'attribute' ExtAttr: 'DontEnum') {"onmouseover", ElementInternal::onmouseoverAttrGetter, ElementInternal::onmouseoverAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onmouseup' (Type: 'attribute' ExtAttr: 'DontEnum') {"onmouseup", ElementInternal::onmouseupAttrGetter, ElementInternal::onmouseupAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onmousewheel' (Type: 'attribute' ExtAttr: 'DontEnum') {"onmousewheel", ElementInternal::onmousewheelAttrGetter, ElementInternal::onmousewheelAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onscroll' (Type: 'attribute' ExtAttr: 'DontEnum') {"onscroll", ElementInternal::onscrollAttrGetter, ElementInternal::onscrollAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onselect' (Type: 'attribute' ExtAttr: 'DontEnum') {"onselect", ElementInternal::onselectAttrGetter, ElementInternal::onselectAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onsubmit' (Type: 'attribute' ExtAttr: 'DontEnum') {"onsubmit", ElementInternal::onsubmitAttrGetter, ElementInternal::onsubmitAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onbeforecut' (Type: 'attribute' ExtAttr: 'DontEnum') {"onbeforecut", ElementInternal::onbeforecutAttrGetter, ElementInternal::onbeforecutAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'oncut' (Type: 'attribute' ExtAttr: 'DontEnum') {"oncut", ElementInternal::oncutAttrGetter, ElementInternal::oncutAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onbeforecopy' (Type: 'attribute' ExtAttr: 'DontEnum') {"onbeforecopy", ElementInternal::onbeforecopyAttrGetter, ElementInternal::onbeforecopyAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'oncopy' (Type: 'attribute' ExtAttr: 'DontEnum') {"oncopy", ElementInternal::oncopyAttrGetter, ElementInternal::oncopyAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onbeforepaste' (Type: 'attribute' ExtAttr: 'DontEnum') {"onbeforepaste", ElementInternal::onbeforepasteAttrGetter, ElementInternal::onbeforepasteAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onpaste' (Type: 'attribute' ExtAttr: 'DontEnum') {"onpaste", ElementInternal::onpasteAttrGetter, ElementInternal::onpasteAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onreset' (Type: 'attribute' ExtAttr: 'DontEnum') {"onreset", ElementInternal::onresetAttrGetter, ElementInternal::onresetAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onsearch' (Type: 'attribute' ExtAttr: 'DontEnum') {"onsearch", ElementInternal::onsearchAttrGetter, ElementInternal::onsearchAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, // Attribute 'onselectstart' (Type: 'attribute' ExtAttr: 'DontEnum') {"onselectstart", ElementInternal::onselectstartAttrGetter, ElementInternal::onselectstartAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, #if ENABLE(FULLSCREEN_API) // Attribute 'onwebkitfullscreenchange' (Type: 'attribute' ExtAttr: 'DontEnum Conditional') {"onwebkitfullscreenchange", ElementInternal::onwebkitfullscreenchangeAttrGetter, ElementInternal::onwebkitfullscreenchangeAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}, #endif // ENABLE(FULLSCREEN_API) }; static const BatchedCallback ElementCallbacks[] = { {"getAttribute", ElementInternal::getAttributeCallback}, {"setAttribute", ElementInternal::setAttributeCallback}, {"removeAttribute", ElementInternal::removeAttributeCallback}, {"getAttributeNode", ElementInternal::getAttributeNodeCallback}, {"getElementsByTagName", ElementInternal::getElementsByTagNameCallback}, {"getAttributeNS", ElementInternal::getAttributeNSCallback}, {"setAttributeNS", ElementInternal::setAttributeNSCallback}, {"removeAttributeNS", ElementInternal::removeAttributeNSCallback}, {"getElementsByTagNameNS", ElementInternal::getElementsByTagNameNSCallback}, {"getAttributeNodeNS", ElementInternal::getAttributeNodeNSCallback}, {"hasAttribute", ElementInternal::hasAttributeCallback}, {"hasAttributeNS", ElementInternal::hasAttributeNSCallback}, {"focus", ElementInternal::focusCallback}, {"blur", ElementInternal::blurCallback}, {"scrollIntoView", ElementInternal::scrollIntoViewCallback}, {"scrollIntoViewIfNeeded", ElementInternal::scrollIntoViewIfNeededCallback}, {"scrollByLines", ElementInternal::scrollByLinesCallback}, {"scrollByPages", ElementInternal::scrollByPagesCallback}, {"getElementsByClassName", ElementInternal::getElementsByClassNameCallback}, {"querySelector", ElementInternal::querySelectorCallback}, {"querySelectorAll", ElementInternal::querySelectorAllCallback}, {"webkitMatchesSelector", ElementInternal::webkitMatchesSelectorCallback}, {"getClientRects", ElementInternal::getClientRectsCallback}, {"getBoundingClientRect", ElementInternal::getBoundingClientRectCallback}, }; static const BatchedConstant ElementConsts[] = { {"ALLOW_KEYBOARD_INPUT", static_cast<signed int>(1)}, }; COMPILE_ASSERT(1 == Element::ALLOW_KEYBOARD_INPUT, ElementEnumALLOW_KEYBOARD_INPUTIsWrongUseDontCheckEnums); static v8::Persistent<v8::FunctionTemplate> ConfigureV8ElementTemplate(v8::Persistent<v8::FunctionTemplate> desc) { desc->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature = configureTemplate(desc, "Element", V8Node::GetTemplate(), V8Element::internalFieldCount, ElementAttrs, WTF_ARRAY_LENGTH(ElementAttrs), ElementCallbacks, WTF_ARRAY_LENGTH(ElementCallbacks)); v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate(); v8::Local<v8::ObjectTemplate> proto = desc->PrototypeTemplate(); #if ENABLE(TOUCH_EVENTS) if (RuntimeEnabledFeatures::ontouchstartEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'ontouchstart' (Type: 'attribute' ExtAttr: 'EnabledAtRuntime DontEnum Conditional') {"ontouchstart", ElementInternal::ontouchstartAttrGetter, ElementInternal::ontouchstartAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) if (RuntimeEnabledFeatures::ontouchmoveEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'ontouchmove' (Type: 'attribute' ExtAttr: 'EnabledAtRuntime DontEnum Conditional') {"ontouchmove", ElementInternal::ontouchmoveAttrGetter, ElementInternal::ontouchmoveAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) if (RuntimeEnabledFeatures::ontouchendEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'ontouchend' (Type: 'attribute' ExtAttr: 'EnabledAtRuntime DontEnum Conditional') {"ontouchend", ElementInternal::ontouchendAttrGetter, ElementInternal::ontouchendAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } #endif // ENABLE(TOUCH_EVENTS) #if ENABLE(TOUCH_EVENTS) if (RuntimeEnabledFeatures::ontouchcancelEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'ontouchcancel' (Type: 'attribute' ExtAttr: 'EnabledAtRuntime DontEnum Conditional') {"ontouchcancel", ElementInternal::ontouchcancelAttrGetter, ElementInternal::ontouchcancelAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::DontEnum), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } #endif // ENABLE(TOUCH_EVENTS) // Custom Signature 'setAttributeNode' const int setAttributeNodeArgc = 1; v8::Handle<v8::FunctionTemplate> setAttributeNodeArgv[setAttributeNodeArgc] = { V8Attr::GetRawTemplate() }; v8::Handle<v8::Signature> setAttributeNodeSignature = v8::Signature::New(desc, setAttributeNodeArgc, setAttributeNodeArgv); proto->Set(v8::String::New("setAttributeNode"), v8::FunctionTemplate::New(ElementInternal::setAttributeNodeCallback, v8::Handle<v8::Value>(), setAttributeNodeSignature)); // Custom Signature 'removeAttributeNode' const int removeAttributeNodeArgc = 1; v8::Handle<v8::FunctionTemplate> removeAttributeNodeArgv[removeAttributeNodeArgc] = { V8Attr::GetRawTemplate() }; v8::Handle<v8::Signature> removeAttributeNodeSignature = v8::Signature::New(desc, removeAttributeNodeArgc, removeAttributeNodeArgv); proto->Set(v8::String::New("removeAttributeNode"), v8::FunctionTemplate::New(ElementInternal::removeAttributeNodeCallback, v8::Handle<v8::Value>(), removeAttributeNodeSignature)); // Custom Signature 'setAttributeNodeNS' const int setAttributeNodeNSArgc = 1; v8::Handle<v8::FunctionTemplate> setAttributeNodeNSArgv[setAttributeNodeNSArgc] = { V8Attr::GetRawTemplate() }; v8::Handle<v8::Signature> setAttributeNodeNSSignature = v8::Signature::New(desc, setAttributeNodeNSArgc, setAttributeNodeNSArgv); proto->Set(v8::String::New("setAttributeNodeNS"), v8::FunctionTemplate::New(ElementInternal::setAttributeNodeNSCallback, v8::Handle<v8::Value>(), setAttributeNodeNSSignature)); if (RuntimeEnabledFeatures::webkitRequestFullScreenEnabled()) proto->Set(v8::String::New("webkitRequestFullScreen"), v8::FunctionTemplate::New(ElementInternal::webkitRequestFullScreenCallback, v8::Handle<v8::Value>(), defaultSignature)); batchConfigureConstants(desc, proto, ElementConsts, WTF_ARRAY_LENGTH(ElementConsts)); // Custom toString template desc->Set(getToStringName(), getToStringTemplate()); return desc; } v8::Persistent<v8::FunctionTemplate> V8Element::GetRawTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->rawTemplateMap().find(&info); if (result != data->rawTemplateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = createRawTemplate(); data->rawTemplateMap().add(&info, templ); return templ; } v8::Persistent<v8::FunctionTemplate> V8Element::GetTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->templateMap().find(&info); if (result != data->templateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = ConfigureV8ElementTemplate(GetRawTemplate()); data->templateMap().add(&info, templ); return templ; } bool V8Element::HasInstance(v8::Handle<v8::Value> value) { return GetRawTemplate()->HasInstance(value); } v8::Handle<v8::Object> V8Element::wrapSlow(Element* impl) { v8::Handle<v8::Object> wrapper; V8Proxy* proxy = 0; if (impl->document()) { proxy = V8Proxy::retrieve(impl->document()->frame()); if (proxy && static_cast<Node*>(impl->document()) == static_cast<Node*>(impl)) { if (proxy->windowShell()->initContextIfNeeded()) { // initContextIfNeeded may have created a wrapper for the object, retry from the start. return V8Element::wrap(impl); } } } v8::Handle<v8::Context> context; if (proxy) context = proxy->context(); // Enter the node's context and create the wrapper in that context. if (!context.IsEmpty()) context->Enter(); wrapper = V8DOMWrapper::instantiateV8Object(proxy, &info, impl); // Exit the node's context if it was entered. if (!context.IsEmpty()) context->Exit(); if (wrapper.IsEmpty()) return wrapper; impl->ref(); v8::Persistent<v8::Object> wrapperHandle = v8::Persistent<v8::Object>::New(wrapper); if (!hasDependentLifetime) wrapperHandle.MarkIndependent(); wrapperHandle.SetWrapperClassId(v8DOMSubtreeClassId); getDOMNodeMap().set(impl, wrapperHandle); return wrapper; } void V8Element::derefObject(void* object) { static_cast<Element*>(object)->deref(); } } // namespace WebCore
{ "content_hash": "b5e2fe2dee8f0aff4cc8cd88e4fea4e8", "timestamp": "", "source": "github", "line_count": 1589, "max_line_length": 283, "avg_line_length": 51.545626179987416, "alnum_prop": 0.7137938612555856, "repo_name": "Treeeater/WebPermission", "id": "53581bb700a9af73377bb3cfd8adc48a58e4f713", "size": "81906", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src_chrome_Release_obj_global_intermediate_webcore/bindings/V8Element.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "1301" }, { "name": "C", "bytes": "1820540" }, { "name": "C++", "bytes": "38574524" }, { "name": "Java", "bytes": "4882" }, { "name": "JavaScript", "bytes": "2238901" }, { "name": "Objective-C", "bytes": "1768529" }, { "name": "PHP", "bytes": "606" }, { "name": "Perl", "bytes": "699893" }, { "name": "Prolog", "bytes": "142937" }, { "name": "Python", "bytes": "131318" }, { "name": "R", "bytes": "290" }, { "name": "Ruby", "bytes": "3798" }, { "name": "Shell", "bytes": "52312" } ], "symlink_target": "" }
<template> <nav role="navigation"> <div class="nav-wrapper container"> <a class="brand-logo" href="#"> <i class="mdi-action-home left"></i> ${router.title} </a> <a href="#" data-activates="mobile-demo" class="button-collapse"><i class="mdi-navigation-menu"></i></a> <ul class="right hide-on-med-and-down"> <li repeat.for="row of router.navigation" class="${row.isActive ? 'active' : ''}"> <a href.bind="row.href">${row.title}</a> </li> </ul> <ul class="side-nav" id="mobile-demo"> <li repeat.for="row of router.navigation" class="${row.isActive ? 'active' : ''}"> <a href.bind="row.href">${row.title}</a> </li> </ul> </div> </nav> <script> $(document).ready(function () { $(".button-collapse").sideNav(); }); </script> </template>
{ "content_hash": "2e617782008af9aa1a9048cf8bfb9863", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 110, "avg_line_length": 33.5, "alnum_prop": 0.5361653272101033, "repo_name": "pyarmak/aurelia-electron-starter", "id": "cba50c8449f85f0d937dd9fcd41e32f66256ef4d", "size": "871", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/app/nav-bar.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3660" }, { "name": "HTML", "bytes": "3416" }, { "name": "JavaScript", "bytes": "30151" }, { "name": "TypeScript", "bytes": "8128" } ], "symlink_target": "" }
 #pragma once #include <aws/snowball/Snowball_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/snowball/model/ClusterState.h> #include <aws/snowball/model/JobType.h> #include <aws/snowball/model/SnowballType.h> #include <aws/core/utils/DateTime.h> #include <aws/snowball/model/JobResource.h> #include <aws/snowball/model/ShippingOption.h> #include <aws/snowball/model/Notification.h> #include <aws/snowball/model/TaxDocuments.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Snowball { namespace Model { /** * <p>Contains metadata about a specific cluster.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ClusterMetadata">AWS * API Reference</a></p> */ class AWS_SNOWBALL_API ClusterMetadata { public: ClusterMetadata(); ClusterMetadata(Aws::Utils::Json::JsonView jsonValue); ClusterMetadata& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The automatically generated ID for a cluster.</p> */ inline const Aws::String& GetClusterId() const{ return m_clusterId; } /** * <p>The automatically generated ID for a cluster.</p> */ inline bool ClusterIdHasBeenSet() const { return m_clusterIdHasBeenSet; } /** * <p>The automatically generated ID for a cluster.</p> */ inline void SetClusterId(const Aws::String& value) { m_clusterIdHasBeenSet = true; m_clusterId = value; } /** * <p>The automatically generated ID for a cluster.</p> */ inline void SetClusterId(Aws::String&& value) { m_clusterIdHasBeenSet = true; m_clusterId = std::move(value); } /** * <p>The automatically generated ID for a cluster.</p> */ inline void SetClusterId(const char* value) { m_clusterIdHasBeenSet = true; m_clusterId.assign(value); } /** * <p>The automatically generated ID for a cluster.</p> */ inline ClusterMetadata& WithClusterId(const Aws::String& value) { SetClusterId(value); return *this;} /** * <p>The automatically generated ID for a cluster.</p> */ inline ClusterMetadata& WithClusterId(Aws::String&& value) { SetClusterId(std::move(value)); return *this;} /** * <p>The automatically generated ID for a cluster.</p> */ inline ClusterMetadata& WithClusterId(const char* value) { SetClusterId(value); return *this;} /** * <p>The optional description of the cluster.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>The optional description of the cluster.</p> */ inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } /** * <p>The optional description of the cluster.</p> */ inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; } /** * <p>The optional description of the cluster.</p> */ inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); } /** * <p>The optional description of the cluster.</p> */ inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); } /** * <p>The optional description of the cluster.</p> */ inline ClusterMetadata& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>The optional description of the cluster.</p> */ inline ClusterMetadata& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>The optional description of the cluster.</p> */ inline ClusterMetadata& WithDescription(const char* value) { SetDescription(value); return *this;} /** * <p>The <code>KmsKeyARN</code> Amazon Resource Name (ARN) associated with this * cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * API action in AWS Key Management Service (AWS KMS).</p> */ inline const Aws::String& GetKmsKeyARN() const{ return m_kmsKeyARN; } /** * <p>The <code>KmsKeyARN</code> Amazon Resource Name (ARN) associated with this * cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * API action in AWS Key Management Service (AWS KMS).</p> */ inline bool KmsKeyARNHasBeenSet() const { return m_kmsKeyARNHasBeenSet; } /** * <p>The <code>KmsKeyARN</code> Amazon Resource Name (ARN) associated with this * cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * API action in AWS Key Management Service (AWS KMS).</p> */ inline void SetKmsKeyARN(const Aws::String& value) { m_kmsKeyARNHasBeenSet = true; m_kmsKeyARN = value; } /** * <p>The <code>KmsKeyARN</code> Amazon Resource Name (ARN) associated with this * cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * API action in AWS Key Management Service (AWS KMS).</p> */ inline void SetKmsKeyARN(Aws::String&& value) { m_kmsKeyARNHasBeenSet = true; m_kmsKeyARN = std::move(value); } /** * <p>The <code>KmsKeyARN</code> Amazon Resource Name (ARN) associated with this * cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * API action in AWS Key Management Service (AWS KMS).</p> */ inline void SetKmsKeyARN(const char* value) { m_kmsKeyARNHasBeenSet = true; m_kmsKeyARN.assign(value); } /** * <p>The <code>KmsKeyARN</code> Amazon Resource Name (ARN) associated with this * cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * API action in AWS Key Management Service (AWS KMS).</p> */ inline ClusterMetadata& WithKmsKeyARN(const Aws::String& value) { SetKmsKeyARN(value); return *this;} /** * <p>The <code>KmsKeyARN</code> Amazon Resource Name (ARN) associated with this * cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * API action in AWS Key Management Service (AWS KMS).</p> */ inline ClusterMetadata& WithKmsKeyARN(Aws::String&& value) { SetKmsKeyARN(std::move(value)); return *this;} /** * <p>The <code>KmsKeyARN</code> Amazon Resource Name (ARN) associated with this * cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * API action in AWS Key Management Service (AWS KMS).</p> */ inline ClusterMetadata& WithKmsKeyARN(const char* value) { SetKmsKeyARN(value); return *this;} /** * <p>The role ARN associated with this cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * API action in AWS Identity and Access Management (IAM).</p> */ inline const Aws::String& GetRoleARN() const{ return m_roleARN; } /** * <p>The role ARN associated with this cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * API action in AWS Identity and Access Management (IAM).</p> */ inline bool RoleARNHasBeenSet() const { return m_roleARNHasBeenSet; } /** * <p>The role ARN associated with this cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * API action in AWS Identity and Access Management (IAM).</p> */ inline void SetRoleARN(const Aws::String& value) { m_roleARNHasBeenSet = true; m_roleARN = value; } /** * <p>The role ARN associated with this cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * API action in AWS Identity and Access Management (IAM).</p> */ inline void SetRoleARN(Aws::String&& value) { m_roleARNHasBeenSet = true; m_roleARN = std::move(value); } /** * <p>The role ARN associated with this cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * API action in AWS Identity and Access Management (IAM).</p> */ inline void SetRoleARN(const char* value) { m_roleARNHasBeenSet = true; m_roleARN.assign(value); } /** * <p>The role ARN associated with this cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * API action in AWS Identity and Access Management (IAM).</p> */ inline ClusterMetadata& WithRoleARN(const Aws::String& value) { SetRoleARN(value); return *this;} /** * <p>The role ARN associated with this cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * API action in AWS Identity and Access Management (IAM).</p> */ inline ClusterMetadata& WithRoleARN(Aws::String&& value) { SetRoleARN(std::move(value)); return *this;} /** * <p>The role ARN associated with this cluster. This ARN was created using the <a * href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * API action in AWS Identity and Access Management (IAM).</p> */ inline ClusterMetadata& WithRoleARN(const char* value) { SetRoleARN(value); return *this;} /** * <p>The current status of the cluster.</p> */ inline const ClusterState& GetClusterState() const{ return m_clusterState; } /** * <p>The current status of the cluster.</p> */ inline bool ClusterStateHasBeenSet() const { return m_clusterStateHasBeenSet; } /** * <p>The current status of the cluster.</p> */ inline void SetClusterState(const ClusterState& value) { m_clusterStateHasBeenSet = true; m_clusterState = value; } /** * <p>The current status of the cluster.</p> */ inline void SetClusterState(ClusterState&& value) { m_clusterStateHasBeenSet = true; m_clusterState = std::move(value); } /** * <p>The current status of the cluster.</p> */ inline ClusterMetadata& WithClusterState(const ClusterState& value) { SetClusterState(value); return *this;} /** * <p>The current status of the cluster.</p> */ inline ClusterMetadata& WithClusterState(ClusterState&& value) { SetClusterState(std::move(value)); return *this;} /** * <p>The type of job for this cluster. Currently, the only job type supported for * clusters is <code>LOCAL_USE</code>.</p> */ inline const JobType& GetJobType() const{ return m_jobType; } /** * <p>The type of job for this cluster. Currently, the only job type supported for * clusters is <code>LOCAL_USE</code>.</p> */ inline bool JobTypeHasBeenSet() const { return m_jobTypeHasBeenSet; } /** * <p>The type of job for this cluster. Currently, the only job type supported for * clusters is <code>LOCAL_USE</code>.</p> */ inline void SetJobType(const JobType& value) { m_jobTypeHasBeenSet = true; m_jobType = value; } /** * <p>The type of job for this cluster. Currently, the only job type supported for * clusters is <code>LOCAL_USE</code>.</p> */ inline void SetJobType(JobType&& value) { m_jobTypeHasBeenSet = true; m_jobType = std::move(value); } /** * <p>The type of job for this cluster. Currently, the only job type supported for * clusters is <code>LOCAL_USE</code>.</p> */ inline ClusterMetadata& WithJobType(const JobType& value) { SetJobType(value); return *this;} /** * <p>The type of job for this cluster. Currently, the only job type supported for * clusters is <code>LOCAL_USE</code>.</p> */ inline ClusterMetadata& WithJobType(JobType&& value) { SetJobType(std::move(value)); return *this;} /** * <p>The type of AWS Snow device to use for this cluster. </p> <p>For * cluster jobs, AWS Snow Family currently supports only the <code>EDGE</code> * device type.</p> */ inline const SnowballType& GetSnowballType() const{ return m_snowballType; } /** * <p>The type of AWS Snow device to use for this cluster. </p> <p>For * cluster jobs, AWS Snow Family currently supports only the <code>EDGE</code> * device type.</p> */ inline bool SnowballTypeHasBeenSet() const { return m_snowballTypeHasBeenSet; } /** * <p>The type of AWS Snow device to use for this cluster. </p> <p>For * cluster jobs, AWS Snow Family currently supports only the <code>EDGE</code> * device type.</p> */ inline void SetSnowballType(const SnowballType& value) { m_snowballTypeHasBeenSet = true; m_snowballType = value; } /** * <p>The type of AWS Snow device to use for this cluster. </p> <p>For * cluster jobs, AWS Snow Family currently supports only the <code>EDGE</code> * device type.</p> */ inline void SetSnowballType(SnowballType&& value) { m_snowballTypeHasBeenSet = true; m_snowballType = std::move(value); } /** * <p>The type of AWS Snow device to use for this cluster. </p> <p>For * cluster jobs, AWS Snow Family currently supports only the <code>EDGE</code> * device type.</p> */ inline ClusterMetadata& WithSnowballType(const SnowballType& value) { SetSnowballType(value); return *this;} /** * <p>The type of AWS Snow device to use for this cluster. </p> <p>For * cluster jobs, AWS Snow Family currently supports only the <code>EDGE</code> * device type.</p> */ inline ClusterMetadata& WithSnowballType(SnowballType&& value) { SetSnowballType(std::move(value)); return *this;} /** * <p>The creation date for this cluster.</p> */ inline const Aws::Utils::DateTime& GetCreationDate() const{ return m_creationDate; } /** * <p>The creation date for this cluster.</p> */ inline bool CreationDateHasBeenSet() const { return m_creationDateHasBeenSet; } /** * <p>The creation date for this cluster.</p> */ inline void SetCreationDate(const Aws::Utils::DateTime& value) { m_creationDateHasBeenSet = true; m_creationDate = value; } /** * <p>The creation date for this cluster.</p> */ inline void SetCreationDate(Aws::Utils::DateTime&& value) { m_creationDateHasBeenSet = true; m_creationDate = std::move(value); } /** * <p>The creation date for this cluster.</p> */ inline ClusterMetadata& WithCreationDate(const Aws::Utils::DateTime& value) { SetCreationDate(value); return *this;} /** * <p>The creation date for this cluster.</p> */ inline ClusterMetadata& WithCreationDate(Aws::Utils::DateTime&& value) { SetCreationDate(std::move(value)); return *this;} /** * <p>The arrays of <a>JobResource</a> objects that can include updated * <a>S3Resource</a> objects or <a>LambdaResource</a> objects.</p> */ inline const JobResource& GetResources() const{ return m_resources; } /** * <p>The arrays of <a>JobResource</a> objects that can include updated * <a>S3Resource</a> objects or <a>LambdaResource</a> objects.</p> */ inline bool ResourcesHasBeenSet() const { return m_resourcesHasBeenSet; } /** * <p>The arrays of <a>JobResource</a> objects that can include updated * <a>S3Resource</a> objects or <a>LambdaResource</a> objects.</p> */ inline void SetResources(const JobResource& value) { m_resourcesHasBeenSet = true; m_resources = value; } /** * <p>The arrays of <a>JobResource</a> objects that can include updated * <a>S3Resource</a> objects or <a>LambdaResource</a> objects.</p> */ inline void SetResources(JobResource&& value) { m_resourcesHasBeenSet = true; m_resources = std::move(value); } /** * <p>The arrays of <a>JobResource</a> objects that can include updated * <a>S3Resource</a> objects or <a>LambdaResource</a> objects.</p> */ inline ClusterMetadata& WithResources(const JobResource& value) { SetResources(value); return *this;} /** * <p>The arrays of <a>JobResource</a> objects that can include updated * <a>S3Resource</a> objects or <a>LambdaResource</a> objects.</p> */ inline ClusterMetadata& WithResources(JobResource&& value) { SetResources(std::move(value)); return *this;} /** * <p>The automatically generated ID for a specific address.</p> */ inline const Aws::String& GetAddressId() const{ return m_addressId; } /** * <p>The automatically generated ID for a specific address.</p> */ inline bool AddressIdHasBeenSet() const { return m_addressIdHasBeenSet; } /** * <p>The automatically generated ID for a specific address.</p> */ inline void SetAddressId(const Aws::String& value) { m_addressIdHasBeenSet = true; m_addressId = value; } /** * <p>The automatically generated ID for a specific address.</p> */ inline void SetAddressId(Aws::String&& value) { m_addressIdHasBeenSet = true; m_addressId = std::move(value); } /** * <p>The automatically generated ID for a specific address.</p> */ inline void SetAddressId(const char* value) { m_addressIdHasBeenSet = true; m_addressId.assign(value); } /** * <p>The automatically generated ID for a specific address.</p> */ inline ClusterMetadata& WithAddressId(const Aws::String& value) { SetAddressId(value); return *this;} /** * <p>The automatically generated ID for a specific address.</p> */ inline ClusterMetadata& WithAddressId(Aws::String&& value) { SetAddressId(std::move(value)); return *this;} /** * <p>The automatically generated ID for a specific address.</p> */ inline ClusterMetadata& WithAddressId(const char* value) { SetAddressId(value); return *this;} /** * <p>The shipping speed for each node in this cluster. This speed doesn't dictate * how soon you'll get each device, rather it represents how quickly each device * moves to its destination while in transit. Regional shipping speeds are as * follows:</p> <ul> <li> <p>In Australia, you have access to express shipping. * Typically, devices shipped express are delivered in about a day.</p> </li> <li> * <p>In the European Union (EU), you have access to express shipping. Typically, * Snow devices shipped express are delivered in about a day. In addition, most * countries in the EU have access to standard shipping, which typically takes less * than a week, one way.</p> </li> <li> <p>In India, Snow devices are delivered in * one to seven days.</p> </li> <li> <p>In the US, you have access to one-day * shipping and two-day shipping.</p> </li> </ul> */ inline const ShippingOption& GetShippingOption() const{ return m_shippingOption; } /** * <p>The shipping speed for each node in this cluster. This speed doesn't dictate * how soon you'll get each device, rather it represents how quickly each device * moves to its destination while in transit. Regional shipping speeds are as * follows:</p> <ul> <li> <p>In Australia, you have access to express shipping. * Typically, devices shipped express are delivered in about a day.</p> </li> <li> * <p>In the European Union (EU), you have access to express shipping. Typically, * Snow devices shipped express are delivered in about a day. In addition, most * countries in the EU have access to standard shipping, which typically takes less * than a week, one way.</p> </li> <li> <p>In India, Snow devices are delivered in * one to seven days.</p> </li> <li> <p>In the US, you have access to one-day * shipping and two-day shipping.</p> </li> </ul> */ inline bool ShippingOptionHasBeenSet() const { return m_shippingOptionHasBeenSet; } /** * <p>The shipping speed for each node in this cluster. This speed doesn't dictate * how soon you'll get each device, rather it represents how quickly each device * moves to its destination while in transit. Regional shipping speeds are as * follows:</p> <ul> <li> <p>In Australia, you have access to express shipping. * Typically, devices shipped express are delivered in about a day.</p> </li> <li> * <p>In the European Union (EU), you have access to express shipping. Typically, * Snow devices shipped express are delivered in about a day. In addition, most * countries in the EU have access to standard shipping, which typically takes less * than a week, one way.</p> </li> <li> <p>In India, Snow devices are delivered in * one to seven days.</p> </li> <li> <p>In the US, you have access to one-day * shipping and two-day shipping.</p> </li> </ul> */ inline void SetShippingOption(const ShippingOption& value) { m_shippingOptionHasBeenSet = true; m_shippingOption = value; } /** * <p>The shipping speed for each node in this cluster. This speed doesn't dictate * how soon you'll get each device, rather it represents how quickly each device * moves to its destination while in transit. Regional shipping speeds are as * follows:</p> <ul> <li> <p>In Australia, you have access to express shipping. * Typically, devices shipped express are delivered in about a day.</p> </li> <li> * <p>In the European Union (EU), you have access to express shipping. Typically, * Snow devices shipped express are delivered in about a day. In addition, most * countries in the EU have access to standard shipping, which typically takes less * than a week, one way.</p> </li> <li> <p>In India, Snow devices are delivered in * one to seven days.</p> </li> <li> <p>In the US, you have access to one-day * shipping and two-day shipping.</p> </li> </ul> */ inline void SetShippingOption(ShippingOption&& value) { m_shippingOptionHasBeenSet = true; m_shippingOption = std::move(value); } /** * <p>The shipping speed for each node in this cluster. This speed doesn't dictate * how soon you'll get each device, rather it represents how quickly each device * moves to its destination while in transit. Regional shipping speeds are as * follows:</p> <ul> <li> <p>In Australia, you have access to express shipping. * Typically, devices shipped express are delivered in about a day.</p> </li> <li> * <p>In the European Union (EU), you have access to express shipping. Typically, * Snow devices shipped express are delivered in about a day. In addition, most * countries in the EU have access to standard shipping, which typically takes less * than a week, one way.</p> </li> <li> <p>In India, Snow devices are delivered in * one to seven days.</p> </li> <li> <p>In the US, you have access to one-day * shipping and two-day shipping.</p> </li> </ul> */ inline ClusterMetadata& WithShippingOption(const ShippingOption& value) { SetShippingOption(value); return *this;} /** * <p>The shipping speed for each node in this cluster. This speed doesn't dictate * how soon you'll get each device, rather it represents how quickly each device * moves to its destination while in transit. Regional shipping speeds are as * follows:</p> <ul> <li> <p>In Australia, you have access to express shipping. * Typically, devices shipped express are delivered in about a day.</p> </li> <li> * <p>In the European Union (EU), you have access to express shipping. Typically, * Snow devices shipped express are delivered in about a day. In addition, most * countries in the EU have access to standard shipping, which typically takes less * than a week, one way.</p> </li> <li> <p>In India, Snow devices are delivered in * one to seven days.</p> </li> <li> <p>In the US, you have access to one-day * shipping and two-day shipping.</p> </li> </ul> */ inline ClusterMetadata& WithShippingOption(ShippingOption&& value) { SetShippingOption(std::move(value)); return *this;} /** * <p>The Amazon Simple Notification Service (Amazon SNS) notification settings for * this cluster.</p> */ inline const Notification& GetNotification() const{ return m_notification; } /** * <p>The Amazon Simple Notification Service (Amazon SNS) notification settings for * this cluster.</p> */ inline bool NotificationHasBeenSet() const { return m_notificationHasBeenSet; } /** * <p>The Amazon Simple Notification Service (Amazon SNS) notification settings for * this cluster.</p> */ inline void SetNotification(const Notification& value) { m_notificationHasBeenSet = true; m_notification = value; } /** * <p>The Amazon Simple Notification Service (Amazon SNS) notification settings for * this cluster.</p> */ inline void SetNotification(Notification&& value) { m_notificationHasBeenSet = true; m_notification = std::move(value); } /** * <p>The Amazon Simple Notification Service (Amazon SNS) notification settings for * this cluster.</p> */ inline ClusterMetadata& WithNotification(const Notification& value) { SetNotification(value); return *this;} /** * <p>The Amazon Simple Notification Service (Amazon SNS) notification settings for * this cluster.</p> */ inline ClusterMetadata& WithNotification(Notification&& value) { SetNotification(std::move(value)); return *this;} /** * <p>The ID of the address that you want a cluster shipped to, after it will be * shipped to its primary address. This field is not supported in most regions.</p> */ inline const Aws::String& GetForwardingAddressId() const{ return m_forwardingAddressId; } /** * <p>The ID of the address that you want a cluster shipped to, after it will be * shipped to its primary address. This field is not supported in most regions.</p> */ inline bool ForwardingAddressIdHasBeenSet() const { return m_forwardingAddressIdHasBeenSet; } /** * <p>The ID of the address that you want a cluster shipped to, after it will be * shipped to its primary address. This field is not supported in most regions.</p> */ inline void SetForwardingAddressId(const Aws::String& value) { m_forwardingAddressIdHasBeenSet = true; m_forwardingAddressId = value; } /** * <p>The ID of the address that you want a cluster shipped to, after it will be * shipped to its primary address. This field is not supported in most regions.</p> */ inline void SetForwardingAddressId(Aws::String&& value) { m_forwardingAddressIdHasBeenSet = true; m_forwardingAddressId = std::move(value); } /** * <p>The ID of the address that you want a cluster shipped to, after it will be * shipped to its primary address. This field is not supported in most regions.</p> */ inline void SetForwardingAddressId(const char* value) { m_forwardingAddressIdHasBeenSet = true; m_forwardingAddressId.assign(value); } /** * <p>The ID of the address that you want a cluster shipped to, after it will be * shipped to its primary address. This field is not supported in most regions.</p> */ inline ClusterMetadata& WithForwardingAddressId(const Aws::String& value) { SetForwardingAddressId(value); return *this;} /** * <p>The ID of the address that you want a cluster shipped to, after it will be * shipped to its primary address. This field is not supported in most regions.</p> */ inline ClusterMetadata& WithForwardingAddressId(Aws::String&& value) { SetForwardingAddressId(std::move(value)); return *this;} /** * <p>The ID of the address that you want a cluster shipped to, after it will be * shipped to its primary address. This field is not supported in most regions.</p> */ inline ClusterMetadata& WithForwardingAddressId(const char* value) { SetForwardingAddressId(value); return *this;} /** * <p>The tax documents required in your AWS Region.</p> */ inline const TaxDocuments& GetTaxDocuments() const{ return m_taxDocuments; } /** * <p>The tax documents required in your AWS Region.</p> */ inline bool TaxDocumentsHasBeenSet() const { return m_taxDocumentsHasBeenSet; } /** * <p>The tax documents required in your AWS Region.</p> */ inline void SetTaxDocuments(const TaxDocuments& value) { m_taxDocumentsHasBeenSet = true; m_taxDocuments = value; } /** * <p>The tax documents required in your AWS Region.</p> */ inline void SetTaxDocuments(TaxDocuments&& value) { m_taxDocumentsHasBeenSet = true; m_taxDocuments = std::move(value); } /** * <p>The tax documents required in your AWS Region.</p> */ inline ClusterMetadata& WithTaxDocuments(const TaxDocuments& value) { SetTaxDocuments(value); return *this;} /** * <p>The tax documents required in your AWS Region.</p> */ inline ClusterMetadata& WithTaxDocuments(TaxDocuments&& value) { SetTaxDocuments(std::move(value)); return *this;} private: Aws::String m_clusterId; bool m_clusterIdHasBeenSet; Aws::String m_description; bool m_descriptionHasBeenSet; Aws::String m_kmsKeyARN; bool m_kmsKeyARNHasBeenSet; Aws::String m_roleARN; bool m_roleARNHasBeenSet; ClusterState m_clusterState; bool m_clusterStateHasBeenSet; JobType m_jobType; bool m_jobTypeHasBeenSet; SnowballType m_snowballType; bool m_snowballTypeHasBeenSet; Aws::Utils::DateTime m_creationDate; bool m_creationDateHasBeenSet; JobResource m_resources; bool m_resourcesHasBeenSet; Aws::String m_addressId; bool m_addressIdHasBeenSet; ShippingOption m_shippingOption; bool m_shippingOptionHasBeenSet; Notification m_notification; bool m_notificationHasBeenSet; Aws::String m_forwardingAddressId; bool m_forwardingAddressIdHasBeenSet; TaxDocuments m_taxDocuments; bool m_taxDocumentsHasBeenSet; }; } // namespace Model } // namespace Snowball } // namespace Aws
{ "content_hash": "9a18923d7c66eadaa1601ad780a577d8", "timestamp": "", "source": "github", "line_count": 723, "max_line_length": 145, "avg_line_length": 42.8865836791148, "alnum_prop": 0.672622311091044, "repo_name": "jt70471/aws-sdk-cpp", "id": "8b8f7fcbff90aba55c107d6d74a36c890f0a71e9", "size": "31126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-snowball/include/aws/snowball/model/ClusterMetadata.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
module Dhfex::Mails::Fedex class Validator def initialize(number) @number = number end def valid? @number.to_s.match(/^[0-9]{34}$/).present? end end end
{ "content_hash": "ec2db3a33724c9036fcfb31564dbe04e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 48, "avg_line_length": 14.461538461538462, "alnum_prop": 0.5904255319148937, "repo_name": "yuryromanov/dhfex", "id": "460270ce784d3424ee8faad4cabf402adb3fd14d", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/dhfex/mails/fedex/validator.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1462" }, { "name": "JavaScript", "bytes": "599" }, { "name": "Ruby", "bytes": "34359" } ], "symlink_target": "" }
<?php /** * @namespace */ namespace Zend\Locale; /** * include needed classes */ require_once 'Zend/Locale/Data.php'; /** * @category Zend * @package Zend_Locale * @subpackage Format * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Format { const STANDARD = 'auto'; private static $_options = array('date_format' => null, 'number_format' => null, 'format_type' => 'iso', 'fix_date' => false, 'locale' => null, 'cache' => null, 'disableCache' => false, 'precision' => null); /** * Sets class wide options, if no option was given, the actual set options will be returned * The 'precision' option of a value is used to truncate or stretch extra digits. -1 means not to touch the extra digits. * The 'locale' option helps when parsing numbers and dates using separators and month names. * The date format 'format_type' option selects between CLDR/ISO date format specifier tokens and PHP's date() tokens. * The 'fix_date' option enables or disables heuristics that attempt to correct invalid dates. * The 'number_format' option can be used to specify a default number format string * The 'date_format' option can be used to specify a default date format string, but beware of using getDate(), * checkDateFormat() and getTime() after using setOptions() with a 'format'. To use these four methods * with the default date format for a locale, use array('date_format' => null, 'locale' => $locale) for their options. * * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false, * locale = Zend_Locale | locale string, precision = whole number between -1 and 30 * @throws Zend_Locale_Exception * @return Options array if no option was given */ public static function setOptions(array $options = array()) { self::$_options = self::_checkOptions($options) + self::$_options; return self::$_options; } /** * Internal function for checking the options array of proper input values * See {@link setOptions()} for details. * * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false, * locale = Zend_Locale | locale string, precision = whole number between -1 and 30 * @throws Zend_Locale_Exception * @return Options array if no option was given */ private static function _checkOptions(array $options = array()) { if (count($options) == 0) { return self::$_options; } foreach ($options as $name => $value) { $name = strtolower($name); if ($name !== 'locale') { if (gettype($value) === 'string') { $value = strtolower($value); } } switch($name) { case 'number_format' : if ($value == Format::STANDARD) { $locale = self::$_options['locale']; if (isset($options['locale'])) { $locale = $options['locale']; } $options['number_format'] = Data\Data::getContent($locale, 'decimalnumber'); } else if ((gettype($value) !== 'string') and ($value !== NULL)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("Unknown number format type '" . gettype($value) . "'. " . "Format '$value' must be a valid number format string."); } break; case 'date_format' : if ($value == Format::STANDARD) { $locale = self::$_options['locale']; if (isset($options['locale'])) { $locale = $options['locale']; } $options['date_format'] = Format::getDateFormat($locale); } else if ((gettype($value) !== 'string') and ($value !== NULL)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("Unknown dateformat type '" . gettype($value) . "'. " . "Format '$value' must be a valid ISO or PHP date format string."); } else { if (((isset($options['format_type']) === true) and ($options['format_type'] == 'php')) or ((isset($options['format_type']) === false) and (self::$_options['format_type'] == 'php'))) { $options['date_format'] = Format::convertPhpToIsoFormat($value); } } break; case 'format_type' : if (($value != 'php') && ($value != 'iso')) { require_once 'Zend/Locale/Exception.php'; throw new Exception("Unknown date format type '$value'. Only 'iso' and 'php'" . " are supported."); } break; case 'fix_date' : if (($value !== true) && ($value !== false)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("Enabling correction of dates must be either true or false" . "(fix_date='$value')."); } break; case 'locale' : $options['locale'] = Locale::findLocale($value); break; case 'cache' : if ($value instanceof \Zend\Cache\Core) { Data\Data::setCache($value); } break; case 'disablecache' : Data\Data::disableCache($value); break; case 'precision' : if ($value === NULL) { $value = -1; } if (($value < -1) || ($value > 30)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("'$value' precision is not a whole number less than 30."); } break; default: require_once 'Zend/Locale/Exception.php'; throw new Exception("Unknown option: '$name' = '$value'"); break; } } return $options; } /** * Changes the numbers/digits within a given string from one script to another * 'Decimal' representated the stardard numbers 0-9, if a script does not exist * an exception will be thrown. * * Examples for conversion from Arabic to Latin numerals: * convertNumerals('١١٠ Tests', 'Arab'); -> returns '100 Tests' * Example for conversion from Latin to Arabic numerals: * convertNumerals('100 Tests', 'Latn', 'Arab'); -> returns '١١٠ Tests' * * @param string $input String to convert * @param string $from Script to parse, see {@link Zend_Locale::getScriptList()} for details. * @param string $to OPTIONAL Script to convert to * @return string Returns the converted input * @throws Zend_Locale_Exception */ public static function convertNumerals($input, $from, $to = null) { if (!self::_getUniCodeSupport()) { trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE); } $from = strtolower($from); $source = Data\Data::getContent('en', 'numberingsystem', $from); if (empty($source)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("Unknown script '$from'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9."); } if ($to !== null) { $to = strtolower($to); $target = Data\Data::getContent('en', 'numberingsystem', $to); if (empty($target)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("Unknown script '$to'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9."); } } else { $target = '0123456789'; } for ($x = 0; $x < 10; ++$x) { $asource[$x] = "/" . iconv_substr($source, $x, 1, 'UTF-8') . "/u"; $atarget[$x] = iconv_substr($target, $x, 1, 'UTF-8'); } return preg_replace($asource, $atarget, $input); } /** * Returns the normalized number from a localized one * Parsing depends on given locale (grouping and decimal) * * Examples for input: * '2345.4356,1234' = 23455456.1234 * '+23,3452.123' = 233452.123 * '12343 ' = 12343 * '-9456' = -9456 * '0' = 0 * * @param string $input Input string to parse for numbers * @param array $options Options: locale, precision. See {@link setOptions()} for details. * @return string Returns the extracted number * @throws Zend_Locale_Exception */ public static function getNumber($input, array $options = array()) { $options = self::_checkOptions($options) + self::$_options; if (!is_string($input)) { return $input; } if (!self::isNumber($input, $options)) { require_once 'Zend/Locale/Exception.php'; throw new Exception('No localized value in ' . $input . ' found, or the given number does not match the localized format'); } // Get correct signs for this locale $symbols = Data\Data::getList($options['locale'],'symbols'); // Change locale input to be default number if ((strpos($input, $symbols['minus']) !== false) || (strpos($input, '-') !== false)) { $input = strtr($input, array($symbols['minus'] => '', '-' => '')); $input = '-' . $input; } $input = str_replace($symbols['group'],'', $input); if (strpos($input, $symbols['decimal']) !== false) { if ($symbols['decimal'] != '.') { $input = str_replace($symbols['decimal'], ".", $input); } $pre = substr($input, strpos($input, '.') + 1); if ($options['precision'] === null) { $options['precision'] = strlen($pre); } if (strlen($pre) >= $options['precision']) { $input = substr($input, 0, strlen($input) - strlen($pre) + $options['precision']); } if (($options['precision'] == 0) && ($input[strlen($input) - 1] == '.')) { $input = substr($input, 0, -1); } } return $input; } /** * Returns a locale formatted number depending on the given options. * The seperation and fraction sign is used from the set locale. * ##0.# -> 12345.12345 -> 12345.12345 * ##0.00 -> 12345.12345 -> 12345.12 * ##,##0.00 -> 12345.12345 -> 12,345.12 * * @param string $input Localized number string * @param array $options Options: number_format, locale, precision. See {@link setOptions()} for details. * @return string locale formatted number * @throws Zend_Locale_Exception */ public static function toNumber($value, array $options = array()) { // load class within method for speed require_once 'Zend/Locale/Math.php'; $value = Math\Math::normalize($value); $value = Math\Math::floatalize($value); $options = self::_checkOptions($options) + self::$_options; $options['locale'] = (string) $options['locale']; // Get correct signs for this locale $symbols = Data\Data::getList($options['locale'], 'symbols'); $oenc = iconv_get_encoding('internal_encoding'); iconv_set_encoding('internal_encoding', 'UTF-8'); // Get format $format = $options['number_format']; if ($format === null) { $format = Data\Data::getContent($options['locale'], 'decimalnumber'); $format = self::_seperateFormat($format, $value, $options['precision']); if ($options['precision'] !== null) { $value = Math\Math::normalize(Math\Math::round($value, $options['precision'])); } } else { // seperate negative format pattern when available $format = self::_seperateFormat($format, $value, $options['precision']); if (strpos($format, '.')) { if (is_numeric($options['precision'])) { $value = Math\Math::round($value, $options['precision']); } else { if (substr($format, iconv_strpos($format, '.') + 1, 3) == '###') { $options['precision'] = null; } else { $options['precision'] = iconv_strlen(iconv_substr($format, iconv_strpos($format, '.') + 1, iconv_strrpos($format, '0') - iconv_strpos($format, '.'))); $format = iconv_substr($format, 0, iconv_strpos($format, '.') + 1) . '###' . iconv_substr($format, iconv_strrpos($format, '0') + 1); } } } else { $value = Math\Math::round($value, 0); $options['precision'] = 0; } $value = Math\Math::normalize($value); } if (iconv_strpos($format, '0') === false) { iconv_set_encoding('internal_encoding', $oenc); require_once 'Zend/Locale/Exception.php'; throw new Exception('Wrong format... missing 0'); } // get number parts $pos = iconv_strpos($value, '.'); if ($pos !== false) { if ($options['precision'] === null) { $precstr = iconv_substr($value, $pos + 1); } else { $precstr = iconv_substr($value, $pos + 1, $options['precision']); if (iconv_strlen($precstr) < $options['precision']) { $precstr = $precstr . str_pad("0", ($options['precision'] - iconv_strlen($precstr)), "0"); } } } else { if ($options['precision'] > 0) { $precstr = str_pad("0", ($options['precision']), "0"); } } if ($options['precision'] === null) { if (isset($precstr)) { $options['precision'] = iconv_strlen($precstr); } else { $options['precision'] = 0; } } // get fraction and format lengths if (strpos($value, '.') !== false) { $number = substr((string) $value, 0, strpos($value, '.')); } else { $number = $value; } $prec = call_user_func(Math\Math::$sub, $value, $number, $options['precision']); $prec = Math\Math::floatalize($prec); $prec = Math\Math::normalize($prec); if (iconv_strpos($prec, '-') !== false) { $prec = iconv_substr($prec, 1); } if (($prec == 0) and ($options['precision'] > 0)) { $prec = "0.0"; } if (($options['precision'] + 2) > iconv_strlen($prec)) { $prec = str_pad((string) $prec, $options['precision'] + 2, "0", STR_PAD_RIGHT); } if (iconv_strpos($number, '-') !== false) { $number = iconv_substr($number, 1); } $group = iconv_strrpos($format, ','); $group2 = iconv_strpos ($format, ','); $point = iconv_strpos ($format, '0'); // Add fraction $rest = ""; if (iconv_strpos($format, '.')) { $rest = iconv_substr($format, iconv_strpos($format, '.') + 1); $length = iconv_strlen($rest); for($x = 0; $x < $length; ++$x) { if (($rest[0] == '0') || ($rest[0] == '#')) { $rest = iconv_substr($rest, 1); } } $format = iconv_substr($format, 0, iconv_strlen($format) - iconv_strlen($rest)); } if ($options['precision'] == '0') { if (iconv_strrpos($format, '-') != 0) { $format = iconv_substr($format, 0, $point) . iconv_substr($format, iconv_strrpos($format, '#') + 2); } else { $format = iconv_substr($format, 0, $point); } } else { $format = iconv_substr($format, 0, $point) . $symbols['decimal'] . iconv_substr($prec, 2); } $format .= $rest; // Add seperation if ($group == 0) { // no seperation $format = $number . iconv_substr($format, $point); } else if ($group == $group2) { // only 1 seperation $seperation = ($point - $group); for ($x = iconv_strlen($number); $x > $seperation; $x -= $seperation) { if (iconv_substr($number, 0, $x - $seperation) !== "") { $number = iconv_substr($number, 0, $x - $seperation) . $symbols['group'] . iconv_substr($number, $x - $seperation); } } $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point); } else { // 2 seperations if (iconv_strlen($number) > ($point - $group)) { $seperation = ($point - $group); $number = iconv_substr($number, 0, iconv_strlen($number) - $seperation) . $symbols['group'] . iconv_substr($number, iconv_strlen($number) - $seperation); if ((iconv_strlen($number) - 1) > ($point - $group + 1)) { $seperation2 = ($group - $group2 - 1); for ($x = iconv_strlen($number) - $seperation2 - 2; $x > $seperation2; $x -= $seperation2) { $number = iconv_substr($number, 0, $x - $seperation2) . $symbols['group'] . iconv_substr($number, $x - $seperation2); } } } $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point); } // set negative sign if (call_user_func(Math\Math::$comp, $value, 0, $options['precision']) < 0) { if (iconv_strpos($format, '-') === false) { $format = $symbols['minus'] . $format; } else { $format = str_replace('-', $symbols['minus'], $format); } } iconv_set_encoding('internal_encoding', $oenc); return (string) $format; } private static function _seperateFormat($format, $value, $precision) { if (iconv_strpos($format, ';') !== false) { if (call_user_func(Math\Math::$comp, $value, 0, $precision) < 0) { $tmpformat = iconv_substr($format, iconv_strpos($format, ';') + 1); if ($tmpformat[0] == '(') { $format = iconv_substr($format, 0, iconv_strpos($format, ';')); } else { $format = $tmpformat; } } else { $format = iconv_substr($format, 0, iconv_strpos($format, ';')); } } return $format; } /** * Checks if the input contains a normalized or localized number * * @param string $input Localized number string * @param array $options Options: locale. See {@link setOptions()} for details. * @return boolean Returns true if a number was found */ public static function isNumber($input, array $options = array()) { if (!self::_getUniCodeSupport()) { trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE); } $options = self::_checkOptions($options) + self::$_options; // Get correct signs for this locale $symbols = Data\Data::getList($options['locale'],'symbols'); $regexs = Format::_getRegexForType('decimalnumber', $options); $regexs = array_merge($regexs, Format::_getRegexForType('scientificnumber', $options)); if (!empty($input) && ($input[0] == $symbols['decimal'])) { $input = 0 . $input; } foreach ($regexs as $regex) { preg_match($regex, $input, $found); if (isset($found[0])) { return true; } } return false; } /** * Internal method to convert cldr number syntax into regex * * @param string $type * @return string */ private static function _getRegexForType($type, $options) { $decimal = Data\Data::getContent($options['locale'], $type); $decimal = preg_replace('/[^#0,;\.\-Ee]/u', '',$decimal); $patterns = explode(';', $decimal); if (count($patterns) == 1) { $patterns[1] = '-' . $patterns[0]; } $symbols = Data\Data::getList($options['locale'],'symbols'); foreach($patterns as $pkey => $pattern) { $regex[$pkey] = '/^'; $rest = 0; $end = null; if (strpos($pattern, '.') !== false) { $end = substr($pattern, strpos($pattern, '.') + 1); $pattern = substr($pattern, 0, -strlen($end) - 1); } if (strpos($pattern, ',') !== false) { $parts = explode(',', $pattern); $count = count($parts); foreach($parts as $key => $part) { switch ($part) { case '#': case '-#': if ($part[0] == '-') { $regex[$pkey] .= '[' . $symbols['minus'] . '-]{0,1}'; } else { $regex[$pkey] .= '[' . $symbols['plus'] . '+]{0,1}'; } if (($parts[$key + 1]) == '##0') { $regex[$pkey] .= '[0-9]{1,3}'; } else if (($parts[$key + 1]) == '##') { $regex[$pkey] .= '[0-9]{1,2}'; } else { throw new Exception('Unsupported token for numberformat (Pos 1):"' . $pattern . '"'); } break; case '##': if ($parts[$key + 1] == '##0') { $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{2})*'; } else { throw new Exception('Unsupported token for numberformat (Pos 2):"' . $pattern . '"'); } break; case '##0': if ($parts[$key - 1] == '##') { $regex[$pkey] .= '[0-9]'; } else if (($parts[$key - 1] == '#') || ($parts[$key - 1] == '-#')) { $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{3})*'; } else { throw new Exception('Unsupported token for numberformat (Pos 3):"' . $pattern . '"'); } break; case '#0': if ($key == 0) { $regex[$pkey] .= '[0-9]*'; } else { throw new Exception('Unsupported token for numberformat (Pos 4):"' . $pattern . '"'); } break; } } } if (strpos($pattern, 'E') !== false) { if (($pattern == '#E0') || ($pattern == '#E00')) { $regex[$pkey] .= '[' . $symbols['plus']. '+]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['plus']. '+]{0,1}[0-9]{1,}'; } else if (($pattern == '-#E0') || ($pattern == '-#E00')) { $regex[$pkey] .= '[' . $symbols['minus']. '-]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['minus']. '-]{0,1}[0-9]{1,}'; } else { throw new Exception('Unsupported token for numberformat (Pos 5):"' . $pattern . '"'); } } if (!empty($end)) { if ($end == '###') { $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}'; } else if ($end == '###-') { $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}[' . $symbols['minus']. '-]'; } else { throw new Exception('Unsupported token for numberformat (Pos 6):"' . $pattern . '"'); } } $regex[$pkey] .= '$/u'; } return $regex; } /** * Alias for getNumber * * @param string $value Number to localize * @param array $options Options: locale, precision. See {@link setOptions()} for details. * @return float */ public static function getFloat($input, array $options = array()) { return floatval(self::getNumber($input, $options)); } /** * Returns a locale formatted integer number * Alias for toNumber() * * @param string $value Number to normalize * @param array $options Options: locale, precision. See {@link setOptions()} for details. * @return string Locale formatted number */ public static function toFloat($value, array $options = array()) { $options['number_format'] = Format::STANDARD; return self::toNumber($value, $options); } /** * Returns if a float was found * Alias for isNumber() * * @param string $input Localized number string * @param array $options Options: locale. See {@link setOptions()} for details. * @return boolean Returns true if a number was found */ public static function isFloat($value, array $options = array()) { return self::isNumber($value, $options); } /** * Returns the first found integer from an string * Parsing depends on given locale (grouping and decimal) * * Examples for input: * ' 2345.4356,1234' = 23455456 * '+23,3452.123' = 233452 * ' 12343 ' = 12343 * '-9456km' = -9456 * '0' = 0 * '(-){0,1}(\d+(\.){0,1})*(\,){0,1})\d+' * * @param string $input Input string to parse for numbers * @param array $options Options: locale. See {@link setOptions()} for details. * @return integer Returns the extracted number */ public static function getInteger($input, array $options = array()) { $options['precision'] = 0; return intval(self::getFloat($input, $options)); } /** * Returns a localized number * * @param string $value Number to normalize * @param array $options Options: locale. See {@link setOptions()} for details. * @return string Locale formatted number */ public static function toInteger($value, array $options = array()) { $options['precision'] = 0; $options['number_format'] = Format::STANDARD; return self::toNumber($value, $options); } /** * Returns if a integer was found * * @param string $input Localized number string * @param array $options Options: locale. See {@link setOptions()} for details. * @return boolean Returns true if a integer was found */ public static function isInteger($value, array $options = array()) { if (!self::isNumber($value, $options)) { return false; } if (self::getInteger($value, $options) == self::getFloat($value, $options)) { return true; } return false; } /** * Converts a format string from PHP's date format to ISO format * Remember that Zend Date always returns localized string, so a month name which returns the english * month in php's date() will return the translated month name with this function... use 'en' as locale * if you are in need of the original english names * * The conversion has the following restrictions: * 'a', 'A' - Meridiem is not explicit upper/lowercase, you have to upper/lowercase the translated value yourself * * @param string $format Format string in PHP's date format * @return string Format string in ISO format */ public static function convertPhpToIsoFormat($format) { if ($format === null) { return null; } $convert = array('d' => 'dd' , 'D' => 'EE' , 'j' => 'd' , 'l' => 'EEEE', 'N' => 'eee' , 'S' => 'SS' , 'w' => 'e' , 'z' => 'D' , 'W' => 'ww' , 'F' => 'MMMM', 'm' => 'MM' , 'M' => 'MMM' , 'n' => 'M' , 't' => 'ddd' , 'L' => 'l' , 'o' => 'YYYY', 'Y' => 'yyyy', 'y' => 'yy' , 'a' => 'a' , 'A' => 'a' , 'B' => 'B' , 'g' => 'h' , 'G' => 'H' , 'h' => 'hh' , 'H' => 'HH' , 'i' => 'mm' , 's' => 'ss' , 'e' => 'zzzz', 'I' => 'I' , 'O' => 'Z' , 'P' => 'ZZZZ', 'T' => 'z' , 'Z' => 'X' , 'c' => 'yyyy-MM-ddTHH:mm:ssZZZZ', 'r' => 'r' , 'U' => 'U'); $values = str_split($format); foreach ($values as $key => $value) { if (isset($convert[$value]) === true) { $values[$key] = $convert[$value]; } } return join($values); } /** * Parse date and split in named array fields * * @param string $date Date string to parse * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format */ private static function _parseDate($date, $options) { if (!self::_getUniCodeSupport()) { trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE); } $options = self::_checkOptions($options) + self::$_options; $test = array('h', 'H', 'm', 's', 'y', 'Y', 'M', 'd', 'D', 'E', 'S', 'l', 'B', 'I', 'X', 'r', 'U', 'G', 'w', 'e', 'a', 'A', 'Z', 'z', 'v'); $format = $options['date_format']; $number = $date; // working copy $result['date_format'] = $format; // save the format used to normalize $number (convenience) $result['locale'] = $options['locale']; // save the locale used to normalize $number (convenience) $oenc = iconv_get_encoding('internal_encoding'); iconv_set_encoding('internal_encoding', 'UTF-8'); $day = iconv_strpos($format, 'd'); $month = iconv_strpos($format, 'M'); $year = iconv_strpos($format, 'y'); $hour = iconv_strpos($format, 'H'); $min = iconv_strpos($format, 'm'); $sec = iconv_strpos($format, 's'); $am = null; if ($hour === false) { $hour = iconv_strpos($format, 'h'); } if ($year === false) { $year = iconv_strpos($format, 'Y'); } if ($day === false) { $day = iconv_strpos($format, 'E'); if ($day === false) { $day = iconv_strpos($format, 'D'); } } if ($day !== false) { $parse[$day] = 'd'; if (!empty($options['locale']) && ($options['locale'] !== 'root') && (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) { // erase day string $daylist = Data\Data::getList($options['locale'], 'day'); foreach($daylist as $key => $name) { if (iconv_strpos($number, $name) !== false) { $number = str_replace($name, "EEEE", $number); break; } } } } $position = false; if ($month !== false) { $parse[$month] = 'M'; if (!empty($options['locale']) && ($options['locale'] !== 'root') && (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) { // prepare to convert month name to their numeric equivalents, if requested, // and we have a $options['locale'] $position = self::_replaceMonth($number, Data\Data::getList($options['locale'], 'month')); if ($position === false) { $position = self::_replaceMonth($number, Data\Data::getList($options['locale'], 'month', array('gregorian', 'format', 'abbreviated'))); } } } if ($year !== false) { $parse[$year] = 'y'; } if ($hour !== false) { $parse[$hour] = 'H'; } if ($min !== false) { $parse[$min] = 'm'; } if ($sec !== false) { $parse[$sec] = 's'; } if (empty($parse)) { iconv_set_encoding('internal_encoding', $oenc); require_once 'Zend/Locale/Exception.php'; throw new Exception("Unknown date format, neither date nor time in '" . $format . "' found"); } ksort($parse); // get daytime if (iconv_strpos($format, 'a') !== false) { if (iconv_strpos(strtoupper($number), strtoupper(Data\Data::getContent($options['locale'], 'am'))) !== false) { $am = true; } else if (iconv_strpos(strtoupper($number), strtoupper(Data\Data::getContent($options['locale'], 'pm'))) !== false) { $am = false; } } // split number parts $split = false; preg_match_all('/\d+/u', $number, $splitted); if (count($splitted[0]) == 0) { iconv_set_encoding('internal_encoding', $oenc); require_once 'Zend/Locale/Exception.php'; throw new Exception("No date part in '$date' found."); } if (count($splitted[0]) == 1) { $split = 0; } $cnt = 0; foreach($parse as $key => $value) { switch($value) { case 'd': if ($split === false) { if (count($splitted[0]) > $cnt) { $result['day'] = $splitted[0][$cnt]; } } else { $result['day'] = iconv_substr($splitted[0][0], $split, 2); $split += 2; } ++$cnt; break; case 'M': if ($split === false) { if (count($splitted[0]) > $cnt) { $result['month'] = $splitted[0][$cnt]; } } else { $result['month'] = iconv_substr($splitted[0][0], $split, 2); $split += 2; } ++$cnt; break; case 'y': $length = 2; if ((iconv_substr($format, $year, 4) == 'yyyy') || (iconv_substr($format, $year, 4) == 'YYYY')) { $length = 4; } if ($split === false) { if (count($splitted[0]) > $cnt) { $result['year'] = $splitted[0][$cnt]; } } else { $result['year'] = iconv_substr($splitted[0][0], $split, $length); $split += $length; } ++$cnt; break; case 'H': if ($split === false) { if (count($splitted[0]) > $cnt) { $result['hour'] = $splitted[0][$cnt]; } } else { $result['hour'] = iconv_substr($splitted[0][0], $split, 2); $split += 2; } ++$cnt; break; case 'm': if ($split === false) { if (count($splitted[0]) > $cnt) { $result['minute'] = $splitted[0][$cnt]; } } else { $result['minute'] = iconv_substr($splitted[0][0], $split, 2); $split += 2; } ++$cnt; break; case 's': if ($split === false) { if (count($splitted[0]) > $cnt) { $result['second'] = $splitted[0][$cnt]; } } else { $result['second'] = iconv_substr($splitted[0][0], $split, 2); $split += 2; } ++$cnt; break; } } // AM/PM correction if ($hour !== false) { if (($am === true) and ($result['hour'] == 12)){ $result['hour'] = 0; } else if (($am === false) and ($result['hour'] != 12)) { $result['hour'] += 12; } } if ($options['fix_date'] === true) { $result['fixed'] = 0; // nothing has been "fixed" by swapping date parts around (yet) } if ($day !== false) { // fix false month if (isset($result['day']) and isset($result['month'])) { if (($position !== false) and ((iconv_strpos($date, $result['day']) === false) or (isset($result['year']) and (iconv_strpos($date, $result['year']) === false)))) { if ($options['fix_date'] !== true) { iconv_set_encoding('internal_encoding', $oenc); require_once 'Zend/Locale/Exception.php'; throw new Exception("Unable to parse date '$date' using '" . $format . "' (false month, $position, $month)"); } $temp = $result['day']; $result['day'] = $result['month']; $result['month'] = $temp; $result['fixed'] = 1; } } // fix switched values d <> y if (isset($result['day']) and isset($result['year'])) { if ($result['day'] > 31) { if ($options['fix_date'] !== true) { iconv_set_encoding('internal_encoding', $oenc); require_once 'Zend/Locale/Exception.php'; throw new Exception("Unable to parse date '$date' using '" . $format . "' (d <> y)"); } $temp = $result['year']; $result['year'] = $result['day']; $result['day'] = $temp; $result['fixed'] = 2; } } // fix switched values M <> y if (isset($result['month']) and isset($result['year'])) { if ($result['month'] > 31) { if ($options['fix_date'] !== true) { iconv_set_encoding('internal_encoding', $oenc); require_once 'Zend/Locale/Exception.php'; throw new Exception("Unable to parse date '$date' using '" . $format . "' (M <> y)"); } $temp = $result['year']; $result['year'] = $result['month']; $result['month'] = $temp; $result['fixed'] = 3; } } // fix switched values M <> d if (isset($result['month']) and isset($result['day'])) { if ($result['month'] > 12) { if ($options['fix_date'] !== true || $result['month'] > 31) { iconv_set_encoding('internal_encoding', $oenc); require_once 'Zend/Locale/Exception.php'; throw new Exception("Unable to parse date '$date' using '" . $format . "' (M <> d)"); } $temp = $result['day']; $result['day'] = $result['month']; $result['month'] = $temp; $result['fixed'] = 4; } } } if (isset($result['year'])) { if (((iconv_strlen($result['year']) == 2) && ($result['year'] < 10)) || (((iconv_strpos($format, 'yy') !== false) && (iconv_strpos($format, 'yyyy') === false)) || ((iconv_strpos($format, 'YY') !== false) && (iconv_strpos($format, 'YYYY') === false)))) { if (($result['year'] >= 0) && ($result['year'] < 100)) { if ($result['year'] < 70) { $result['year'] = (int) $result['year'] + 100; } $result['year'] = (int) $result['year'] + 1900; } } } iconv_set_encoding('internal_encoding', $oenc); return $result; } /** * Search $number for a month name found in $monthlist, and replace if found. * * @param string $number Date string (modified) * @param array $monthlist List of month names * * @return int|false Position of replaced string (false if nothing replaced) */ protected static function _replaceMonth(&$number, $monthlist) { // If $locale was invalid, $monthlist will default to a "root" identity // mapping for each month number from 1 to 12. // If no $locale was given, or $locale was invalid, do not use this identity mapping to normalize. // Otherwise, translate locale aware month names in $number to their numeric equivalents. $position = false; if ($monthlist && $monthlist[1] != 1) { foreach($monthlist as $key => $name) { if (($position = iconv_strpos($number, $name, 0, 'UTF-8')) !== false) { $number = str_ireplace($name, $key, $number); return $position; } } } return false; } /** * Returns the default date format for $locale. * * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT') * @return string format * @throws Zend_Locale_Exception throws an exception when locale data is broken */ public static function getDateFormat($locale = null) { $format = Data\Data::getContent($locale, 'date'); if (empty($format)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("failed to receive data from locale $locale"); } return $format; } /** * Returns an array with the normalized date from an locale date * a input of 10.01.2006 without a $locale would return: * array ('day' => 10, 'month' => 1, 'year' => 2006) * The 'locale' option is only used to convert human readable day * and month names to their numeric equivalents. * The 'format' option allows specification of self-defined date formats, * when not using the default format for the 'locale'. * * @param string $date Date string * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format */ public static function getDate($date, array $options = array()) { $options = self::_checkOptions($options) + self::$_options; if (empty($options['date_format'])) { $options['format_type'] = 'iso'; $options['date_format'] = self::getDateFormat($options['locale']); } return self::_parseDate($date, $options); } /** * Returns if the given datestring contains all date parts from the given format. * If no format is given, the default date format from the locale is used * If you want to check if the date is a proper date you should use Zend_Date::isDate() * * @param string $date Date string * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details. * @return boolean */ public static function checkDateFormat($date, array $options = array()) { try { $date = self::getDate($date, $options); } catch (\Exception $e) { return false; } if (empty($options['date_format'])) { $options['format_type'] = 'iso'; $options['date_format'] = self::getDateFormat($options['locale']); } $options = self::_checkOptions($options) + self::$_options; // day expected but not parsed if ((iconv_strpos($options['date_format'], 'd', 0, 'UTF-8') !== false) and (!isset($date['day']) or ($date['day'] === ""))) { return false; } // month expected but not parsed if ((iconv_strpos($options['date_format'], 'M', 0, 'UTF-8') !== false) and (!isset($date['month']) or ($date['month'] === ""))) { return false; } // year expected but not parsed if (((iconv_strpos($options['date_format'], 'Y', 0, 'UTF-8') !== false) or (iconv_strpos($options['date_format'], 'y', 0, 'UTF-8') !== false)) and (!isset($date['year']) or ($date['year'] === ""))) { return false; } // second expected but not parsed if ((iconv_strpos($options['date_format'], 's', 0, 'UTF-8') !== false) and (!isset($date['second']) or ($date['second'] === ""))) { return false; } // minute expected but not parsed if ((iconv_strpos($options['date_format'], 'm', 0, 'UTF-8') !== false) and (!isset($date['minute']) or ($date['minute'] === ""))) { return false; } // hour expected but not parsed if (((iconv_strpos($options['date_format'], 'H', 0, 'UTF-8') !== false) or (iconv_strpos($options['date_format'], 'h', 0, 'UTF-8') !== false)) and (!isset($date['hour']) or ($date['hour'] === ""))) { return false; } return true; } /** * Returns the default time format for $locale. * * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT') * @return string format */ public static function getTimeFormat($locale = null) { $format = Data\Data::getContent($locale, 'time'); if (empty($format)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("failed to receive data from locale $locale"); } return $format; } /** * Returns an array with 'hour', 'minute', and 'second' elements extracted from $time * according to the order described in $format. For a format of 'H:m:s', and * an input of 11:20:55, getTime() would return: * array ('hour' => 11, 'minute' => 20, 'second' => 55) * The optional $locale parameter may be used to help extract times from strings * containing both a time and a day or month name. * * @param string $time Time string * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format */ public static function getTime($time, array $options = array()) { $options = self::_checkOptions($options) + self::$_options; if (empty($options['date_format'])) { $options['format_type'] = 'iso'; $options['date_format'] = self::getTimeFormat($options['locale']); } return self::_parseDate($time, $options); } /** * Returns the default datetime format for $locale. * * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT') * @return string format */ public static function getDateTimeFormat($locale = null) { $format = Data\Data::getContent($locale, 'datetime'); if (empty($format)) { require_once 'Zend/Locale/Exception.php'; throw new Exception("failed to receive data from locale $locale"); } return $format; } /** * Returns an array with 'year', 'month', 'day', 'hour', 'minute', and 'second' elements * extracted from $datetime according to the order described in $format. For a format of 'd.M.y H:m:s', * and an input of 10.05.1985 11:20:55, getDateTime() would return: * array ('year' => 1985, 'month' => 5, 'day' => 10, 'hour' => 11, 'minute' => 20, 'second' => 55) * The optional $locale parameter may be used to help extract times from strings * containing both a time and a day or month name. * * @param string $datetime DateTime string * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format */ public static function getDateTime($datetime, array $options = array()) { $options = self::_checkOptions($options) + self::$_options; if (empty($options['date_format'])) { $options['format_type'] = 'iso'; $options['date_format'] = self::getDateTimeFormat($options['locale']); } return self::_parseDate($datetime, $options); } /** * Internal method to detect of Unicode supports UTF8 * which should be enabled within vanilla php installations * * @return boolean */ protected static function _getUniCodeSupport() { return (@preg_match('/\pL/u', 'a')) ? true : false; } }
{ "content_hash": "b9ae10018af6b7d20e26c7abee012fe2", "timestamp": "", "source": "github", "line_count": 1251, "max_line_length": 167, "avg_line_length": 41.81774580335731, "alnum_prop": 0.4645983866651374, "repo_name": "FbN/Zend-Framework-Namespaced-", "id": "8f88715c573546db7cbed49690408115635cdbe8", "size": "53081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Zend/Locale/Format.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "14877183" } ], "symlink_target": "" }
/* @LICENSE(MUSLC_MIT) */ #include <limits.h> #include <fenv.h> #include "libm.h" /* If the result cannot be represented (overflow, nan), then lrint raises the invalid exception. Otherwise if the input was not an integer then the inexact exception is raised. C99 is a bit vague about whether inexact exception is allowed to be raised when invalid is raised. (F.9 explicitly allows spurious inexact exceptions, F.9.6.5 does not make it clear if that rule applies to lrint, but IEEE 754r 7.8 seems to forbid spurious inexact exception in the ineger conversion functions) So we try to make sure that no spurious inexact exception is raised in case of an overflow. If the bit size of long > precision of double, then there cannot be inexact rounding in case the result overflows, otherwise LONG_MAX and LONG_MIN can be represented exactly as a double. */ #if LONG_MAX < 1U<<53 && defined(FE_INEXACT) long lrint(double x) { int e; e = fetestexcept(FE_INEXACT); x = rint(x); if (!e && (x > LONG_MAX || x < LONG_MIN)) feclearexcept(FE_INEXACT); /* conversion */ return x; } #else long lrint(double x) { return rint(x); } #endif
{ "content_hash": "57325ba2aa1a1339346a599ce3329b0d", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 60, "avg_line_length": 24.21276595744681, "alnum_prop": 0.7337434094903339, "repo_name": "gapry/refos", "id": "2878485fd5f215caf9e9a8220a0a92477115ba62", "size": "1138", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libs/libmuslc/src/math/lrint.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "120890" }, { "name": "Awk", "bytes": "5573" }, { "name": "Brainfuck", "bytes": "2225" }, { "name": "C", "bytes": "11472698" }, { "name": "C++", "bytes": "331648" }, { "name": "CSS", "bytes": "114" }, { "name": "Groff", "bytes": "159607" }, { "name": "HyPhy", "bytes": "28604" }, { "name": "Makefile", "bytes": "147788" }, { "name": "Objective-C", "bytes": "1437" }, { "name": "Python", "bytes": "354004" }, { "name": "Shell", "bytes": "18699" }, { "name": "SourcePawn", "bytes": "757" }, { "name": "TeX", "bytes": "397786" }, { "name": "VimL", "bytes": "765" } ], "symlink_target": "" }
<a href="http://github.com/angular/angular.js/tree/v1.2.10/src/ng/sce.js#L92" class="view-source btn btn-action"><i class="icon-zoom-in"> </i> View source</a><a href="http://github.com/angular/angular.js/edit/master/src/ng/sce.js" class="improve-docs btn btn-primary"><i class="icon-edit"> </i> Improve this doc</a><h1><code ng:non-bindable="">$sceDelegateProvider</code> <div><span class="hint">service in module <code ng:non-bindable="">ng</code> </span> </div> </h1> <div><h2 id="description">Description</h2> <div class="description"><div class="ng-scedelegateprovider-page"><p>The <code>$sceDelegateProvider</code> provider allows developers to configure the <a href="api/ng.$sceDelegate"><code>$sceDelegate</code></a> service. This allows one to get/set the whitelists and blacklists used to ensure that the URLs used for sourcing Angular templates are safe. Refer <a href="api/ng.$sceDelegateProvider#methods_resourceurlwhitelist"><code>$sceDelegateProvider.resourceUrlWhitelist</code></a> and <a href="api/ng.$sceDelegateProvider#methods_resourceurlblacklist"><code>$sceDelegateProvider.resourceUrlBlacklist</code></a></p> <p>For the general details about this service in Angular, read the main page for <a href="api/ng.$sce"><code>Strict Contextual Escaping (SCE)</code></a>.</p> <p><strong>Example</strong>: Consider the following case. <a name="example"></a></p> <ul> <li>your app is hosted at url <code>http://myapp.example.com/</code></li> <li>but some of your templates are hosted on other domains you control such as <code>http://srv01.assets.example.com/</code>, <code>http://srv02.assets.example.com/</code>, etc.</li> <li>and you have an open redirect at <code>http://myapp.example.com/clickThru?...</code>.</li> </ul> <p>Here is what a secure configuration for this scenario might look like:</p> <pre class="prettyprint" class="prettyprint linenums"> angular.module('myApp', []).config(function($sceDelegateProvider) { $sceDelegateProvider.resourceUrlWhitelist([ // Allow same origin resource loads. 'self', // Allow loading from our assets domain. Notice the difference between * and **. 'http://srv*.assets.example.com/**']); // The blacklist overrides the whitelist so the open redirect here is blocked. $sceDelegateProvider.resourceUrlBlacklist([ 'http://myapp.example.com/clickThru**']); }); </pre> </div></div> <div class="member method"><h2 id="methods">Methods</h2> <ul class="methods"><li><h3 id="methods_resourceurlblacklist">resourceUrlBlacklist(blacklist)</h3> <div class="resourceurlblacklist"><div class="ng-scedelegateprovider-resourceurlblacklist-page"><p>Sets/Gets the blacklist of trusted resource URLs.</p> </div><h5 id="methods_resourceurlblacklist_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>blacklist <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-array">Array</a></td><td><div class="ng-scedelegateprovider-resourceurlblacklist-page"><p>When provided, replaces the resourceUrlBlacklist with the value provided. This must be an array or null. A snapshot of this array is used so further changes to the array are ignored.</p> <p>Follow <a href="api/ng.$sce#resourceurlpatternitem"><code>this link</code></a> for a description of the items allowed in this array.</p> <p>The typical usage for the blacklist is to <strong>block <a href="http://cwe.mitre.org/data/definitions/601.html">open redirects</a></strong> served by your domain as these would otherwise be trusted but actually return content from the redirected domain.</p> <p>Finally, <strong>the blacklist overrides the whitelist</strong> and has the final say.</p> </div></td></tr></tbody></table><h5 id="methods_resourceurlblacklist_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-array">Array</a></td><td><div class="ng-scedelegateprovider-resourceurlblacklist-page"><p>the currently set blacklist array.</p> <p>The <strong>default value</strong> when no whitelist has been explicitly set is the empty array (i.e. there is no blacklist.)</p> </div></td></tr></table></div> </li> <li><h3 id="methods_resourceurlwhitelist">resourceUrlWhitelist(whitelist)</h3> <div class="resourceurlwhitelist"><div class="ng-scedelegateprovider-resourceurlwhitelist-page"><p>Sets/Gets the whitelist of trusted resource URLs.</p> </div><h5 id="methods_resourceurlwhitelist_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>whitelist <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-array">Array</a></td><td><div class="ng-scedelegateprovider-resourceurlwhitelist-page"><p>When provided, replaces the resourceUrlWhitelist with the value provided. This must be an array or null. A snapshot of this array is used so further changes to the array are ignored.</p> <p>Follow <a href="api/ng.$sce#resourceurlpatternitem"><code>this link</code></a> for a description of the items allowed in this array.</p> <p>Note: <strong>an empty whitelist array will block all URLs</strong>!</p> </div></td></tr></tbody></table><h5 id="methods_resourceurlwhitelist_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-array">Array</a></td><td><div class="ng-scedelegateprovider-resourceurlwhitelist-page"><p>the currently set whitelist array.</p> <p>The <strong>default value</strong> when no whitelist has been explicitly set is <code>[&#39;self&#39;]</code> allowing only same origin resource requests.</p> </div></td></tr></table></div> </li> </ul> </div> </div>
{ "content_hash": "dee33825ae8776852106c170295d440c", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 465, "avg_line_length": 89.6923076923077, "alnum_prop": 0.7349914236706689, "repo_name": "leika/AD_AggregatedDashboards_Sample", "id": "4a77762cc8968d1210dbee80db544109a96d3ec9", "size": "5830", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "assets/angular/docs/partials/api/ng.$sceDelegateProvider.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "14732" }, { "name": "JavaScript", "bytes": "1139" }, { "name": "Shell", "bytes": "779" } ], "symlink_target": "" }
A valid language code is specified by a valid **ISO 639-2 language code**, optionally followed by a valid **ISO 3166-1 alpha-2 country code**, such as `fr` or `en-US`. To start you need to specify the languages supported by your application in the `conf/application.conf` file: ``` application.langs="en,en-US,fr" ``` ## Externalizing messages You can externalize messages in the `conf/messages.xxx` files. The default `conf/messages` file matches all languages. Additionally you can specify language-specific message files such as `conf/messages.fr` or `conf/messages.en-US`. You can then retrieve messages using the `play.api.i18n.Messages` object: ```scala val title = Messages("home.title") ``` All internationalization API calls take an implicit `play.api.i18.Lang` argument retrieved from the current scope. You can also specify it explicitly: ```scala val title = Messages("home.title")(Lang("fr")) ``` > **Note:** If you have an implicit `Request` in the scope, it will provide an implicit `Lang` value corresponding to the preferred language extracted from the `Accept-Language` header and matching one of the application supported languages. You should add a `Lang` implicit parameter to your template like this: `@()(implicit lang: Lang)`. ## Messages format Messages can be formatted using the `java.text.MessageFormat` library. For example, assuming you have message defined like: ``` files.summary=The disk {1} contains {0} file(s). ``` You can then specify parameters as: ```scala Messages("files.summary", d.files.length, d.name) ``` ## Retrieving supported language from an HTTP request You can retrieve the languages supported by a specific HTTP request: ```scala def index = Action { request => Ok("Languages: " + request.acceptLanguages.map(_.code).mkString(", ")) } ``` > **Next:** [[The application Global object | ScalaGlobal]]
{ "content_hash": "242f679131c595c305b4401da0ec8778", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 340, "avg_line_length": 35.301886792452834, "alnum_prop": 0.7423837520042758, "repo_name": "noel-yap/setter-for-catan", "id": "90d132bdb2f64908462e6b76087734006a459c8c", "size": "1963", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "play-2.1.1/documentation/manual/scalaGuide/main/i18n/ScalaI18N.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "6386" }, { "name": "Java", "bytes": "463689" }, { "name": "JavaScript", "bytes": "841409" }, { "name": "Scala", "bytes": "1510018" }, { "name": "Shell", "bytes": "7220" } ], "symlink_target": "" }
#include <Base.h> #include <Library/DebugLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Protocol/ArmScmiBaseProtocol.h> #include <Protocol/ArmScmiClockProtocol.h> #include <Protocol/ArmScmiPerformanceProtocol.h> #include "ArmScmiBaseProtocolPrivate.h" #include "ArmScmiClockProtocolPrivate.h" #include "ArmScmiPerformanceProtocolPrivate.h" #include "ScmiDxe.h" #include "ScmiPrivate.h" STATIC CONST SCMI_PROTOCOL_ENTRY Protocols[] = { { SCMI_PROTOCOL_ID_BASE, ScmiBaseProtocolInit }, { SCMI_PROTOCOL_ID_PERFORMANCE, ScmiPerformanceProtocolInit }, { SCMI_PROTOCOL_ID_CLOCK, ScmiClockProtocolInit } }; /** ARM SCMI driver entry point function. This function installs the SCMI Base protocol and a list of other protocols is queried using the Base protocol. If protocol is supported, driver will call each protocol init function to install the protocol on the ImageHandle. @param[in] ImageHandle Handle to this EFI Image which will be used to install Base, Clock and Performance protocols. @param[in] SystemTable A pointer to boot time system table. @retval EFI_SUCCESS Driver initalized successfully. @retval EFI_UNSUPPORTED If SCMI base protocol version is not supported. @retval !(EFI_SUCCESS) Other errors. **/ EFI_STATUS EFIAPI ArmScmiDxeEntryPoint ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; SCMI_BASE_PROTOCOL *BaseProtocol; UINT32 Version; UINT32 Index; UINT32 NumProtocols; UINT32 ProtocolIndex; UINT8 *SupportedList; UINT32 SupportedListSize; // Every SCMI implementation must implement the base protocol. ASSERT (Protocols[0].Id == SCMI_PROTOCOL_ID_BASE); Status = ScmiBaseProtocolInit (&ImageHandle); if (EFI_ERROR (Status)) { ASSERT (FALSE); return Status; } Status = gBS->LocateProtocol ( &gArmScmiBaseProtocolGuid, NULL, (VOID**)&BaseProtocol ); if (EFI_ERROR (Status)) { ASSERT (FALSE); return Status; } // Get SCMI Base protocol version. Status = BaseProtocol->GetVersion (BaseProtocol, &Version); if (EFI_ERROR (Status)) { ASSERT (FALSE); return Status; } if (Version != BASE_PROTOCOL_VERSION) { ASSERT (FALSE); return EFI_UNSUPPORTED; } // Apart from Base protocol, SCMI may implement various other protocols, // query total protocols implemented by the SCP firmware. NumProtocols = 0; Status = BaseProtocol->GetTotalProtocols (BaseProtocol, &NumProtocols); if (EFI_ERROR (Status)) { ASSERT (FALSE); return Status; } ASSERT (NumProtocols != 0); SupportedListSize = (NumProtocols * sizeof (*SupportedList)); Status = gBS->AllocatePool ( EfiBootServicesData, SupportedListSize, (VOID**)&SupportedList ); if (EFI_ERROR (Status)) { ASSERT (FALSE); return Status; } // Get the list of protocols supported by SCP firmware on the platform. Status = BaseProtocol->DiscoverListProtocols ( BaseProtocol, &SupportedListSize, SupportedList ); if (EFI_ERROR (Status)) { gBS->FreePool (SupportedList); ASSERT (FALSE); return Status; } // Install supported protocol on ImageHandle. for (ProtocolIndex = 1; ProtocolIndex < ARRAY_SIZE (Protocols); ProtocolIndex++) { for (Index = 0; Index < NumProtocols; Index++) { if (Protocols[ProtocolIndex].Id == SupportedList[Index]) { Status = Protocols[ProtocolIndex].InitFn (&ImageHandle); if (EFI_ERROR (Status)) { ASSERT_EFI_ERROR (Status); return Status; } break; } } } gBS->FreePool (SupportedList); return EFI_SUCCESS; }
{ "content_hash": "98fa3eec853b1794a9eef846f3c2174b", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 75, "avg_line_length": 30.31159420289855, "alnum_prop": 0.6206072196987807, "repo_name": "MattDevo/edk2", "id": "0400799b5c521dcfa2ce866b0ffd48530e8cf0d1", "size": "4859", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ArmPkg/Drivers/ArmScmiDxe/ScmiDxe.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "4545237" }, { "name": "Batchfile", "bytes": "93042" }, { "name": "C", "bytes": "94289702" }, { "name": "C++", "bytes": "20170310" }, { "name": "CSS", "bytes": "1905" }, { "name": "DIGITAL Command Language", "bytes": "13695" }, { "name": "GAP", "bytes": "698245" }, { "name": "GDB", "bytes": "96" }, { "name": "HTML", "bytes": "472114" }, { "name": "Lua", "bytes": "249" }, { "name": "Makefile", "bytes": "231845" }, { "name": "NSIS", "bytes": "2229" }, { "name": "Objective-C", "bytes": "4147834" }, { "name": "PHP", "bytes": "674" }, { "name": "PLSQL", "bytes": "24782" }, { "name": "Perl", "bytes": "6218" }, { "name": "Python", "bytes": "27130096" }, { "name": "R", "bytes": "21094" }, { "name": "Roff", "bytes": "28192" }, { "name": "Shell", "bytes": "104362" }, { "name": "SourcePawn", "bytes": "29427" }, { "name": "Visual Basic", "bytes": "494" } ], "symlink_target": "" }
package com.github.mauricio.async.db.util import org.specs2.mutable.Specification import io.netty.util.CharsetUtil import io.netty.buffer.Unpooled class ChannelUtilsSpec extends Specification { val charset = CharsetUtil.UTF_8 "utils" should { "correctly write and read a string" in { val content = "some text" val buffer = Unpooled.buffer() ByteBufferUtils.writeCString(content, buffer, charset) ByteBufferUtils.readCString(buffer, charset) === content buffer.readableBytes() === 0 } "correctly read the buggy MySQL EOF string when there is an EOF" in { val content = "some text" val buffer = Unpooled.buffer() ByteBufferUtils.writeCString(content, buffer, charset) ByteBufferUtils.readUntilEOF(buffer, charset) === content buffer.readableBytes() === 0 } "correctly read the buggy MySQL EOF string when there is no EOF" in { val content = "some text" val buffer = Unpooled.buffer() buffer.writeBytes(content.getBytes(charset)) ByteBufferUtils.readUntilEOF(buffer, charset) === content buffer.readableBytes() === 0 } } }
{ "content_hash": "24018b1357e087bcc0071e6b5585a22b", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 73, "avg_line_length": 23.714285714285715, "alnum_prop": 0.6824440619621343, "repo_name": "dripower/postgresql-async", "id": "cd0c85e3a5041e049984b5e95b37398922ec141a", "size": "1798", "binary": false, "copies": "1", "ref": "refs/heads/0.3.x", "path": "db-async-common/src/test/scala/com/github/mauricio/async/db/util/ChannelUtilsSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2373" }, { "name": "Scala", "bytes": "641302" }, { "name": "Shell", "bytes": "2808" } ], "symlink_target": "" }
* gulp task watches TypeScript file changes. * gulp tasks sends http request, including all changed file paths, to hotreload server * hotreload sends websocket request to browser, including all changed file paths. * System.update(changedPaths) will be called to hotreload the code in the browser without reloading the page * In v1 Just add a new tag to the head and rely on browser f12 to reload javascript
{ "content_hash": "f10d848d5e9abd462f5e660e1eccdc2d", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 108, "avg_line_length": 81.2, "alnum_prop": 0.8029556650246306, "repo_name": "roelvanlisdonk/dev", "id": "4ec7275e136f513e760cb7fd6f63483ed9be3b09", "size": "427", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apps/sportersonline/www/libraries/am/docs/hot.reload.in.dev.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "11453" }, { "name": "CSS", "bytes": "2343" }, { "name": "HTML", "bytes": "30129" }, { "name": "JavaScript", "bytes": "12985" }, { "name": "PowerShell", "bytes": "4175" }, { "name": "TypeScript", "bytes": "221442" } ], "symlink_target": "" }
# http://pear.php.net/manual/en/guide.users.commandline.channels.php require 'chef/mixin/shell_out' require 'chef/mixin/language' include Chef::Mixin::ShellOut def whyrun_supported? true end action :discover do unless exists? Chef::Log.info("Discovering pear channel #{@new_resource}") execute "pear channel-discover #{@new_resource.channel_name}" do action :run end end end action :add do unless exists? Chef::Log.info("Adding pear channel #{@new_resource} from #{@new_resource.channel_xml}") execute "pear channel-add #{@new_resource.channel_xml}" do action :run end end end action :update do if exists? update_needed = false begin updated_needed = true if shell_out("pear search -c #{@new_resource.channel_name} NNNNNN").stdout =~ /channel-update/ rescue Chef::Exceptions::CommandTimeout # CentOS can hang on 'pear search' if a channel needs updating Chef::Log.info("Timed out checking if channel-update needed...forcing update of pear channel #{@new_resource}") update_needed = true end if update_needed description = "update pear channel #{@new_resource}" converge_by(description) do Chef::Log.info("Updating pear channel #{@new_resource}") shell_out!("pear channel-update #{@new_resource.channel_name}") end end end end action :remove do if exists? Chef::Log.info("Deleting pear channel #{@new_resource}") execute "pear channel-delete #{@new_resource.channel_name}" do action :run end end end def load_current_resource @current_resource = Chef::Resource::PhpPearChannel.new(@new_resource.name) @current_resource.channel_name(@new_resource.channel_name) @current_resource end private def exists? begin shell_out!("pear channel-info #{@current_resource.channel_name}") true rescue Chef::Exceptions::ShellCommandFailed rescue Mixlib::ShellOut::ShellCommandFailed false end end
{ "content_hash": "cfb31a1b7eff5aa43b0e31d8bc569475", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 122, "avg_line_length": 27.635135135135137, "alnum_prop": 0.6689486552567238, "repo_name": "williamCardenas/Ite_teste_PHP", "id": "78a96ea7611f577e8838ec41edfd4def4633b41a", "size": "2766", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vagrant-testephp/cookbooks/site/php/providers/pear_channel.rb", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "22893" }, { "name": "PHP", "bytes": "88522" }, { "name": "Perl", "bytes": "8849" }, { "name": "Ruby", "bytes": "321578" }, { "name": "Shell", "bytes": "2782" } ], "symlink_target": "" }
package graph_test import ( "github.com/chrisbbe/GoAnalysis/analyzer/linter/ccomplexity/graph" "testing" ) // Letter is the type to store in the graph. type Letter struct { letter string } // Satisfies the Value interface. func (l Letter) UID() string { return l.letter } // Letter must satisfies the Value interface in graph. func (l Letter) String() string { return l.letter } func sccExists(correctSCCList, actualSCCList []*graph.StronglyConnectedComponent) bool { existCounter := 0 for _, correctScc := range correctSCCList { for _, actualScc := range actualSCCList { if existInList(correctScc.Nodes, actualScc.Nodes) { existCounter++ } } } return existCounter == len(correctSCCList) } // Compare two lists. func existInList(elementList, list []*graph.Node) bool { existCounter := 0 for _, e := range elementList { for _, r := range list { if e.Value == r.Value { existCounter++ } } } return existCounter == len(elementList) } func TestDirectedGraph(test *testing.T) { //Create some nodes. a := graph.Node{Value: Letter{"A"}} b := graph.Node{Value: Letter{"B"}} c := graph.Node{Value: Letter{"C"}} d := graph.Node{Value: Letter{"D"}} e := graph.Node{Value: Letter{"E"}} f := graph.Node{Value: Letter{"F"}} g := graph.Node{Value: Letter{"G"}} h := graph.Node{Value: Letter{"H"}} graph := graph.NewGraph() //Add directed node-pairs to graph. graph.InsertEdge(&a, &b) graph.InsertEdge(&a, &d) graph.InsertEdge(&b, &d) graph.InsertEdge(&b, &c) graph.InsertEdge(&c, &e) graph.InsertEdge(&e, &g) graph.InsertEdge(&e, &f) graph.InsertEdge(&f, &h) //Test number of nodes in graph. if graph.GetNumberOfNodes() != 8 { test.Fatalf("Graph should contain 8 nodes, not %d!\n", graph.GetNumberOfNodes()) } //Node A should be root node. if graph.Root.Value != a.Value { test.Errorf("Node A should be root node, not node %v\n", graph.Root.Value) } //Test node A. if a.GetInDegree() != 0 { test.Errorf("Node A in-degree should be 0, not %d\n", a.GetInDegree()) } if a.GetOutDegree() != 2 { test.Errorf("Node A out-degree should be 2, not %d\n", a.GetInDegree()) } //Test node B. if b.GetInDegree() != 1 { test.Errorf("Node A in-degree should be 1, not %d\n", b.GetInDegree()) } if b.GetOutDegree() != 2 { test.Errorf("Node A out-degree should be 2, not %d\n", b.GetInDegree()) } //Test node C. if c.GetInDegree() != 1 { test.Errorf("Node A in-degree should be 1, not %d\n", c.GetInDegree()) } if c.GetOutDegree() != 1 { test.Errorf("Node A out-degree should be 1, not %d\n", c.GetInDegree()) } //Test node D. if d.GetInDegree() != 2 { test.Errorf("Node A in-degree should be 2, not %d\n", d.GetInDegree()) } if d.GetOutDegree() != 0 { test.Errorf("Node A out-degree should be 0, not %d\n", d.GetInDegree()) } //Test node E. if e.GetInDegree() != 1 { test.Errorf("Node A in-degree should be 1, not %d\n", e.GetInDegree()) } if e.GetOutDegree() != 2 { test.Errorf("Node A out-degree should be 2, not %d\n", e.GetInDegree()) } //Test node F. if f.GetInDegree() != 1 { test.Errorf("Node A in-degree should be 1, not %d\n", f.GetInDegree()) } if f.GetOutDegree() != 1 { test.Errorf("Node A out-degree should be 1, not %d\n", f.GetInDegree()) } //Test node G. if g.GetInDegree() != 1 { test.Errorf("Node A in-degree should be 1, not %d\n", g.GetInDegree()) } if g.GetOutDegree() != 0 { test.Errorf("Node A out-degree should be 0, not %d\n", g.GetInDegree()) } //Test node H. if h.GetInDegree() != 1 { test.Errorf("Node A in-degree should be 1, not %d\n", h.GetInDegree()) } if h.GetOutDegree() != 0 { test.Errorf("Node A out-degree should be 0, not %d\n", h.GetInDegree()) } } func TestDepthFirstSearchInGraph(t *testing.T) { //Create some nodes. a := graph.Node{Value: Letter{"A"}} b := graph.Node{Value: Letter{"B"}} c := graph.Node{Value: Letter{"C"}} d := graph.Node{Value: Letter{"D"}} e := graph.Node{Value: Letter{"E"}} f := graph.Node{Value: Letter{"F"}} g := graph.Node{Value: Letter{"G"}} h := graph.Node{Value: Letter{"H"}} graph := graph.NewGraph() //Add directed node-pairs to graph. graph.InsertEdge(&a, &b) graph.InsertEdge(&a, &d) graph.InsertEdge(&b, &d) graph.InsertEdge(&b, &c) graph.InsertEdge(&c, &e) graph.InsertEdge(&e, &g) graph.InsertEdge(&e, &f) graph.InsertEdge(&f, &h) expectedDepthFirstSearch := graph.GetDFS() correctDfs := []Letter{{"A"}, {"B"}, {"D"}, {"C"}, {"E"}, {"G"}, {"F"}, {"H"}} //Equal length. if len(correctDfs) != len(expectedDepthFirstSearch) { t.Errorf("Length of DFS (%d) is not equal length of correct DFS (%d)!\n", len(expectedDepthFirstSearch), len(correctDfs)) } //Check nodes in depth first search. for index, node := range expectedDepthFirstSearch { if node.String() != correctDfs[index].String() { t.Error("Faen i helvete") } } } func TestDepthFirstSearchInCycleGraph(t *testing.T) { //Create some nodes. a := graph.Node{Value: Letter{"A"}} b := graph.Node{Value: Letter{"B"}} c := graph.Node{Value: Letter{"C"}} d := graph.Node{Value: Letter{"D"}} e := graph.Node{Value: Letter{"E"}} f := graph.Node{Value: Letter{"F"}} g := graph.Node{Value: Letter{"G"}} directGraph := graph.NewGraph() directGraph.InsertEdge(&a, &b) directGraph.InsertEdge(&a, &c) directGraph.InsertEdge(&a, &e) directGraph.InsertEdge(&b, &d) directGraph.InsertEdge(&b, &f) directGraph.InsertEdge(&c, &g) directGraph.InsertEdge(&f, &e) expectedDepthFirstSearch := directGraph.GetDFS() correctDepthFirstSearch := []Letter{ {"A"}, {"B"}, {"D"}, {"F"}, {"E"}, {"C"}, {"G"}, } //Compare DFS with correct DFS. for index := 0; index < len(expectedDepthFirstSearch); index++ { if expectedDepthFirstSearch[index].Value.String() != correctDepthFirstSearch[index].letter { t.Errorf("Element nr. %d in DFS should be %s, not %s\n", index, correctDepthFirstSearch[index].letter, expectedDepthFirstSearch[index].Value.String()) } } } func TestStronglyConnectedComponentsInGraph(t *testing.T) { directedGraph := graph.NewGraph() a := graph.Node{Value: Letter{"A"}} b := graph.Node{Value: Letter{"B"}} c := graph.Node{Value: Letter{"C"}} d := graph.Node{Value: Letter{"D"}} e := graph.Node{Value: Letter{"E"}} f := graph.Node{Value: Letter{"F"}} g := graph.Node{Value: Letter{"G"}} h := graph.Node{Value: Letter{"H"}} directedGraph.InsertEdge(&a, &b) directedGraph.InsertEdge(&b, &c) directedGraph.InsertEdge(&c, &d) directedGraph.InsertEdge(&d, &c) directedGraph.InsertEdge(&d, &h) directedGraph.InsertEdge(&h, &d) directedGraph.InsertEdge(&c, &g) directedGraph.InsertEdge(&h, &g) directedGraph.InsertEdge(&f, &g) directedGraph.InsertEdge(&g, &f) directedGraph.InsertEdge(&b, &f) directedGraph.InsertEdge(&e, &f) directedGraph.InsertEdge(&e, &a) directedGraph.InsertEdge(&b, &e) expectedStronglyConnectedComponents := directedGraph.GetSCComponents() correctStronglyConnectedComponents := []*graph.StronglyConnectedComponent{ { Nodes: []*graph.Node{ {Value: Letter{"F"}}, {Value: Letter{"G"}}, }}, { Nodes: []*graph.Node{ {Value: Letter{"H"}}, {Value: Letter{"C"}}, {Value: Letter{"D"}}, }}, { Nodes: []*graph.Node{ {Value: Letter{"B"}}, {Value: Letter{"A"}}, {Value: Letter{"E"}}, }}, } // Check the number of SCC sets. if len(expectedStronglyConnectedComponents) != len(correctStronglyConnectedComponents) { t.Fatalf("Number of strongly connected components be %d, but are %d!\n", len(correctStronglyConnectedComponents), len(expectedStronglyConnectedComponents)) } if !sccExists(correctStronglyConnectedComponents, expectedStronglyConnectedComponents) { t.Error("Not all SCC exists") } } func TestStronglyConnectedComponentsInGraph2(t *testing.T) { directedGraph := graph.NewGraph() a := graph.Node{Value: Letter{"A"}} b := graph.Node{Value: Letter{"B"}} c := graph.Node{Value: Letter{"C"}} d := graph.Node{Value: Letter{"D"}} e := graph.Node{Value: Letter{"E"}} f := graph.Node{Value: Letter{"F"}} g := graph.Node{Value: Letter{"G"}} h := graph.Node{Value: Letter{"H"}} directedGraph.InsertEdge(&a, &b) directedGraph.InsertEdge(&a, &f) directedGraph.InsertEdge(&b, &f) directedGraph.InsertEdge(&b, &c) directedGraph.InsertEdge(&c, &d) directedGraph.InsertEdge(&c, &g) directedGraph.InsertEdge(&e, &a) directedGraph.InsertEdge(&f, &e) directedGraph.InsertEdge(&f, &g) directedGraph.InsertEdge(&g, &c) directedGraph.InsertEdge(&h, &g) expectedStronglyConnectedComponents := directedGraph.GetSCComponents() correctStronglyConnectedComponents := []*graph.StronglyConnectedComponent{ { Nodes: []*graph.Node{ {Value: Letter{"D"}}, }}, { Nodes: []*graph.Node{ {Value: Letter{"C"}}, {Value: Letter{"G"}}, }}, { Nodes: []*graph.Node{ {Value: Letter{"A"}}, {Value: Letter{"B"}}, {Value: Letter{"E"}}, {Value: Letter{"F"}}, }}, { Nodes: []*graph.Node{ {Value: Letter{"H"}}, }}, } // Check the number of SCC sets. if len(expectedStronglyConnectedComponents) != len(correctStronglyConnectedComponents) { t.Fatalf("Number of strongly connected components be %d, but are %d!\n", len(correctStronglyConnectedComponents), len(expectedStronglyConnectedComponents)) } if !sccExists(correctStronglyConnectedComponents, expectedStronglyConnectedComponents) { t.Error("Not all SCC exists") } }
{ "content_hash": "ffb9af24e81f7652dc2dc7ce8ad2a592", "timestamp": "", "source": "github", "line_count": 342, "max_line_length": 123, "avg_line_length": 27.538011695906434, "alnum_prop": 0.6596942025907836, "repo_name": "chrisbbe/GoAnalysis", "id": "2c7154406edb19977edbc57153c15d1fa8e75c1f", "size": "9595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "analyzer/linter/ccomplexity/graph/graph_test.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "545" }, { "name": "Go", "bytes": "131523" }, { "name": "Java", "bytes": "21203" }, { "name": "Makefile", "bytes": "679" } ], "symlink_target": "" }
package com.siyeh.ig.bugs; import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase; import com.intellij.codeInspection.LocalInspectionTool; import org.jetbrains.annotations.NotNull; public class EmptyStatementBodyInspectionFixTest extends LightQuickFixParameterizedTestCase { public void test() { doAllTests(); } @NotNull @Override protected LocalInspectionTool[] configureLocalInspectionTools() { return new LocalInspectionTool[] {new EmptyStatementBodyInspection()}; } @Override protected String getBasePath() { return "/codeInsight/daemonCodeAnalyzer/quickFix/emptyStatement"; } }
{ "content_hash": "263b647a8b62287da6b82460a78980d2", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 93, "avg_line_length": 30.476190476190474, "alnum_prop": 0.80625, "repo_name": "jk1/intellij-community", "id": "984b9b85f186005fe9760274a1e2d1a3680ff74e", "size": "1240", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/EmptyStatementBodyInspectionFixTest.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using ImageGallery.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OAuth; namespace ImageGallery.Providers { public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider { private readonly string _publicClientId; private readonly Func<UserManager<User>> _userManagerFactory; public ApplicationOAuthProvider(string publicClientId, Func<UserManager<User>> userManagerFactory) { if (publicClientId == null) { throw new ArgumentNullException("publicClientId"); } if (userManagerFactory == null) { throw new ArgumentNullException("userManagerFactory"); } _publicClientId = publicClientId; _userManagerFactory = userManagerFactory; } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (UserManager<User> userManager = _userManagerFactory()) { User user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } } public override Task TokenEndpoint(OAuthTokenEndpointContext context) { foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) { context.AdditionalResponseParameters.Add(property.Key, property.Value); } return Task.FromResult<object>(null); } public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { // Resource owner password credentials does not provide a client ID. if (context.ClientId == null) { context.Validated(); } return Task.FromResult<object>(null); } public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) { if (context.ClientId == _publicClientId) { Uri expectedRootUri = new Uri(context.Request.Uri, "/"); if (expectedRootUri.AbsoluteUri == context.RedirectUri) { context.Validated(); } } return Task.FromResult<object>(null); } public static AuthenticationProperties CreateProperties(string userName) { IDictionary<string, string> data = new Dictionary<string, string> { { "userName", userName } }; return new AuthenticationProperties(data); } } }
{ "content_hash": "a1e09be02dc0f9355e0a0d7e8eed10a6", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 115, "avg_line_length": 37.28155339805825, "alnum_prop": 0.6026041666666667, "repo_name": "gyuwon/ImageGallery", "id": "2aa632dc133ccd7fc48db203180ac97f1e0144f3", "size": "3842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ImageGallery/Providers/ApplicationOAuthProvider.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "C#", "bytes": "127857" }, { "name": "CSS", "bytes": "2587" }, { "name": "JavaScript", "bytes": "547082" } ], "symlink_target": "" }
<?php /** * CakePHP Debug Level: * * Production Mode: * 0: No error messages, errors, or warnings shown. Flash messages redirect. * * Development Mode: * 1: Errors and warnings shown, model caches refreshed, flash messages halted. * 2: As in 1, but also with full debug messages and SQL output. * * In production mode, flash messages redirect after a time interval. * In development mode, you need to click the flash message to continue. */ Configure::write('debug', 0); /** * Configure the Error handler used to handle errors for your application. By default * ErrorHandler::handleError() is used. It will display errors using Debugger, when debug > 0 * and log errors with CakeLog when debug = 0. * * Options: * * - `handler` - callback - The callback to handle errors. You can set this to any callable type, * including anonymous functions. * Make sure you add App::uses('MyHandler', 'Error'); when using a custom handler class * - `level` - integer - The level of errors you are interested in capturing. * - `trace` - boolean - Include stack traces for errors in log files. * * @see ErrorHandler for more information on error handling and configuration. */ Configure::write('Error', array( 'handler' => 'ErrorHandler::handleError', 'level' => E_ALL & ~E_DEPRECATED, 'trace' => true )); /** * Configure the Exception handler used for uncaught exceptions. By default, * ErrorHandler::handleException() is used. It will display a HTML page for the exception, and * while debug > 0, framework errors like Missing Controller will be displayed. When debug = 0, * framework errors will be coerced into generic HTTP errors. * * Options: * * - `handler` - callback - The callback to handle exceptions. You can set this to any callback type, * including anonymous functions. * Make sure you add App::uses('MyHandler', 'Error'); when using a custom handler class * - `renderer` - string - The class responsible for rendering uncaught exceptions. If you choose a custom class you * should place the file for that class in app/Lib/Error. This class needs to implement a render method. * - `log` - boolean - Should Exceptions be logged? * - `skipLog` - array - list of exceptions to skip for logging. Exceptions that * extend one of the listed exceptions will also be skipped for logging. * Example: `'skipLog' => array('NotFoundException', 'UnauthorizedException')` * * @see ErrorHandler for more information on exception handling and configuration. */ Configure::write('Exception', array( 'handler' => 'ErrorHandler::handleException', 'renderer' => 'ExceptionRenderer', 'log' => true )); /** * Application wide charset encoding */ Configure::write('App.encoding', 'UTF-8'); /** * To configure CakePHP *not* to use mod_rewrite and to * use CakePHP pretty URLs, remove these .htaccess * files: * * /.htaccess * /app/.htaccess * /app/webroot/.htaccess * * And uncomment the App.baseUrl below. But keep in mind * that plugin assets such as images, CSS and JavaScript files * will not work without URL rewriting! * To work around this issue you should either symlink or copy * the plugin assets into you app's webroot directory. This is * recommended even when you are using mod_rewrite. Handling static * assets through the Dispatcher is incredibly inefficient and * included primarily as a development convenience - and * thus not recommended for production applications. */ //Configure::write('App.baseUrl', env('SCRIPT_NAME')); /** * To configure CakePHP to use a particular domain URL * for any URL generation inside the application, set the following * configuration variable to the http(s) address to your domain. This * will override the automatic detection of full base URL and can be * useful when generating links from the CLI (e.g. sending emails) */ //Configure::write('App.fullBaseUrl', 'http://example.com'); /** * Web path to the public images directory under webroot. * If not set defaults to 'img/' */ //Configure::write('App.imageBaseUrl', 'img/'); /** * Web path to the CSS files directory under webroot. * If not set defaults to 'css/' */ //Configure::write('App.cssBaseUrl', 'css/'); /** * Web path to the js files directory under webroot. * If not set defaults to 'js/' */ //Configure::write('App.jsBaseUrl', 'js/'); /** * Uncomment the define below to use CakePHP prefix routes. * * The value of the define determines the names of the routes * and their associated controller actions: * * Set to an array of prefixes you want to use in your application. Use for * admin or other prefixed routes. * * Routing.prefixes = array('admin', 'manager'); * * Enables: * `admin_index()` and `/admin/controller/index` * `manager_index()` and `/manager/controller/index` * */ //Configure::write('Routing.prefixes', array('admin')); /** * Turn off all caching application-wide. * */ //Configure::write('Cache.disable', true); /** * Enable cache checking. * * If set to true, for view caching you must still use the controller * public $cacheAction inside your controllers to define caching settings. * You can either set it controller-wide by setting public $cacheAction = true, * or in each action using $this->cacheAction = true. * */ //Configure::write('Cache.check', true); /** * Enable cache view prefixes. * * If set it will be prepended to the cache name for view file caching. This is * helpful if you deploy the same application via multiple subdomains and languages, * for instance. Each version can then have its own view cache namespace. * Note: The final cache file name will then be `prefix_cachefilename`. */ //Configure::write('Cache.viewPrefix', 'prefix'); /** * Session configuration. * * Contains an array of settings to use for session configuration. The defaults key is * used to define a default preset to use for sessions, any settings declared here will override * the settings of the default config. * * ## Options * * - `Session.cookie` - The name of the cookie to use. Defaults to 'CAKEPHP' * - `Session.timeout` - The number of minutes you want sessions to live for. This timeout is handled by CakePHP * - `Session.cookieTimeout` - The number of minutes you want session cookies to live for. * - `Session.checkAgent` - Do you want the user agent to be checked when starting sessions? You might want to set the * value to false, when dealing with older versions of IE, Chrome Frame or certain web-browsing devices and AJAX * - `Session.defaults` - The default configuration set to use as a basis for your session. * There are four builtins: php, cake, cache, database. * - `Session.handler` - Can be used to enable a custom session handler. Expects an array of callables, * that can be used with `session_save_handler`. Using this option will automatically add `session.save_handler` * to the ini array. * - `Session.autoRegenerate` - Enabling this setting, turns on automatic renewal of sessions, and * sessionids that change frequently. See CakeSession::$requestCountdown. * - `Session.ini` - An associative array of additional ini values to set. * * The built in defaults are: * * - 'php' - Uses settings defined in your php.ini. * - 'cake' - Saves session files in CakePHP's /tmp directory. * - 'database' - Uses CakePHP's database sessions. * - 'cache' - Use the Cache class to save sessions. * * To define a custom session handler, save it at /app/Model/Datasource/Session/<name>.php. * Make sure the class implements `CakeSessionHandlerInterface` and set Session.handler to <name> * * To use database sessions, run the app/Config/Schema/sessions.php schema using * the cake shell command: cake schema create Sessions * */ Configure::write('Session', array( 'defaults' => 'php' )); /** * A random string used in security hashing methods. */ Configure::write('Security.salt', '6497eb7c59701e0098ee445eac8c890afb2afd5b'); /** * A random numeric string (digits only) used to encrypt/decrypt strings. */ Configure::write('Security.cipherSeed', '570293112567274531701244737557'); /** * Apply timestamps with the last modified time to static assets (js, css, images). * Will append a query string parameter containing the time the file was modified. This is * useful for invalidating browser caches. * * Set to `true` to apply timestamps when debug > 0. Set to 'force' to always enable * timestamping regardless of debug value. */ //Configure::write('Asset.timestamp', true); /** * Compress CSS output by removing comments, whitespace, repeating tags, etc. * This requires a/var/cache directory to be writable by the web server for caching. * and /vendors/csspp/csspp.php * * To use, prefix the CSS link URL with '/ccss/' instead of '/css/' or use HtmlHelper::css(). */ //Configure::write('Asset.filter.css', 'css.php'); /** * Plug in your own custom JavaScript compressor by dropping a script in your webroot to handle the * output, and setting the config below to the name of the script. * * To use, prefix your JavaScript link URLs with '/cjs/' instead of '/js/' or use JsHelper::link(). */ //Configure::write('Asset.filter.js', 'custom_javascript_output_filter.php'); /** * The class name and database used in CakePHP's * access control lists. */ Configure::write('Acl.classname', 'DbAcl'); Configure::write('Acl.database', 'default'); /** * Uncomment this line and correct your server timezone to fix * any date & time related errors. */ //date_default_timezone_set('UTC'); /** * `Config.timezone` is available in which you can set users' timezone string. * If a method of CakeTime class is called with $timezone parameter as null and `Config.timezone` is set, * then the value of `Config.timezone` will be used. This feature allows you to set users' timezone just * once instead of passing it each time in function calls. */ //Configure::write('Config.timezone', 'Europe/Paris'); /** * Cache Engine Configuration * Default settings provided below * * File storage engine. * * Cache::config('default', array( * 'engine' => 'File', //[required] * 'duration' => 3600, //[optional] * 'probability' => 100, //[optional] * 'path' => CACHE, //[optional] use system tmp directory - remember to use absolute path * 'prefix' => 'cake_', //[optional] prefix every cache file with this string * 'lock' => false, //[optional] use file locking * 'serialize' => true, //[optional] * 'mask' => 0664, //[optional] * )); * * APC (http://pecl.php.net/package/APC) * * Cache::config('default', array( * 'engine' => 'Apc', //[required] * 'duration' => 3600, //[optional] * 'probability' => 100, //[optional] * 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string * )); * * Xcache (http://xcache.lighttpd.net/) * * Cache::config('default', array( * 'engine' => 'Xcache', //[required] * 'duration' => 3600, //[optional] * 'probability' => 100, //[optional] * 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string * 'user' => 'user', //user from xcache.admin.user settings * 'password' => 'password', //plaintext password (xcache.admin.pass) * )); * * Memcached (http://www.danga.com/memcached/) * * Uses the memcached extension. See http://php.net/memcached * * Cache::config('default', array( * 'engine' => 'Memcached', //[required] * 'duration' => 3600, //[optional] * 'probability' => 100, //[optional] * 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string * 'servers' => array( * '127.0.0.1:11211' // localhost, default port 11211 * ), //[optional] * 'persistent' => 'my_connection', // [optional] The name of the persistent connection. * 'compress' => false, // [optional] compress data in Memcached (slower, but uses less memory) * )); * * Wincache (http://php.net/wincache) * * Cache::config('default', array( * 'engine' => 'Wincache', //[required] * 'duration' => 3600, //[optional] * 'probability' => 100, //[optional] * 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string * )); */ /** * Configure the cache handlers that CakePHP will use for internal * metadata like class maps, and model schema. * * By default File is used, but for improved performance you should use APC. * * Note: 'default' and other application caches should be configured in app/Config/bootstrap.php. * Please check the comments in bootstrap.php for more info on the cache engines available * and their settings. */ $engine = 'File'; // In development mode, caches should expire quickly. $duration = '+999 days'; if (Configure::read('debug') > 0) { $duration = '+10 seconds'; } // Prefix each application on the same server with a different string, to avoid Memcache and APC conflicts. $prefix = 'myapp_'; /** * Configure the cache used for general framework caching. Path information, * object listings, and translation cache files are stored with this configuration. */ Cache::config('_cake_core_', array( 'engine' => $engine, 'prefix' => $prefix . 'cake_core_', 'path' => CACHE . 'persistent' . DS, 'serialize' => ($engine === 'File'), 'duration' => $duration )); /** * Configure the cache for model and datasource caches. This cache configuration * is used to store schema descriptions, and table listings in connections. */ Cache::config('_cake_model_', array( 'engine' => $engine, 'prefix' => $prefix . 'cake_model_', 'path' => CACHE . 'models' . DS, 'serialize' => ($engine === 'File'), 'duration' => $duration )); Configure::write('CakePdf', array( 'engine' => 'CakePdf.Tcpdf', 'options' => array( 'print-media-type' => false, 'outline' => true, 'dpi' => 96 ), 'pageSize' => 'letter', 'margin' => array( 'bottom' => 15, 'left' => 50, 'right' => 30, 'top' => 45 ), 'orientation' => 'portrait' ));
{ "content_hash": "bf8ff2c86fe04b9ad9974712bee4b601", "timestamp": "", "source": "github", "line_count": 385, "max_line_length": 118, "avg_line_length": 36.753246753246756, "alnum_prop": 0.6847349823321555, "repo_name": "maths22/ibl-scheduler", "id": "5e3acc2cb1f233cbdf0a5e977e94b9ef029df437", "size": "14865", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IBLScheduler/app/Config/core.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31235" }, { "name": "JavaScript", "bytes": "149" }, { "name": "PHP", "bytes": "8150508" }, { "name": "Shell", "bytes": "2888" } ], "symlink_target": "" }
var util = require('util'); var events = require('events'); var http = require('http'); var https = require('https'); var Logger = require('./../util/logger'); var format = util.format; module.exports = (function() { var Settings = { selenium_host : 'localhost', selenium_port : 4444, default_path : '/wd/hub', credentials : null, use_ssl : false, proxy : null, timeout : 60000, retry_attempts : 0 }; var DO_NOT_LOG_ERRORS = [ 'Unable to locate element', '{"errorMessage":"Unable to find element', 'no such element' ]; function HttpRequest(options) { events.EventEmitter.call(this); this.setOptions(options); } util.inherits(HttpRequest, events.EventEmitter); HttpRequest.prototype.setOptions = function(options) { this.data = options.data && jsonStringify(options.data) || ''; this.contentLength = this.data.length; this.reqOptions = this.createOptions(options); this.hostname = formatHostname(this.reqOptions.host, this.reqOptions.port); this.request = null; this.timeout = Settings.timeout; this.retryAttempts = Settings.retry_attempts; return this; }; HttpRequest.prototype.setPathPrefix = function(options) { this.defaultPathPrefix = options.path && options.path.indexOf(Settings.default_path) === -1 ? Settings.default_path : ''; return this; }; HttpRequest.prototype.createOptions = function(options) { this.setPathPrefix(options); var reqOptions = { path : this.defaultPathPrefix + (options.path || ''), host : options.host || Settings.selenium_host, port : options.selenium_port || Settings.selenium_port, method : options.method || 'POST', headers : {} }; var requestMethod = reqOptions.method.toUpperCase(); if (options.sessionId) { reqOptions.path = reqOptions.path.replace(':sessionId', options.sessionId); } if (requestMethod === 'GET') { reqOptions.headers['Accept'] = 'application/json'; } if (this.contentLength > 0) { reqOptions.headers['Content-Type'] = 'application/json; charset=utf-8'; } if (needsContentLengthHeader(requestMethod)) { reqOptions.headers['Content-Length'] = this.contentLength; } if (Settings.credentials && Settings.credentials.username && Settings.credentials.key ) { var authHeader = new Buffer(Settings.credentials.username + ':' + Settings.credentials.key).toString('base64'); reqOptions.headers['Authorization'] = 'Basic ' + authHeader; } if (Settings.proxy) { var ProxyAgent = require('proxy-agent'); var proxyUri = Settings.proxy; reqOptions.agent = new ProxyAgent(proxyUri); } return reqOptions; }; HttpRequest.prototype.send = function() { var self = this; var startTime = new Date(); var isAborted = false; this.request = (Settings.use_ssl ? https: http).request(this.reqOptions, function (response) { response.setEncoding('utf8'); var redirected = false; if (isRedirect(response.statusCode)) { redirected = true; } var flushed = ''; response.on('data', function (chunk) { if (self.reqOptions.method !== 'HEAD') { flushed += chunk; } }); response.on('end', function () { var elapsedTime = new Date() - startTime; var screenshotContent; var result, errorMessage = ''; if (flushed) { result = parseResult(flushed); if (result.value) { if (result.value.screen) { screenshotContent = result.value.screen; delete result.value.screen; } if (result.value.stackTrace) { // Selenium stack traces won't help us here and they will pollute the output delete result.value.stackTrace; } if (needsFormattedErrorMessage(result)) { errorMessage = formatErrorMessage(result.value); delete result.value.localizedMessage; delete result.value.message; } } } else { result = {}; } if (errorMessage !== '') { console.log(Logger.colors.yellow('There was an error while executing the Selenium command') + (!Logger.isEnabled() ? ' - enabling the --verbose option might offer more details.' : '') ); console.log(errorMessage); } self.emit('beforeResult', result); var base64Data; if (result.suppressBase64Data) { base64Data = result.value; result.value = ''; } var logMethod = response.statusCode.toString().indexOf('5') === 0 ? 'error' : 'info'; Logger[logMethod](util.format('Response %s %s %s (%sms) ', response.statusCode, self.reqOptions.method, self.hostname + self.reqOptions.path, elapsedTime), result); if (result.suppressBase64Data) { result.value = base64Data; } if (response.statusCode.toString().indexOf('2') === 0 || redirected) { if (isAborted) { return; } self.emit('success', result, response, redirected); } else { self.emit('error', result, response, screenshotContent); } }); }); this.request.on('error', function(response) { self.emit('error', {}, response); }); this.request.setTimeout(this.timeout, function() { if (self.retryAttempts) { self.request.socket.unref(); isAborted = true; // prevent emitting of the success event multiple times. self.retryAttempts = self.retryAttempts - 1; self.send(); } else { self.request.abort(); } }); Logger.info('Request: ' + this.reqOptions.method + ' ' + this.hostname + this.reqOptions.path, '\n - data: ', this.data, '\n - headers: ', JSON.stringify(this.reqOptions.headers)); this.request.write(this.data); this.request.end(); return this; }; /** * * @param s * @param emit_unicode * @returns {string} */ HttpRequest.JSON_stringify = function(s, emit_unicode) { var json = JSON.stringify(s); if (json) { return emit_unicode ? json : json.replace(jsonRegex, jsonRegexReplace); } }; HttpRequest.setSeleniumPort = function(port) { Settings.selenium_port = port; }; HttpRequest.useSSL = function(value) { Settings.use_ssl = value; }; HttpRequest.setSeleniumHost = function(host) { Settings.selenium_host = host; }; HttpRequest.setCredentials = function(credentials) { Settings.credentials = credentials; }; HttpRequest.setProxy = function(proxy) { Settings.proxy = proxy; }; HttpRequest.setDefaultPathPrefix = function(path) { Settings.default_path = path; }; HttpRequest.setTimeout = function(timeout) { Settings.timeout = timeout; }; HttpRequest.setRetryAttempts = function(retryAttempts) { Settings.retry_attempts = retryAttempts; }; /////////////////////////////////////////////////////////// // Helpers /////////////////////////////////////////////////////////// var jsonRegex = new RegExp('[\\u007f-\\uffff]', 'g'); var jsonRegexReplace = function(c) { return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4); }; /** * Built in JSON.stringify() will return unicode characters that require UTF-8 encoding on the wire. * This function will replace unicode characters with their escaped (ASCII-safe) equivalents to support * the keys sending command. * * @param {object} s * @returns {string} */ function jsonStringify(s) { var json = JSON.stringify(s); if (json) { return json.replace(jsonRegex, jsonRegexReplace); } return json; } function formatHostname(hostname, port) { var isLocalHost = ['127.0.0.1', 'localhost'].indexOf(hostname) > -1; var protocol = Settings.use_ssl ? 'https://' : 'http://'; var isPortDefault = [80, 443].indexOf(port) > -1; if (isLocalHost) { return ''; } return protocol + hostname + (!isPortDefault && (':' + port) || ''); } function isRedirect(statusCode) { return [302, 303, 304].indexOf(statusCode) > -1; } function needsContentLengthHeader(requestMethod) { return ['POST', 'DELETE'].indexOf(requestMethod) > -1; } function needsFormattedErrorMessage(result) { return !!(result.localizedMessage || result.message); } function hasLocalizedMessage(result) { return !!result.localizedMessage; } function formatErrorMessage(info) { var msg = hasLocalizedMessage(info) ? info.localizedMessage : info.message; if (shouldLogErrorMessage(msg)) { msg = msg.replace(/\n/g, '\n\t'); } return msg; } function parseResult(data) { var result; data = stripUnknownChars(data); try { result = JSON.parse(data); } catch (err) { console.log(Logger.colors.red('Error processing the server response:'), '\n', data); result = {value: -1, error: err.message}; } return result; } function shouldLogErrorMessage(msg) { return !DO_NOT_LOG_ERRORS.some(function(item) { return msg.indexOf(item) === 0; }); } function stripUnknownChars(str) { var x = [], i = 0, length = str.length; for (i; i < length; i++) { if (str.charCodeAt(i)) { x.push(str.charAt(i)); } } return x.join(''); } return HttpRequest; })();
{ "content_hash": "bf8294db8ed5197814855c1a4f934cf9", "timestamp": "", "source": "github", "line_count": 325, "max_line_length": 172, "avg_line_length": 29.501538461538463, "alnum_prop": 0.6014810179390905, "repo_name": "Crunch-io/nightwatch", "id": "62f576074d9636081b2f1e03f47fd4f877ca0fc0", "size": "9588", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "lib/http/request.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1757" }, { "name": "JavaScript", "bytes": "842059" } ], "symlink_target": "" }
package org.apache.drill.exec.store.parquet.columnreaders; import org.apache.drill.common.exceptions.ExecutionSetupException; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.vector.BigIntVector; import org.apache.drill.exec.vector.BitVector; import org.apache.drill.exec.vector.DateVector; import org.apache.drill.exec.vector.Float4Vector; import org.apache.drill.exec.vector.Float8Vector; import org.apache.drill.exec.vector.IntVector; import org.apache.drill.exec.vector.IntervalVector; import org.apache.drill.exec.vector.NullableBigIntVector; import org.apache.drill.exec.vector.NullableBitVector; import org.apache.drill.exec.vector.NullableDateVector; import org.apache.drill.exec.vector.NullableFloat4Vector; import org.apache.drill.exec.vector.NullableFloat8Vector; import org.apache.drill.exec.vector.NullableIntVector; import org.apache.drill.exec.vector.NullableIntervalVector; import org.apache.drill.exec.vector.NullableTimeStampVector; import org.apache.drill.exec.vector.NullableTimeVector; import org.apache.drill.exec.vector.NullableUInt4Vector; import org.apache.drill.exec.vector.NullableUInt8Vector; import org.apache.drill.exec.vector.NullableVarBinaryVector; import org.apache.drill.exec.vector.NullableVarCharVector; import org.apache.drill.exec.vector.NullableVarDecimalVector; import org.apache.drill.exec.vector.TimeStampVector; import org.apache.drill.exec.vector.TimeVector; import org.apache.drill.exec.vector.UInt4Vector; import org.apache.drill.exec.vector.UInt8Vector; import org.apache.drill.exec.vector.ValueVector; import org.apache.drill.exec.vector.VarBinaryVector; import org.apache.drill.exec.vector.VarCharVector; import org.apache.drill.exec.vector.VarDecimalVector; import org.apache.drill.exec.vector.VariableWidthVector; import org.apache.parquet.column.ColumnDescriptor; import org.apache.parquet.format.ConvertedType; import org.apache.parquet.format.SchemaElement; import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData; import java.util.Collections; public class ColumnReaderFactory { /** * Creates fixed column reader for the given column based on its metadata. * * @param fixedLength if fixed length reader should be used * @param descriptor column descriptor * @param columnChunkMetaData column metadata * * @return ColumnReader object instance */ static ColumnReader<?> createFixedColumnReader(ParquetRecordReader recordReader, boolean fixedLength, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData, ValueVector v, SchemaElement schemaElement) throws Exception { ConvertedType convertedType = schemaElement.getConverted_type(); // if the column is required, or repeated (in which case we just want to use this to generate our appropriate // ColumnReader for actually transferring data into the data vector inside of our repeated vector if (descriptor.getMaxDefinitionLevel() == 0 || descriptor.getMaxRepetitionLevel() > 0) { return getColumnReader(recordReader, fixedLength, descriptor, columnChunkMetaData, v, schemaElement, convertedType); } else { // if the column is nullable return getNullableColumnReader(recordReader, descriptor, columnChunkMetaData, fixedLength, v, schemaElement); } } static VarLengthValuesColumn<?> getReader(ParquetRecordReader parentReader, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData, boolean fixedLength, ValueVector v, SchemaElement schemaElement ) throws ExecutionSetupException { ConvertedType convertedType = schemaElement.getConverted_type(); switch (descriptor.getMaxDefinitionLevel()) { case 0: if (convertedType == null) { return new VarLengthColumnReaders.VarBinaryColumn(parentReader, descriptor, columnChunkMetaData, fixedLength, (VarBinaryVector) v, schemaElement); } switch (convertedType) { case UTF8: case ENUM: return new VarLengthColumnReaders.VarCharColumn(parentReader, descriptor, columnChunkMetaData, fixedLength, (VarCharVector) v, schemaElement); case DECIMAL: if (v instanceof VarDecimalVector) { return new VarLengthColumnReaders.VarDecimalColumn(parentReader, descriptor, columnChunkMetaData, fixedLength, (VarDecimalVector) v, schemaElement); } default: return new VarLengthColumnReaders.VarBinaryColumn(parentReader, descriptor, columnChunkMetaData, fixedLength, (VarBinaryVector) v, schemaElement); } default: if (convertedType == null) { return new VarLengthColumnReaders.NullableVarBinaryColumn(parentReader, descriptor, columnChunkMetaData, fixedLength, (NullableVarBinaryVector) v, schemaElement); } switch (convertedType) { case UTF8: case ENUM: return new VarLengthColumnReaders.NullableVarCharColumn(parentReader, descriptor, columnChunkMetaData, fixedLength, (NullableVarCharVector) v, schemaElement); case DECIMAL: if (v instanceof NullableVarDecimalVector) { return new VarLengthColumnReaders.NullableVarDecimalColumn(parentReader, descriptor, columnChunkMetaData, fixedLength, (NullableVarDecimalVector) v, schemaElement); } default: return new VarLengthColumnReaders.NullableVarBinaryColumn(parentReader, descriptor, columnChunkMetaData, fixedLength, (NullableVarBinaryVector) v, schemaElement); } } } private static ColumnReader<? extends ValueVector> getColumnReader(ParquetRecordReader recordReader, boolean fixedLength, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData, ValueVector v, SchemaElement schemaElement, ConvertedType convertedType) throws ExecutionSetupException { switch (columnChunkMetaData.getPrimitiveType().getPrimitiveTypeName()) { case BOOLEAN: return new BitReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (BitVector) v, schemaElement); case INT32: if (convertedType == null) { return new ParquetFixedWidthDictionaryReaders.DictionaryIntReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (IntVector) v, schemaElement); } switch (convertedType) { case DATE: switch(recordReader.getDateCorruptionStatus()) { case META_SHOWS_CORRUPTION: return new FixedByteAlignedReader.CorruptDateReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (DateVector) v, schemaElement); case META_SHOWS_NO_CORRUPTION: return new FixedByteAlignedReader.DateReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (DateVector) v, schemaElement); case META_UNCLEAR_TEST_VALUES: return new FixedByteAlignedReader.CorruptionDetectingDateReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (DateVector) v, schemaElement); default: throw new ExecutionSetupException( String.format("Issue setting up parquet reader for date type, " + "unrecognized date corruption status %s. See DRILL-4203 for more info.", recordReader.getDateCorruptionStatus())); } case DECIMAL: return new ParquetFixedWidthDictionaryReaders.DictionaryVarDecimalReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (VarDecimalVector) v, schemaElement); case TIME_MILLIS: return new ParquetFixedWidthDictionaryReaders.DictionaryTimeReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (TimeVector) v, schemaElement); case INT_8: case INT_16: case INT_32: return new ParquetFixedWidthDictionaryReaders.DictionaryIntReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (IntVector) v, schemaElement); case UINT_8: case UINT_16: case UINT_32: return new ParquetFixedWidthDictionaryReaders.DictionaryUInt4Reader(recordReader, descriptor, columnChunkMetaData, fixedLength, (UInt4Vector) v, schemaElement); default: throw new ExecutionSetupException("Unsupported dictionary converted type " + convertedType + " for primitive type INT32"); } case INT64: if (convertedType == null) { return new ParquetFixedWidthDictionaryReaders.DictionaryBigIntReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (BigIntVector) v, schemaElement); } switch (convertedType) { // DRILL-6670: handle TIMESTAMP_MICROS as INT64 with no logical type case INT_64: case TIMESTAMP_MICROS: return new ParquetFixedWidthDictionaryReaders.DictionaryBigIntReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (BigIntVector) v, schemaElement); case UINT_64: return new ParquetFixedWidthDictionaryReaders.DictionaryUInt8Reader(recordReader, descriptor, columnChunkMetaData, fixedLength, (UInt8Vector) v, schemaElement); case DECIMAL: return new ParquetFixedWidthDictionaryReaders.DictionaryVarDecimalReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (VarDecimalVector) v, schemaElement); case TIMESTAMP_MILLIS: return new ParquetFixedWidthDictionaryReaders.DictionaryTimeStampReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (TimeStampVector) v, schemaElement); default: throw new ExecutionSetupException("Unsupported dictionary converted type " + convertedType + " for primitive type INT64"); } case FLOAT: return new ParquetFixedWidthDictionaryReaders.DictionaryFloat4Reader(recordReader, descriptor, columnChunkMetaData, fixedLength, (Float4Vector) v, schemaElement); case DOUBLE: return new ParquetFixedWidthDictionaryReaders.DictionaryFloat8Reader(recordReader, descriptor, columnChunkMetaData, fixedLength, (Float8Vector) v, schemaElement); case FIXED_LEN_BYTE_ARRAY: if (convertedType != null) { switch (convertedType) { case DECIMAL: return new ParquetFixedWidthDictionaryReaders.DictionaryVarDecimalReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (VarDecimalVector) v, schemaElement); case INTERVAL: return new FixedByteAlignedReader.IntervalReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (IntervalVector) v, schemaElement); } } if (!Collections.disjoint(columnChunkMetaData.getEncodings(), ColumnReader.DICTIONARY_ENCODINGS)) { return new ParquetFixedWidthDictionaryReaders.DictionaryFixedBinaryReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (VarBinaryVector) v, schemaElement); } return new FixedByteAlignedReader.FixedBinaryReader(recordReader, descriptor, columnChunkMetaData, (VariableWidthVector) v, schemaElement); case INT96: if (recordReader.getFragmentContext().getOptions().getOption(ExecConstants.PARQUET_READER_INT96_AS_TIMESTAMP).bool_val) { return new ParquetFixedWidthDictionaryReaders.DictionaryBinaryAsTimeStampReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (TimeStampVector) v, schemaElement); } else { return new ParquetFixedWidthDictionaryReaders.DictionaryFixedBinaryReader(recordReader, descriptor, columnChunkMetaData, fixedLength, (VarBinaryVector) v, schemaElement); } default: throw new ExecutionSetupException("Unsupported dictionary column type " + descriptor.getPrimitiveType().getPrimitiveTypeName().name()); } } public static ColumnReader<?> getNullableColumnReader(ParquetRecordReader parentReader, ColumnDescriptor columnDescriptor, ColumnChunkMetaData columnChunkMetaData, boolean fixedLength, ValueVector valueVec, SchemaElement schemaElement) throws ExecutionSetupException { ConvertedType convertedType = schemaElement.getConverted_type(); switch (columnDescriptor.getPrimitiveType().getPrimitiveTypeName()) { case BOOLEAN: return new NullableBitReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableBitVector) valueVec, schemaElement); case INT32: if (convertedType == null) { return new NullableFixedByteAlignedReaders.NullableDictionaryIntReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableIntVector) valueVec, schemaElement); } switch (convertedType) { case INT_8: case INT_16: case INT_32: return new NullableFixedByteAlignedReaders.NullableDictionaryIntReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableIntVector) valueVec, schemaElement); case UINT_8: case UINT_16: case UINT_32: return new NullableFixedByteAlignedReaders.NullableDictionaryUInt4Reader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableUInt4Vector) valueVec, schemaElement); case DECIMAL: return new NullableFixedByteAlignedReaders.NullableDictionaryVarDecimalReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableVarDecimalVector) valueVec, schemaElement); case TIME_MILLIS: return new NullableFixedByteAlignedReaders.NullableDictionaryTimeReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableTimeVector) valueVec, schemaElement); case DATE: switch (parentReader.getDateCorruptionStatus()) { case META_SHOWS_CORRUPTION: return new NullableFixedByteAlignedReaders.NullableCorruptDateReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableDateVector) valueVec, schemaElement); case META_SHOWS_NO_CORRUPTION: return new NullableFixedByteAlignedReaders.NullableDateReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableDateVector) valueVec, schemaElement); case META_UNCLEAR_TEST_VALUES: return new NullableFixedByteAlignedReaders.CorruptionDetectingNullableDateReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableDateVector) valueVec, schemaElement); default: throw new ExecutionSetupException( String.format("Issue setting up parquet reader for date type, " + "unrecognized date corruption status %s. See DRILL-4203 for more info.", parentReader.getDateCorruptionStatus())); } default: throw new ExecutionSetupException("Unsupported nullable converted type " + convertedType + " for primitive type INT32"); } case INT64: if (convertedType == null) { return new NullableFixedByteAlignedReaders.NullableDictionaryBigIntReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableBigIntVector)valueVec, schemaElement); } switch (convertedType) { case UINT_64: return new NullableFixedByteAlignedReaders.NullableDictionaryUInt8Reader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableUInt8Vector) valueVec, schemaElement); case DECIMAL: return new NullableFixedByteAlignedReaders.NullableDictionaryVarDecimalReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableVarDecimalVector) valueVec, schemaElement); case TIMESTAMP_MILLIS: return new NullableFixedByteAlignedReaders.NullableDictionaryTimeStampReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableTimeStampVector)valueVec, schemaElement); // DRILL-6670: handle TIMESTAMP_MICROS as INT64 with no logical type case TIMESTAMP_MICROS: case INT_64: return new NullableFixedByteAlignedReaders.NullableDictionaryBigIntReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableBigIntVector) valueVec, schemaElement); default: throw new ExecutionSetupException("Unsupported nullable converted type " + convertedType + " for primitive type INT64"); } case INT96: // TODO: check convertedType once parquet support TIMESTAMP_NANOS type annotation. if (parentReader.getFragmentContext().getOptions().getOption(ExecConstants.PARQUET_READER_INT96_AS_TIMESTAMP).bool_val) { return new NullableFixedByteAlignedReaders.NullableFixedBinaryAsTimeStampReader(parentReader, columnDescriptor, columnChunkMetaData, true, (NullableTimeStampVector) valueVec, schemaElement); } else { return new NullableFixedByteAlignedReaders.NullableFixedBinaryReader(parentReader, columnDescriptor, columnChunkMetaData, true, (NullableVarBinaryVector) valueVec, schemaElement); } case FLOAT: return new NullableFixedByteAlignedReaders.NullableDictionaryFloat4Reader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableFloat4Vector)valueVec, schemaElement); case DOUBLE: return new NullableFixedByteAlignedReaders.NullableDictionaryFloat8Reader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableFloat8Vector)valueVec, schemaElement); case FIXED_LEN_BYTE_ARRAY: if (convertedType != null) { switch (convertedType) { case DECIMAL: return new NullableFixedByteAlignedReaders.NullableDictionaryVarDecimalReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableVarDecimalVector) valueVec, schemaElement); case INTERVAL: return new NullableFixedByteAlignedReaders.NullableIntervalReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableIntervalVector) valueVec, schemaElement); } } if (!Collections.disjoint(columnChunkMetaData.getEncodings(), ColumnReader.DICTIONARY_ENCODINGS)) { return new NullableFixedByteAlignedReaders.NullableFixedBinaryReader(parentReader, columnDescriptor, columnChunkMetaData, fixedLength, (NullableVarBinaryVector) valueVec, schemaElement); } return new NullableFixedByteAlignedReaders.NullableFixedByteAlignedReader<>(parentReader,columnDescriptor, columnChunkMetaData, fixedLength, valueVec, schemaElement); default: throw new ExecutionSetupException("Unsupported nullable column type " + columnDescriptor.getPrimitiveType().getPrimitiveTypeName().name()); } } }
{ "content_hash": "9aa52b3e06183f6ecc3a2c72bbbab46a", "timestamp": "", "source": "github", "line_count": 321, "max_line_length": 205, "avg_line_length": 61.92211838006231, "alnum_prop": 0.7134879508980229, "repo_name": "vdiravka/drill", "id": "e084c2d0cd513b0001e849e3cf650eb22faa419d", "size": "20678", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/columnreaders/ColumnReaderFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "22729" }, { "name": "Batchfile", "bytes": "7471" }, { "name": "C", "bytes": "31425" }, { "name": "C++", "bytes": "595697" }, { "name": "CMake", "bytes": "25162" }, { "name": "CSS", "bytes": "15158" }, { "name": "Dockerfile", "bytes": "8183" }, { "name": "FreeMarker", "bytes": "196525" }, { "name": "Java", "bytes": "32999718" }, { "name": "JavaScript", "bytes": "81363" }, { "name": "Shell", "bytes": "119707" } ], "symlink_target": "" }
Freeze table columns in place. ## Requirements Requires [`jquery-tableslice`][tableslice] and [`jquery-tablesplit`][tablesplit]. ## Installing With [Bower][bower]: ```sh $ bower install --save jquery-tableslice jquery-tablesplit jquery-columnfreeze ``` ## Example Using default config: ```js $('.example').columnFreeze(); ``` Simple configuration: ```js $('.example').columnFreeze('freeze', { index: 2, wrapperClass: 'columnfreeze-wrapper clearfix' }); ``` ## Usage ```js $('table').columnFreeze([action], [options]); ``` `$.fn.columnFreeze()` returns the original table but replaces it with a new DOM element. ### Actions * `$('table').columnFreeze('freeze', options);` * Freeze a table in place * `$('table').columnFreeze('unfreeze', options);` * Return the table to its original state * `$('table').columnFreeze('config', key, [val]);` * Get a config value: `$('table').columnFreeze('config', 'index') === 1` * Set a config value: `$('table').columnFreeze('config', 'index', 2)` * Set multiple values: `$('table').columnFreeze('config', { index: 3 })` * `$('table').columnFreeze('isFrozen');` * Returns `true` if the table is currently frozen * `$('table').columnFreeze('init', options);` * Initializes a controller without freezing a table * `$('table').columnFreeze('controller');` * Returns the internal controller ### Options Default values are retrieved from `$.fn.columnFreeze.defaults`. * `index`: (default: 1) * `containerFixedClass`: (default: 'columnfreeze-container columnfreeze-container-fixed') * `containerFixedCSS` * `containerScrollClass`: (default: 'columnfreeze-container columnfreeze-container-scroll') * `containerScrollCSS` * `wrapperClass`: (default: 'columnfreeze-wrapper') - wrapper for above containers * `wrapperCSS` * `rowSelector`: (default: 'tr') - used to determine rows * `headerSelector`: (default: 'thead tr:last-child th, thead tr:last-child td') - used to determine table headers * `fixedWidth`: (default: null) - width of fixed section * `scrollWidth`: (default: null) - width of scrollable section (e.g. 'auto' or '1200px') ## License [MIT license](LICENSE). [tableslice]: https://github.com/j-/jquery-tableslice [tablesplit]: https://github.com/j-/jquery-tablesplit [bower]: http://bower.io/
{ "content_hash": "d982f450c119e6956aa08208d893af63", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 113, "avg_line_length": 28.746835443037973, "alnum_prop": 0.6948480845442536, "repo_name": "j-/jquery-columnfreeze", "id": "f745b37150acf06d79d7c7c32fa8b1fddae8173e", "size": "2302", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6880" } ], "symlink_target": "" }
<html> <body> <table border="1"> <tr> <td>name</td><td>value</td><td>description</td> </tr> <tr> <td><a name="hadoop.job.history.location">hadoop.job.history.location</a></td><td></td><td> If job tracker is static the history files are stored in this single well known place. If No value is set here, by default, it is in the local file system at ${hadoop.log.dir}/history. </td> </tr> <tr> <td><a name="hadoop.job.history.user.location">hadoop.job.history.user.location</a></td><td></td><td> User can specify a location to store the history files of a particular job. If nothing is specified, the logs are stored in output directory. The files are stored in "_logs/history/" in the directory. User can stop logging by giving the value "none". </td> </tr> <tr> <td><a name="mapred.job.tracker.history.completed.location">mapred.job.tracker.history.completed.location</a></td><td></td><td> The completed job history files are stored at this single well known location. If nothing is specified, the files are stored at ${hadoop.job.history.location}/done. </td> </tr> <tr> <td><a name="io.sort.factor">io.sort.factor</a></td><td>10</td><td>The number of streams to merge at once while sorting files. This determines the number of open file handles.</td> </tr> <tr> <td><a name="io.sort.mb">io.sort.mb</a></td><td>100</td><td>The total amount of buffer memory to use while sorting files, in megabytes. By default, gives each merge stream 1MB, which should minimize seeks.</td> </tr> <tr> <td><a name="io.sort.record.percent">io.sort.record.percent</a></td><td>0.05</td><td>The percentage of io.sort.mb dedicated to tracking record boundaries. Let this value be r, io.sort.mb be x. The maximum number of records collected before the collection thread must block is equal to (r * x) / 4</td> </tr> <tr> <td><a name="io.sort.spill.percent">io.sort.spill.percent</a></td><td>0.80</td><td>The soft limit in either the buffer or record collection buffers. Once reached, a thread will begin to spill the contents to disk in the background. Note that this does not imply any chunking of data to the spill. A value less than 0.5 is not recommended.</td> </tr> <tr> <td><a name="io.map.index.skip">io.map.index.skip</a></td><td>0</td><td>Number of index entries to skip between each entry. Zero by default. Setting this to values larger than zero can facilitate opening large map files using less memory.</td> </tr> <tr> <td><a name="mapred.job.tracker">mapred.job.tracker</a></td><td>local</td><td>The host and port that the MapReduce job tracker runs at. If "local", then jobs are run in-process as a single map and reduce task. </td> </tr> <tr> <td><a name="mapred.job.tracker.http.address">mapred.job.tracker.http.address</a></td><td>0.0.0.0:50030</td><td> The job tracker http server address and port the server will listen on. If the port is 0 then the server will start on a free port. </td> </tr> <tr> <td><a name="mapred.job.tracker.handler.count">mapred.job.tracker.handler.count</a></td><td>10</td><td> The number of server threads for the JobTracker. This should be roughly 4% of the number of tasktracker nodes. </td> </tr> <tr> <td><a name="mapred.task.tracker.report.address">mapred.task.tracker.report.address</a></td><td>127.0.0.1:0</td><td>The interface and port that task tracker server listens on. Since it is only connected to by the tasks, it uses the local interface. EXPERT ONLY. Should only be changed if your host does not have the loopback interface.</td> </tr> <tr> <td><a name="mapred.local.dir">mapred.local.dir</a></td><td>${hadoop.tmp.dir}/mapred/local</td><td>The local directory where MapReduce stores intermediate data files. May be a comma-separated list of directories on different devices in order to spread disk i/o. Directories that do not exist are ignored. </td> </tr> <tr> <td><a name="mapred.system.dir">mapred.system.dir</a></td><td>${hadoop.tmp.dir}/mapred/system</td><td>The directory where MapReduce stores control files. </td> </tr> <tr> <td><a name="mapreduce.jobtracker.staging.root.dir">mapreduce.jobtracker.staging.root.dir</a></td><td>${hadoop.tmp.dir}/mapred/staging</td><td>The root of the staging area for users' job files In practice, this should be the directory where users' home directories are located (usually /user) </td> </tr> <tr> <td><a name="mapred.temp.dir">mapred.temp.dir</a></td><td>${hadoop.tmp.dir}/mapred/temp</td><td>A shared directory for temporary files. </td> </tr> <tr> <td><a name="mapred.local.dir.minspacestart">mapred.local.dir.minspacestart</a></td><td>0</td><td>If the space in mapred.local.dir drops under this, do not ask for more tasks. Value in bytes. </td> </tr> <tr> <td><a name="mapred.local.dir.minspacekill">mapred.local.dir.minspacekill</a></td><td>0</td><td>If the space in mapred.local.dir drops under this, do not ask more tasks until all the current ones have finished and cleaned up. Also, to save the rest of the tasks we have running, kill one of them, to clean up some space. Start with the reduce tasks, then go with the ones that have finished the least. Value in bytes. </td> </tr> <tr> <td><a name="local.cache.size">local.cache.size</a></td><td>10737418240</td><td>The number of bytes to allocate in each local TaskTracker directory for holding Distributed Cache data.</td> </tr> <tr> <td><a name="mapreduce.tasktracker.cache.local.numberdirectories">mapreduce.tasktracker.cache.local.numberdirectories</a></td><td>10000</td><td> The maximum number of subdirectories that should be created in any particular distributed cache store. After this many directories have been created, cache items will be expunged regardless of whether the total size threshold has been exceeded. </td> </tr> <tr> <td><a name="mapred.tasktracker.expiry.interval">mapred.tasktracker.expiry.interval</a></td><td>600000</td><td>Expert: The time-interval, in miliseconds, after which a tasktracker is declared 'lost' if it doesn't send heartbeats. </td> </tr> <tr> <td><a name="mapred.tasktracker.instrumentation">mapred.tasktracker.instrumentation</a></td><td>org.apache.hadoop.mapred.TaskTrackerMetricsInst</td><td>Expert: The instrumentation class to associate with each TaskTracker. </td> </tr> <tr> <td><a name="mapred.tasktracker.resourcecalculatorplugin">mapred.tasktracker.resourcecalculatorplugin</a></td><td></td><td> Name of the class whose instance will be used to query resource information on the tasktracker. The class must be an instance of org.apache.hadoop.util.ResourceCalculatorPlugin. If the value is null, the tasktracker attempts to use a class appropriate to the platform. Currently, the only platform supported is Linux. </td> </tr> <tr> <td><a name="mapred.tasktracker.taskmemorymanager.monitoring-interval">mapred.tasktracker.taskmemorymanager.monitoring-interval</a></td><td>5000</td><td>The interval, in milliseconds, for which the tasktracker waits between two cycles of monitoring its tasks' memory usage. Used only if tasks' memory management is enabled via mapred.tasktracker.tasks.maxmemory. </td> </tr> <tr> <td><a name="mapred.tasktracker.tasks.sleeptime-before-sigkill">mapred.tasktracker.tasks.sleeptime-before-sigkill</a></td><td>5000</td><td>The time, in milliseconds, the tasktracker waits for sending a SIGKILL to a process, after it has been sent a SIGTERM.</td> </tr> <tr> <td><a name="mapred.map.tasks">mapred.map.tasks</a></td><td>2</td><td>The default number of map tasks per job. Ignored when mapred.job.tracker is "local". </td> </tr> <tr> <td><a name="mapred.reduce.tasks">mapred.reduce.tasks</a></td><td>1</td><td>The default number of reduce tasks per job. Typically set to 99% of the cluster's reduce capacity, so that if a node fails the reduces can still be executed in a single wave. Ignored when mapred.job.tracker is "local". </td> </tr> <tr> <td><a name="mapreduce.tasktracker.outofband.heartbeat">mapreduce.tasktracker.outofband.heartbeat</a></td><td>false</td><td>Expert: Set this to true to let the tasktracker send an out-of-band heartbeat on task-completion for better latency. </td> </tr> <tr> <td><a name="mapred.jobtracker.restart.recover">mapred.jobtracker.restart.recover</a></td><td>false</td><td>"true" to enable (job) recovery upon restart, "false" to start afresh </td> </tr> <tr> <td><a name="mapred.jobtracker.job.history.block.size">mapred.jobtracker.job.history.block.size</a></td><td>3145728</td><td>The block size of the job history file. Since the job recovery uses job history, its important to dump job history to disk as soon as possible. Note that this is an expert level parameter. The default value is set to 3 MB. </td> </tr> <tr> <td><a name="mapreduce.jobtracker.split.metainfo.maxsize">mapreduce.jobtracker.split.metainfo.maxsize</a></td><td>10000000</td><td>The maximum permissible size of the split metainfo file. The JobTracker won't attempt to read split metainfo files bigger than the configured value. No limits if set to -1. </td> </tr> <tr> <td><a name="mapred.jobtracker.taskScheduler">mapred.jobtracker.taskScheduler</a></td><td>org.apache.hadoop.mapred.JobQueueTaskScheduler</td><td>The class responsible for scheduling the tasks.</td> </tr> <tr> <td><a name="mapred.jobtracker.taskScheduler.maxRunningTasksPerJob">mapred.jobtracker.taskScheduler.maxRunningTasksPerJob</a></td><td></td><td>The maximum number of running tasks for a job before it gets preempted. No limits if undefined. </td> </tr> <tr> <td><a name="mapred.map.max.attempts">mapred.map.max.attempts</a></td><td>4</td><td>Expert: The maximum number of attempts per map task. In other words, framework will try to execute a map task these many number of times before giving up on it. </td> </tr> <tr> <td><a name="mapred.reduce.max.attempts">mapred.reduce.max.attempts</a></td><td>4</td><td>Expert: The maximum number of attempts per reduce task. In other words, framework will try to execute a reduce task these many number of times before giving up on it. </td> </tr> <tr> <td><a name="mapred.reduce.parallel.copies">mapred.reduce.parallel.copies</a></td><td>5</td><td>The default number of parallel transfers run by reduce during the copy(shuffle) phase. </td> </tr> <tr> <td><a name="mapreduce.reduce.shuffle.maxfetchfailures">mapreduce.reduce.shuffle.maxfetchfailures</a></td><td>10</td><td>The maximum number of times a reducer tries to fetch a map output before it reports it. </td> </tr> <tr> <td><a name="mapreduce.reduce.shuffle.connect.timeout">mapreduce.reduce.shuffle.connect.timeout</a></td><td>180000</td><td>Expert: The maximum amount of time (in milli seconds) a reduce task spends in trying to connect to a tasktracker for getting map output. </td> </tr> <tr> <td><a name="mapreduce.reduce.shuffle.read.timeout">mapreduce.reduce.shuffle.read.timeout</a></td><td>180000</td><td>Expert: The maximum amount of time (in milli seconds) a reduce task waits for map output data to be available for reading after obtaining connection. </td> </tr> <tr> <td><a name="mapred.task.timeout">mapred.task.timeout</a></td><td>600000</td><td>The number of milliseconds before a task will be terminated if it neither reads an input, writes an output, nor updates its status string. </td> </tr> <tr> <td><a name="mapred.tasktracker.map.tasks.maximum">mapred.tasktracker.map.tasks.maximum</a></td><td>2</td><td>The maximum number of map tasks that will be run simultaneously by a task tracker. </td> </tr> <tr> <td><a name="mapred.tasktracker.reduce.tasks.maximum">mapred.tasktracker.reduce.tasks.maximum</a></td><td>2</td><td>The maximum number of reduce tasks that will be run simultaneously by a task tracker. </td> </tr> <tr> <td><a name="mapred.jobtracker.completeuserjobs.maximum">mapred.jobtracker.completeuserjobs.maximum</a></td><td>100</td><td>The maximum number of complete jobs per user to keep around before delegating them to the job history.</td> </tr> <tr> <td><a name="mapreduce.reduce.input.limit">mapreduce.reduce.input.limit</a></td><td>-1</td><td>The limit on the input size of the reduce. If the estimated input size of the reduce is greater than this value, job is failed. A value of -1 means that there is no limit set. </td> </tr> <tr> <td><a name="mapred.job.tracker.retiredjobs.cache.size">mapred.job.tracker.retiredjobs.cache.size</a></td><td>1000</td><td>The number of retired job status to keep in the cache. </td> </tr> <tr> <td><a name="mapred.job.tracker.jobhistory.lru.cache.size">mapred.job.tracker.jobhistory.lru.cache.size</a></td><td>5</td><td>The number of job history files loaded in memory. The jobs are loaded when they are first accessed. The cache is cleared based on LRU. </td> </tr> <tr> <td><a name="mapred.jobtracker.instrumentation">mapred.jobtracker.instrumentation</a></td><td>org.apache.hadoop.mapred.JobTrackerMetricsInst</td><td>Expert: The instrumentation class to associate with each JobTracker. </td> </tr> <tr> <td><a name="mapred.jobtracker.plugins">mapred.jobtracker.plugins</a></td><td></td><td>Comma-separated list of jobtracker plug-ins to be activated. </td> </tr> <tr> <td><a name="mapred.child.java.opts">mapred.child.java.opts</a></td><td>-Xmx200m</td><td>Java opts for the task tracker child processes. The following symbol, if present, will be interpolated: @taskid@ is replaced by current TaskID. Any other occurrences of '@' will go unchanged. For example, to enable verbose gc logging to a file named for the taskid in /tmp and to set the heap maximum to be a gigabyte, pass a 'value' of: -Xmx1024m -verbose:gc -Xloggc:/tmp/@taskid@.gc The configuration variable mapred.child.ulimit can be used to control the maximum virtual memory of the child processes. </td> </tr> <tr> <td><a name="mapred.child.env">mapred.child.env</a></td><td></td><td>User added environment variables for the task tracker child processes. Example : 1) A=foo This will set the env variable A to foo 2) B=$B:c This is inherit tasktracker's B env variable. </td> </tr> <tr> <td><a name="mapred.child.ulimit">mapred.child.ulimit</a></td><td></td><td>The maximum virtual memory, in KB, of a process launched by the Map-Reduce framework. This can be used to control both the Mapper/Reducer tasks and applications using Hadoop Pipes, Hadoop Streaming etc. By default it is left unspecified to let cluster admins control it via limits.conf and other such relevant mechanisms. Note: mapred.child.ulimit must be greater than or equal to the -Xmx passed to JavaVM, else the VM might not start. </td> </tr> <tr> <td><a name="mapred.cluster.map.memory.mb">mapred.cluster.map.memory.mb</a></td><td>-1</td><td>The size, in terms of virtual memory, of a single map slot in the Map-Reduce framework, used by the scheduler. A job can ask for multiple slots for a single map task via mapred.job.map.memory.mb, upto the limit specified by mapred.cluster.max.map.memory.mb, if the scheduler supports the feature. The value of -1 indicates that this feature is turned off. </td> </tr> <tr> <td><a name="mapred.cluster.reduce.memory.mb">mapred.cluster.reduce.memory.mb</a></td><td>-1</td><td>The size, in terms of virtual memory, of a single reduce slot in the Map-Reduce framework, used by the scheduler. A job can ask for multiple slots for a single reduce task via mapred.job.reduce.memory.mb, upto the limit specified by mapred.cluster.max.reduce.memory.mb, if the scheduler supports the feature. The value of -1 indicates that this feature is turned off. </td> </tr> <tr> <td><a name="mapred.cluster.max.map.memory.mb">mapred.cluster.max.map.memory.mb</a></td><td>-1</td><td>The maximum size, in terms of virtual memory, of a single map task launched by the Map-Reduce framework, used by the scheduler. A job can ask for multiple slots for a single map task via mapred.job.map.memory.mb, upto the limit specified by mapred.cluster.max.map.memory.mb, if the scheduler supports the feature. The value of -1 indicates that this feature is turned off. </td> </tr> <tr> <td><a name="mapred.cluster.max.reduce.memory.mb">mapred.cluster.max.reduce.memory.mb</a></td><td>-1</td><td>The maximum size, in terms of virtual memory, of a single reduce task launched by the Map-Reduce framework, used by the scheduler. A job can ask for multiple slots for a single reduce task via mapred.job.reduce.memory.mb, upto the limit specified by mapred.cluster.max.reduce.memory.mb, if the scheduler supports the feature. The value of -1 indicates that this feature is turned off. </td> </tr> <tr> <td><a name="mapred.job.map.memory.mb">mapred.job.map.memory.mb</a></td><td>-1</td><td>The size, in terms of virtual memory, of a single map task for the job. A job can ask for multiple slots for a single map task, rounded up to the next multiple of mapred.cluster.map.memory.mb and upto the limit specified by mapred.cluster.max.map.memory.mb, if the scheduler supports the feature. The value of -1 indicates that this feature is turned off iff mapred.cluster.map.memory.mb is also turned off (-1). </td> </tr> <tr> <td><a name="mapred.job.reduce.memory.mb">mapred.job.reduce.memory.mb</a></td><td>-1</td><td>The size, in terms of virtual memory, of a single reduce task for the job. A job can ask for multiple slots for a single map task, rounded up to the next multiple of mapred.cluster.reduce.memory.mb and upto the limit specified by mapred.cluster.max.reduce.memory.mb, if the scheduler supports the feature. The value of -1 indicates that this feature is turned off iff mapred.cluster.reduce.memory.mb is also turned off (-1). </td> </tr> <tr> <td><a name="mapred.child.tmp">mapred.child.tmp</a></td><td>./tmp</td><td> To set the value of tmp directory for map and reduce tasks. If the value is an absolute path, it is directly assigned. Otherwise, it is prepended with task's working directory. The java tasks are executed with option -Djava.io.tmpdir='the absolute path of the tmp dir'. Pipes and streaming are set with environment variable, TMPDIR='the absolute path of the tmp dir' </td> </tr> <tr> <td><a name="mapred.inmem.merge.threshold">mapred.inmem.merge.threshold</a></td><td>1000</td><td>The threshold, in terms of the number of files for the in-memory merge process. When we accumulate threshold number of files we initiate the in-memory merge and spill to disk. A value of 0 or less than 0 indicates we want to DON'T have any threshold and instead depend only on the ramfs's memory consumption to trigger the merge. </td> </tr> <tr> <td><a name="mapred.job.shuffle.merge.percent">mapred.job.shuffle.merge.percent</a></td><td>0.66</td><td>The usage threshold at which an in-memory merge will be initiated, expressed as a percentage of the total memory allocated to storing in-memory map outputs, as defined by mapred.job.shuffle.input.buffer.percent. </td> </tr> <tr> <td><a name="mapred.job.shuffle.input.buffer.percent">mapred.job.shuffle.input.buffer.percent</a></td><td>0.70</td><td>The percentage of memory to be allocated from the maximum heap size to storing map outputs during the shuffle. </td> </tr> <tr> <td><a name="mapred.job.reduce.input.buffer.percent">mapred.job.reduce.input.buffer.percent</a></td><td>0.0</td><td>The percentage of memory- relative to the maximum heap size- to retain map outputs during the reduce. When the shuffle is concluded, any remaining map outputs in memory must consume less than this threshold before the reduce can begin. </td> </tr> <tr> <td><a name="mapred.map.tasks.speculative.execution">mapred.map.tasks.speculative.execution</a></td><td>true</td><td>If true, then multiple instances of some map tasks may be executed in parallel.</td> </tr> <tr> <td><a name="mapred.reduce.tasks.speculative.execution">mapred.reduce.tasks.speculative.execution</a></td><td>true</td><td>If true, then multiple instances of some reduce tasks may be executed in parallel.</td> </tr> <tr> <td><a name="mapred.job.reuse.jvm.num.tasks">mapred.job.reuse.jvm.num.tasks</a></td><td>1</td><td>How many tasks to run per jvm. If set to -1, there is no limit. </td> </tr> <tr> <td><a name="mapred.min.split.size">mapred.min.split.size</a></td><td>0</td><td>The minimum size chunk that map input should be split into. Note that some file formats may have minimum split sizes that take priority over this setting.</td> </tr> <tr> <td><a name="mapred.jobtracker.maxtasks.per.job">mapred.jobtracker.maxtasks.per.job</a></td><td>-1</td><td>The maximum number of tasks for a single job. A value of -1 indicates that there is no maximum. </td> </tr> <tr> <td><a name="mapred.submit.replication">mapred.submit.replication</a></td><td>10</td><td>The replication level for submitted job files. This should be around the square root of the number of nodes. </td> </tr> <tr> <td><a name="mapred.tasktracker.dns.interface">mapred.tasktracker.dns.interface</a></td><td>default</td><td>The name of the Network Interface from which a task tracker should report its IP address. </td> </tr> <tr> <td><a name="mapred.tasktracker.dns.nameserver">mapred.tasktracker.dns.nameserver</a></td><td>default</td><td>The host name or IP address of the name server (DNS) which a TaskTracker should use to determine the host name used by the JobTracker for communication and display purposes. </td> </tr> <tr> <td><a name="tasktracker.http.threads">tasktracker.http.threads</a></td><td>40</td><td>The number of worker threads that for the http server. This is used for map output fetching </td> </tr> <tr> <td><a name="mapred.task.tracker.http.address">mapred.task.tracker.http.address</a></td><td>0.0.0.0:50060</td><td> The task tracker http server address and port. If the port is 0 then the server will start on a free port. </td> </tr> <tr> <td><a name="keep.failed.task.files">keep.failed.task.files</a></td><td>false</td><td>Should the files for failed tasks be kept. This should only be used on jobs that are failing, because the storage is never reclaimed. It also prevents the map outputs from being erased from the reduce directory as they are consumed.</td> </tr> <tr> <td><a name="mapred.output.compress">mapred.output.compress</a></td><td>false</td><td>Should the job outputs be compressed? </td> </tr> <tr> <td><a name="mapred.output.compression.type">mapred.output.compression.type</a></td><td>RECORD</td><td>If the job outputs are to compressed as SequenceFiles, how should they be compressed? Should be one of NONE, RECORD or BLOCK. </td> </tr> <tr> <td><a name="mapred.output.compression.codec">mapred.output.compression.codec</a></td><td>org.apache.hadoop.io.compress.DefaultCodec</td><td>If the job outputs are compressed, how should they be compressed? </td> </tr> <tr> <td><a name="mapred.compress.map.output">mapred.compress.map.output</a></td><td>false</td><td>Should the outputs of the maps be compressed before being sent across the network. Uses SequenceFile compression. </td> </tr> <tr> <td><a name="mapred.map.output.compression.codec">mapred.map.output.compression.codec</a></td><td>org.apache.hadoop.io.compress.DefaultCodec</td><td>If the map outputs are compressed, how should they be compressed? </td> </tr> <tr> <td><a name="map.sort.class">map.sort.class</a></td><td>org.apache.hadoop.util.QuickSort</td><td>The default sort class for sorting keys. </td> </tr> <tr> <td><a name="mapred.userlog.limit.kb">mapred.userlog.limit.kb</a></td><td>0</td><td>The maximum size of user-logs of each task in KB. 0 disables the cap. </td> </tr> <tr> <td><a name="mapred.userlog.retain.hours">mapred.userlog.retain.hours</a></td><td>24</td><td>The maximum time, in hours, for which the user-logs are to be retained after the job completion. </td> </tr> <tr> <td><a name="mapred.user.jobconf.limit">mapred.user.jobconf.limit</a></td><td>5242880</td><td>The maximum allowed size of the user jobconf. The default is set to 5 MB</td> </tr> <tr> <td><a name="mapred.hosts">mapred.hosts</a></td><td></td><td>Names a file that contains the list of nodes that may connect to the jobtracker. If the value is empty, all hosts are permitted.</td> </tr> <tr> <td><a name="mapred.hosts.exclude">mapred.hosts.exclude</a></td><td></td><td>Names a file that contains the list of hosts that should be excluded by the jobtracker. If the value is empty, no hosts are excluded.</td> </tr> <tr> <td><a name="mapred.heartbeats.in.second">mapred.heartbeats.in.second</a></td><td>100</td><td>Expert: Approximate number of heart-beats that could arrive at JobTracker in a second. Assuming each RPC can be processed in 10msec, the default value is made 100 RPCs in a second. </td> </tr> <tr> <td><a name="mapred.max.tracker.blacklists">mapred.max.tracker.blacklists</a></td><td>4</td><td>The number of blacklists for a taskTracker by various jobs after which the task tracker could be blacklisted across all jobs. The tracker will be given a tasks later (after a day). The tracker will become a healthy tracker after a restart. </td> </tr> <tr> <td><a name="mapred.max.tracker.failures">mapred.max.tracker.failures</a></td><td>4</td><td>The number of task-failures on a tasktracker of a given job after which new tasks of that job aren't assigned to it. </td> </tr> <tr> <td><a name="jobclient.output.filter">jobclient.output.filter</a></td><td>FAILED</td><td>The filter for controlling the output of the task's userlogs sent to the console of the JobClient. The permissible options are: NONE, KILLED, FAILED, SUCCEEDED and ALL. </td> </tr> <tr> <td><a name="jobclient.completion.poll.interval">jobclient.completion.poll.interval</a></td><td>5000</td><td>The interval (in milliseconds) between which the JobClient polls the JobTracker for updates about job status. You may want to set this to a lower value to make tests run faster on a single node system. Adjusting this value in production may lead to unwanted client-server traffic. </td> </tr> <tr> <td><a name="jobclient.progress.monitor.poll.interval">jobclient.progress.monitor.poll.interval</a></td><td>1000</td><td>The interval (in milliseconds) between which the JobClient reports status to the console and checks for job completion. You may want to set this to a lower value to make tests run faster on a single node system. Adjusting this value in production may lead to unwanted client-server traffic. </td> </tr> <tr> <td><a name="mapred.job.tracker.persist.jobstatus.active">mapred.job.tracker.persist.jobstatus.active</a></td><td>false</td><td>Indicates if persistency of job status information is active or not. </td> </tr> <tr> <td><a name="mapred.job.tracker.persist.jobstatus.hours">mapred.job.tracker.persist.jobstatus.hours</a></td><td>0</td><td>The number of hours job status information is persisted in DFS. The job status information will be available after it drops of the memory queue and between jobtracker restarts. With a zero value the job status information is not persisted at all in DFS. </td> </tr> <tr> <td><a name="mapred.job.tracker.persist.jobstatus.dir">mapred.job.tracker.persist.jobstatus.dir</a></td><td>/jobtracker/jobsInfo</td><td>The directory where the job status information is persisted in a file system to be available after it drops of the memory queue and between jobtracker restarts. </td> </tr> <tr> <td><a name="mapreduce.job.complete.cancel.delegation.tokens">mapreduce.job.complete.cancel.delegation.tokens</a></td><td>true</td><td> if false - do not unregister/cancel delegation tokens from renewal, because same tokens may be used by spawned jobs </td> </tr> <tr> <td><a name="mapred.task.profile">mapred.task.profile</a></td><td>false</td><td>To set whether the system should collect profiler information for some of the tasks in this job? The information is stored in the user log directory. The value is "true" if task profiling is enabled.</td> </tr> <tr> <td><a name="mapred.task.profile.maps">mapred.task.profile.maps</a></td><td>0-2</td><td> To set the ranges of map tasks to profile. mapred.task.profile has to be set to true for the value to be accounted. </td> </tr> <tr> <td><a name="mapred.task.profile.reduces">mapred.task.profile.reduces</a></td><td>0-2</td><td> To set the ranges of reduce tasks to profile. mapred.task.profile has to be set to true for the value to be accounted. </td> </tr> <tr> <td><a name="mapred.line.input.format.linespermap">mapred.line.input.format.linespermap</a></td><td>1</td><td> Number of lines per split in NLineInputFormat. </td> </tr> <tr> <td><a name="mapred.skip.attempts.to.start.skipping">mapred.skip.attempts.to.start.skipping</a></td><td>2</td><td> The number of Task attempts AFTER which skip mode will be kicked off. When skip mode is kicked off, the tasks reports the range of records which it will process next, to the TaskTracker. So that on failures, TT knows which ones are possibly the bad records. On further executions, those are skipped. </td> </tr> <tr> <td><a name="mapred.skip.map.auto.incr.proc.count">mapred.skip.map.auto.incr.proc.count</a></td><td>true</td><td> The flag which if set to true, SkipBadRecords.COUNTER_MAP_PROCESSED_RECORDS is incremented by MapRunner after invoking the map function. This value must be set to false for applications which process the records asynchronously or buffer the input records. For example streaming. In such cases applications should increment this counter on their own. </td> </tr> <tr> <td><a name="mapred.skip.reduce.auto.incr.proc.count">mapred.skip.reduce.auto.incr.proc.count</a></td><td>true</td><td> The flag which if set to true, SkipBadRecords.COUNTER_REDUCE_PROCESSED_GROUPS is incremented by framework after invoking the reduce function. This value must be set to false for applications which process the records asynchronously or buffer the input records. For example streaming. In such cases applications should increment this counter on their own. </td> </tr> <tr> <td><a name="mapred.skip.out.dir">mapred.skip.out.dir</a></td><td></td><td> If no value is specified here, the skipped records are written to the output directory at _logs/skip. User can stop writing skipped records by giving the value "none". </td> </tr> <tr> <td><a name="mapred.skip.map.max.skip.records">mapred.skip.map.max.skip.records</a></td><td>0</td><td> The number of acceptable skip records surrounding the bad record PER bad record in mapper. The number includes the bad record as well. To turn the feature of detection/skipping of bad records off, set the value to 0. The framework tries to narrow down the skipped range by retrying until this threshold is met OR all attempts get exhausted for this task. Set the value to Long.MAX_VALUE to indicate that framework need not try to narrow down. Whatever records(depends on application) get skipped are acceptable. </td> </tr> <tr> <td><a name="mapred.skip.reduce.max.skip.groups">mapred.skip.reduce.max.skip.groups</a></td><td>0</td><td> The number of acceptable skip groups surrounding the bad group PER bad group in reducer. The number includes the bad group as well. To turn the feature of detection/skipping of bad groups off, set the value to 0. The framework tries to narrow down the skipped range by retrying until this threshold is met OR all attempts get exhausted for this task. Set the value to Long.MAX_VALUE to indicate that framework need not try to narrow down. Whatever groups(depends on application) get skipped are acceptable. </td> </tr> <tr> <td><a name="job.end.retry.attempts">job.end.retry.attempts</a></td><td>0</td><td>Indicates how many times hadoop should attempt to contact the notification URL </td> </tr> <tr> <td><a name="job.end.retry.interval">job.end.retry.interval</a></td><td>30000</td><td>Indicates time in milliseconds between notification URL retry calls</td> </tr> <tr> <td><a name="hadoop.rpc.socket.factory.class.JobSubmissionProtocol">hadoop.rpc.socket.factory.class.JobSubmissionProtocol</a></td><td></td><td> SocketFactory to use to connect to a Map/Reduce master (JobTracker). If null or empty, then use hadoop.rpc.socket.class.default. </td> </tr> <tr> <td><a name="mapred.task.cache.levels">mapred.task.cache.levels</a></td><td>2</td><td> This is the max level of the task cache. For example, if the level is 2, the tasks cached are at the host level and at the rack level. </td> </tr> <tr> <td><a name="mapred.queue.names">mapred.queue.names</a></td><td>default</td><td> Comma separated list of queues configured for this jobtracker. Jobs are added to queues and schedulers can configure different scheduling properties for the various queues. To configure a property for a queue, the name of the queue must match the name specified in this value. Queue properties that are common to all schedulers are configured here with the naming convention, mapred.queue.$QUEUE-NAME.$PROPERTY-NAME, for e.g. mapred.queue.default.submit-job-acl. The number of queues configured in this parameter could depend on the type of scheduler being used, as specified in mapred.jobtracker.taskScheduler. For example, the JobQueueTaskScheduler supports only a single queue, which is the default configured here. Before adding more queues, ensure that the scheduler you've configured supports multiple queues. </td> </tr> <tr> <td><a name="mapred.acls.enabled">mapred.acls.enabled</a></td><td>false</td><td> Specifies whether ACLs should be checked for authorization of users for doing various queue and job level operations. ACLs are disabled by default. If enabled, access control checks are made by JobTracker and TaskTracker when requests are made by users for queue operations like submit job to a queue and kill a job in the queue and job operations like viewing the job-details (See mapreduce.job.acl-view-job) or for modifying the job (See mapreduce.job.acl-modify-job) using Map/Reduce APIs, RPCs or via the console and web user interfaces. </td> </tr> <tr> <td><a name="mapred.queue.default.state">mapred.queue.default.state</a></td><td>RUNNING</td><td> This values defines the state , default queue is in. the values can be either "STOPPED" or "RUNNING" This value can be changed at runtime. </td> </tr> <tr> <td><a name="mapred.job.queue.name">mapred.job.queue.name</a></td><td>default</td><td> Queue to which a job is submitted. This must match one of the queues defined in mapred.queue.names for the system. Also, the ACL setup for the queue must allow the current user to submit a job to the queue. Before specifying a queue, ensure that the system is configured with the queue, and access is allowed for submitting jobs to the queue. </td> </tr> <tr> <td><a name="mapreduce.job.acl-modify-job">mapreduce.job.acl-modify-job</a></td><td> </td><td> Job specific access-control list for 'modifying' the job. It is only used if authorization is enabled in Map/Reduce by setting the configuration property mapred.acls.enabled to true. This specifies the list of users and/or groups who can do modification operations on the job. For specifying a list of users and groups the format to use is "user1,user2 group1,group". If set to '*', it allows all users/groups to modify this job. If set to ' '(i.e. space), it allows none. This configuration is used to guard all the modifications with respect to this job and takes care of all the following operations: o killing this job o killing a task of this job, failing a task of this job o setting the priority of this job Each of these operations are also protected by the per-queue level ACL "acl-administer-jobs" configured via mapred-queues.xml. So a caller should have the authorization to satisfy either the queue-level ACL or the job-level ACL. Irrespective of this ACL configuration, job-owner, the user who started the cluster, cluster administrators configured via mapreduce.cluster.administrators and queue administrators of the queue to which this job is submitted to configured via mapred.queue.queue-name.acl-administer-jobs in mapred-queue-acls.xml can do all the modification operations on a job. By default, nobody else besides job-owner, the user who started the cluster, cluster administrators and queue administrators can perform modification operations on a job. </td> </tr> <tr> <td><a name="mapreduce.job.acl-view-job">mapreduce.job.acl-view-job</a></td><td> </td><td> Job specific access-control list for 'viewing' the job. It is only used if authorization is enabled in Map/Reduce by setting the configuration property mapred.acls.enabled to true. This specifies the list of users and/or groups who can view private details about the job. For specifying a list of users and groups the format to use is "user1,user2 group1,group". If set to '*', it allows all users/groups to modify this job. If set to ' '(i.e. space), it allows none. This configuration is used to guard some of the job-views and at present only protects APIs that can return possibly sensitive information of the job-owner like o job-level counters o task-level counters o tasks' diagnostic information o task-logs displayed on the TaskTracker web-UI and o job.xml showed by the JobTracker's web-UI Every other piece of information of jobs is still accessible by any other user, for e.g., JobStatus, JobProfile, list of jobs in the queue, etc. Irrespective of this ACL configuration, job-owner, the user who started the cluster, cluster administrators configured via mapreduce.cluster.administrators and queue administrators of the queue to which this job is submitted to configured via mapred.queue.queue-name.acl-administer-jobs in mapred-queue-acls.xml can do all the view operations on a job. By default, nobody else besides job-owner, the user who started the cluster, cluster administrators and queue administrators can perform view operations on a job. </td> </tr> <tr> <td><a name="mapred.tasktracker.indexcache.mb">mapred.tasktracker.indexcache.mb</a></td><td>10</td><td> The maximum memory that a task tracker allows for the index cache that is used when serving map outputs to reducers. </td> </tr> <tr> <td><a name="mapred.merge.recordsBeforeProgress">mapred.merge.recordsBeforeProgress</a></td><td>10000</td><td> The number of records to process during merge before sending a progress notification to the TaskTracker. </td> </tr> <tr> <td><a name="mapred.reduce.slowstart.completed.maps">mapred.reduce.slowstart.completed.maps</a></td><td>0.05</td><td>Fraction of the number of maps in the job which should be complete before reduces are scheduled for the job. </td> </tr> <tr> <td><a name="mapred.task.tracker.task-controller">mapred.task.tracker.task-controller</a></td><td>org.apache.hadoop.mapred.DefaultTaskController</td><td>TaskController which is used to launch and manage task execution </td> </tr> <tr> <td><a name="mapreduce.tasktracker.group">mapreduce.tasktracker.group</a></td><td></td><td>Expert: Group to which TaskTracker belongs. If LinuxTaskController is configured via mapreduce.tasktracker.taskcontroller, the group owner of the task-controller binary should be same as this group. </td> </tr> <tr> <td><a name="mapred.disk.healthChecker.interval">mapred.disk.healthChecker.interval</a></td><td>60000</td><td>How often the TaskTracker checks the health of its local directories. Configuring this to a value smaller than the heartbeat interval is equivalent to setting this to heartbeat interval value. </td> </tr> <tr> <td><a name="mapred.healthChecker.script.path">mapred.healthChecker.script.path</a></td><td></td><td>Absolute path to the script which is periodicallyrun by the node health monitoring service to determine if the node is healthy or not. If the value of this key is empty or the file does not exist in the location configured here, the node health monitoring service is not started.</td> </tr> <tr> <td><a name="mapred.healthChecker.interval">mapred.healthChecker.interval</a></td><td>60000</td><td>Frequency of the node health script to be run, in milliseconds</td> </tr> <tr> <td><a name="mapred.healthChecker.script.timeout">mapred.healthChecker.script.timeout</a></td><td>600000</td><td>Time after node health script should be killed if unresponsive and considered that the script has failed.</td> </tr> <tr> <td><a name="mapred.healthChecker.script.args">mapred.healthChecker.script.args</a></td><td></td><td>List of arguments which are to be passed to node health script when it is being launched comma seperated. </td> </tr> <tr> <td><a name="mapreduce.job.counters.limit">mapreduce.job.counters.limit</a></td><td>120</td><td>Limit on the number of counters allowed per job. </td> </tr> </table> </body> </html>
{ "content_hash": "c53bfc6041d3e53e861aa717184af756", "timestamp": "", "source": "github", "line_count": 822, "max_line_length": 221, "avg_line_length": 50.92457420924574, "alnum_prop": 0.7224319159101767, "repo_name": "koven2049/hdfs-cloudera-cdh3u3-production", "id": "b91a1a5a27b9be3b32948219636f38d13691af42", "size": "41860", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/mapred-default.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "357798" }, { "name": "C++", "bytes": "456142" }, { "name": "Java", "bytes": "15422691" }, { "name": "JavaScript", "bytes": "59122" }, { "name": "Objective-C", "bytes": "118273" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "140392" }, { "name": "Python", "bytes": "1163804" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "3755838" }, { "name": "Smalltalk", "bytes": "56562" } ], "symlink_target": "" }
/************************************************************************* ** ** ** Description ** ** ** ** The class ParameterSet contains a linked list of GAMMA parameters, ** ** the latter embodied in class SinglePar. Each entry in a Parameter ** ** Set is of type SinglePar, see class SinglePar. ** ** ** *************************************************************************/ #ifndef ParameterSet_cc // Is this file included? # define ParameterSet_cc 1 // If not, then remember it # if defined(GAMPRAGMA) // Using the GNU compiler? # pragma implementation // Then this is the implementaion # endif #include <GamGen.h> // Include OS specific stuff #include <Basics/ParamSet.h> // Include the implementation #include <Basics/Gutils.h> // Include GAMMA error handling #include <Basics/StringCut.h> // Include Gdec function #include <Basics/SinglePar.h> // Include single parameters #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string> // Include libstdc++ strings #include <iostream> // Include io streams (cout) #include <list> // Include STL list class #include <fstream> // Include libstdc++ filestreams #include <vector> // Include STL vector class using std::string; // Using libstdc++ strings using std::list; // Using libstdc++ STL lists using std::vector; // Using libstdc++ STL vectors using std::ostream; // Using libstdc++ output streams using std::endl; // Using libstdc++ line ends // ---------------------------------------------------------------------------- // --------------------------- PRIVATE FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // i PARAMETER SET ERROR FUNCTIONS // ____________________________________________________________________________ /* Input pset : Parameter set (this) eidx : Error index noret : Flag for linefeed (0=linefeed) pname : Added error message for output Output none : Error message output Program execution stopped if fatal The following error messages use the defaults set in the Gutils package Case Error Message (0) Program Aborting..... (1) Problems With Input File Stream (2) Problems With Output File Stream default Unknown Error */ void ParameterSet::Perror(int eidx, int noret) const { string hdr("Parameter Set"); switch(eidx) { case 3: GAMMAerror(hdr, "Cannot Read Parameters From Input", noret);// (3) break; case 4: GAMMAerror(hdr, "Cannot Write Parameters To Output", noret);// (4) break; case 5: GAMMAerror(hdr, "Cannot Fill With Any Parameters", noret);// (5) break; default: GAMMAerror(hdr, eidx, noret); break;// Usually Unknown Error (-1) } } void ParameterSet::Perror(int eidx, const string& pname, int noret) const { string hdr("Parameter Set"); switch(eidx) { case 1: GAMMAerror(hdr, 1, pname, noret); break; // File Problems (1) default: GAMMAerror(hdr, -1, pname, noret); break; // Unknown Error (-1) } } volatile void ParameterSet::Pfatality(int eidx) const { Perror(eidx, 1); // First output the error if(eidx) Perror(0); // Now output that its fatal GAMMAfatal(); // Clean exit from program } // ---------------------------------------------------------------------------- // ---------------------------- PUBLIC FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // A PARAMETER SET CONSTRUCTORS/ASSIGNMENTS/DESTRUCTOR // ____________________________________________________________________________ /* These functions are inherited from the ANSI standard "list" class in the C++ library libstdc++. I am listing them here so that I & other users don't have to keep looking them up all the time. ParameterSet() Empty Parameter Set ParameterSet(int N) Parameter Set w/ N Parameters ParameterSet(int N, const SinglePar& par) Parameter Set w/ N pars ParameterSet(const ParameterSet& pset) Parameter Set copy of pset ParameterSet assign(N) Assign N element ~ParameterSet() Destructor of Parameter Set */ // ____________________________________________________________________________ // B PARAMETER SET ITERATORS & MEMBER ACCESS // ____________________________________________________________________________ /* These functions are inherited from the ANSI standard "list" class in the C++ library libstdc++. I am listing them here so that I & other users don't have to keep looking them up all the time. list<SinglePar>::iterator ParameterSet::begin() Pointer to 1st element list<SinglePar>::iterator ParameterSet::end() Pointer to last element SinglePar ParameterSet::front() First element SinglePar ParameterSet::back() Last element */ // ____________________________________________________________________________ // C PARAMETER SET LIST & QUEUE OPERATIONS // ____________________________________________________________________________ /* These functions are inherited from the ANSI standard "list" class in the C++ library libstdc++. I am listing them here so that I & other users don't have to keep looking them up all the time. ParameterSet::push_back(const SinglePar& par) Add par to list end ParameterSet::pop_back() Remove par at list end ParameterSet::push_front(const SinglePar& par) Add par to list start ParameterSet::pop_front(const SinglePar& par) Remove par at list start ParameterSet::insert(iterator p, SinglePar& par) Add par before p ParameterSet::erase(iterator p) Remove par at p ParameterSet::clear() Remove all list entries */ // ____________________________________________________________________________ // D PARAMETER SET ADDITIONAL QUEUE OPERATIONS // ____________________________________________________________________________ /* These functions are inherited from the ANSI standard "list" class in the C++ library libstdc++. I am listing them here so that I & other users don't have to keep looking them up all the time. int ParameterSet::size() Number of entries bool ParameterSet::empty() TRUE if pset empty bool ParameterSet::operator==(ParameterSet pset) TRUE if psets equal bool ParameterSet::operator!=(ParameterSet pset) TRUE if psets not equal */ // ____________________________________________________________________________ // E PARAMETER SET AUXILIARY FUNCTIONS // ____________________________________________________________________________ /* These functions are "list" type of functions that have been added to make the list of single parameters (i.e. parameter list) do simple things needed for ready access of single parameters. Function Arguments Result ---------- --------- ----------------------------------------------------- contains string Returns true/false if parameter with name is in pset " SinglePar Returns true/false if single parmeters is in pset seek string Returns iterator in pset for parameter with name " SinglePar Returns iterator in pset for single parameter strip int Returns parameter set with parameters named [#]name countpar string,int Counts contiguous parameters in pset of name name(#) Note that in the function "strip" the returned parameter set contains parameters whos names no longer are prefixed with [#]. */ int ParameterSet::contains(const string& pname) const { return (seek(pname) != end()); } int ParameterSet::contains(const SinglePar& par) const { return contains(par.name()); } ParameterSet::const_iterator ParameterSet::seek(const string& pname) const { SinglePar par; // Working single parameter list<SinglePar>::const_iterator item=begin(); // Begin at input pset start while(item != end()) // and loop over all of its { // parameters par = *(item); // This is a parameter if(pname == par.name()) return item; // Return item is name match item++; // Go to the next Pix } return item; } ParameterSet::const_iterator ParameterSet::seek(const SinglePar& par) const { return seek(par.name()); } ParameterSet ParameterSet::strip(int idx) const { ParameterSet subpset; // The pset to be returned string Nidx=string("[")+Gdec(idx)+string("]"); // Parameter name prefix int len = Nidx.length(); // Prefix length SinglePar par; // Temporary single parameter string pname; // Temporary parameter name list<SinglePar>::const_iterator item=begin(); // Begin at input pset start while(item != end()) // and loop over all of its { // parameters par = *(item); // This is a parameter pname = par.name(); // & this is its name if(!pname.find(Nidx)) // See if name starts with { // [#] where # is idx par.name(pname.substr(len)); // Cut out prefix subpset.push_back(par); // Add it to sub pset } item++; // Go to the next Pix } return subpset; } int ParameterSet::countpar(const string& pnamein, int idx0) { int cnt=0, found=1, fiter; // Set counter to zero string suffi("("); // Suffix start string sufff(")"); // Suffix finish string sidx = suffi + Gdec(idx0) + sufff; // Parameter name index string pname = pnamein + sidx; // Parameter name to look for list<SinglePar>::iterator item; // Item in the parameter set SinglePar par; // Single parameter while(found) // Look for pname in pset { fiter = 0; // Havent found pname yet item = begin(); // Begin at input pset start while((item != end()) && !fiter) // and loop over all of its { // parameters par = *(item); // This is a parameter if(pname == par.name()) // Compare name to sought name fiter++; } if(fiter) // If we found pname then { // we'll update the counter cnt++; // and reset for next pname sidx = suffi + Gdec(idx0+cnt) + sufff; } else found = 0; } return cnt; } // ____________________________________________________________________________ // F PARAMETER SET OUTPUT FUNCTIONS // ____________________________________________________________________________ /* These are functions that output formatted information concerning the Parameter set to a specified output stream of file. The latter function, write, will produce an ASCII file that is self-readable by this class. Input pset : Parameter set (this) ostr : Output ASCII file stream file : ASCII output file (making pset file) warn : Warning level flag for write fail Return void : pset is sent to the output stream int : T/F write to output pset file. */ vector<string> ParameterSet::printStrings() const { vector<string> PStrings; // Strings for parameters int np = int(size()); // # of parameters if(!np) return PStrings; // Nothing if no parameters // Arrays For Strings We Will Oputput string sts[5] = { "Integer", "Double", "String", "Coordinate", "Tensor" }; vector<string> PNs; // For parameter names vector<string> PTs; // For parameter types vector<string> PVs; // For parameter values vector<string> PCs; // For parameter comments vector<int> MaxLens; // For column lengths string pline; // For parameter line // Fill String Arrays & Find Maximum Column Lengths list<SinglePar>::const_iterator i; i = begin(); // Begin at input pset start int k=0; // Temp for array index int maxpn = 0; // Max parameter name length int maxpt = 0; // Max parameter type length int maxpv = 0; // Max parameter value length int maxpc = 0; // Max parameter comment length while(i != end()) // So long as Pix is OK { PNs.push_back((*i).name()); // Store ith parameter name maxpn = gmax(maxpn, int((PNs[k]).length()));// Set maximum name length PTs.push_back(sts[(*i).type()]); // Store ith parameter type maxpt = gmax(maxpt, int((PTs[k]).length()));// Set maximum value length PVs.push_back((*i).data()); // Store ith parameter value maxpv = gmax(maxpv, int((PVs[k]).length()));// Set maximum value length PCs.push_back((*i).state()); // Store ith parameter comment maxpc = gmax(maxpc, int((PCs[k]).length()));// Set maximum comment length i++; // Get next Pix k++; } MaxLens.push_back(gmin(maxpn, 20)); MaxLens.push_back(maxpt); MaxLens.push_back(gmin(maxpv, 30)); MaxLens.push_back(gmin(maxpc, 50)); // Set Up Column Headers To Use // Their Widths Are Adjusted To Handle Parameters In Set vector<string> chdrs; chdrs.push_back("Name"); // 1st column header chdrs.push_back("Type"); // 2nd column header chdrs.push_back("Value"); // 3rd column header chdrs.push_back("Comment"); // 4th column header int nc = int(chdrs.size()); // Number of columns string tmp; int tl; for(k=0; k<nc; k++) { tl = chdrs[k].length(); if(tl < MaxLens[k]) { tmp = string((MaxLens[k]-tl)/2, ' '); tmp += chdrs[k]; tmp += string(MaxLens[k]-tmp.length(), ' '); chdrs[k] = tmp; } } // Set Column Header Strings int cspcl = 2; // Spacing between columns string cspc(cspcl, ' ' ); // For spacing between cols int ll = -cspcl; // Total line length for(k=0; k<nc; k++) // Get total line length { ll+= chdrs[k].length() + cspcl; } string spc(40-ll/2, ' '); // Spacer to center line pline = spc; // Space to 1st column start for(k=0; k<nc; k++) // Loop columns and add { pline += chdrs[k]; // Add the column title if(k<nc-1) pline += cspc; // Space to next column } PStrings.push_back(pline); // Store title header pline = spc; // Space to 1st column start for(k=0; k<nc; k++) // Loop columns and output { pline += string(chdrs[k].length(), '-'); if(k<nc-1) pline += cspc; } PStrings.push_back(pline); // Store header underlines // Make And Store Strings For Each Parameter // (Each String Will Be A Line Containing Parameter Info) int ml; for(k=0; k<np; k++) // Loop over all parameters { pline = spc; // Space to 1st column start pline += PNs[k]; // Set parameter name tl = PNs[k].length(); // Length of name ml = MaxLens[0]; // Length of column if(tl<ml) pline += string(ml-tl, ' '); // Space to end of column pline += cspc; // Space to next column pline += PTs[k]; // Set parameter type tl = PTs[k].length(); // Length of name ml = MaxLens[1]; // Length of column if(tl<ml) pline += string(ml-tl, ' '); // Space to end of column pline += cspc; // Space to next column pline += PVs[k]; // Set parameter value tl = PVs[k].length(); // Length of name ml = MaxLens[2]; // Length of column if(tl<ml) pline += string(ml-tl, ' ');// Space to end of column pline += cspc; // Space to next column pline += PCs[k]; // Set parameter comment PStrings.push_back(pline); // Store parameter string } return PStrings; } ostream& ParameterSet::print(ostream& ostr) const { // Output Header (All If Empty Parameter Set) string hdr("Parameter Set"); // Basic header int hl; // Header length int np = int(size()); // # of parameters if(!np) // This if no parameters { // Header is centered hdr = "Empty " + hdr; hl = hdr.length(); ostr << "\n" << string(40-hl/2, ' ') << hdr; return ostr; } hl = hdr.length(); // This if parameters ostr << "\n" << string(40-hl/2, ' ') // Header is centered << hdr; ostr << endl; vector<string> PStrings; // Array of strings to print PStrings = printStrings(); // Get our print strings unsigned ns = PStrings.size(); // No. of strings to print for(unsigned i=0; i<ns; i++) // Loop over strings and send ostr << PStrings[i] << endl; // to our string stream ostr << endl; // Another line feed return ostr; // Return the output stream } ostream& operator<< (ostream& ostr, const ParameterSet& pset) { return pset.print(ostr); } bool ParameterSet::write(const string &fileout, int warn) const { std::ofstream ofstr(fileout.c_str()); // Open fileout for output int w2 = 0; // Warning level for next call if(warn) w2 = 1; // Use level 1 warning if(!write(ofstr, w2)) { if(warn) Perror(1,fileout,1); // Problems with output file if(warn==1) Perror(4); // Can't write parameters out else Pfatality(4); // with out without die return false; } return true; } bool ParameterSet::write(std::ofstream& ofstr, int warn) const { if(!ofstr.good()) // If file bad then exit { if(warn) { Perror(2, 1); // Output filestream problems if(warn==1) Perror(4); // Can't write parameters out else Pfatality(4); // with out without die } return false; } list<SinglePar>::const_iterator i=begin(); // Begin at input pset start while(i != end()) { (*i).write(ofstr); i++; } return true; } // ____________________________________________________________________________ // G PARAMETER SET INPUT FUNCTIONS // ____________________________________________________________________________ // ---------------------------------------------------------------------------- // Direct Read of Parameter Set From An ASCII File Or Input Stream // ---------------------------------------------------------------------------- // Input pset : Parameter set (this) // filein : Input filename // Or inp : Input filestream // fflag : Flag for fatal warnings. // 0 : No error messages // 1 : Non-fatal messages // else : Messages, stop execution // Output int : True if file filein or input stream // inp has been scanned for parameters. // Note : Parameter set filled with parameters // read from the input file filein // or input file stream inp bool ParameterSet::read(const string &filein, int fflag) { std::ifstream inp(filein.c_str()); // Open filename for input if(!read(inp, fflag?1:0)) // Use overloaded function { if(fflag) // Output any error messages { // as desired via fflag Perror(1,filein,1); // Problems with file (fflag>1)?Pfatality(5):Perror(5,0); // Can't read pset } return false; } inp.close(); // Close the input file return true; // Return we succeeded } bool ParameterSet::read(std::ifstream& inp, int fflag) { clear(); // Clear any existing parameters if(!inp) // If file bad then exit { if(fflag) // Output any error messages { // as desired via fflag Perror(1, 1); // Problems with input stream (fflag>1)?Pfatality(3):Perror(3,1); // Can't read pset } return false; // Exit that we failed } SinglePar par; // Here's a single parameter int fend; while(!inp.eof()) // While successfully reading { // look for valid parameters fend = par.read(inp); // Try & read a parameter if(fend>0 && !contains(par)) push_back(par);// Add to list if good & unique } return true; } // ____________________________________________________________________________ // H PARAMETER SET INTERACTIVE FUNCTIONS // ____________________________________________________________________________ // Input pset : Parameter set (this) // argc : Number of arguments // argv : Vector of argc arguments // argn : Argument index // Output filename: The parameter argn of array argc // is used to supply a filename // from which the parameter set is read // If the argument argn is not in argv, // the user is asked to supply a filename // The filename is returned // Note : The file should be an ASCII file // containing recognized sys parameters // Note : The parameter set is modifed (filled) string ParameterSet::ask_read(int argc, char* argv[], int argn) { string fn; // Name of spin system file query_parameter(argc, argv, argn, // Get filename from command "\n\tASCII Parameter Set filename? ",fn);// Or ask for it read(fn); // Read system from filename return fn; // Give back the filename } // ------------------------------------------------------------------------- // Parameter Value Functions // ------------------------------------------------------------------------- // Input pset : Parameter set (this) // name : Name of parameter desired // value : Value of parameter desired // Output TF : True if parameter named "name" exists // in pset and sucessfully parsed as // an integer, value set to param. value bool ParameterSet::getParameter(const string& name, string& value) const { return getString(name,value); } bool ParameterSet::getParameter(const string& name, int& value) const { return getInt(name,value); } bool ParameterSet::getParameter(const string& name, double& value) const { return getDouble(name,value); } bool ParameterSet::getString(const string& name, string& value) const { list<SinglePar>::const_iterator item; // Pix into pset item = seek(name); // See if parameter in pset if(item == end()) return false; // If not just bail if((*(item)).type() != 2) return false; // Insure its a string value = (*(item)).data(); // Set value to parameter data return value.length()?true:false; // Fail only if no data } bool ParameterSet::getInt(const string& name, int& value) const { list<SinglePar>::const_iterator item; // Pix into pset item = seek(name); // See if parameter in pset if(item == end()) return false; // If not just bail if((*(item)).type() != 0) return false; // Insure its an integer string sval = (*(item)).data(); // Get value of parameter data if(!sval.length()) return false; // Fail only if no data value = atoi(sval.c_str()); // Convert to integer return true; } bool ParameterSet::getDouble(const string& name, double& value) const { list<SinglePar>::const_iterator item; // Pix into pset item = seek(name); // See if parameter in pset if(item == end()) return false; // If not just bail if((*(item)).type() != 1) return false; // Insure its a double string sval = (*(item)).data(); // Get value of parameter data if(!sval.length()) return false; // Fail only if no data value = atof(sval.c_str()); // Convert to integer return true; } #endif // ParamSet.cc
{ "content_hash": "5a5cfa5a863a671ab284d431ddf1b2c5", "timestamp": "", "source": "github", "line_count": 606, "max_line_length": 80, "avg_line_length": 41.49009900990099, "alnum_prop": 0.5211788569383129, "repo_name": "tesch1/GAMMA", "id": "800ef4ee72ec1f3caa48c16aa239602084170aad", "size": "25940", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Basics/ParamSet.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "923133" }, { "name": "C++", "bytes": "11254062" }, { "name": "M", "bytes": "693" }, { "name": "Makefile", "bytes": "539168" }, { "name": "Matlab", "bytes": "4779" }, { "name": "Objective-C", "bytes": "9244" }, { "name": "Python", "bytes": "43687" }, { "name": "Shell", "bytes": "41354" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Wed May 26 22:29:58 EDT 2004 --> <TITLE> gravity (Gravity Framework (Version 1.0-beta-1)) </TITLE> <META NAME="keywords" CONTENT="gravity package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> </HEAD> <SCRIPT> function asd() { parent.document.title="gravity (Gravity Framework (Version 1.0-beta-1))"; } </SCRIPT> <BODY BGCOLOR="white" onload="asd();"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../gravity/package-summary.html" TARGET="classFrame">gravity</A></FONT> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="Component.html" TARGET="classFrame"><I>Component</I></A> <BR> <A HREF="ComponentInvocationHandler.html" TARGET="classFrame"><I>ComponentInvocationHandler</I></A> <BR> <A HREF="ComponentProxy.html" TARGET="classFrame"><I>ComponentProxy</I></A> <BR> <A HREF="ComponentStrategy.html" TARGET="classFrame"><I>ComponentStrategy</I></A> <BR> <A HREF="Container.html" TARGET="classFrame"><I>Container</I></A> <BR> <A HREF="DynamicWeaver.html" TARGET="classFrame"><I>DynamicWeaver</I></A> <BR> <A HREF="MutableContainer.html" TARGET="classFrame"><I>MutableContainer</I></A> <BR> <A HREF="Plugin.html" TARGET="classFrame"><I>Plugin</I></A> <BR> <A HREF="ProxyableComponent.html" TARGET="classFrame"><I>ProxyableComponent</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="ComponentCallback.html" TARGET="classFrame">ComponentCallback</A> <BR> <A HREF="ComponentPhase.html" TARGET="classFrame">ComponentPhase</A> <BR> <A HREF="Gravity.html" TARGET="classFrame">Gravity</A> <BR> <A HREF="Location.html" TARGET="classFrame">Location</A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Exceptions</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="UsageException.html" TARGET="classFrame">UsageException</A> <BR> <A HREF="WrapperException.html" TARGET="classFrame">WrapperException</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
{ "content_hash": "c2384630ec38cb672498b8ce9724fb4d", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 105, "avg_line_length": 29.89873417721519, "alnum_prop": 0.6998306519898391, "repo_name": "harishkswamy/gravity", "id": "a3ac02dda728cc74c37ee3f4fea869f95c143840", "size": "2362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/framework/docs/api/gravity/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2601" }, { "name": "HTML", "bytes": "1827" }, { "name": "Java", "bytes": "326934" }, { "name": "XSLT", "bytes": "921" } ], "symlink_target": "" }
package au.edu.uq.rcc.nimrod.optim.modules; import au.edu.uq.rcc.nimrod.optim.IAlgorithmDefinition; public interface INimrodOKModule { public String getName(); public Author[] getAuthors(); IAlgorithmDefinition[] getAlgorithms(); }
{ "content_hash": "b3bb6fd7435dbb539147d30e76d49be2", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 55, "avg_line_length": 21.083333333333332, "alnum_prop": 0.7351778656126482, "repo_name": "UQ-RCC/nimrodok-interface", "id": "9fd72bd0c7ff3c0c5026da669f860d4650189334", "size": "1436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/au/edu/uq/rcc/nimrod/optim/modules/INimrodOKModule.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "55344" }, { "name": "Shell", "bytes": "357" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ee8d68a0bc8bedc377efbc61b5f30abb", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "c897e88bbff6996de9fde87298fe69385eb30dec", "size": "241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Geraniales/Geraniaceae/Geranium/Geranium thunbergii/ Syn. Geranium nepalense thunbergii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
function Fcn_GUI_INI_TP_Switch_with_without_flame(varargin) hObject = varargin{1}; handles = guidata(hObject); global CI switch CI.CD.isNoFlame case 1 set(handles.pop_HA_style, 'value',1,'enable','off'); set(handles.edit_TD_Tratio, 'value',1,'enable','off'); otherwise set(handles.pop_HA_style, 'enable','on'); set(handles.edit_TD_Tratio, 'enable','on'); end guidata(hObject, handles);
{ "content_hash": "52d6cdff8c9be794d4219eee0aec82a1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 62, "avg_line_length": 33.15384615384615, "alnum_prop": 0.6519721577726219, "repo_name": "MorgansLab/OSCILOS-Long-1-3", "id": "b74dc8e889711eec751217ce54622156b113ac12", "size": "431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "subProgram/GUI_Fcn/Fcn_INI_GUI/Fcn_TP/Fcn_GUI_INI_TP_Switch_with_without_flame.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Matlab", "bytes": "762996" }, { "name": "Mercury", "bytes": "2901" } ], "symlink_target": "" }
Напишете функция average, която приема като аргумент масив и връща средно аритметично на елементите на масива. # Task 2 Напишете функция circleShift, която приема като аргументи масив и число N и отмества елементите на масива N пъти надясно. # Task 3 Напишете функция encode, която приема като аргумент символен низ и кодира съдържанието му като прибавя/изважда число от всеки елемент. Отпечатайте резултата преди и след извикването на функцията. # Task 4 Напишете функция decode, която приема като аргумент символен низ и декодира съдържанието му като прибавя/изважда число от всеки елемент. Отпечатайте резултата преди и след извикването на функцията.
{ "content_hash": "881c87132b6332f662decaaba0a11f7e", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 136, "avg_line_length": 33.2, "alnum_prop": 0.8147590361445783, "repo_name": "Martinski95/FMI_UP_IS_2017_2018", "id": "17e2290a65280d402a15c929787217684de67cf7", "size": "1168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Week_9/tasks.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "19245" } ], "symlink_target": "" }
import * as regex from "../../helpers/regex"; import * as t from "../../../types"; export function shouldVisit(node) { return regex.is(node, "y"); } export function Literal(node) { if (!regex.is(node, "y")) return; return t.newExpression(t.identifier("RegExp"), [ t.literal(node.regex.pattern), t.literal(node.regex.flags) ]); }
{ "content_hash": "e71276e2f4e29b7478220c80c0e81abf", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 50, "avg_line_length": 24.785714285714285, "alnum_prop": 0.6397694524495677, "repo_name": "casser/asx", "id": "3227c59635cb1f2eab073856cb71b32b35df9d6c", "size": "347", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/babel/transformation/transformers/es6/regex.sticky.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "572900" }, { "name": "Makefile", "bytes": "323" } ], "symlink_target": "" }
(function($) { 'use strict'; if (!Function.prototype.bind) { Function.prototype.bind = function(scope) { var fn = this; return function() { return fn.apply(scope); }; }; } var uuid = 0; // Plugin $.fn.redactor = function(options) { var val = []; var args = Array.prototype.slice.call(arguments, 1); if (typeof options === 'string') { this.each(function() { var instance = $.data(this, 'redactor'); var func; if (options.search(/\./) !== '-1') { func = options.split('.'); if (typeof instance[func[0]] !== 'undefined') { func = instance[func[0]][func[1]]; } } else { func = instance[options]; } if (typeof instance !== 'undefined' && $.isFunction(func)) { var methodVal = func.apply(instance, args); if (methodVal !== undefined && methodVal !== instance) { val.push(methodVal); } } else { $.error('No such method "' + options + '" for Redactor'); } }); } else { this.each(function() { $.data(this, 'redactor', {}); $.data(this, 'redactor', Redactor(this, options)); }); } if (val.length === 0) { return this; } else if (val.length === 1) { return val[0]; } else { return val; } }; // Initialization function Redactor(el, options) { return new Redactor.prototype.init(el, options); } // Options $.Redactor = Redactor; $.Redactor.VERSION = '2.4'; $.Redactor.modules = ['air', 'autosave', 'block', 'buffer', 'build', 'button', 'caret', 'clean', 'code', 'core', 'detect', 'dropdown', 'events', 'file', 'focus', 'image', 'indent', 'inline', 'insert', 'keydown', 'keyup', 'lang', 'line', 'link', 'linkify', 'list', 'marker', 'modal', 'observe', 'offset', 'paragraphize', 'paste', 'placeholder', 'progress', 'selection', 'shortcuts', 'storage', 'toolbar', 'upload', 'uploads3', 'utils', 'browser' // deprecated ]; $.Redactor.settings = {}; $.Redactor.opts = { // settings animation: false, lang: 'en', direction: 'ltr', spellcheck: true, overrideStyles: true, scrollTarget: document, focus: false, focusEnd: false, clickToEdit: false, structure: false, tabindex: false, minHeight: false, // string maxHeight: false, // string maxWidth: false, // string plugins: false, // array callbacks: {}, placeholder: false, linkify: true, enterKey: true, pastePlainText: false, pasteImages: true, pasteLinks: true, pasteBlockTags: ['pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'table', 'tbody', 'thead', 'tfoot', 'th', 'tr', 'td', 'ul', 'ol', 'li', 'blockquote', 'p', 'figure', 'figcaption'], pasteInlineTags: ['br', 'strong', 'ins', 'code', 'del', 'span', 'samp', 'kbd', 'sup', 'sub', 'mark', 'var', 'cite', 'small', 'b', 'u', 'em', 'i'], preClass: false, // string preSpaces: 4, // or false tabAsSpaces: false, // true or number of spaces tabKey: true, autosave: false, // false or url autosaveName: false, autosaveFields: false, imageUpload: null, imageUploadParam: 'file', imageUploadFields: false, imageUploadForms: false, imageTag: 'figure', imageEditable: true, imageCaption: true, imagePosition: false, imageResizable: false, imageFloatMargin: '10px', dragImageUpload: true, multipleImageUpload: true, clipboardImageUpload: true, fileUpload: null, fileUploadParam: 'file', fileUploadFields: false, fileUploadForms: false, dragFileUpload: true, s3: false, linkNewTab: false, linkTooltip: true, linkNofollow: false, linkSize: 30, pasteLinkTarget: false, videoContainerClass: 'video-container', toolbar: true, toolbarFixed: true, toolbarFixedTarget: document, toolbarFixedTopOffset: 0, // pixels toolbarExternal: false, // ID selector air: false, airWidth: false, formatting: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], formattingAdd: false, buttons: ['format', 'bold', 'italic', 'deleted', 'lists', 'image', 'file', 'link'], // + 'horizontalrule', 'underline', 'ol', 'ul', 'indent', 'outdent' buttonsHide: [], buttonsHideOnMobile: [], script: true, removeNewlines: false, removeComments: true, replaceTags: { 'b': 'strong', 'i': 'em', 'strike': 'del' }, // shortcuts shortcuts: { 'ctrl+shift+m, meta+shift+m': { func: 'inline.removeFormat' }, 'ctrl+b, meta+b': { func: 'inline.format', params: ['bold'] }, 'ctrl+i, meta+i': { func: 'inline.format', params: ['italic'] }, 'ctrl+h, meta+h': { func: 'inline.format', params: ['superscript'] }, 'ctrl+l, meta+l': { func: 'inline.format', params: ['subscript'] }, 'ctrl+k, meta+k': { func: 'link.show' }, 'ctrl+shift+7': { func: 'list.toggle', params: ['orderedlist'] }, 'ctrl+shift+8': { func: 'list.toggle', params: ['unorderedlist'] } }, shortcutsAdd: false, activeButtons: ['deleted', 'italic', 'bold'], activeButtonsStates: { b: 'bold', strong: 'bold', i: 'italic', em: 'italic', del: 'deleted', strike: 'deleted' }, // private lang langs: { en: { "format": "Format", "image": "Image", "file": "File", "link": "Link", "bold": "Bold", "italic": "Italic", "deleted": "Strikethrough", "underline": "Underline", "bold-abbr": "B", "italic-abbr": "I", "deleted-abbr": "S", "underline-abbr": "U", "lists": "Lists", "link-insert": "Insert link", "link-edit": "Edit link", "link-in-new-tab": "Open link in new tab", "unlink": "Unlink", "cancel": "Cancel", "close": "Close", "insert": "Insert", "save": "Save", "delete": "Delete", "text": "Text", "edit": "Edit", "title": "Title", "paragraph": "Normal text", "quote": "Quote", "code": "Code", "heading1": "Heading 1", "heading2": "Heading 2", "heading3": "Heading 3", "heading4": "Heading 4", "heading5": "Heading 5", "heading6": "Heading 6", "filename": "Name", "optional": "optional", "unorderedlist": "Unordered List", "orderedlist": "Ordered List", "outdent": "Outdent", "indent": "Indent", "horizontalrule": "Line", "upload-label": "Drop file here or ", "caption": "Caption", "bulletslist": "Bullets", "numberslist": "Numbers", "image-position": "Position", "none": "None", "left": "Left", "right": "Right", "center": "Center", "accessibility-help-label": "Rich text editor" } }, // private type: 'textarea', // textarea, div, inline, pre inline: false, buffer: [], rebuffer: [], inlineTags: ['a', 'span', 'strong', 'strike', 'b', 'u', 'em', 'i', 'code', 'del', 'ins', 'samp', 'kbd', 'sup', 'sub', 'mark', 'var', 'cite', 'small'], blockTags: ['pre', 'ul', 'ol', 'li', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'dl', 'dt', 'dd', 'div', 'td', 'blockquote', 'output', 'figcaption', 'figure', 'address', 'section', 'header', 'footer', 'aside', 'article', 'iframe'], paragraphize: true, paragraphizeBlocks: ['table', 'div', 'pre', 'form', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'dl', 'blockquote', 'figcaption', 'address', 'section', 'header', 'footer', 'aside', 'article', 'object', 'style', 'script', 'iframe', 'select', 'input', 'textarea', 'button', 'option', 'map', 'area', 'math', 'hr', 'fieldset', 'legend', 'hgroup', 'nav', 'figure', 'details', 'menu', 'summary', 'p'], emptyHtml: '<p>&#x200b;</p>', invisibleSpace: '&#x200b;', emptyHtmlRendered: $('').html('​').html(), imageTypes: ['image/png', 'image/jpeg', 'image/gif'], userAgent: navigator.userAgent.toLowerCase(), observe: { dropdowns: [] }, regexps: { linkyoutube: /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w.\-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig, linkvimeo: /https?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/, linkimage: /((https?|www)[^\s]+\.)(jpe?g|png|gif)(\?[^\s-]+)?/ig, url: /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/ig } }; // Functionality Redactor.fn = $.Redactor.prototype = { keyCode: { BACKSPACE: 8, DELETE: 46, UP: 38, DOWN: 40, ENTER: 13, SPACE: 32, ESC: 27, TAB: 9, CTRL: 17, META: 91, SHIFT: 16, ALT: 18, RIGHT: 39, LEFT: 37, LEFT_WIN: 91 }, // =init init: function(el, options) { this.$element = $(el); this.uuid = uuid++; this.loadOptions(options); this.loadModules(); // click to edit if (this.opts.clickToEdit && !this.$element.hasClass('redactor-click-to-edit')) { return this.loadToEdit(options); } else if (this.$element.hasClass('redactor-click-to-edit')) { this.$element.removeClass('redactor-click-to-edit'); } // block & inline test tag regexp this.reIsBlock = new RegExp('^(' + this.opts.blockTags.join('|' ).toUpperCase() + ')$', 'i'); this.reIsInline = new RegExp('^(' + this.opts.inlineTags.join('|' ).toUpperCase() + ')$', 'i'); // set up drag upload this.opts.dragImageUpload = (this.opts.imageUpload === null) ? false : this.opts.dragImageUpload; this.opts.dragFileUpload = (this.opts.fileUpload === null) ? false : this.opts.dragFileUpload; // formatting storage this.formatting = {}; // load lang this.lang.load(); // extend shortcuts $.extend(this.opts.shortcuts, this.opts.shortcutsAdd); // set editor this.$editor = this.$element; // detect type of editor this.detectType(); // start callback this.core.callback('start'); this.core.callback('startToEdit'); // build this.start = true; this.build.start(); }, detectType: function() { if (this.build.isInline() || this.opts.inline) { this.opts.type = 'inline'; } else if (this.build.isTag('DIV')) { this.opts.type = 'div'; } else if (this.build.isTag('PRE')) { this.opts.type = 'pre'; } }, loadToEdit: function(options) { this.$element.on('click.redactor-click-to-edit', $.proxy(function() { this.initToEdit(options); }, this)); this.$element.addClass('redactor-click-to-edit'); return; }, initToEdit: function(options) { $.extend(options.callbacks, { startToEdit: function() { this.insert.node(this.marker.get(), false); }, initToEdit: function() { this.selection.restore(); this.clickToCancelStorage = this.code.get(); // cancel $(this.opts.clickToCancel).off('.redactor-click-to-edit'); $(this.opts.clickToCancel).show().on('click.redactor-click-to-edit', $.proxy(function(e) { e.preventDefault(); this.core.destroy(); this.events.syncFire = false; this.$element.html(this.clickToCancelStorage); this.core.callback('cancel', this.clickToCancelStorage); this.events.syncFire = true; this.clickToCancelStorage = ''; $(this.opts.clickToCancel).hide(); $(this.opts.clickToSave).hide(); this.$element.on('click.redactor-click-to-edit', $.proxy(function() { this.initToEdit(options); }, this)); this.$element.addClass('redactor-click-to-edit'); }, this)); // save $(this.opts.clickToSave).off('.redactor-click-to-edit'); $(this.opts.clickToSave).show().on('click.redactor-click-to-edit', $.proxy(function(e) { e.preventDefault(); this.core.destroy(); this.core.callback('save', this.code.get()); $(this.opts.clickToCancel).hide(); $(this.opts.clickToSave).hide(); this.$element.on('click.redactor-click-to-edit', $.proxy(function() { this.initToEdit(options); }, this)); this.$element.addClass('redactor-click-to-edit'); }, this)); } }); this.$element.redactor(options); this.$element.off('.redactor-click-to-edit'); }, loadOptions: function(options) { var settings = {}; // check namespace if (typeof $.Redactor.settings.namespace !== 'undefined') { if (this.$element.hasClass($.Redactor.settings.namespace)) { settings = $.Redactor.settings; } } else { settings = $.Redactor.settings; } this.opts = $.extend( {}, $.Redactor.opts, this.$element.data(), options ); this.opts = $.extend(true, this.opts, settings); }, getModuleMethods: function(object) { return Object.getOwnPropertyNames(object).filter(function(property) { return typeof object[property] === 'function'; }); }, loadModules: function() { var len = $.Redactor.modules.length; for (var i = 0; i < len; i++) { this.bindModuleMethods($.Redactor.modules[i]); } }, bindModuleMethods: function(module) { if (typeof this[module] === 'undefined') { return; } // init module this[module] = this[module](); var methods = this.getModuleMethods(this[module]); var len = methods.length; // bind methods for (var z = 0; z < len; z++) { this[module][methods[z]] = this[module][methods[z]].bind(this); } }, // =air air: function() { return { enabled: false, collapsed: function() { if (this.opts.air) { this.selection.get().collapseToStart(); } }, collapsedEnd: function() { if (this.opts.air) { this.selection.get().collapseToEnd(); } }, build: function() { if (this.detect.isMobile()) { return; } this.button.hideButtons(); this.button.hideButtonsOnMobile(); if (this.opts.buttons.length === 0) { return; } this.$air = this.air.createContainer(); if (this.opts.airWidth !== false) { this.$air.css('width', this.opts.airWidth); } this.air.append(); this.button.$toolbar = this.$air; this.button.setFormatting(); this.button.load(this.$air); this.core.editor().on('mouseup.redactor', this, $.proxy(function(e) { if (this.selection.text() !== '') { this.air.show(e); } }, this)); }, append: function() { this.$air.appendTo('body'); }, createContainer: function() { return $('<ul>').addClass('redactor-air').attr({ 'id': 'redactor-air-' + this.uuid, 'role': 'toolbar' }).hide(); }, show: function (e) { //this.marker.remove(); this.selection.saveInstant(); //this.selection.restore(false); $('.redactor-air').hide(); var leftFix = 0; var width = this.$air.innerWidth(); if ($(window).width() < (e.clientX + width)) { leftFix = 200; } this.$air.css({ left: (e.clientX - leftFix) + 'px', top: (e.clientY + 10 + $(document).scrollTop()) + 'px' }).show(); this.air.enabled = true; this.air.bindHide(); }, bindHide: function() { $(document).on('mousedown.redactor-air.' + this.uuid, $.proxy(function(e) { var dropdown = $(e.target).closest('.redactor-dropdown').length; if ($(e.target).closest(this.$air).length === 0 && dropdown === 0) { var hide = this.air.hide(e); if (hide !== false) { this.marker.remove(); } } }, this)).on('keydown.redactor-air.' + this.uuid, $.proxy(function(e) { var key = e.which; if ((!this.utils.isRedactorParent(e.target) && !$(e.target).hasClass('redactor-in')) || $(e.target).closest('#redactor-modal').length !== 0) { return; } if (key === this.keyCode.ESC) { this.selection.get().collapseToStart(); //this.marker.remove(); } else if (key === this.keyCode.BACKSPACE || key === this.keyCode.DELETE) { var sel = this.selection.get(); var range = this.selection.range(sel); range.deleteContents(); //this.marker.remove(); } else if (key === this.keyCode.ENTER) { this.selection.get().collapseToEnd(); //this.marker.remove(); } if (this.air.enabled) { this.air.hide(e); } else { this.selection.get().collapseToStart(); //this.marker.remove(); } }, this)); }, hide: function(e) { var ctrl = e.ctrlKey || e.metaKey || (e.shiftKey && e.altKey); if (ctrl) { return false; } this.button.setInactiveAll(); this.$air.fadeOut(100); this.air.enabled = false; $(document).off('mousedown.redactor-air.' + this.uuid); $(document).off('keydown.redactor-air.' + this.uuid); } }; }, // =autosave autosave: function() { return { enabled: false, html: false, init: function() { if (!this.opts.autosave) { return; } this.autosave.enabled = true; this.autosave.name = (this.opts.autosaveName) ? this.opts.autosaveName : this.$textarea.attr('name'); }, is: function() { return this.autosave.enabled; }, send: function() { if (!this.opts.autosave) { return; } this.autosave.source = this.code.get(); if (this.autosave.html === this.autosave.source) { return; } // data var data = {}; data.name = this.autosave.name; data[this.autosave.name] = this.autosave.source; data = this.autosave.getHiddenFields(data); // ajax var jsxhr = $.ajax({ url: this.opts.autosave, type: 'post', data: data }); jsxhr.done(this.autosave.success); }, getHiddenFields: function(data) { if (this.opts.autosaveFields === false || typeof this.opts.autosaveFields !== 'object') { return data; } $.each(this.opts.autosaveFields, $.proxy(function(k, v) { if (v !== null && v.toString().indexOf('#') === 0) { v = $(v).val(); } data[k] = v; }, this)); return data; }, success: function(data) { var json; try { json = JSON.parse(data); } catch(e) { //data has already been parsed json = data; } var callbackName = (typeof json.error === 'undefined') ? 'autosave' : 'autosaveError'; this.core.callback(callbackName, this.autosave.name, json); this.autosave.html = this.autosave.source; }, disable: function() { this.autosave.enabled = false; clearInterval(this.autosaveTimeout); } }; }, // =block block: function() { return { format: function(tag, attr, value, type) { tag = (tag === 'quote') ? 'blockquote' : tag; this.block.tags = ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'figure']; if ($.inArray(tag, this.block.tags) === -1) { return; } if (tag === 'p' && typeof attr === 'undefined') { // remove all attr = 'class'; } this.placeholder.hide(); this.buffer.set(); return (this.utils.isCollapsed()) ? this.block.formatCollapsed(tag, attr, value, type) : this.block.formatUncollapsed(tag, attr, value, type); }, formatCollapsed: function(tag, attr, value, type) { this.selection.save(); var block = this.selection.block(); var currentTag = block.tagName.toLowerCase(); if ($.inArray(currentTag, this.block.tags) === -1) { this.selection.restore(); return; } if (currentTag === tag) { tag = 'p'; } var replaced; if (currentTag === 'blockquote' && this.utils.isEndOfElement(block)) { this.marker.remove(); replaced = document.createElement('p'); replaced.innerHTML = this.opts.invisibleSpace; $(block).after(replaced); this.caret.start(replaced); var $last = $(block).children().last(); if ($last.length !== 0 && $last[0].tagName === 'BR') { $last.remove(); } } else { replaced = this.utils.replaceToTag(block, tag); } if (typeof attr === 'object') { type = value; for (var key in attr) { replaced = this.block.setAttr(replaced, key, attr[key], type); } } else { replaced = this.block.setAttr(replaced, attr, value, type); } // trim pre if (tag === 'pre' && replaced.length === 1) { $(replaced).html($.trim($(replaced).html())); } this.selection.restore(); this.block.removeInlineTags(replaced); return replaced; }, formatUncollapsed: function(tag, attr, value, type) { this.selection.save(); var replaced = []; var blocks = this.selection.blocks(); if (blocks[0] && $(blocks[0]).hasClass('redactor-in')) { blocks = $(blocks[0]).find(this.opts.blockTags.join(', ')); } var len = blocks.length; for (var i = 0; i < len; i++) { var currentTag = blocks[i].tagName.toLowerCase(); if ($.inArray(currentTag, this.block.tags) !== -1 && currentTag !== 'figure') { var block = this.utils.replaceToTag(blocks[i], tag); if (typeof attr === 'object') { type = value; for (var key in attr) { block = this.block.setAttr(block, key, attr[key], type); } } else { block = this.block.setAttr(block, attr, value, type); } replaced.push(block); this.block.removeInlineTags(block); } } this.selection.restore(); // combine pre if (tag === 'pre' && replaced.length !== 0) { var first = replaced[0]; $.each(replaced, function(i,s) { if (i !== 0) { $(first).append("\n" + $.trim(s.html())); $(s).remove(); } }); replaced = []; replaced.push(first); } return replaced; }, removeInlineTags: function(node) { node = node[0] || node; var tags = this.opts.inlineTags; var blocks = ['PRE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6']; if ($.inArray(node.tagName, blocks) === - 1) { return; } if (node.tagName !== 'PRE') { var index = tags.indexOf('a'); tags.splice(index, 1); } $(node).find(tags.join(',')).not('.redactor-selection-marker').contents().unwrap(); }, setAttr: function(block, attr, value, type) { if (typeof attr === 'undefined') { return block; } var func = (typeof type === 'undefined') ? 'replace' : type; if (attr === 'class') { block = this.block[func + 'Class'](value, block); } else { if (func === 'remove') { block = this.block[func + 'Attr'](attr, block); } else if (func === 'removeAll') { block = this.block[func + 'Attr'](attr, block); } else { block = this.block[func + 'Attr'](attr, value, block); } } return block; }, getBlocks: function(block) { return (typeof block === 'undefined') ? this.selection.blocks() : block; }, replaceClass: function(value, block) { return $(this.block.getBlocks(block)).removeAttr('class').addClass(value)[0]; }, toggleClass: function(value, block) { return $(this.block.getBlocks(block)).toggleClass(value)[0]; }, addClass: function(value, block) { return $(this.block.getBlocks(block)).addClass(value)[0]; }, removeClass: function(value, block) { return $(this.block.getBlocks(block)).removeClass(value)[0]; }, removeAllClass: function(block) { return $(this.block.getBlocks(block)).removeAttr('class')[0]; }, replaceAttr: function(attr, value, block) { block = this.block.removeAttr(attr, block); return $(block).attr(attr, value)[0]; }, toggleAttr: function(attr, value, block) { block = this.block.getBlocks(block); var self = this; var returned = []; $.each(block, function(i,s) { var $el = $(s); if ($el.attr(attr)) { returned.push(self.block.removeAttr(attr, s)); } else { returned.push(self.block.addAttr(attr, value, s)); } }); return returned; }, addAttr: function(attr, value, block) { return $(this.block.getBlocks(block)).attr(attr, value)[0]; }, removeAttr: function(attr, block) { return $(this.block.getBlocks(block)).removeAttr(attr)[0]; }, removeAllAttr: function(block) { block = this.block.getBlocks(block); var returned = []; $.each(block, function(i,s) { if (typeof s.attributes === 'undefined') { returned.push(s); } var $el = $(s); var len = s.attributes.length; for (var z = 0; z < len; z++) { $el.removeAttr(s.attributes[z].name); } returned.push($el[0]); }); return returned; } }; }, // buffer buffer: function() { return { set: function(type) { if (typeof type === 'undefined') { this.buffer.clear(); } if (typeof type === 'undefined' || type === 'undo') { this.buffer.setUndo(); } else { this.buffer.setRedo(); } }, setUndo: function() { var saved = this.selection.saveInstant(); var last = this.opts.buffer[this.opts.buffer.length-1]; var current = this.core.editor().html(); var save = (typeof last !== 'undefined' && (last[0] === current)) ? false : true; if (save) { this.opts.buffer.push([current, saved]); } //this.selection.restoreInstant(); }, setRedo: function() { var saved = this.selection.saveInstant(); this.opts.rebuffer.push([this.core.editor().html(), saved]); //this.selection.restoreInstant(); }, add: function() { this.opts.buffer.push([this.core.editor().html(), 0]); }, undo: function() { if (this.opts.buffer.length === 0) { return; } var buffer = this.opts.buffer.pop(); this.buffer.set('redo'); this.core.editor().html(buffer[0]); this.selection.restoreInstant(buffer[1]); this.observe.load(); }, redo: function() { if (this.opts.rebuffer.length === 0) { return; } var buffer = this.opts.rebuffer.pop(); this.buffer.set('undo'); this.core.editor().html(buffer[0]); this.selection.restoreInstant(buffer[1]); this.observe.load(); }, clear: function() { this.opts.rebuffer = []; } }; }, // =build build: function() { return { start: function() { if (this.opts.type === 'inline') { this.opts.type = 'inline'; } else if (this.opts.type === 'div') { // empty var html = $.trim(this.$editor.html()); if (html === '') { this.$editor.html(this.opts.emptyHtml); } } else if (this.opts.type === 'textarea') { this.build.startTextarea(); } // set in this.build.setIn(); // set id this.build.setId(); // enable this.build.enableEditor(); // options this.build.setOptions(); // call this.build.callEditor(); }, createContainerBox: function() { this.$box = $('<div class="redactor-box" role="application" />'); }, setIn: function() { this.core.editor().addClass('redactor-in'); }, setId: function() { var id = (this.opts.type === 'textarea') ? 'redactor-uuid-' + this.uuid : this.$element.attr('id'); this.core.editor().attr('id', (typeof id === 'undefined') ? 'redactor-uuid-' + this.uuid : id); }, getName: function() { var name = this.$element.attr('name'); return (typeof name === 'undefined') ? 'content-' + this.uuid : name; }, loadFromTextarea: function() { this.$editor = $('<div />'); // textarea this.$textarea = this.$element; this.$element.attr('name', this.build.getName()); // place this.$box.insertAfter(this.$element).append(this.$editor).append(this.$element); this.$editor.addClass('redactor-layer'); if (this.opts.overrideStyles) { this.$editor.addClass('redactor-styles'); } this.$element.hide(); this.$box.prepend('<span class="redactor-voice-label" id="redactor-voice-' + this.uuid +'" aria-hidden="false">' + this.lang.get('accessibility-help-label') + '</span>'); this.$editor.attr({ 'aria-labelledby': 'redactor-voice-' + this.uuid, 'role': 'presentation' }); }, startTextarea: function() { this.build.createContainerBox(); // load this.build.loadFromTextarea(); // set code this.code.start(this.core.textarea().val()); // set value this.core.textarea().val(this.clean.onSync(this.$editor.html())); }, isTag: function(tag) { return (this.$element[0].tagName === tag); }, isInline: function() { return (!this.build.isTag('TEXTAREA') && !this.build.isTag('DIV') && !this.build.isTag('PRE')); }, enableEditor: function() { this.core.editor().attr({ 'contenteditable': true }); }, setOptions: function() { // inline if (this.opts.type === 'inline') { this.opts.enterKey = false; } // inline & pre if (this.opts.type === 'inline' || this.opts.type === 'pre') { this.opts.toolbarMobile = false; this.opts.toolbar = false; this.opts.air = false; this.opts.linkify = false; } // spellcheck this.core.editor().attr('spellcheck', this.opts.spellcheck); // structure if (this.opts.structure) { this.core.editor().addClass('redactor-structure'); } // options sets only in textarea mode if (this.opts.type !== 'textarea') { return; } // direction this.core.box().attr('dir', this.opts.direction); this.core.editor().attr('dir', this.opts.direction); // tabindex if (this.opts.tabindex) { this.core.editor().attr('tabindex', this.opts.tabindex); } // min height if (this.opts.minHeight) { this.core.editor().css('min-height', this.opts.minHeight); } else { this.core.editor().css('min-height', '40px'); } // max height if (this.opts.maxHeight) { this.core.editor().css('max-height', this.opts.maxHeight); } // max width if (this.opts.maxWidth) { this.core.editor().css({ 'max-width': this.opts.maxWidth, 'margin': 'auto' }); } }, callEditor: function() { this.build.disableBrowsersEditing(); this.events.init(); this.build.setHelpers(); // init buttons if (this.opts.toolbar || this.opts.air) { this.toolbarsButtons = this.button.init(); } // load toolbar if (this.opts.air) { this.air.build(); } else if (this.opts.toolbar) { this.toolbar.build(); } if (this.detect.isMobile() && this.opts.toolbarMobile && this.opts.air) { this.opts.toolbar = true; this.toolbar.build(); } // observe dropdowns if (this.opts.air || this.opts.toolbar) { this.core.editor().on('mouseup.redactor-observe.' + this.uuid + ' keyup.redactor-observe.' + this.uuid + ' focus.redactor-observe.' + this.uuid + ' touchstart.redactor-observe.' + this.uuid, $.proxy(this.observe.toolbar, this)); this.core.element().on('blur.callback.redactor', $.proxy(function() { this.button.setInactiveAll(); }, this)); } // modal templates init this.modal.templates(); // plugins this.build.plugins(); // autosave this.autosave.init(); // sync code this.code.html = this.code.cleaned(this.core.editor().html()); // init callback this.core.callback('init'); this.core.callback('initToEdit'); // get images & files list this.storage.observe(); // started this.start = false; }, setHelpers: function() { // linkify if (this.opts.linkify) { this.linkify.format(); } // placeholder this.placeholder.init(); // focus if (this.opts.focus) { setTimeout(this.focus.start, 100); } else if (this.opts.focusEnd) { setTimeout(this.focus.end, 100); } }, disableBrowsersEditing: function() { try { // FF fix document.execCommand('enableObjectResizing', false, false); document.execCommand('enableInlineTableEditing', false, false); // IE prevent converting links document.execCommand("AutoUrlDetect", false, false); } catch (e) {} }, plugins: function() { if (!this.opts.plugins) { return; } $.each(this.opts.plugins, $.proxy(function(i, s) { var func = (typeof RedactorPlugins !== 'undefined' && typeof RedactorPlugins[s] !== 'undefined') ? RedactorPlugins : Redactor.fn; if (!$.isFunction(func[s])) { return; } this[s] = func[s](); // get methods var methods = this.getModuleMethods(this[s]); var len = methods.length; // bind methods for (var z = 0; z < len; z++) { this[s][methods[z]] = this[s][methods[z]].bind(this); } // append lang if (typeof this[s].langs !== 'undefined') { var lang = {}; if (typeof this[s].langs[this.opts.lang] !== 'undefined') { lang = this[s].langs[this.opts.lang]; } else if (typeof this[s].langs[this.opts.lang] === 'undefined' && typeof this[s].langs.en !== 'undefined') { lang = this[s].langs.en; } // extend var self = this; $.each(lang, function(i,s) { if (typeof self.opts.curLang[i] === 'undefined') { self.opts.curLang[i] = s; } }); } // init if ($.isFunction(this[s].init)) { this[s].init(); } }, this)); } }; }, // =button button: function() { return { toolbar: function() { return (typeof this.button.$toolbar === 'undefined' || !this.button.$toolbar) ? this.$toolbar : this.button.$toolbar; }, init: function() { return { format: { title: this.lang.get('format'), icon: true, dropdown: { p: { title: this.lang.get('paragraph'), func: 'block.format' }, blockquote: { title: this.lang.get('quote'), func: 'block.format' }, pre: { title: this.lang.get('code'), func: 'block.format' }, h1: { title: this.lang.get('heading1'), func: 'block.format' }, h2: { title: this.lang.get('heading2'), func: 'block.format' }, h3: { title: this.lang.get('heading3'), func: 'block.format' }, h4: { title: this.lang.get('heading4'), func: 'block.format' }, h5: { title: this.lang.get('heading5'), func: 'block.format' }, h6: { title: this.lang.get('heading6'), func: 'block.format' } } }, bold: { title: this.lang.get('bold-abbr'), icon: true, label: this.lang.get('bold'), func: 'inline.format' }, italic: { title: this.lang.get('italic-abbr'), icon: true, label: this.lang.get('italic'), func: 'inline.format' }, deleted: { title: this.lang.get('deleted-abbr'), icon: true, label: this.lang.get('deleted'), func: 'inline.format' }, underline: { title: this.lang.get('underline-abbr'), icon: true, label: this.lang.get('underline'), func: 'inline.format' }, lists: { title: this.lang.get('lists'), icon: true, dropdown: { unorderedlist: { title: '&bull; ' + this.lang.get('unorderedlist'), func: 'list.toggle' }, orderedlist: { title: '1. ' + this.lang.get('orderedlist'), func: 'list.toggle' }, outdent: { title: '< ' + this.lang.get('outdent'), func: 'indent.decrease', observe: { element: 'li', out: { attr: { 'class': 'redactor-dropdown-link-inactive', 'aria-disabled': true } } } }, indent: { title: '> ' + this.lang.get('indent'), func: 'indent.increase', observe: { element: 'li', out: { attr: { 'class': 'redactor-dropdown-link-inactive', 'aria-disabled': true } } } } } }, ul: { title: '&bull; ' + this.lang.get('bulletslist'), icon: true, func: 'list.toggle' }, ol: { title: '1. ' + this.lang.get('numberslist'), icon: true, func: 'list.toggle' }, outdent: { title: this.lang.get('outdent'), icon: true, func: 'indent.decrease' }, indent: { title: this.lang.get('indent'), icon: true, func: 'indent.increase' }, image: { title: this.lang.get('image'), icon: true, func: 'image.show' }, file: { title: this.lang.get('file'), icon: true, func: 'file.show' }, link: { title: this.lang.get('link'), icon: true, dropdown: { link: { title: this.lang.get('link-insert'), func: 'link.show', observe: { element: 'a', 'in': { title: this.lang.get('link-edit'), }, out: { title: this.lang.get('link-insert') } } }, unlink: { title: this.lang.get('unlink'), func: 'link.unlink', observe: { element: 'a', out: { attr: { 'class': 'redactor-dropdown-link-inactive', 'aria-disabled': true } } } } } }, horizontalrule: { title: this.lang.get('horizontalrule'), icon: true, func: 'line.insert' } }; }, setFormatting: function() { $.each(this.toolbarsButtons.format.dropdown, $.proxy(function (i, s) { if ($.inArray(i, this.opts.formatting) === -1) { delete this.toolbarsButtons.format.dropdown[i]; } }, this)); }, hideButtons: function() { if (this.opts.buttonsHide.length !== 0) { this.button.hideButtonsSlicer(this.opts.buttonsHide); } }, hideButtonsOnMobile: function() { if (this.detect.isMobile() && this.opts.buttonsHideOnMobile.length !== 0) { this.button.hideButtonsSlicer(this.opts.buttonsHideOnMobile); } }, hideButtonsSlicer: function(buttons) { $.each(buttons, $.proxy(function(i, s) { var index = this.opts.buttons.indexOf(s); if (index !== -1) { this.opts.buttons.splice(index, 1); } }, this)); }, load: function($toolbar) { this.button.buttons = []; $.each(this.opts.buttons, $.proxy(function(i, btnName) { if (!this.toolbarsButtons[btnName] || (btnName === 'file' && !this.file.is()) || (btnName === 'image' && !this.image.is())) { return; } $toolbar.append($('<li>').append(this.button.build(btnName, this.toolbarsButtons[btnName]))); }, this)); }, buildButtonTooltip: function($btn, title) { if (this.opts.air || this.detect.isMobile()) { return; } var $tooltip = $('<span>'); $tooltip.addClass('re-button-tooltip'); $tooltip.html(title); $btn.append($tooltip); $btn.on('mouseover', function() { if ($(this).hasClass('redactor-button-disabled')) { return; } $tooltip.show(); $tooltip.css('margin-left', -($tooltip.innerWidth()/2)); }).on('mouseout', function() { $tooltip.hide(); }); }, build: function(btnName, btnObject) { if (this.opts.toolbar === false) { return; } var title = (typeof btnObject.label !== 'undefined') ? btnObject.label : btnObject.title; var $button = $('<a href="javascript:void(null);" alt="' + title + '" rel="' + btnName + '" />') $button.addClass('re-button re-' + btnName); $button.attr({ 'role': 'button', 'aria-label': title, 'tabindex': '-1' }); if (typeof btnObject.icon !== 'undefined') { var $icon = $('<i>'); $icon.addClass('re-icon-' + btnName); $button.append($icon); $button.addClass('re-button-icon'); this.button.buildButtonTooltip($button, title); } else { $button.html(btnObject.title); } // click if (btnObject.func || btnObject.command || btnObject.dropdown) { this.button.setEvent($button, btnName, btnObject); } // dropdown if (btnObject.dropdown) { $button.addClass('redactor-toolbar-link-dropdown').attr('aria-haspopup', true); var $dropdown = $('<ul class="redactor-dropdown redactor-dropdown-' + this.uuid + ' redactor-dropdown-box-' + btnName + '" style="display: none;">'); $button.data('dropdown', $dropdown); this.dropdown.build(btnName, $dropdown, btnObject.dropdown); } this.button.buttons.push($button); return $button; }, getButtons: function() { return this.button.toolbar().find('a.re-button'); }, getButtonsKeys: function() { return this.button.buttons; }, setEvent: function($button, btnName, btnObject) { $button.on('mousedown', $.proxy(function(e) { e.preventDefault(); if ($button.hasClass('redactor-button-disabled')) { return false; } var type = 'func'; var callback = btnObject.func; if (btnObject.command) { type = 'command'; callback = btnObject.command; } else if (btnObject.dropdown) { type = 'dropdown'; callback = false; } this.button.toggle(e, btnName, type, callback); return false; }, this)); }, toggle: function(e, btnName, type, callback, args) { if (this.detect.isIe() || !this.detect.isDesktop()) { this.utils.freezeScroll(); e.returnValue = false; } if (type === 'command') { this.inline.format(callback); } else if (type === 'dropdown') { this.dropdown.show(e, btnName); } else { this.button.clickCallback(e, callback, btnName, args); } if (type !== 'dropdown') { this.dropdown.hideAll(false); } if (this.opts.air && type !== 'dropdown') { this.air.hide(e); } if (this.detect.isIe() || !this.detect.isDesktop()) { this.utils.unfreezeScroll(); } }, clickCallback: function(e, callback, btnName, args) { var func; args = (typeof args === 'undefined') ? btnName : args; if ($.isFunction(callback)) { callback.call(this, btnName); } else if (callback.search(/\./) !== '-1') { func = callback.split('.'); if (typeof this[func[0]] === 'undefined') { return; } if (typeof args === 'object') { this[func[0]][func[1]].apply(this, args); } else { this[func[0]][func[1]].call(this, args); } } else { if (typeof args === 'object') { this[callback].apply(this, args); } else { this[callback].call(this, args); } } this.observe.buttons(e, btnName); }, all: function() { return this.button.buttons; }, get: function(key) { if (this.opts.toolbar === false) { return; } return this.button.toolbar().find('a.re-' + key); }, set: function(key, title) { if (this.opts.toolbar === false) { return; } var $btn = this.button.toolbar().find('a.re-' + key); $btn.html(title).attr('aria-label', title); return $btn; }, add: function(key, title) { if (this.button.isAdded(key) !== true) { return $(); } var btn = this.button.build(key, { title: title }); this.button.toolbar().append($('<li>').append(btn)); return btn; }, addFirst: function(key, title) { if (this.button.isAdded(key) !== true) { return $(); } var btn = this.button.build(key, { title: title }); this.button.toolbar().prepend($('<li>').append(btn)); return btn; }, addAfter: function(afterkey, key, title) { if (this.button.isAdded(key) !== true) { return $(); } var btn = this.button.build(key, { title: title }); var $btn = this.button.get(afterkey); if ($btn.length !== 0) { $btn.parent().after($('<li>').append(btn)); } else { this.button.toolbar().append($('<li>').append(btn)); } return btn; }, addBefore: function(beforekey, key, title) { if (this.button.isAdded(key) !== true) { return $(); } var btn = this.button.build(key, { title: title }); var $btn = this.button.get(beforekey); if ($btn.length !== 0) { $btn.parent().before($('<li>').append(btn)); } else { this.button.toolbar().append($('<li>').append(btn)); } return btn; }, isAdded: function(key) { var index = this.opts.buttonsHideOnMobile.indexOf(key); if (this.opts.toolbar === false || (index !== -1 && this.detect.isMobile())) { return false; } return true; }, setIcon: function($btn, icon) { $btn.html(icon).addClass('re-button-icon'); this.button.buildButtonTooltip($btn, $btn.attr('alt')); }, changeIcon: function(key, newIconClass) { var $btn = this.button.get(key); if ($btn.length !== 0) { $btn.find('i').removeAttr('class').addClass('re-icon-' + newIconClass); } }, addCallback: function($btn, callback) { if (typeof $btn === 'undefined' || this.opts.toolbar === false) { return; } var type = (callback === 'dropdown') ? 'dropdown' : 'func'; var key = $btn.attr('rel'); $btn.on('mousedown', $.proxy(function(e) { if ($btn.hasClass('redactor-button-disabled')) { return false; } this.button.toggle(e, key, type, callback); }, this)); }, addDropdown: function($btn, dropdown) { if (this.opts.toolbar === false) { return; } $btn.addClass('redactor-toolbar-link-dropdown').attr('aria-haspopup', true); var key = $btn.attr('rel'); this.button.addCallback($btn, 'dropdown'); var $dropdown = $('<div class="redactor-dropdown redactor-dropdown-' + this.uuid + ' redactor-dropdown-box-' + key + '" style="display: none;">'); $btn.data('dropdown', $dropdown); // build dropdown if (dropdown) { this.dropdown.build(key, $dropdown, dropdown); } return $dropdown; }, setActive: function(key) { this.button.get(key).addClass('redactor-act'); }, setInactive: function(key) { this.button.get(key).removeClass('redactor-act'); }, setInactiveAll: function(key) { var $btns = this.button.toolbar().find('a.re-button'); if (typeof key !== 'undefined') { $btns = $btns.not('.re-' + key); } $btns.removeClass('redactor-act'); }, disable: function(key) { this.button.get(key).addClass('redactor-button-disabled'); }, enable: function(key) { this.button.get(key).removeClass('redactor-button-disabled'); }, disableAll: function(key) { var $btns = this.button.toolbar().find('a.re-button'); if (typeof key !== 'undefined') { $btns = $btns.not('.re-' + key); } $btns.addClass('redactor-button-disabled'); }, enableAll: function() { this.button.toolbar().find('a.re-button').removeClass('redactor-button-disabled'); }, remove: function(key) { this.button.get(key).remove(); } }; }, // =caret caret: function() { return { set: function(node1, node2, end) { this.core.editor().focus(); end = (typeof end === 'undefined') ? 0 : 1; node1 = node1[0] || node1; node2 = node2[0] || node2; var sel = this.selection.get(); var range = this.selection.range(sel); try { range.setStart(node1, 0); range.setEnd(node2, end); } catch (e) {} this.selection.update(sel, range); }, prepare: function(node) { // firefox focus if (this.detect.isFirefox() && typeof this.start !== 'undefined') { this.core.editor().focus(); } return node[0] || node; }, start: function(node) { var sel, range; node = this.caret.prepare(node); if (!node) { return; } if (node.tagName === 'BR') { return this.caret.before(node); } var $first = $(node).children().first(); // empty or inline tag var inline = this.utils.isInlineTag(node.tagName); if (node.innerHTML === '' || inline) { this.caret.setStartEmptyOrInline(node, inline); } // empty inline inside else if ($first && $first.length !== 0 && this.utils.isInlineTag($first[0].tagName) && $first.text() === '') { this.caret.setStartEmptyOrInline($first[0], true); } // block tag else { sel = window.getSelection(); sel.removeAllRanges(); range = document.createRange(); range.selectNodeContents(node); range.collapse(true); sel.addRange(range); } }, setStartEmptyOrInline: function(node, inline) { var sel = window.getSelection(); var range = document.createRange(); var textNode = document.createTextNode('\u200B'); range.setStart(node, 0); range.insertNode(textNode); range.setStartAfter(textNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); // remove invisible text node if (!inline) { this.core.editor().on('keydown.redactor-remove-textnode', function() { $(textNode).remove(); $(this).off('keydown.redactor-remove-textnode'); }); } }, end: function(node) { var sel, range; node = this.caret.prepare(node); if (!node) { return; } // empty node if (node.tagName !== 'BR' && node.innerHTML === '') { return this.caret.start(node); } // br if (node.tagName === 'BR') { var space = document.createElement('span'); space.className = 'redactor-invisible-space'; space.innerHTML = '&#x200b;'; $(node).after(space); sel = window.getSelection(); sel.removeAllRanges(); range = document.createRange(); range.setStartBefore(space); range.setEndBefore(space); sel.addRange(range); $(space).replaceWith(function() { return $(this).contents(); }); return; } if (node.lastChild && node.lastChild.nodeType === 1) { return this.caret.after(node.lastChild); } sel = window.getSelection(); sel.removeAllRanges(); range = document.createRange(); range.selectNodeContents(node); range.collapse(false); sel.addRange(range); }, after: function(node) { var sel, range; node = this.caret.prepare(node); if (!node) { return; } if (node.tagName === 'BR') { return this.caret.end(node); } // block tag if (this.utils.isBlockTag(node.tagName)) { var next = this.caret.next(node); if (typeof next === 'undefined') { this.caret.end(node); } else { // table if (next.tagName === 'TABLE') { next = $(next).find('th, td').first()[0]; } // list else if (next.tagName === 'UL' || next.tagName === 'OL') { next = $(next).find('li').first()[0]; } this.caret.start(next); } return; } // inline tag var textNode = document.createTextNode('\u200B'); sel = window.getSelection(); sel.removeAllRanges(); range = document.createRange(); range.setStartAfter(node); range.insertNode(textNode); range.setStartAfter(textNode); range.collapse(true); sel.addRange(range); }, before: function(node) { var sel, range; node = this.caret.prepare(node); if (!node) { return; } // block tag if (this.utils.isBlockTag(node.tagName)) { var prev = this.caret.prev(node); if (typeof prev === 'undefined') { this.caret.start(node); } else { // table if (prev.tagName === 'TABLE') { prev = $(prev).find('th, td').last()[0]; } // list else if (prev.tagName === 'UL' || prev.tagName === 'OL') { prev = $(prev).find('li').last()[0]; } this.caret.end(prev); } return; } // inline tag sel = window.getSelection(); sel.removeAllRanges(); range = document.createRange(); range.setStartBefore(node); range.collapse(true); sel.addRange(range); }, next: function(node) { var $next = $(node).next(); if ($next.hasClass('redactor-script-tag, redactor-selection-marker')) { return $next.next()[0]; } else { return $next[0]; } }, prev: function(node) { var $prev = $(node).prev(); if ($prev.hasClass('redactor-script-tag, redactor-selection-marker')) { return $prev.prev()[0]; } else { return $prev[0]; } }, // #backward offset: function(node) { return this.offset.get(node); } }; }, // =clean clean: function() { return { onSet: function(html) { html = this.clean.savePreCode(html); html = this.clean.saveFormTags(html); // convert script tag if (this.opts.script) { html = html.replace(/<script(.*?[^>]?)>([\w\W]*?)<\/script>/gi, '<pre class="redactor-script-tag" $1>$2</pre>'); } // converting entity html = html.replace(/\$/g, '&#36;'); html = html.replace(/&amp;/g, '&'); // replace special characters in links html = html.replace(/<a href="(.*?[^>]?)®(.*?[^>]?)">/gi, '<a href="$1&reg$2">'); // save markers html = html.replace(/<span id="selection-marker-1"(.*?[^>]?)>​<\/span>/gi, '###marker1###'); html = html.replace(/<span id="selection-marker-2"(.*?[^>]?)>​<\/span>/gi, '###marker2###'); // replace tags var self = this; var $div = $("<div/>").html($.parseHTML(html, document, true)); var replacement = this.opts.replaceTags; if (replacement) { var keys = Object.keys(this.opts.replaceTags); $div.find(keys.join(',')).each(function(i,s) { self.utils.replaceToTag(s, replacement[s.tagName.toLowerCase()]); }); } // add span marker $div.find('span, a').attr('data-redactor-span', true).each(function() { // add style cache var $el = $(this); if ($el.attr('style')) { $el.attr('data-redactor-style-cache', $el.attr('style')); } }); html = $div.html(); // remove tags var tags = ['font', 'html', 'head', 'link', 'body', 'meta', 'applet']; if (!this.opts.script) { tags.push('script'); } html = this.clean.stripTags(html, tags); // remove html comments if (this.opts.removeComments) { html = html.replace(/<!--[\s\S]*?-->/gi, ''); } // paragraphize html = this.paragraphize.load(html); // restore markers html = html.replace('###marker1###', '<span id="selection-marker-1" class="redactor-selection-marker">​</span>'); html = html.replace('###marker2###', '<span id="selection-marker-2" class="redactor-selection-marker">​</span>'); // empty if (html.search(/^(||\s||<br\s?\/?>||&nbsp;)$/i) !== -1) { return this.opts.emptyHtml; } return html; }, onGet: function(html) { return this.clean.onSync(html); }, onSync: function(html) { // remove invisible spaces html = html.replace(/\u200B/g, ''); html = html.replace(/&#x200b;/gi, ''); //html = html.replace(/&nbsp;&nbsp;/gi, '&nbsp;'); if (html.search(/^<p>(||\s||<br\s?\/?>||&nbsp;)<\/p>$/i) !== -1) { return ''; } // remove image resize html = html.replace(/<span(.*?)id="redactor-image-box"(.*?[^>])>([\w\W]*?)<img(.*?)><\/span>/gi, '$3<img$4>'); html = html.replace(/<span(.*?)id="redactor-image-resizer"(.*?[^>])>(.*?)<\/span>/gi, ''); html = html.replace(/<span(.*?)id="redactor-image-editter"(.*?[^>])>(.*?)<\/span>/gi, ''); html = html.replace(/<img(.*?)style="(.*?)opacity: 0\.5;(.*?)"(.*?)>/gi, '<img$1style="$2$3"$4>'); var $div = $("<div/>").html($.parseHTML(html, document, true)); // remove empty atributes $div.find('*[style=""]').removeAttr('style'); $div.find('*[class=""]').removeAttr('class'); $div.find('*[rel=""]').removeAttr('rel'); // remove markers $div.find('.redactor-invisible-space, .redactor-unlink').each(function() { $(this).contents().unwrap(); }); // remove span without attributes & span marker $div.find('span, a').removeAttr('data-redactor-span data-redactor-style-cache').each(function() { if (this.attributes.length === 0) { $(this).contents().unwrap(); } }); // remove rel attribute from img $div.find('img').removeAttr('rel'); $div.find('.redactor-selection-marker, #redactor-insert-marker').remove(); html = $div.html(); // reconvert script tag if (this.opts.script) { html = html.replace(/<pre class="redactor-script-tag"(.*?[^>]?)>([\w\W]*?)<\/pre>/gi, '<script$1>$2</script>'); } // restore form tag html = this.clean.restoreFormTags(html); // remove br in|of li/header tags html = html.replace(new RegExp('<br\\s?/?></h', 'gi'), '</h'); html = html.replace(new RegExp('<br\\s?/?></li>', 'gi'), '</li>'); html = html.replace(new RegExp('</li><br\\s?/?>', 'gi'), '</li>'); // pre class html = html.replace(/<pre>/gi, "<pre>\n"); if (this.opts.preClass) { html = html.replace(/<pre>/gi, '<pre class="' + this.opts.preClass + '">'); } // link nofollow if (this.opts.linkNofollow) { html = html.replace(/<a(.*?)rel="nofollow"(.*?[^>])>/gi, '<a$1$2>'); html = html.replace(/<a(.*?[^>])>/gi, '<a$1 rel="nofollow">'); } // replace special characters var chars = { '\u2122': '&trade;', '\u00a9': '&copy;', '\u2026': '&hellip;', '\u2014': '&mdash;', '\u2010': '&dash;' }; $.each(chars, function(i,s) { html = html.replace(new RegExp(i, 'g'), s); }); html = html.replace(/&amp;/g, '&'); // remove empty paragpraphs html = html.replace(/<p><\/p>/gi, ""); // remove new lines html = html.replace(/\n{2,}/g, "\n"); // remove all newlines if (this.opts.removeNewlines) { html = html.replace(/\r?\n/g, ""); } return html; }, onPaste: function(html, data, insert) { // if paste event if (insert !== true) { // remove google docs markers html = html.replace(/<b\sid="internal-source-marker(.*?)">([\w\W]*?)<\/b>/gi, "$2"); html = html.replace(/<b(.*?)id="docs-internal-guid(.*?)">([\w\W]*?)<\/b>/gi, "$3"); // google docs styles html = html.replace(/<span[^>]*(font-style: italic; font-weight: bold|font-weight: bold; font-style: italic)[^>]*>([\w\W]*?)<\/span>/gi, '<b><i>$2</i></b>'); html = html.replace(/<span[^>]*(font-style: italic; font-weight: 700|font-weight: 700; font-style: italic)[^>]*>([\w\W]*?)<\/span>/gi, '<b><i>$2</i></b>'); html = html.replace(/<span[^>]*font-style: italic[^>]*>([\w\W]*?)<\/span>/gi, '<i>$1</i>'); html = html.replace(/<span[^>]*font-weight: bold[^>]*>([\w\W]*?)<\/span>/gi, '<b>$1</b>'); html = html.replace(/<span[^>]*font-weight: 700[^>]*>([\w\W]*?)<\/span>/gi, '<b>$1</b>'); var msword = this.clean.isHtmlMsWord(html); if (msword) { html = this.clean.cleanMsWord(html); } } html = $.trim(html); if (data.pre) { if (this.opts.preSpaces) { html = html.replace(/\t/g, new Array(this.opts.preSpaces + 1).join(' ')); } } else { html = this.clean.replaceBrToNl(html); html = this.clean.removeTagsInsidePre(html); } // if paste event if (insert !== true) { html = this.clean.removeEmptyInlineTags(html); if (data.encode === false) { html = html.replace(/&/g, '&amp;'); html = this.clean.convertTags(html, data); html = this.clean.getPlainText(html); html = this.clean.reconvertTags(html, data); } } if (data.text) { html = this.clean.replaceNbspToSpaces(html); html = this.clean.getPlainText(html); } if (data.lists) { html = html.replace("\n", '<br>'); } if (data.encode) { html = this.clean.encodeHtml(html); } if (data.paragraphize) { html = this.paragraphize.load(html); } return html; }, getCurrentType: function(html, insert) { var blocks = this.selection.blocks(); var data = { text: false, encode: false, paragraphize: true, line: this.clean.isHtmlLine(html), blocks: this.clean.isHtmlBlocked(html), pre: false, lists: false, block: true, inline: true, links: true, images: true }; if (blocks.length === 1 && this.utils.isCurrentOrParent(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'figcaption'])) { data.text = true; data.paragraphize = false; data.inline = false; data.images = false; data.links = false; data.line = true; } else if (this.opts.type === 'inline' || this.opts.enterKey === false) { data.paragraphize = false; data.block = false; data.line = true; } else if (blocks.length === 1 && this.utils.isCurrentOrParent(['li'])) { data.lists = true; data.block = false; data.paragraphize = false; data.images = false; } else if (blocks.length === 1 && this.utils.isCurrentOrParent(['th', 'td', 'blockquote'])) { data.block = false; data.paragraphize = false; } else if (this.opts.type === 'pre' || (blocks.length === 1 && this.utils.isCurrentOrParent('pre'))) { data.inline = false; data.block = false; data.encode = true; data.pre = true; data.paragraphize = false; data.images = false; data.links = false; } if (data.line === true) { data.paragraphize = false; } if (insert === true) { data.text = false; } return data; }, isHtmlBlocked: function(html) { var match1 = html.match(new RegExp('</(' + this.opts.blockTags.join('|' ).toUpperCase() + ')>', 'gi')); var match2 = html.match(new RegExp('<hr(.*?[^>])>', 'gi')); return (match1 === null && match2 === null) ? false : true; }, isHtmlLine: function(html) { if (this.clean.isHtmlBlocked(html)) { return false; } var matchBR = html.match(/<br\s?\/?>/gi); var matchNL = html.match(/\n/gi); return (!matchBR && !matchNL) ? true : false; }, isHtmlMsWord: function(html) { return html.match(/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i); }, removeEmptyInlineTags: function(html) { var tags = this.opts.inlineTags; var $div = $("<div/>").html($.parseHTML(html, document, true)); var self = this; var $spans = $div.find('span'); var $tags = $div.find(tags.join(',')); $tags.removeAttr('style'); $tags.each(function() { var tagHtml = $(this).html(); if (this.attributes.length === 0 && self.utils.isEmpty(tagHtml)) { $(this).replaceWith(function() { return $(this).contents(); }); } }); $spans.each(function() { var tagHtml = $(this).html(); if (this.attributes.length === 0) { $(this).replaceWith(function() { return $(this).contents(); }); } }); html = $div.html(); // convert php tags html = html.replace('<!--?php', '<?php'); html = html.replace('<!--?', '<?'); html = html.replace('?-->', '?>'); $div.remove(); return html; }, cleanMsWord: function(html) { html = html.replace(/<!--[\s\S]*?-->/g, ""); html = html.replace(/<o:p>[\s\S]*?<\/o:p>/gi, ''); html = html.replace(/\n/g, " "); html = html.replace(/<br\s?\/?>|<\/p>|<\/div>|<\/li>|<\/td>/gi, '\n\n'); // lists var $div = $("<div/>").html(html); var lastList = false; var lastLevel = 1; var listsIds = []; $div.find("p[style]").each(function() { var matches = $(this).attr('style').match(/mso\-list\:l([0-9]+)\slevel([0-9]+)/); if (matches) { var currentList = parseInt(matches[1]); var currentLevel = parseInt(matches[2]); var listType = $(this).html().match(/^[\w]+\./) ? "ol" : "ul"; var $li = $("<li/>").html($(this).html()); $li.html($li.html().replace(/^([\w\.]+)</, '<')); $li.find("span:first").remove(); if (currentLevel == 1 && $.inArray(currentList, listsIds) == -1) { var $list = $("<" + listType + "/>").attr({"data-level": currentLevel, "data-list": currentList}).html($li); $(this).replaceWith($list); lastList = currentList; listsIds.push(currentList); } else { if (currentLevel > lastLevel) { var $prevList = $div.find('[data-level="' + lastLevel + '"][data-list="' + lastList + '"]'); var $lastList = $prevList; for(var i = lastLevel; i < currentLevel; i++) { $list = $("<" + listType + "/>"); $list.appendTo($lastList.find("li").last()); $lastList = $list; } $lastList.attr({"data-level": currentLevel, "data-list": currentList}).html($li); } else { var $prevList = $div.find('[data-level="' + currentLevel + '"][data-list="' + currentList + '"]').last(); $prevList.append($li); } lastLevel = currentLevel; lastList = currentList; $(this).remove(); } } }); $div.find('[data-level][data-list]').removeAttr('data-level data-list'); html = $div.html(); return html; }, replaceNbspToSpaces: function(html) { return html.replace('&nbsp;', ' '); }, replaceBrToNl: function(html) { return html.replace(/<br\s?\/?>/gi, '\n'); }, replaceNlToBr: function(html) { return html.replace(/\n/g, '<br />'); }, convertTags: function(html, data) { var $div = $('<div>').html(html); // remove iframe $div.find('iframe').remove(); // link target & attrs var $links = $div.find('a'); $links.removeAttr('style'); if (this.opts.pasteLinkTarget !== false) { $links.attr('target', this.opts.pasteLinkTarget); } // links if (data.links && this.opts.pasteLinks) { $div.find('a').each(function(i, link) { if (link.href) { var tmp = '##%a href="' + link.href + '"'; var attr; for (var j = 0, length = link.attributes.length; j < length; j++) { attr = link.attributes.item(j); if (attr.name !== 'href') { tmp += ' ' + attr.name + '="' + attr.value + '"'; } } link.outerHTML = tmp + '%##' + link.innerHTML + '##%/a%##'; } }); } html = $div.html(); // images if (data.images && this.opts.pasteImages) { html = html.replace(/<img(.*?)src="(.*?)"(.*?[^>])>/gi, '##%img$1src="$2"$3%##'); } // plain text if (this.opts.pastePlainText) { return html; } // all tags var blockTags = (data.lists) ? ['ul', 'ol', 'li'] : this.opts.pasteBlockTags; var tags; if (data.block || data.lists) { tags = (data.inline) ? blockTags.concat(this.opts.pasteInlineTags) : blockTags; } else { tags = (data.inline) ? this.opts.pasteInlineTags : []; } var len = tags.length; for (var i = 0; i < len; i++) { html = html.replace(new RegExp('<\/' + tags[i] + '>', 'gi'), '###/' + tags[i] + '###'); if (tags[i] === 'td' || tags[i] === 'th') { html = html.replace(new RegExp('<' + tags[i] + '(.*?[^>])((colspan|rowspan)="(.*?[^>])")?(.*?[^>])>', 'gi'), '###' + tags[i] + ' $2###'); } else if (tags[i] === 'span') { html = html.replace(new RegExp('<' + tags[i] + '([^>]*)class="([^>]*)"[^>]*>', 'gi'), '###' + tags[i] + ' class="$2"###'); html = html.replace(new RegExp('<' + tags[i] + '([^>]*)data-redactor-style-cache="([^>]*)"[^>]*>', 'gi'), '###' + tags[i] + ' cache="$2"###'); } else { html = html.replace(new RegExp('<' + tags[i] + '[^>]*>', 'gi'), '###' + tags[i] + '###'); } } return html; }, reconvertTags: function(html, data) { // links & images if ((data.links && this.opts.pasteLinks) || (data.images && this.opts.pasteImages)) { html = html.replace(new RegExp('##%', 'gi'), '<'); html = html.replace(new RegExp('%##', 'gi'), '>'); } // plain text if (this.opts.pastePlainText) { return html; } var blockTags = (data.lists) ? ['ul', 'ol', 'li'] : this.opts.pasteBlockTags; var tags; if (data.block || data.lists) { tags = (data.inline) ? blockTags.concat(this.opts.pasteInlineTags) : blockTags; } else { tags = (data.inline) ? this.opts.pasteInlineTags : []; } var len = tags.length; for (var i = 0; i < len; i++) { html = html.replace(new RegExp('###\/' + tags[i] + '###', 'gi'), '</' + tags[i] + '>'); } for (var i = 0; i < len; i++) { html = html.replace(new RegExp('###' + tags[i] + '###', 'gi'), '<' + tags[i] + '>'); } for (var i = 0; i < len; i++) { if (tags[i] === 'td' || tags[i] === 'th') { html = html.replace(new RegExp('###' + tags[i] + '\s?(.*?[^#])###', 'gi'), '<' + tags[i] + '$1>'); } else if (tags[i] === 'span') { html = html.replace(new RegExp('###' + tags[i] + ' cache="(.*?[^#])"###', 'gi'), '<' + tags[i] + ' style="$1" data-redactor-span="true" data-redactor-style-cache="$1">'); html = html.replace(new RegExp('###' + tags[i] + '\s?(.*?[^#])###', 'gi'), '<' + tags[i] + '$1>'); } } return html; }, cleanPre: function(block) { block = (typeof block === 'undefined') ? $(this.selection.block()).closest('pre', this.core.editor()[0]) : block; $(block).find('br').replaceWith(function() { return document.createTextNode('\n'); }); $(block).find('p').replaceWith(function() { return $(this).contents(); }); }, removeTagsInsidePre: function(html) { var $div = $('<div />').append(html); $div.find('pre').replaceWith(function() { var str = $(this).html(); str = str.replace(/<br\s?\/?>|<\/p>|<\/div>|<\/li>|<\/td>/gi, '\n'); str = str.replace(/(<([^>]+)>)/gi, ''); return $('<pre />').append(str); }); html = $div.html(); $div.remove(); return html; }, getPlainText: function(html) { html = html.replace(/<!--[\s\S]*?-->/gi, ''); html = html.replace(/<style[\s\S]*?style>/gi, ''); html = html.replace(/<\/p>|<\/div>|<\/li>|<\/td>/gi, '\n'); html = html.replace(/<\/H[1-6]>/gi, '\n\n'); var tmp = document.createElement('div'); tmp.innerHTML = html; html = tmp.textContent || tmp.innerText; return $.trim(html); }, savePreCode: function(html) { html = this.clean.savePreFormatting(html); html = this.clean.saveCodeFormatting(html); html = this.clean.restoreSelectionMarkers(html); return html; }, savePreFormatting: function(html) { var pre = html.match(/<pre(.*?)>([\w\W]*?)<\/pre>/gi); if (pre === null) { return html; } $.each(pre, $.proxy(function(i,s) { var arr = []; var codeTag = false; var contents, attr1, attr2; if (s.match(/<pre(.*?)>(([\n\r\s]+)?)<code(.*?)>/i)) { arr = s.match(/<pre(.*?)>(([\n\r\s]+)?)<code(.*?)>([\w\W]*?)<\/code>(([\n\r\s]+)?)<\/pre>/i); codeTag = true; contents = arr[5]; attr1 = arr[1]; attr2 = arr[4]; } else { arr = s.match(/<pre(.*?)>([\w\W]*?)<\/pre>/i); contents = arr[2]; attr1 = arr[1]; } contents = contents.replace(/<br\s?\/?>/g, '\n'); contents = contents.replace(/&nbsp;/g, ' '); if (this.opts.preSpaces) { contents = contents.replace(/\t/g, new Array(this.opts.preSpaces + 1).join(' ')); } contents = this.clean.encodeEntities(contents); // $ fix contents = contents.replace(/\$/g, '&#36;'); if (codeTag) { html = html.replace(s, '<pre' + attr1 + '><code' + attr2 + '>' + contents + '</code></pre>'); } else { html = html.replace(s, '<pre' + attr1 + '>' + contents + '</pre>'); } }, this)); return html; }, saveCodeFormatting: function(html) { var code = html.match(/<code(.*?)>([\w\W]*?)<\/code>/gi); if (code === null) { return html; } $.each(code, $.proxy(function(i,s) { var arr = s.match(/<code(.*?)>([\w\W]*?)<\/code>/i); arr[2] = arr[2].replace(/&nbsp;/g, ' '); arr[2] = this.clean.encodeEntities(arr[2]); arr[2] = arr[2].replace(/\$/g, '&#36;'); html = html.replace(s, '<code' + arr[1] + '>' + arr[2] + '</code>'); }, this)); return html; }, restoreSelectionMarkers: function(html) { html = html.replace(/&lt;span id=&quot;selection-marker-([0-9])&quot; class=&quot;redactor-selection-marker&quot;&gt;​&lt;\/span&gt;/g, '<span id="selection-marker-$1" class="redactor-selection-marker">​</span>'); return html; }, saveFormTags: function(html) { return html.replace(/<form(.*?)>([\w\W]*?)<\/form>/gi, '<section$1 rel="redactor-form-tag">$2</section>'); }, restoreFormTags: function(html) { return html.replace(/<section(.*?) rel="redactor-form-tag"(.*?)>([\w\W]*?)<\/section>/gi, '<form$1$2>$3</form>'); }, encodeHtml: function(html) { html = html.replace(/”/g, '"'); html = html.replace(/“/g, '"'); html = html.replace(/‘/g, '\''); html = html.replace(/’/g, '\''); html = this.clean.encodeEntities(html); return html; }, encodeEntities: function(str) { str = String(str).replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"'); str = str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); return str; }, stripTags: function(input, denied) { if (typeof denied === 'undefined') { return input.replace(/(<([^>]+)>)/gi, ''); } var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi; return input.replace(tags, function ($0, $1) { return denied.indexOf($1.toLowerCase()) === -1 ? $0 : ''; }); }, removeMarkers: function(html) { return html.replace(/<span(.*?[^>]?)class="redactor-selection-marker"(.*?[^>]?)>([\w\W]*?)<\/span>/gi, ''); }, removeSpaces: function(html) { html = $.trim(html); html = html.replace(/\n/g, ''); html = html.replace(/[\t]*/g, ''); html = html.replace(/\n\s*\n/g, "\n"); html = html.replace(/^[\s\n]*/g, ' '); html = html.replace(/[\s\n]*$/g, ' '); html = html.replace( />\s{2,}</g, '> <'); // between inline tags can be only one space html = html.replace(/\n\n/g, "\n"); html = html.replace(/\u200B/g, ''); return html; }, removeSpacesHard: function(html) { html = $.trim(html); html = html.replace(/\n/g, ''); html = html.replace(/[\t]*/g, ''); html = html.replace(/\n\s*\n/g, "\n"); html = html.replace(/^[\s\n]*/g, ''); html = html.replace(/[\s\n]*$/g, ''); html = html.replace( />\s{2,}</g, '><'); html = html.replace(/\n\n/g, "\n"); html = html.replace(/\u200B/g, ''); return html; }, normalizeCurrentHeading: function() { var heading = this.selection.block(); if (this.utils.isCurrentOrParentHeader() && heading) { heading.normalize(); } } }; }, // =code code: function() { return { syncFire: true, html: false, start: function(html) { html = $.trim(html); html = html.replace(/^(<span id="selection-marker-1" class="redactor-selection-marker">​<\/span>)/, ''); // clean if (this.opts.type === 'textarea') { html = this.clean.onSet(html); } else if (this.opts.type === 'div' && html === '') { html = this.opts.emptyHtml; } html = html.replace(/<p><span id="selection-marker-1" class="redactor-selection-marker">​<\/span><\/p>/, ''); this.events.stopDetectChanges(); this.core.editor().html(html); this.observe.load(); this.events.startDetectChanges(); }, set: function(html, options) { html = $.trim(html); options = options || {}; // start if (options.start) { this.start = options.start; } // clean if (this.opts.type === 'textarea') { html = this.clean.onSet(html); } else if (this.opts.type === 'div' && html === '') { html = this.opts.emptyHtml; } this.core.editor().html(html); if (this.opts.type === 'textarea') { this.code.sync(); } this.placeholder.enable(); }, get: function() { if (this.opts.type === 'textarea') { return this.core.textarea().val(); } else { var html = this.core.editor().html(); // clean html = this.clean.onGet(html); return html; } }, sync: function() { if (!this.code.syncFire) { return; } var html = this.core.editor().html(); var htmlCleaned = this.code.cleaned(html); // is there a need to synchronize if (this.code.isSync(htmlCleaned)) { // do not sync return; } // save code this.code.html = htmlCleaned; if (this.opts.type !== 'textarea') { this.core.callback('sync', html); this.core.callback('change', html); return; } if (this.opts.type === 'textarea') { setTimeout($.proxy(function() { this.code.startSync(html); }, this), 10); } }, startSync: function(html) { // before clean callback html = this.core.callback('syncBefore', html); // clean html = this.clean.onSync(html); // set code this.core.textarea().val(html); // after sync callback this.core.callback('sync', html); // change callback if (this.start === false) { this.core.callback('change', html); } this.start = false; }, isSync: function(htmlCleaned) { var html = (this.code.html !== false) ? this.code.html : false; return (html !== false && html === htmlCleaned); }, cleaned: function(html) { html = html.replace(/\u200B/g, ''); return this.clean.removeMarkers(html); } }; }, // =core core: function() { return { id: function() { return this.$editor.attr('id'); }, element: function() { return this.$element; }, editor: function() { return (typeof this.$editor === 'undefined') ? $() : this.$editor; }, textarea: function() { return this.$textarea; }, box: function() { return (this.opts.type === 'textarea') ? this.$box : this.$element; }, toolbar: function() { return (this.$toolbar) ? this.$toolbar : false; }, air: function() { return (this.$air) ? this.$air : false; }, object: function() { return $.extend({}, this); }, structure: function() { this.core.editor().toggleClass('redactor-structure'); }, addEvent: function(name) { this.core.event = name; }, getEvent: function() { return this.core.event; }, callback: function(type, e, data) { var eventNamespace = 'redactor'; var returnValue = false; var events = $._data(this.core.element()[0], 'events'); // on callback if (typeof events !== 'undefined' && typeof events[type] !== 'undefined') { var len = events[type].length; for (var i = 0; i < len; i++) { var namespace = events[type][i].namespace; if (namespace === 'callback.' + eventNamespace) { var handler = events[type][i].handler; var args = (typeof data === 'undefined') ? [e] : [e, data]; returnValue = (typeof args === 'undefined') ? handler.call(this, e) : handler.call(this, e, args); } } } if (returnValue) { return returnValue; } // no callback if (typeof this.opts.callbacks[type] === 'undefined') { return (typeof data === 'undefined') ? e : data; } // callback var callback = this.opts.callbacks[type]; if ($.isFunction(callback)) { return (typeof data === 'undefined') ? callback.call(this, e) : callback.call(this, e, data); } else { return (typeof data === 'undefined') ? e : data; } }, destroy: function() { this.opts.destroyed = true; this.core.callback('destroy'); // placeholder this.placeholder.destroy(); // progress this.progress.destroy(); // help label $('#redactor-voice-' + this.uuid).remove(); this.core.editor().removeClass('redactor-in redactor-styles redactor-structure redactor-layer-img-edit'); // caret service this.core.editor().off('keydown.redactor-remove-textnode'); // observer this.core.editor().off('.redactor-observe.' + this.uuid); // off events and remove data this.$element.off('.redactor').removeData('redactor'); this.core.editor().off('.redactor'); $(document).off('.redactor-dropdown'); $(document).off('.redactor-air.' + this.uuid); $(document).off('mousedown.redactor-blur.' + this.uuid); $(document).off('mousedown.redactor.' + this.uuid); $(document).off('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid); $(window).off('.redactor-toolbar.' + this.uuid); $(window).off('touchmove.redactor.' + this.uuid); $("body").off('scroll.redactor.' + this.uuid); $(this.opts.toolbarFixedTarget).off('scroll.redactor.' + this.uuid); // plugins events var self = this; if (this.opts.plugins !== false) { $.each(this.opts.plugins, function(i,s) { $(window).off('.redactor-plugin-' + s); $(document).off('.redactor-plugin-' + s); $("body").off('.redactor-plugin-' + s); self.core.editor().off('.redactor-plugin-' + s); }); } // click to edit this.$element.off('click.redactor-click-to-edit'); this.$element.removeClass('redactor-click-to-edit'); // common this.core.editor().removeClass('redactor-layer'); this.core.editor().removeAttr('contenteditable'); var html = this.code.get(); if (this.opts.toolbar && this.$toolbar) { // dropdowns off this.$toolbar.find('a').each(function() { var $el = $(this); if ($el.data('dropdown')) { $el.data('dropdown').remove(); $el.data('dropdown', {}); } }); } if (this.opts.type === 'textarea') { this.$box.after(this.$element); this.$box.remove(); this.$element.val(html).show(); } // air if (this.opts.air) { this.$air.remove(); } if (this.opts.toolbar && this.$toolbar) { this.$toolbar.remove(); } // modal if (this.$modalBox) { this.$modalBox.remove(); } if (this.$modalOverlay) { this.$modalOverlay.remove(); } // hide link's tooltip $('.redactor-link-tooltip').remove(); // autosave clearInterval(this.autosaveTimeout); } }; }, // =detect detect: function() { return { // public isWebkit: function() { return /webkit/.test(this.opts.userAgent); }, isFirefox: function() { return this.opts.userAgent.indexOf('firefox') > -1; }, isIe: function(v) { if (document.documentMode || /Edge/.test(navigator.userAgent)) { return 'edge'; } var ie; ie = RegExp('msie' + (!isNaN(v)?('\\s'+v):''), 'i').test(navigator.userAgent); if (!ie) { ie = !!navigator.userAgent.match(/Trident.*rv[ :]*11\./); } return ie; }, isMobile: function() { return /(iPhone|iPod|BlackBerry|Android)/.test(navigator.userAgent); }, isDesktop: function() { return !/(iPhone|iPod|iPad|BlackBerry|Android)/.test(navigator.userAgent); }, isIpad: function() { return /iPad/.test(navigator.userAgent); } }; }, // =dropdown dropdown: function() { return { active: false, button: false, key: false, position: [], getDropdown: function() { return this.dropdown.active; }, build: function(name, $dropdown, dropdownObject) { dropdownObject = this.dropdown.buildFormatting(name, dropdownObject); $.each(dropdownObject, $.proxy(function(btnName, btnObject) { var $item = this.dropdown.buildItem(btnName, btnObject); this.observe.addDropdown($item, btnName, btnObject); $dropdown.attr('rel', name).append($item); }, this)); }, buildFormatting: function(name, dropdownObject) { if (name !== 'format' || this.opts.formattingAdd === false) { return dropdownObject; } $.each(this.opts.formattingAdd, $.proxy(function(i,s) { var type = (this.utils.isBlockTag(s.args[0])) ? 'block' : 'inline'; dropdownObject[i] = { func: (type === 'block') ? 'block.format' : 'inline.format', args: s.args, title: s.title }; }, this)); return dropdownObject; }, buildItem: function(btnName, btnObject) { var $itemContainer = $('<li />'); if (typeof btnObject.classname !== 'undefined') { $itemContainer.addClass(btnObject.classname); } if (btnName.search(/^divider/i) !== -1) { $itemContainer.addClass('redactor-dropdown-divider'); return $itemContainer; } var $item = $('<a href="#" class="redactor-dropdown-' + btnName + '" role="button" />'); var $itemSpan = $('<span />').html(btnObject.title); $item.append($itemSpan); $item.on('mousedown', $.proxy(function(e) { e.preventDefault(); this.dropdown.buildClick(e, btnName, btnObject); }, this)); $itemContainer.append($item); return $itemContainer; }, buildClick: function(e, btnName, btnObject) { if ($(e.target).hasClass('redactor-dropdown-link-inactive')) { return; } var command = this.dropdown.buildCommand(btnObject); if (typeof btnObject.args !== ' undefined') { this.button.toggle(e, btnName, command.type, command.callback, btnObject.args); } else { this.button.toggle(e, btnName, command.type, command.callback); } }, buildCommand: function(btnObject) { var command = {}; command.type = 'func'; command.callback = btnObject.func; if (btnObject.command) { command.type = 'command'; command.callback = btnObject.command; } else if (btnObject.dropdown) { command.type = 'dropdown'; command.callback = btnObject.dropdown; } return command; }, show: function(e, key) { if (this.detect.isDesktop()) { this.core.editor().focus(); } this.dropdown.hideAll(false, key); this.dropdown.key = key; this.dropdown.button = this.button.get(this.dropdown.key); if (this.dropdown.button.hasClass('dropact')) { this.dropdown.hide(); return; } // re append this.dropdown.active = this.dropdown.button.data('dropdown').appendTo(document.body); // callback this.core.callback('dropdownShow', { dropdown: this.dropdown.active, key: this.dropdown.key, button: this.dropdown.button }); // set button this.button.setActive(this.dropdown.key); this.dropdown.button.addClass('dropact'); // position this.dropdown.getButtonPosition(); // show if (this.button.toolbar().hasClass('toolbar-fixed-box') && this.detect.isDesktop()) { this.dropdown.showIsFixedToolbar(); } else { this.dropdown.showIsUnFixedToolbar(); } // disable scroll whan dropdown scroll if (this.detect.isDesktop() && !this.detect.isFirefox()) { this.dropdown.active.on('mouseover.redactor-dropdown', $.proxy(this.utils.disableBodyScroll, this)); this.dropdown.active.on('mouseout.redactor-dropdown mousedown.redactor-dropdown', $.proxy(this.utils.enableBodyScroll, this)); } e.stopPropagation(); }, showIsFixedToolbar: function() { var top = this.dropdown.button.position().top + this.dropdown.button.innerHeight() + this.opts.toolbarFixedTopOffset; var position = 'fixed'; if (this.opts.toolbarFixedTarget !== document) { top = (this.dropdown.button.innerHeight() + this.$toolbar.offset().top) + this.opts.toolbarFixedTopOffset; position = 'absolute'; } this.dropdown.active.css({ position: position, left: this.dropdown.position.left + 'px', top: top + 'px' }).show(); // animate this.dropdown.active.redactorAnimation('slideDown', { duration: 0.2 }, $.proxy(function() { this.dropdown.enableCallback(); this.dropdown.enableEvents(); }, this)); }, showIsUnFixedToolbar: function() { this.dropdown.active.css({ position: 'absolute', left: this.dropdown.position.left + 'px', top: (this.dropdown.button.innerHeight() + this.dropdown.position.top) + 'px' }).show(); // animate this.dropdown.active.redactorAnimation(((this.opts.animation) ? 'slideDown' : 'show'), { duration: 0.2 }, $.proxy(function() { this.dropdown.enableCallback(); this.dropdown.enableEvents(); }, this)); }, enableEvents: function() { $(document).on('mousedown.redactor-dropdown', $.proxy(this.dropdown.hideAll, this)); this.core.editor().on('touchstart.redactor-dropdown', $.proxy(this.dropdown.hideAll, this)); $(document).on('keyup.redactor-dropdown', $.proxy(this.dropdown.closeHandler, this)); }, enableCallback: function() { this.core.callback('dropdownShown', { dropdown: this.dropdown.active, key: this.dropdown.key, button: this.dropdown.button }); }, getButtonPosition: function() { this.dropdown.position = this.dropdown.button.offset(); // fix right placement var dropdownWidth = this.dropdown.active.width(); if ((this.dropdown.position.left + dropdownWidth) > $(document).width()) { this.dropdown.position.left = Math.max(0, this.dropdown.position.left - dropdownWidth + parseInt(this.dropdown.button.innerWidth())); } }, closeHandler: function(e) { if (e.which !== this.keyCode.ESC) { return; } this.dropdown.hideAll(e); this.core.editor().focus(); }, hideAll: function(e, key) { if (this.detect.isDesktop()) { this.utils.enableBodyScroll(); } if (e !== false && $(e.target).closest('.redactor-dropdown').length !== 0) { return; } var $buttons = (typeof key === 'undefined') ? this.button.toolbar().find('a.dropact') : this.button.toolbar().find('a.dropact').not('.re-' + key); var $elements = (typeof key === 'undefined') ? $('.redactor-dropdown-' + this.uuid) : $('.redactor-dropdown-' + this.uuid).not('.redactor-dropdown-box-' + key); if ($elements.length !== 0) { $(document).off('.redactor-dropdown'); this.core.editor().off('.redactor-dropdown'); $.each($elements, $.proxy(function(i,s) { var $el = $(s); this.core.callback('dropdownHide', $el); $el.hide(); $el.off('mouseover mouseout').off('.redactor-dropdown'); }, this)); $buttons .removeClass('redactor-act dropact'); } }, hide: function () { if (this.dropdown.active === false) { return; } if (this.detect.isDesktop()) { this.utils.enableBodyScroll(); } this.dropdown.active.redactorAnimation(((this.opts.animation) ? 'slideUp' : 'hide'), { duration: 0.2 }, $.proxy(function() { $(document).off('.redactor-dropdown'); this.core.editor().off('.redactor-dropdown'); this.dropdown.hideOut(); }, this)); }, hideOut: function() { this.core.callback('dropdownHide', this.dropdown.active); this.dropdown.button.removeClass('redactor-act dropact'); this.dropdown.active.off('mouseover mouseout').off('.redactor-dropdown'); this.dropdown.button = false; this.dropdown.key = false; this.dropdown.active = false; } }; }, // =events events: function() { return { focused: false, blured: true, dropImage: false, stopChanges: false, stopDetectChanges: function() { this.events.stopChanges = true; }, startDetectChanges: function() { var self = this; setTimeout(function() { self.events.stopChanges = false; }, 1); }, dragover: function(e) { e.preventDefault(); e.stopPropagation(); if (e.target.tagName === 'IMG') { $(e.target).addClass('redactor-image-dragover'); } }, dragleave: function(e) { // remove image dragover this.core.editor().find('img').removeClass('redactor-image-dragover'); }, drop: function(e) { e = e.originalEvent || e; // remove image dragover this.core.editor().find('img').removeClass('redactor-image-dragover'); if (this.opts.type === 'inline' || this.opts.type === 'pre') { e.preventDefault(); return false; } if (window.FormData === undefined || !e.dataTransfer) { return true; } if (e.dataTransfer.files.length === 0) { return this.events.onDrop(e); } else { this.events.onDropUpload(e); } this.core.callback('drop', e); }, click: function(e) { var event = this.core.getEvent(); var type = (event === 'click' || event === 'arrow') ? false : 'click'; this.core.addEvent(type); this.utils.disableSelectAll(); this.core.callback('click', e); }, focus: function(e) { if (this.rtePaste) { return; } if (this.events.isCallback('focus')) { this.core.callback('focus', e); } this.events.focused = true; this.events.blured = false; // tab if (this.selection.current() === false) { var sel = this.selection.get(); var range = this.selection.range(sel); range.setStart(this.core.editor()[0], 0); range.setEnd(this.core.editor()[0], 0); this.selection.update(sel, range); } }, blur: function(e) { if (this.start || this.rtePaste) { return; } if ($(e.target).closest('#' + this.core.id() + ', .redactor-toolbar, .redactor-dropdown, #redactor-modal-box').length !== 0) { return; } if (!this.events.blured && this.events.isCallback('blur')) { this.core.callback('blur', e); } this.events.focused = false; this.events.blured = true; }, touchImageEditing: function() { var scrollTimer = -1; this.events.imageEditing = false; $(window).on('touchmove.redactor.' + this.uuid, $.proxy(function() { this.events.imageEditing = true; if (scrollTimer !== -1) { clearTimeout(scrollTimer); } scrollTimer = setTimeout($.proxy(function() { this.events.imageEditing = false; }, this), 500); }, this)); }, init: function() { this.core.editor().on('dragover.redactor dragenter.redactor', $.proxy(this.events.dragover, this)); this.core.editor().on('dragleave.redactor', $.proxy(this.events.dragleave, this)); this.core.editor().on('drop.redactor', $.proxy(this.events.drop, this)); this.core.editor().on('click.redactor', $.proxy(this.events.click, this)); this.core.editor().on('paste.redactor', $.proxy(this.paste.init, this)); this.core.editor().on('keydown.redactor', $.proxy(this.keydown.init, this)); this.core.editor().on('keyup.redactor', $.proxy(this.keyup.init, this)); this.core.editor().on('focus.redactor', $.proxy(this.events.focus, this)); $(document).on('mousedown.redactor-blur.' + this.uuid, $.proxy(this.events.blur, this)); this.events.touchImageEditing(); this.events.createObserver(); this.events.setupObserver(); }, createObserver: function() { var self = this; this.events.observer = new MutationObserver(function(mutations) { mutations.forEach($.proxy(self.events.iterateObserver, self)); }); }, iterateObserver: function(mutation) { var stop = false; // target if (((this.opts.type === 'textarea' || this.opts.type === 'div') && (!this.detect.isFirefox() && mutation.target === this.core.editor()[0])) || (mutation.attributeName === 'class' && mutation.target === this.core.editor()[0]) ) { stop = true; } if (!stop) { this.observe.load(); this.events.changeHandler(); } }, setupObserver: function() { this.events.observer.observe(this.core.editor()[0], { attributes: true, subtree: true, childList: true, characterData: true, characterDataOldValue: true }); }, changeHandler: function() { if (this.events.stopChanges) { return; } this.code.sync(); // autosave if (this.autosave.is()) { clearTimeout(this.autosaveTimeout); this.autosaveTimeout = setTimeout($.proxy(this.autosave.send, this), 300); } }, onDropUpload: function(e) { e.preventDefault(); e.stopPropagation(); if ((!this.opts.dragImageUpload && !this.opts.dragFileUpload) || (this.opts.imageUpload === null && this.opts.fileUpload === null)) { return; } if (e.target.tagName === 'IMG') { this.events.dropImage = e.target; } var files = e.dataTransfer.files; var len = files.length; for (var i = 0; i < len; i++) { this.upload.directUpload(files[i], e); } }, onDrop: function(e) { this.core.callback('drop', e); }, isCallback: function(name) { return (typeof this.opts.callbacks[name] !== 'undefined' && $.isFunction(this.opts.callbacks[name])); }, // #backward stopDetect: function() { this.events.stopDetectChanges(); }, startDetect: function() { this.events.startDetectChanges(); } }; }, // =file file: function() { return { is: function() { return !(!this.opts.fileUpload || !this.opts.fileUpload && !this.opts.s3); }, show: function() { // build modal this.modal.load('file', this.lang.get('file'), 700); // build upload this.upload.init('#redactor-modal-file-upload', this.opts.fileUpload, this.file.insert); // set selected text $('#redactor-filename').val(this.selection.get().toString()); // show this.modal.show(); }, insert: function(json, direct, e) { // error callback if (typeof json.error !== 'undefined') { this.modal.close(); this.core.callback('fileUploadError', json); return; } this.file.release(e, direct); // prepare this.buffer.set(); this.air.collapsed(); // get var text = this.file.text(json); var $link = $('<a />').attr('href', json.url).text(text); var id = (typeof json.id === 'undefined') ? '' : json.id; var type = (typeof json.s3 === 'undefined') ? 'file' : 's3'; // set id $link.attr('data-' + type, id); // insert $link = $(this.insert.node($link)); // focus this.caret.after($link); // callback this.storage.add({ type: type, node: $link[0], url: $link[0].href, id: id }); if (direct !== null) { this.core.callback('fileUpload', $link, json); } }, release: function(e, direct) { if (direct) { // drag and drop upload this.marker.remove(); this.insert.nodeToPoint(e, this.marker.get()); this.selection.restore(); } else { // upload from modal this.modal.close(); } }, text: function(json) { var text = $('#redactor-filename').val(); return (typeof text === 'undefined' || text === '') ? json.name : text; } }; }, // =focus focus: function() { return { start: function() { this.core.editor().focus(); if (this.opts.type === 'inline') { return; } var $first = this.focus.first(); if ($first !== false) { this.caret.start($first); } }, end: function() { this.core.editor().focus(); var last = (this.opts.inline) ? this.core.editor() : this.focus.last(); if (last.length === 0) { return; } // get inline last node var lastNode = this.focus.lastChild(last); if (!this.detect.isWebkit() && lastNode !== false) { this.caret.end(lastNode); } else { var sel = this.selection.get(); var range = this.selection.range(sel); if (range !== null) { range.selectNodeContents(last[0]); range.collapse(false); this.selection.update(sel, range); } else { this.caret.end(last); } } }, first: function() { var $first = this.core.editor().children().first(); if ($first.length === 0 && ($first[0].length === 0 || $first[0].tagName === 'BR' || $first[0].tagName === 'HR' || $first[0].nodeType === 3)) { return false; } if ($first[0].tagName === 'UL' || $first[0].tagName === 'OL') { return $first.find('li').first(); } return $first; }, last: function() { return this.core.editor().children().last(); }, lastChild: function(last) { var lastNode = last[0].lastChild; return (lastNode !== null && this.utils.isInlineTag(lastNode.tagName)) ? lastNode : false; }, is: function() { return (this.core.editor()[0] === document.activeElement); } }; }, // =image image: function() { return { is: function() { return !(!this.opts.imageUpload || !this.opts.imageUpload && !this.opts.s3); }, show: function() { // build modal this.modal.load('image', this.lang.get('image'), 700); // build upload this.upload.init('#redactor-modal-image-droparea', this.opts.imageUpload, this.image.insert); this.modal.show(); }, insert: function(json, direct, e) { var $img; // error callback if (typeof json.error !== 'undefined') { this.modal.close(); this.events.dropImage = false; this.core.callback('imageUploadError', json, e); return; } // change image if (this.events.dropImage !== false) { $img = $(this.events.dropImage); this.core.callback('imageDelete', $img[0].src, $img); $img.attr('src', json.url); this.events.dropImage = false; this.core.callback('imageUpload', $img, json); return; } this.placeholder.hide(); var $figure = $('<' + this.opts.imageTag + '>'); $img = $('<img>'); $img.attr('src', json.url); // set id var id = (typeof json.id === 'undefined') ? '' : json.id; var type = (typeof json.s3 === 'undefined') ? 'image' : 's3'; $img.attr('data-' + type, id); $figure.append($img); var pre = this.utils.isTag(this.selection.current(), 'pre'); if (direct) { this.air.collapsed(); this.marker.remove(); var node = this.insert.nodeToPoint(e, this.marker.get()); var $next = $(node).next(); this.selection.restore(); // buffer this.buffer.set(); // insert if (typeof $next !== 'undefined' && $next.length !== 0 && $next[0].tagName === 'IMG') { // delete callback this.core.callback('imageDelete', $next[0].src, $next); // replace $next.closest('figure, p', this.core.editor()[0]).replaceWith($figure); this.caret.after($figure); } else { if (pre) { $(pre).after($figure); } else { this.insert.node($figure); } this.caret.after($figure); } } else { this.modal.close(); // buffer this.buffer.set(); // insert this.air.collapsed(); if (pre) { $(pre).after($figure); } else { this.insert.node($figure); } this.caret.after($figure); } this.events.dropImage = false; this.storage.add({ type: type, node: $img[0], url: $img[0].src, id: id }); var nextNode = $img[0].nextSibling; var $nextFigure = $figure.next(); var isNextEmpty = $(nextNode).text().replace(/\u200B/g, ''); var isNextFigureEmpty = $nextFigure.text().replace(/\u200B/g, ''); if (isNextEmpty === '') { $(nextNode).remove(); } if ($nextFigure.length === 1 && $nextFigure[0].tagName === 'FIGURE' && isNextFigureEmpty === '') { $nextFigure.remove(); } if (direct !== null) { this.core.callback('imageUpload', $img, json); } else { this.core.callback('imageInserted', $img, json); } }, setEditable: function($image) { $image.on('dragstart', function(e) { e.preventDefault(); }); if (this.opts.imageResizable) { var handler = $.proxy(function(e) { this.observe.image = $image; this.image.resizer = this.image.loadEditableControls($image); $(document).on('mousedown.redactor-image-resize-hide.' + this.uuid, $.proxy(this.image.hideResize, this)); if (this.image.resizer) { this.image.resizer.on('mousedown.redactor touchstart.redactor', $.proxy(function(e) { this.image.setResizable(e, $image); }, this)); } }, this); $image.off('mousedown.redactor').on('mousedown.redactor', $.proxy(this.image.hideResize, this)); $image.off('click.redactor touchstart.redactor').on('click.redactor touchstart.redactor', handler); } else { $image.off('click.redactor touchstart.redactor').on('click.redactor touchstart.redactor', $.proxy(function(e) { setTimeout($.proxy(function() { this.image.showEdit($image); }, this), 200); }, this)); } }, setResizable: function(e, $image) { e.preventDefault(); this.image.resizeHandle = { x : e.pageX, y : e.pageY, el : $image, ratio: $image.width() / $image.height(), h: $image.height() }; e = e.originalEvent || e; if (e.targetTouches) { this.image.resizeHandle.x = e.targetTouches[0].pageX; this.image.resizeHandle.y = e.targetTouches[0].pageY; } this.image.startResize(); }, startResize: function() { $(document).on('mousemove.redactor-image-resize touchmove.redactor-image-resize', $.proxy(this.image.moveResize, this)); $(document).on('mouseup.redactor-image-resize touchend.redactor-image-resize', $.proxy(this.image.stopResize, this)); }, moveResize: function(e) { e.preventDefault(); e = e.originalEvent || e; var height = this.image.resizeHandle.h; if (e.targetTouches) height += (e.targetTouches[0].pageY - this.image.resizeHandle.y); else height += (e.pageY - this.image.resizeHandle.y); var width = Math.round(height * this.image.resizeHandle.ratio); if (height < 50 || width < 100) return; var height = Math.round(this.image.resizeHandle.el.width() / this.image.resizeHandle.ratio); this.image.resizeHandle.el.attr({width: width, height: height}); this.image.resizeHandle.el.width(width); this.image.resizeHandle.el.height(height); this.code.sync(); }, stopResize: function() { this.handle = false; $(document).off('.redactor-image-resize'); this.image.hideResize(); }, hideResize: function(e) { if (e && $(e.target).closest('#redactor-image-box', this.$editor[0]).length !== 0) return; if (e && e.target.tagName == 'IMG') { var $image = $(e.target); } var imageBox = this.$editor.find('#redactor-image-box'); if (imageBox.length === 0) return; $('#redactor-image-editter').remove(); $('#redactor-image-resizer').remove(); imageBox.find('img').css({ marginTop: imageBox[0].style.marginTop, marginBottom: imageBox[0].style.marginBottom, marginLeft: imageBox[0].style.marginLeft, marginRight: imageBox[0].style.marginRight }); imageBox.css('margin', ''); imageBox.find('img').css('opacity', ''); imageBox.replaceWith(function() { return $(this).contents(); }); $(document).off('mousedown.redactor-image-resize-hide.' + this.uuid); if (typeof this.image.resizeHandle !== 'undefined') { this.image.resizeHandle.el.attr('rel', this.image.resizeHandle.el.attr('style')); } }, loadResizableControls: function($image, imageBox) { if (this.opts.imageResizable && !this.detect.isMobile()) { var imageResizer = $('<span id="redactor-image-resizer" data-redactor="verified"></span>'); if (!this.detect.isDesktop()) { imageResizer.css({ width: '15px', height: '15px' }); } imageResizer.attr('contenteditable', false); imageBox.append(imageResizer); imageBox.append($image); return imageResizer; } else { imageBox.append($image); return false; } }, loadEditableControls: function($image) { var imageBox = $('<span id="redactor-image-box" data-redactor="verified">'); imageBox.css('float', $image.css('float')).attr('contenteditable', false); if ($image[0].style.margin != 'auto') { imageBox.css({ marginTop: $image[0].style.marginTop, marginBottom: $image[0].style.marginBottom, marginLeft: $image[0].style.marginLeft, marginRight: $image[0].style.marginRight }); $image.css('margin', ''); } else { imageBox.css({ 'display': 'block', 'margin': 'auto' }); } $image.css('opacity', '.5').after(imageBox); if (this.opts.imageEditable) { // editter this.image.editter = $('<span id="redactor-image-editter" data-redactor="verified">' + this.lang.get('edit') + '</span>'); this.image.editter.attr('contenteditable', false); this.image.editter.on('click', $.proxy(function() { this.image.showEdit($image); }, this)); imageBox.append(this.image.editter); // position correction var editerWidth = this.image.editter.innerWidth(); this.image.editter.css('margin-left', '-' + editerWidth/2 + 'px'); } return this.image.loadResizableControls($image, imageBox); }, showEdit: function($image) { if (this.events.imageEditing) { return; } this.observe.image = $image; var $link = $image.closest('a', this.$editor[0]); var $figure = $image.closest('figure', this.$editor[0]); var $container = ($figure.length !== 0) ? $figure : $image; this.modal.load('image-edit', this.lang.get('edit'), 705); this.image.buttonDelete = this.modal.getDeleteButton().text(this.lang.get('delete')); this.image.buttonSave = this.modal.getActionButton().text(this.lang.get('save')); this.image.buttonDelete.on('click', $.proxy(this.image.remove, this)); this.image.buttonSave.on('click', $.proxy(this.image.update, this)); if (this.opts.imageCaption === false) { $('#redactor-image-caption').val('').hide().prev().hide(); } else { var $parent = $image.closest(this.opts.imageTag, this.$editor[0]); var $ficaption = $parent.find('figcaption'); if ($ficaption !== 0) { $('#redactor-image-caption').val($ficaption.text()).show(); } } if (!this.opts.imagePosition) { $('.redactor-image-position-option').hide(); } else { var isCentered = ($figure.length !== 0) ? ($container.css('text-align') === 'center') : ($container.css('display') == 'block' && $container.css('float') == 'none'); var floatValue = (isCentered) ? 'center' : $container.css('float'); $('#redactor-image-align').val(floatValue); } $('#redactor-image-preview').html($('<img src="' + $image.attr('src') + '" style="max-width: 100%;">')); $('#redactor-image-title').val($image.attr('alt')); var $redactorImageLink = $('#redactor-image-link'); $redactorImageLink.attr('href', $image.attr('src')); if ($link.length !== 0) { $redactorImageLink.val($link.attr('href')); if ($link.attr('target') === '_blank') { $('#redactor-image-link-blank').prop('checked', true); } } // hide link's tooltip $('.redactor-link-tooltip').remove(); this.modal.show(); // focus if (this.detect.isDesktop()) { $('#redactor-image-title').focus(); } }, update: function() { var $image = this.observe.image; var $link = $image.closest('a', this.core.editor()[0]); var title = $('#redactor-image-title').val().replace(/(<([^>]+)>)/ig,""); $image.attr('alt', title).attr('title', title); this.image.setFloating($image); // as link var link = $.trim($('#redactor-image-link').val()).replace(/(<([^>]+)>)/ig,""); if (link !== '') { // test url (add protocol) var pattern = '((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}'; var re = new RegExp('^(http|ftp|https)://' + pattern, 'i'); var re2 = new RegExp('^' + pattern, 'i'); if (link.search(re) === -1 && link.search(re2) === 0 && this.opts.linkProtocol) { link = this.opts.linkProtocol + '://' + link; } var target = ($('#redactor-image-link-blank').prop('checked')) ? true : false; if ($link.length === 0) { var a = $('<a href="' + link + '" id="redactor-img-tmp">' + this.utils.getOuterHtml($image) + '</a>'); if (target) { a.attr('target', '_blank'); } $image = $image.replaceWith(a); $link = this.core.editor().find('#redactor-img-tmp'); $link.removeAttr('id'); } else { $link.attr('href', link); if (target) { $link.attr('target', '_blank'); } else { $link.removeAttr('target'); } } } else if ($link.length !== 0) { $link.replaceWith(this.utils.getOuterHtml($image)); } this.image.addCaption($image, $link); this.modal.close(); // buffer this.buffer.set(); }, setFloating: function($image) { var $figure = $image.closest('figure', this.$editor[0]); var $container = ($figure.length !== 0) ? $figure : $image; var floating = $('#redactor-image-align').val(); var imageFloat = ''; var imageDisplay = ''; var imageMargin = ''; var textAlign = ''; switch (floating) { case 'left': imageFloat = 'left'; imageMargin = '0 ' + this.opts.imageFloatMargin + ' ' + this.opts.imageFloatMargin + ' 0'; break; case 'right': imageFloat = 'right'; imageMargin = '0 0 ' + this.opts.imageFloatMargin + ' ' + this.opts.imageFloatMargin; break; case 'center': if ($figure.length !== 0) { textAlign = 'center'; } else { imageDisplay = 'block'; imageMargin = 'auto'; } break; } $container.css({ 'float': imageFloat, 'display': imageDisplay, 'margin': imageMargin, 'text-align': textAlign }); $container.attr('rel', $image.attr('style')); }, addCaption: function($image, $link) { var caption = $('#redactor-image-caption').val(); var $target = ($link.length !== 0) ? $link : $image; var $figcaption = $target.next(); if ($figcaption.length === 0 || $figcaption[0].tagName !== 'FIGCAPTION') { $figcaption = false; } if (caption !== '') { if ($figcaption === false) { $figcaption = $('<figcaption />').text(caption); $target.after($figcaption); } else { $figcaption.text(caption); } } else if ($figcaption !== false) { $figcaption.remove(); } }, remove: function(e, $image, index) { $image = (typeof $image === 'undefined') ? $(this.observe.image) : $image; // delete from modal if (typeof e !== 'boolean') { this.buffer.set(); } this.events.stopDetectChanges(); var $link = $image.closest('a', this.core.editor()[0]); var $figure = $image.closest(this.opts.imageTag, this.core.editor()[0]); var $parent = $image.parent(); // callback var imageDeleteStop = this.core.callback('imageDelete', e, $image[0]); if (imageDeleteStop === false) { e.preventDefault(); return false; } if ($('#redactor-image-box').length !== 0) { $parent = $('#redactor-image-box').parent(); } var $next, $prev; if ($figure.length !== 0) { $prev = $figure.prev(); $next = $figure.next(); $figure.remove(); } else if ($link.length !== 0) { $parent = $link.parent(); $link.remove(); } else { $image.remove(); } $('#redactor-image-box').remove(); if (e !== false) { if ($next && $next.length !== 0) { this.caret.start($next); } else if ($prev && $prev.length !== 0) { this.caret.end($prev); } } if (typeof e !== 'boolean') { this.modal.close(); } this.utils.restoreScroll(); this.observe.image = false; this.events.startDetectChanges(); this.placeholder.enable(); this.code.sync(); } }; }, // =indent indent: function() { return { increase: function() { if (!this.list.get()) { return; } var $current = $(this.selection.current()).closest('li'); var $list = $current.closest('ul, ol', this.core.editor()[0]); var $li = $current.closest('li'); var $prev = $li.prev(); if ($prev.length === 0 || $prev[0].tagName !== 'LI') { return; } this.buffer.set(); if (this.utils.isCollapsed()) { var listTag = $list[0].tagName; var $newList = $('<' + listTag + ' />'); this.selection.save(); var $ol = $prev.find('ol').first(); if ($ol.length === 1) { $ol.append($current); } else { var listTag = $list[0].tagName; var $newList = $('<' + listTag + ' />'); $newList.append($current); $prev.append($newList); } this.selection.restore(); } else { document.execCommand('indent'); // normalize this.selection.save(); this.indent.removeEmpty(); this.indent.normalize(); this.selection.restore(); } }, decrease: function() { if (!this.list.get()) { return; } var $current = $(this.selection.current()).closest('li'); var $list = $current.closest('ul, ol', this.core.editor()[0]); this.buffer.set(); document.execCommand('outdent'); var $item = $(this.selection.current()).closest('li', this.core.editor()[0]); if (this.utils.isCollapsed()) { this.indent.repositionItem($item); } if ($item.length === 0) { document.execCommand('formatblock', false, 'p'); $item = $(this.selection.current()); var $next = $item.next(); if ($next.length !== 0 && $next[0].tagName === 'BR') { $next.remove(); } } // normalize this.selection.save(); this.indent.removeEmpty(); this.indent.normalize(); this.selection.restore(); }, repositionItem: function($item) { var $next = $item.next(); if ($next.length !== 0 && ($next[0].tagName !== 'UL' || $next[0].tagName !== 'OL')) { $item.append($next); } var $prev = $item.prev(); if ($prev.length !== 0 && $prev[0].tagName !== 'LI') { this.selection.save(); var $li = $item.parents('li', this.core.editor()[0]); $li.after($item); this.selection.restore(); } }, normalize: function() { this.core.editor().find('li').each($.proxy(function(i,s) { var $el = $(s); // remove style $el.find(this.opts.inlineTags.join(',')).each(function() { $(this).removeAttr('style'); }); var $parent = $el.parent(); if ($parent.length !== 0 && $parent[0].tagName === 'LI') { $parent.after($el); return; } var $next = $el.next(); if ($next.length !== 0 && ($next[0].tagName === 'UL' || $next[0].tagName === 'OL')) { $el.append($next); } }, this)); }, removeEmpty: function($list) { var $lists = this.core.editor().find('ul, ol'); var $items = this.core.editor().find('li'); $items.each($.proxy(function(i, s) { this.indent.removeItemEmpty(s); }, this)); $lists.each($.proxy(function(i, s) { this.indent.removeItemEmpty(s); }, this)); $items.each($.proxy(function(i, s) { this.indent.removeItemEmpty(s); }, this)); }, removeItemEmpty: function(s) { var html = s.innerHTML.replace(/[\t\s\n]/g, ''); html = html.replace(/<span><\/span>/g, ''); if (html === '') { $(s).remove(); } } }; }, // =inline inline: function() { return { getClearedNodes: function() { var nodes = this.selection.nodes(); var newNodes = []; var len = nodes.length; var started = 0; // find array slice for (var i = 0; i < len; i++) { if ($(nodes[i]).hasClass('redactor-selection-marker')) { started = i + 2; break; } } // find selected inline & text nodes for (var i = 0; i < len; i++) { if (i >= started && !this.utils.isBlockTag(nodes[i].tagName)) { newNodes.push(nodes[i]); } } return newNodes; }, isConvertableAttr: function(node, attr, value) { var nodeAttrValue = $(node).attr(attr); if (nodeAttrValue) { if (attr === 'style') { value = $.trim(value).replace(/;$/, '') var rules = value.split(';'); var count = 0; for (var i = 0; i < rules.length; i++) { var arr = rules[i].split(':'); var ruleName = $.trim(arr[0]); var ruleValue = $.trim(arr[1]); if (ruleName.search(/color/) !== -1) { var val = $(node).css(ruleName); if (val && (val === ruleValue || this.utils.rgb2hex(val) === ruleValue)) { count++; } } else if ($(node).css(ruleName) === ruleValue) { count++; } } if (count === rules.length) { return 1; } } else if (nodeAttrValue === value) { return 1; } } return 0; }, isConvertable: function(node, nodeTag, tag, attr) { if (nodeTag === tag) { if (attr) { var count = 0; for (var key in attr) { count += this.inline.isConvertableAttr(node, key, attr[key]); } if (count === Object.keys(attr).length) { return true; } } else { return true; } } return false; }, setNodesStriked: function(nodes, tag, attr) { for (var i = 0; i < nodes.length; i++) { var nodeTag = (nodes[i].tagName) ? nodes[i].tagName.toLowerCase() : undefined; var parent = nodes[i].parentNode; var parentTag = (parent && parent.tagName) ? parent.tagName.toLowerCase() : undefined; var convertable = this.inline.isConvertable(parent, parentTag, tag, attr); if (convertable) { var $el = $(parent).replaceWith(function() { return $('<strike>').append($(this).contents()); }); $el.attr('data-redactor-inline-converted'); } var convertable = this.inline.isConvertable(nodes[i], nodeTag, tag, attr); if (convertable) { var $el = $(nodes[i]).replaceWith(function() { return $('<strike>').append($(this).contents()); }); } } }, format: function(tag, attr, value, type) { if (typeof attr !== 'undefined' && typeof attr !== 'object') { var obj = {}; obj[attr] = value; attr = obj; } tag = tag.toLowerCase(); // Stop formatting pre/code if (this.utils.isCurrentOrParent(['PRE', 'CODE'])) { return; } var tags = ['b', 'bold', 'i', 'italic', 'underline', 'strikethrough', 'deleted', 'superscript', 'subscript']; var replaced = ['strong', 'strong', 'em', 'em', 'u', 'del', 'del', 'sup', 'sub']; for (var i = 0; i < tags.length; i++) { if (tag === tags[i]) { tag = replaced[i]; } } this.placeholder.hide(); this.buffer.set(); if (this.utils.isCollapsed()) { this.inline.formatCollapsed(tag, attr, value, type); } else { this.inline.formatUncollapsed(tag, attr, value, type); } }, formatUncollapsed: function(tag, attr, value, type) { this.selection.save(); var nodes = this.inline.getClearedNodes(); this.inline.setNodesStriked(nodes, tag, attr); this.selection.restore(); document.execCommand('strikethrough'); this.selection.saveInstant(); var self = this; this.core.editor().find('strike').each(function() { var $el = self.utils.replaceToTag(this, tag); for (var key in attr) { self.inline.setAttr($el, key, attr[key], type); } // remove inside var $inside = $el.find(tag); if ($inside.length !== 0) { for (var key in attr) { self.inline.removeSpecificAttr($inside, key, attr[key]); } } // same parent var $parent = $el.parent(); if ($parent.html() == $el[0].outerHTML) { for (var key in attr) { self.inline.removeSpecificAttr($parent, key, attr[key]); } } // bugfix: remove empty inline tags after selection if (self.detect.isFirefox()) { self.core.editor().find(tag + ':empty').remove(); } // cache style $el.attr('data-redactor-style-cache', $el.attr('style')); }); this.selection.restoreInstant(); }, formatCollapsed: function(tag, attr, value, type) { var inline = this.selection.inline(); if (inline) { var currentTag = inline.tagName.toLowerCase(); if (currentTag === tag) { // empty = remove if (this.utils.isEmpty(inline.innerHTML)) { this.caret.after(inline); $(inline).remove(); } // not empty = break else { var $first = this.inline.insertBreakpoint(inline, currentTag); this.caret.after($first); } } else if ($(inline).closest(tag).length === 0) { this.inline.insertInline(tag, attr, value, type); } else { this.caret.start(inline); } } else { this.inline.insertInline(tag, attr, value, type); } }, insertBreakpoint: function(inline, currentTag) { var breakpoint = document.createElement('span'); breakpoint.id = 'redactor-inline-breakpoint'; breakpoint = this.insert.node(breakpoint); var end = this.utils.isEndOfElement(inline); var code = this.utils.getOuterHtml(inline); var endTag = (end) ? '' : '<' + currentTag + '>'; code = code.replace(/<span\sid="redactor-inline-breakpoint">​<\/span>/i, '</' + currentTag + '>' + endTag); var $code = $(code); $(inline).replaceWith($code); if (endTag !== '') { this.utils.cloneAttributes(inline, $code.last()); } return $code.first(); }, insertInline: function(tag, attr, value, type) { var node = document.createElement(tag); node = this.inline.setAttr(node, attr, value, type); this.insert.node(node); this.caret.start(node); }, setAttr: function(inline, attr, value, type) { if (typeof attr === 'undefined') { return inline; } var func = (typeof type === 'undefined') ? 'toggle' : type; if (attr === 'class') { inline = this.inline[func + 'Class'](value, inline); } else { if (func === 'remove') { inline = this.inline[func + 'Attr'](attr, inline); } else if (func === 'removeAll') { inline = this.inline[func + 'Attr'](inline); } else { inline = this.inline[func + 'Attr'](attr, value, inline); if (attr === 'style' && inline[0].tagName === 'SPAN') { $(inline).attr('data-redactor-span', true); } } } return inline; }, getInlines: function(inline) { return (typeof inline === 'undefined') ? this.selection.inlines() : inline; }, update: function(tag, attr, value, type) { var inlines = this.selection.inlines(); var result = []; var self = this; $.each(inlines, function(i,s) { if ($.isArray(tag)) { if ($.inArray(s.tagName.toLowerCase(), tag) === -1) { return; } } else { if (tag !== '*' && s.tagName.toLowerCase() !== tag) { return; } } result.push(self.inline.setAttr(s, attr, value, type)); }); return result; }, replaceClass: function(value, inline) { return $(this.inline.getInlines(inline)).removeAttr('class').addClass(value)[0]; }, toggleClass: function(value, inline) { return $(this.inline.getInlines(inline)).toggleClass(value)[0]; }, addClass: function(value, inline) { return $(this.inline.getInlines(inline)).addClass(value)[0]; }, removeClass: function(value, inline) { return $(this.inline.getInlines(inline)).removeClass(value)[0]; }, removeAllClass: function(inline) { return $(this.inline.getInlines(inline)).removeAttr('class')[0]; }, replaceAttr: function(inline, attr, value) { inline = this.inline.removeAttr(attr, this.inline.getInlines(inline)); return $(inline).attr(attr, value)[0]; }, toggleAttr: function(attr, value, inline) { inline = this.inline.getInlines(inline); var self = this; var returned = []; $.each(inline, function(i,s) { var $el = $(s); if ($el.attr(attr)) { returned.push(self.inline.removeAttr(attr, s)); } else { returned.push(self.inline.addAttr(attr, value, s)); } }); return returned; }, addAttr: function(attr, value, inline) { return $(this.inline.getInlines(inline)).attr(attr, value)[0]; }, removeSpecificAttr: function(inline, key, value) { if (key === 'style') { var arr = value.split(':'); var name = arr[0].trim(); $(inline).css(name, ''); this.utils.removeEmptyAttr(inline, 'style'); } else { $(inline).removeAttr(key)[0]; } }, removeAttr: function(attr, inline) { return $(this.inline.getInlines(inline)).removeAttr(attr)[0]; }, removeAllAttr: function(inline) { inline = this.inline.getInlines(inline); var returned = []; $.each(inline, function(i, s) { if (typeof s.attributes === 'undefined') { returned.push(s); } var $el = $(s); var len = s.attributes.length; for (var z = 0; z < len; z++) { $el.removeAttr(s.attributes[z].name); } returned.push($el[0]); }); return returned; }, removeFormat: function() { this.selection.save(); var nodes = this.inline.getClearedNodes(); for (var i = 0; i < nodes.length; i++) { if (nodes[i].nodeType === 1) { $(nodes[i]).replaceWith(function() { return $(this).contents(); }); } } this.selection.restore(); }, removeStyleRule: function(name) { this.buffer.set(); var parent = this.selection.parent(); var nodes = this.selection.inlines(); this.selection.save(); if (parent && parent.tagName === 'SPAN') { var $s = $(parent); $s.css(name, ''); $s.removeAttr('data-redactor-span'); this.utils.removeEmptyAttr($s, 'style'); if ($s[0].attributes.length === 0) { $s.replaceWith($s.contents()); } } $.each(nodes, $.proxy(function(i,s) { var $s = $(s); if ($.inArray(s.tagName.toLowerCase(), this.opts.inlineTags) != -1 && !$s.hasClass('redactor-selection-marker')) { $s.css(name, ''); this.utils.removeEmptyAttr($s, 'style'); if ($s[0].attributes.length === 0) { $s.replaceWith($s.contents()); } } }, this)); this.selection.restore(); } }; }, // =insert insert: function() { return { set: function(html) { this.placeholder.hide(); this.code.set(html); this.focus.end(); this.placeholder.enable(); }, html: function(html, data) { this.placeholder.hide(); this.core.editor().focus(); var block = this.selection.block(); var inline = this.selection.inline(); // clean if (typeof data === 'undefined') { data = this.clean.getCurrentType(html, true); html = this.clean.onPaste(html, data, true); } html = $.parseHTML(html); // delete selected content var sel = this.selection.get(); var range = this.selection.range(sel); range.deleteContents(); this.selection.update(sel, range); // insert list in list if (data.lists) { var $list = $(html); if ($list.length !== 0 && ($list[0].tagName === 'UL' || $list[0].tagName === 'OL')) { this.insert.appendLists(block, $list); return; } } if (data.blocks && block) { if (this.utils.isSelectAll()) { this.core.editor().html(html); this.focus.end(); } else { var breaked = this.utils.breakBlockTag(); if (breaked === false) { this.insert.placeHtml(html); } else { var $last = $(html).children().last(); $last.append(this.marker.get()); if (breaked.type === 'start') { breaked.$block.before(html); } else { breaked.$block.after(html); } this.selection.restore(); this.core.editor().find('p').each(function() { if ($.trim(this.innerHTML) === '') { $(this).remove(); } }); } } } else { if (inline) { // remove same tag inside var $div = $("<div/>").html(html); $div.find(inline.tagName.toLowerCase()).each(function() { $(this).contents().unwrap(); }); html = $div.html(); } if (this.utils.isSelectAll()) { var $node = $(this.opts.emptyHtml); this.core.editor().html('').append($node); $node.html(html); this.caret.end($node); } else { this.insert.placeHtml(html); } } this.utils.disableSelectAll(); this.linkify.format(); if (data.pre) { this.clean.cleanPre(); } }, text: function(text) { text = text.toString(); text = $.trim(text); var tmp = document.createElement('div'); tmp.innerHTML = text; text = tmp.textContent || tmp.innerText; if (typeof text === 'undefined') { return; } this.placeholder.hide(); this.core.editor().focus(); // blocks var blocks = this.selection.blocks(); // nl to spaces text = text.replace(/\n/g, ' '); // select all if (this.utils.isSelectAll()) { var $node = $(this.opts.emptyHtml); this.core.editor().html('').append($node); $node.html(text); this.caret.end($node); } else { // insert var sel = this.selection.get(); var node = document.createTextNode(text); if (sel.getRangeAt && sel.rangeCount) { var range = sel.getRangeAt(0); range.deleteContents(); range.insertNode(node); range.setStartAfter(node); range.collapse(true); this.selection.update(sel, range); } // wrap node if selected two or more block tags if (blocks.length > 1) { $(node).wrap('<p>'); this.caret.after(node); } } this.utils.disableSelectAll(); this.linkify.format(); this.clean.normalizeCurrentHeading(); }, raw: function(html) { this.placeholder.hide(); this.core.editor().focus(); var sel = this.selection.get(); var range = this.selection.range(sel); range.deleteContents(); var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ((node = el.firstChild)) { lastNode = frag.appendChild(node); } range.insertNode(frag); if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } }, node: function(node, deleteContent) { this.placeholder.hide(); if (typeof this.start !== 'undefined') { this.core.editor().focus(); } node = node[0] || node; var block = this.selection.block(); var gap = this.utils.isBlockTag(node.tagName); var result = true; if (this.utils.isSelectAll()) { if (gap) { this.core.editor().html(node); } else { this.core.editor().html($('<p>').html(node)); } this.code.sync(); } else if (gap && block) { var breaked = this.utils.breakBlockTag(); if (breaked === false) { this.insert.placeNode(node, deleteContent); } else { if (breaked.type === 'start') { breaked.$block.before(node); } else { breaked.$block.after(node); } this.core.editor().find('p:empty').remove(); } } else { result = this.insert.placeNode(node, deleteContent); } this.utils.disableSelectAll(); if (result) { this.caret.end(node); } return node; }, appendLists: function(block, $list) { var $block = $(block); var last; var isEmpty = this.utils.isEmpty(block.innerHTML); if (isEmpty || this.utils.isEndOfElement(block)) { last = $block; $list.find('li').each(function() { last.after(this); last = $(this); }); if (isEmpty) { $block.remove(); } } else if (this.utils.isStartOfElement(block)) { $list.find('li').each(function() { $block.before(this); last = $(this); }); } else { var endOfNode = this.selection.extractEndOfNode(block); $block.after($('<li>').append(endOfNode)); $block.append($list); last = $list; } this.marker.remove(); if (last) { this.caret.end(last); } this.linkify.format(); }, placeHtml: function(html) { var marker = document.createElement('span'); marker.id = 'redactor-insert-marker'; marker = this.insert.node(marker); $(marker).before(html); this.selection.restore(); this.caret.after(marker); $(marker).remove(); }, placeNode: function(node, deleteContent) { var sel = this.selection.get(); var range = this.selection.range(sel); if (range == null) { return false; } if (deleteContent !== false) { range.deleteContents(); } range.insertNode(node); range.collapse(false); this.selection.update(sel, range); }, nodeToPoint: function(e, node) { this.placeholder.hide(); node = node[0] || node; if (this.utils.isEmpty()) { node = (this.utils.isBlock(node)) ? node : $('<p />').append(node); this.core.editor().html(node); return node; } var range; var x = e.clientX, y = e.clientY; if (document.caretPositionFromPoint) { var pos = document.caretPositionFromPoint(x, y); var sel = document.getSelection(); range = sel.getRangeAt(0); range.setStart(pos.offsetNode, pos.offset); range.collapse(true); range.insertNode(node); } else if (document.caretRangeFromPoint) { range = document.caretRangeFromPoint(x, y); range.insertNode(node); } else if (typeof document.body.createTextRange !== "undefined") { range = document.body.createTextRange(); range.moveToPoint(x, y); var endRange = range.duplicate(); endRange.moveToPoint(x, y); range.setEndPoint("EndToEnd", endRange); range.select(); } return node; }, // #backward nodeToCaretPositionFromPoint: function(e, node) { this.insert.nodeToPoint(e, node); }, marker: function() { this.marker.insert(); } }; }, // =keydown keydown: function() { return { init: function(e) { if (this.rtePaste) { return; } var key = e.which; var arrow = (key >= 37 && key <= 40); this.keydown.ctrl = e.ctrlKey || e.metaKey; this.keydown.parent = this.selection.parent(); this.keydown.current = this.selection.current(); this.keydown.block = this.selection.block(); // detect tags this.keydown.pre = this.utils.isTag(this.keydown.current, 'pre'); this.keydown.blockquote = this.utils.isTag(this.keydown.current, 'blockquote'); this.keydown.figcaption = this.utils.isTag(this.keydown.current, 'figcaption'); this.keydown.figure = this.utils.isTag(this.keydown.current, 'figure'); // callback var keydownStop = this.core.callback('keydown', e); if (keydownStop === false) { e.preventDefault(); return false; } // shortcuts setup this.shortcuts.init(e, key); // buffer this.keydown.checkEvents(arrow, key); this.keydown.setupBuffer(e, key); if (this.utils.isSelectAll() && ( key === this.keyCode.ENTER || key === this.keyCode.BACKSPACE || key === this.keyCode.DELETE)) { e.preventDefault(); this.code.set(this.opts.emptyHtml); return; } this.keydown.addArrowsEvent(arrow); this.keydown.setupSelectAll(e, key); // turn off enter key if (!this.opts.enterKey && key === this.keyCode.ENTER) { e.preventDefault(); // remove selected var sel = this.selection.get(); var range = this.selection.range(sel); if (!range.collapsed) { range.deleteContents(); } return; } // down if (this.opts.enterKey && key === this.keyCode.DOWN) { this.keydown.onArrowDown(); } // up if (this.opts.enterKey && key === this.keyCode.UP) { this.keydown.onArrowUp(); } // replace to p before / after the table or into body if ((this.opts.type === 'textarea' || this.opts.type === 'div') && this.keydown.current && this.keydown.current.nodeType === 3 && $(this.keydown.parent).hasClass('redactor-in')) { this.keydown.wrapToParagraph(); } // on Shift+Space or Ctrl+Space if (!this.keyup.lastShiftKey && key === this.keyCode.SPACE && (e.ctrlKey || e.shiftKey)) { e.preventDefault(); return this.keydown.onShiftSpace(); } // on Shift+Enter or Ctrl+Enter if (key === this.keyCode.ENTER && (e.ctrlKey || e.shiftKey)) { e.preventDefault(); return this.keydown.onShiftEnter(e); } // on enter if (key === this.keyCode.ENTER && !e.shiftKey && !e.ctrlKey && !e.metaKey) { return this.keydown.onEnter(e); } // tab or cmd + [ if (key === this.keyCode.TAB || e.metaKey && key === 221 || e.metaKey && key === 219) { return this.keydown.onTab(e, key); } // firefox bugfix if (this.detect.isFirefox() && key === this.keyCode.BACKSPACE && this.keydown.block && this.keydown.block.tagName === 'P' && this.utils.isStartOfElement(this.keydown.block)) { var $prev = $(this.keydown.block).prev(); if ($prev.length !== 0) { e.preventDefault(); $prev.append(this.marker.get()); $prev.append($(this.keydown.block).html()); $(this.keydown.block).remove(); this.selection.restore(); return; } } // backspace & delete if (key === this.keyCode.BACKSPACE || key === this.keyCode.DELETE) { if (this.observe.image && typeof this.observe.image !== 'undefined' && $('#redactor-image-box').length !== 0) { e.preventDefault(); var $prev = this.observe.image.closest('figure, p').prev() this.image.remove(false); this.observe.image = false; if ($prev && $prev.length !== 0) { this.caret.end($prev); } else { this.core.editor().focus(); } return; } this.keydown.onBackspaceAndDeleteBefore(); } if (key === this.keyCode.DELETE) { var $next = $(this.keydown.block).next(); // delete figure if (this.utils.isEndOfElement(this.keydown.block) && $next.length !== 0 && $next[0].tagName === 'FIGURE') { $next.remove(); return false; } // append list (safari bug) var tagLi = (this.keydown.block && this.keydown.block.tagName === 'LI') ? this.keydown.block : false; if (tagLi) { var $list = $(this.keydown.block).parents('ul, ol').last(); var $nextList = $list.next(); if (this.utils.isRedactorParent($list) && this.utils.isEndOfElement($list) && $nextList.length !== 0 && ($nextList[0].tagName === 'UL' || $nextList[0].tagName === 'OL')) { e.preventDefault(); $list.append($nextList.contents()); $nextList.remove(); return false; } } // append pre if (this.utils.isEndOfElement(this.keydown.block) && $next.length !== 0 && $next[0].tagName === 'PRE') { $(this.keydown.block).append($next.text()); $next.remove(); return false; } } // image delete if (key === this.keyCode.DELETE && $('#redactor-image-box').length !== 0) { this.image.remove(); } // backspace if (key === this.keyCode.BACKSPACE) { if (this.detect.isFirefox()) { this.line.removeOnBackspace(e); } // combine list after and before if paragraph is empty if (this.list.combineAfterAndBefore(this.keydown.block)) { e.preventDefault(); return; } // backspace as outdent var block = this.selection.block(); if (block && block.tagName === 'LI' && this.utils.isCollapsed() && this.utils.isStartOfElement()) { this.indent.decrease(); e.preventDefault(); return; } this.keydown.removeInvisibleSpace(); this.keydown.removeEmptyListInTable(e); } if (key === this.keyCode.BACKSPACE || key === this.keyCode.DELETE) { this.keydown.onBackspaceAndDeleteAfter(e); } }, onShiftSpace: function() { this.buffer.set(); this.insert.raw('&nbsp;'); return false; }, onShiftEnter: function(e) { this.buffer.set(); return (this.keydown.pre) ? this.keydown.insertNewLine(e) : this.insert.raw('<br>'); }, onBackspaceAndDeleteBefore: function() { this.utils.saveScroll(); }, onBackspaceAndDeleteAfter: function(e) { // remove style tag setTimeout($.proxy(function() { this.code.syncFire = false; this.keydown.removeEmptyLists(); this.core.editor().find('*[style]').not('img, figure, #redactor-image-box, #redactor-image-editter, [data-redactor-span]').removeAttr('style'); this.keydown.formatEmpty(e); this.code.syncFire = true; }, this), 1); }, onEnter: function(e) { var stop = this.core.callback('enter', e); if (stop === false) { e.preventDefault(); return false; } // blockquote exit if (this.keydown.blockquote && this.keydown.exitFromBlockquote(e) === true) { return false; } // pre if (this.keydown.pre) { return this.keydown.insertNewLine(e); } // blockquote & figcaption else if (this.keydown.blockquote || this.keydown.figcaption) { return this.keydown.insertBreakLine(e); } // figure else if (this.keydown.figure) { setTimeout($.proxy(function() { this.keydown.replaceToParagraph('FIGURE'); }, this), 1); } // paragraphs else if (this.keydown.block) { setTimeout($.proxy(function() { this.keydown.replaceToParagraph('DIV'); }, this), 1); // empty list exit if (this.keydown.block.tagName === 'LI') { var current = this.selection.current(); var $parent = $(current).closest('li', this.$editor[0]); var $list = $parent.parents('ul,ol', this.$editor[0]).last(); if ($parent.length !== 0 && this.utils.isEmpty($parent.html()) && $list.next().length === 0 && this.utils.isEmpty($list.find("li").last().html())) { $list.find("li").last().remove(); var node = $(this.opts.emptyHtml); $list.after(node); this.caret.start(node); return false; } } } // outside else if (!this.keydown.block) { return this.keydown.insertParagraph(e); } // firefox enter into inline element if (this.detect.isFirefox() && this.utils.isInline(this.keydown.parent)) { this.keydown.insertBreakLine(e); return; } // remove inline tags in new-empty paragraph setTimeout($.proxy(function() { var inline = this.selection.inline(); if (inline && this.utils.isEmpty(inline.innerHTML)) { var parent = this.selection.block(); $(inline).remove(); //this.caret.start(parent); var range = document.createRange(); range.setStart(parent, 0); var textNode = document.createTextNode('\u200B'); range.insertNode(textNode); range.setStartAfter(textNode); range.collapse(true); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } }, this), 1); }, checkEvents: function(arrow, key) { if (!arrow && (this.core.getEvent() === 'click' || this.core.getEvent() === 'arrow')) { this.core.addEvent(false); if (this.keydown.checkKeyEvents(key)) { this.buffer.set(); } } }, checkKeyEvents: function(key) { var k = this.keyCode; var keys = [k.BACKSPACE, k.DELETE, k.ENTER, k.ESC, k.TAB, k.CTRL, k.META, k.ALT, k.SHIFT]; return ($.inArray(key, keys) === -1) ? true : false; }, addArrowsEvent: function(arrow) { if (!arrow) { return; } if ((this.core.getEvent() === 'click' || this.core.getEvent() === 'arrow')) { this.core.addEvent(false); return; } this.core.addEvent('arrow'); }, setupBuffer: function(e, key) { if (this.keydown.ctrl && key === 90 && !e.shiftKey && !e.altKey && this.opts.buffer.length) // z key { e.preventDefault(); this.buffer.undo(); return; } // redo else if (this.keydown.ctrl && key === 90 && e.shiftKey && !e.altKey && this.opts.rebuffer.length !== 0) { e.preventDefault(); this.buffer.redo(); return; } else if (!this.keydown.ctrl) { if (key === this.keyCode.SPACE || key === this.keyCode.BACKSPACE || key === this.keyCode.DELETE || (key === this.keyCode.ENTER && !e.ctrlKey && !e.shiftKey)) { this.buffer.set(); } } }, exitFromBlockquote: function(e) { if (!this.utils.isEndOfElement(this.keydown.blockquote)) { return; } var tmp = this.clean.removeSpacesHard($(this.keydown.blockquote).html()); if (tmp.search(/(<br\s?\/?>){1}$/i) !== -1) { e.preventDefault(); var $last = $(this.keydown.blockquote).children().last(); $last.filter('br').remove(); $(this.keydown.blockquote).children().last().filter('span').remove(); var node = $(this.opts.emptyHtml); $(this.keydown.blockquote).after(node); this.caret.start(node); return true; } return; }, onArrowDown: function() { var tags = [this.keydown.blockquote, this.keydown.pre, this.keydown.figcaption]; for (var i = 0; i < tags.length; i++) { if (tags[i]) { this.keydown.insertAfterLastElement(tags[i]); return false; } } }, onArrowUp: function() { var tags = [this.keydown.blockquote, this.keydown.pre, this.keydown.figcaption]; for (var i = 0; i < tags.length; i++) { if (tags[i]) { this.keydown.insertBeforeFirstElement(tags[i]); return false; } } }, insertAfterLastElement: function(element) { if (!this.utils.isEndOfElement(element)) { return; } var last = this.core.editor().contents().last(); var $next = (element.tagName === 'FIGCAPTION') ? $(this.keydown.block).parent().next() : $(this.keydown.block).next(); if ($next.length !== 0) { return; } else if (last.length === 0 && last[0] !== element) { this.caret.start(last); return; } else { var node = $(this.opts.emptyHtml); if (element.tagName === 'FIGCAPTION') { $(element).parent().after(node); } else { $(element).after(node); } this.caret.start(node); } }, insertBeforeFirstElement: function(element) { if (!this.utils.isStartOfElement()) { return; } if (this.core.editor().contents().length > 1 && this.core.editor().contents().first()[0] !== element) { return; } var node = $(this.opts.emptyHtml); $(element).before(node); this.caret.start(node); }, onTab: function(e, key) { if (!this.opts.tabKey) { return true; } var isList = (this.keydown.block && this.keydown.block.tagName === 'LI') if (this.utils.isEmpty(this.code.get()) || (!isList && !this.keydown.pre && this.opts.tabAsSpaces === false)) { return true; } e.preventDefault(); this.buffer.set(); var isListStart = (isList && this.utils.isStartOfElement(this.keydown.block)); var node; if (this.keydown.pre && !e.shiftKey) { node = (this.opts.preSpaces) ? document.createTextNode(Array(this.opts.preSpaces + 1).join('\u00a0')) : document.createTextNode('\t'); this.insert.node(node); } else if (this.opts.tabAsSpaces !== false && !isListStart) { node = document.createTextNode(Array(this.opts.tabAsSpaces + 1).join('\u00a0')); this.insert.node(node); } else { if (e.metaKey && key === 219) { this.indent.decrease(); } else if (e.metaKey && key === 221) { this.indent.increase(); } else if (!e.shiftKey) { this.indent.increase(); } else { this.indent.decrease(); } } return false; }, setupSelectAll: function(e, key) { if (this.keydown.ctrl && key === 65) { this.utils.enableSelectAll(); } else if (key !== this.keyCode.LEFT_WIN && !this.keydown.ctrl) { this.utils.disableSelectAll(); } }, insertNewLine: function(e) { e.preventDefault(); var node = document.createTextNode('\n'); var sel = this.selection.get(); var range = this.selection.range(sel); range.deleteContents(); range.insertNode(node); this.caret.after(node); return false; }, insertParagraph: function(e) { e.preventDefault(); var p = document.createElement('p'); p.innerHTML = this.opts.invisibleSpace; var sel = this.selection.get(); var range = this.selection.range(sel); range.deleteContents(); range.insertNode(p); this.caret.start(p); return false; }, insertBreakLine: function(e) { return this.keydown.insertBreakLineProcessing(e); }, insertDblBreakLine: function(e) { return this.keydown.insertBreakLineProcessing(e, true); }, insertBreakLineProcessing: function(e, dbl) { e.stopPropagation(); var br1 = document.createElement('br'); this.insert.node(br1); if (dbl === true) { var br2 = document.createElement('br'); this.insert.node(br2); this.caret.after(br2); } else { this.caret.after(br1); } return false; }, wrapToParagraph: function() { var $current = $(this.keydown.current); var node = $('<p>').append($current.clone()); $current.replaceWith(node); var next = $(node).next(); if (typeof(next[0]) !== 'undefined' && next[0].tagName === 'BR') { next.remove(); } this.caret.end(node); }, replaceToParagraph: function(tag) { var blockElem = this.selection.block(); var $prev = $(blockElem).prev(); var blockHtml = blockElem.innerHTML.replace(/<br\s?\/?>/gi, ''); if (blockElem.tagName === tag && this.utils.isEmpty(blockHtml) && !$(blockElem).hasClass('redactor-in')) { var p = document.createElement('p'); $(blockElem).replaceWith(p); this.keydown.setCaretToParagraph(p); return false; } else if (blockElem.tagName === 'P') { $(blockElem).removeAttr('class').removeAttr('style'); // fix #227 if (this.detect.isIe() && this.utils.isEmpty(blockHtml) && this.utils.isInline(this.keydown.parent)) { $(blockElem).on('input', $.proxy(function() { var parent = this.selection.parent(); if (this.utils.isInline(parent)) { var html = $(parent).html(); $(blockElem).html(html); this.caret.end(blockElem); } $(blockElem).off('keyup'); }, this)); } return false; } else if ($prev.hasClass(this.opts.videoContainerClass)) { $prev.removeAttr('class'); var p = document.createElement('p'); $prev.replaceWith(p); this.keydown.setCaretToParagraph(p); return false; } }, setCaretToParagraph: function(p) { var range = document.createRange(); range.setStart(p, 0); var textNode = document.createTextNode('\u200B'); range.insertNode(textNode); range.setStartAfter(textNode); range.collapse(true); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); }, removeInvisibleSpace: function() { var $current = $(this.keydown.current); if ($current.text().search(/^\u200B$/g) === 0) { $current.remove(); } }, removeEmptyListInTable: function(e) { var $current = $(this.keydown.current); var $parent = $(this.keydown.parent); var td = $current.closest('td', this.$editor[0]); if (td.length !== 0 && $current.closest('li', this.$editor[0]) && $parent.children('li').length === 1) { if (!this.utils.isEmpty($current.text())) { return; } e.preventDefault(); $current.remove(); $parent.remove(); this.caret.start(td); } }, removeEmptyLists: function() { var removeIt = function() { var html = $.trim(this.innerHTML).replace(/\/t\/n/g, ''); if (html === '') { $(this).remove(); } }; this.core.editor().find('li').each(removeIt); this.core.editor().find('ul, ol').each(removeIt); }, formatEmpty: function(e) { var html = $.trim(this.core.editor().html()); if (!this.utils.isEmpty(html)) { return; } e.preventDefault(); if (this.opts.type === 'inline' || this.opts.type === 'pre') { this.core.editor().html(this.marker.html()); this.selection.restore(); } else { this.core.editor().html(this.opts.emptyHtml); this.focus.start(); } return false; } }; }, // =keyup keyup: function() { return { init: function(e) { if (this.rtePaste) { return; } var key = e.which; this.keyup.block = this.selection.block(); this.keyup.current = this.selection.current(); this.keyup.parent = this.selection.parent(); this.keyup.lastShiftKey = e.shiftKey; // callback var stop = this.core.callback('keyup', e); if (stop === false) { e.preventDefault(); return false; } // replace a prev figure to paragraph if caret is before image if (key === this.keyCode.ENTER) { if (this.keyup.block && this.keyup.block.tagName === 'FIGURE') { var $prev = $(this.keyup.block).prev(); if ($prev.length !== 0 && $prev[0].tagName === 'FIGURE') { var $newTag = this.utils.replaceToTag($prev, 'p'); this.caret.start($newTag); return; } } } // replace figure to paragraph if (key === this.keyCode.BACKSPACE || key === this.keyCode.DELETE) { if (this.utils.isSelectAll()) { this.focus.start(); return; } // if caret before figure - delete image if (this.keyup.block && this.keydown.block && this.keyup.block.tagName === 'FIGURE' && this.utils.isStartOfElement(this.keydown.block)) { e.preventDefault(); this.selection.save(); $(this.keyup.block).find('figcaption').remove(); $(this.keyup.block).find('img').first().remove(); this.utils.replaceToTag(this.keyup.block, 'p'); var $marker = this.marker.find(); $('html, body').animate({ scrollTop: $marker.position().top + 20 }, 500); this.selection.restore(); return; } // if paragraph does contain only image replace to figure if (this.keyup.block && this.keyup.block.tagName === 'P') { var isContainImage = $(this.keyup.block).find('img').length; var text = $(this.keyup.block).text().replace(/\u200B/g, ''); if (text === '' && isContainImage !== 0) { this.utils.replaceToTag(this.keyup.block, 'figure'); } } // if figure does not contain image - replace to paragraph if (this.keyup.block && this.keyup.block.tagName === 'FIGURE' && $(this.keyup.block).find('img').length === 0) { this.selection.save(); this.utils.replaceToTag(this.keyup.block, 'p'); this.selection.restore(); } } // linkify if (this.linkify.isKey(key)) { this.linkify.format(); } } }; }, // =lang lang: function() { return { load: function() { this.opts.curLang = this.opts.langs[this.opts.lang]; }, get: function(name) { return (typeof this.opts.curLang[name] !== 'undefined') ? this.opts.curLang[name] : ''; } }; }, // =line line: function() { return { insert: function() { this.buffer.set(); // insert this.insert.html(this.line.getLineHtml()); // find var $hr = this.core.editor().find('#redactor-hr-tmp-id'); $hr.removeAttr('id'); this.core.callback('insertedLine', $hr); return $hr; }, getLineHtml: function() { var html = '<hr id="redactor-hr-tmp-id" />'; if (!this.detect.isFirefox() && this.utils.isEmpty()) { html += '<p>' + this.opts.emptyHtml + '</p>'; } return html; }, // ff only removeOnBackspace: function(e) { if (!this.utils.isCollapsed()) { return; } var $block = $(this.selection.block()); if ($block.length === 0 || !this.utils.isStartOfElement($block)) { return; } // if hr is previous element var $prev = $block.prev(); if ($prev && $prev.length !== 0 && $prev[0].tagName === 'HR') { e.preventDefault(); $prev.remove(); } } }; }, // =link link: function() { return { // public get: function() { return $(this.selection.inlines('a')); }, is: function() { var nodes = this.selection.nodes() ; var $link = $(this.selection.current()).closest('a', this.core.editor()[0]); return ($link.length === 0 || nodes.length > 1) ? false : $link; }, unlink: function(e) { // if call from clickable element if (typeof e !== 'undefined' && e.preventDefault) { e.preventDefault(); } // buffer this.buffer.set(); var links = this.selection.inlines('a'); if (links.length === 0) { return; } var $links = this.link.replaceLinksToText(links); this.observe.closeAllTooltip(); this.core.callback('deletedLink', $links); }, insert: function(link, cleaned) { var $el = this.link.is(); if (cleaned !== true) { link = this.link.buildLinkFromObject($el, link); if (link === false) { return false; } } // buffer this.buffer.set(); // callback link = this.core.callback('beforeInsertingLink', link); if ($el === false) { // insert $el = $('<a />'); $el = this.link.update($el, link); $el = $(this.insert.node($el)); var $parent = $el.parent(); if (this.utils.isRedactorParent($parent) === false) { $el.wrap('<p>'); } // remove unlink wrapper if ($parent.hasClass('redactor-unlink')) { $parent.replaceWith(function(){ return $(this).contents(); }); } this.caret.after($el); this.core.callback('insertedLink', $el); } else { // update $el = this.link.update($el, link); this.caret.after($el); } }, update: function($el, link) { $el.text(link.text); $el.attr('href', link.url); this.link.target($el, link.target); return $el; }, target: function($el, target) { return (target) ? $el.attr('target', '_blank') : $el.removeAttr('target'); }, show: function(e) { // if call from clickable element if (typeof e !== 'undefined' && e.preventDefault) { e.preventDefault(); } // close tooltip this.observe.closeAllTooltip(); // is link var $el = this.link.is(); // build modal this.link.buildModal($el); // build link var link = this.link.buildLinkFromElement($el); // if link cut & paste inside editor browser added self host to a link link.url = this.link.removeSelfHostFromUrl(link.url); // new tab target if (this.opts.linkNewTab && !$el) { link.target = true; } // set modal values this.link.setModalValues(link); // show modal this.modal.show(); // focus if (this.detect.isDesktop()) { $('#redactor-link-url').focus(); } }, // private setModalValues: function(link) { $('#redactor-link-blank').prop('checked', link.target); $('#redactor-link-url').val(link.url); $('#redactor-link-url-text').val(link.text); }, buildModal: function($el) { this.modal.load('link', this.lang.get(($el === false) ? 'link-insert' : 'link-edit'), 600); // button insert var $btn = this.modal.getActionButton(); $btn.text(this.lang.get(($el === false) ? 'insert' : 'save')).on('click', $.proxy(this.link.callback, this)); }, callback: function() { // build link var link = this.link.buildLinkFromModal(); if (link === false) { return false; } // close this.modal.close(); // insert or update this.link.insert(link, true); }, cleanUrl: function(url) { return (typeof url === 'undefined') ? '' : $.trim(url.replace(/[^\W\w\D\d+&\'@#/%?=~_|!:,.;\(\)]/gi, '')); }, cleanText: function(text) { return (typeof text === 'undefined') ? '' :$.trim(text.replace(/(<([^>]+)>)/gi, '')); }, getText: function(link) { return (link.text === '' && link.url !== '') ? this.link.truncateUrl(link.url.replace(/<|>/g, '')) : link.text; }, isUrl: function(url) { var pattern = '((xn--)?[\\W\\w\\D\\d]+(-[\\W\\w\\D\\d]+)*\\.)+[\\W\\w]{2,}'; var re1 = new RegExp('^(http|ftp|https)://' + pattern, 'i'); var re2 = new RegExp('^' + pattern, 'i'); var re3 = new RegExp('\.(html|php)$', 'i'); var re4 = new RegExp('^/', 'i'); var re5 = new RegExp('^tel:(.*?)', 'i'); // add protocol if (url.search(re1) === -1 && url.search(re2) !== -1 && url.search(re3) === -1 && url.substring(0, 1) !== '/') { url = 'http://' + url; } if (url.search(re1) !== -1 || url.search(re3) !== -1 || url.search(re4) !== -1 || url.search(re5) !== -1) { return url; } return false; }, isMailto: function(url) { return (url.search('@') !== -1 && /(http|ftp|https):\/\//i.test(url) === false); }, isEmpty: function(link) { return (link.url === '' || (link.text === '' && link.url === '')); }, truncateUrl: function(url) { return (url.length > this.opts.linkSize) ? url.substring(0, this.opts.linkSize) + '...' : url; }, parse: function(link) { // mailto if (this.link.isMailto(link.url)) { link.url = 'mailto:' + link.url.replace('mailto:', ''); } // url else if (link.url.search('#') !== 0) { link.url = this.link.isUrl(link.url); } // empty url or text or isn't url return (this.link.isEmpty(link) || link.url === false) ? false : link; }, buildLinkFromModal: function() { var link = {}; // url link.url = this.link.cleanUrl($('#redactor-link-url').val()); // text link.text = this.link.cleanText($('#redactor-link-url-text').val()); link.text = this.link.getText(link); // target link.target = ($('#redactor-link-blank').prop('checked')) ? true : false; // parse return this.link.parse(link); }, buildLinkFromObject: function($el, link) { // url link.url = this.link.cleanUrl(link.url); // text link.text = (typeof link.text === 'undefined' && this.selection.is()) ? this.selection.text() : this.link.cleanText(link.text); link.text = this.link.getText(link); // target link.target = ($el === false) ? link.target : this.link.buildTarget($el); // parse return this.link.parse(link); }, buildLinkFromElement: function($el) { var link = { url: '', text: (this.selection.is()) ? this.selection.text() : '', target: false }; if ($el !== false) { link.url = $el.attr('href'); link.text = $el.text(); link.target = this.link.buildTarget($el); } return link; }, buildTarget: function($el) { return (typeof $el.attr('target') !== 'undefined' && $el.attr('target') === '_blank') ? true : false; }, removeSelfHostFromUrl: function(url) { var href = self.location.href.replace('#', '').replace(/\/$/i, ''); return url.replace(/^\/\#/, '#').replace(href, '').replace('mailto:', ''); }, replaceLinksToText: function(links) { var $first; var $links = $.each(links, function(i,s) { var $el = $(s); var $unlinked = $('<span class="redactor-unlink" />').append($el.contents()); $el.replaceWith($unlinked); if (i === 0) { $first = $unlinked; } return $el; }); // set caret after unlinked node if (links.length === 1 && this.selection.isCollapsed()) { this.caret.after($first); } return $links; } }; }, // =linkify linkify: function() { return { isKey: function(key) { return key === this.keyCode.ENTER || key === this.keyCode.SPACE; }, isLink: function(node) { return (node.nodeValue.match(this.opts.regexps.linkyoutube) || node.nodeValue.match(this.opts.regexps.linkvimeo) || node.nodeValue.match(this.opts.regexps.linkimage) || node.nodeValue.match(this.opts.regexps.url)); }, isFiltered: function(i, node) { return node.nodeType === 3 && $.trim(node.nodeValue) !== "" && !$(node).parent().is("pre") && (this.linkify.isLink(node)); }, handler: function(i, node) { var $el = $(node); var text = $el.text(); var html = text; if (html.match(this.opts.regexps.linkyoutube) || html.match(this.opts.regexps.linkvimeo)) { html = this.linkify.convertVideoLinks(html); } else if (html.match(this.opts.regexps.linkimage)) { html = this.linkify.convertImages(html); } else { html = this.linkify.convertLinks(html); } $el.before(text.replace(text, html)).remove(); }, format: function() { if (!this.opts.linkify || this.utils.isCurrentOrParent('pre')) { return; } this.core.editor().find(":not(iframe,img,a,pre,code,.redactor-unlink)").addBack().contents().filter($.proxy(this.linkify.isFiltered, this)).each($.proxy(this.linkify.handler, this)); // collect var $objects = this.core.editor().find('.redactor-linkify-object').each($.proxy(function(i,s) { var $el = $(s); $el.removeClass('redactor-linkify-object'); if ($el.attr('class') === '') { $el.removeAttr('class'); } if (s.tagName === 'DIV') // video container { this.linkify.breakBlockTag($el, 'video'); } else if (s.tagName === 'IMG') // image { this.linkify.breakBlockTag($el, 'image'); } else if (s.tagName === 'A') { this.core.callback('insertedLink', $el); } return $el; }, this)); // callback setTimeout($.proxy(function() { this.code.sync(); this.core.callback('linkify', $objects); }, this), 100); }, breakBlockTag: function($el, type) { var breaked = this.utils.breakBlockTag(); if (breaked === false) { return; } var $newBlock = $el; if (type === 'image') { $newBlock = $('<figure />').append($el); } if (breaked.type === 'start') { breaked.$block.before($newBlock); } else { breaked.$block.after($newBlock); } if (type === 'image') { this.caret.after($newBlock); } }, convertVideoLinks: function(html) { var iframeStart = '<div class="' + this.opts.videoContainerClass + ' redactor-linkify-object"><iframe class="redactor-linkify-object" width="500" height="281" src="'; var iframeEnd = '" frameborder="0" allowfullscreen></iframe></div>'; if (html.match(this.opts.regexps.linkyoutube)) { html = html.replace(this.opts.regexps.linkyoutube, iframeStart + '//www.youtube.com/embed/$1' + iframeEnd); } if (html.match(this.opts.regexps.linkvimeo)) { html = html.replace(this.opts.regexps.linkvimeo, iframeStart + '//player.vimeo.com/video/$2' + iframeEnd); } return html; }, convertImages: function(html) { var matches = html.match(this.opts.regexps.linkimage); if (!matches) { return html; } return html.replace(html, '<img src="' + matches + '" class="redactor-linkify-object" />'); }, convertLinks: function(html) { var matches = html.match(this.opts.regexps.url); if (!matches) { return html; } matches = $.grep(matches, function(v, k) { return $.inArray(v, matches) === k; }); var length = matches.length; for (var i = 0; i < length; i++) { var href = matches[i], text = href; var linkProtocol = (href.match(/(https?|ftp):\/\//i) !== null) ? '' : 'http://'; if (text.length > this.opts.linkSize) { text = text.substring(0, this.opts.linkSize) + '...'; } if (text.search('%') === -1) { text = decodeURIComponent(text); } var regexB = "\\b"; if ($.inArray(href.slice(-1), ["/", "&", "="]) !== -1) { regexB = ""; } // escaping url var regexp = new RegExp('(' + href.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + regexB + ')', 'g'); html = html.replace(regexp, '<a href="' + linkProtocol + $.trim(href) + '" class="redactor-linkify-object">' + $.trim(text) + '</a>'); } return html; } }; }, // =list list: function() { return { toggle: function(cmd) { if (this.utils.inBlocks(['table', 'td', 'th', 'tr'])) { return; } var tag = (cmd === 'orderedlist' || cmd === 'ol') ? 'OL' : 'UL'; cmd = (tag === 'OL') ? 'orderedlist' : 'unorderedlist' var $list = $(this.selection.current()).parentsUntil('.redactor-in', 'ul, ol').first(); this.placeholder.hide(); this.buffer.set(); if ($list.length !== 0 && $list[0].tagName === tag && this.utils.isRedactorParent($list)) { this.selection.save(); // remove list $list.find('ul, ol').each(function() { var parent = $(this).closest('li'); $(this).find('li').each(function() { $(parent).after(this); }); }); $list.find('ul, ol').remove(); $list.find('li').each(function() { return $(this).replaceWith(function() { return $('<p />').append($(this).contents()); }); }); $list.replaceWith(function() { return $(this).contents(); }); this.selection.restore(); return; } this.selection.save(); if ($list.length !== 0 && $list[0].tagName !== tag) { $list.each($.proxy(function(i,s) { this.utils.replaceToTag(s, tag); }, this)); } else { document.execCommand('insert' + cmd); } this.selection.restore(); var $insertedList = this.list.get(); if (!$insertedList) { if (!this.selection.block()) { document.execCommand('formatblock', false, 'p'); } return; } // clear span $insertedList.find('span').replaceWith(function() { return $(this).contents(); }); // remove style $insertedList.find(this.opts.inlineTags.join(',')).each(function() { $(this).removeAttr('style'); }); // remove block-element list wrapper var $listParent = $insertedList.parent(); if (this.utils.isRedactorParent($listParent) && $listParent[0].tagName !== 'LI' && this.utils.isBlock($listParent)) { this.selection.save(); $listParent.replaceWith($listParent.contents()); this.selection.restore(); } }, get: function() { var current = this.selection.current(); var $list = $(current).closest('ul, ol', this.core.editor()[0]); return ($list.length === 0) ? false : $list; }, combineAfterAndBefore: function(block) { var $prev = $(block).prev(); var $next = $(block).next(); var isEmptyBlock = (block && block.tagName === 'P' && (block.innerHTML === '<br>' || block.innerHTML === '')); var isBlockWrapped = ($prev.closest('ol, ul', this.core.editor()[0]).length === 1 && $next.closest('ol, ul', this.core.editor()[0]).length === 1); if (isEmptyBlock && isBlockWrapped) { $prev.children('li').last().append(this.marker.get()); $prev.append($next.contents()); this.selection.restore(); return true; } return false; } }; }, // =marker marker: function() { return { // public get: function(num) { num = (typeof num === 'undefined') ? 1 : num; var marker = document.createElement('span'); marker.id = 'selection-marker-' + num; marker.className = 'redactor-selection-marker'; marker.innerHTML = this.opts.invisibleSpace; return marker; }, html: function(num) { return this.utils.getOuterHtml(this.marker.get(num)); }, find: function(num) { num = (typeof num === 'undefined') ? 1 : num; return this.core.editor().find('span#selection-marker-' + num); }, insert: function() { var sel = this.selection.get(); var range = this.selection.range(sel); this.marker.insertNode(range, this.marker.get(1), true); if (range && range.collapsed === false) { this.marker.insertNode(range, this.marker.get(2), false); } }, remove: function() { this.core.editor().find('.redactor-selection-marker').each(this.marker.iterateRemove); }, // private insertNode: function(range, node, collapse) { var parent = this.selection.parent(); if (range === null || $(parent).closest('.redactor-in').length === 0) { return; } range = range.cloneRange(); try { range.collapse(collapse); range.insertNode(node); } catch (e) { this.focus.start(); } }, iterateRemove: function(i, el) { var $el = $(el); var text = $el.text().replace(/\u200B/g, ''); return (text === '') ? $el.remove() : $el.replaceWith(function() { return $(this).contents(); }); } }; }, // =modal modal: function() { return { callbacks: {}, templates: function() { this.opts.modal = { 'image-edit': String() + '<div class="redactor-modal-tab redactor-group" data-title="General">' + '<div id="redactor-image-preview" class="redactor-modal-tab-side">' + '</div>' + '<div class="redactor-modal-tab-area">' + '<section>' + '<label>' + this.lang.get('title') + '</label>' + '<input type="text" id="redactor-image-title" />' + '</section>' + '<section>' + '<label>' + this.lang.get('caption') + '</label>' + '<input type="text" id="redactor-image-caption" aria-label="' + this.lang.get('caption') + '" />' + '</section>' + '<section>' + '<label>' + this.lang.get('link') + '</label>' + '<input type="text" id="redactor-image-link" aria-label="' + this.lang.get('link') + '" />' + '</section>' + '<section>' + '<label class="redactor-image-position-option">' + this.lang.get('image-position') + '</label>' + '<select class="redactor-image-position-option" id="redactor-image-align" aria-label="' + this.lang.get('image-position') + '">' + '<option value="none">' + this.lang.get('none') + '</option>' + '<option value="left">' + this.lang.get('left') + '</option>' + '<option value="center">' + this.lang.get('center') + '</option>' + '<option value="right">' + this.lang.get('right') + '</option>' + '</select>' + '</section>' + '<section>' + '<label class="checkbox"><input type="checkbox" id="redactor-image-link-blank" aria-label="' + this.lang.get('link-in-new-tab') + '"> ' + this.lang.get('link-in-new-tab') + '</label>' + '</section>' + '<section>' + '<button id="redactor-modal-button-action">' + this.lang.get('insert') + '</button>' + '<button id="redactor-modal-button-cancel">' + this.lang.get('cancel') + '</button>' + '<button id="redactor-modal-button-delete" class="redactor-modal-button-offset">' + this.lang.get('delete') + '</button>' + '</section>' + '</div>' + '</div>', 'image': String() + '<div class="redactor-modal-tab" data-title="Upload">' + '<section>' + '<div id="redactor-modal-image-droparea"></div>' + '</section>' + '</div>', 'file': String() + '<div class="redactor-modal-tab" data-title="Upload">' + '<section>' + '<label>' + this.lang.get('filename') + ' <span class="desc">(' + this.lang.get('optional') + ')</span></label>' + '<input type="text" id="redactor-filename" aria-label="' + this.lang.get('filename') + '" /><br><br>' + '</section>' + '<section>' + '<div id="redactor-modal-file-upload"></div>' + '</section>' + '</div>', 'link': String() + '<div class="redactor-modal-tab" data-title="General">' + '<section>' + '<label>URL</label>' + '<input type="url" id="redactor-link-url" aria-label="URL" />' + '</section>' + '<section>' + '<label>' + this.lang.get('text') + '</label>' + '<input type="text" id="redactor-link-url-text" aria-label="' + this.lang.get('text') + '" />' + '</section>' + '<section>' + '<label class="checkbox"><input type="checkbox" id="redactor-link-blank"> ' + this.lang.get('link-in-new-tab') + '</label>' + '</section>' + '<section>' + '<button id="redactor-modal-button-action">' + this.lang.get('insert') + '</button>' + '<button id="redactor-modal-button-cancel">' + this.lang.get('cancel') + '</button>' + '</section>' + '</div>' }; $.extend(this.opts, this.opts.modal); }, addCallback: function(name, callback) { this.modal.callbacks[name] = callback; }, addTemplate: function(name, template) { this.opts.modal[name] = template; }, getTemplate: function(name) { return this.opts.modal[name]; }, getModal: function() { return this.$modalBody; }, getActionButton: function() { return this.$modalBody.find('#redactor-modal-button-action'); }, getCancelButton: function() { return this.$modalBody.find('#redactor-modal-button-cancel'); }, getDeleteButton: function() { return this.$modalBody.find('#redactor-modal-button-delete'); }, load: function(templateName, title, width) { if (typeof this.$modalBox !== 'undefined' && this.$modalBox.hasClass('open')) { return; } this.modal.templateName = templateName; this.modal.width = width; this.modal.build(); this.modal.enableEvents(); this.modal.setTitle(title); this.modal.setDraggable(); this.modal.setContent(); // callbacks if (typeof this.modal.callbacks[templateName] !== 'undefined') { this.modal.callbacks[templateName].call(this); } }, show: function() { if (!this.detect.isDesktop()) { document.activeElement.blur(); } this.selection.save(); this.modal.buildTabber(); if (this.detect.isMobile()) { this.modal.width = '96%'; } // resize setTimeout($.proxy(this.modal.buildWidth, this), 0); $(window).on('resize.redactor-modal', $.proxy(this.modal.buildWidth, this)); this.$modalOverlay.redactorAnimation('fadeIn', { duration: 0.25 }); this.$modalBox.addClass('open').show(); this.$modal.redactorAnimation('fadeIn', { timing: 'cubic-bezier(0.175, 0.885, 0.320, 1.105)' }, $.proxy(function() { this.utils.saveScroll(); this.utils.disableBodyScroll(); // modal shown callback this.core.callback('modalOpened', this.modal.templateName, this.$modal); // fix bootstrap modal focus $(document).off('focusin.modal'); // enter var $elements = this.$modal.find('input[type=text],input[type=url],input[type=email]'); $elements.on('keydown.redactor-modal', $.proxy(this.modal.setEnter, this)); }, this) ); }, buildWidth: function() { var windowHeight = $(window).height(); var windowWidth = $(window).width(); var number = (typeof this.modal.width === 'number'); if (!number && this.modal.width.match(/%$/)) { this.$modal.css({ 'width': this.modal.width, 'margin-bottom': '16px' }); } else if (parseInt(this.modal.width) > windowWidth) { this.$modal.css({ 'width': '96%', 'margin-bottom': '2%' }); } else { if (number) { this.modal.width += 'px'; } this.$modal.css({ 'width': this.modal.width, 'margin-bottom': '16px' }); } // margin top var height = this.$modal.outerHeight(); var top = (windowHeight/2 - height/2) + 'px'; if (this.detect.isMobile()) { top = '2%'; } else if (height > windowHeight) { top = '16px'; } this.$modal.css('margin-top', top); }, buildTabber: function() { this.modal.tabs = this.$modal.find('.redactor-modal-tab'); if (this.modal.tabs.length < 2) { return; } this.modal.$tabsBox = $('<div id="redactor-modal-tabber" />'); $.each(this.modal.tabs, $.proxy(function(i,s) { var a = $('<a href="#" rel="' + i + '" />').text($(s).attr('data-title')); a.on('click', $.proxy(this.modal.showTab, this)); if (i === 0) { a.addClass('active'); } this.modal.$tabsBox.append(a); }, this)); this.$modalBody.prepend(this.modal.$tabsBox); }, showTab: function(e) { e.preventDefault(); var $el = $(e.target); var index = $el.attr('rel'); this.modal.tabs.hide(); this.modal.tabs.eq(index).show(); $('#redactor-modal-tabber').find('a').removeClass('active'); $el.addClass('active'); return false; }, setTitle: function(title) { this.$modalHeader.html(title); }, setContent: function() { this.$modalBody.html(this.modal.getTemplate(this.modal.templateName)); this.modal.getCancelButton().on('mousedown', $.proxy(this.modal.close, this)); }, setDraggable: function() { if (typeof $.fn.draggable === 'undefined') { return; } this.$modal.draggable({ handle: this.$modalHeader }); this.$modalHeader.css('cursor', 'move'); }, setEnter: function(e) { if (e.which !== 13) { return; } e.preventDefault(); this.modal.getActionButton().click(); }, build: function() { this.modal.buildOverlay(); this.$modalBox = $('<div id="redactor-modal-box"/>').hide(); this.$modal = $('<div id="redactor-modal" role="dialog" />'); this.$modalHeader = $('<div id="redactor-modal-header" />'); this.$modalClose = $('<button type="button" id="redactor-modal-close" aria-label="' + this.lang.get('close') + '" />').html('&times;'); this.$modalBody = $('<div id="redactor-modal-body" />'); this.$modal.append(this.$modalHeader); this.$modal.append(this.$modalBody); this.$modal.append(this.$modalClose); this.$modalBox.append(this.$modal); this.$modalBox.appendTo(document.body); }, buildOverlay: function() { this.$modalOverlay = $('<div id="redactor-modal-overlay">').hide(); $('body').prepend(this.$modalOverlay); }, enableEvents: function() { this.$modalClose.on('mousedown.redactor-modal', $.proxy(this.modal.close, this)); $(document).on('keyup.redactor-modal', $.proxy(this.modal.closeHandler, this)); this.core.editor().on('keyup.redactor-modal', $.proxy(this.modal.closeHandler, this)); this.$modalBox.on('click.redactor-modal', $.proxy(this.modal.close, this)); }, disableEvents: function() { this.$modalClose.off('mousedown.redactor-modal'); $(document).off('keyup.redactor-modal'); this.core.editor().off('keyup.redactor-modal'); this.$modalBox.off('click§.redactor-modal'); $(window).off('resize.redactor-modal'); }, closeHandler: function(e) { if (e.which !== this.keyCode.ESC) { return; } this.modal.close(false); }, close: function(e) { if (e) { if ($(e.target).attr('id') !== 'redactor-modal-button-cancel' && e.target !== this.$modalClose[0] && e.target !== this.$modalBox[0]) { return; } e.preventDefault(); } if (!this.$modalBox) { return; } // restore selection this.selection.restore(); this.modal.disableEvents(); this.utils.enableBodyScroll(); this.utils.restoreScroll(); this.$modalOverlay.redactorAnimation('fadeOut', { duration: 0.4 }, $.proxy(function() { this.$modalOverlay.remove(); }, this)); this.$modal.redactorAnimation('fadeOut', { duration: 0.3, timing: 'cubic-bezier(0.175, 0.885, 0.320, 1.175)' }, $.proxy(function() { if (typeof this.$modalBox !== 'undefined') { this.$modalBox.remove(); this.$modalBox = undefined; } $(document.body).css('overflow', this.modal.bodyOveflow); this.core.callback('modalClosed', this.modal.templateName); }, this)); } }; }, // =observe observe: function() { return { load: function() { if (typeof this.opts.destroyed !== 'undefined') { return; } this.observe.links(); this.observe.images(); }, isCurrent: function($el, $current) { if (typeof $current === 'undefined') { $current = $(this.selection.current()); } return $current.is($el) || $current.parents($el).length > 0; }, toolbar: function() { this.observe.buttons(); this.observe.dropdowns(); }, buttons: function(e, btnName) { var current = this.selection.current(); var parent = this.selection.parent(); if (e !== false) { this.button.setInactiveAll(); } else { this.button.setInactiveAll(btnName); } if (e === false && btnName !== 'html') { if ($.inArray(btnName, this.opts.activeButtons) !== -1) { this.button.toggleActive(btnName); } return; } if (!this.utils.isRedactorParent(current)) { return; } // disable line if (this.utils.isCurrentOrParentHeader() || this.utils.isCurrentOrParent(['table', 'pre', 'blockquote', 'li'])) { this.button.disable('horizontalrule'); } else { this.button.enable('horizontalrule'); } $.each(this.opts.activeButtonsStates, $.proxy(function(key, value) { var parentEl = $(parent).closest(key, this.$editor[0]); var currentEl = $(current).closest(key, this.$editor[0]); if (parentEl.length !== 0 && !this.utils.isRedactorParent(parentEl)) { return; } if (!this.utils.isRedactorParent(currentEl)) { return; } if (parentEl.length !== 0 || currentEl.closest(key, this.$editor[0]).length !== 0) { this.button.setActive(value); } }, this)); }, dropdowns: function() { var finded = $('<div />').html(this.selection.html()).find('a').length; var $current = $(this.selection.current()); var isRedactor = this.utils.isRedactorParent($current); $.each(this.opts.observe.dropdowns, $.proxy(function(key, value) { var observe = value.observe, element = observe.element, $item = value.item, inValues = typeof observe['in'] !== 'undefined' ? observe['in'] : false, outValues = typeof observe.out !== 'undefined' ? observe.out : false; if (($current.closest(element).length > 0 && isRedactor) || (element === 'a' && finded !== 0)) { this.observe.setDropdownProperties($item, inValues, outValues); } else { this.observe.setDropdownProperties($item, outValues, inValues); } }, this)); }, setDropdownProperties: function($item, addProperties, deleteProperties) { if (deleteProperties && typeof deleteProperties.attr !== 'undefined') { this.observe.setDropdownAttr($item, deleteProperties.attr, true); } if (typeof addProperties.attr !== 'undefined') { this.observe.setDropdownAttr($item, addProperties.attr); } if (typeof addProperties.title !== 'undefined') { $item.find('span').text(addProperties.title); } }, setDropdownAttr: function($item, properties, isDelete) { $.each(properties, function(key, value) { if (key === 'class') { if (!isDelete) { $item.addClass(value); } else { $item.removeClass(value); } } else { if (!isDelete) { $item.attr(key, value); } else { $item.removeAttr(key); } } }); }, addDropdown: function($item, btnName, btnObject) { if (typeof btnObject.observe === "undefined") { return; } btnObject.item = $item; this.opts.observe.dropdowns.push(btnObject); }, images: function() { if (this.opts.imageEditable) { this.core.editor().addClass('redactor-layer-img-edit'); this.core.editor().find('img').each($.proxy(function(i, img) { var $img = $(img); // IE fix (when we clicked on an image and then press backspace IE does goes to image's url) $img.closest('a', this.$editor[0]).on('click', function(e) { e.preventDefault(); }); this.image.setEditable($img); }, this)); } }, links: function() { if (this.opts.linkTooltip) { this.core.editor().find('a').each($.proxy(function(i, s) { var $link = $(s); if ($link.data('cached') !== true) { $link.data('cached', true); $link.on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.showTooltip, this)); } }, this)); } }, getTooltipPosition: function($link) { return $link.offset(); }, showTooltip: function(e) { var $el = $(e.target); if ($el[0].tagName === 'IMG') { return; } if ($el[0].tagName !== 'A') { $el = $el.closest('a', this.$editor[0]); } if ($el[0].tagName !== 'A') { return; } var $link = $el; var pos = this.observe.getTooltipPosition($link); var tooltip = $('<span class="redactor-link-tooltip"></span>'); var href = $link.attr('href'); if (href === undefined) { href = ''; } if (href.length > 24) { href = href.substring(0, 24) + '...'; } var aLink = $('<a href="' + $link.attr('href') + '" target="_blank" />').html(href).addClass('redactor-link-tooltip-action'); var aEdit = $('<a href="#" />').html(this.lang.get('edit')).on('click', $.proxy(this.link.show, this)).addClass('redactor-link-tooltip-action'); var aUnlink = $('<a href="#" />').html(this.lang.get('unlink')).on('click', $.proxy(this.link.unlink, this)).addClass('redactor-link-tooltip-action'); tooltip.append(aLink).append(' | ').append(aEdit).append(' | ').append(aUnlink); var lineHeight = parseInt($link.css('line-height'), 10); var lineClicked = Math.ceil((e.pageY - pos.top)/lineHeight); var top = pos.top + lineClicked * lineHeight; tooltip.css({ top: top + 'px', left: pos.left + 'px' }); $('.redactor-link-tooltip').remove(); $('body').append(tooltip); this.core.editor().on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.closeTooltip, this)); $(document).on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.closeTooltip, this)); }, closeAllTooltip: function() { $('.redactor-link-tooltip').remove(); }, closeTooltip: function(e) { e = e.originalEvent || e; var target = e.target; var $parent = $(target).closest('a', this.$editor[0]); if ($parent.length !== 0 && $parent[0].tagName === 'A' && target.tagName !== 'A') { return; } else if ((target.tagName === 'A' && this.utils.isRedactorParent(target)) || $(target).hasClass('redactor-link-tooltip-action')) { return; } this.observe.closeAllTooltip(); this.core.editor().off('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.closeTooltip, this)); $(document).off('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.closeTooltip, this)); } }; }, // =offset offset: function() { return { get: function(node) { var cloned = this.offset.clone(node); if (cloned === false) { return 0; } var div = document.createElement('div'); div.appendChild(cloned.cloneContents()); div.innerHTML = div.innerHTML.replace(/<img(.*?[^>])>$/gi, 'i'); var text = $.trim($(div).text()).replace(/[\t\n\r\n]/g, '').replace(/\u200B/g, ''); return text.length; }, clone: function(node) { var sel = this.selection.get(); var range = this.selection.range(sel); if (range === null && typeof node === 'undefined') { return false; } node = (typeof node === 'undefined') ? this.$editor : node; if (node === false) { return false; } node = node[0] || node; var cloned = range.cloneRange(); cloned.selectNodeContents(node); cloned.setEnd(range.endContainer, range.endOffset); return cloned; }, set: function(start, end) { end = (typeof end === 'undefined') ? start : end; if (!this.focus.is()) { this.focus.start(); } var sel = this.selection.get(); var range = this.selection.range(sel); var node, offset = 0; var walker = document.createTreeWalker(this.$editor[0], NodeFilter.SHOW_TEXT, null, null); while ((node = walker.nextNode()) !== null) { offset += node.nodeValue.length; if (offset > start) { range.setStart(node, node.nodeValue.length + start - offset); start = Infinity; } if (offset >= end) { range.setEnd(node, node.nodeValue.length + end - offset); break; } } range.collapse(false); this.selection.update(sel, range); } }; }, // =paragraphize paragraphize: function() { return { load: function(html) { if (this.opts.paragraphize === false || this.opts.type === 'inline' || this.opts.type === 'pre') { return html; } if (html === '' || html === '<p></p>') { return this.opts.emptyHtml; } html = html + "\n"; this.paragraphize.safes = []; this.paragraphize.z = 0; // before html = html.replace(/(<br\s?\/?>){1,}\n?<\/blockquote>/gi, '</blockquote>'); html = html.replace(/<\/pre>/gi, "</pre>\n\n"); html = html.replace(/<p>\s<br><\/p>/gi, '<p></p>'); html = this.paragraphize.getSafes(html); html = html.replace('<br>', "\n"); html = this.paragraphize.convert(html); html = this.paragraphize.clear(html); html = this.paragraphize.restoreSafes(html); // after html = html.replace(new RegExp('<br\\s?/?>\n?<(' + this.opts.paragraphizeBlocks.join('|') + ')(.*?[^>])>', 'gi'), '<p><br /></p>\n<$1$2>'); return $.trim(html); }, getSafes: function(html) { var $div = $('<div />').append(html); // remove paragraphs in blockquotes $div.find('blockquote p').replaceWith(function() { return $(this).append('<br />').contents(); }); $div.find(this.opts.paragraphizeBlocks.join(', ')).each($.proxy(function(i,s) { this.paragraphize.z++; this.paragraphize.safes[this.paragraphize.z] = s.outerHTML; return $(s).replaceWith("\n#####replace" + this.paragraphize.z + "#####\n\n"); }, this)); // deal with redactor selection markers $div.find('span.redactor-selection-marker').each($.proxy(function(i,s) { this.paragraphize.z++; this.paragraphize.safes[this.paragraphize.z] = s.outerHTML; return $(s).replaceWith("\n#####replace" + this.paragraphize.z + "#####\n\n"); }, this)); return $div.html(); }, restoreSafes: function(html) { $.each(this.paragraphize.safes, function(i,s) { s = (typeof s !== 'undefined') ? s.replace(/\$/g, '&#36;') : s; html = html.replace('#####replace' + i + '#####', s); }); return html; }, convert: function(html) { html = html.replace(/\r\n/g, "xparagraphmarkerz"); html = html.replace(/\n/g, "xparagraphmarkerz"); html = html.replace(/\r/g, "xparagraphmarkerz"); var re1 = /\s+/g; html = html.replace(re1, " "); html = $.trim(html); var re2 = /xparagraphmarkerzxparagraphmarkerz/gi; html = html.replace(re2, "</p><p>"); var re3 = /xparagraphmarkerz/gi; html = html.replace(re3, "<br>"); html = '<p>' + html + '</p>'; html = html.replace("<p></p>", ""); html = html.replace("\r\n\r\n", ""); html = html.replace(/<\/p><p>/g, "</p>\r\n\r\n<p>"); html = html.replace(new RegExp("<br\\s?/?></p>", "g"), "</p>"); html = html.replace(new RegExp("<p><br\\s?/?>", "g"), "<p>"); html = html.replace(new RegExp("<p><br\\s?/?>", "g"), "<p>"); html = html.replace(new RegExp("<br\\s?/?></p>", "g"), "</p>"); html = html.replace(/<p>&nbsp;<\/p>/gi, ""); html = html.replace(/<p>\s?<br>&nbsp;<\/p>/gi, ''); html = html.replace(/<p>\s?<br>/gi, '<p>'); return html; }, clear: function(html) { html = html.replace(/<p>(.*?)#####replace(.*?)#####\s?<\/p>/gi, '<p>$1</p>#####replace$2#####'); html = html.replace(/(<br\s?\/?>){2,}<\/p>/gi, '</p>'); html = html.replace(new RegExp('</blockquote></p>', 'gi'), '</blockquote>'); html = html.replace(new RegExp('<p></blockquote>', 'gi'), '</blockquote>'); html = html.replace(new RegExp('<p><blockquote>', 'gi'), '<blockquote>'); html = html.replace(new RegExp('<blockquote></p>', 'gi'), '<blockquote>'); html = html.replace(new RegExp('<p><p ', 'gi'), '<p '); html = html.replace(new RegExp('<p><p>', 'gi'), '<p>'); html = html.replace(new RegExp('</p></p>', 'gi'), '</p>'); html = html.replace(new RegExp('<p>\\s?</p>', 'gi'), ''); html = html.replace(new RegExp("\n</p>", 'gi'), '</p>'); html = html.replace(new RegExp('<p>\t?\t?\n?<p>', 'gi'), '<p>'); html = html.replace(new RegExp('<p>\t*</p>', 'gi'), ''); return html; } }; }, // =paste paste: function() { return { init: function(e) { this.rtePaste = true; var pre = (this.opts.type === 'pre' || this.utils.isCurrentOrParent('pre')) ? true : false; // clipboard event if (this.detect.isDesktop()) { if (!this.paste.pre && this.opts.clipboardImageUpload && this.opts.imageUpload && this.paste.detectClipboardUpload(e)) { if (this.detect.isIe()) { setTimeout($.proxy(this.paste.clipboardUpload, this), 100); } return; } } this.utils.saveScroll(); this.selection.save(); this.paste.createPasteBox(pre); $(window).on('scroll.redactor-freeze', $.proxy(function() { $(window).scrollTop(this.saveBodyScroll); }, this)); setTimeout($.proxy(function() { var html = this.paste.getPasteBoxCode(pre); // buffer this.buffer.set(); this.selection.restore(); this.utils.restoreScroll(); // paste info var data = this.clean.getCurrentType(html); // clean html = this.clean.onPaste(html, data); // callback var returned = this.core.callback('paste', html); html = (typeof returned === 'undefined') ? html : returned; this.paste.insert(html, data); this.rtePaste = false; // clean pre breaklines if (pre) { this.clean.cleanPre(); } $(window).off('scroll.redactor-freeze'); }, this), 1); }, getPasteBoxCode: function(pre) { var html = (pre) ? this.$pasteBox.val() : this.$pasteBox.html(); this.$pasteBox.remove(); return html; }, createPasteBox: function(pre) { var css = { position: 'fixed', width: '1px', top: 0, left: '-9999px' }; this.$pasteBox = (pre) ? $('<textarea>').css(css) : $('<div>').attr('contenteditable', 'true').css(css); this.paste.appendPasteBox(); this.$pasteBox.focus(); }, appendPasteBox: function() { if (this.detect.isIe()) { this.core.box().append(this.$pasteBox); } else { // bootstrap modal var $visibleModals = $('.modal-body:visible'); if ($visibleModals.length > 0) { $visibleModals.append(this.$pasteBox); } else { $('body').prepend(this.$pasteBox); } } }, detectClipboardUpload: function(e) { e = e.originalEvent || e; var clipboard = e.clipboardData; if (this.detect.isIe()) { return true; } if (this.detect.isFirefox()) { return false; } // prevent safari fake url var types = clipboard.types; if (types.indexOf('public.tiff') !== -1) { e.preventDefault(); return false; } if (!clipboard.items || !clipboard.items.length) { return; } var file = clipboard.items[0].getAsFile(); if (file === null) { return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = $.proxy(this.paste.insertFromClipboard, this); return true; }, clipboardUpload: function() { var imgs = this.$editor.find('img'); $.each(imgs, $.proxy(function(i,s) { if (s.src.search(/^data\:image/i) === -1) { return; } var formData = !!window.FormData ? new FormData() : null; if (!window.FormData) { return; } this.upload.direct = true; this.upload.type = 'image'; this.upload.url = this.opts.imageUpload; this.upload.callback = $.proxy(function(data) { if (this.detect.isIe()) { $(s).wrap($('<figure />')); } else { var $parent = $(s).parent(); this.utils.replaceToTag($parent, 'figure'); } s.src = data.url; this.core.callback('imageUpload', $(s), data); }, this); var blob = this.utils.dataURItoBlob(s.src); formData.append('clipboard', 1); formData.append(this.opts.imageUploadParam, blob); this.progress.show(); this.upload.send(formData, false); this.code.sync(); this.rtePaste = false; }, this)); }, insertFromClipboard: function(e) { var formData = !!window.FormData ? new FormData() : null; if (!window.FormData) { return; } this.upload.direct = true; this.upload.type = 'image'; this.upload.url = this.opts.imageUpload; this.upload.callback = this.image.insert; var blob = this.utils.dataURItoBlob(e.target.result); formData.append('clipboard', 1); formData.append(this.opts.imageUploadParam, blob); this.progress.show(); this.upload.send(formData, e); this.rtePaste = false; }, insert: function(html, data) { if (data.pre) { this.insert.raw(html); } else if (data.text) { this.insert.text(html); } else { this.insert.html(html, data); } // Firefox Clipboard Observe if (this.detect.isFirefox() && this.opts.clipboardImageUpload) { setTimeout($.proxy(this.paste.clipboardUpload, this), 100); } } }; }, // =placeholder placeholder: function() { return { // public enable: function() { setTimeout($.proxy(function() { return (this.placeholder.isEditorEmpty()) ? this.placeholder.show() : this.placeholder.hide(); }, this), 5); }, show: function() { this.core.editor().addClass('redactor-placeholder'); }, update: function(text) { this.opts.placeholder = text; this.core.editor().attr('placeholder', text); }, hide: function() { this.core.editor().removeClass('redactor-placeholder'); }, is: function() { return this.core.editor().hasClass('redactor-placeholder'); }, // private init: function() { if (!this.placeholder.enabled()) { return; } if (!this.utils.isEditorRelative()) { this.utils.setEditorRelative(); } this.placeholder.build(); this.placeholder.buildPosition(); this.placeholder.enable(); this.placeholder.enableEvents(); }, enabled: function() { return (this.opts.placeholder) ? this.core.element().attr('placeholder', this.opts.placeholder) : this.placeholder.isAttr(); }, enableEvents: function() { this.core.editor().on('keydown.redactor-placeholder.' + this.uuid, $.proxy(this.placeholder.enable, this)); }, disableEvents: function() { this.core.editor().off('.redactor-placeholder.' + this.uuid); }, build: function() { this.core.editor().attr('placeholder', this.core.element().attr('placeholder')); }, buildPosition: function() { var $style = $('<style />'); $style.addClass('redactor-placeholder-style-tag'); $style.html('#' + this.core.id() + '.redactor-placeholder::after ' + this.placeholder.getPosition()); $('head').append($style); }, getPosition: function() { return '{ top: ' + this.core.editor().css('padding-top') + '; left: ' + this.core.editor().css('padding-left') + '; }'; }, isEditorEmpty: function() { var html = $.trim(this.core.editor().html()).replace(/[\t\n]/g, ''); var states = ['', '<p>​</p>', '<p>​<br></p>', this.opts.emptyHtmlRendered]; return ($.inArray(html, states) !== -1); }, isAttr: function() { return (typeof this.core.element().attr('placeholder') !== 'undefined' && this.core.element().attr('placeholder') !== ''); }, destroy: function() { this.core.editor().removeAttr('placeholder'); this.placeholder.hide(); this.placeholder.disableEvents(); $('.redactor-placeholder-style-tag').remove(); } }; }, // =progress progress: function() { return { $box: null, $bar: null, target: document.body, // or id selector // public show: function() { if (!this.progress.is()) { this.progress.build(); this.progress.$box.redactorAnimation('fadeIn'); } else { this.progress.$box.show(); } }, hide: function() { if (this.progress.is()) { this.progress.$box.redactorAnimation('fadeOut', { duration: 0.35 }, $.proxy(this.progress.destroy, this)); } }, update: function(value) { this.progress.show(); this.progress.$bar.css('width', value + '%'); }, is: function() { return (this.progress.$box === null) ? false : true; }, // private build: function() { this.progress.$bar = $('<span />'); this.progress.$box = $('<div id="redactor-progress" />'); this.progress.$box.append(this.progress.$bar); $(this.progress.target).append(this.progress.$box); }, destroy: function() { if (this.progress.is()) { this.progress.$box.remove(); } this.progress.$box = null; this.progress.$bar = null; } }; }, // =selection selection: function() { return { get: function() { if (window.getSelection) { return window.getSelection(); } else if (document.selection && document.selection.type !== "Control") { return document.selection; } return null; }, range: function(sel) { if (typeof sel === 'undefined') { sel = this.selection.get(); } if (sel.getRangeAt && sel.rangeCount) { return sel.getRangeAt(0); } return null; }, is: function() { return (this.selection.isCollapsed()) ? false : true; }, isRedactor: function() { var range = this.selection.range(); if (range !== null) { var el = range.startContainer.parentNode; if ($(el).hasClass('redactor-in') || $(el).parents('.redactor-in').length !== 0) { return true; } } return false; }, isCollapsed: function() { var sel = this.selection.get(); return (sel === null) ? false : sel.isCollapsed; }, update: function(sel, range) { if (range === null) { return; } sel.removeAllRanges(); sel.addRange(range); }, current: function() { var sel = this.selection.get(); return (sel === null) ? false : sel.anchorNode; }, parent: function() { var current = this.selection.current(); return (current === null) ? false : current.parentNode; }, block: function(node) { node = node || this.selection.current(); while (node) { if (this.utils.isBlockTag(node.tagName)) { return ($(node).hasClass('redactor-in')) ? false : node; } node = node.parentNode; } return false; }, inline: function(node) { node = node || this.selection.current(); while (node) { if (this.utils.isInlineTag(node.tagName)) { return ($(node).hasClass('redactor-in')) ? false : node; } node = node.parentNode; } return false; }, element: function(node) { if (!node) { node = this.selection.current(); } while (node) { if (node.nodeType === 1) { if ($(node).hasClass('redactor-in')) { return false; } return node; } node = node.parentNode; } return false; }, prev: function() { var current = this.selection.current(); return (current === null) ? false : this.selection.current().previousSibling; }, next: function() { var current = this.selection.current(); return (current === null) ? false : this.selection.current().nextSibling; }, blocks: function(tag) { var blocks = []; var nodes = this.selection.nodes(tag); $.each(nodes, $.proxy(function(i,node) { if (this.utils.isBlock(node)) { blocks.push(node); } }, this)); var block = this.selection.block(); if (blocks.length === 0 && block === false) { return []; } else if (blocks.length === 0 && block !== false) { return [block]; } else { return blocks; } }, inlines: function(tag) { var inlines = []; var nodes = this.selection.nodes(tag); $.each(nodes, $.proxy(function(i,node) { if (this.utils.isInline(node)) { inlines.push(node); } }, this)); var inline = this.selection.inline(); if (inlines.length === 0 && inline === false) { return []; } else if (inlines.length === 0 && inline !== false) { return [inline]; } else { return inlines; } }, nodes: function(tag) { var filter = (typeof tag === 'undefined') ? [] : (($.isArray(tag)) ? tag : [tag]); var sel = this.selection.get(); var range = this.selection.range(sel); if (this.utils.isCollapsed()) { return [this.selection.current()]; } else { var node = range.startContainer; var endNode = range.endContainer; // single node if (node === endNode) { return [this.selection.parent()]; } // iterate var nodes = []; while (node && node !== endNode) { nodes.push(node = this.selection.nextNode(node)); } // partially selected nodes node = range.startContainer; while (node && node !== range.commonAncestorContainer) { nodes.unshift(node); node = node.parentNode; } // remove service nodes var resultNodes = []; $.each(nodes, function(i,s) { if (s) { var tagName = (s.nodeType !== 1) ? false : s.tagName.toLowerCase(); if ($(s).hasClass('redactor-script-tag, redactor-selection-marker')) { return; } else if (tagName && filter.length !== 0 && $.inArray(tagName, filter) === -1) { return; } else { resultNodes.push(s); } } }); return (resultNodes.length === 0) ? [] : resultNodes; } }, nextNode: function(node) { if (node.hasChildNodes()) { return node.firstChild; } else { while (node && !node.nextSibling) { node = node.parentNode; } if (!node) { return null; } return node.nextSibling; } }, save: function() { this.marker.insert(); this.savedSel = this.core.editor().html(); }, restore: function(removeMarkers) { var node1 = this.marker.find(1); var node2 = this.marker.find(2); if (this.detect.isFirefox()) { this.core.editor().focus(); } if (node1.length !== 0 && node2.length !== 0) { this.caret.set(node1, node2); } else if (node1.length !== 0) { this.caret.start(node1); } else { this.core.editor().focus(); } if (removeMarkers !== false) { this.marker.remove(); this.savedSel = false; } }, saveInstant: function() { var el = this.core.editor()[0]; var doc = el.ownerDocument, win = doc.defaultView; var sel = win.getSelection(); if (!sel.getRangeAt || !sel.rangeCount) { return; } var range = sel.getRangeAt(0); var selectionRange = range.cloneRange(); selectionRange.selectNodeContents(el); selectionRange.setEnd(range.startContainer, range.startOffset); var start = selectionRange.toString().length; this.saved = { start: start, end: start + range.toString().length, node: range.startContainer }; return this.saved; }, restoreInstant: function(saved) { if (typeof saved === 'undefined' && !this.saved) { return; } this.saved = (typeof saved !== 'undefined') ? saved : this.saved; var $node = this.core.editor().find(this.saved.node); if ($node.length !== 0 && $node.text().trim().replace(/\u200B/g, '').length === 0) { try { var range = document.createRange(); range.setStart($node[0], 0); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } catch(e) {} return; } var el = this.core.editor()[0]; var doc = el.ownerDocument, win = doc.defaultView; var charIndex = 0, range = doc.createRange(); range.setStart(el, 0); range.collapse(true); var nodeStack = [el], node, foundStart = false, stop = false; while (!stop && (node = nodeStack.pop())) { if (node.nodeType == 3) { var nextCharIndex = charIndex + node.length; if (!foundStart && this.saved.start >= charIndex && this.saved.start <= nextCharIndex) { range.setStart(node, this.saved.start - charIndex); foundStart = true; } if (foundStart && this.saved.end >= charIndex && this.saved.end <= nextCharIndex) { range.setEnd(node, this.saved.end - charIndex); stop = true; } charIndex = nextCharIndex; } else { var i = node.childNodes.length; while (i--) { nodeStack.push(node.childNodes[i]); } } } var sel = win.getSelection(); sel.removeAllRanges(); sel.addRange(range); }, node: function(node) { $(node).prepend(this.marker.get(1)); $(node).append(this.marker.get(2)); this.selection.restore(); }, all: function() { this.core.editor().focus(); var sel = this.selection.get(); var range = this.selection.range(sel); range.selectNodeContents(this.core.editor()[0]); this.selection.update(sel, range); }, remove: function() { this.selection.get().removeAllRanges(); }, replace: function(html) { this.insert.html(html); }, text: function() { return this.selection.get().toString(); }, html: function() { var html = ''; var sel = this.selection.get(); if (sel.rangeCount) { var container = document.createElement('div'); var len = sel.rangeCount; for (var i = 0; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = this.clean.onGet(container.innerHTML); } return html; }, extractEndOfNode: function(node) { var sel = this.selection.get(); var range = this.selection.range(sel); var clonedRange = range.cloneRange(); clonedRange.selectNodeContents(node); clonedRange.setStart(range.endContainer, range.endOffset); return clonedRange.extractContents(); }, // #backward removeMarkers: function() { this.marker.remove(); }, marker: function(num) { return this.marker.get(num); }, markerHtml: function(num) { return this.marker.html(num); } }; }, // =shortcuts shortcuts: function() { return { // based on https://github.com/jeresig/jquery.hotkeys hotkeysSpecialKeys: { 8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'" }, hotkeysShiftNums: { "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", ".": ">", "/": "?", "\\": "|" }, init: function(e, key) { // disable browser's hot keys for bold and italic if shortcuts off if (this.opts.shortcuts === false) { if ((e.ctrlKey || e.metaKey) && (key === 66 || key === 73)) { e.preventDefault(); } return false; } else { // build $.each(this.opts.shortcuts, $.proxy(function(str, command) { this.shortcuts.build(e, str, command); }, this)); } }, build: function(e, str, command) { var handler = $.proxy(function() { this.shortcuts.buildHandler(command); }, this); var keys = str.split(','); var len = keys.length; for (var i = 0; i < len; i++) { if (typeof keys[i] === 'string') { this.shortcuts.handler(e, $.trim(keys[i]), handler); } } }, buildHandler: function(command) { var func; if (command.func.search(/\./) !== '-1') { func = command.func.split('.'); if (typeof this[func[0]] !== 'undefined') { this[func[0]][func[1]].apply(this, command.params); } } else { this[command.func].apply(this, command.params); } }, handler: function(e, keys, origHandler) { keys = keys.toLowerCase().split(" "); var special = this.shortcuts.hotkeysSpecialKeys[e.keyCode]; var character = String.fromCharCode(e.which).toLowerCase(); var modif = "", possible = {}; $.each([ "alt", "ctrl", "meta", "shift"], function(index, specialKey) { if (e[specialKey + 'Key'] && special !== specialKey) { modif += specialKey + '+'; } }); if (special) { possible[modif + special] = true; } if (character) { possible[modif + character] = true; possible[modif + this.shortcuts.hotkeysShiftNums[character]] = true; // "$" can be triggered as "Shift+4" or "Shift+$" or just "$" if (modif === "shift+") { possible[this.shortcuts.hotkeysShiftNums[character]] = true; } } var len = keys.length; for (var i = 0; i < len; i++) { if (possible[keys[i]]) { e.preventDefault(); return origHandler.apply(this, arguments); } } } }; }, // =storage storage: function() { return { data: [], add: function(data) { // type, node, url, id data.status = true; data.url = decodeURI(this.link.removeSelfHostFromUrl(data.url)); this.storage.data[data.url] = data; }, status: function(url, status) { this.storage.data[decodeURI(url)].status = status; }, observe: function() { var _this = this; var $images = this.core.editor().find('[data-image]'); $images.each(function(i, s) { _this.storage.add({ type: 'image', node: s, url: s.src, id: $(s).attr('data-image') }); }); var $files = this.core.editor().find('[data-file]'); $files.each(function(i, s) { _this.storage.add({ type: 'file', node: s, url: s.href, id: $(s).attr('data-file') }); }); var $s3 = this.core.editor().find('[data-s3]'); $s3.each(function(i, s) { var url = (s.tagName === 'IMG') ? s.src : s.href; _this.storage.add({ type: 's3', node: s, url: url, id: $(s).attr('data-s3') }); }); }, changes: function() { for (var key in this.storage.data) { var data = this.storage.data[key]; var attr = (data.node.tagName === 'IMG') ? 'src' : 'href'; var $el = this.core.editor().find('[data-' + data.type + '][' + attr + '="' + data.url + '"]'); if ($el.length === 0) { this.storage.status(data.url, false); } else { this.storage.status(data.url, true); } } return this.storage.data; } }; }, // =toolbar toolbar: function() { return { build: function() { this.button.hideButtons(); this.button.hideButtonsOnMobile(); this.$toolbar = this.toolbar.createContainer(); this.toolbar.append(); this.button.$toolbar = this.$toolbar; this.button.setFormatting(); this.button.load(this.$toolbar); this.toolbar.setFixed(); }, createContainer: function() { return $('<ul>').addClass('redactor-toolbar').attr({ 'id': 'redactor-toolbar-' + this.uuid, 'role': 'toolbar' }); }, append: function() { if (this.opts.toolbarExternal) { this.$toolbar.addClass('redactor-toolbar-external'); $(this.opts.toolbarExternal).html(this.$toolbar); } else { if (this.opts.type === 'textarea') { this.$box.prepend(this.$toolbar); } else { this.$element.before(this.$toolbar); } } }, setFixed: function() { if (!this.opts.toolbarFixed || this.opts.toolbarExternal) { return; } if (this.opts.toolbarFixedTarget !== document) { var $el = $(this.opts.toolbarFixedTarget); this.toolbarOffsetTop = ($el.length === 0) ? 0 : this.core.box().offset().top - $el.offset().top; } // bootstrap modal fix var late = (this.core.box().closest('.modal-body').length !== 0) ? 1000 : 0; setTimeout($.proxy(function() { var self = this; this.toolbar.observeScroll(false); if (this.detect.isDesktop()) { $(this.opts.toolbarFixedTarget).on('scroll.redactor.' + this.uuid, function() { if (self.core.editor().height() < 100 || self.placeholder.isEditorEmpty()) { return; } self.toolbar.observeScroll(); }); } else { $(this.opts.toolbarFixedTarget).on('scroll.redactor.' + this.uuid, function() { if (self.core.editor().height() < 100 || self.placeholder.isEditorEmpty()) { return; } self.core.toolbar().hide(); clearTimeout($.data(this, "scrollCheck")); $.data(this, "scrollCheck", setTimeout(function() { self.core.toolbar().show(); self.toolbar.observeScroll(); }, 250) ); }); } }, this), late); }, getBoxTop: function() { return (this.opts.toolbarFixedTarget === document) ? this.core.box().offset().top : this.toolbar.toolbarOffsetTop; }, observeScroll: function(start) { // tolerance 0 if redactor in the hidden layer var tolerance = 0; if (start !== false) { tolerance = (this.opts.toolbarFixedTarget === document) ? 20 : 0; } var scrollTop = $(this.opts.toolbarFixedTarget).scrollTop(); var boxTop = this.toolbar.getBoxTop(); if (scrollTop === boxTop) { return; } if ((scrollTop + this.opts.toolbarFixedTopOffset + tolerance) > boxTop) { this.toolbar.observeScrollEnable(scrollTop, boxTop); } else { this.toolbar.observeScrollDisable(); } }, observeScrollResize: function() { this.$toolbar.css({ width: this.core.box().innerWidth(), left: this.core.box().offset().left }); }, observeScrollEnable: function(scrollTop, boxTop) { if (typeof this.fullscreen !== 'undefined' && this.fullscreen.isOpened === false) { this.toolbar.observeScrollDisable(); return; } var end = boxTop + this.core.box().outerHeight() - 32; var width = this.core.box().innerWidth(); var position = (this.detect.isDesktop()) ? 'fixed' : 'absolute'; var top = (this.detect.isDesktop()) ? this.opts.toolbarFixedTopOffset : ($(this.opts.toolbarFixedTarget).scrollTop() - boxTop + this.opts.toolbarFixedTopOffset); var left = (this.detect.isDesktop()) ? this.core.box().offset().left : 0; if (this.opts.toolbarFixedTarget !== document) { position = 'absolute'; top = this.opts.toolbarFixedTopOffset + $(this.opts.toolbarFixedTarget).scrollTop() - boxTop; left = 0; } this.$toolbar.addClass('toolbar-fixed-box'); this.$toolbar.css({ position: position, width: width, top: top, left: left }); if (scrollTop > end) { $('.redactor-dropdown-' + this.uuid + ':visible').hide(); } this.toolbar.setDropdownsFixed(); this.$toolbar.css('visibility', (scrollTop < end) ? 'visible' : 'hidden'); $(window).on('resize.redactor-toolbar.' + this.uuid, $.proxy(this.toolbar.observeScrollResize, this)); }, observeScrollDisable: function() { this.$toolbar.css({ position: 'relative', width: 'auto', top: 0, left: 0, visibility: 'visible' }); this.toolbar.unsetDropdownsFixed(); this.$toolbar.removeClass('toolbar-fixed-box'); $(window).off('resize.redactor-toolbar.' + this.uuid); }, setDropdownsFixed: function() { var position = (this.opts.toolbarFixedTarget === document && this.detect.isDesktop()) ? 'fixed' : 'absolute'; this.toolbar.setDropdownPosition(position); }, unsetDropdownsFixed: function() { this.toolbar.setDropdownPosition('absolute'); }, setDropdownPosition: function(position) { var self = this; $('.redactor-dropdown-' + this.uuid).each(function() { var $el = $(this); var $button = self.button.get($el.attr('rel')); var top = (position === 'fixed') ? self.opts.toolbarFixedTopOffset : $button.offset().top; $el.css({ position: position, top: ($button.innerHeight() + top) + 'px' }); }); } }; }, // =upload upload: function() { return { init: function(id, url, callback) { this.upload.direct = false; this.upload.callback = callback; this.upload.url = url; this.upload.$el = $(id); this.upload.$droparea = $('<div id="redactor-droparea" />'); this.upload.$placeholdler = $('<div id="redactor-droparea-placeholder" />').text(this.lang.get('upload-label')); this.upload.$input = $('<input type="file" name="file" />'); this.upload.$placeholdler.append(this.upload.$input); this.upload.$droparea.append(this.upload.$placeholdler); this.upload.$el.append(this.upload.$droparea); this.upload.$droparea.off('redactor.upload'); this.upload.$input.off('redactor.upload'); this.upload.$droparea.on('dragover.redactor.upload', $.proxy(this.upload.onDrag, this)); this.upload.$droparea.on('dragleave.redactor.upload', $.proxy(this.upload.onDragLeave, this)); // change this.upload.$input.on('change.redactor.upload', $.proxy(function(e) { e = e.originalEvent || e; this.upload.traverseFile(this.upload.$input[0].files[0], e); }, this)); // drop this.upload.$droparea.on('drop.redactor.upload', $.proxy(function(e) { e.preventDefault(); this.upload.$droparea.removeClass('drag-hover').addClass('drag-drop'); this.upload.onDrop(e); }, this)); }, directUpload: function(file, e) { this.upload.direct = true; this.upload.traverseFile(file, e); }, onDrop: function(e) { e = e.originalEvent || e; var files = e.dataTransfer.files; if (this.opts.multipleImageUpload) { var len = files.length; for (var i = 0; i < len; i++) { this.upload.traverseFile(files[i], e); } } else { this.upload.traverseFile(files[0], e); } }, traverseFile: function(file, e) { if (this.opts.s3) { this.upload.setConfig(file); this.uploads3.send(file, e); return; } var formData = !!window.FormData ? new FormData() : null; if (window.FormData) { this.upload.setConfig(file); var name = (this.upload.type === 'image') ? this.opts.imageUploadParam : this.opts.fileUploadParam; formData.append(name, file); } this.progress.show(); this.core.callback('uploadStart', e, formData); this.upload.send(formData, e); }, setConfig: function(file) { this.upload.getType(file); if (this.upload.direct) { this.upload.url = (this.upload.type === 'image') ? this.opts.imageUpload : this.opts.fileUpload; this.upload.callback = (this.upload.type === 'image') ? this.image.insert : this.file.insert; } }, getType: function(file) { this.upload.type = (this.opts.imageTypes.indexOf(file.type) === -1) ? 'file' : 'image'; if (this.opts.imageUpload === null && this.opts.fileUpload !== null) { this.upload.type = 'file'; } }, getHiddenFields: function(obj, fd) { if (obj === false || typeof obj !== 'object') { return fd; } $.each(obj, $.proxy(function(k, v) { if (v !== null && v.toString().indexOf('#') === 0) { v = $(v).val(); } fd.append(k, v); }, this)); return fd; }, send: function(formData, e) { // append hidden fields if (this.upload.type === 'image') { formData = this.utils.appendFields(this.opts.imageUploadFields, formData); formData = this.utils.appendForms(this.opts.imageUploadForms, formData); formData = this.upload.getHiddenFields(this.upload.imageFields, formData); } else { formData = this.utils.appendFields(this.opts.fileUploadFields, formData); formData = this.utils.appendForms(this.opts.fileUploadForms, formData); formData = this.upload.getHiddenFields(this.upload.fileFields, formData); } var xhr = new XMLHttpRequest(); xhr.open('POST', this.upload.url); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // complete xhr.onreadystatechange = $.proxy(function() { if (xhr.readyState === 4) { var data = xhr.responseText; data = data.replace(/^\[/, ''); data = data.replace(/\]$/, ''); var json; try { json = (typeof data === 'string' ? JSON.parse(data) : data); } catch(err) { json = { error: true }; } this.progress.hide(); if (!this.upload.direct) { this.upload.$droparea.removeClass('drag-drop'); } this.upload.callback(json, this.upload.direct, e); } }, this); xhr.send(formData); }, onDrag: function(e) { e.preventDefault(); this.upload.$droparea.addClass('drag-hover'); }, onDragLeave: function(e) { e.preventDefault(); this.upload.$droparea.removeClass('drag-hover'); }, clearImageFields: function() { this.upload.imageFields = {}; }, addImageFields: function(name, value) { this.upload.imageFields[name] = value; }, removeImageFields: function(name) { delete this.upload.imageFields[name]; }, clearFileFields: function() { this.upload.fileFields = {}; }, addFileFields: function(name, value) { this.upload.fileFields[name] = value; }, removeFileFields: function(name) { delete this.upload.fileFields[name]; } }; }, // =s3 uploads3: function() { return { send: function(file, e) { this.uploads3.executeOnSignedUrl(file, $.proxy(function(signedURL) { this.uploads3.sendToS3(file, signedURL, e); }, this)); }, executeOnSignedUrl: function(file, callback) { var xhr = new XMLHttpRequest(); var mark = (this.opts.s3.search(/\?/) === -1) ? '?' : '&'; xhr.open('GET', this.opts.s3 + mark + 'name=' + file.name + '&type=' + file.type, true); // hack to pass bytes through unprocessed. if (xhr.overrideMimeType) { xhr.overrideMimeType('text/plain; charset=x-user-defined'); } var that = this; xhr.onreadystatechange = function(e) { if (this.readyState === 4 && this.status === 200) { that.progress.show(); callback(decodeURIComponent(this.responseText)); } }; xhr.send(); }, createCORSRequest: function(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { xhr.open(method, url, true); } else if (typeof XDomainRequest !== "undefined") { xhr = new XDomainRequest(); xhr.open(method, url); } else { xhr = null; } return xhr; }, sendToS3: function(file, url, formData) { var xhr = this.uploads3.createCORSRequest('PUT', url); if (!xhr) { return; } xhr.onload = $.proxy(function() { var json; this.progress.hide(); if (xhr.status !== 200) { // error json = { error: true }; this.upload.callback(json, this.upload.direct, xhr); return; } var s3file = url.split('?'); if (!s3file[0]) { // url parsing is fail return false; } if (!this.upload.direct) { this.upload.$droparea.removeClass('drag-drop'); } json = { url: s3file[0], id: s3file[0], s3: true }; if (this.upload.type === 'file') { var arr = s3file[0].split('/'); json.name = arr[arr.length-1]; } this.upload.callback(json, this.upload.direct, e); }, this); xhr.onerror = function() {}; xhr.upload.onprogress = function(e) {}; xhr.setRequestHeader('Content-Type', file.type); xhr.setRequestHeader('x-amz-acl', 'public-read'); xhr.send(formData); } }; }, // =utils utils: function() { return { isEmpty: function(html) { html = (typeof html === 'undefined') ? this.core.editor().html() : html; html = html.replace(/[\u200B-\u200D\uFEFF]/g, ''); html = html.replace(/&nbsp;/gi, ''); html = html.replace(/<\/?br\s?\/?>/g, ''); html = html.replace(/\s/g, ''); html = html.replace(/^<p>[^\W\w\D\d]*?<\/p>$/i, ''); html = html.replace(/<iframe(.*?[^>])>$/i, 'iframe'); html = html.replace(/<source(.*?[^>])>$/i, 'source'); // remove empty tags html = html.replace(/<[^\/>][^>]*><\/[^>]+>/gi, ''); html = html.replace(/<[^\/>][^>]*><\/[^>]+>/gi, ''); html = $.trim(html); return html === ''; }, isElement: function(obj) { try { // Using W3 DOM2 (works for FF, Opera and Chrome) return obj instanceof HTMLElement; } catch(e) { return (typeof obj === "object") && (obj.nodeType === 1) && (typeof obj.style === "object") && (typeof obj.ownerDocument === "object"); } }, strpos: function(haystack, needle, offset) { var i = haystack.indexOf(needle, offset); return i >= 0 ? i : false; }, dataURItoBlob: function(dataURI) { var byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) { byteString = atob(dataURI.split(',')[1]); } else { byteString = unescape(dataURI.split(',')[1]); } var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; var ia = new Uint8Array(byteString.length); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ia], { type:mimeString }); }, getOuterHtml: function(el) { return $('<div>').append($(el).eq(0).clone()).html(); }, cloneAttributes: function(from, to) { from = from[0] || from; to = $(to); var attrs = from.attributes; var len = attrs.length; while (len--) { var attr = attrs[len]; to.attr(attr.name, attr.value); } return to; }, breakBlockTag: function() { var block = this.selection.block(); if (!block) { return false; } var isEmpty = this.utils.isEmpty(block.innerHTML); var tag = block.tagName.toLowerCase(); if (tag === 'pre' || tag === 'li' || tag === 'td' || tag === 'th') { return false; } if (!isEmpty && this.utils.isStartOfElement(block)) { return { $block: $(block), $next: $(block).next(), type: 'start' }; } else if (!isEmpty && this.utils.isEndOfElement(block)) { return { $block: $(block), $next: $(block).next(), type: 'end' }; } else { var endOfNode = this.selection.extractEndOfNode(block); var $nextPart = $('<' + tag + ' />').append(endOfNode); $nextPart = this.utils.cloneAttributes(block, $nextPart); $(block).after($nextPart); return { $block: $(block), $next: $nextPart, type: 'break' }; } }, // tag detection inBlocks: function(tags) { tags = ($.isArray(tags)) ? tags : [tags]; var blocks = this.selection.blocks(); var len = blocks.length; var contains = false; for (var i = 0; i < len; i++) { if (blocks[i] !== false) { var tag = blocks[i].tagName.toLowerCase(); if ($.inArray(tag, tags) !== -1) { contains = true; } } } return contains; }, inInlines: function(tags) { tags = ($.isArray(tags)) ? tags : [tags]; var inlines = this.selection.inlines(); var len = inlines.length; var contains = false; for (var i = 0; i < len; i++) { var tag = inlines[i].tagName.toLowerCase(); if ($.inArray(tag, tags) !== -1) { contains = true; } } return contains; }, isTag: function(current, tag) { var element = $(current).closest(tag, this.core.editor()[0]); if (element.length === 1) { return element[0]; } return false; }, isBlock: function(block) { if (block === null) { return false; } block = block[0] || block; return block && this.utils.isBlockTag(block.tagName); }, isBlockTag: function(tag) { return (typeof tag === 'undefined') ? false : this.reIsBlock.test(tag); }, isInline: function(inline) { inline = inline[0] || inline; return inline && this.utils.isInlineTag(inline.tagName); }, isInlineTag: function(tag) { return (typeof tag === 'undefined') ? false : this.reIsInline.test(tag); }, // parents detection isRedactorParent: function(el) { if (!el) { return false; } if ($(el).parents('.redactor-in').length === 0 || $(el).hasClass('redactor-in')) { return false; } return el; }, isCurrentOrParentHeader: function() { return this.utils.isCurrentOrParent(['H1', 'H2', 'H3', 'H4', 'H5', 'H6']); }, isCurrentOrParent: function(tagName) { var parent = this.selection.parent(); var current = this.selection.current(); if ($.isArray(tagName)) { var matched = 0; $.each(tagName, $.proxy(function(i, s) { if (this.utils.isCurrentOrParentOne(current, parent, s)) { matched++; } }, this)); return (matched === 0) ? false : true; } else { return this.utils.isCurrentOrParentOne(current, parent, tagName); } }, isCurrentOrParentOne: function(current, parent, tagName) { tagName = tagName.toUpperCase(); return parent && parent.tagName === tagName ? parent : current && current.tagName === tagName ? current : false; }, isEditorRelative: function() { var position = this.core.editor().css('position'); var arr = ['absolute', 'fixed', 'relative']; return ($.inArray(arr, position) !== -1); }, setEditorRelative: function() { this.core.editor().addClass('redactor-relative'); }, // scroll getScrollTarget: function() { var $scrollTarget = $(this.opts.scrollTarget); return ($scrollTarget.length !== 0) ? $scrollTarget : $(document); }, freezeScroll: function() { this.freezeScrollTop = this.utils.getScrollTarget().scrollTop(); this.utils.getScrollTarget().scrollTop(this.freezeScrollTop); }, unfreezeScroll: function() { if (typeof this.freezeScrollTop === 'undefined') { return; } this.utils.getScrollTarget().scrollTop(this.freezeScrollTop); }, saveScroll: function() { this.tmpScrollTop = this.utils.getScrollTarget().scrollTop(); }, restoreScroll: function() { if (typeof this.tmpScrollTop === 'undefined') { return; } this.utils.getScrollTarget().scrollTop(this.tmpScrollTop); }, isStartOfElement: function(element) { if (typeof element === 'undefined') { element = this.selection.block(); if (!element) { return false; } } return (this.offset.get(element) === 0) ? true : false; }, isEndOfElement: function(element) { if (typeof element === 'undefined') { element = this.selection.block(); if (!element) { return false; } } var text = $.trim($(element).text()).replace(/[\t\n\r\n]/g, '').replace(/\u200B/g, ''); var offset = this.offset.get(element); return (offset === text.length) ? true : false; }, removeEmptyAttr: function(el, attr) { var $el = $(el); if (typeof $el.attr(attr) === 'undefined') { return true; } if ($el.attr(attr) === '') { $el.removeAttr(attr); return true; } return false; }, replaceToTag: function(node, tag) { var replacement; $(node).replaceWith(function() { replacement = $('<' + tag + ' />').append($(this).contents()); for (var i = 0; i < this.attributes.length; i++) { replacement.attr(this.attributes[i].name, this.attributes[i].value); } return replacement; }); return replacement; }, // select all isSelectAll: function() { return this.selectAll; }, enableSelectAll: function() { this.selectAll = true; }, disableSelectAll: function() { this.selectAll = false; }, disableBodyScroll: function() { var $body = $('html'); var windowWidth = window.innerWidth; if (!windowWidth) { var documentElementRect = document.documentElement.getBoundingClientRect(); windowWidth = documentElementRect.right - Math.abs(documentElementRect.left); } var isOverflowing = document.body.clientWidth < windowWidth; var scrollbarWidth = this.utils.measureScrollbar(); $body.css('overflow', 'hidden'); if (isOverflowing) { $body.css('padding-right', scrollbarWidth); } }, measureScrollbar: function() { var $body = $('body'); var scrollDiv = document.createElement('div'); scrollDiv.className = 'redactor-scrollbar-measure'; $body.append(scrollDiv); var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; $body[0].removeChild(scrollDiv); return scrollbarWidth; }, enableBodyScroll: function() { $('html').css({ 'overflow': '', 'padding-right': '' }); $('body').remove('redactor-scrollbar-measure'); }, appendFields: function(appendFields, data) { if (!appendFields) { return data; } else if (typeof appendFields === 'object') { $.each(appendFields, function(k, v) { if (v !== null && v.toString().indexOf('#') === 0) { v = $(v).val(); } data.append(k, v); }); return data; } var $fields = $(appendFields); if ($fields.length === 0) { return data; } else { var str = ''; $fields.each(function() { data.append($(this).attr('name'), $(this).val()); }); return data; } }, appendForms: function(appendForms, data) { if (!appendForms) { return data; } var $forms = $(appendForms); if ($forms.length === 0) { return data; } else { var formData = $forms.serializeArray(); $.each(formData, function(z,f) { data.append(f.name, f.value); }); return data; } }, isRgb: function(str) { return (str.search(/^rgb/i) === 0); }, rgb2hex: function(rgb) { rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i); return (rgb && rgb.length === 4) ? "#" + ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : ''; }, // #backward isCollapsed: function() { return this.selection.isCollapsed(); }, isMobile: function() { return this.detect.isMobile(); }, isDesktop: function() { return this.detect.isDesktop(); }, isPad: function() { return this.detect.isIpad(); } }; }, // #backward browser: function() { return { webkit: function() { return this.detect.isWebkit(); }, ff: function() { return this.detect.isFirefox(); }, ie: function() { return this.detect.isIe(); } }; } }; $(window).on('load.tools.redactor', function() { $('[data-tools="redactor"]').redactor(); }); // constructor Redactor.prototype.init.prototype = Redactor.prototype; })(jQuery); (function($) { $.fn.redactorAnimation = function(animation, options, callback) { return this.each(function() { new redactorAnimation(this, animation, options, callback); }); }; function redactorAnimation(element, animation, options, callback) { // default var opts = { duration: 0.5, iterate: 1, delay: 0, prefix: 'redactor-', timing: 'linear' }; this.animation = animation; this.slide = (this.animation === 'slideDown' || this.animation === 'slideUp'); this.$element = $(element); this.prefixes = ['', '-moz-', '-o-animation-', '-webkit-']; this.queue = []; // options or callback if (typeof options === 'function') { callback = options; this.opts = opts; } else { this.opts = $.extend(opts, options); } // slide if (this.slide) { this.$element.height(this.$element.height()); } // init this.init(callback); } redactorAnimation.prototype = { init: function(callback) { this.queue.push(this.animation); this.clean(); if (this.animation === 'show') { this.opts.timing = 'linear'; this.$element.removeClass('hide').show(); if (typeof callback === 'function') { callback(this); } } else if (this.animation === 'hide') { this.opts.timing = 'linear'; this.$element.hide(); if (typeof callback === 'function') { callback(this); } } else { this.animate(callback); } }, animate: function(callback) { this.$element.addClass('redactor-animated').css('display', '').removeClass('hide'); this.$element.addClass(this.opts.prefix + this.queue[0]); this.set(this.opts.duration + 's', this.opts.delay + 's', this.opts.iterate, this.opts.timing); var _callback = (this.queue.length > 1) ? null : callback; this.complete('AnimationEnd', $.proxy(function() { if (this.$element.hasClass(this.opts.prefix + this.queue[0])) { this.clean(); this.queue.shift(); if (this.queue.length) { this.animate(callback); } } }, this), _callback); }, set: function(duration, delay, iterate, timing) { var len = this.prefixes.length; while (len--) { this.$element.css(this.prefixes[len] + 'animation-duration', duration); this.$element.css(this.prefixes[len] + 'animation-delay', delay); this.$element.css(this.prefixes[len] + 'animation-iteration-count', iterate); this.$element.css(this.prefixes[len] + 'animation-timing-function', timing); } }, clean: function() { this.$element.removeClass('redactor-animated'); this.$element.removeClass(this.opts.prefix + this.queue[0]); this.set('', '', '', ''); }, complete: function(type, make, callback) { this.$element.one(type.toLowerCase() + ' webkit' + type + ' o' + type + ' MS' + type, $.proxy(function() { if (typeof make === 'function') { make(); } if (typeof callback === 'function') { callback(this); } // hide var effects = ['fadeOut', 'slideUp', 'zoomOut', 'slideOutUp', 'slideOutRight', 'slideOutLeft']; if ($.inArray(this.animation, effects) !== -1) { this.$element.css('display', 'none'); } // slide if (this.slide) { this.$element.css('height', ''); } }, this)); } }; })(jQuery);
{ "content_hash": "756c27ad809ab9264dc9c6354416e228", "timestamp": "", "source": "github", "line_count": 11168, "max_line_length": 234, "avg_line_length": 24.6822170487106, "alnum_prop": 0.5144113389757338, "repo_name": "nathanhnew/NLNF", "id": "778fc7349c9fc2c816a0fe616920aa2053909aaa", "size": "275897", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "static/redactor/redactor.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "214712" }, { "name": "HTML", "bytes": "12929" }, { "name": "JavaScript", "bytes": "766338" }, { "name": "Python", "bytes": "23803" } ], "symlink_target": "" }
#ifndef CRUFT_UTIL_POINTER_HPP #define CRUFT_UTIL_POINTER_HPP #include <cstddef> #include <cstdint> namespace util { /////////////////////////////////////////////////////////////////////////// /// round the pointer upwards to satisfy the provided alignment template <typename T> constexpr T* align (T *_ptr, size_t alignment) { // we perform this as two steps to avoid unnecessarily incrementing when // remainder is zero. auto ptr = reinterpret_cast<uintptr_t> (_ptr); if (ptr % alignment) ptr += alignment - ptr % alignment; return reinterpret_cast<T*> (ptr); } ///------------------------------------------------------------------------ /// round the pointer upwards to satisfy the provided alignment constexpr inline uintptr_t align (uintptr_t ptr, size_t alignment) { // we perform this as two steps to avoid unnecessarily incrementing when // remainder is zero. if (ptr % alignment) ptr += alignment - ptr % alignment; return ptr; } ///------------------------------------------------------------------------ /// round the pointer upwards to the nearest valid alignment for T template <typename T> constexpr auto align (T *t) { return align (t, alignof (T)); } ///------------------------------------------------------------------------ /// round the pointer upwards to the nearest valid alignment for T template <typename T> constexpr auto align (uintptr_t ptr) { return align (ptr, alignof (T)); } } #endif
{ "content_hash": "9259aed8549626039c8da63d5fb81d82", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 80, "avg_line_length": 27.915254237288135, "alnum_prop": 0.49848208864602306, "repo_name": "gim/libgim", "id": "bd55ccfc85733ad004256cb4502a2c0f7a9dfd30", "size": "2269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pointer.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1142733" }, { "name": "CMake", "bytes": "11891" }, { "name": "Python", "bytes": "8037" }, { "name": "Ragel", "bytes": "36511" }, { "name": "Shell", "bytes": "681" } ], "symlink_target": "" }
#ifndef _TCOD_BRESENHAM_H #define _TCOD_BRESENHAM_H typedef bool (*TCOD_line_listener_t) (int x, int y); TCODLIB_API void TCOD_line_init(int xFrom, int yFrom, int xTo, int yTo); TCODLIB_API bool TCOD_line_step(int *xCur, int *yCur); /* advance one step. returns true if we reach destination */ /* atomic callback function. Stops when the callback returns false */ TCODLIB_API bool TCOD_line(int xFrom, int yFrom, int xTo, int yTo, TCOD_line_listener_t listener); /* thread-safe versions */ typedef struct { int stepx; int stepy; int e; int deltax; int deltay; int origx; int origy; int destx; int desty; } TCOD_bresenham_data_t; TCODLIB_API void TCOD_line_init_mt(int xFrom, int yFrom, int xTo, int yTo, TCOD_bresenham_data_t *data); TCODLIB_API bool TCOD_line_step_mt(int *xCur, int *yCur, TCOD_bresenham_data_t *data); TCODLIB_API bool TCOD_line_mt(int xFrom, int yFrom, int xTo, int yTo, TCOD_line_listener_t listener, TCOD_bresenham_data_t *data); #endif
{ "content_hash": "3533cdd19af827de10346340dd96b535", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 130, "avg_line_length": 32.63333333333333, "alnum_prop": 0.7242083758937692, "repo_name": "lantra/vugamedev", "id": "82883b44f9bd19b3913ecd1a5accb6318a27edea", "size": "2485", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "dist/src/lib/libtcod-1.5.2/include/bresenham.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1382627" }, { "name": "C++", "bytes": "863116" }, { "name": "CSS", "bytes": "18584" }, { "name": "JavaScript", "bytes": "1647" }, { "name": "Objective-C", "bytes": "30562" }, { "name": "Python", "bytes": "270355" } ], "symlink_target": "" }
from django.test import TestCase from user_contacts.models import ( Person, Phone) class PersonTest(TestCase): def test_unicode(self): person = Person() first_name = "fred" last_name = "smith" person.first_name = first_name person.last_name = last_name expected = "%s, %s" % (last_name, first_name) actual = person.__unicode__() self.assertEquals(expected, actual) class PhoneTest(TestCase): def test_unicode(self): phone = Phone() number = "8675309" phone.number = number expected = number actual = phone.__unicode__() self.assertEquals(expected, actual)
{ "content_hash": "1af9e458ba58f7c4f913d974fcbd55a3", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 53, "avg_line_length": 24.642857142857142, "alnum_prop": 0.5942028985507246, "repo_name": "Victory/realpython-tdd", "id": "2d1f8fc7c55a92c8d1b8d54e68804548c64e7cfa", "size": "690", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "contacts/user_contacts/tests/test_models.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "756" }, { "name": "Python", "bytes": "30133" }, { "name": "Shell", "bytes": "1111" } ], "symlink_target": "" }
<?php require_once("inc.php"); checkLogin(); // Parameter auslesen $id = getArrayElement($_GET, "id"); $secret = getArrayElement($_GET, "secret"); $twick = TwickInfo::fetchById($id); $user = getUser(); // Sicher ist sicher if($user->getId() != $twick->getUserId() && !isAdmin() || $secret != $user->getSecret()) { redirect(HTTP_ROOT . "/index.php"); exit; } $title = _loc('mobile.edit.title'); include("inc/header.php"); ?> <div class="class_content"> <h1><?php loc('mobile.edit.headline', $twick->getTitle()) ?></h1> <?php if ($twick->isEditable()) { ?> <form action="confirm.php" method="post" id="your_twick"> <?php echo(SpamBlocker::printHiddenTags()) ?> <input type="hidden" name="id" value="<?php echo($twick->getId()) ?>" /> <input type="hidden" name="title" value="<?php echo(htmlspecialchars($twick->getTitle())) ?>" /> <label for="accronym"><?php loc('mobile.yourTwick.accronym') ?>:</label> <input type="text" name="accronym" value="<?php echo(htmlspecialchars($twick->getAccronym())) ?>" /><br /> <label for="text" id="explanationLabel"><?php loc('mobile.yourTwick.explanation') ?>:</label> <input id="explanationText" type="text" maxlength="140" name="text" value="<?php echo(htmlspecialchars($twick->getText())) ?>"/><br /> <label for="link"><?php loc('mobile.yourTwick.link') ?>:</label> <input type="text" name="link" value="<?php echo(htmlspecialchars($twick->getLink())) ?>"/><br /> <br /> <input type="submit" value="<?php loc('mobile.yourTwick.preview') ?>" class="class_button class_longbutton" /> </form> <?php include("inc/js_booster.php"); ?> <?php } else { ?> <?php loc('mobile.edit.notEditable') ?><br /> <br /> <a href="topic.php?search=<?php echo(urlencode($twick->getTitle())) ?>" style="padding:35px 0px 35px 0px;width:100%;display:block;border-top:1px solid #ccc">&nbsp;&nbsp;<?php loc('mobile.core.back') ?></a> <?php } ?> <br /> </div> <?php include("inc/footer.php"); ?> </body> </html>
{ "content_hash": "c4cf766bbe4174b199749ad2e1e88c03", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 205, "avg_line_length": 40.69387755102041, "alnum_prop": 0.6258776328986961, "repo_name": "derlangemarkus/Twick.it", "id": "dd2eea65da62c8b70f0c3f706ccdec4a40a8c1ab", "size": "1994", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "base/mobile/edit.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1185693" }, { "name": "JavaScript", "bytes": "2875795" }, { "name": "PHP", "bytes": "18635460" }, { "name": "Shell", "bytes": "599" } ], "symlink_target": "" }
package com.google.cloud.compute.v1; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.compute.v1.stub.GlobalForwardingRuleStub; import com.google.cloud.compute.v1.stub.GlobalForwardingRuleStubSettings; import com.google.common.util.concurrent.MoreExecutors; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND SERVICE /** * Service Description: Creates and runs virtual machines on Google Cloud Platform. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre> * <code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * Operation response = globalForwardingRuleClient.deleteGlobalForwardingRule(forwardingRule); * } * </code> * </pre> * * <p>Note: close() needs to be called on the globalForwardingRuleClient object to clean up * resources such as threads. In the example above, try-with-resources is used, which automatically * calls close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li>A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li>A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li>A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of GlobalForwardingRuleSettings * to create(). For example: * * <p>To customize credentials: * * <pre> * <code> * GlobalForwardingRuleSettings globalForwardingRuleSettings = * GlobalForwardingRuleSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * GlobalForwardingRuleClient globalForwardingRuleClient = * GlobalForwardingRuleClient.create(globalForwardingRuleSettings); * </code> * </pre> * * To customize the endpoint: * * <pre> * <code> * GlobalForwardingRuleSettings globalForwardingRuleSettings = * GlobalForwardingRuleSettings.newBuilder().setEndpoint(myEndpoint).build(); * GlobalForwardingRuleClient globalForwardingRuleClient = * GlobalForwardingRuleClient.create(globalForwardingRuleSettings); * </code> * </pre> */ @Generated("by gapic-generator") @BetaApi public class GlobalForwardingRuleClient implements BackgroundResource { private final GlobalForwardingRuleSettings settings; private final GlobalForwardingRuleStub stub; /** Constructs an instance of GlobalForwardingRuleClient with default settings. */ public static final GlobalForwardingRuleClient create() throws IOException { return create(GlobalForwardingRuleSettings.newBuilder().build()); } /** * Constructs an instance of GlobalForwardingRuleClient, using the given settings. The channels * are created based on the settings passed in, or defaults for any settings that are not set. */ public static final GlobalForwardingRuleClient create(GlobalForwardingRuleSettings settings) throws IOException { return new GlobalForwardingRuleClient(settings); } /** * Constructs an instance of GlobalForwardingRuleClient, using the given stub for making calls. * This is for advanced usage - prefer to use GlobalForwardingRuleSettings}. */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final GlobalForwardingRuleClient create(GlobalForwardingRuleStub stub) { return new GlobalForwardingRuleClient(stub); } /** * Constructs an instance of GlobalForwardingRuleClient, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected GlobalForwardingRuleClient(GlobalForwardingRuleSettings settings) throws IOException { this.settings = settings; this.stub = ((GlobalForwardingRuleStubSettings) settings.getStubSettings()).createStub(); } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") protected GlobalForwardingRuleClient(GlobalForwardingRuleStub stub) { this.settings = null; this.stub = stub; } public final GlobalForwardingRuleSettings getSettings() { return settings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public GlobalForwardingRuleStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Deletes the specified GlobalForwardingRule resource. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * Operation response = globalForwardingRuleClient.deleteGlobalForwardingRule(forwardingRule); * } * </code></pre> * * @param forwardingRule Name of the ForwardingRule resource to delete. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation deleteGlobalForwardingRule( ProjectGlobalForwardingRuleName forwardingRule) { DeleteGlobalForwardingRuleHttpRequest request = DeleteGlobalForwardingRuleHttpRequest.newBuilder() .setForwardingRule(forwardingRule == null ? null : forwardingRule.toString()) .build(); return deleteGlobalForwardingRule(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Deletes the specified GlobalForwardingRule resource. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * Operation response = globalForwardingRuleClient.deleteGlobalForwardingRule(forwardingRule.toString()); * } * </code></pre> * * @param forwardingRule Name of the ForwardingRule resource to delete. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation deleteGlobalForwardingRule(String forwardingRule) { DeleteGlobalForwardingRuleHttpRequest request = DeleteGlobalForwardingRuleHttpRequest.newBuilder() .setForwardingRule(forwardingRule) .build(); return deleteGlobalForwardingRule(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Deletes the specified GlobalForwardingRule resource. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * DeleteGlobalForwardingRuleHttpRequest request = DeleteGlobalForwardingRuleHttpRequest.newBuilder() * .setForwardingRule(forwardingRule.toString()) * .build(); * Operation response = globalForwardingRuleClient.deleteGlobalForwardingRule(request); * } * </code></pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation deleteGlobalForwardingRule(DeleteGlobalForwardingRuleHttpRequest request) { return deleteGlobalForwardingRuleCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Deletes the specified GlobalForwardingRule resource. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * DeleteGlobalForwardingRuleHttpRequest request = DeleteGlobalForwardingRuleHttpRequest.newBuilder() * .setForwardingRule(forwardingRule.toString()) * .build(); * ApiFuture&lt;Operation&gt; future = globalForwardingRuleClient.deleteGlobalForwardingRuleCallable().futureCall(request); * // Do something * Operation response = future.get(); * } * </code></pre> */ @BetaApi public final UnaryCallable<DeleteGlobalForwardingRuleHttpRequest, Operation> deleteGlobalForwardingRuleCallable() { return stub.deleteGlobalForwardingRuleCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Returns the specified GlobalForwardingRule resource. Gets a list of available forwarding rules * by making a list() request. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * ForwardingRule response = globalForwardingRuleClient.getGlobalForwardingRule(forwardingRule); * } * </code></pre> * * @param forwardingRule Name of the ForwardingRule resource to return. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final ForwardingRule getGlobalForwardingRule( ProjectGlobalForwardingRuleName forwardingRule) { GetGlobalForwardingRuleHttpRequest request = GetGlobalForwardingRuleHttpRequest.newBuilder() .setForwardingRule(forwardingRule == null ? null : forwardingRule.toString()) .build(); return getGlobalForwardingRule(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Returns the specified GlobalForwardingRule resource. Gets a list of available forwarding rules * by making a list() request. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * ForwardingRule response = globalForwardingRuleClient.getGlobalForwardingRule(forwardingRule.toString()); * } * </code></pre> * * @param forwardingRule Name of the ForwardingRule resource to return. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final ForwardingRule getGlobalForwardingRule(String forwardingRule) { GetGlobalForwardingRuleHttpRequest request = GetGlobalForwardingRuleHttpRequest.newBuilder().setForwardingRule(forwardingRule).build(); return getGlobalForwardingRule(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Returns the specified GlobalForwardingRule resource. Gets a list of available forwarding rules * by making a list() request. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * GetGlobalForwardingRuleHttpRequest request = GetGlobalForwardingRuleHttpRequest.newBuilder() * .setForwardingRule(forwardingRule.toString()) * .build(); * ForwardingRule response = globalForwardingRuleClient.getGlobalForwardingRule(request); * } * </code></pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final ForwardingRule getGlobalForwardingRule(GetGlobalForwardingRuleHttpRequest request) { return getGlobalForwardingRuleCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Returns the specified GlobalForwardingRule resource. Gets a list of available forwarding rules * by making a list() request. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * GetGlobalForwardingRuleHttpRequest request = GetGlobalForwardingRuleHttpRequest.newBuilder() * .setForwardingRule(forwardingRule.toString()) * .build(); * ApiFuture&lt;ForwardingRule&gt; future = globalForwardingRuleClient.getGlobalForwardingRuleCallable().futureCall(request); * // Do something * ForwardingRule response = future.get(); * } * </code></pre> */ @BetaApi public final UnaryCallable<GetGlobalForwardingRuleHttpRequest, ForwardingRule> getGlobalForwardingRuleCallable() { return stub.getGlobalForwardingRuleCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Creates a GlobalForwardingRule resource in the specified project using the data included in the * request. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * ForwardingRule forwardingRuleResource = ForwardingRule.newBuilder().build(); * Operation response = globalForwardingRuleClient.insertGlobalForwardingRule(project, forwardingRuleResource); * } * </code></pre> * * @param project Project ID for this request. * @param forwardingRuleResource A ForwardingRule resource. A ForwardingRule resource specifies * which pool of target virtual machines to forward a packet to if it matches the given * [IPAddress, IPProtocol, ports] tuple. (== resource_for beta.forwardingRules ==) (== * resource_for v1.forwardingRules ==) (== resource_for beta.globalForwardingRules ==) (== * resource_for v1.globalForwardingRules ==) (== resource_for beta.regionForwardingRules ==) * (== resource_for v1.regionForwardingRules ==) * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation insertGlobalForwardingRule( ProjectName project, ForwardingRule forwardingRuleResource) { InsertGlobalForwardingRuleHttpRequest request = InsertGlobalForwardingRuleHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .setForwardingRuleResource(forwardingRuleResource) .build(); return insertGlobalForwardingRule(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Creates a GlobalForwardingRule resource in the specified project using the data included in the * request. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * ForwardingRule forwardingRuleResource = ForwardingRule.newBuilder().build(); * Operation response = globalForwardingRuleClient.insertGlobalForwardingRule(project.toString(), forwardingRuleResource); * } * </code></pre> * * @param project Project ID for this request. * @param forwardingRuleResource A ForwardingRule resource. A ForwardingRule resource specifies * which pool of target virtual machines to forward a packet to if it matches the given * [IPAddress, IPProtocol, ports] tuple. (== resource_for beta.forwardingRules ==) (== * resource_for v1.forwardingRules ==) (== resource_for beta.globalForwardingRules ==) (== * resource_for v1.globalForwardingRules ==) (== resource_for beta.regionForwardingRules ==) * (== resource_for v1.regionForwardingRules ==) * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation insertGlobalForwardingRule( String project, ForwardingRule forwardingRuleResource) { InsertGlobalForwardingRuleHttpRequest request = InsertGlobalForwardingRuleHttpRequest.newBuilder() .setProject(project) .setForwardingRuleResource(forwardingRuleResource) .build(); return insertGlobalForwardingRule(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Creates a GlobalForwardingRule resource in the specified project using the data included in the * request. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * ForwardingRule forwardingRuleResource = ForwardingRule.newBuilder().build(); * InsertGlobalForwardingRuleHttpRequest request = InsertGlobalForwardingRuleHttpRequest.newBuilder() * .setProject(project.toString()) * .setForwardingRuleResource(forwardingRuleResource) * .build(); * Operation response = globalForwardingRuleClient.insertGlobalForwardingRule(request); * } * </code></pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation insertGlobalForwardingRule(InsertGlobalForwardingRuleHttpRequest request) { return insertGlobalForwardingRuleCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Creates a GlobalForwardingRule resource in the specified project using the data included in the * request. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * ForwardingRule forwardingRuleResource = ForwardingRule.newBuilder().build(); * InsertGlobalForwardingRuleHttpRequest request = InsertGlobalForwardingRuleHttpRequest.newBuilder() * .setProject(project.toString()) * .setForwardingRuleResource(forwardingRuleResource) * .build(); * ApiFuture&lt;Operation&gt; future = globalForwardingRuleClient.insertGlobalForwardingRuleCallable().futureCall(request); * // Do something * Operation response = future.get(); * } * </code></pre> */ @BetaApi public final UnaryCallable<InsertGlobalForwardingRuleHttpRequest, Operation> insertGlobalForwardingRuleCallable() { return stub.insertGlobalForwardingRuleCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Retrieves a list of GlobalForwardingRule resources available to the specified project. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * for (ForwardingRule element : globalForwardingRuleClient.listGlobalForwardingRules(project).iterateAll()) { * // doThingsWith(element); * } * } * </code></pre> * * @param project Project ID for this request. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final ListGlobalForwardingRulesPagedResponse listGlobalForwardingRules( ProjectName project) { ListGlobalForwardingRulesHttpRequest request = ListGlobalForwardingRulesHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .build(); return listGlobalForwardingRules(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Retrieves a list of GlobalForwardingRule resources available to the specified project. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * for (ForwardingRule element : globalForwardingRuleClient.listGlobalForwardingRules(project.toString()).iterateAll()) { * // doThingsWith(element); * } * } * </code></pre> * * @param project Project ID for this request. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final ListGlobalForwardingRulesPagedResponse listGlobalForwardingRules(String project) { ListGlobalForwardingRulesHttpRequest request = ListGlobalForwardingRulesHttpRequest.newBuilder().setProject(project).build(); return listGlobalForwardingRules(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Retrieves a list of GlobalForwardingRule resources available to the specified project. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * ListGlobalForwardingRulesHttpRequest request = ListGlobalForwardingRulesHttpRequest.newBuilder() * .setProject(project.toString()) * .build(); * for (ForwardingRule element : globalForwardingRuleClient.listGlobalForwardingRules(request).iterateAll()) { * // doThingsWith(element); * } * } * </code></pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final ListGlobalForwardingRulesPagedResponse listGlobalForwardingRules( ListGlobalForwardingRulesHttpRequest request) { return listGlobalForwardingRulesPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Retrieves a list of GlobalForwardingRule resources available to the specified project. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * ListGlobalForwardingRulesHttpRequest request = ListGlobalForwardingRulesHttpRequest.newBuilder() * .setProject(project.toString()) * .build(); * ApiFuture&lt;ListGlobalForwardingRulesPagedResponse&gt; future = globalForwardingRuleClient.listGlobalForwardingRulesPagedCallable().futureCall(request); * // Do something * for (ForwardingRule element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * </code></pre> */ @BetaApi public final UnaryCallable< ListGlobalForwardingRulesHttpRequest, ListGlobalForwardingRulesPagedResponse> listGlobalForwardingRulesPagedCallable() { return stub.listGlobalForwardingRulesPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Retrieves a list of GlobalForwardingRule resources available to the specified project. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectName project = ProjectName.of("[PROJECT]"); * ListGlobalForwardingRulesHttpRequest request = ListGlobalForwardingRulesHttpRequest.newBuilder() * .setProject(project.toString()) * .build(); * while (true) { * ForwardingRuleList response = globalForwardingRuleClient.listGlobalForwardingRulesCallable().call(request); * for (ForwardingRule element : response.getItemsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * </code></pre> */ @BetaApi public final UnaryCallable<ListGlobalForwardingRulesHttpRequest, ForwardingRuleList> listGlobalForwardingRulesCallable() { return stub.listGlobalForwardingRulesCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Changes target URL for the GlobalForwardingRule resource. The new target should be of the same * type as the old target. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * TargetReference targetReferenceResource = TargetReference.newBuilder().build(); * Operation response = globalForwardingRuleClient.setTargetGlobalForwardingRule(forwardingRule, targetReferenceResource); * } * </code></pre> * * @param forwardingRule Name of the ForwardingRule resource in which target is to be set. * @param targetReferenceResource * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation setTargetGlobalForwardingRule( ProjectGlobalForwardingRuleName forwardingRule, TargetReference targetReferenceResource) { SetTargetGlobalForwardingRuleHttpRequest request = SetTargetGlobalForwardingRuleHttpRequest.newBuilder() .setForwardingRule(forwardingRule == null ? null : forwardingRule.toString()) .setTargetReferenceResource(targetReferenceResource) .build(); return setTargetGlobalForwardingRule(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Changes target URL for the GlobalForwardingRule resource. The new target should be of the same * type as the old target. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * TargetReference targetReferenceResource = TargetReference.newBuilder().build(); * Operation response = globalForwardingRuleClient.setTargetGlobalForwardingRule(forwardingRule.toString(), targetReferenceResource); * } * </code></pre> * * @param forwardingRule Name of the ForwardingRule resource in which target is to be set. * @param targetReferenceResource * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation setTargetGlobalForwardingRule( String forwardingRule, TargetReference targetReferenceResource) { SetTargetGlobalForwardingRuleHttpRequest request = SetTargetGlobalForwardingRuleHttpRequest.newBuilder() .setForwardingRule(forwardingRule) .setTargetReferenceResource(targetReferenceResource) .build(); return setTargetGlobalForwardingRule(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Changes target URL for the GlobalForwardingRule resource. The new target should be of the same * type as the old target. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * TargetReference targetReferenceResource = TargetReference.newBuilder().build(); * SetTargetGlobalForwardingRuleHttpRequest request = SetTargetGlobalForwardingRuleHttpRequest.newBuilder() * .setForwardingRule(forwardingRule.toString()) * .setTargetReferenceResource(targetReferenceResource) * .build(); * Operation response = globalForwardingRuleClient.setTargetGlobalForwardingRule(request); * } * </code></pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ @BetaApi public final Operation setTargetGlobalForwardingRule( SetTargetGlobalForwardingRuleHttpRequest request) { return setTargetGlobalForwardingRuleCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Changes target URL for the GlobalForwardingRule resource. The new target should be of the same * type as the old target. * * <p>Sample code: * * <pre><code> * try (GlobalForwardingRuleClient globalForwardingRuleClient = GlobalForwardingRuleClient.create()) { * ProjectGlobalForwardingRuleName forwardingRule = ProjectGlobalForwardingRuleName.of("[PROJECT]", "[FORWARDING_RULE]"); * TargetReference targetReferenceResource = TargetReference.newBuilder().build(); * SetTargetGlobalForwardingRuleHttpRequest request = SetTargetGlobalForwardingRuleHttpRequest.newBuilder() * .setForwardingRule(forwardingRule.toString()) * .setTargetReferenceResource(targetReferenceResource) * .build(); * ApiFuture&lt;Operation&gt; future = globalForwardingRuleClient.setTargetGlobalForwardingRuleCallable().futureCall(request); * // Do something * Operation response = future.get(); * } * </code></pre> */ @BetaApi public final UnaryCallable<SetTargetGlobalForwardingRuleHttpRequest, Operation> setTargetGlobalForwardingRuleCallable() { return stub.setTargetGlobalForwardingRuleCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListGlobalForwardingRulesPagedResponse extends AbstractPagedListResponse< ListGlobalForwardingRulesHttpRequest, ForwardingRuleList, ForwardingRule, ListGlobalForwardingRulesPage, ListGlobalForwardingRulesFixedSizeCollection> { public static ApiFuture<ListGlobalForwardingRulesPagedResponse> createAsync( PageContext<ListGlobalForwardingRulesHttpRequest, ForwardingRuleList, ForwardingRule> context, ApiFuture<ForwardingRuleList> futureResponse) { ApiFuture<ListGlobalForwardingRulesPage> futurePage = ListGlobalForwardingRulesPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, new ApiFunction<ListGlobalForwardingRulesPage, ListGlobalForwardingRulesPagedResponse>() { @Override public ListGlobalForwardingRulesPagedResponse apply( ListGlobalForwardingRulesPage input) { return new ListGlobalForwardingRulesPagedResponse(input); } }, MoreExecutors.directExecutor()); } private ListGlobalForwardingRulesPagedResponse(ListGlobalForwardingRulesPage page) { super(page, ListGlobalForwardingRulesFixedSizeCollection.createEmptyCollection()); } } public static class ListGlobalForwardingRulesPage extends AbstractPage< ListGlobalForwardingRulesHttpRequest, ForwardingRuleList, ForwardingRule, ListGlobalForwardingRulesPage> { private ListGlobalForwardingRulesPage( PageContext<ListGlobalForwardingRulesHttpRequest, ForwardingRuleList, ForwardingRule> context, ForwardingRuleList response) { super(context, response); } private static ListGlobalForwardingRulesPage createEmptyPage() { return new ListGlobalForwardingRulesPage(null, null); } @Override protected ListGlobalForwardingRulesPage createPage( PageContext<ListGlobalForwardingRulesHttpRequest, ForwardingRuleList, ForwardingRule> context, ForwardingRuleList response) { return new ListGlobalForwardingRulesPage(context, response); } @Override public ApiFuture<ListGlobalForwardingRulesPage> createPageAsync( PageContext<ListGlobalForwardingRulesHttpRequest, ForwardingRuleList, ForwardingRule> context, ApiFuture<ForwardingRuleList> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListGlobalForwardingRulesFixedSizeCollection extends AbstractFixedSizeCollection< ListGlobalForwardingRulesHttpRequest, ForwardingRuleList, ForwardingRule, ListGlobalForwardingRulesPage, ListGlobalForwardingRulesFixedSizeCollection> { private ListGlobalForwardingRulesFixedSizeCollection( List<ListGlobalForwardingRulesPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListGlobalForwardingRulesFixedSizeCollection createEmptyCollection() { return new ListGlobalForwardingRulesFixedSizeCollection(null, 0); } @Override protected ListGlobalForwardingRulesFixedSizeCollection createCollection( List<ListGlobalForwardingRulesPage> pages, int collectionSize) { return new ListGlobalForwardingRulesFixedSizeCollection(pages, collectionSize); } } }
{ "content_hash": "bb95c23555ad507c7e3edb0d1b52c271", "timestamp": "", "source": "github", "line_count": 849, "max_line_length": 160, "avg_line_length": 41.08362779740872, "alnum_prop": 0.7364105504587156, "repo_name": "vam-google/google-cloud-java", "id": "7708ee9c662d9b4b92cea655fd29ffd2f8740628", "size": "35474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/GlobalForwardingRuleClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "128" }, { "name": "CSS", "bytes": "23036" }, { "name": "Dockerfile", "bytes": "127" }, { "name": "Go", "bytes": "9641" }, { "name": "HTML", "bytes": "16158" }, { "name": "Java", "bytes": "47356483" }, { "name": "JavaScript", "bytes": "989" }, { "name": "Python", "bytes": "110799" }, { "name": "Shell", "bytes": "9162" } ], "symlink_target": "" }
package com.facebook.buck.python; import static org.junit.Assert.assertThat; import com.facebook.buck.cli.BuildTargetNodeToBuildRuleTransformer; import com.facebook.buck.cli.FakeBuckConfig; import com.facebook.buck.cxx.CxxBinaryBuilder; import com.facebook.buck.cxx.CxxPlatformUtils; import com.facebook.buck.io.AlwaysFoundExecutableFinder; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.model.FlavorDomain; import com.facebook.buck.model.ImmutableFlavor; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRules; import com.facebook.buck.rules.FakeBuildContext; import com.facebook.buck.rules.FakeBuildableContext; import com.facebook.buck.rules.FakeSourcePath; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.coercer.PatternMatchedCollection; import com.facebook.buck.rules.coercer.SourceList; import com.facebook.buck.shell.ShBinary; import com.facebook.buck.shell.ShBinaryBuilder; import com.facebook.buck.step.Step; import com.facebook.buck.testutil.TargetGraphFactory; import com.google.common.base.Optional; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import org.hamcrest.Matchers; import org.junit.Test; import java.nio.file.Paths; import java.util.regex.Pattern; public class PythonTestDescriptionTest { @Test public void thatTestModulesAreInComponents() throws Exception { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer()); PythonTest testRule = (PythonTest) PythonTestBuilder.create(BuildTargetFactory.newInstance("//:bin")) .setSrcs( SourceList.ofUnnamedSources( ImmutableSortedSet.<SourcePath>of(new FakeSourcePath("blah.py")))) .build(resolver); PythonBinary binRule = testRule.getBinary(); PythonPackageComponents components = binRule.getComponents(); assertThat( components.getModules().keySet(), Matchers.hasItem(PythonTestDescription.getTestModulesListName())); assertThat( components.getModules().keySet(), Matchers.hasItem(PythonTestDescription.getTestMainName())); assertThat( binRule.getMainModule(), Matchers.equalTo( PythonUtil.toModuleName( testRule.getBuildTarget(), PythonTestDescription.getTestMainName().toString()))); } @Test public void baseModule() throws Exception { BuildTarget target = BuildTargetFactory.newInstance("//foo:test"); String sourceName = "main.py"; SourcePath source = new FakeSourcePath("foo/" + sourceName); // Run without a base module set and verify it defaults to using the build target // base name. PythonTest normal = (PythonTest) PythonTestBuilder.create(target) .setSrcs(SourceList.ofUnnamedSources(ImmutableSortedSet.of(source))) .build( new BuildRuleResolver( TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer())); assertThat( normal.getBinary().getComponents().getModules().keySet(), Matchers.hasItem(target.getBasePath().resolve(sourceName))); // Run *with* a base module set and verify it gets used to build the main module path. String baseModule = "blah"; PythonTest withBaseModule = (PythonTest) PythonTestBuilder.create(target) .setSrcs(SourceList.ofUnnamedSources(ImmutableSortedSet.of(source))) .setBaseModule(baseModule) .build( new BuildRuleResolver( TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer())); assertThat( withBaseModule.getBinary().getComponents().getModules().keySet(), Matchers.hasItem(Paths.get(baseModule).resolve(sourceName))); } @Test public void buildArgs() throws Exception { BuildTarget target = BuildTargetFactory.newInstance("//foo:test"); BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer()); ImmutableList<String> buildArgs = ImmutableList.of("--some", "--args"); PythonTest test = (PythonTest) PythonTestBuilder.create(target) .setBuildArgs(buildArgs) .build(resolver); PythonBinary binary = test.getBinary(); ImmutableList<Step> buildSteps = binary.getBuildSteps(FakeBuildContext.NOOP_CONTEXT, new FakeBuildableContext()); PexStep pexStep = FluentIterable.from(buildSteps) .filter(PexStep.class) .get(0); assertThat( pexStep.getCommandPrefix(), Matchers.hasItems(buildArgs.toArray(new String[buildArgs.size()]))); } @Test public void platformSrcs() throws Exception { BuildTarget target = BuildTargetFactory.newInstance("//foo:test"); SourcePath matchedSource = new FakeSourcePath("foo/a.py"); SourcePath unmatchedSource = new FakeSourcePath("foo/b.py"); PythonTest test = (PythonTest) PythonTestBuilder.create(target) .setPlatformSrcs( PatternMatchedCollection.<SourceList>builder() .add( Pattern.compile(PythonTestUtils.PYTHON_PLATFORM.getFlavor().toString()), SourceList.ofUnnamedSources(ImmutableSortedSet.of(matchedSource))) .add( Pattern.compile("won't match anything"), SourceList.ofUnnamedSources(ImmutableSortedSet.of(unmatchedSource))) .build()) .build( new BuildRuleResolver( TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer())); assertThat( test.getBinary().getComponents().getModules().values(), Matchers.allOf( Matchers.hasItem(matchedSource), Matchers.not(Matchers.hasItem(unmatchedSource)))); } @Test public void platformResources() throws Exception { BuildTarget target = BuildTargetFactory.newInstance("//foo:test"); SourcePath matchedSource = new FakeSourcePath("foo/a.dat"); SourcePath unmatchedSource = new FakeSourcePath("foo/b.dat"); PythonTest test = (PythonTest) PythonTestBuilder.create(target) .setPlatformResources( PatternMatchedCollection.<SourceList>builder() .add( Pattern.compile(PythonTestUtils.PYTHON_PLATFORM.getFlavor().toString()), SourceList.ofUnnamedSources(ImmutableSortedSet.of(matchedSource))) .add( Pattern.compile("won't match anything"), SourceList.ofUnnamedSources(ImmutableSortedSet.of(unmatchedSource))) .build()) .build( new BuildRuleResolver( TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer())); assertThat( test.getBinary().getComponents().getResources().values(), Matchers.allOf( Matchers.hasItem(matchedSource), Matchers.not(Matchers.hasItem(unmatchedSource)))); } @Test public void explicitPythonHome() throws Exception { PythonPlatform platform1 = PythonPlatform.of( ImmutableFlavor.of("pyPlat1"), new PythonEnvironment(Paths.get("python2.6"), PythonVersion.of("CPython", "2.6")), Optional.<BuildTarget>absent()); PythonPlatform platform2 = PythonPlatform.of( ImmutableFlavor.of("pyPlat2"), new PythonEnvironment(Paths.get("python2.7"), PythonVersion.of("CPython", "2.7")), Optional.<BuildTarget>absent()); PythonTestBuilder builder = PythonTestBuilder.create( BuildTargetFactory.newInstance("//:bin"), FlavorDomain.of("Python Platform", platform1, platform2)); PythonTest test1 = (PythonTest) builder .setPlatform(platform1.getFlavor().toString()) .build( new BuildRuleResolver( TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer())); assertThat(test1.getBinary().getPythonPlatform(), Matchers.equalTo(platform1)); PythonTest test2 = (PythonTest) builder .setPlatform(platform2.getFlavor().toString()) .build( new BuildRuleResolver( TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer())); assertThat(test2.getBinary().getPythonPlatform(), Matchers.equalTo(platform2)); } @Test public void runtimeDepOnDeps() throws Exception { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer()); BuildRule cxxBinary = new CxxBinaryBuilder(BuildTargetFactory.newInstance("//:dep")) .build(resolver); BuildRule pythonLibrary = new PythonLibraryBuilder(BuildTargetFactory.newInstance("//:lib")) .setDeps(ImmutableSortedSet.of(cxxBinary.getBuildTarget())) .build(resolver); PythonTest pythonTest = (PythonTest) PythonTestBuilder.create(BuildTargetFactory.newInstance("//:test")) .setDeps(ImmutableSortedSet.of(pythonLibrary.getBuildTarget())) .build(resolver); assertThat( BuildRules.getTransitiveRuntimeDeps(pythonTest), Matchers.hasItem(cxxBinary)); } @Test public void packageStyleParam() throws Exception { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer()); PythonTest pythonTest = (PythonTest) PythonTestBuilder.create(BuildTargetFactory.newInstance("//:bin")) .setPackageStyle(PythonBuckConfig.PackageStyle.INPLACE) .build(resolver); assertThat( pythonTest.getBinary(), Matchers.instanceOf(PythonInPlaceBinary.class)); resolver = new BuildRuleResolver(TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer()); pythonTest = (PythonTest) PythonTestBuilder.create(BuildTargetFactory.newInstance("//:bin")) .setPackageStyle(PythonBuckConfig.PackageStyle.STANDALONE) .build(resolver); assertThat( pythonTest.getBinary(), Matchers.instanceOf(PythonPackagedBinary.class)); } @Test public void pexExecutorIsAddedToTestRuntimeDeps() throws Exception { ShBinaryBuilder pexExecutorBuilder = new ShBinaryBuilder(BuildTargetFactory.newInstance("//:pex_executor")) .setMain(new FakeSourcePath("run.sh")); PythonTestBuilder builder = new PythonTestBuilder( BuildTargetFactory.newInstance("//:bin"), new PythonBuckConfig( FakeBuckConfig.builder() .setSections( ImmutableMap.of( "python", ImmutableMap.of( "path_to_pex_executer", pexExecutorBuilder.getTarget().toString()))) .build(), new AlwaysFoundExecutableFinder()), PythonTestUtils.PYTHON_PLATFORMS, CxxPlatformUtils.DEFAULT_PLATFORM, CxxPlatformUtils.DEFAULT_PLATFORMS); builder .setPackageStyle(PythonBuckConfig.PackageStyle.STANDALONE); BuildRuleResolver resolver = new BuildRuleResolver( TargetGraphFactory.newInstance( pexExecutorBuilder.build(), builder.build()), new BuildTargetNodeToBuildRuleTransformer()); ShBinary pexExecutor = (ShBinary) pexExecutorBuilder.build(resolver); PythonTest binary = (PythonTest) builder.build(resolver); assertThat( binary.getRuntimeDeps(), Matchers.hasItem(pexExecutor)); } }
{ "content_hash": "731a5a64a40d06dc12b490bb7153e2d2", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 96, "avg_line_length": 42.243986254295535, "alnum_prop": 0.6661514683153014, "repo_name": "mikekap/buck", "id": "c912aad7e1060ae8704657f62eee7e9cc81f3ce3", "size": "12898", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/com/facebook/buck/python/PythonTestDescriptionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "87" }, { "name": "Batchfile", "bytes": "726" }, { "name": "C", "bytes": "246511" }, { "name": "C#", "bytes": "237" }, { "name": "C++", "bytes": "5058" }, { "name": "CSS", "bytes": "54863" }, { "name": "D", "bytes": "1017" }, { "name": "Go", "bytes": "13780" }, { "name": "Groff", "bytes": "440" }, { "name": "Groovy", "bytes": "3362" }, { "name": "HTML", "bytes": "5108" }, { "name": "IDL", "bytes": "128" }, { "name": "Java", "bytes": "12550121" }, { "name": "JavaScript", "bytes": "931960" }, { "name": "Lex", "bytes": "2442" }, { "name": "MATLAB", "bytes": "47" }, { "name": "Makefile", "bytes": "1791" }, { "name": "OCaml", "bytes": "3060" }, { "name": "Objective-C", "bytes": "108013" }, { "name": "Objective-C++", "bytes": "34" }, { "name": "PowerShell", "bytes": "244" }, { "name": "Python", "bytes": "259021" }, { "name": "Rust", "bytes": "938" }, { "name": "Scala", "bytes": "898" }, { "name": "Shell", "bytes": "30060" }, { "name": "Smalltalk", "bytes": "897" }, { "name": "Standard ML", "bytes": "15" }, { "name": "Swift", "bytes": "3735" }, { "name": "Thrift", "bytes": "387" }, { "name": "Yacc", "bytes": "323" } ], "symlink_target": "" }
import arcpy from arcpy.sa import * import os def init(input_shp): #arcpy.env.workspace = arcpy.env.scratchFolder arcpy.CheckOutExtension('Spatial') arcpy.AddMessage(arcpy.CheckExtension('Spatial')) # adding new shapefile to ArcMap mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "*")[0] newLayer = arcpy.mapping.Layer(input_shp) arcpy.ApplySymbologyFromLayer_management(newLayer, "points_new_style.lyr") arcpy.mapping.AddLayer(df, newLayer, "TOP") arcpy.env.workspace = arcpy.env.scratchGDB arcpy.env.workspace = arcpy.env.scratchFolder arcpy.AddMessage(arcpy.env.workspace) densityOutput = PointDensity(input_shp, 'accuracy') densityOutput.save('density.tif') densityLayer = arcpy.mapping.Layer('density.tif') arcpy.ApplySymbologyFromLayer_management(densityLayer, "density_style.lyr") arcpy.mapping.AddLayer(df, densityLayer, "BOTTOM")
{ "content_hash": "32db66aa704362187fdbb88991cd115d", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 79, "avg_line_length": 32.666666666666664, "alnum_prop": 0.710204081632653, "repo_name": "mdragunski/BottleNcr", "id": "ad101983da039c3d744a32283ad2ebf85aeb8a9d", "size": "980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "visualizer.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "9499" } ], "symlink_target": "" }
<config> <maxchars>10000</maxchars> <maxrows>500</maxrows> <timeout>5</timeout> <memory>100</memory> <permission>admin</permission> </config>
{ "content_hash": "794547e1f18a87c1678f7ba2d9da2a61", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 32, "avg_line_length": 22.428571428571427, "alnum_prop": 0.6687898089171974, "repo_name": "ksclarke/basex", "id": "83da3a46dfb8810c081a361da9d6286389423f9d", "size": "157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "basex-api/src/main/webapp/dba/files/config.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "9372" }, { "name": "Batchfile", "bytes": "2502" }, { "name": "C", "bytes": "17146" }, { "name": "C#", "bytes": "15295" }, { "name": "C++", "bytes": "7796" }, { "name": "CSS", "bytes": "3386" }, { "name": "Common Lisp", "bytes": "3211" }, { "name": "HTML", "bytes": "1057" }, { "name": "Haskell", "bytes": "4065" }, { "name": "Java", "bytes": "23470529" }, { "name": "JavaScript", "bytes": "6834" }, { "name": "Makefile", "bytes": "1234" }, { "name": "PHP", "bytes": "8690" }, { "name": "Perl", "bytes": "7801" }, { "name": "Python", "bytes": "26123" }, { "name": "QMake", "bytes": "377" }, { "name": "Rebol", "bytes": "4731" }, { "name": "Ruby", "bytes": "7359" }, { "name": "Scala", "bytes": "11692" }, { "name": "Shell", "bytes": "3557" }, { "name": "Visual Basic", "bytes": "11957" }, { "name": "XQuery", "bytes": "306332" }, { "name": "XSLT", "bytes": "172" } ], "symlink_target": "" }
<html> <head lang="en"> <!-- IE Edge Meta Tag --> <meta charset="UTF-8"> <!-- Viewport : enables combatibility with display on smaller devices --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Upload</title> <!-- links to style sheet --> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" /> <!-- putting script after does not allow upload feedback --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <!-- <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> --> </head> <style> .btn-file { position: relative; overflow: hidden; } .btn-file input[type=file] { position: absolute; top: 0; right: 0; min-width: 100%; min-height: 100%; font-size: 100px; text-align: right; filter: alpha(opacity=0); opacity: 0; outline: none; background: white; cursor: inherit; display: block; } input[readonly] { background-color: white !important ; cursor: text !important ; } </style> <body> <!-- Links to header images--> <div> <a href="http://www.northeastern.edu/"><img class="img-responsive" src="../static/university.jpg" width="400" height="49"></a> <img class="img-responsive" src="../static/Lab-banner.jpg" width="960" height="46"> </div> <!-- Nav-bar --> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li><a href="http://www.northeastern.edu/helmuthlab/index.html"><span class="glyphicon glyphicon-home"> </span> <strong>Back to Helmuth lab Home</strong></a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li role="presentation"><a href="query"><strong>Query</strong></a></li> {% if not session.logged_in %} <li><a href="{{ url_for('login_page.login') }}"><span class="glyphicon glyphicon-log-in"></span> <strong>Log in</strong></a> </li> {% else %} <li><a href="{{ url_for('login_page.logout') }}"><span class="glyphicon glyphicon-log-out"></span> <strong>Log out</strong></a> </li> {% endif %} </ul> </div> </div> </nav> <div class="container text-danger"> <h1>Upload Files</h1> </div> <div class= container> <h2>Upload new Logger Data</h2> <form action="/upload" method="post" enctype="multipart/form-data"> <div class= "input-group col-md-6"> <span class="input-group-btn"> <span class="btn btn-default btn-file"> Choose file to upload<input type="file" name="loggerTypeFile" value="loggerTypeFile"> </span> </span> <input type="text" class="form-control" readonly> </div> <br> <strong>Accepted file format is CSV<a href = "../static/sample_logger.csv"> See Example</a><strong> <br><br> <button type="submit" value="Upload" class="btn-default btn-lg">Upload <span class="glyphicon glyphicon-upload"></span></button> </form> <br><br> <h2>Upload new Logger Temperature</h2> <form method="post" enctype= "multipart/form-data" id="upload-form"> <div class= "input-group col-md-6 "> <span class="input-group-btn"> <span class="btn btn-default btn-file"> Choose file to upload<input type="file" name="loggerTempFile" value="loggerTempFile" multiple id="loggerTempFile"> </span> </span> <input type="text" class="form-control" readonly> </div> <br> <strong>Accepted file formats are CSV, TXT<a href = "../static/sample_temp.txt"> See Example</a><strong> <br><br> <button type="submit" value="Upload" class="btn-default btn-lg"> Upload <span class="glyphicon glyphicon-upload"></span></button> </form> <br> {% if error %} <p class="error"><h2 class= "container text-danger"><strong>Error:</strong> {{ error }}<h2></p> {% endif %} {% if result %} <div class="container" id="query-results-table" > <table class="table table-bordered" id="statistics-table"> <thead><h2>Upload Statistics </h2> <h3>(complete in {{ result.time_taken }} secs) </h3></thead> <tbody> <tr> <td># Total Records</td> <td>{{ result.total }}</td> </tr> <tr> <td># Proper Records</td> <td>{{ result.success }}</td> </tr> <tr> <td># Corrupt Records</td> <td>{{ result.failure }}</td> </tr> </tbody> </table> </div> {% endif %} </div> </body> </html> <script> $(document).on('change', '.btn-file :file', function() { var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1, label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); input.trigger('fileselect', [numFiles, label]); }); $(document).ready( function() { $('.btn-file :file').on('fileselect', function(event, numFiles, label) { var input = $(this).parents('.input-group').find(':text'), log = numFiles > 1 ? numFiles + ' files selected' : label; if( input.length ) { input.val(log); } else { if( log ) alert(log); } }); }); </script>
{ "content_hash": "a498faf38eeb617374b33e53a06504a6", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 185, "avg_line_length": 43.12883435582822, "alnum_prop": 0.48236130867709814, "repo_name": "DefendersOfNemo/SavingNemo", "id": "64968228ee6722a374545bb490f4db36436ee157", "size": "7030", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "client/templates/upload.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "776" }, { "name": "HTML", "bytes": "29793" }, { "name": "JavaScript", "bytes": "24889" }, { "name": "Makefile", "bytes": "1437" }, { "name": "Python", "bytes": "116802" } ], "symlink_target": "" }
define(["../compat"], function (compat) { function BaseSegmentation(imageData, options) { if (!(imageData instanceof ImageData)) throw "Invalid ImageData"; this.imageData = compat.createImageData(imageData.width, imageData.height); this.imageData.data.set(imageData.data); } BaseSegmentation.prototype.finer = function () {}; BaseSegmentation.prototype.coarser = function () {}; return BaseSegmentation; });
{ "content_hash": "44b9d84c4476d72acc55498df2d9bac5", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 79, "avg_line_length": 27.5, "alnum_prop": 0.7113636363636363, "repo_name": "kyamagu/js-segment-annotator", "id": "956485c3be653ee7552556d755c4a4efd9bd18f8", "size": "532", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "js/image/segmentation/base.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "3378" }, { "name": "HTML", "bytes": "216" }, { "name": "JavaScript", "bytes": "226928" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="/public/stylesheets/bs.css"> <link rel="stylesheet" href="/public/stylesheets/styles.css"> <link rel="stylesheet" href="/public/stylesheets/pygment_trac.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css"> <link rel="canonical" href="http://localhost:4000/posts/pyqt-calc"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <link rel="icon" type="image/x-icon" href="/favicon.ico" /> <title>pyqt calculator | ashishkg0022</title> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> </head> <body> <div class="wrapper"> <section> <div id="header"> <h1> <a id="git-ic" href="https://github.com/ashishkg0022"><i class="fa fa-github"></i></a> <a id="sitename" href="">Ashish Kumar Gaurav</a> </h1> <!-- Add something about you in p tag--> <p>Hi , I am ashish . i am currently in my first year . There are only a very few projects that I have undertaken till now, but I am highly interested in developing and contributing to the open-source world. Languages that I code in include Python, Java, and C++. I am a newbie in Android and Web Development. And i am almost always smiling</p> <hr/> <span class="credits left"> <a href="/home" style="font-size:160%;">Home</a> | <a href="/project" style="font-size:160%;">Project</a> | <a href="/skills" style="font-size:160%;">skills</a> | <a href="/about" style="font-size:160%;">About</a> | <a href="/contact" style="font-size:160%;">Contact</a> </span> </div> <div class="post-title"> <h1>pyqt calculator</h1> <p class="text-muted"> 31 Jan 2017 | <i class="fa fa-comment"></i> <a class="text-muted" href="/posts/pyqt-calc/#disqus_thread"></a> | <i class="fa fa-tag"></i> </p> </div> <p><a href="https://github.com/ashishkg0022/Calculator" target="_blank" class="btn btn-success"><i class="fa fa-github fa-lg"></i> View on GitHub</a></p> <div class="comments"> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'ashish'; /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a> </div> <hr/> <div class="post-navs row"> <div class="col-md-6 post-nav"> <h3 class="section-header"> Newer <span class="text-muted"> &middot; </span> <a href="/archive">View Archive (3)</a> </h3> <h2 class="post-title-link"><a href="/posts/number-sys">number-systems</a></h2> <p><a href="https://github.com/ashishkg0022/number-systems" target="_blank" class="btn btn-success"><i class="fa fa-github fa-lg"></i> View on GitHub</a></p> </div> </div> <footer> <hr/> <div class="left"> &copy;2017 ashishkg. </div> </div> </footer> </section> </div> </div> <script src="/public/javascripts/jquery.min.js"></script> <script src="/public/javascripts/bootstrap.min.js"></script> <!-- Place your <script> tags here. --> <!-- disqus comment counter --> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'ashish'; /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var s = document.createElement('script'); s.async = true; s.type = 'text/javascript'; s.src = '//' + disqus_shortname + '.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s); }()); </script> <!-- /disqus comment counter --> <!-- google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', ' ashish gaurav', 'auto'); ga('send', 'pageview'); </script> <!-- /google analytics --> </body> </html>
{ "content_hash": "efdc198d8bbd46c3d3af864ff4265cd2", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 346, "avg_line_length": 31.936781609195403, "alnum_prop": 0.5987043368724132, "repo_name": "ashishkg0022/ashishkg0022.github.io", "id": "3f7ee444d31d1bfb9613b5a2f3779386dfd00e5b", "size": "5557", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_site/posts/pyqt-calc.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "155356" }, { "name": "HTML", "bytes": "57210" } ], "symlink_target": "" }
package com.github.sworisbreathing.sfmf4j.api; import java.io.File; /** * Interface for callbacks invoked when a directory's contents have changed. * Developers are encouraged to extend {@link DirectoryListenerAdapter} if they * only need to implement a subset of this interface's callbacks. * * @author Steven Swor */ public interface DirectoryListener { /** * Callback invoked when a new file is detected. * @param created the new file */ void fileCreated(File created); /** * Callback invoked when a change to a file is detected. * @param changed the file which was changed */ void fileChanged(File changed); /** * Callback invoked when a file in a directory is no longer detected. * @param deleted the file which was deleted */ void fileDeleted(File deleted); }
{ "content_hash": "6310016b42a7e2363cb1a5598ec80c14", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 79, "avg_line_length": 26.09090909090909, "alnum_prop": 0.6782810685249709, "repo_name": "sworisbreathing/sfmf4j", "id": "5d2614e9db9406d47680fd21ebcf6515051f8bf6", "size": "1462", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sfmf4j-api/src/main/java/com/github/sworisbreathing/sfmf4j/api/DirectoryListener.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1113" }, { "name": "Java", "bytes": "140083" } ], "symlink_target": "" }
""" SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python and does not require any external libraries, except optionally for plotting support. See the webpage for more information and documentation: http://code.google.com/p/sympy/""" from __future__ import absolute_import, print_function __version__ = "0.7.3" import sys if sys.version_info[0] == 2 and sys.version_info[1] < 6: raise ImportError("Python Version 2.6 or above is required for SymPy.") else: # Python 3 pass # Here we can also check for specific Python 3 versions, if needed del sys def __sympy_debug(): # helper function so we don't import os globally import os return eval(os.getenv('SYMPY_DEBUG', 'False')) SYMPY_DEBUG = __sympy_debug() from .core import * from .logic import * from .assumptions import * from .polys import * from .series import * from .functions import * from .ntheory import * from .concrete import * from .simplify import * from .sets import * from .solvers import * from .matrices import * from .geometry import * from .utilities import * from .integrals import * from .tensor import * from .parsing import * # Adds about .04-.05 seconds of import time # from combinatorics import * # This module is slow to import: #from physics import units from .plotting import plot, Plot, textplot, plot_backends, plot_implicit from .printing import pretty, pretty_print, pprint, pprint_use_unicode, \ pprint_try_use_unicode, print_gtk, print_tree, pager_print, TableForm from .printing import ccode, fcode, jscode, latex, preview from .printing import python, print_python, srepr, sstr, sstrrepr from .interactive import init_session, init_printing evalf._create_evalf_table() # This is slow to import: #import abc
{ "content_hash": "4a0776defa533d53f256825ce9c90d97", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 75, "avg_line_length": 30.682539682539684, "alnum_prop": 0.743921365752716, "repo_name": "kmacinnis/sympy", "id": "b81cea2b36ad0ec3e43c67181f9b92d8ebd1257d", "size": "1933", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sympy/__init__.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "13573973" }, { "name": "Ruby", "bytes": "304" }, { "name": "Scheme", "bytes": "125" }, { "name": "Shell", "bytes": "1284" }, { "name": "TeX", "bytes": "8790" }, { "name": "XSLT", "bytes": "366202" } ], "symlink_target": "" }
package org.mybatis.generator.api.dom.java; import static org.mybatis.generator.api.dom.OutputUtilities.calculateImports; import static org.mybatis.generator.api.dom.OutputUtilities.javaIndent; import static org.mybatis.generator.api.dom.OutputUtilities.newLine; import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * @author Jeff Butler */ public class Interface extends JavaElement implements CompilationUnit { private Set<FullyQualifiedJavaType> importedTypes; private Set<String> staticImports; private FullyQualifiedJavaType type; private Set<FullyQualifiedJavaType> superInterfaceTypes; private List<Method> methods; private List<String> fileCommentLines; /** * */ public Interface(FullyQualifiedJavaType type) { super(); this.type = type; superInterfaceTypes = new LinkedHashSet<FullyQualifiedJavaType>(); methods = new ArrayList<Method>(); importedTypes = new TreeSet<FullyQualifiedJavaType>(); fileCommentLines = new ArrayList<String>(); staticImports = new TreeSet<String>(); } public Interface(String type) { this(new FullyQualifiedJavaType(type)); } public Set<FullyQualifiedJavaType> getImportedTypes() { return Collections.unmodifiableSet(importedTypes); } public void addImportedType(FullyQualifiedJavaType importedType) { if (importedType.isExplicitlyImported() && !importedType.getPackageName().equals(type.getPackageName())) { importedTypes.add(importedType); } } public String getFormattedContent() { StringBuilder sb = new StringBuilder(); for (String commentLine : fileCommentLines) { sb.append(commentLine); newLine(sb); } if (stringHasValue(getType().getPackageName())) { sb.append("package "); //$NON-NLS-1$ sb.append(getType().getPackageName()); sb.append(';'); newLine(sb); newLine(sb); } for (String staticImport : staticImports) { sb.append("import static "); //$NON-NLS-1$ sb.append(staticImport); sb.append(';'); newLine(sb); } if (staticImports.size() > 0) { newLine(sb); } Set<String> importStrings = calculateImports(importedTypes); for (String importString : importStrings) { sb.append(importString); newLine(sb); } if (importStrings.size() > 0) { newLine(sb); } int indentLevel = 0; addFormattedJavadoc(sb, indentLevel); addFormattedAnnotations(sb, indentLevel); sb.append(getVisibility().getValue()); if (isStatic()) { sb.append("static "); //$NON-NLS-1$ } if (isFinal()) { sb.append("final "); //$NON-NLS-1$ } sb.append("interface "); //$NON-NLS-1$ sb.append(getType().getShortName()); if (getSuperInterfaceTypes().size() > 0) { sb.append(" extends "); //$NON-NLS-1$ boolean comma = false; for (FullyQualifiedJavaType fqjt : getSuperInterfaceTypes()) { if (comma) { sb.append(", "); //$NON-NLS-1$ } else { comma = true; } sb.append(fqjt.getShortName()); } } sb.append(" {"); //$NON-NLS-1$ indentLevel++; Iterator<Method> mtdIter = getMethods().iterator(); while (mtdIter.hasNext()) { newLine(sb); Method method = mtdIter.next(); sb.append(method.getFormattedContent(indentLevel, true)); if (mtdIter.hasNext()) { newLine(sb); } } indentLevel--; newLine(sb); javaIndent(sb, indentLevel); sb.append('}'); return sb.toString(); } public void addSuperInterface(FullyQualifiedJavaType superInterface) { superInterfaceTypes.add(superInterface); } /** * @return Returns the methods. */ public List<Method> getMethods() { return methods; } public void addMethod(Method method) { methods.add(method); } /** * @return Returns the type. */ public FullyQualifiedJavaType getType() { return type; } public FullyQualifiedJavaType getSuperClass() { // interfaces do not have superclasses return null; } public Set<FullyQualifiedJavaType> getSuperInterfaceTypes() { return superInterfaceTypes; } public boolean isJavaInterface() { return true; } public boolean isJavaEnumeration() { return false; } public void addFileCommentLine(String commentLine) { fileCommentLines.add(commentLine); } public List<String> getFileCommentLines() { return fileCommentLines; } public void addImportedTypes(Set<FullyQualifiedJavaType> importedTypes) { this.importedTypes.addAll(importedTypes); } public Set<String> getStaticImports() { return staticImports; } public void addStaticImport(String staticImport) { staticImports.add(staticImport); } public void addStaticImports(Set<String> staticImports) { this.staticImports.addAll(staticImports); } }
{ "content_hash": "213c885c615686e35fbce7108e14cda1", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 82, "avg_line_length": 27.710280373831775, "alnum_prop": 0.5779089376053963, "repo_name": "ivaneye/pig-template", "id": "85a9c2d7f101729428dd7dafd62c7ce13d42ad5c", "size": "6567", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mybatis-generator-plugins/src/main/java/org/mybatis/generator/api/dom/java/Interface.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2530" }, { "name": "Java", "bytes": "1612251" }, { "name": "JavaScript", "bytes": "484" } ], "symlink_target": "" }
package conf import ( "io/ioutil" "log" "os" "github.com/mitchellh/go-homedir" "gopkg.in/yaml.v2" ) // Configuration is the struct representing a configuration. type Configuration struct { Service string `yaml:"service"` Token string `yaml:"token"` } // C is the exported global configuration variable var C Configuration // Load loads the given fp (file path) to the C global configuration variable. func Load() error { var err error var hd string var conf []byte if hd, err = homedir.Dir(); err != nil { return err } cdir := hd + "/.config/" cf := cdir + "goploader.conf.yml" if _, err = os.Stat(cdir); os.IsNotExist(err) { log.Printf("Creating %v directory.\n", cdir) os.Mkdir(cdir, 0700) } else if err != nil { return err } if _, err = os.Stat(cf); os.IsNotExist(err) { log.Printf("Configuration file %v not found. Writing default configuration.\n", cf) C.Service = "https://gpldr.in/" if conf, err = yaml.Marshal(C); err != nil { return err } return ioutil.WriteFile(cf, conf, 0644) } else if err != nil { return err } if conf, err = ioutil.ReadFile(cf); err != nil { return err } return yaml.Unmarshal(conf, &C) }
{ "content_hash": "73d4b7a6334906e00d3cf29c6d4d3fe3", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 85, "avg_line_length": 21.071428571428573, "alnum_prop": 0.6610169491525424, "repo_name": "Depado/goploader", "id": "53f65dc11d2939603945ab7771e057484c072511", "size": "1180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/conf/conf.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8320" }, { "name": "Dockerfile", "bytes": "633" }, { "name": "Go", "bytes": "50347" }, { "name": "HTML", "bytes": "45278" }, { "name": "JavaScript", "bytes": "189747" }, { "name": "Makefile", "bytes": "2340" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>coalgebras: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.12.1 / coalgebras - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> coalgebras <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-28 18:49:07 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-28 18:49:07 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.12.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/coalgebras&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Coalgebras&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: coalgebra&quot; &quot;keyword: bisimulation&quot; &quot;keyword: weakly final&quot; &quot;keyword: coiteration&quot; &quot;keyword: co-inductive types&quot; &quot;category: Mathematics/Category Theory&quot; &quot;date: 2008-10&quot; ] authors: [ &quot;Milad Niqui &lt;M.Niqui@cwi.nl&gt; [http://www.cwi.nl/~milad]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/coalgebras/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/coalgebras.git&quot; synopsis: &quot;Coalgebras, bisimulation and lambda-coiteration&quot; description: &quot;&quot;&quot; This contribution contains a formalisation of coalgebras, bisimulation on coalgebras, weakly final coalgebras, lambda-coiteration definition scheme (including primitive corecursion) and a version of lambda-bisimulation. The formalisation is modular. The implementation of the module types for streams and potentially infinite Peano numbers are provided using the coinductive types.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/coalgebras/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=6e0e5646c3de55b4a707bf05d5622736&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-coalgebras.8.9.0 coq.8.12.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.12.1). The following dependencies couldn&#39;t be met: - coq-coalgebras -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-coalgebras.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "2fcbc2c35ac39a3a1ed4626df35477cb", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 399, "avg_line_length": 41.95375722543353, "alnum_prop": 0.5578671810416093, "repo_name": "coq-bench/coq-bench.github.io", "id": "4f76610696eab66f5cd9196ee1d554e935798752", "size": "7283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.12.1/coalgebras/8.9.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
SELECT DISTINCT SOURCE_CODE collate Latin1_General_CS_AS, TARGET_CONCEPT_ID FROM SOURCE_TO_CONCEPT_MAP WHERE SOURCE_VOCABULARY_ID IN (11, 900) AND TARGET_VOCABULARY_ID = 11 AND PRIMARY_MAP = 'Y' AND (INVALID_REASON IS NULL or INVALID_REASON = '') AND GETDATE() BETWEEN VALID_START_DATE AND VALID_END_DATE
{ "content_hash": "d0184df1e71c1b90dda4c9ebbd218cb4", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 76, "avg_line_length": 46, "alnum_prop": 0.7298136645962733, "repo_name": "OHDSI/ETL-CDMBuilder", "id": "1bd6bf6adb477529ce89eb4a7030b855826d5180", "size": "324", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CDMv4/source/Builders/org.ohdsi.cdm.builders.truven/Truven/Lookups/Lab_Units.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "2469354" }, { "name": "Dockerfile", "bytes": "2077" }, { "name": "Perl", "bytes": "11421" }, { "name": "TSQL", "bytes": "140218" } ], "symlink_target": "" }
@NonNullInternalApi package org.gradle.internal.fingerprint.impl; import org.gradle.internal.NonNullInternalApi;
{ "content_hash": "da658a1022cb097b29e10f78f824f7d8", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 46, "avg_line_length": 19.333333333333332, "alnum_prop": 0.8448275862068966, "repo_name": "robinverduijn/gradle", "id": "149e7aa0759588699b6a18f509fd2e5baec8c900", "size": "731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "subprojects/snapshots/src/main/java/org/gradle/internal/fingerprint/impl/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "277" }, { "name": "Brainfuck", "bytes": "54" }, { "name": "C", "bytes": "98580" }, { "name": "C++", "bytes": "1805886" }, { "name": "CSS", "bytes": "188237" }, { "name": "CoffeeScript", "bytes": "620" }, { "name": "GAP", "bytes": "424" }, { "name": "Gherkin", "bytes": "191" }, { "name": "Groovy", "bytes": "25537093" }, { "name": "HTML", "bytes": "77104" }, { "name": "Java", "bytes": "24906063" }, { "name": "JavaScript", "bytes": "209481" }, { "name": "Kotlin", "bytes": "2846791" }, { "name": "Objective-C", "bytes": "840" }, { "name": "Objective-C++", "bytes": "441" }, { "name": "Perl", "bytes": "37849" }, { "name": "Python", "bytes": "57" }, { "name": "Ruby", "bytes": "16" }, { "name": "Scala", "bytes": "29814" }, { "name": "Shell", "bytes": "7212" }, { "name": "Swift", "bytes": "6972" }, { "name": "XSLT", "bytes": "42845" } ], "symlink_target": "" }
package com.compositesw.services.system.admin.resource; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for foreignKeyList complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="foreignKeyList"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="foreignKey" type="{http://www.compositesw.com/services/system/admin/resource}foreignKey" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "foreignKeyList", propOrder = { "foreignKey" }) public class ForeignKeyList { protected List<ForeignKey> foreignKey; /** * Gets the value of the foreignKey property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the foreignKey property. * * <p> * For example, to add a new item, do as follows: * <pre> * getForeignKey().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ForeignKey } * * */ public List<ForeignKey> getForeignKey() { if (foreignKey == null) { foreignKey = new ArrayList<ForeignKey>(); } return this.foreignKey; } }
{ "content_hash": "946e347141a0c0fcfd43bcbcf7ff432f", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 155, "avg_line_length": 28.761194029850746, "alnum_prop": 0.621691748832382, "repo_name": "cisco/PDTool", "id": "73a55e906a3625e52b553fca4ed474e6041ebcb7", "size": "1927", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CISAdminApi7.0.5/src/com/compositesw/services/system/admin/resource/ForeignKeyList.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "961455" }, { "name": "HTML", "bytes": "844541" }, { "name": "Java", "bytes": "7869304" }, { "name": "Perl", "bytes": "9840" }, { "name": "Python", "bytes": "3299" }, { "name": "Shell", "bytes": "113115" }, { "name": "XSLT", "bytes": "242648" } ], "symlink_target": "" }
from ..parsers import RegisterParser def test_parse_register_proper_data(Request): parser = RegisterParser() test_data = { 'email': 'test_email', 'password': 'test_password', } data = parser.parse_args(req=Request(test_data)) assert data == test_data def test_parse_register_missing_email(parser_failer): parser_failer(RegisterParser(), {'password': 'test_password'}, expected_errors={'email': 'Email is required'}) def test_parse_register_missing_password(parser_failer): parser_failer(RegisterParser(), {'email': 'test_email'}, expected_errors={'password': 'Password is required'})
{ "content_hash": "2b8de38e0c39a342851d6ab3df68058a", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 71, "avg_line_length": 29.217391304347824, "alnum_prop": 0.6488095238095238, "repo_name": "kszarlej/libkeep", "id": "44e2e856ce528f54a14c3afdffb07d806c0f1a70", "size": "672", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/project/user/tests/test_parsers.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "909" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "6ba4a00b03c09e130396ddf453d57997", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "a431a52be1613349771d170d64d230a75f69ea35", "size": "166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Calorhabdos/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!doctype html> <html class="no-js" lang="{% if site.language == nil %}en{% else %}{{ site.language }}{% endif %}"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% if page.meta_title %}{{ page.meta_title }}{% elsif page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title> <link rel="stylesheet" href="{{ site.url }}{{ site.baseurl }}/assets/css/styles_feeling_responsive.css"> <script src="{{ site.url }}{{ site.baseurl }}/assets/js/modernizr.min.js"></script> <script> WebFontConfig = { google: { families: [ 'Lato:400,700,400italic:latin', 'Volkhov::latin' ] } }; (function() { var wf = document.createElement('script'); wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1.5.6/webfont.js'; wf.type = 'text/javascript'; wf.async = 'true'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wf, s); })(); </script> <noscript> <link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic%7cVolkhov' rel='stylesheet' type='text/css'> </noscript> {% if site.google_site_verification %}<meta name="google-site-verification" content="{{ site.google_site_verification}}" />{% endif %} {% if site.bing_webmastertools_id %}<meta name="msvalidate.01" content="{{ site.bing_webmastertools_id }}" />{% endif %} {% if page.meta_description %}<meta name="description" content="{{ page.meta_description | strip_html | escape }}"/>{% elsif page.teaser %}<meta name="description" content="{{ page.teaser | strip_html | escape }}"/>{% elsif site.description %}<meta name="description" content="{{ site.description | strip_html | escape }}"/>{% endif %} {% if site.google_author %}<link rel="author" href="{{ site.google_author }}"/>{% endif %} {% include favicon %} <!-- Facebook Optimization --> <meta property="og:locale" content="{% if site.og_locale == nil %}en_EN{% else %}{{ site.og_locale }}{% endif %}" /> {% if site.og_type %}<meta property="og:type" content="website" />{% endif %} <meta property="og:title" content="{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}" /> {% if page.meta_description %}<meta property="og:description" content="{{ page.meta_description | strip_html | escape }}"/>{% elsif page.description %}<meta property="og:description" content="{{ page.description | strip_html | escape }}"/>{% elsif site.description %}<meta property="og:description" content="{{ site.description | strip_html | escape }}"/>{% endif %} <meta property="og:url" content="{{ site.url }}{{ site.baseurl }}/{{ page.url }}" /> {% if site.title %}<meta property="og:site_name" content="{{ site.title }}" />{% endif %} {% if page.image.thumb %}<meta property="og:image" content="{{ site.urlimg }}/{{ page.image.thumb }}" />{% endif %} {% if site.alexa_verify_id %}<meta name="alexaVerifyID" content="{{ site.alexa_verify_id }}" />{% endif %} <!-- Search Engine Optimization --> {% if page.noindex == true %}<meta name="robots" content="noindex">{% endif %} <link type="text/plain" rel="author" href="{{ site.url }}{{ site.baseurl }}//humans.txt" /> {% unless page.style == NULL %} <style type="text/css">{{ page.style }}</style> {% endunless %} </head>
{ "content_hash": "4bd211fd6b99f539642d1db7c21d8a26", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 367, "avg_line_length": 59.21052631578947, "alnum_prop": 0.6290370370370371, "repo_name": "cstac/cstac.github.io", "id": "c55a169e0183292c21e8d664bbfc6aff52423211", "size": "3375", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "_includes/head.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "363644" }, { "name": "HTML", "bytes": "147726" }, { "name": "JavaScript", "bytes": "250333" } ], "symlink_target": "" }
/* Layout helpers ----------------------------------*/ .ui-helper-hidden { display: none; } .ui-helper-hidden-accessible { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } .ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; border-collapse: collapse; } .ui-helper-clearfix:after { clear: both; } .ui-helper-clearfix { min-height: 0; /* support: IE7 */ } .ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } .ui-front { z-index: 100; } /* Interaction Cues ----------------------------------*/ .ui-state-disabled { cursor: default !important; } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } /* Misc visuals ----------------------------------*/ /* Overlays */ .ui-widget-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; } .ui-resizable { position: relative; } .ui-resizable-handle { position: absolute; font-size: 0.1px; display: block; } .ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } .ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } .ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } .ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } .ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } .ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } .ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } .ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } .ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px; } .ui-selectable-helper { position: absolute; z-index: 100; border: 1px dotted black; } .ui-accordion .ui-accordion-header { display: block; cursor: pointer; position: relative; margin-top: 2px; padding: .5em .5em .5em .7em; min-height: 0; /* support: IE7 */ } .ui-accordion .ui-accordion-icons { padding-left: 2.2em; } .ui-accordion .ui-accordion-noicons { padding-left: .7em; } .ui-accordion .ui-accordion-icons .ui-accordion-icons { padding-left: 2.2em; } .ui-accordion .ui-accordion-header .ui-accordion-header-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: auto; } .ui-autocomplete { position: absolute; top: 0; left: 0; cursor: default; } .ui-button { display: inline-block; position: relative; padding: 0; line-height: normal; margin-right: .1em; cursor: pointer; vertical-align: middle; text-align: center; overflow: visible; /* removes extra width in IE */ } .ui-button, .ui-button:link, .ui-button:visited, .ui-button:hover, .ui-button:active { text-decoration: none; } /* to make room for the icon, a width needs to be set here */ .ui-button-icon-only { width: 2.2em; } /* button elements seem to need a little more width */ button.ui-button-icon-only { width: 2.4em; } .ui-button-icons-only { width: 3.4em; } button.ui-button-icons-only { width: 3.7em; } /* button text element */ .ui-button .ui-button-text { display: block; line-height: normal; } .ui-button-text-only .ui-button-text { padding: .4em 1em; } .ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } .ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } .ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } .ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } /* no icon support for input elements, provide padding by default */ input.ui-button { padding: .4em 1em; } /* button icon element(s) */ .ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } .ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } .ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } .ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } /* button sets */ .ui-buttonset { margin-right: 7px; } .ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } /* workarounds */ /* reset extra padding in Firefox, see h5bp.com/l */ input.ui-button::-moz-focus-inner, button.ui-button::-moz-focus-inner { border: 0; padding: 0; } .ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } .ui-datepicker .ui-datepicker-header { position: relative; padding: .2em 0; } .ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position: absolute; top: 2px; width: 1.8em; height: 1.8em; } .ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } .ui-datepicker .ui-datepicker-prev { left: 2px; } .ui-datepicker .ui-datepicker-next { right: 2px; } .ui-datepicker .ui-datepicker-prev-hover { left: 1px; } .ui-datepicker .ui-datepicker-next-hover { right: 1px; } .ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } .ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } .ui-datepicker .ui-datepicker-title select { font-size: 1em; margin: 1px 0; } .ui-datepicker select.ui-datepicker-month-year { width: 100%; } .ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year { width: 49%; } .ui-datepicker table { width: 100%; font-size: .9em; border-collapse: collapse; margin: 0 0 .4em; } .ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } .ui-datepicker td { border: 0; padding: 1px; } .ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } .ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding: 0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } .ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width: auto; overflow: visible; } .ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float: left; } /* with multiple calendars */ .ui-datepicker.ui-datepicker-multi { width: auto; } .ui-datepicker-multi .ui-datepicker-group { float: left; } .ui-datepicker-multi .ui-datepicker-group table { width: 95%; margin: 0 auto .4em; } .ui-datepicker-multi-2 .ui-datepicker-group { width: 50%; } .ui-datepicker-multi-3 .ui-datepicker-group { width: 33.3%; } .ui-datepicker-multi-4 .ui-datepicker-group { width: 25%; } .ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header, .ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width: 0; } .ui-datepicker-multi .ui-datepicker-buttonpane { clear: left; } .ui-datepicker-row-break { clear: both; width: 100%; font-size: 0; } /* RTL support */ .ui-datepicker-rtl { direction: rtl; } .ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } .ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } .ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } .ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } .ui-datepicker-rtl .ui-datepicker-buttonpane { clear: right; } .ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } .ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current, .ui-datepicker-rtl .ui-datepicker-group { float: right; } .ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header, .ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width: 0; border-left-width: 1px; } .ui-dialog { position: absolute; top: 0; left: 0; padding: .2em; outline: 0; } .ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } .ui-dialog .ui-dialog-title { float: left; margin: .1em 0; white-space: nowrap; width: 90%; overflow: hidden; text-overflow: ellipsis; } .ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 21px; margin: -10px 0 0 0; padding: 1px; height: 20px; } .ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; } .ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin-top: .5em; padding: .3em 1em .5em .4em; } .ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } .ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } .ui-dialog .ui-resizable-se { width: 12px; height: 12px; right: -5px; bottom: -5px; background-position: 16px 16px; } .ui-draggable .ui-dialog-titlebar { cursor: move; } .ui-menu { list-style: none; padding: 2px; margin: 0; display: block; outline: none; } .ui-menu .ui-menu { margin-top: -3px; position: absolute; } .ui-menu .ui-menu-item { margin: 0; padding: 0; width: 100%; } .ui-menu .ui-menu-divider { margin: 5px -2px 5px -2px; height: 0; font-size: 0; line-height: 0; border-width: 1px 0 0 0; } .ui-menu .ui-menu-item a { text-decoration: none; display: block; padding: 2px .4em; line-height: 1.5; min-height: 0; /* support: IE7 */ font-weight: normal; } .ui-menu .ui-menu-item a.ui-state-focus, .ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; } .ui-menu .ui-state-disabled { font-weight: normal; margin: .4em 0 .2em; line-height: 1.5; } .ui-menu .ui-state-disabled a { cursor: default; } /* icon support */ .ui-menu-icons { position: relative; } .ui-menu-icons .ui-menu-item a { position: relative; padding-left: 2em; } /* left-aligned */ .ui-menu .ui-icon { position: absolute; top: .2em; left: .2em; } /* right-aligned */ .ui-menu .ui-menu-icon { position: static; float: right; } .ui-progressbar { height: 2em; text-align: left; overflow: hidden; } .ui-progressbar .ui-progressbar-value { margin: -1px; height: 100%; } .ui-progressbar .ui-progressbar-overlay { background: url("images/animated-overlay.gif"); height: 100%; filter: alpha(opacity=25); opacity: 0.25; } .ui-progressbar-indeterminate .ui-progressbar-value { background-image: none; } .ui-slider { position: relative; text-align: left; } .ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; } .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } /* For IE8 - See #6727 */ .ui-slider.ui-state-disabled .ui-slider-handle, .ui-slider.ui-state-disabled .ui-slider-range { filter: inherit; } .ui-slider-horizontal { height: .8em; } .ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } .ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } .ui-slider-horizontal .ui-slider-range-min { left: 0; } .ui-slider-horizontal .ui-slider-range-max { right: 0; } .ui-slider-vertical { width: .8em; height: 100px; } .ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } .ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } .ui-slider-vertical .ui-slider-range-min { bottom: 0; } .ui-slider-vertical .ui-slider-range-max { top: 0; } .ui-spinner { position: relative; display: inline-block; overflow: hidden; padding: 0; vertical-align: middle; } .ui-spinner-input { border: none; background: none; color: inherit; padding: 0; margin: .2em 0; vertical-align: middle; margin-left: .4em; margin-right: 22px; } .ui-spinner-button { width: 16px; height: 50%; font-size: .5em; padding: 0; margin: 0; text-align: center; position: absolute; cursor: default; display: block; overflow: hidden; right: 0; } /* more specificity required here to overide default borders */ .ui-spinner a.ui-spinner-button { border-top: none; border-bottom: none; border-right: none; } /* vertical centre icon */ .ui-spinner .ui-icon { position: absolute; margin-top: -8px; top: 50%; left: 0; } .ui-spinner-up { top: 0; } .ui-spinner-down { bottom: 0; } /* TR overrides */ .ui-spinner .ui-icon-triangle-1-s { /* need to fix icons sprite */ background-position: -65px -16px; } .ui-tabs { position: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ padding: .2em; } .ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } .ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 0; margin: 1px .2em 0 0; border-bottom-width: 0; padding: 0; white-space: nowrap; } .ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } .ui-tabs .ui-tabs-nav li.ui-tabs-active { margin-bottom: -1px; padding-bottom: 1px; } .ui-tabs .ui-tabs-nav li.ui-tabs-active a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-tabs-loading a { cursor: text; } .ui-tabs .ui-tabs-nav li a, /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ .ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a { cursor: pointer; } .ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } .ui-tooltip { padding: 8px; position: absolute; z-index: 9999; max-width: 300px; -webkit-box-shadow: 0 0 5px #aaa; box-shadow: 0 0 5px #aaa; } body .ui-tooltip { border-width: 2px; } /* Component containers ----------------------------------*/ .ui-widget { font-family: Trebuchet MS,Tahoma,Verdana,Arial,sans-serif; font-size: 1.1em; } .ui-widget .ui-widget { font-size: 1em; } .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Trebuchet MS,Tahoma,Verdana,Arial,sans-serif; font-size: 1em; } .ui-widget-content { border: 1px solid #dddddd; background: #eeeeee url(/assets/dev/ui-bg_highlight-soft_100_eeeeee_1x100.png) 50% top repeat-x; color: #333333; } .ui-widget-content a { color: #333333; } .ui-widget-header { border: 1px solid #e78f08; background: #f6a828 url(/assets/dev/ui-bg_gloss-wave_35_f6a828_500x100.png) 50% 50% repeat-x; color: #ffffff; font-weight: bold; } .ui-widget-header a { color: #ffffff; } /* Interaction states ----------------------------------*/ .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; background: #f6f6f6 url(/assets/dev/ui-bg_glass_100_f6f6f6_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #1c94c4; } .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #1c94c4; text-decoration: none; } .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #fbcb09; background: #fdf5ce url(/assets/dev/ui-bg_glass_100_fdf5ce_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #c77405; } .ui-state-hover a, .ui-state-hover a:hover, .ui-state-hover a:link, .ui-state-hover a:visited { color: #c77405; text-decoration: none; } .ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #fbd850; background: #ffffff url(/assets/dev/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #eb8f00; } .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #eb8f00; text-decoration: none; } /* Interaction Cues ----------------------------------*/ .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #fed22f; background: #ffe45c url(/assets/dev/ui-bg_highlight-soft_75_ffe45c_1x100.png) 50% top repeat-x; color: #363636; } .ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a { color: #363636; } .ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #cd0a0a; background: #b81900 url(/assets/dev/ui-bg_diagonals-thick_18_b81900_40x40.png) 50% 50% repeat; color: #ffffff; } .ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #ffffff; } .ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #ffffff; } .ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } .ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } .ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } .ui-state-disabled .ui-icon { filter:Alpha(Opacity=35); /* For IE8 - See #6059 */ } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { width: 16px; height: 16px; } .ui-icon, .ui-widget-content .ui-icon { background-image: url(/assets/dev/ui-icons_222222_256x240.png); } .ui-widget-header .ui-icon { background-image: url(/assets/dev/ui-icons_ffffff_256x240.png); } .ui-state-default .ui-icon { background-image: url(/assets/dev/ui-icons_ef8c08_256x240.png); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { background-image: url(/assets/dev/ui-icons_ef8c08_256x240.png); } .ui-state-active .ui-icon { background-image: url(/assets/dev/ui-icons_ef8c08_256x240.png); } .ui-state-highlight .ui-icon { background-image: url(/assets/dev/ui-icons_228ef1_256x240.png); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { background-image: url(/assets/dev/ui-icons_ffd27a_256x240.png); } /* positioning */ .ui-icon-blank { background-position: 16px 16px; } .ui-icon-carat-1-n { background-position: 0 0; } .ui-icon-carat-1-ne { background-position: -16px 0; } .ui-icon-carat-1-e { background-position: -32px 0; } .ui-icon-carat-1-se { background-position: -48px 0; } .ui-icon-carat-1-s { background-position: -64px 0; } .ui-icon-carat-1-sw { background-position: -80px 0; } .ui-icon-carat-1-w { background-position: -96px 0; } .ui-icon-carat-1-nw { background-position: -112px 0; } .ui-icon-carat-2-n-s { background-position: -128px 0; } .ui-icon-carat-2-e-w { background-position: -144px 0; } .ui-icon-triangle-1-n { background-position: 0 -16px; } .ui-icon-triangle-1-ne { background-position: -16px -16px; } .ui-icon-triangle-1-e { background-position: -32px -16px; } .ui-icon-triangle-1-se { background-position: -48px -16px; } .ui-icon-triangle-1-s { background-position: -64px -16px; } .ui-icon-triangle-1-sw { background-position: -80px -16px; } .ui-icon-triangle-1-w { background-position: -96px -16px; } .ui-icon-triangle-1-nw { background-position: -112px -16px; } .ui-icon-triangle-2-n-s { background-position: -128px -16px; } .ui-icon-triangle-2-e-w { background-position: -144px -16px; } .ui-icon-arrow-1-n { background-position: 0 -32px; } .ui-icon-arrow-1-ne { background-position: -16px -32px; } .ui-icon-arrow-1-e { background-position: -32px -32px; } .ui-icon-arrow-1-se { background-position: -48px -32px; } .ui-icon-arrow-1-s { background-position: -64px -32px; } .ui-icon-arrow-1-sw { background-position: -80px -32px; } .ui-icon-arrow-1-w { background-position: -96px -32px; } .ui-icon-arrow-1-nw { background-position: -112px -32px; } .ui-icon-arrow-2-n-s { background-position: -128px -32px; } .ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } .ui-icon-arrow-2-e-w { background-position: -160px -32px; } .ui-icon-arrow-2-se-nw { background-position: -176px -32px; } .ui-icon-arrowstop-1-n { background-position: -192px -32px; } .ui-icon-arrowstop-1-e { background-position: -208px -32px; } .ui-icon-arrowstop-1-s { background-position: -224px -32px; } .ui-icon-arrowstop-1-w { background-position: -240px -32px; } .ui-icon-arrowthick-1-n { background-position: 0 -48px; } .ui-icon-arrowthick-1-ne { background-position: -16px -48px; } .ui-icon-arrowthick-1-e { background-position: -32px -48px; } .ui-icon-arrowthick-1-se { background-position: -48px -48px; } .ui-icon-arrowthick-1-s { background-position: -64px -48px; } .ui-icon-arrowthick-1-sw { background-position: -80px -48px; } .ui-icon-arrowthick-1-w { background-position: -96px -48px; } .ui-icon-arrowthick-1-nw { background-position: -112px -48px; } .ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } .ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } .ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } .ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } .ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } .ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } .ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } .ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } .ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } .ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } .ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } .ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } .ui-icon-arrowreturn-1-w { background-position: -64px -64px; } .ui-icon-arrowreturn-1-n { background-position: -80px -64px; } .ui-icon-arrowreturn-1-e { background-position: -96px -64px; } .ui-icon-arrowreturn-1-s { background-position: -112px -64px; } .ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } .ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } .ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } .ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } .ui-icon-arrow-4 { background-position: 0 -80px; } .ui-icon-arrow-4-diag { background-position: -16px -80px; } .ui-icon-extlink { background-position: -32px -80px; } .ui-icon-newwin { background-position: -48px -80px; } .ui-icon-refresh { background-position: -64px -80px; } .ui-icon-shuffle { background-position: -80px -80px; } .ui-icon-transfer-e-w { background-position: -96px -80px; } .ui-icon-transferthick-e-w { background-position: -112px -80px; } .ui-icon-folder-collapsed { background-position: 0 -96px; } .ui-icon-folder-open { background-position: -16px -96px; } .ui-icon-document { background-position: -32px -96px; } .ui-icon-document-b { background-position: -48px -96px; } .ui-icon-note { background-position: -64px -96px; } .ui-icon-mail-closed { background-position: -80px -96px; } .ui-icon-mail-open { background-position: -96px -96px; } .ui-icon-suitcase { background-position: -112px -96px; } .ui-icon-comment { background-position: -128px -96px; } .ui-icon-person { background-position: -144px -96px; } .ui-icon-print { background-position: -160px -96px; } .ui-icon-trash { background-position: -176px -96px; } .ui-icon-locked { background-position: -192px -96px; } .ui-icon-unlocked { background-position: -208px -96px; } .ui-icon-bookmark { background-position: -224px -96px; } .ui-icon-tag { background-position: -240px -96px; } .ui-icon-home { background-position: 0 -112px; } .ui-icon-flag { background-position: -16px -112px; } .ui-icon-calendar { background-position: -32px -112px; } .ui-icon-cart { background-position: -48px -112px; } .ui-icon-pencil { background-position: -64px -112px; } .ui-icon-clock { background-position: -80px -112px; } .ui-icon-disk { background-position: -96px -112px; } .ui-icon-calculator { background-position: -112px -112px; } .ui-icon-zoomin { background-position: -128px -112px; } .ui-icon-zoomout { background-position: -144px -112px; } .ui-icon-search { background-position: -160px -112px; } .ui-icon-wrench { background-position: -176px -112px; } .ui-icon-gear { background-position: -192px -112px; } .ui-icon-heart { background-position: -208px -112px; } .ui-icon-star { background-position: -224px -112px; } .ui-icon-link { background-position: -240px -112px; } .ui-icon-cancel { background-position: 0 -128px; } .ui-icon-plus { background-position: -16px -128px; } .ui-icon-plusthick { background-position: -32px -128px; } .ui-icon-minus { background-position: -48px -128px; } .ui-icon-minusthick { background-position: -64px -128px; } .ui-icon-close { background-position: -80px -128px; } .ui-icon-closethick { background-position: -96px -128px; } .ui-icon-key { background-position: -112px -128px; } .ui-icon-lightbulb { background-position: -128px -128px; } .ui-icon-scissors { background-position: -144px -128px; } .ui-icon-clipboard { background-position: -160px -128px; } .ui-icon-copy { background-position: -176px -128px; } .ui-icon-contact { background-position: -192px -128px; } .ui-icon-image { background-position: -208px -128px; } .ui-icon-video { background-position: -224px -128px; } .ui-icon-script { background-position: -240px -128px; } .ui-icon-alert { background-position: 0 -144px; } .ui-icon-info { background-position: -16px -144px; } .ui-icon-notice { background-position: -32px -144px; } .ui-icon-help { background-position: -48px -144px; } .ui-icon-check { background-position: -64px -144px; } .ui-icon-bullet { background-position: -80px -144px; } .ui-icon-radio-on { background-position: -96px -144px; } .ui-icon-radio-off { background-position: -112px -144px; } .ui-icon-pin-w { background-position: -128px -144px; } .ui-icon-pin-s { background-position: -144px -144px; } .ui-icon-play { background-position: 0 -160px; } .ui-icon-pause { background-position: -16px -160px; } .ui-icon-seek-next { background-position: -32px -160px; } .ui-icon-seek-prev { background-position: -48px -160px; } .ui-icon-seek-end { background-position: -64px -160px; } .ui-icon-seek-start { background-position: -80px -160px; } /* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ .ui-icon-seek-first { background-position: -80px -160px; } .ui-icon-stop { background-position: -96px -160px; } .ui-icon-eject { background-position: -112px -160px; } .ui-icon-volume-off { background-position: -128px -160px; } .ui-icon-volume-on { background-position: -144px -160px; } .ui-icon-power { background-position: 0 -176px; } .ui-icon-signal-diag { background-position: -16px -176px; } .ui-icon-signal { background-position: -32px -176px; } .ui-icon-battery-0 { background-position: -48px -176px; } .ui-icon-battery-1 { background-position: -64px -176px; } .ui-icon-battery-2 { background-position: -80px -176px; } .ui-icon-battery-3 { background-position: -96px -176px; } .ui-icon-circle-plus { background-position: 0 -192px; } .ui-icon-circle-minus { background-position: -16px -192px; } .ui-icon-circle-close { background-position: -32px -192px; } .ui-icon-circle-triangle-e { background-position: -48px -192px; } .ui-icon-circle-triangle-s { background-position: -64px -192px; } .ui-icon-circle-triangle-w { background-position: -80px -192px; } .ui-icon-circle-triangle-n { background-position: -96px -192px; } .ui-icon-circle-arrow-e { background-position: -112px -192px; } .ui-icon-circle-arrow-s { background-position: -128px -192px; } .ui-icon-circle-arrow-w { background-position: -144px -192px; } .ui-icon-circle-arrow-n { background-position: -160px -192px; } .ui-icon-circle-zoomin { background-position: -176px -192px; } .ui-icon-circle-zoomout { background-position: -192px -192px; } .ui-icon-circle-check { background-position: -208px -192px; } .ui-icon-circlesmall-plus { background-position: 0 -208px; } .ui-icon-circlesmall-minus { background-position: -16px -208px; } .ui-icon-circlesmall-close { background-position: -32px -208px; } .ui-icon-squaresmall-plus { background-position: -48px -208px; } .ui-icon-squaresmall-minus { background-position: -64px -208px; } .ui-icon-squaresmall-close { background-position: -80px -208px; } .ui-icon-grip-dotted-vertical { background-position: 0 -224px; } .ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } .ui-icon-grip-solid-vertical { background-position: -32px -224px; } .ui-icon-grip-solid-horizontal { background-position: -48px -224px; } .ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } .ui-icon-grip-diagonal-se { background-position: -80px -224px; } /* Misc visuals ----------------------------------*/ /* Corner radius */ .ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { border-top-left-radius: 4px; } .ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { border-top-right-radius: 4px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { border-bottom-left-radius: 4px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { border-bottom-right-radius: 4px; } /* Overlays */ .ui-widget-overlay { background: #666666 url(/assets/dev/ui-bg_diagonals-thick_20_666666_40x40.png) 50% 50% repeat; opacity: .5; filter: Alpha(Opacity=50); } .ui-widget-shadow { margin: -5px 0 0 -5px; padding: 5px; background: #000000 url(/assets/dev/ui-bg_flat_10_000000_40x100.png) 50% 50% repeat-x; opacity: .2; filter: Alpha(Opacity=20); border-radius: 5px; }
{ "content_hash": "e5c53a3fbccaa997ae54c025bc4c0a0f", "timestamp": "", "source": "github", "line_count": 1171, "max_line_length": 165, "avg_line_length": 25.831767719897524, "alnum_prop": 0.6892789844292373, "repo_name": "sinisterchipmunk/jax", "id": "20321e42028a200165994dfd012a171261bc4994", "size": "32126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jax-engine/vendor/assets/stylesheets/dev/jquery-ui.css", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "133525" }, { "name": "CoffeeScript", "bytes": "696347" }, { "name": "JavaScript", "bytes": "179532" }, { "name": "Ruby", "bytes": "108930" } ], "symlink_target": "" }
<?php /** * Message translations. * * This file is automatically generated by 'yii message' command. * It contains the localizable messages extracted from source code. * You may modify this file by translating the extracted messages. * * Each array element represents the translation (value) of a message (key). * If the value is empty, the message is considered as not translated. * Messages that no longer need translation will have their translations * enclosed between a pair of '@@' marks. * * Message string can be used with plural forms format. Check i18n section * of the guide for details. * * NOTE: this file must be saved in UTF-8 encoding. */ return [ '{nFormatted} B' => '{nFormatted} B', '{nFormatted} GB' => '{nFormatted} Gb', '{nFormatted} GiB' => '{nFormatted} GiB', '{nFormatted} KB' => '{nFormatted} KB', '{nFormatted} KiB' => '{nFormatted} KiB', '{nFormatted} MB' => '{nFormatted} MB', '{nFormatted} MiB' => '{nFormatted} MiB', '{nFormatted} PB' => '{nFormatted} PB', '{nFormatted} PiB' => '{nFormatted} PiB', '{nFormatted} TB' => '{nFormatted} TB', '{nFormatted} TiB' => '{nFormatted} TiB', '{nFormatted} {n, plural, =1{byte} other{bytes}}' => '{nFormatted} {n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{gibibyte} other{gibibytes}}' => '{nFormatted} gibi{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{gigabyte} other{gigabytes}}' => '{nFormatted} giga{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}' => '{nFormatted} kibi{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{kilobyte} other{kilobytes}}' => '{nFormatted} kilo{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{mebibyte} other{mebibytes}}' => '{nFormatted} mebi{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{megabyte} other{megabytes}}' => '{nFormatted} mega{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}' => '{nFormatted} pebi{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} peta{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} tebi{n, plural, zero{baitu} one{baits} other{baiti}}', '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} tera{n, plural, zero{baitu} one{baits} other{baiti}}', '(not set)' => '(nav uzstādīts)', 'An internal server error occurred.' => 'Notika servera iekšēja kļūda.', 'Are you sure you want to delete this item?' => 'Vai jūs esat pārliecināti, ka vēlaties nodzēst šo elementu?', 'Delete' => 'Dzēst', 'Error' => 'Kļūda', 'File upload failed.' => 'Neizdevās augšupielādēt failu.', 'Home' => 'Galvenā', 'Invalid data received for parameter "{param}".' => 'Tika saņemta nepareiza vērtība parametram "{param}".', 'Login Required' => 'Nepieciešama autorizācija.', 'Missing required arguments: {params}' => 'Trūkst nepieciešamos argumentus: {params}', 'Missing required parameters: {params}' => 'Trūkst nepieciešamos parametrus: {params}', 'No' => 'Nē', 'No help for unknown command "{command}".' => 'Palīdzība nezināmai komandai "{command}" nav pieejama.', 'No help for unknown sub-command "{command}".' => 'Palīdzība nezināmai sub-komandai "{command}" nav pieejama', 'No results found.' => 'Nekas nav atrasts.', 'Only files with these MIME types are allowed: {mimeTypes}.' => 'Ir atļauts augšupielādēt failus tikai ar sekojošiem MIME-tipiem: {mimeTypes}.', 'Only files with these extensions are allowed: {extensions}.' => 'Ir atļauts augšupielādēt failus tikai ar sekojošiem paplašinājumiem: {extensions}.', 'Page not found.' => 'Pieprasīta lapa netika atrasta.', 'Please fix the following errors:' => 'Nepieciešams izlabot sekojošas kļūdas:', 'Please upload a file.' => 'Lūdzu, augšupielādiet failu.', 'Showing <b>{begin, number}-{end, number}</b> of <b>{totalCount, number}</b> {totalCount, plural, one{item} other{items}}.' => 'Tiek rādīti ieraksti <b>{begin, number}-{end, number}</b> no <b>{totalCount, number}</b>.', 'The file "{file}" is not an image.' => 'Fails „{file}” nav uzskatīts par attēlu.', 'The file "{file}" is too big. Its size cannot exceed {limit, number} {limit, plural, one{byte} other{bytes}}.' => 'Fails „{file}” pārsniedz pieļaujamo ierobežojumu. Izmēram nedrīkst pārsniegt {limit, number} {limit, plural, one{baitu} other{baitus}}.', 'The file "{file}" is too small. Its size cannot be smaller than {limit, number} {limit, plural, one{byte} other{bytes}}.' => 'Fails „{file}” ir pārāk mazs. Izmēram ir jābūt vairāk par {limit, number} {limit, plural, one{baitu} other{baitiem}}.', 'The format of {attribute} is invalid.' => 'Vērtībai „{attribute}” ir nepareizs formāts.', 'The image "{file}" is too large. The height cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'Attēls „{file}” ir pārāk liels. Augstumam ir jābūt mazākam par {limit, number} {limit, plural, one{pikseļi} other{pikseļiem}}.', 'The image "{file}" is too large. The width cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'Attēls „{file}” ir pārāk liels. Platumam ir jābūt mazākam par {limit, number} {limit, plural, one{pikseļi} other{pikseļiem}}.', 'The image "{file}" is too small. The height cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'Attēls „{file}” ir pārāk mazs. Augstumam ir jābūt lielākam par {limit, number} {limit, plural, one{pikseļi} other{pikseļiem}}.', 'The image "{file}" is too small. The width cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'Attēls „{file}” ir pārāk mazs. Platumam ir jābūt lielākam par {limit, number} {limit, plural, one{pikseļi} other{pikseļiem}}.', 'The requested view "{name}" was not found.' => 'Pieprasīts priekšstata fails „{name}” nav atrasts.', 'The verification code is incorrect.' => 'Nepareizs pārbaudes kods.', 'Total <b>{count, number}</b> {count, plural, one{item} other{items}}.' => 'Kopā <b>{count, number}</b> {count, plural, zero{ierakstu} one{ieraksts} other{ieraksti}}.', 'Unable to verify your data submission.' => 'Neizdevās pārbaudīt nosūtītos datus.', 'Unknown command "{command}".' => 'Nezināma komanda "{command}".', 'Unknown option: --{name}' => 'Nezināma opcija: --{name}', 'Update' => 'Labot', 'View' => 'Skatīties', 'Yes' => 'Jā', 'You are not allowed to perform this action.' => 'Jūs neesat autorizēts veikt šo darbību.', 'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.' => 'Jūs nevarat augšupielādēt vairāk par {limit, number} {limit, plural, one{failu} other{failiem}}.', 'in {delta, plural, =1{a day} other{# days}}' => 'pēc {delta, plural, =1{dienas} one{#. dienas} other{#. dienām}}', 'in {delta, plural, =1{a minute} other{# minutes}}' => 'pēc {delta, plural, =1{minūtes} one{#. minūtes} other{#. minūtēm}}', 'in {delta, plural, =1{a month} other{# months}}' => 'pēc {delta, plural, =1{mēneša} one{#. mēneša} other{# mēnešiem}}', 'in {delta, plural, =1{a second} other{# seconds}}' => 'pēc {delta, plural, =1{sekundes} one{#. sekundes} other{#. sekundēm}}', 'in {delta, plural, =1{a year} other{# years}}' => 'pēc {delta, plural, =1{gada} one{#. gada} other{#. gadām}}', 'in {delta, plural, =1{an hour} other{# hours}}' => 'pēc {delta, plural, =1{stundas} one{#. stundas} other{#. stundām}}', 'the input value' => 'ievadīta vērtība', '{attribute} "{value}" has already been taken.' => '{attribute} „{value}” jau ir aizņemts.', '{attribute} cannot be blank.' => 'Ir jāaizpilda „{attribute}”.', '{attribute} is invalid.' => '„{attribute}” vērtība ir nepareiza.', '{attribute} is not a valid URL.' => '„{attribute}” vērtība netiek uzskatīta par pareizu URL.', '{attribute} is not a valid email address.' => '„{attribute}” vērtība netiek uzskatīta par pareizu e-pasta adresi.', '{attribute} must be "{requiredValue}".' => '„{attribute}” vērtībai ir jābūt vienādai ar „{requiredValue}”.', '{attribute} must be a number.' => '„{attribute}” vērtībai ir jābūt skaitlim.', '{attribute} must be a string.' => '„{attribute}” vērtībai ir jābūt virknei.', '{attribute} must be an integer.' => '„{attribute}” vērtībai ir jābūt veselam skaitlim.', '{attribute} must be either "{true}" or "{false}".' => '„{attribute}” vērtībai ir jābūt „{true}” vai „{false}”.', '{attribute} must be greater than "{compareValue}".' => '„{attribute}” vērtībai ir jābūt lielākai par „{compareValue}” vērību.', '{attribute} must be greater than or equal to "{compareValue}".' => '„{attribute}” vērtībai ir jābūt lielākai vai vienādai ar „{compareValue}” vērtību.', '{attribute} must be less than "{compareValue}".' => '„{attribute}” vērtībai ir jābūt mazākai par „{compareValue}” vērtību.', '{attribute} must be less than or equal to "{compareValue}".' => '„{attribute}” vērtībai ir jābūt mazākai vai vienādai ar „{compareValue}” vērtību.', '{attribute} must be no greater than {max}.' => '„{attribute}” vērtībai nedrīkst pārsniegt {max}.', '{attribute} must be no less than {min}.' => '„{attribute}” vērtībai ir jāpārsniedz {min}.', '{attribute} must be repeated exactly.' => '„{attribute}” vērtībai ir precīzi jāatkārto.', '{attribute} must not be equal to "{compareValue}".' => '„{attribute}” vērtībai nedrīkst būt vienādai ar „{compareValue}”.', '{attribute} should contain at least {min, number} {min, plural, one{character} other{characters}}.' => '„{attribute}” vērtībai ir jāietver vismaz {min, number} {min, plural, one{simbolu} other{simbolus}}.', '{attribute} should contain at most {max, number} {max, plural, one{character} other{characters}}.' => '„{attribute}” vērtībai ir jāietver ne vairāk par {max, number} {max, plural, one{simbolu} other{simbolus}}.', '{attribute} should contain {length, number} {length, plural, one{character} other{characters}}.' => '„{attribute}” vērtībai ir jāietver {length, number} {length, plural, one{simbolu} other{simbolus}}.', '{delta, plural, =1{a day} other{# days}} ago' => '{delta, plural, =1{diena} zero{# dienas} one{#. diena} other{#. dienas}} atpakaļ', '{delta, plural, =1{a minute} other{# minutes}} ago' => '{delta, plural, =1{minūte} zero{# minūtes} one{#. minūte} other{#. minūtes}} atpakaļ', '{delta, plural, =1{a month} other{# months}} ago' => '{delta, plural, =1{mēness} zero{# mēnešu} one{#. mēness} other{#. mēnešu}} atpakaļ', '{delta, plural, =1{a second} other{# seconds}} ago' => '{delta, plural, =1{sekunde} zero{# sekundes} one{#. sekunde} other{#. sekundes}} atpakaļ', '{delta, plural, =1{a year} other{# years}} ago' => '{delta, plural, =1{gads} zero{# gadi} one{#. gads} other{#. gadi}} atpakaļ', '{delta, plural, =1{an hour} other{# hours}} ago' => '{delta, plural, =1{stunda} zero{# stundas} one{#. stunda} other{#. stundas}} atpakaļ', ];
{ "content_hash": "ce36557c3ae14c0998b9e10a31b359cd", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 264, "avg_line_length": 98.8103448275862, "alnum_prop": 0.648490664805444, "repo_name": "pranjalcodefire/yiiuserplugin", "id": "6bb56e0930043e43ba834ddf28c595237b26b6db", "size": "11871", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "vendor/yiisoft/yii2/messages/lv/yii.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "3961" }, { "name": "JavaScript", "bytes": "8872" }, { "name": "PHP", "bytes": "320816" }, { "name": "R", "bytes": "857" }, { "name": "Shell", "bytes": "1601" } ], "symlink_target": "" }
package poussecafe.attribute.entity; import java.util.Collection; import poussecafe.domain.Entity; import poussecafe.domain.EntityAttributes; public class EntityMapAttributeBuilder<K, E extends Entity<K, ?>> { EntityMapAttributeBuilder(Class<E> entityClass) { this.entityClass = entityClass; } private Class<E> entityClass; public <J, U extends EntityAttributes<K>> AdaptingEntityMapAttributeBuilder<J, U, K, E> entriesStoredAs( Class<J> storedIdType, Class<U> storedValueType) { return new AdaptingEntityMapAttributeBuilder<>(entityClass); } public <U extends EntityAttributes<K>> Complete<K, E> withCollection(Collection<U> collection) { var builder = new AdaptingEntityCollectionBackedMapAttributeBuilder<U, K, E>(entityClass); builder.collection = collection; return builder; } public static interface Complete<K, E extends Entity<K, ?>> { EntityMapAttribute<K, E> build(); } }
{ "content_hash": "c0c7cfd79714b8f07a3393ac0120548b", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 108, "avg_line_length": 32.86666666666667, "alnum_prop": 0.7139959432048681, "repo_name": "pousse-cafe/pousse-cafe", "id": "e0308fc7f6e17f5d936819b36ba5669bf1411658", "size": "986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pousse-cafe-core/src/main/java/poussecafe/attribute/entity/EntityMapAttributeBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "828466" }, { "name": "Shell", "bytes": "213" } ], "symlink_target": "" }
package org.apache.calcite.avatica.remote; import org.apache.http.HttpHost; import org.apache.http.NoHttpResponseException; import org.apache.http.auth.AuthSchemeProvider; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.AuthSchemes; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.RequestExpectContinue; import org.apache.http.config.Lookup; import org.apache.http.config.RegistryBuilder; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.impl.auth.BasicSchemeFactory; import org.apache.http.impl.auth.DigestSchemeFactory; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Objects; /** * A common class to invoke HTTP requests against the Avatica server agnostic of the data being * sent and received across the wire. */ public class AvaticaCommonsHttpClientImpl implements AvaticaHttpClient, UsernamePasswordAuthenticateable { private static final Logger LOG = LoggerFactory.getLogger(AvaticaCommonsHttpClientImpl.class); // Some basic exposed configurations private static final String MAX_POOLED_CONNECTION_PER_ROUTE_KEY = "avatica.pooled.connections.per.route"; private static final String MAX_POOLED_CONNECTION_PER_ROUTE_DEFAULT = "25"; private static final String MAX_POOLED_CONNECTIONS_KEY = "avatica.pooled.connections.max"; private static final String MAX_POOLED_CONNECTIONS_DEFAULT = "100"; protected final HttpHost host; protected final URI uri; protected final HttpProcessor httpProcessor; protected final HttpRequestExecutor httpExecutor; protected final BasicAuthCache authCache; protected final CloseableHttpClient client; final PoolingHttpClientConnectionManager pool; protected UsernamePasswordCredentials credentials = null; protected CredentialsProvider credentialsProvider = null; protected Lookup<AuthSchemeProvider> authRegistry = null; public AvaticaCommonsHttpClientImpl(URL url) { this.host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); this.uri = toURI(Objects.requireNonNull(url)); this.httpProcessor = HttpProcessorBuilder.create() .add(new RequestContent()) .add(new RequestTargetHost()) .add(new RequestConnControl()) .add(new RequestExpectContinue()).build(); this.httpExecutor = new HttpRequestExecutor(); pool = new PoolingHttpClientConnectionManager(); // Increase max total connection to 100 final String maxCnxns = System.getProperty(MAX_POOLED_CONNECTIONS_KEY, MAX_POOLED_CONNECTIONS_DEFAULT); pool.setMaxTotal(Integer.parseInt(maxCnxns)); // Increase default max connection per route to 25 final String maxCnxnsPerRoute = System.getProperty(MAX_POOLED_CONNECTION_PER_ROUTE_KEY, MAX_POOLED_CONNECTION_PER_ROUTE_DEFAULT); pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute)); this.authCache = new BasicAuthCache(); // A single thread-safe HttpClient, pooling connections via the ConnectionManager this.client = HttpClients.custom().setConnectionManager(pool).build(); } public byte[] send(byte[] request) { while (true) { HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host); // Set the credentials if they were provided. if (null != this.credentials) { context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache); } ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM); // Create the client with the AuthSchemeRegistry and manager HttpPost post = new HttpPost(uri); post.setEntity(entity); try (CloseableHttpResponse response = execute(post, context)) { final int statusCode = response.getStatusLine().getStatusCode(); if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) { return EntityUtils.toByteArray(response.getEntity()); } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) { LOG.debug("Failed to connect to server (HTTP/503), retrying"); continue; } throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode); } catch (NoHttpResponseException e) { // This can happen when sitting behind a load balancer and a backend server dies LOG.debug("The server failed to issue an HTTP response, retrying"); continue; } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Failed to execute HTTP request", e); throw new RuntimeException(e); } } } // Visible for testing CloseableHttpResponse execute(HttpPost post, HttpClientContext context) throws IOException, ClientProtocolException { return client.execute(post, context); } @Override public void setUsernamePassword(AuthenticationType authType, String username, String password) { this.credentials = new UsernamePasswordCredentials( Objects.requireNonNull(username), Objects.requireNonNull(password)); this.credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create(); switch (authType) { case BASIC: authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); break; case DIGEST: authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; default: throw new IllegalArgumentException("Unsupported authentiation type: " + authType); } this.authRegistry = authRegistryBuilder.build(); } private static URI toURI(URL url) throws RuntimeException { try { return url.toURI(); } catch (URISyntaxException e) { throw new RuntimeException(e); } } } // End AvaticaCommonsHttpClientImpl.java
{ "content_hash": "6112a465cb8bd654cd8e092c9dcf0d47", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 98, "avg_line_length": 39.790055248618785, "alnum_prop": 0.7553457372951958, "repo_name": "yeongwei/incubator-calcite", "id": "5e8fb5f166d45bb9af50e297e9a828076100cfb0", "size": "7999", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "avatica/core/src/main/java/org/apache/calcite/avatica/remote/AvaticaCommonsHttpClientImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2917" }, { "name": "CSS", "bytes": "73120" }, { "name": "FreeMarker", "bytes": "2154" }, { "name": "HTML", "bytes": "38552" }, { "name": "Java", "bytes": "14696640" }, { "name": "Protocol Buffer", "bytes": "15917" }, { "name": "Ruby", "bytes": "8067" }, { "name": "Shell", "bytes": "7961" } ], "symlink_target": "" }
import { mount } from '../../test-helpers/EnzymeHelper'; import browser from 'sinon-chrome'; import React from 'react'; import Watching from '../../src/class/popup/Watching'; window.browser = browser; const item = {title: `Test`}; const component = mount( <Watching item={item}/> ); delete window.browser; describe(`Watching`, () => { before(() => { window.browser = browser; }); after(() => { component.unmount(); browser.flush(); delete window.browser; }); it(`sends analytics appView`, () => { expect(browser.runtime.sendMessage.callCount).to.equal(1); expect(browser.runtime.sendMessage.args[0]).to.deep.equal([{ type: `sendAppView`, view: `Watching ${item.title}` }]); }); it(`has the correct html classes`, () => { const card = component.find(`.mdl-card.mdl-shadow--2dp.watching-card-thumb`).hostNodes(); const cardTitle = component.find(`.mdl-card__title.mdl-card--expand`); const cardActions = component.find(`.mdl-card__actions`); const thumbTitle = component.find(`.watching-card-thumb__title`); expect(card.hasClass(`mdl-card mdl-shadow--2dp watching-card-thumb`)).to.be.true; expect(cardTitle.hasClass(`mdl-card__title mdl-card--expand`)).to.be.true; expect(cardActions.hasClass(`mdl-card__actions`)).to.be.true; expect(thumbTitle.hasClass(`watching-card-thumb__title`)).to.be.true; }); it(`text content equals props.item.title`, () => { const span = component.find(`span`); expect(span.text()).to.equal(item.title); }); it(`card div must have thumb in background style`, () => { const card = component.find(`.mdl-card.mdl-shadow--2dp.watching-card-thumb`).hostNodes(); expect(card.getDOMNode().style.backgroundImage).to.equal(`url("https://trakt.tv/assets/placeholders/thumb/poster-2d5709c1b640929ca1ab60137044b152.png")`); }); });
{ "content_hash": "614b9853de7209142c7750477804222c", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 158, "avg_line_length": 35.132075471698116, "alnum_prop": 0.667561761546724, "repo_name": "MrMamen/traktflix", "id": "5d04b99120c46de4da14c0a24642b54cdde238c4", "size": "1862", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/popup/Watching.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3133" }, { "name": "HTML", "bytes": "2044" }, { "name": "JavaScript", "bytes": "177809" } ], "symlink_target": "" }
// <copyright file="ICompilationManager.cs" company="Microsoft Open Technologies, Inc."> // Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System.Threading.Tasks; using Microsoft.Owin.FileSystems; namespace Microsoft.AspNet.Razor.Owin.Compilation { public interface ICompilationManager { Task<CompilationResult> Compile(IFileInfo file, ITrace tracer); } }
{ "content_hash": "88d6bee3493aa3a33aad78a5151b471d", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 89, "avg_line_length": 38.07692307692308, "alnum_prop": 0.7484848484848485, "repo_name": "shinyhappyrachy/Katana-Project", "id": "640909efb27c2193ad5172320de7281cff358a07", "size": "992", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "src/Microsoft.AspNet.Razor.Owin/Compilation/ICompilationManager.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "1877" }, { "name": "C#", "bytes": "3066884" }, { "name": "CSS", "bytes": "9676" }, { "name": "JavaScript", "bytes": "11545" }, { "name": "PowerShell", "bytes": "20946" }, { "name": "Shell", "bytes": "11193" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "85d624aeb03fbff67b36cb1847f10406", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "f68eb55db07227155f12459b2f61e552fba337fe", "size": "198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Bryophyta/Bryopsida/Grimmiales/Grimmiaceae/Grimmia/Grimmia madagassa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package 'vim'
{ "content_hash": "fcc3e5c17e09173a8977d1ca9853ed3c", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 13, "avg_line_length": 7.5, "alnum_prop": 0.6666666666666666, "repo_name": "theappleman/cookbooks", "id": "18945a96528427d5a7dd7110adc2ed94c36908a2", "size": "15", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vim/recipes/default.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "12720" }, { "name": "Shell", "bytes": "2554" } ], "symlink_target": "" }
package edu.illinois.my.wiki.portlet.http.services; import com.google.inject.Inject; import edu.illinois.my.names.Username; import edu.illinois.my.security.RequestRegistrar; import edu.illinois.my.security.keys.RequestKey; import edu.illinois.my.wiki.services.WikiService; import edu.illinois.my.wiki.services.parameters.ParametersBuilder; final class RequestRegistrarWrapper implements Registrar { private final RequestRegistrar registrar; @Inject RequestRegistrarWrapper(RequestRegistrar registrar) { this.registrar = registrar; } @Override public void addCredentials(Username username, ParametersBuilder parametersBuilder) { parametersBuilder.add(WikiService.USERNAME, username.asString()); RequestKey key = registrar.registerRequest(username); parametersBuilder.add(WikiService.KEY, key.asString()); } }
{ "content_hash": "edd82bbc13f8a23dd3c447d4a6e33bc8", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 73, "avg_line_length": 32.81481481481482, "alnum_prop": 0.7652370203160271, "repo_name": "drewwills/confluence-portlet", "id": "1b514fc0bc87f0da7a7471bbe81ea8e826020f57", "size": "1653", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WikiPortlet/src/main/java/edu/illinois/my/wiki/portlet/http/services/RequestRegistrarWrapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2222" }, { "name": "Java", "bytes": "274262" } ], "symlink_target": "" }
package org.jayware.e2.component.impl.generation.analyse; import org.jayware.e2.component.api.Component; import org.jayware.e2.component.api.MalformedComponentException; import org.jayware.e2.component.api.generation.analyse.ComponentHierarchyAnalyser; import org.jayware.e2.component.impl.TestComponents.MalformedCombinedTestComponent; import org.jayware.e2.component.impl.TestComponents.TestComponentA; import org.jayware.e2.component.impl.TestComponents.TestComponentACB; import org.jayware.e2.component.impl.TestComponents.TestComponentB; import org.jayware.e2.component.impl.TestComponents.TestComponentCB; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class ComponentHierarchyAnalyserImplTest { private ComponentHierarchyAnalyser testee; @BeforeEach public void setup() { testee = new ComponentHierarchyAnalyserImpl(); } @Test public void should_return_a_Set_containing_all_component_interfaces() { final Set<Class<? extends Component>> result = testee.analyse(TestComponentACB.class); assertThat(result).containsExactlyInAnyOrder(TestComponentA.class, TestComponentB.class, TestComponentCB.class, TestComponentACB.class); } @Test public void should_throw_a_MalformedComponentException_if_one_of_the_interfaces_does_not_extend_the_Component_interface() { try { testee.analyse(MalformedCombinedTestComponent.class); fail("Expected a MalformedCombinedTestComponent"); } catch (MalformedComponentException ignored) { } } }
{ "content_hash": "31003564ddb9f1f2d754d29888faea2e", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 144, "avg_line_length": 33.71153846153846, "alnum_prop": 0.7655447803764974, "repo_name": "jayware/entity-essentials", "id": "839d5a2f0efa6c319ec0dd2a5c9cd5f27a77eb4b", "size": "2506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "entity-essentials-impl/src/test/java/org/jayware/e2/component/impl/generation/analyse/ComponentHierarchyAnalyserImplTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1138566" } ], "symlink_target": "" }
<?php /* *--------------------------------------------------------------- * APPLICATION ENVIRONMENT *--------------------------------------------------------------- * * You can load different configurations depending on your * current environment. Setting the environment also influences * things like logging and error reporting. * * This can be set to anything, but default usage is: * * development * testing * production * * NOTE: If you change these, also change the error_reporting() code below */ define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'production'); /* *--------------------------------------------------------------- * ERROR REPORTING *--------------------------------------------------------------- * * Different environments will require different levels of error reporting. * By default development will show errors but testing and live will hide them. */ switch (ENVIRONMENT) { case 'development': error_reporting(-1); ini_set('display_errors', 1); break; case 'testing': case 'production': ini_set('display_errors', 0); if (version_compare(PHP_VERSION, '5.3', '>=')) { error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED); } else { error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE); } break; default: header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'The application environment is not set correctly.'; exit(1); // EXIT_ERROR } /* *--------------------------------------------------------------- * SYSTEM FOLDER NAME *--------------------------------------------------------------- * * This variable must contain the name of your "system" folder. * Include the path if the folder is not in the same directory * as this file. */ $system_path = '/var/www/eid_dir/eid_dashboard/system'; /* *--------------------------------------------------------------- * APPLICATION FOLDER NAME *--------------------------------------------------------------- * * If you want this front controller to use a different "application" * folder than the default one you can set its name here. The folder * can also be renamed or relocated anywhere on your server. If * you do, use a full server path. For more info please see the user guide: * https://codeigniter.com/user_guide/general/managing_apps.html * * NO TRAILING SLASH! */ $application_folder = '/var/www/eid_dir/eid_dashboard/application'; /* *--------------------------------------------------------------- * VIEW FOLDER NAME *--------------------------------------------------------------- * * If you want to move the view folder out of the application * folder set the path to the folder here. The folder can be renamed * and relocated anywhere on your server. If blank, it will default * to the standard location inside your application folder. If you * do move this, use the full server path to this folder. * * NO TRAILING SLASH! */ $view_folder = ''; /* * -------------------------------------------------------------------- * DEFAULT CONTROLLER * -------------------------------------------------------------------- * * Normally you will set your default controller in the routes.php file. * You can, however, force a custom routing by hard-coding a * specific controller class/function here. For most applications, you * WILL NOT set your routing here, but it's an option for those * special instances where you might want to override the standard * routing in a specific front controller that shares a common CI installation. * * IMPORTANT: If you set the routing here, NO OTHER controller will be * callable. In essence, this preference limits your application to ONE * specific controller. Leave the function name blank if you need * to call functions dynamically via the URI. * * Un-comment the $routing array below to use this feature */ // The directory name, relative to the "controllers" folder. Leave blank // if your controller is not in a sub-folder within the "controllers" folder // $routing['directory'] = ''; // The controller class file name. Example: mycontroller // $routing['controller'] = ''; // The controller function you wish to be called. // $routing['function'] = ''; /* * ------------------------------------------------------------------- * CUSTOM CONFIG VALUES * ------------------------------------------------------------------- * * The $assign_to_config array below will be passed dynamically to the * config class when initialized. This allows you to set custom config * items or override any default config values found in the config.php file. * This can be handy as it permits you to share one application between * multiple front controller files, with each file containing different * config values. * * Un-comment the $assign_to_config array below to use this feature */ // $assign_to_config['name_of_config_item'] = 'value of config item'; // -------------------------------------------------------------------- // END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE // -------------------------------------------------------------------- /* * --------------------------------------------------------------- * Resolve the system path for increased reliability * --------------------------------------------------------------- */ // Set the current directory correctly for CLI requests if (defined('STDIN')) { chdir(dirname(__FILE__)); } if (($_temp = realpath($system_path)) !== FALSE) { $system_path = $_temp.'/'; } else { // Ensure there's a trailing slash $system_path = rtrim($system_path, '/').'/'; } // Is the system path correct? if ( ! is_dir($system_path)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME); exit(3); // EXIT_CONFIG } /* * ------------------------------------------------------------------- * Now that we know the path, set the main path constants * ------------------------------------------------------------------- */ // The name of THIS file define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); // Path to the system folder define('BASEPATH', str_replace('\\', '/', $system_path)); // Path to the front controller (this file) define('FCPATH', dirname(__FILE__).'/'); // Name of the "system folder" define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/')); // The path to the "application" folder if (is_dir($application_folder)) { if (($_temp = realpath($application_folder)) !== FALSE) { $application_folder = $_temp; } define('APPPATH', $application_folder.DIRECTORY_SEPARATOR); } else { if ( ! is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF; exit(3); // EXIT_CONFIG } define('APPPATH', BASEPATH.$application_folder.DIRECTORY_SEPARATOR); } // The path to the "views" folder if ( ! is_dir($view_folder)) { if ( ! empty($view_folder) && is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR)) { $view_folder = APPPATH.$view_folder; } elseif ( ! is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF; exit(3); // EXIT_CONFIG } else { $view_folder = APPPATH.'views'; } } if (($_temp = realpath($view_folder)) !== FALSE) { $view_folder = $_temp.DIRECTORY_SEPARATOR; } else { $view_folder = rtrim($view_folder, '/\\').DIRECTORY_SEPARATOR; } define('VIEWPATH', $view_folder); /* * -------------------------------------------------------------------- * LOAD THE BOOTSTRAP FILE * -------------------------------------------------------------------- * * And away we go... */ require_once BASEPATH.'core/CodeIgniter.php';
{ "content_hash": "c9474b5fe207c1812bd0271ccc6c5c00", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 158, "avg_line_length": 31.7027027027027, "alnum_prop": 0.5605894531725734, "repo_name": "mwendakith/eid_dashboard", "id": "17ce71b8dfdce450c15d9835465c9755087528f3", "size": "9871", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "95311" }, { "name": "HTML", "bytes": "8177944" }, { "name": "Hack", "bytes": "758" }, { "name": "JavaScript", "bytes": "5135927" }, { "name": "PHP", "bytes": "6151777" }, { "name": "PLpgSQL", "bytes": "47573" }, { "name": "SQLPL", "bytes": "446896" } ], "symlink_target": "" }
require 'prologue/cli' require 'prologue/version' module Prologue # Autoloads autoload :Errors , 'prologue/errors' autoload :TemplateRunner , 'prologue/template_runner' end
{ "content_hash": "9ab56607c43f9942c8926938d9713f23", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 55, "avg_line_length": 16.636363636363637, "alnum_prop": 0.7540983606557377, "repo_name": "codegenome/cg-prologue", "id": "af3b338e5711b1d2fbdefb590376514c5f74a49c", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/prologue.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "200" }, { "name": "Ruby", "bytes": "63174" } ], "symlink_target": "" }
.class Lcom/ub/main/account/AccountBindPhone$5; .super Ljava/lang/Object; .source "AccountBindPhone.java" # interfaces .implements Landroid/content/DialogInterface$OnClickListener; # annotations .annotation system Ldalvik/annotation/EnclosingMethod; value = Lcom/ub/main/account/AccountBindPhone;->HttpResponse(Lcom/ub/main/util/NetConfig$HttpRequestId;Ljava/lang/String;Ljava/lang/String;)V .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = null .end annotation # instance fields .field final synthetic this$0:Lcom/ub/main/account/AccountBindPhone; # direct methods .method constructor <init>(Lcom/ub/main/account/AccountBindPhone;)V .locals 0 .parameter .prologue .line 1 iput-object p1, p0, Lcom/ub/main/account/AccountBindPhone$5;->this$0:Lcom/ub/main/account/AccountBindPhone; .line 515 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public onClick(Landroid/content/DialogInterface;I)V .locals 0 .parameter "dialog" .parameter "whichButton" .prologue .line 518 return-void .end method
{ "content_hash": "d55377d5d07a1c30a8dff72a5100d3a9", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 145, "avg_line_length": 24.79591836734694, "alnum_prop": 0.7176954732510288, "repo_name": "achellies/WaterEveryDay", "id": "4c1e91bb89eda71779ee137aa9c08313dcc6c23b", "size": "1215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WaterEveryDay/Bin/ubox_android_ch_release_v2.2.1/smali/com/ub/main/account/AccountBindPhone$5.smali", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "719444" }, { "name": "C++", "bytes": "1862724" }, { "name": "Java", "bytes": "19730" }, { "name": "Objective-C", "bytes": "31937" }, { "name": "Shell", "bytes": "324" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SignalR_playground.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } } }
{ "content_hash": "29f34d8673ee908e0830398188b1a62f", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 44, "avg_line_length": 18.3125, "alnum_prop": 0.6518771331058021, "repo_name": "albinsunnanbo/SignalR-playground", "id": "3b3eb026ae9c9acc22362a5454e812b11c856d47", "size": "295", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SignalR-playground/SignalR-playground/Controllers/HomeController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "C#", "bytes": "10845" }, { "name": "CSS", "bytes": "560" }, { "name": "HTML", "bytes": "8722" }, { "name": "JavaScript", "bytes": "132628" } ], "symlink_target": "" }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Infrastructure; namespace Microsoft.AspNetCore.Mvc; public class ActionResultOfTTest { [Fact] public void Constructor_WithValue_ThrowsForInvalidType() { // Arrange var input = new FileStreamResult(Stream.Null, "application/json"); // Act & Assert var ex = Assert.Throws<ArgumentException>(() => new ActionResult<FileStreamResult>(value: input)); Assert.Equal($"Invalid type parameter '{typeof(FileStreamResult)}' specified for 'ActionResult<T>'.", ex.Message); } [Fact] public void Constructor_WithActionResult_ThrowsForInvalidType() { // Arrange var actionResult = new OkResult(); // Act & Assert var ex = Assert.Throws<ArgumentException>(() => new ActionResult<FileStreamResult>(result: actionResult)); Assert.Equal($"Invalid type parameter '{typeof(FileStreamResult)}' specified for 'ActionResult<T>'.", ex.Message); } [Fact] public void Constructor_WithIResult_ThrowsForInvalidType() { // Arrange var result = new TestResult(); // Act & Assert var ex = Assert.Throws<ArgumentException>(() => new ActionResult<TestResult>(value: result)); Assert.Equal($"Invalid type parameter '{typeof(TestResult)}' specified for 'ActionResult<T>'.", ex.Message); } [Fact] public void Convert_ReturnsResultIfSet() { // Arrange var expected = new OkResult(); var actionResultOfT = new ActionResult<string>(expected); var convertToActionResult = (IConvertToActionResult)actionResultOfT; // Act var result = convertToActionResult.Convert(); // Assert Assert.Same(expected, result); } [Fact] public void Convert_ReturnsObjectResultWrappingValue() { // Arrange var value = new BaseItem(); var actionResultOfT = new ActionResult<BaseItem>(value); var convertToActionResult = (IConvertToActionResult)actionResultOfT; // Act var result = convertToActionResult.Convert(); // Assert var objectResult = Assert.IsType<ObjectResult>(result); Assert.Same(value, objectResult.Value); Assert.Equal(typeof(BaseItem), objectResult.DeclaredType); Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode); } [Fact] public void Convert_ReturnsObjectResultWrappingValue_SetsStatusCodeFromProblemDetails() { // Arrange var value = new ProblemDetails { Status = StatusCodes.Status400BadRequest }; var actionResultOfT = new ActionResult<ProblemDetails>(value); var convertToActionResult = (IConvertToActionResult)actionResultOfT; // Act var result = convertToActionResult.Convert(); // Assert var objectResult = Assert.IsType<ObjectResult>(result); Assert.Same(value, objectResult.Value); Assert.Equal(typeof(ProblemDetails), objectResult.DeclaredType); Assert.Equal(StatusCodes.Status400BadRequest, objectResult.StatusCode); } [Fact] public void Convert_InfersDeclaredTypeFromActionResultTypeParameter() { // Arrange var value = new DerivedItem(); var actionResultOfT = new ActionResult<BaseItem>(value); var convertToActionResult = (IConvertToActionResult)actionResultOfT; // Act var result = convertToActionResult.Convert(); // Assert var objectResult = Assert.IsType<ObjectResult>(result); Assert.Same(value, objectResult.Value); Assert.Equal(typeof(BaseItem), objectResult.DeclaredType); Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode); } private class BaseItem { } private class DerivedItem : BaseItem { } private class TestResult : IResult { public Task ExecuteAsync(HttpContext httpContext) => Task.CompletedTask; } }
{ "content_hash": "c0535507c99036304fdb52cf5866c7ed", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 122, "avg_line_length": 32.609756097560975, "alnum_prop": 0.6656694091249065, "repo_name": "aspnet/AspNetCore", "id": "e6a4c78cac5e8c8cc86cc77de3c3994eaffcf834", "size": "4149", "binary": false, "copies": "1", "ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2", "path": "src/Mvc/Mvc.Core/test/ActionResultOfTTest.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "Batchfile", "bytes": "19526" }, { "name": "C", "bytes": "213916" }, { "name": "C#", "bytes": "47455169" }, { "name": "C++", "bytes": "1900454" }, { "name": "CMake", "bytes": "7955" }, { "name": "CSS", "bytes": "62326" }, { "name": "Dockerfile", "bytes": "3584" }, { "name": "F#", "bytes": "7982" }, { "name": "Groovy", "bytes": "1529" }, { "name": "HTML", "bytes": "1130653" }, { "name": "Java", "bytes": "297552" }, { "name": "JavaScript", "bytes": "2726829" }, { "name": "Lua", "bytes": "4904" }, { "name": "Makefile", "bytes": "220" }, { "name": "Objective-C", "bytes": "222" }, { "name": "PowerShell", "bytes": "241706" }, { "name": "Python", "bytes": "19476" }, { "name": "Roff", "bytes": "6044" }, { "name": "Shell", "bytes": "142293" }, { "name": "Smalltalk", "bytes": "3" }, { "name": "TypeScript", "bytes": "797435" } ], "symlink_target": "" }
package net.sf.luciddb.aggdes; import org.pentaho.aggdes.model.*; import org.pentaho.aggdes.algorithm.*; import org.pentaho.aggdes.output.*; import org.pentaho.aggdes.output.impl.*; import java.util.*; import java.io.*; import java.sql.*; /** * LucidDbAggResultHandler implements the ResultHandler interface * by executing DDL commands again the local LucidDB instance. * * @author John Sichi * @version $Id$ */ public class LucidDbAggResultHandler extends ResultHandlerImpl { public LucidDbAggResultHandler() { } public void handle( Map<Parameter, Object> parameterValues, Schema schema, Result result) { try { handleImpl(parameterValues, schema, result); } catch (Exception ex) { throw new RuntimeException( "Aggregate designer failed; see trace for details", ex); } } private void handleImpl( Map<Parameter, Object> parameterValues, Schema schema, Result result) throws Exception { AggregateTableOutputFactory outputFactory = new AggregateTableOutputFactory(); List<Output> outputs = outputFactory.createOutputs( schema, result.getAggregates()); Connection conn = DriverManager.getConnection("jdbc:default:connection"); Statement stmt = conn.createStatement(); // CREATE TABLE CreateTableGenerator tgen = new CreateTableGenerator(); for (Output output : outputs) { String sql = tgen.generate(schema, output); sql = sql.replaceAll("INTEGER\\(.*\\)", "INTEGER"); sql = sql.replaceAll("BIGINT\\(.*\\)", "BIGINT"); sql = sql.replaceAll("SMALLINT\\(.*\\)", "SMALLINT"); executeSql(stmt, sql); } PopulateTableGenerator pgen = new PopulateTableGenerator(); for (Output output : outputs) { // INSERT AggregateTableOutput tableOutput = (AggregateTableOutput) output; String sql = pgen.generate(schema, output); executeSql(stmt, sql); // ANALYZE final StringBuilder buf = new StringBuilder(); buf.append("ANALYZE TABLE "); schema.getDialect().quoteIdentifier( buf, tableOutput.getCatalogName(), tableOutput.getSchemaName(), tableOutput.getTableName()); buf.append(" ESTIMATE STATISTICS FOR ALL COLUMNS;"); sql = buf.toString(); executeSql(stmt, sql); } // Regenerate XML String mondrianOutput = null; for (Parameter p : parameterValues.keySet()) { if (p.getName().equals("mondrianOutput")) { mondrianOutput = (String) parameterValues.get(p); break; } } MondrianSchemaGenerator sgen = new MondrianSchemaGenerator(); String xml = sgen.generateFull(schema, outputs); FileWriter fw = new FileWriter(mondrianOutput); try { fw.write(xml); } finally { fw.close(); } } private void executeSql(Statement stmt, String sql) throws SQLException { int i = sql.lastIndexOf(';'); sql = sql.substring(0, i); stmt.executeUpdate(sql); } } // End LucidDbAggResultHandler.java
{ "content_hash": "f614cac86124f11c1e4b088b58d5544b", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 79, "avg_line_length": 30.693693693693692, "alnum_prop": 0.5920164367478721, "repo_name": "julianhyde/luciddb", "id": "7d9509b78c00b37b896da316df2b6a78d86d3c5c", "size": "4205", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "luciddb/ext/aggdes/src/net/sf/luciddb/aggdes/LucidDbAggResultHandler.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>MAGMA: General matrices</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="magma-logo.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">MAGMA &#160;<span id="projectnumber">2.1.0</span> </div> <div id="projectbrief">Matrix Algebra for GPU and Multicore Architectures</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="modules.html"><span>Routines</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('group__sparse__gesv.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#groups">Modules</a> </div> <div class="headertitle"> <div class="title">General matrices<div class="ingroups"><a class="el" href="group__sparse.html">Sparse</a> &raquo; <a class="el" href="group__sparse__solvers.html">Sparse linear systems</a></div></div> </div> </div><!--header--> <div class="contents"> <p>Solve \( Ax = b \), for general \( A \). <a href="#details">More...</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="groups"></a> Modules</h2></td></tr> <tr class="memitem:group__magmasparse__sgesv"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__magmasparse__sgesv.html">single precision</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:group__magmasparse__dgesv"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__magmasparse__dgesv.html">double precision</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:group__magmasparse__cgesv"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__magmasparse__cgesv.html">single-complex precision</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:group__magmasparse__zgesv"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__magmasparse__zgesv.html">double-complex precision</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <p>Solve \( Ax = b \), for general \( A \). </p> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li> </ul> </div> </body> </html>
{ "content_hash": "4fcdd40a30c20035bbf83e6cfe1af3ed", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 239, "avg_line_length": 46.2027972027972, "alnum_prop": 0.6544573936733767, "repo_name": "maxhutch/magma", "id": "04d076da4fbf25d97c56135fe4f2162b7d580690", "size": "6607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/html/group__sparse__gesv.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1166551" }, { "name": "C++", "bytes": "20905815" }, { "name": "CMake", "bytes": "15561" }, { "name": "CSS", "bytes": "3888" }, { "name": "Cuda", "bytes": "5147842" }, { "name": "FORTRAN", "bytes": "8368760" }, { "name": "Makefile", "bytes": "32020" }, { "name": "Matlab", "bytes": "1292" }, { "name": "Objective-C", "bytes": "6420" }, { "name": "Python", "bytes": "1733398" }, { "name": "Shell", "bytes": "13153" } ], "symlink_target": "" }
/*! \file BTree.h \date Wednesday May 13, 2009 \author Gregory Diamos <gregory.diamos@gatech.edu> \brief The header file for the BTree class */ #ifndef BTREE_H_INCLUDED #define BTREE_H_INCLUDED #include <hydrazine/interface/debug.h> #include <hydrazine/interface/macros.h> #include <hydrazine/interface/ValueCompare.h> #ifdef REPORT_BASE #undef REPORT_BASE #endif #define REPORT_BASE 1 #include <stack> #include <cstring> #include <utility> namespace hydrazine { /*! \brief A Btree data structure providing the STL map interface. */ template< typename Key, typename Value, typename Compare = std::less<Key>, typename _Allocator = std::allocator< std::pair< const Key, Value > >, size_t PageSize = 1024 > class BTree { template< typename K, typename V, typename C, typename A, size_t P > friend std::ostream& operator<<( std::ostream&, const BTree< K, V, C, A, P >& ); public: class Iterator; class ConstIterator; public: typedef Key key_type; typedef Value mapped_type; typedef std::pair< key_type, mapped_type > value_type; public: typedef typename _Allocator::template rebind< value_type >::other Allocator; public: typedef BTree type; typedef Compare key_compare; typedef Allocator allocator_type; typedef typename Allocator::reference reference; typedef typename Allocator::const_reference const_reference; typedef Iterator iterator; typedef ConstIterator const_iterator; typedef typename Allocator::size_type size_type; typedef typename Allocator::difference_type difference_type; typedef typename Allocator::pointer pointer; typedef typename Allocator::const_pointer const_pointer; typedef std::reverse_iterator< iterator > reverse_iterator; typedef std::reverse_iterator< const_iterator > const_reverse_iterator; typedef std::pair< iterator, bool > insertion; typedef ValueCompare< Compare, type > value_compare; private: Allocator _allocator; value_compare _compare; key_compare _keyCompare; private: class Body; class Node; class Leaf; private: typedef std::pair< Node*, size_type > StackElement; typedef std::stack< StackElement > Stack; private: static const size_type MaxNodes = MAX( 8, PageSize / ( sizeof( key_type ) + sizeof( mapped_type ) ) ); static const size_type MaxLeafs = MAX( 8, PageSize / ( sizeof( key_type ) + sizeof( Node* ) ) ); static const size_type MinNodes = MaxNodes / 2; static const size_type MinLeafs = MaxLeafs / 2; private: typedef typename _Allocator::template rebind< Body >::other BodyAllocator; typedef typename _Allocator::template rebind< Leaf >::other LeafAllocator; private: BodyAllocator _bodyAllocator; LeafAllocator _leafAllocator; private: /*! \brief A base class for an internal node. */ class Node { public: size_type level; size_type size; public: inline void construct( size_type l ) { level = l; size = 0; } inline bool leaf() const { return level == 0; } }; /*! \brief Body Node */ class Body : public Node { public: key_type keys[ MaxNodes ]; Node* children[ MaxNodes + 1 ]; public: inline void construct( const size_type level ) { Node::construct( level ); } inline bool full() const { return size == MaxNodes; } inline bool deficient() const { return size < MinNodes; } inline bool borderline() const { return size <= MinNodes; } }; /*! \brief A leaf node */ class Leaf : public Node { public: Leaf* previous; Leaf* next; value_type data[ MaxLeafs ]; public: inline void construct() { Node::construct( 0 ); previous = 0; next = 0; } inline bool full() const { return size == MaxLeafs; } inline bool deficient() const { return size < MinLeafs; } inline bool borderline() const { return size <= MaxLeafs; } }; public: class Iterator { friend class BTree; friend class Node; friend class Leaf; public: typedef Iterator iterator_type; typedef std::bidirectional_iterator_tag iterator_category; typedef BTree::value_type value_type; typedef BTree::pointer pointer; typedef BTree::reference reference; typedef BTree::difference_type difference_type; private: Leaf* _leaf; size_type _current; private: inline Iterator( Leaf* l, size_type c ) : _leaf( l ), _current( c ) {} public: inline Iterator( ) {} inline Iterator( const Iterator& i ) : _leaf( i._leaf ), _current( i._current ) {} inline Iterator& operator=( const Iterator& i ) { _leaf = i._leaf; _current = i._current; return *this; } inline reference operator*() const { assert( _current < _leaf->size ); return _leaf->data[ _current ]; } inline pointer operator->() const { assert( _current < _leaf->size ); return &_leaf->data[ _current ]; } inline Iterator& operator++() { if( _current + 1 < _leaf->size ) { ++_current; } else if( 0 != _leaf->next ) { _current = 0; _leaf = _leaf->next; } else { _current = _leaf->size; } return *this; } inline Iterator operator++( int ) { Iterator next( *this ); ++next; return std::move( next ); } inline Iterator& operator--() { if( _current != 0 ) { --_current; } else if( _leaf->previous != 0 ) { _leaf = _leaf->previous; _current = _leaf->size - 1; } else { _current = 0; } return *this; } inline Iterator operator--( int ) { Iterator previous( *this ); --previous; return std::move( previous ); } public: bool operator==( const ConstIterator& i ) { return _leaf == i._leaf && _current == i._current; } bool operator!=( const ConstIterator& i ) { return _leaf != i._leaf || _current != i._current; } }; public: class ConstIterator { friend class BTree; friend class Node; friend class Leaf; public: typedef Iterator iterator_type; typedef std::bidirectional_iterator_tag iterator_category; typedef BTree::value_type value_type; typedef BTree::const_pointer pointer; typedef BTree::const_reference reference; typedef BTree::difference_type difference_type; private: Leaf* _leaf; size_type _current; private: inline ConstIterator( Leaf* l, size_type c ) : _leaf( l ), _current( c ) {} public: inline ConstIterator() {} inline ConstIterator( const Iterator& i ) : _leaf( i._leaf), _current( i._current ) {} inline ConstIterator( const ConstIterator& i ) : _leaf( i._leaf), _current( i._current ) {} inline ConstIterator& operator=( const ConstIterator& i ) { _leaf = i._leaf; _current = i._current; return *this; } inline reference operator*() const { assert( _current < _leaf->size ); return _leaf->data[ _current ]; } inline pointer operator->() const { assert( _current < _leaf->size ); return &_leaf->data[ _current ]; } inline ConstIterator& operator++() { if( _current + 1 < _leaf->size ) { ++_current; } else if( 0 != _leaf->next ) { _current = 0; _leaf = _leaf->next; } else { _current = _leaf->size; } return *this; } inline ConstIterator operator++( int ) { Iterator next( *this ); ++next; return std::move( next ); } inline ConstIterator& operator--() { if( _current != 0 ) { --_current; } else if( _leaf->previous != 0 ) { _leaf = _leaf->previous; _current = _leaf->size - 1; } else { _current = 0; } return *this; } inline ConstIterator operator--( int ) { Iterator previous( *this ); --previous; return std::move( previous ); } const pointer& base() const { return _current; } public: bool operator==( const ConstIterator& i ) { return _leaf == i._leaf && _current == i._current; } bool operator!=( const ConstIterator& i ) { return _leaf != i._leaf || _current != i._current; } }; private: class Stats { public: size_type elements; size_type leafs; size_type bodies; public: inline Stats() : elements( 0 ), leafs( 0 ), bodies( 0 ) {} inline size_type nodes() const { return leafs + bodies; } }; /*! \brief Internal Data */ private: Node* _root; Leaf* _begin; Leaf* _end; Stats _stats; /*! \brief Copy/Construct/Destroy */ public: explicit BTree( const Compare& comp = Compare(), const Allocator& alloc = Allocator() ) : _allocator( alloc ), _compare( comp ), _root( 0 ), _begin( 0 ), _end( 0 ) { } template < typename InputIterator > BTree( InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& alloc = Allocator() ) : _allocator( alloc ), _compare( comp ), _root( 0 ), _begin( 0 ), _end( 0 ) { insert( first, last ); } BTree( const BTree& tree ) : _allocator( tree._allocator ), _compare( tree._compare ), _root( 0 ), _begin( 0 ), _end( 0 ) { insert( tree.begin(), tree.end() ); } ~BTree() { clear(); } BTree& operator=( const BTree& tree ) { clear(); insert( tree.begin(), tree.end() ); return *this; } /*! \brief Iterators */ public: inline iterator begin() { return iterator( _begin, 0 ); } inline const_iterator begin() const { return const_iterator( _begin, 0 ); } inline iterator end() { return iterator( _end, _end != 0 ? _end->size : 0 ); } inline const_iterator end() const { return const_iterator( _end, _end != 0 ? _end->size : 0 ); } inline reverse_iterator rbegin() { return reverse_iterator( end() ); } inline const_reverse_iterator rbegin() const { return const_reverse_iterator( end() ); } inline reverse_iterator rend() { return reverse_iterator( begin() ); } inline const_reverse_iterator rend() const { return const_reverse_iterator( begin() ); } /*! \brief Capacity */ public: inline bool empty() const { return size() == 0; } inline size_type size() const { return _stats.elements; } inline size_type max_size() const { return _allocator.max_size(); } /*! \brief Element access */ public: inline reference operator[]( const key_type& key ) { iterator fi = lower_bound( key ); if( fi == end() ) { fi = _root->insert( fi, std::make_pair( key, mapped_type() ) ); } else { if( _compare( *fi, key ) || _compare( key, *fi ) ) { fi = _root->insert( fi, std::make_pair( key, mapped_type() ) ); } } return fi->second; } /*! \brief Modifiers */ public: inline insertion insert( const_reference x ) { report( "Inserting " << x.first << "," << x.second ); if( _root != 0 ) { Stack stack; stack.push( StackElement( _root, 0 ) ); _findInsertLeaf( stack, x ); insertion result( _insertLeaf( stack.top().first, x ) ); if( result.first._leaf->full() ) { assert( result.second ); report( " Insert caused a split." ); _split( stack, result.first ); } return result; } else { report( " Creating the root node." ); _createRoot(); assert( _root->leaf() ); Leaf* leaf = static_cast< Leaf* >( _root ); leaf->data[ 0 ] = x; leaf->size = 1; return insertion( begin(), true ); } } inline iterator insert( iterator position, const_reference x ) { return insert( x ).first; } template < typename InputIterator > inline void insert( InputIterator first, InputIterator last ) { for( InputIterator fi = first; fi != last; ++fi ) { insert( *fi ); } } inline void erase( iterator position ) { assert( "Erase not implemented." == 0 ); } inline size_type erase( const key_type& x ) { iterator position = find( x ); if( x != end() ) { erase( position ); return 1; } return 0; } inline void erase( iterator first, iterator last ) { assert( "Erase not implemented." == 0 ); } inline void swap( BTree& tree ) { std::swap( _stats, tree._stats ); std::swap( _begin, tree._begin ); std::swap( _end, tree._end ); std::swap( _root, tree._root ); } inline void clear() { if( _root != 0 ) { _clear( _root ); _free( _root ); _root = 0; _begin = 0; _end = 0; _stats = Stats(); } } private: inline void _createRoot() { assert( _root == 0 ); Leaf* leaf = _leafAllocator.allocate( 1 ); leaf->construct(); _root = leaf; } inline void _findInsertLeaf( Stack& stack, const_reference value ) { for( size_type level = _root->level; level > 0; --level ) { assert( stack.top().first->level == level ); Body* body = static_cast< Body* >( stack.top().first ); Key* key = std::lower_bound( body->keys, body->keys + body->size, value, _compare ); size_type position = key - body->keys; stack.push( StackElement( body->children[ position ], position ) ); } assert( stack.top().first->leaf() ); } inline insertion _insertLeaf( Node* node, const_reference value ) { Leaf* leaf = static_cast< Leaf* >( node ); pointer position = std::lower_bound( leaf->data, leaf->data + leaf->size, value, _compare ); if( position != leaf->data + leaf->size ) { if( !_compare( value, *position ) ) { return insertion( iterator( leaf, position - leaf->data ), false ); } } std::copy_backward( position, leaf->data + leaf->size, leaf->data + leaf->size + 1 ); *position = value; ++leaf->size; return insertion( iterator( leaf, position - leaf->data ), true ); } inline void _split( Stack& stack, iterator& fi ) { assert( stack.top().first->leaf() ); Leaf* leaf = static_cast< Leaf* >( stack.top().first ); size_type position = stack.top().second; assert( leaf == fi._leaf ); if( !leaf->full() ) { return; } Leaf* right = _splitLeaf( leaf, fi ); stack.pop(); if( stack.empty() ) { report( " Splitting the root." ); _bumpRoot( leaf, right ); return; } else { Body* parent = static_cast< Body* >( stack.top().first ); _propagate( parent, leaf, right, position ); } while( stack.size() > 1 ) { Body* body = static_cast< Body* >( stack.top().first ); size_type position = stack.top().second; stack.pop(); if( !body->full() ) { return; } size_type splitKey; Body* right = _splitBody( body, splitKey ); Body* parent = static_cast< Body* >( stack.top().first ); _propagate( parent, body, right, position, splitKey ); } assert( stack.top().first == _root ); Body* body = static_cast< Body* >( stack.top().first ); stack.pop(); if( !body->full() ) { return; } report( " Splitting the root." ); size_type splitKey; Body* rightBody = _splitBody( body, splitKey ); _bumpRoot( body, rightBody, splitKey ); } inline Leaf* _splitLeaf( Leaf* leaf, iterator& fi ) { report( " Splitting leaf node." ); Leaf* right = _allocateLeaf(); size_type median = leaf->size / 2; right->size = leaf->size - median; std::copy( leaf->data + median, leaf->data + leaf->size, right->data ); leaf->size = median; if( fi._current >= median ) { fi._leaf = right; fi._current -= median; } if( _end == leaf ) { _end = right; } return right; } inline Body* _splitBody( Body* body, size_type& key ) { assert( body->full() ); report( " Splitting body node." ); Body* right = _allocateBody( body->level ); size_type median = body->size / 2; report( " median index is " << median ); right->size = body->size - median - 1; std::copy( body->keys + median + 1, body->keys + body->size, right->keys ); std::copy( body->children + median + 1, body->children + body->size + 1, right->children ); body->size = median; key = body->keys[ median ]; report( " right size is " << right->size ); report( " left size is " << body->size ); report( " split on key " << key ); return right; } inline void _bumpRoot( Body* left, Body* right, size_type key ) { assert( left == _root ); report( " Bumped to level " << (left->level + 1) << " on key " << key ); Body* root = _allocateBody( left->level + 1 ); root->size = 1; root->keys[0] = key; root->children[0] = left; root->children[1] = right; report( " left is below " << left->keys[ left->size - 1 ] ); report( " right is above " << key ); _root = root; } inline void _bumpRoot( Leaf* left, Leaf* right ) { assert( left == _root ); report( " Bumped to level 1" ); Body* root = _allocateBody( 1 ); root->size = 1; root->keys[0] = right->data[0].first; root->children[0] = left; root->children[1] = right; _root = root; } inline void _propagate( Body* parent, Leaf* left, Leaf* right, size_type position ) { assert( position <= parent->size ); assert( parent->children[ position ] == left ); report( " Propagating the split up the tree at index " << position << "." ); std::copy_backward( parent->keys + position, parent->keys + parent->size, parent->keys + parent->size + 1 ); std::copy_backward( parent->children + position + 1, parent->children + parent->size + 1, parent->children + parent->size + 2 ); ++parent->size; parent->keys[ position ] = right->data[0].first; parent->children[ position + 1 ] = right; } inline void _propagate( Body* parent, Body* left, Body* right, size_type position, size_type& key ) { assert( position <= parent->size ); assert( parent->children[ position ] == left ); report( " Propagating the split up the tree at index " << position << "." ); std::copy_backward( parent->keys + position, parent->keys + parent->size, parent->keys + parent->size + 1 ); std::copy_backward( parent->children + position + 1, parent->children + parent->size + 1, parent->children + parent->size + 2 ); ++parent->size; parent->keys[ position ] = key; parent->children[ position + 1 ] = right; } inline void _clear( Node* n ) { if( !n->leaf() ) { Body* body = static_cast< Body* >( n ); for( size_type i = 0; i < n->size; ++i ) { _clear( body->children[ i ] ); _free( body->children[ i ] ); } } } inline Body* _allocateBody( size_type level ) { Body* body = _bodyAllocator.allocate( 1 ); body->construct( level ); ++_stats.bodies; return body; } inline Leaf* _allocateLeaf( ) { Leaf* leaf = _leafAllocator.allocate( 1 ); leaf->construct(); ++_stats.leafs; return leaf; } inline void _free( Node* n ) { if( n->leaf() ) { _leafAllocator.deallocate( static_cast< Leaf* >( n ), 1 ); --_stats.leafs; } else { _bodyAllocator.deallocate( static_cast< Body* >( n ), 1 ); --_stats.bodies; } } inline void _insert( iterator position, const_reference val ) { assert( "_insert not implemented." == 0 ); } /*! \brief Observers */ public: inline key_compare key_comp() const { return _compare.compare; } inline value_compare value_comp() const { return _compare; } /*! \brief Map Operations */ public: inline iterator find( const key_type& x ) { iterator result = lower_bound( x ); report( "Finding key " << x ); if( result != end() ) { if( !_keyCompare( x, result->first ) ) { report( " Found value " << result->second ); return result; } } reportE( result == end(), " Could not find value for key." ); return end(); } inline const_iterator find( const key_type& x ) const { const_iterator result = lower_bound( x ); report( "Finding key " << x ); if( result != end() ) { if( !_compareKey( x, result->first ) ) { report( " Found value " << result->second ); return result; } } reportE( result == end(), " Could not find value for key." ); return end(); } inline size_type count( const key_type& x ) const { return find( x ) != end(); } inline iterator lower_bound( const key_type& x ) { if ( _root == 0 ) return end(); Node* node = _root; while( !node->leaf() ) { Body* body = static_cast< Body* >( node ); Key* key = std::lower_bound( body->keys, body->keys + body->size, x, _keyCompare ); node = body->children[ key - body->keys ]; } Leaf* leaf = static_cast< Leaf* >( node ); value_type* fi = std::lower_bound( leaf->data, leaf->data + leaf->size, x, _compare ); size_type index = fi - leaf->data; if( index == leaf->size ) { return end(); } return iterator( leaf, index ); } inline const_iterator lower_bound( const key_type& x ) const { return lower_bound( x ); } inline iterator upper_bound( const key_type& x ) { iterator result = lower_bound( x ); if( result != end() ) { if( !_compare( x, *result ) ) { ++result; } } return result; } inline const_iterator upper_bound( const key_type& x ) const { const_iterator result = lower_bound( x ); if( result != end() ) { if( !_compare( x, *result ) ) { ++result; } } return result; } inline std::pair< iterator, iterator > equal_range( const key_type& x ) { std::pair< iterator, iterator > result; result.first = lower_bound( x ); result.second = result.first; if( result.second != end() ) { if( !_compare( x, *result.second ) ) { ++result.second; } } return result; } inline std::pair< const_iterator, const_iterator > equal_range( const key_type& x ) const { std::pair< iterator, iterator > result; result.first = lower_bound( x ); result.second = result.first; if( result.second != end() ) { if( !_compare( x, *result.second ) ) { ++result.second; } } return result; } }; template <typename Key, typename T, typename Compare, typename Allocator, size_t PageSize> bool operator==(const BTree< Key, T, Compare, Allocator, PageSize>& x, const BTree< Key, T, Compare, Allocator, PageSize >& y) { if( x.size() != y.size() ) { return false; } return std::equal( x.begin(), x.end(), y.begin() ); } template < typename Key, typename T, typename Compare, typename Allocator, size_t PageSize > bool operator< (const BTree< Key, T, Compare, Allocator, PageSize >& x, const BTree< Key, T, Compare, Allocator, PageSize >& y) { return std::lexicographical_compare( x.begin(), x.end(), y.begin(), y.end(), x.value_comp() ); } template < typename Key, typename T, typename Compare, typename Allocator, size_t PageSize > bool operator!=(const BTree< Key, T, Compare, Allocator, PageSize >& x, const BTree< Key, T, Compare, Allocator, PageSize >& y) { return !( x == y ); } template < typename Key, typename T, typename Compare, typename Allocator, size_t PageSize > bool operator> (const BTree< Key, T, Compare, Allocator, PageSize >& x, const BTree< Key, T, Compare, Allocator, PageSize >& y) { return y < x; } template < typename Key, typename T, typename Compare, typename Allocator, size_t PageSize > bool operator>=(const BTree< Key, T, Compare, Allocator, PageSize >& x, const BTree< Key, T, Compare, Allocator, PageSize >& y) { return !( x < y ); } template < typename Key, typename T, typename Compare, typename Allocator, size_t PageSize > bool operator<=(const BTree< Key, T, Compare, Allocator, PageSize >& x, const BTree< Key, T, Compare, Allocator, PageSize >& y ) { return !( x > y ); } // specialized algorithms: template < typename Key, typename T, typename Compare, typename Allocator, size_t PageSize > void swap( BTree< Key, T, Compare, Allocator, PageSize >& x, BTree< Key, T, Compare, Allocator, PageSize >& y ) { x.swap( y ); } template < typename Key, typename T, typename Compare, typename Allocator, size_t PageSize > std::ostream& operator<<( std::ostream& out, const BTree< Key, T, Compare, Allocator, PageSize >& tree ) { typedef BTree< Key, T, Compare, Allocator, PageSize > BTree; typedef std::stack< const typename BTree::Node* > NodeStack; if( tree._root == 0 ) { return out; } NodeStack stack; stack.push( tree._root ); out << "digraph BTree_" << &tree << " {\n"; out << "\tnode [ shape = record ];\n\n"; while( !stack.empty() ) { const typename BTree::Node* node = stack.top(); stack.pop(); out << "\tnode_" << node << " [ "; if( !node->leaf() ) { out << "color = red, "; } else { out << "color = black, "; } out << "label = \"{"; if( node->leaf() ) { const typename BTree::Leaf* leaf = static_cast< const typename BTree::Leaf* >( node ); out << "<head> leaf_" << leaf->data->first << " (" << leaf->size << ")" << " | { { "; for( typename BTree::const_pointer fi = leaf->data; fi != leaf->data + leaf->size; ++fi ) { if( fi != leaf->data ) { out << "| { "; } out << "<key_" << ( fi - leaf->data ) << "> " << fi->first << " | " << fi->second << " } "; } out << "} }\"];\n"; } else { const typename BTree::Body* body = static_cast< const typename BTree::Body* >( node ); out << "<head> node_" << *body->keys << " (" << body->size << ")" << "(level_" << body->level << ")" << " | { {"; out << "<key_0> previous } "; for( const typename BTree::key_type* ki = body->keys; ki != body->keys + body->size; ++ki ) { out << "| { "; out << "<key_" << ( ki - body->keys + 1) << "> " << *ki << " } "; } out << "} }\"];\n"; for( typename BTree::Node* const* ni = &body->children[0]; ni != body->children + body->size + 1; ++ni ) { out << "\tnode_" << node << ":key_" << ( ni - body->children ) << " -> node_" << *ni << ":head;\n"; stack.push( *ni ); } out << "\n"; } } out << "}"; return out; } } #endif
{ "content_hash": "201dca54a21106fa85f64d5db1972856", "timestamp": "", "source": "github", "line_count": 1212, "max_line_length": 76, "avg_line_length": 23.155115511551156, "alnum_prop": 0.5441847206385405, "repo_name": "CPFL/gdev", "id": "d527c71204e69c01912b44f2099edf4bfa46b916", "size": "28064", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "compiler/as/ptx2sass/hydrazine/interface/BTree.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "13409306" }, { "name": "C++", "bytes": "6774313" }, { "name": "CMake", "bytes": "21006" }, { "name": "Cuda", "bytes": "47838" }, { "name": "LLVM", "bytes": "73989" }, { "name": "Makefile", "bytes": "46721" }, { "name": "Objective-C", "bytes": "24955" }, { "name": "Python", "bytes": "93614" }, { "name": "Shell", "bytes": "4252" }, { "name": "Yacc", "bytes": "77538" } ], "symlink_target": "" }
#include "test_case.h" #include <stdio.h> #include <string.h> #include <qpid/dispatch/ctools.h> #include <qpid/dispatch/bitmask.h> #include "alloc.h" typedef struct item_t { DEQ_LINKS(struct item_t); char letter; } item_t; DEQ_DECLARE(item_t, item_list_t); typedef struct multi_item_t { DEQ_LINKS(struct multi_item_t); DEQ_LINKS_N(second, struct multi_item_t); char letter; } multi_item_t; DEQ_DECLARE(multi_item_t, multi_item_list_t); static char* list_well_formed(item_list_t list, char *key) { item_t *ptr; item_t *last = 0; int size = DEQ_SIZE(list); int count = 0; char str[32]; ptr = DEQ_HEAD(list); while (ptr) { str[count] = ptr->letter; count++; if (DEQ_PREV(ptr) != last) return "Corrupt previous link"; last = ptr; ptr = DEQ_NEXT(ptr); } str[count] = '\0'; if (strcmp(str, key) != 0) return "Invalid key"; if (count != size) return "Size different from number of items (forward)"; count = 0; last = 0; ptr = DEQ_TAIL(list); while (ptr) { count++; if (DEQ_NEXT(ptr) != last) return "Corrupt next link"; last = ptr; ptr = DEQ_PREV(ptr); } if (count != size) return "Size different from number of items (backward)"; return 0; } static char* test_deq_basic(void *context) { item_list_t list; item_t item[10]; item_t *ptr; int idx; char *subtest; DEQ_INIT(list); if (DEQ_SIZE(list) != 0) return "Expected zero initial size"; for (idx = 0; idx < 10; idx++) { DEQ_ITEM_INIT(&item[idx]); item[idx].letter = 'A' + idx; DEQ_INSERT_TAIL(list, &item[idx]); } if (DEQ_SIZE(list) != 10) return "Expected 10 items in list"; ptr = DEQ_HEAD(list); if (!ptr) return "Expected valid head item"; if (DEQ_PREV(ptr)) return "Head item has non-null previous link"; if (ptr->letter != 'A') return "Expected item A at the head"; if (DEQ_NEXT(ptr) == 0) return "Head item has null next link"; subtest = list_well_formed(list, "ABCDEFGHIJ"); if (subtest) return subtest; DEQ_REMOVE_HEAD(list); if (DEQ_SIZE(list) != 9) return "Expected 9 items in list"; ptr = DEQ_HEAD(list); if (ptr->letter != 'B') return "Expected item B at the head"; subtest = list_well_formed(list, "BCDEFGHIJ"); if (subtest) return subtest; DEQ_REMOVE_TAIL(list); if (DEQ_SIZE(list) != 8) return "Expected 8 items in list"; ptr = DEQ_TAIL(list); if (ptr->letter != 'I') return "Expected item I at the tail"; subtest = list_well_formed(list, "BCDEFGHI"); if (subtest) return subtest; DEQ_REMOVE(list, &item[4]); if (DEQ_SIZE(list) != 7) return "Expected 7 items in list"; subtest = list_well_formed(list, "BCDFGHI"); if (subtest) return subtest; DEQ_REMOVE(list, &item[1]); if (DEQ_SIZE(list) != 6) return "Expected 6 items in list"; subtest = list_well_formed(list, "CDFGHI"); if (subtest) return subtest; DEQ_REMOVE(list, &item[8]); if (DEQ_SIZE(list) != 5) return "Expected 5 items in list"; subtest = list_well_formed(list, "CDFGH"); if (subtest) return subtest; DEQ_INSERT_HEAD(list, &item[8]); if (DEQ_SIZE(list) != 6) return "Expected 6 items in list"; ptr = DEQ_HEAD(list); if (ptr->letter != 'I') return "Expected item I at the head"; subtest = list_well_formed(list, "ICDFGH"); if (subtest) return subtest; DEQ_INSERT_AFTER(list, &item[4], &item[7]); if (DEQ_SIZE(list) != 7) return "Expected 7 items in list"; ptr = DEQ_TAIL(list); if (ptr->letter != 'E') return "Expected item E at the head"; subtest = list_well_formed(list, "ICDFGHE"); if (subtest) return subtest; DEQ_INSERT_AFTER(list, &item[1], &item[5]); if (DEQ_SIZE(list) != 8) return "Expected 8 items in list"; subtest = list_well_formed(list, "ICDFBGHE"); if (subtest) return subtest; if (item[0].prev || item[0].next) return "Unlisted item A has non-null pointers"; if (item[9].prev || item[9].next) return "Unlisted item J has non-null pointers"; return 0; } static char* test_deq_basic2(void *context) { item_list_t list; item_t item[10]; item_t *ptr; int idx; char *subtest; DEQ_INIT(list); if (DEQ_SIZE(list) != 0) return "Expected zero initial size"; for (idx = 0; idx < 10; idx++) { DEQ_ITEM_INIT(&item[idx]); item[idx].letter = '0' + idx; } DEQ_INSERT_TAIL(list, &item[0]); if (DEQ_SIZE(list) != 1) return "Expected 1 items in list"; subtest = list_well_formed(list, "0"); if (subtest) return subtest; ptr = DEQ_HEAD(list); DEQ_REMOVE_HEAD(list); if (ptr->letter != '0') return "Expected item '0'"; if (DEQ_SIZE(list) != 0) return "Expected 0 items in list"; DEQ_INSERT_TAIL(list, &item[0]); if (DEQ_SIZE(list) != 1) return "Expected 1 items in list"; subtest = list_well_formed(list, "0"); if (subtest) return subtest; ptr = DEQ_HEAD(list); DEQ_REMOVE_HEAD(list); if (ptr->letter != '0') return "Expected item '0'"; if (DEQ_SIZE(list) != 0) return "Expected 0 items in list"; return 0; } static char* test_deq_multi(void *context) { multi_item_list_t list1; multi_item_list_t list2; multi_item_t item[10]; multi_item_t *ptr; int idx; DEQ_INIT(list1); DEQ_INIT(list2); if (DEQ_SIZE(list1) != 0) return "Expected zero initial size 1"; if (DEQ_SIZE(list2) != 0) return "Expected zero initial size 2"; for (idx = 0; idx < 10; idx++) { DEQ_ITEM_INIT(&item[idx]); DEQ_ITEM_INIT_N(second, &item[idx]); item[idx].letter = '0' + idx; DEQ_INSERT_TAIL(list1, &item[idx]); if ((idx & 1) == 0) // even index DEQ_INSERT_TAIL_N(second, list2, &item[idx]); } if (DEQ_SIZE(list1) != 10) return "Expected list 1 size to be 10"; if (DEQ_SIZE(list2) != 5) return "Expected list 2 size to be 5"; idx = 0; while (DEQ_HEAD(list1)) { ptr = DEQ_HEAD(list1); DEQ_REMOVE_HEAD(list1); if (ptr->letter != '0' + idx) return "Incorrect value in list 1"; idx++; } idx = 0; while (DEQ_HEAD(list2)) { ptr = DEQ_HEAD(list2); DEQ_REMOVE_HEAD_N(second, list2); if (ptr->letter != '0' + idx) return "Incorrect value in list 2"; idx += 2; } return 0; } static char* test_bitmask(void *context) { qd_bitmask_t *bm; int num; int old; int c; int total; int count; bm = qd_bitmask(0); if (!bm) return "Can't allocate a bit mask"; if (qd_bitmask_first_set(bm, &num)) return "Expected no first set bit"; if (qd_bitmask_cardinality(bm) != 0) return "Expected cardinality == 0"; old = qd_bitmask_set_bit(bm, 3); if (old) return "Expected old value to be zero"; if (qd_bitmask_cardinality(bm) != 1) return "Expected cardinality == 1"; old = qd_bitmask_set_bit(bm, 3); if (!old) return "Expected old value to be one"; qd_bitmask_set_bit(bm, 100); if (qd_bitmask_cardinality(bm) != 2) return "Expected cardinality == 2"; if (!qd_bitmask_first_set(bm, &num)) return "Expected first set bit"; if (num != 3) return "Expected first set bit to be 3"; old = qd_bitmask_clear_bit(bm, num); if (!old) return "Expected old value to be one(2)"; old = qd_bitmask_clear_bit(bm, num); if (old) return "Expected old value to be zero(2)"; if (!qd_bitmask_first_set(bm, &num)) return "Expected first set bit (2)"; if (num != 100) return "Expected first set bit to be 100"; qd_bitmask_clear_bit(bm, num); if (qd_bitmask_first_set(bm, &num)) return "Expected no first set bit (2)"; qd_bitmask_set_bit(bm, 6); qd_bitmask_set_bit(bm, 2); qd_bitmask_set_bit(bm, 4); qd_bitmask_set_bit(bm, 8); qd_bitmask_set_bit(bm, 70); qd_bitmask_clear_bit(bm, 8); qd_bitmask_clear_bit(bm, 80); if (qd_bitmask_cardinality(bm) != 4) return "Expected cardinality == 4"; total = 0; count = 0; for (QD_BITMASK_EACH(bm, num, c)) { total += num; count++; } if (count != 4) return "Expected count to be 4"; if (total != 82) return "Expected bit-number total to be 82"; qd_bitmask_free(bm); return 0; } int tool_tests(void) { int result = 0; TEST_CASE(test_deq_basic, 0); TEST_CASE(test_deq_basic2, 0); TEST_CASE(test_deq_multi, 0); TEST_CASE(test_bitmask, 0); return result; }
{ "content_hash": "fdaacbd17871c146348a15ade463dc69", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 85, "avg_line_length": 29.382838283828384, "alnum_prop": 0.5694709648433113, "repo_name": "adel-boutros/qpid-dispatch", "id": "4b68edc2850a012a3cf828edad39d95c1f1c2fd0", "size": "9712", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/tool_test.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1115393" }, { "name": "C++", "bytes": "30402" }, { "name": "CMake", "bytes": "24640" }, { "name": "CSS", "bytes": "143203" }, { "name": "HTML", "bytes": "72162" }, { "name": "Java", "bytes": "1940" }, { "name": "JavaScript", "bytes": "1769068" }, { "name": "Objective-C", "bytes": "5351" }, { "name": "Python", "bytes": "772975" }, { "name": "Shell", "bytes": "19636" } ], "symlink_target": "" }
package com.netflix.spinnaker.front50.validator; import com.netflix.spinnaker.front50.model.application.Application; import java.util.Optional; import org.springframework.stereotype.Component; @Component public class HasNameValidator implements ApplicationValidator { @Override public void validate(Application application, ApplicationValidationErrors validationErrors) { if (Optional.ofNullable(application.getName()).orElse("").trim().isEmpty()) { validationErrors.rejectValue( "name", "application.name.empty", "Application must have a non-empty name"); } } }
{ "content_hash": "90e5dd457c4f1836804703084a266e6a", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 95, "avg_line_length": 37.1875, "alnum_prop": 0.7747899159663866, "repo_name": "spinnaker/front50", "id": "015d106e8272d44ca339d799942d49db1c055502", "size": "595", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "front50-core/src/main/java/com/netflix/spinnaker/front50/validator/HasNameValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "216631" }, { "name": "Java", "bytes": "502533" }, { "name": "Kotlin", "bytes": "122942" }, { "name": "Shell", "bytes": "394" }, { "name": "Slim", "bytes": "380" } ], "symlink_target": "" }
<? defined('C5_EXECUTE') or die("Access Denied."); use \Concrete\Core\Permission\Access\Entity\Entity as PermissionAccessEntity; use \Concrete\Core\Permission\Duration as PermissionDuration; use \Concrete\Core\Workflow\Workflow as Workflow; use \Concrete\Core\Tree\Node\Node as TreeNode; if ($_REQUEST['treeNodeID'] > 0) { $node = TreeNode::getByID($_REQUEST['treeNodeID']); $np = new Permissions($node); $handle = $node->getPermissionObjectKeyCategoryHandle(); if ($np->canEditTreeNodePermissions()) { if ($_REQUEST['task'] == 'add_access_entity' && Loader::helper("validation/token")->validate('add_access_entity')) { $pk = PermissionKey::getByID($_REQUEST['pkID']); $pk->setPermissionObject($node); $pa = PermissionAccess::getByID($_REQUEST['paID'], $pk); $pe = PermissionAccessEntity::getByID($_REQUEST['peID']); $pd = PermissionDuration::getByID($_REQUEST['pdID']); $pa->addListItem($pe, $pd, $_REQUEST['accessType']); } if ($_REQUEST['task'] == 'revert_to_global_node_permissions' && Loader::helper("validation/token")->validate('revert_to_global_node_permissions')) { $node->setTreeNodePermissionsToGlobal(); } if ($_REQUEST['task'] == 'override_global_node_permissions' && Loader::helper("validation/token")->validate('override_global_node_permissions')) { $node->setTreeNodePermissionsToOverride(); } if ($_REQUEST['task'] == 'remove_access_entity' && Loader::helper("validation/token")->validate('remove_access_entity')) { $pk = PermissionKey::getByID($_REQUEST['pkID']); $pk->setPermissionObject($node); $pa = PermissionAccess::getByID($_REQUEST['paID'], $pk); $pe = PermissionAccessEntity::getByID($_REQUEST['peID']); $pa->removeListItem($pe); } if ($_REQUEST['task'] == 'save_permission' && Loader::helper("validation/token")->validate('save_permission')) { $pk = PermissionKey::getByID($_REQUEST['pkID']); $pk->setPermissionObject($node); $pa = PermissionAccess::getByID($_REQUEST['paID'], $pk); $pa->save($_POST); } if ($_REQUEST['task'] == 'display_access_cell' && Loader::helper("validation/token")->validate('display_access_cell')) { $pk = PermissionKey::getByID($_REQUEST['pkID']); $pk->setPermissionObject($node); $pa = PermissionAccess::getByID($_REQUEST['paID'], $pk); Loader::element('permission/labels', array('pk' => $pk, 'pa' => $pa)); } if ($_REQUEST['task'] == 'save_permission_assignments' && Loader::helper("validation/token")->validate('save_permission_assignments')) { $permissions = PermissionKey::getList($handle); foreach($permissions as $pk) { $paID = $_POST['pkID'][$pk->getPermissionKeyID()]; $pk->setPermissionObject($node); $pt = $pk->getPermissionAssignmentObject(); $pt->clearPermissionAssignment(); if ($paID > 0) { $pa = PermissionAccess::getByID($paID, $pk); if (is_object($pa)) { $pt->assignPermissionAccess($pa); } } } } } }
{ "content_hash": "26258770cf028235e51f14965f1f1e8c", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 150, "avg_line_length": 41.40845070422535, "alnum_prop": 0.6615646258503401, "repo_name": "baardev/lbtb", "id": "46d4f7700e973bfa043ac377799d9a101f33634d", "size": "2940", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "concrete/tools/permissions/categories/tree_node.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "220905" }, { "name": "ApacheConf", "bytes": "335" }, { "name": "Batchfile", "bytes": "41" }, { "name": "CSS", "bytes": "828306" }, { "name": "JavaScript", "bytes": "792139" }, { "name": "PHP", "bytes": "6677077" }, { "name": "Shell", "bytes": "355" } ], "symlink_target": "" }
// // AppLovinAd.h // sdk // // Copyright (c) 2013, AppLovin Corporation. All rights reserved. #import <Foundation/Foundation.h> #import "ALAnnotations.h" #import "ALAdSize.h" #import "ALAdType.h" AL_ASSUME_NONNULL_BEGIN /** * This class represents an ad that has been served from the AppLovin server and * should be displayed to the user. */ @interface ALAd : NSObject <NSCopying> /** * @name Ad Properties */ /** * The size of this ad. */ @property (strong, nonatomic, readonly) ALAdSize *size; /** * The type of this ad. */ @property (strong, nonatomic, readonly) ALAdType *type; /** * The zone identifier for the ad, if any. */ @property (copy, nonatomic, readonly, alnullable) NSString *zoneIdentifier; /** * Whether or not the current ad is a video advertisement. */ @property (assign, readonly, getter=isVideoAd) BOOL videoAd; /** * Get an arbitrary ad value for a given key. The list of keys may be found * in AppLovin documentation online. */ - (alnullable NSString *)adValueForKey:(NSString *)key; /** * @name Ad Identification */ /** * A unique ID which identifies this advertisement. * * Should you need to report a broken ad to AppLovin support, please include this number's longValue. */ @property (strong, nonatomic, readonly) NSNumber *adIdNumber; @end @interface ALAd (ALDeprecated) @property (strong, readonly, getter=size, alnullable) ALAdSize *adSize __deprecated_msg("Use size property instead."); @property (strong, readonly, getter=type, alnullable) ALAdType *adType __deprecated_msg("Use type property instead."); @end AL_ASSUME_NONNULL_END
{ "content_hash": "05d3ff6bb0d7c49b40d73f70419844d2", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 118, "avg_line_length": 23.057142857142857, "alnum_prop": 0.7094175960346965, "repo_name": "soulgame/CocoaPods-TGSDK", "id": "471c704de3a9693364ce01f0fc6b1449cf15e0d3", "size": "1614", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "TGSDK/frameworks/AppLovinSDK.framework/Headers/ALAd.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6903" }, { "name": "HTML", "bytes": "820" }, { "name": "Objective-C", "bytes": "837627" }, { "name": "Ruby", "bytes": "2947" } ], "symlink_target": "" }
require 'rubygems' require 'rails' require 'json' require 'active_support' require 'action_pack' require 'action_view' require 'action_controller' require 'action_view/template' require 'active_support/core_ext/hash' require 'rspec' require 'social_buttons' SPEC_DIR = File.dirname(__FILE__)
{ "content_hash": "12626f979f52e946411eea38e39c8062", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 38, "avg_line_length": 18.5, "alnum_prop": 0.7601351351351351, "repo_name": "HomeStayTravel/social-buttons", "id": "d18c5584b17d352a3d157a5b5a5e58a48310deaf", "size": "312", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "27695" } ], "symlink_target": "" }
using Aurum.Core.Parser; using Aurum.SQL.Data; using filter = System.Func<Aurum.SQL.Data.SqlTableDetail, bool>; using query = System.Func<Aurum.SQL.Data.SqlTableDetail, string>; namespace Aurum.SQL.Templates { /// <summary> Template that can be applied to a Sql Table or View to produce a default SQL Query </summary> public class SqlQueryTemplate : SqlQueryTemplateData, ISqlQueryTemplate { internal SqlQueryTemplate(SqlQueryTemplateData data, IParser<filter> filterParser, IParser<query> queryParser) { Name = data.Name; QueryName = data.Name; Description = data.Description; IsDestructive = data.IsDestructive; AllowAutoSubquery = data.AllowAutoSubquery; QueryText = data.QueryText; FilterText = data.FilterText; //TODO: ASYNC AppliesTo = string.IsNullOrEmpty(FilterText) ? (t) => true : filterParser.Parse(FilterText).Result; //GetQuery = queryParser.Parse(QueryText); } public filter AppliesTo { get; private set; } public query GetQuery { get; private set; } } }
{ "content_hash": "c9398fd08e2f3615ae00169d74273274", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 118, "avg_line_length": 36.03125, "alnum_prop": 0.6582827406764961, "repo_name": "404htm/Aurum", "id": "26e54813c32630465be474cfb188a19dd2817483", "size": "1155", "binary": false, "copies": "1", "ref": "refs/heads/Development", "path": "Project/Aurum.SQL/Templates/SqlQueryTemplate.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "156781" }, { "name": "CSS", "bytes": "1868" }, { "name": "HTML", "bytes": "3517" } ], "symlink_target": "" }
#include <errno.h> #include <stdio.h> #include <stdlib.h> #include "sol-util-internal.h" #include "sol-log.h" #include "sol-macros.h" #include "sol-log-impl.h" #include "sol-str-table.h" /* NOTE: these are not static since we share them with sol-log-impl-*.c * to make it simpler for those to change and check these variables * without the need to resort to getters and setters. * * It also enables the sol_log_impl_init() to reset these variables, * that is done before _inited is set to true. * * See sol-log-impl-linux.c for instance, it will parse from envvars * directly to these variables, otherwise it would need to use * intermediate variables. */ struct sol_log_domain _global_domain = { .color = SOL_LOG_COLOR_WHITE, .name = "", .level = SOL_LOG_LEVEL_WARNING }; uint8_t _abort_level = SOL_LOG_LEVEL_CRITICAL; bool _show_colors = false; bool _show_file = true; bool _show_function = true; bool _show_line = true; void (*_print_function)(void *data, const struct sol_log_domain *domain, uint8_t message_level, const char *file, const char *function, int line, const char *format, va_list args) = sol_log_print_function_stderr; const void *_print_function_data = NULL; static struct sol_str_table *_env_levels = NULL; static char *_env_levels_str = NULL; static bool _inited = false; #define SOL_LOG_INIT_CHECK(fmt, ...) \ do { \ if (SOL_UNLIKELY(!_inited)) { \ fprintf(stderr, "CRITICAL:%s:%d:%s() " \ "SOL_LOG used before initialization. "fmt "\n", \ __FILE__, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__); \ abort(); \ } \ } while (0) SOL_API struct sol_log_domain *sol_log_global_domain = &_global_domain; /* used in sol-mainloop.c */ int sol_log_init(void); void sol_log_shutdown(void); int sol_log_init(void) { int r = sol_log_impl_init(); if (r == 0) _inited = true; return r; } void sol_log_shutdown(void) { sol_log_impl_shutdown(); free(_env_levels); free(_env_levels_str); _env_levels = NULL; _env_levels_str = NULL; _inited = false; } static bool _level_str_parse(const char *buf, size_t buflen, uint8_t *storage) { int16_t found; static const struct sol_str_table table[] = { SOL_STR_TABLE_ITEM("CRI", SOL_LOG_LEVEL_CRITICAL), SOL_STR_TABLE_ITEM("CRIT", SOL_LOG_LEVEL_CRITICAL), SOL_STR_TABLE_ITEM("CRITICAL", SOL_LOG_LEVEL_CRITICAL), SOL_STR_TABLE_ITEM("DBG", SOL_LOG_LEVEL_DEBUG), SOL_STR_TABLE_ITEM("DEBUG", SOL_LOG_LEVEL_DEBUG), SOL_STR_TABLE_ITEM("ERR", SOL_LOG_LEVEL_ERROR), SOL_STR_TABLE_ITEM("ERROR", SOL_LOG_LEVEL_ERROR), SOL_STR_TABLE_ITEM("INF", SOL_LOG_LEVEL_INFO), SOL_STR_TABLE_ITEM("INFO", SOL_LOG_LEVEL_INFO), SOL_STR_TABLE_ITEM("WARN", SOL_LOG_LEVEL_WARNING), SOL_STR_TABLE_ITEM("WARNING", SOL_LOG_LEVEL_WARNING), SOL_STR_TABLE_ITEM("WRN", SOL_LOG_LEVEL_WARNING), { } }; if (!sol_str_table_lookup(table, SOL_STR_SLICE_STR(buf, buflen), &found)) return false; *storage = found; return true; } static bool _int32_parse(const char *str, size_t size, int32_t *storage) { int64_t value = 0; size_t i; bool negative = false; errno = 0; for (i = 0; i < size; i++) { const char c = str[i]; if (i == 0 && c == '-') { negative = true; continue; } if (c < '0' || c > '9') break; value = (value * 10) + (c - '0'); if (value > INT32_MAX) { errno = ERANGE; return false; } } if (i == 0) { errno = EINVAL; return false; } if (negative) { value = -value; if (value < INT32_MIN) { errno = ERANGE; return false; } } *storage = value; return true; } bool sol_log_level_parse(const char *str, size_t size, uint8_t *storage) { int32_t i; uint8_t level = 0; if (size == 0) return false; if (_int32_parse(str, size, &i)) level = i; else if (!_level_str_parse(str, size, &level)) return false; *storage = level; return true; } bool sol_log_levels_parse(const char *str, size_t size) { const char *str_end = str + size; unsigned int count = 0; struct sol_str_table *itr; const char *p, *e; for (p = str; p < str_end; p++) { if (*p == ',') count++; } if (p > str) count++; free(_env_levels); free(_env_levels_str); if (count == 0) { _env_levels = NULL; _env_levels_str = NULL; return false; } _env_levels = malloc((count + 1) * sizeof(*_env_levels)); if (!_env_levels) { _env_levels_str = NULL; return false; } _env_levels_str = strndup(str, size); if (!_env_levels_str) { free(_env_levels); _env_levels = NULL; _env_levels_str = NULL; return false; } itr = _env_levels; e = NULL; str = _env_levels_str; str_end = str + size; for (p = str;; p++) { if (p < str_end && *p == ':') e = p; else if (p == str_end || *p == ',') { if (e && str + 1 < e && e + 1 < p) { uint8_t val; itr->key = str; itr->len = e - str; if (sol_log_level_parse(e + 1, p - e - 1, &val)) { itr->val = val; itr++; } } if (p == str_end) break; str = p + 1; e = NULL; } } if (itr == _env_levels) { free(_env_levels); free(_env_levels_str); _env_levels = NULL; _env_levels_str = NULL; return false; } itr->key = NULL; itr->len = 0; itr->val = 0; return true; } SOL_API void sol_log_init_level_global(const char *str, size_t length) { sol_log_level_parse(str, length, &_global_domain.level); } SOL_API void sol_log_init_levels(const char *str, size_t length) { sol_log_levels_parse(str, length); } SOL_API void sol_log_domain_init_level(struct sol_log_domain *domain) { int16_t level; SOL_LOG_INIT_CHECK("domain=%p", domain); if (!domain || !domain->name) return; if (_env_levels) { level = sol_str_table_lookup_fallback(_env_levels, sol_str_slice_from_str(domain->name), _global_domain.level); } else level = _global_domain.level; domain->level = level; } SOL_API void sol_log_print(const struct sol_log_domain *domain, uint8_t message_level, const char *file, const char *function, int line, const char *format, ...) { va_list ap; va_start(ap, format); sol_log_vprint(domain, message_level, file, function, line, format, ap); va_end(ap); } SOL_API void sol_log_vprint(const struct sol_log_domain *domain, uint8_t message_level, const char *file, const char *function, int line, const char *format, va_list args) { int errno_bkp = errno; SOL_LOG_INIT_CHECK("domain=%p, file=%s, function=%s, line=%d, fomart=%s", domain, file, function, line, format); if (!domain) domain = &_global_domain; if (!file) file = ""; if (!function) function = ""; if (!format) { fprintf(stderr, "ERROR: sol_log_print() called with format == NULL " "from function=%s, file=%s, line=%d\n", function, file, line); abort(); return; } if (message_level > domain->level) return; errno = errno_bkp; if (!sol_log_impl_lock()) { fprintf(stderr, "ERROR: sol_log_print() cannot lock " "from function=%s, file=%s, line=%d\n", function, file, line); abort(); return; } _print_function((void *)_print_function_data, domain, message_level, file, function, line, format, args); sol_log_impl_unlock(); if (message_level <= _abort_level) abort(); errno = errno_bkp; } SOL_API void sol_log_set_print_function(void (*cb)(void *data, const struct sol_log_domain *domain, uint8_t message_level, const char *file, const char *function, int line, const char *format, va_list args), const void *data) { SOL_LOG_INIT_CHECK("cb=%p, data=%p", cb, data); if (cb) { _print_function = cb; _print_function_data = data; } else { _print_function = sol_log_print_function_stderr; _print_function_data = NULL; } } SOL_API void sol_log_print_function_stderr(void *data, const struct sol_log_domain *domain, uint8_t message_level, const char *file, const char *function, int line, const char *format, va_list args) { sol_log_impl_print_function_stderr(data, domain, message_level, file, function, line, format, args); } SOL_API void sol_log_level_to_str(uint8_t level, char *buf, size_t buflen) { static const char *level_names[] = { [SOL_LOG_LEVEL_CRITICAL] = "CRI", [SOL_LOG_LEVEL_ERROR] = "ERR", [SOL_LOG_LEVEL_WARNING] = "WRN", [SOL_LOG_LEVEL_INFO] = "INF", [SOL_LOG_LEVEL_DEBUG] = "DBG" }; SOL_LOG_INIT_CHECK("level=%hhu, buf=%p, buflen=%zd", level, buf, buflen); if (buflen < 1) return; if (level < SOL_UTIL_ARRAY_SIZE(level_names)) { if (level_names[level]) { strncpy(buf, level_names[level], buflen - 1); buf[buflen - 1] = '\0'; return; } } snprintf(buf, buflen, "%03d", level); } SOL_API const char * sol_log_get_level_color(uint8_t level) { static const char *level_colors[] = { [SOL_LOG_LEVEL_CRITICAL] = SOL_LOG_COLOR_RED, [SOL_LOG_LEVEL_ERROR] = SOL_LOG_COLOR_LIGHTRED, [SOL_LOG_LEVEL_WARNING] = SOL_LOG_COLOR_ORANGE, [SOL_LOG_LEVEL_INFO] = SOL_LOG_COLOR_CYAN, [SOL_LOG_LEVEL_DEBUG] = SOL_LOG_COLOR_LIGHTBLUE }; SOL_LOG_INIT_CHECK("level=%hhu", level); if (level < SOL_UTIL_ARRAY_SIZE(level_colors)) { if (level_colors[level]) return level_colors[level]; } return SOL_LOG_COLOR_MAGENTA; } SOL_API void sol_log_set_abort_level(uint8_t level) { SOL_LOG_INIT_CHECK("level=%hhu", level); _abort_level = level; } SOL_API uint8_t sol_log_get_abort_level(void) { SOL_LOG_INIT_CHECK(""); return _abort_level; } SOL_API void sol_log_set_level(uint8_t level) { SOL_LOG_INIT_CHECK("level=%hhu", level); _global_domain.level = level; } SOL_API uint8_t sol_log_get_level(void) { SOL_LOG_INIT_CHECK(""); return _global_domain.level; } SOL_API void sol_log_set_show_colors(bool enabled) { SOL_LOG_INIT_CHECK("enabled=%hhu", enabled); _show_colors = enabled; } SOL_API bool sol_log_get_show_colors(void) { SOL_LOG_INIT_CHECK(""); return _show_colors; } SOL_API void sol_log_set_show_file(bool enabled) { SOL_LOG_INIT_CHECK("enabled=%hhu", enabled); _show_file = enabled; } SOL_API bool sol_log_get_show_file(void) { SOL_LOG_INIT_CHECK(""); return _show_file; } SOL_API void sol_log_set_show_function(bool enabled) { SOL_LOG_INIT_CHECK("enabled=%hhu", enabled); _show_function = enabled; } SOL_API bool sol_log_get_show_function(void) { SOL_LOG_INIT_CHECK(""); return _show_function; } SOL_API void sol_log_set_show_line(bool enabled) { SOL_LOG_INIT_CHECK("enabled=%hhu", enabled); _show_line = enabled; } SOL_API bool sol_log_get_show_line(void) { SOL_LOG_INIT_CHECK(""); return _show_line; }
{ "content_hash": "ce14e0d3191b738b12189d02fe4d38f9", "timestamp": "", "source": "github", "line_count": 468, "max_line_length": 212, "avg_line_length": 24.867521367521366, "alnum_prop": 0.5697714383914761, "repo_name": "nagineni/soletta", "id": "d941df73dd89c518dcbed8daf6638f40b5252d65", "size": "12311", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/lib/common/sol-log.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "3344" }, { "name": "C", "bytes": "4749448" }, { "name": "C++", "bytes": "104064" }, { "name": "JavaScript", "bytes": "50236" }, { "name": "Makefile", "bytes": "58643" }, { "name": "NSIS", "bytes": "1385" }, { "name": "Python", "bytes": "214282" }, { "name": "Shell", "bytes": "7287" }, { "name": "Smarty", "bytes": "1145" }, { "name": "VimL", "bytes": "748" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Actions; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models.Trees; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Trees; using Umbraco.Cms.Web.Common.Attributes; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Extensions; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Web.BackOffice.Trees { [PluginController(Constants.Web.Mvc.BackOfficeTreeArea)] [CoreTree] public abstract class MemberTypeAndGroupTreeControllerBase : TreeController { private readonly IMemberTypeService _memberTypeService; public IMenuItemCollectionFactory MenuItemCollectionFactory { get; } protected MemberTypeAndGroupTreeControllerBase( ILocalizedTextService localizedTextService, UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection, IMenuItemCollectionFactory menuItemCollectionFactory, IEventAggregator eventAggregator, IMemberTypeService memberTypeService) : base(localizedTextService, umbracoApiControllerTypeCollection, eventAggregator) { MenuItemCollectionFactory = menuItemCollectionFactory; _memberTypeService = memberTypeService; } [Obsolete("Use ctor injecting IMemberTypeService")] protected MemberTypeAndGroupTreeControllerBase( ILocalizedTextService localizedTextService, UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection, IMenuItemCollectionFactory menuItemCollectionFactory, IEventAggregator eventAggregator) : this( localizedTextService, umbracoApiControllerTypeCollection, menuItemCollectionFactory, eventAggregator, StaticServiceProvider.Instance.GetRequiredService<IMemberTypeService>()) { } protected override ActionResult<TreeNodeCollection> GetTreeNodes(string id, FormCollection queryStrings) { var nodes = new TreeNodeCollection(); // if the request is for folders only then just return if (queryStrings["foldersonly"].ToString().IsNullOrWhiteSpace() == false && queryStrings["foldersonly"].ToString() == "1") return nodes; nodes.AddRange(GetTreeNodesFromService(id, queryStrings)); return nodes; } protected override ActionResult<MenuItemCollection> GetMenuForNode(string id, FormCollection queryStrings) { var menu = MenuItemCollectionFactory.Create(); if (id == Constants.System.RootString) { // root actions menu.Items.Add(new CreateChildEntity(LocalizedTextService)); menu.Items.Add(new RefreshNode(LocalizedTextService, true)); return menu; } else { var memberType = _memberTypeService.Get(int.Parse(id)); if (memberType != null) { menu.Items.Add<ActionCopy>(LocalizedTextService, opensDialog: true, useLegacyIcon: false); } // delete member type/group menu.Items.Add<ActionDelete>(LocalizedTextService, opensDialog: true, useLegacyIcon: false); } return menu; } protected abstract IEnumerable<TreeNode> GetTreeNodesFromService(string id, FormCollection queryStrings); } }
{ "content_hash": "1a86d298784500ff41519c1020854310", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 134, "avg_line_length": 39.242105263157896, "alnum_prop": 0.6746244635193133, "repo_name": "KevinJump/Umbraco-CMS", "id": "8982f2d2f5d61a2ea6d38cd949da490b87c79267", "size": "3728", "binary": false, "copies": "1", "ref": "refs/heads/v10/contrib", "path": "src/Umbraco.Web.BackOffice/Trees/MemberTypeAndGroupTreeControllerBase.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "16567573" }, { "name": "CSS", "bytes": "17972" }, { "name": "Dockerfile", "bytes": "2352" }, { "name": "HTML", "bytes": "1275234" }, { "name": "JavaScript", "bytes": "4590300" }, { "name": "Less", "bytes": "688558" }, { "name": "PowerShell", "bytes": "20112" }, { "name": "Shell", "bytes": "3572" }, { "name": "TSQL", "bytes": "371" }, { "name": "TypeScript", "bytes": "123694" } ], "symlink_target": "" }
package org.apache.hadoop.hbase.snapshot; import java.io.IOException; import java.util.Collections; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.snapshot.SnapshotManifestV2; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.FSUtils; /** * Utility class to help manage {@link SnapshotDescription SnapshotDesriptions}. * <p> * Snapshots are laid out on disk like this: * * <pre> * /hbase/.snapshots * /.tmp &lt;---- working directory * /[snapshot name] &lt;----- completed snapshot * </pre> * * A completed snapshot named 'completed' then looks like (multiple regions, servers, files, etc. * signified by '...' on the same directory depth). * * <pre> * /hbase/.snapshots/completed * .snapshotinfo &lt;--- Description of the snapshot * .tableinfo &lt;--- Copy of the tableinfo * /.logs * /[server_name] * /... [log files] * ... * /[region name] &lt;---- All the region's information * .regioninfo &lt;---- Copy of the HRegionInfo * /[column family name] * /[hfile name] &lt;--- name of the hfile in the real region * ... * ... * ... * </pre> * * Utility methods in this class are useful for getting the correct locations for different parts of * the snapshot, as well as moving completed snapshots into place (see * {@link #completeSnapshot}, and writing the * {@link SnapshotDescription} to the working snapshot directory. */ public class SnapshotDescriptionUtils { /** * Filter that only accepts completed snapshot directories */ public static class CompletedSnaphotDirectoriesFilter extends FSUtils.BlackListDirFilter { /** * @param fs */ public CompletedSnaphotDirectoriesFilter(FileSystem fs) { super(fs, Collections.singletonList(SNAPSHOT_TMP_DIR_NAME)); } } private static final Log LOG = LogFactory.getLog(SnapshotDescriptionUtils.class); /** * Version of the fs layout for a snapshot. Future snapshots may have different file layouts, * which we may need to read in differently. */ public static final int SNAPSHOT_LAYOUT_VERSION = SnapshotManifestV2.DESCRIPTOR_VERSION; // snapshot directory constants /** * The file contains the snapshot basic information and it is under the directory of a snapshot. */ public static final String SNAPSHOTINFO_FILE = ".snapshotinfo"; /** Temporary directory under the snapshot directory to store in-progress snapshots */ public static final String SNAPSHOT_TMP_DIR_NAME = ".tmp"; // snapshot operation values /** Default value if no start time is specified */ public static final long NO_SNAPSHOT_START_TIME_SPECIFIED = 0; public static final String MASTER_SNAPSHOT_TIMEOUT_MILLIS = "hbase.snapshot.master.timeout.millis"; /** By default, wait 60 seconds for a snapshot to complete */ public static final long DEFAULT_MAX_WAIT_TIME = 60000; private SnapshotDescriptionUtils() { // private constructor for utility class } /** * @param conf {@link Configuration} from which to check for the timeout * @param type type of snapshot being taken * @param defaultMaxWaitTime Default amount of time to wait, if none is in the configuration * @return the max amount of time the master should wait for a snapshot to complete */ public static long getMaxMasterTimeout(Configuration conf, SnapshotDescription.Type type, long defaultMaxWaitTime) { String confKey; switch (type) { case DISABLED: default: confKey = MASTER_SNAPSHOT_TIMEOUT_MILLIS; } return conf.getLong(confKey, defaultMaxWaitTime); } /** * Get the snapshot root directory. All the snapshots are kept under this directory, i.e. * ${hbase.rootdir}/.snapshot * @param rootDir hbase root directory * @return the base directory in which all snapshots are kept */ public static Path getSnapshotRootDir(final Path rootDir) { return new Path(rootDir, HConstants.SNAPSHOT_DIR_NAME); } /** * Get the directory for a specified snapshot. This directory is a sub-directory of snapshot root * directory and all the data files for a snapshot are kept under this directory. * @param snapshot snapshot being taken * @param rootDir hbase root directory * @return the final directory for the completed snapshot */ public static Path getCompletedSnapshotDir(final SnapshotDescription snapshot, final Path rootDir) { return getCompletedSnapshotDir(snapshot.getName(), rootDir); } /** * Get the directory for a completed snapshot. This directory is a sub-directory of snapshot root * directory and all the data files for a snapshot are kept under this directory. * @param snapshotName name of the snapshot being taken * @param rootDir hbase root directory * @return the final directory for the completed snapshot */ public static Path getCompletedSnapshotDir(final String snapshotName, final Path rootDir) { return getCompletedSnapshotDir(getSnapshotsDir(rootDir), snapshotName); } /** * Get the general working directory for snapshots - where they are built, where they are * temporarily copied on export, etc. * @param rootDir root directory of the HBase installation * @return Path to the snapshot tmp directory, relative to the passed root directory */ public static Path getWorkingSnapshotDir(final Path rootDir) { return new Path(getSnapshotsDir(rootDir), SNAPSHOT_TMP_DIR_NAME); } /** * Get the directory to build a snapshot, before it is finalized * @param snapshot snapshot that will be built * @param rootDir root directory of the hbase installation * @return {@link Path} where one can build a snapshot */ public static Path getWorkingSnapshotDir(SnapshotDescription snapshot, final Path rootDir) { return getCompletedSnapshotDir(getWorkingSnapshotDir(rootDir), snapshot.getName()); } /** * Get the directory to build a snapshot, before it is finalized * @param snapshotName name of the snapshot * @param rootDir root directory of the hbase installation * @return {@link Path} where one can build a snapshot */ public static Path getWorkingSnapshotDir(String snapshotName, final Path rootDir) { return getCompletedSnapshotDir(getWorkingSnapshotDir(rootDir), snapshotName); } /** * Get the directory to store the snapshot instance * @param snapshotsDir hbase-global directory for storing all snapshots * @param snapshotName name of the snapshot to take * @return the final directory for the completed snapshot */ private static final Path getCompletedSnapshotDir(final Path snapshotsDir, String snapshotName) { return new Path(snapshotsDir, snapshotName); } /** * @param rootDir hbase root directory * @return the directory for all completed snapshots; */ public static final Path getSnapshotsDir(Path rootDir) { return new Path(rootDir, HConstants.SNAPSHOT_DIR_NAME); } /** * Convert the passed snapshot description into a 'full' snapshot description based on default * parameters, if none have been supplied. This resolves any 'optional' parameters that aren't * supplied to their default values. * @param snapshot general snapshot descriptor * @param conf Configuration to read configured snapshot defaults if snapshot is not complete * @return a valid snapshot description * @throws IllegalArgumentException if the {@link SnapshotDescription} is not a complete * {@link SnapshotDescription}. */ public static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf) throws IllegalArgumentException { if (!snapshot.hasTable()) { throw new IllegalArgumentException( "Descriptor doesn't apply to a table, so we can't build it."); } // set the creation time, if one hasn't been set long time = snapshot.getCreationTime(); if (time == SnapshotDescriptionUtils.NO_SNAPSHOT_START_TIME_SPECIFIED) { time = EnvironmentEdgeManager.currentTime(); LOG.debug("Creation time not specified, setting to:" + time + " (current time:" + EnvironmentEdgeManager.currentTime() + ")."); SnapshotDescription.Builder builder = snapshot.toBuilder(); builder.setCreationTime(time); snapshot = builder.build(); } return snapshot; } /** * Write the snapshot description into the working directory of a snapshot * @param snapshot description of the snapshot being taken * @param workingDir working directory of the snapshot * @param fs {@link FileSystem} on which the snapshot should be taken * @throws IOException if we can't reach the filesystem and the file cannot be cleaned up on * failure */ public static void writeSnapshotInfo(SnapshotDescription snapshot, Path workingDir, FileSystem fs) throws IOException { FsPermission perms = FSUtils.getFilePermissions(fs, fs.getConf(), HConstants.DATA_FILE_UMASK_KEY); Path snapshotInfo = new Path(workingDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE); try { FSDataOutputStream out = FSUtils.create(fs, snapshotInfo, perms, true); try { snapshot.writeTo(out); } finally { out.close(); } } catch (IOException e) { // if we get an exception, try to remove the snapshot info if (!fs.delete(snapshotInfo, false)) { String msg = "Couldn't delete snapshot info file: " + snapshotInfo; LOG.error(msg); throw new IOException(msg); } } } /** * Read in the {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription} stored for the snapshot in the passed directory * @param fs filesystem where the snapshot was taken * @param snapshotDir directory where the snapshot was stored * @return the stored snapshot description * @throws CorruptedSnapshotException if the * snapshot cannot be read */ public static SnapshotDescription readSnapshotInfo(FileSystem fs, Path snapshotDir) throws CorruptedSnapshotException { Path snapshotInfo = new Path(snapshotDir, SNAPSHOTINFO_FILE); try { FSDataInputStream in = null; try { in = fs.open(snapshotInfo); SnapshotDescription desc = SnapshotDescription.parseFrom(in); return desc; } finally { if (in != null) in.close(); } } catch (IOException e) { throw new CorruptedSnapshotException("Couldn't read snapshot info from:" + snapshotInfo, e); } } /** * Move the finished snapshot to its final, publicly visible directory - this marks the snapshot * as 'complete'. * @param snapshot description of the snapshot being tabken * @param rootdir root directory of the hbase installation * @param workingDir directory where the in progress snapshot was built * @param fs {@link FileSystem} where the snapshot was built * @throws org.apache.hadoop.hbase.snapshot.SnapshotCreationException if the * snapshot could not be moved * @throws IOException the filesystem could not be reached */ public static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir, FileSystem fs) throws SnapshotCreationException, IOException { Path finishedDir = getCompletedSnapshotDir(snapshot, rootdir); LOG.debug("Snapshot is done, just moving the snapshot from " + workingDir + " to " + finishedDir); if (!fs.rename(workingDir, finishedDir)) { throw new SnapshotCreationException("Failed to move working directory(" + workingDir + ") to completed directory(" + finishedDir + ").", snapshot); } } /** * Check if the user is this table snapshot's owner * @param snapshot the table snapshot description * @param user the user * @return true if the user is the owner of the snapshot, * false otherwise or the snapshot owner field is not present. */ public static boolean isSnapshotOwner(final SnapshotDescription snapshot, final User user) { if (user == null) return false; if (!snapshot.hasOwner()) return false; return snapshot.getOwner().equals(user.getShortName()); } }
{ "content_hash": "a4d0cefeef1068602c928246cfadfe84", "timestamp": "", "source": "github", "line_count": 317, "max_line_length": 147, "avg_line_length": 40.99369085173502, "alnum_prop": 0.7019622931896884, "repo_name": "SeekerResource/hbase", "id": "2fc5d83ff6125ec68776ccd1746679d8d0ad1552", "size": "13801", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/snapshot/SnapshotDescriptionUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "351" }, { "name": "Batchfile", "bytes": "24335" }, { "name": "C", "bytes": "28534" }, { "name": "C++", "bytes": "770077" }, { "name": "CMake", "bytes": "10933" }, { "name": "CSS", "bytes": "68278" }, { "name": "HTML", "bytes": "70903" }, { "name": "Java", "bytes": "26780919" }, { "name": "JavaScript", "bytes": "2694" }, { "name": "Makefile", "bytes": "1409" }, { "name": "PHP", "bytes": "413443" }, { "name": "Perl", "bytes": "383793" }, { "name": "Protocol Buffer", "bytes": "147894" }, { "name": "Python", "bytes": "539649" }, { "name": "Ruby", "bytes": "512225" }, { "name": "Shell", "bytes": "203386" }, { "name": "Thrift", "bytes": "39996" }, { "name": "XSLT", "bytes": "2892" } ], "symlink_target": "" }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace InventoryExpress.Model { /// <summary> /// Vorlage /// </summary> public class Template : ItemTag { /// <summary> /// Liefert oder setzt die Attribute /// </summary> public virtual ICollection<TemplateAttribute> TemplateAttributes { get; set; } public virtual ICollection<Inventory> Inventories { get; set; } /// <summary> /// Konstruktor /// </summary> public Template() : base() { } } }
{ "content_hash": "95cc11700d6570fb29e9be4fd409adf2", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 86, "avg_line_length": 23.576923076923077, "alnum_prop": 0.5742251223491027, "repo_name": "ReneSchwarzer/InventoryExpress", "id": "d6ec5a03a9f758dacedf243f649a0d600051f99a", "size": "615", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core/InventoryExpress/Model/Template.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "377388" }, { "name": "Shell", "bytes": "173" } ], "symlink_target": "" }