text
stringlengths
2
1.04M
meta
dict
module NLP class RIDCategory < Category def self.top_level [new(:PIERWOTNE),new(:WTORNE),new(:EMOCJE)] end def primary? root == :PIERWOTNE end def secondary? root == :WTORNE end def emotions? root == :EMOCJE end end end
{ "content_hash": "d5152d42f8990f37f23e9af7580437b9", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 49, "avg_line_length": 13.571428571428571, "alnum_prop": 0.5684210526315789, "repo_name": "knife/nlp", "id": "30bf5501087c0f818e316dca1a0274a66b9007b3", "size": "285", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/dictionaries/rid_category.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6134" }, { "name": "Perl", "bytes": "1720" }, { "name": "Prolog", "bytes": "790" }, { "name": "Ruby", "bytes": "30852" } ], "symlink_target": "" }
FactoryGirl.define do factory :user do name "User name" uid "1234567890" provider "social_network" oauth_token "token" oauth_expires_at Date.tomorrow end end
{ "content_hash": "a79718fbd8fe5b5b70e613c91c499643", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 34, "avg_line_length": 20.22222222222222, "alnum_prop": 0.6868131868131868, "repo_name": "andresilveira/gimme_a_break", "id": "494b5d25743910e8b28f066251391f604e52f0d9", "size": "252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/factories/users.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "744" }, { "name": "CoffeeScript", "bytes": "211" }, { "name": "JavaScript", "bytes": "664" }, { "name": "Ruby", "bytes": "28295" } ], "symlink_target": "" }
/* all fields */ .x-form-field { margin: 0 0 0 0; } .ext-webkit *:focus { outline: none !important; } /* ---- text fields ---- */ .x-form-text, textarea.x-form-field { padding: 1px 3px; background: repeat-x 0 0; border: 1px solid; } textarea.x-form-field { padding: 2px 3px; } .x-form-text, .ext-ie .x-form-file { height: 22px; line-height: 18px; vertical-align: middle; } .ext-ie6 .x-form-text, .ext-ie7 .x-form-text { margin: -1px 0; /* ie bogus margin bug */ height: 22px; /* ie quirks */ line-height: 18px; } .ext-ie6 .x-form-field-wrap .x-form-file-btn, .ext-ie7 .x-form-field-wrap .x-form-file-btn { top: -1px; /* because of all these margin hacks, these buttons are off by one pixel in IE6,7 */ } .ext-ie6 textarea.x-form-field, .ext-ie7 textarea.x-form-field { margin: -1px 0; /* ie bogus margin bug */ } .ext-strict .x-form-text { height: 18px; } .ext-safari.ext-mac textarea.x-form-field { margin-bottom: -2px; /* another bogus margin bug, safari/mac only */ } /* .ext-strict .ext-ie8 .x-form-text, .ext-strict .ext-ie8 textarea.x-form-field { margin-bottom: 1px; } */ .ext-gecko .x-form-text, .ext-ie8 .x-form-text { padding-top: 2px; /* FF won't center the text vertically */ padding-bottom: 0; } .ext-ie6 .x-form-composite .x-form-text.x-box-item, .ext-ie7 .x-form-composite .x-form-text.x-box-item { margin: 0 !important; /* clear ie bogus margin bug fix */ } textarea { resize: none; /* Disable browser resizable textarea */ } /* select boxes */ .x-form-select-one { height: 20px; line-height: 18px; vertical-align: middle; border: 1px solid; } /* multi select boxes */ /* --- TODO --- */ /* 2.0.2 style */ .x-form-check-wrap { line-height: 18px; height: auto; } .ext-ie .x-form-check-wrap input { width: 15px; height: 15px; } .x-form-check-wrap input { vertical-align: bottom; } .x-editor .x-form-check-wrap { padding: 3px; } .x-editor .x-form-checkbox { height: 13px; } .x-form-check-group-label { border-bottom: 1px solid; margin-bottom: 5px; padding-left: 3px !important; float: none !important; } /* wrapped fields and triggers */ .x-form-field-wrap .x-form-trigger { width: 17px; height: 21px; border: 0; background: transparent no-repeat 0 0; cursor: pointer; border-bottom: 1px solid; position: absolute; top: 0; } .x-form-field-wrap .x-form-date-trigger, .x-form-field-wrap .x-form-clear-trigger, .x-form-field-wrap .x-form-search-trigger { cursor: pointer; } .x-form-field-wrap .x-form-twin-triggers .x-form-trigger { position: static; top: auto; vertical-align: top; } .x-form-field-wrap { position: relative; left: 0; top: 0; text-align: left; zoom: 1; white-space: nowrap; } .ext-strict .ext-ie8 .x-toolbar-cell .x-form-field-trigger-wrap .x-form-trigger { right: 0; /* IE8 Strict mode trigger bug */ } .x-form-field-wrap .x-form-trigger-over { background-position: -17px 0; } .x-form-field-wrap .x-form-trigger-click { background-position: -34px 0; } .x-trigger-wrap-focus .x-form-trigger { background-position: -51px 0; } .x-trigger-wrap-focus .x-form-trigger-over { background-position: -68px 0; } .x-trigger-wrap-focus .x-form-trigger-click { background-position: -85px 0; } .x-trigger-wrap-focus .x-form-trigger { border-bottom: 1px solid; } .x-item-disabled .x-form-trigger-over { background-position: 0 0 !important; border-bottom: 1px solid; } .x-item-disabled .x-form-trigger-click { background-position: 0 0 !important; border-bottom: 1px solid; } .x-trigger-noedit { cursor: pointer; } /* field focus style */ .x-form-focus, textarea.x-form-focus { border: 1px solid; } /* invalid fields */ .x-form-invalid, textarea.x-form-invalid { background: repeat-x bottom; border: 1px solid; } .x-form-inner-invalid, textarea.x-form-inner-invalid { background: repeat-x bottom; } /* editors */ .x-editor { visibility: hidden; padding: 0; margin: 0; } .x-form-grow-sizer { left: -10000px; padding: 8px 3px; position: absolute; visibility: hidden; top: -10000px; white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; word-wrap: break-word; zoom: 1; } .x-form-grow-sizer p { margin: 0 !important; border: 0 none !important; padding: 0 !important; } /* Form Items CSS */ .x-form-item { display: block; margin-bottom: 4px; zoom: 1; } .x-form-item label.x-form-item-label { display: block; float: left; width: 100px; padding: 3px; padding-left: 0; clear: left; z-index: 2; position: relative; } .x-form-element { padding-left: 105px; position: relative; } .x-form-invalid-msg { padding: 2px; padding-left: 18px; background: transparent no-repeat 0 2px; line-height: 16px; width: 200px; } .x-form-label-left label.x-form-item-label { text-align: left; } .x-form-label-right label.x-form-item-label { text-align: right; } .x-form-label-top .x-form-item label.x-form-item-label { width: auto; float: none; clear: none; display: inline; margin-bottom: 4px; position: static; } .x-form-label-top .x-form-element { padding-left: 0; padding-top: 4px; } .x-form-label-top .x-form-item { padding-bottom: 4px; } /* Editor small font for grid, toolbar and tree */ .x-small-editor .x-form-text { height: 20px; line-height: 16px; vertical-align: middle; } .ext-ie6 .x-small-editor .x-form-text, .ext-ie7 .x-small-editor .x-form-text { margin-top: -1px !important; /* ie bogus margin bug */ margin-bottom: -1px !important; height: 20px !important; /* ie quirks */ line-height: 16px !important; } .ext-strict .x-small-editor .x-form-text { height: 16px !important; } .ext-ie6 .x-small-editor .x-form-text, .ext-ie7 .x-small-editor .x-form-text { height: 20px; line-height: 16px; } .ext-border-box .x-small-editor .x-form-text { height: 20px; } .x-small-editor .x-form-select-one { height: 20px; line-height: 16px; vertical-align: middle; } .x-small-editor .x-form-num-field { text-align: right; } .x-small-editor .x-form-field-wrap .x-form-trigger { height: 19px; } .ext-webkit .x-small-editor .x-form-field-wrap .x-form-trigger { height: 21px; } .ext-webkit .x-small-editor .x-form-text { padding-top: 3px; font-size: 100%; } .x-form-clear { clear: both; height: 0; overflow: hidden; line-height: 0; font-size: 0; } .x-form-clear-left { clear: left; height: 0; overflow: hidden; line-height: 0; font-size: 0; } .ext-ie6 .x-form-check-wrap input, .ext-border-box .x-form-check-wrap input { margin-top: 3px; } .x-form-cb-label { position: relative; margin-left: 4px; top: 2px; } .ext-ie .x-form-cb-label { top: 1px; } .ext-ie6 .x-form-cb-label, .ext-border-box .x-form-cb-label { top: 3px; } .x-form-display-field { padding-top: 2px; } .ext-gecko .x-form-display-field, .ext-strict .ext-ie7 .x-form-display-field { padding-top: 1px; } .ext-ie .x-form-display-field { padding-top: 3px; } .ext-strict .ext-ie8 .x-form-display-field { padding-top: 0; } .x-form-column { float: left; padding: 0; margin: 0; width: 48%; overflow: hidden; zoom: 1; } /* buttons */ .x-form .x-form-btns-ct .x-btn { float: right; clear: none; } .x-form .x-form-btns-ct .x-form-btns td { border: 0; padding: 0; } .x-form .x-form-btns-ct .x-form-btns-right table { float: right; clear: none; } .x-form .x-form-btns-ct .x-form-btns-left table { float: left; clear: none; } .x-form .x-form-btns-ct .x-form-btns-center { text-align: center; /*ie*/ } .x-form .x-form-btns-ct .x-form-btns-center table { margin: 0 auto; /*everyone else*/ } .x-form .x-form-btns-ct table td.x-form-btn-td { padding: 3px; } .x-form .x-form-btns-ct .x-btn-focus .x-btn-left { background-position: 0 -147px; } .x-form .x-form-btns-ct .x-btn-focus .x-btn-right { background-position: 0 -168px; } .x-form .x-form-btns-ct .x-btn-focus .x-btn-center { background-position: 0 -189px; } .x-form .x-form-btns-ct .x-btn-click .x-btn-center { background-position: 0 -126px; } .x-form .x-form-btns-ct .x-btn-click .x-btn-right { background-position: 0 -84px; } .x-form .x-form-btns-ct .x-btn-click .x-btn-left { background-position: 0 -63px; } .x-form-invalid-icon { width: 16px; height: 18px; visibility: hidden; position: absolute; left: 0; top: 0; display: block; background: transparent no-repeat 0 2px; } /* fieldsets */ .x-fieldset { border: 1px solid; padding: 10px; margin-bottom: 10px; display: block; /* preserve margins in IE */ } /* make top of checkbox/tools visible in webkit */ .ext-webkit .x-fieldset-header { padding-top: 1px; } .ext-ie .x-fieldset legend { margin-bottom: 10px; } .ext-ie .x-fieldset { padding-top: 0; padding-bottom: 10px; } .x-fieldset legend .x-tool-toggle { margin-right: 3px; margin-left: 0; float: left !important; } .x-fieldset legend input { margin-right: 3px; float: left !important; height: 13px; width: 13px; } fieldset.x-panel-collapsed { padding-bottom: 0 !important; border-width: 1px 1px 0 1px !important; border-left-color: transparent; border-right-color: transparent; } .ext-ie6 fieldset.x-panel-collapsed { padding-bottom: 0 !important; border-width: 1px 0 0 0 !important; margin-left: 1px; margin-right: 1px; } fieldset.x-panel-collapsed .x-fieldset-bwrap { visibility: hidden; position: absolute; left: -1000px; top: -1000px; } .ext-ie .x-fieldset-bwrap { zoom: 1; } .x-fieldset-noborder { border: 0px none transparent; } .x-fieldset-noborder legend { margin-left: -3px; } /* IE legend positioning bug */ .ext-ie .x-fieldset-noborder legend { position: relative; margin-bottom: 23px; } .ext-ie .x-fieldset-noborder legend span { position: absolute; left: 16px; } .ext-gecko .x-window-body .x-form-item { -moz-outline: none; outline: none; overflow: auto; } .ext-mac.ext-gecko .x-window-body .x-form-item { overflow: hidden; } .ext-gecko .x-form-item { -moz-outline: none; outline: none; } .x-hide-label label.x-form-item-label { display: none; } .x-hide-label .x-form-element { padding-left: 0 !important; } .x-form-label-top .x-hide-label label.x-form-item-label { display: none; } .x-fieldset { overflow: hidden; } .x-fieldset-bwrap { overflow: hidden; zoom: 1; } .x-fieldset-body { overflow: hidden; }
{ "content_hash": "a4f53ff9fb3a4e40c9ed5f2db70297b6", "timestamp": "", "source": "github", "line_count": 482, "max_line_length": 126, "avg_line_length": 21.690871369294605, "alnum_prop": 0.6540411286465806, "repo_name": "csgf/glibrary-repo-browser-portlet", "id": "aff82352b6ae689c84cef10bbba00f64d0c33ba0", "size": "10579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docroot/html/css/ext-js/resources/css/structure/.sass-cache/form.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3346719" }, { "name": "Java", "bytes": "50711" }, { "name": "JavaScript", "bytes": "4568062" } ], "symlink_target": "" }
 #include <aws/billingconductor/model/DeletePricingRuleRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::BillingConductor::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DeletePricingRuleRequest::DeletePricingRuleRequest() : m_arnHasBeenSet(false) { } Aws::String DeletePricingRuleRequest::SerializePayload() const { JsonValue payload; if(m_arnHasBeenSet) { payload.WithString("Arn", m_arn); } return payload.View().WriteReadable(); }
{ "content_hash": "bf70559605efc8b0cdfbc4576651ca74", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 64, "avg_line_length": 16.78125, "alnum_prop": 0.7467411545623837, "repo_name": "cedral/aws-sdk-cpp", "id": "745781948fb32ee1bdc18b45583312dd93da18f9", "size": "656", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-cpp-sdk-billingconductor/source/model/DeletePricingRuleRequest.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ChartsModule } from 'ng2-charts'; import { TechniquesChartComponent } from './techniques-chart.component'; import { SummaryCalculationService } from '../../summary-calculation.service'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; describe('TechniquesChartComponent', () => { let component: TechniquesChartComponent; let fixture: ComponentFixture<TechniquesChartComponent>; const serviceMock = { barColors: ['color'], sophisticationNumberToWord: number => 'word', riskSub: new BehaviorSubject<number>(null), techniqueBreakdown: { a: '1', c: '.33' }, renderLegend: () => 'legend stuff' }; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [TechniquesChartComponent], imports: [ChartsModule], providers: [ { provide: SummaryCalculationService, useValue: serviceMock } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TechniquesChartComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should generate appropriate values', () => { expect(component.barChartData[0].data[0]).toBe(100); expect(component.barChartData[0].data[1]).toBe(33); }) });
{ "content_hash": "3c54895aa67ba90bacb8fa109f4ed256", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 157, "avg_line_length": 32.34090909090909, "alnum_prop": 0.6725228390723823, "repo_name": "unfetter-discover/unfetter-ui", "id": "b2ab399ed5eff53dbb2ea4b66245c9fbb9e22252", "size": "1423", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/app/baseline/result/summary/summary-report/techniques-chart/techniques-chart.component.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "141878" }, { "name": "Dockerfile", "bytes": "1707" }, { "name": "HTML", "bytes": "497299" }, { "name": "JavaScript", "bytes": "4883" }, { "name": "Shell", "bytes": "595" }, { "name": "TypeScript", "bytes": "2672398" } ], "symlink_target": "" }
 (function (definition, window) { if (window.breeze) { definition(window.breeze); } else if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { // CommonJS or Node var b = require('breeze'); definition(b); } else if (typeof define === "function" && define["amd"] && !window.breeze) { // Requirejs / AMD define(['breeze'], definition); } else { throw new Error("Can't find breeze"); } }(function (breeze) { "use strict"; var ctor = function () { }; breeze.AbstractRestDataServiceAdapter = ctor; // borrow from the AbstractDataServiceAdapter var abstractDsaProto = breeze.AbstractDataServiceAdapter.prototype; ctor.prototype = { // Breeze DataService API executeQuery: executeQuery, fetchMetadata: fetchMetadata, initialize: initialize, saveChanges: saveChanges, // Configuration API ChangeRequestInterceptor: abstractDsaProto.changeRequestInterceptor, // default, no-op ctor checkForRecomposition: checkForRecomposition, saveOnlyOne: false, // true if may only save one entity at a time. ignoreDeleteNotFound: true, // true if should ignore a 404 error from a delete // "protected" members available to derived concrete dataservice adapter types _addToSaveContext: _addToSaveContext, _addKeyMapping: _addKeyMapping, _ajaxImpl: undefined, // see initialize() _catchNoConnectionError: abstractDsaProto._catchNoConnectionError, _changeRequestSucceeded: _changeRequestSucceeded, _createErrorFromResponse: _createErrorFromResponse, _createChangeRequest: _createChangeRequest, _createJsonResultsAdapter: _createJsonResultsAdapter, _clientTypeNameToServer: _clientTypeNameToServer, _getEntityTypeFromMappingContext: _getEntityTypeFromMappingContext, _getNodeEntityType: _getNodeEntityType, _getResponseData: _getResponseData, _processSavedEntity: _processSavedEntity, _serializeToJson: _serializeToJson, // serialize raw entity data to JSON for save _serverTypeNameToClient: _serverTypeNameToClient, _transformSaveValue: _transformSaveValue }; /*** Breeze DataService API ***/ function initialize() { var adapter = this; var ajaxImpl = adapter._ajaxImpl = breeze.config.getAdapterInstance("ajax"); if (!ajaxImpl) { throw new Error("Unable to initialize ajax for " + adapter.name); } var ajax = ajaxImpl.ajax; if (!ajax) { throw new Error("Breeze was unable to find an 'ajax' adapter for " + adapter.name); } adapter.Q = breeze.Q; // adapter.Q is for backward compat if (!adapter.jsonResultsAdapter) { adapter.jsonResultsAdapter = adapter._createJsonResultsAdapter(); } } function checkForRecomposition(interfaceInitializedArgs) { if (interfaceInitializedArgs.interfaceName === "ajax" && interfaceInitializedArgs.isDefault) { this.initialize(); } } function executeQuery(mappingContext) { var adapter = this; var deferred = adapter.Q.defer(); var url = mappingContext.getUrl(); var headers = { 'Accept': 'application/json' }; adapter._ajaxImpl.ajax({ type: "GET", url: url, headers: headers, params: mappingContext.query.parameters, success: querySuccess, error: function (response) { deferred.reject(adapter._createErrorFromResponse(response, url, mappingContext)); } }); return deferred.promise; function querySuccess(response) { try { var rData = { results: adapter._getResponseData(response).results, httpResponse: response }; deferred.resolve(rData); } catch (e) { // program error means adapter it broken, not SP or the user deferred.reject(new Error("Program error: failed while parsing successful query response")); } } } function fetchMetadata() { throw new Error("Cannot process server metadata; create your own and use that instead"); } function saveChanges(saveContext, saveBundle) { var adapter = saveContext.adapter = this; var Q = adapter.Q; try { if (adapter.saveOnlyOne && saveBundle.entities.length > 1) { return Q.reject(new Error("Only one entity may be saved at a time.")); } adapter._addToSaveContext(saveContext); var requests = createChangeRequests(saveContext, saveBundle); var promises = sendChangeRequests(saveContext, requests); var comboPromise = Q.all(promises); return comboPromise .then(reviewSaveResult) .then(null, saveFailed); } catch (err) { return Q.reject(err); } function reviewSaveResult(/* promiseValues */) { var saveResult = saveContext.saveResult; var entitiesWithErrors = saveResult.entitiesWithErrors; var errorCount = entitiesWithErrors.length; if (!errorCount) { return saveResult; } // all good // at least one request failed; process those that succeeded saveContext.processSavedEntities(saveResult); var error; // Compose error; promote the first error when one or all fail if (requests.length === 1 || requests.length === errorCount) { // When all fail, good chance the first error is the same reason for all error = entitiesWithErrors[0].error; } else { error = new Error("\n The save failed although some entities were saved."); } error.message = (error.message || "Save failed") + " \n See 'error.saveResult' for more details.\n"; error.saveResult = saveResult; return Q.reject(error); } function saveFailed(error) { return Q.reject(error); } } /*** Members a derived Type might use or replace ***/ function _addToSaveContext(/* saveContext */) { } function _addKeyMapping(saveContext, index, saved){ var tempKey = saveContext.tempKeys[index]; if (tempKey) { // entity had a temporary key; add a temp-to-perm key mapping var entityType = tempKey.entityType; var tempValue = tempKey.values[0]; var realKey = getRealKey(entityType, saved); var keyMapping = { entityTypeName: entityType.name, tempValue: tempValue, realValue: realKey.values[0] }; saveContext.saveResult.keyMappings.push(keyMapping); } } function _clientTypeNameToServer(typeName) { var jrAdapter = this.jsonResultsAdapter; return jrAdapter.clientTypeNameToServer ? jrAdapter.clientTypeNameToServer(typeName) : typeName; } function _createChangeRequest(/* saveContext, entity, index */) { throw new Error("Need a concrete implementation of _createChangeRequest"); } // Create error object for both query and save responses. // 'context' can help differentiate query and save // 'errorEntity' only defined for save response function _createErrorFromResponse(response, url, context, errorEntity) { var err = new Error(); err.response = response; if (url) { err.url = url; } err.status = response.status || '???'; err.statusText = response.statusText; err.message = response.message || response.error || response.statusText; fn_.catchNoConnectionError(err); return err; } function _createJsonResultsAdapter(/*dataServiceAdapter*/) { return new breeze.JsonResultsAdapter({ name: "noop", visitNode: function (/*node, mappingContext, nodeContext*/) { return {}; } }); } function _getEntityTypeFromMappingContext(mappingContext) { var query = mappingContext.query; if (!query) {return null;} var entityType = query.entityType || query.resultEntityType; if (!entityType) { // try to figure it out from the query.resourceName var metadataStore = mappingContext.metadataStore; var etName = metadataStore.getEntityTypeNameForResourceName(query.resourceName); if (etName) { entityType = metadataStore.getEntityType(etName); } } return entityType; } function _getNodeEntityType(mappingContext, typeName) { // Get the EntityType corresponding to the typeName // A utility for implementation of jsonResultsAdapter.visitNode // typeName: a string on the node that identifies the type of the raw data // // This method memoizes the type names it encounters // by adding a 'typeMap' object to the JsonResultsAdapter. if (!typeName) { return undefined; } var jsonResultsAdapter = mappingContext.jsonResultsAdapter; var typeMap = jsonResultsAdapter.typeMap; if (!typeMap) { // if missing, make one with a fallback mapping typeMap = { "": { _mappedPropertiesCount: NaN } }; jsonResultsAdapter.typeMap = typeMap; } var entityType = typeMap[typeName]; // EntityType for a node with this metadata.type if (!entityType) { // Haven't see this typeName before; add it to the typeMap // Figure out what EntityType this is and remember it entityType = mappingContext.metadataStore.getEntityType(typeName, true); typeMap[typeName] = entityType || typeMap[""]; } return entityType; } function _getResponseData(response) { return response.data; } function _processSavedEntity(/*savedEntity, response, saveContext, index*/){ // Virtual method. Override in concrete adapter if needed. } function _serializeToJson(rawEntityData) { // Serialize raw entity data to JSON during save // You could override this default version // Note that DataJS has an amazingly complex set of tricks for this, // all of them depending on metadata attached to the property values // which breeze entity data never have. return JSON.stringify(rawEntityData); } function _serverTypeNameToClient(mappingContext, typeName) { var jrAdapter = mappingContext.jsonResultsAdapter; return jrAdapter.serverTypeNameToClient ? jrAdapter.serverTypeNameToClient(typeName) : typeName; } function _transformSaveValue(prop, val) { // prepare a property value for save by transforming it if (prop.isUnmapped) { return undefined; } if (prop.dataType === breeze.DataType.DateTimeOffset) { // The datajs lib tries to treat client dateTimes that are defined as DateTimeOffset on the server differently // from other dateTimes. This fix compensates before the save. // TODO: If not using datajs (and this adapter doesn't) is this necessary? val = val && new Date(val.getTime() - (val.getTimezoneOffset() * 60000)); } else if (prop.dataType.quoteJsonOData) { val = val != null ? val.toString() : val; } return val; } /*** private members ***/ function createChangeRequests(saveContext, saveBundle) { var adapter = saveContext.adapter; var originalEntities = saveContext.originalEntities = saveBundle.entities; saveContext.tempKeys = []; var changeRequestInterceptor = abstractDsaProto._createChangeRequestInterceptor(saveContext, saveBundle); var requests = originalEntities.map(function (entity, index) { var request = adapter._createChangeRequest(saveContext, entity, index); return changeRequestInterceptor.getRequest(request, entity, index); }); changeRequestInterceptor.done(requests); return requests; } function getRealKey(entityType, rawEntity) { return entityType.getEntityKeyFromRawEntity(rawEntity, breeze.DataProperty.getRawValueFromServer); } function sendChangeRequests(saveContext, requests) { // Sends each prepared save request and processes the promised results // returns a single "comboPromise" that waits for the individual promises to complete // Todo: What happens when there are a gazillion async requests? var saveResult = { entities: [], entitiesWithErrors: [], keyMappings: [] }; saveContext.saveResult = saveResult; return requests.map(function (request, index) { return sendChangeRequest(saveContext, request, index); }); } function sendChangeRequest(saveContext, request, index) { var adapter = saveContext.adapter; var deferred = adapter.Q.defer(); var url = request.requestUri; adapter._ajaxImpl.ajax({ url: url, type: request.method, headers: request.headers, data: request.data, success: tryRequestSucceeded, error: tryRequestFailed }); return deferred.promise; function tryRequestSucceeded(response) { try { var status = +response.status; if ((!status) || status >= 400) { tryRequestFailed(response); } else { var savedEntity = adapter._changeRequestSucceeded(saveContext, response, index); adapter._processSavedEntity(savedEntity, response, saveContext, index); deferred.resolve(true); } } catch (e) { // program error means adapter is broken, not remote server or the user deferred.reject("Program error: failed while processing successful save response"); } } function tryRequestFailed(response) { try { var status = +response.status; if (status && status === 404 && adapter.ignoreDeleteNotFound && saveContext.originalEntities[index].entityAspect.entityState.isDeleted()) { // deleted entity not found; treat as if successfully deleted. response.status = 204; response.statusText = 'resource was already deleted; no content'; response.data = undefined; tryRequestSucceeded(response); } else { // Do NOT fail saveChanges at the request level var errorEntity = saveContext.originalEntities[index]; saveContext.saveResult.entitiesWithErrors.push({ entity: errorEntity, error: adapter._createErrorFromResponse(response, url, saveContext, errorEntity) }); deferred.resolve(false); } } catch (e) { // program error means adapter is broken, not remote server or the user deferred.reject("Program error: failed while processing save error"); } } } function _changeRequestSucceeded(saveContext, response, index) { var saved = saveContext.adapter._getResponseData(response); if (saved && typeof saved === 'object') { // Have "saved entity" data; add its type (for JsonResultsAdapter) & KeyMapping saved.$entityType = saveContext.originalEntities[index].entityType; saveContext.adapter._addKeyMapping(saveContext, index, saved); } else { // No "saved entity" data; return the original entity saved = saveContext.originalEntities[index]; } saveContext.saveResult.entities.push(saved); return saved; } }, this));
{ "content_hash": "8e8e2588b83d7dbe5267b83caaafa5cc", "timestamp": "", "source": "github", "line_count": 416, "max_line_length": 122, "avg_line_length": 39.64182692307692, "alnum_prop": 0.6106361045418713, "repo_name": "JeremyNevill/firework-ng", "id": "dd3339d7fc8507cb0dab5036ade6d042f04e23fe", "size": "17756", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dist/bower_components/breezejs/labs/breeze.labs.dataservice.abstractrest.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "48278" }, { "name": "CSS", "bytes": "1411" }, { "name": "HTML", "bytes": "25520" }, { "name": "JavaScript", "bytes": "23196" }, { "name": "Shell", "bytes": "3468" }, { "name": "TypeScript", "bytes": "170334" } ], "symlink_target": "" }
/** * A mixin for groups of Focusable things (Components, Widgets, etc) that * should respond to arrow keys to navigate among the peers, but keep only * one of the peers tabbable by default (tabIndex=0) * * Some examples: Toolbars, Radio groups, Tab bars, Panel headers, Menus */ Ext.define('Ext.util.FocusableContainer', { extend: 'Ext.Mixin', requires: [ 'Ext.util.KeyNav' ], mixinConfig: { id: 'focusablecontainer', // The methods listed below are injected into the parent class // via special mixin mechanism, which makes them hard to override // in child classes. This is why these special methods are split, // and the injected wrapper will call the corresponding "doSomething" // method that is not special in any way and can be easily overridden. // The actual logic should go into the second part. before: { onAdd: 'onFocusableChildAdd', onRemove: 'onFocusableChildRemove', destroy: 'destroyFocusableContainer', onFocusEnter: 'onFocusEnter' }, after: { afterRender: 'initFocusableContainer', onFocusLeave: 'onFocusLeave', afterShow: 'activateFocusableContainerEl' } }, isFocusableContainer: true, /** * @cfg {Boolean} [enableFocusableContainer=true] Enable or disable * navigation with arrow keys for this FocusableContainer. This option may * be useful with nested FocusableContainers such as Grid column headers, * when only the root container should handle keyboard events. */ enableFocusableContainer: true, /** * @cfg {Number} [activeChildTabIndex=0] DOM tabIndex attribute to set on the * active Focusable child of this container when using the "Roaming tabindex" * technique. Set this value to > 0 to precisely control the tabbing order * of the components/containers on the page. */ activeChildTabIndex: 0, /** * @cfg {Number} [inactiveChildTabIndex=-1] DOM tabIndex attribute to set on * inactive Focusable children of this container when using the "Roaming tabindex" * technique. This value rarely needs to be changed from its default. */ inactiveChildTabIndex: -1, privates: { initFocusableContainer: function(clearChildren) { var items, i, len; // Allow nested containers to optionally disable // children containers' behavior if (this.enableFocusableContainer) { clearChildren = clearChildren != null ? clearChildren : true; this.doInitFocusableContainer(clearChildren); } // A FocusableContainer instance such as a toolbar could have decided // to opt out of FC behavior for some reason; it could have happened // after all or almost all child items have been initialized with // focusableContainer reference. We need to clean this up if we're not // going to behave like a FocusableContainer after all. else { items = this.getFocusables(); for (i = 0, len = items.length; i < len; i++) { items[i].focusableContainer = null; } } }, doInitFocusableContainer: function(clearChildren) { var me = this, el, child; el = me.getFocusableContainerEl(); // This flag allows post factum initialization of the focusable container, // i.e. when container was empty initially and then some tabbable children // were added and we need to clear their tabIndices after priming our own // element's tabIndex. // This is useful for Panel and Window headers that might have tools // added dynamically. if (clearChildren) { me.clearFocusables(); } // If we have no potentially focusable children, or all potentially focusable // children are presently disabled, don't init the container el tabIndex. // There is no point in tabbing into container when it can't shift focus // to a child. child = me.findNextFocusableChild({ step: 1, beforeRender: true }); if (child) { // We set tabIndex on the focusable container el so that the user // could tab into it; we catch its focus event and focus a child instead me.activateFocusableContainerEl(el); } // Some FCs such as Grid header containers can be dynamically reconfigured // which might leave them with no focusable children. In this case we need // to remove tab stop from the empty FC element. else if (me.isFocusableContainerActive()) { me.deactivateFocusableContainerEl(el); } // Unsightly long names help to avoid possible clashing with class // or instance properties. We have to be extra careful in a mixin! me.focusableContainerMouseListener = me.mon( el, 'mousedown', me.onFocusableContainerMousedown, me ); // Having keyNav doesn't hurt when container el is not focusable me.focusableKeyNav = me.createFocusableContainerKeyNav(el); }, createFocusableContainerKeyNav: function(el) { var me = this; return new Ext.util.KeyNav(el, { eventName: 'keydown', ignoreInputFields: true, scope: me, tab: me.onFocusableContainerTabKey, enter: me.onFocusableContainerEnterKey, space: me.onFocusableContainerSpaceKey, up: me.onFocusableContainerUpKey, down: me.onFocusableContainerDownKey, left: me.onFocusableContainerLeftKey, right: me.onFocusableContainerRightKey }); }, destroyFocusableContainer: function() { if (this.enableFocusableContainer) { this.doDestroyFocusableContainer(); } }, doDestroyFocusableContainer: function() { var me = this; if (me.keyNav) { me.keyNav.destroy(); } if (me.focusableContainerMouseListener) { me.focusableContainerMouseListener.destroy(); } me.focusableKeyNav = me.focusableContainerMouseListener = null; }, // Default FocusableContainer implies a flat list of focusable children getFocusables: function() { return this.items.items; }, initDefaultFocusable: function(beforeRender) { var me = this, activeIndex = me.activeChildTabIndex, haveFocusable = false, items, item, i, len, tabIdx; items = me.getFocusables(); len = items.length; if (!len) { return; } // Check if any child Focusable is already active. // Note that we're not determining *which* focusable child // to focus here, only that we have some focusables. for (i = 0; i < len; i++) { item = items[i]; if (item.focusable && !item.disabled) { haveFocusable = true; tabIdx = item.getTabIndex(); if (tabIdx != null && tabIdx >= activeIndex) { return item; } } } // No interactive children found, no point in going further if (!haveFocusable) { return; } // No child is focusable by default, so the first *interactive* // one gets initial childTabIndex. We are not looking for a focusable // child here because it may not be focusable yet if this happens // before rendering; we assume that an interactive child will become // focusable later and now activateFocusable() will just assign it // the respective tabIndex. item = me.findNextFocusableChild({ beforeRender: beforeRender, items: items, step: true }); if (item) { me.activateFocusable(item); } return item; }, clearFocusables: function() { var me = this, items = me.getFocusables(), len = items.length, item, i; for (i = 0; i < len; i++) { item = items[i]; if (item.focusable && !item.disabled) { me.deactivateFocusable(item); } } }, activateFocusable: function(child, /* optional */ newTabIndex) { var activeIndex = newTabIndex != null ? newTabIndex : this.activeChildTabIndex; child.setTabIndex(activeIndex); }, deactivateFocusable: function(child, /* optional */ newTabIndex) { var inactiveIndex = newTabIndex != null ? newTabIndex : this.inactiveChildTabIndex; child.setTabIndex(inactiveIndex); }, onFocusableContainerTabKey: function() { return true; }, onFocusableContainerEnterKey: function() { return true; }, onFocusableContainerSpaceKey: function() { return true; }, onFocusableContainerUpKey: function(e) { // Default action is to scroll the nearest vertically scrollable container e.preventDefault(); return this.moveChildFocus(e, false); }, onFocusableContainerDownKey: function(e) { // Ditto e.preventDefault(); return this.moveChildFocus(e, true); }, onFocusableContainerLeftKey: function(e) { // Default action is to scroll the nearest horizontally scrollable container e.preventDefault(); return this.moveChildFocus(e, false); }, onFocusableContainerRightKey: function(e) { // Ditto e.preventDefault(); return this.moveChildFocus(e, true); }, getFocusableFromEvent: function(e) { var child = Ext.Component.fromElement(e.getTarget()); //<debug> if (!child) { Ext.raise("No focusable child found for keyboard event!"); } //</debug> return child; }, moveChildFocus: function(e, forward) { var child = this.getFocusableFromEvent(e); return this.focusChild(child, forward, e); }, focusChild: function(child, forward) { var nextChild = this.findNextFocusableChild({ child: child, step: forward }); if (nextChild) { nextChild.focus(); } return nextChild; }, findNextFocusableChild: function(options) { // This method is private, so options should always be provided var beforeRender = options.beforeRender, items, item, child, step, idx, i, len; items = options.items || this.getFocusables(); step = options.step != null ? options.step : 1; child = options.child; // If the child is null or undefined, idx will be -1. // The loop below will account for that, trying to find // the first focusable child from either end (depending on step) idx = Ext.Array.indexOf(items, child); // It's often easier to pass a boolean for 1/-1 step = step === true ? 1 : step === false ? -1 : step; len = items.length; i = step > 0 ? (idx < len ? idx + step : 0) : (idx > 0 ? idx + step : len - 1); for (;; i += step) { // We're looking for the first or last focusable child // and we've reached the end of the items, so punt if (idx < 0 && (i >= len || i < 0)) { return null; } // Loop over forward else if (i >= len) { i = -1; // Iterator will increase it once more continue; } // Loop over backward else if (i < 0) { i = len; continue; } // Looped to the same item, give up else if (i === idx) { return null; } item = items[i]; if (!item || !item.focusable || item.disabled) { continue; } // This loop can be run either at FocusableContainer init time, // or later when we need to navigate upon pressing an arrow key. // When we're navigating, we have to know exactly if the child is // focusable or not, hence only rendered children will make the cut. // At the init time item.isFocusable() may return false incorrectly // just because the item has not been rendered yet and its focusEl // is not defined, so we don't bother to call isFocusable and return // the first potentially focusable child. if (beforeRender || (item.isFocusable && item.isFocusable())) { return item; } } return null; }, getFocusableContainerEl: function() { return this.el; }, activateFocusableContainerEl: function(el) { el = el || this.getFocusableContainerEl(); // Might not yet be rendered if (el) { el.set({ tabIndex: this.activeChildTabIndex }); } }, deactivateFocusableContainerEl: function(el) { el = el || this.getFocusableContainerEl(); if (el) { el.set({ tabIndex: undefined }); } }, isFocusableContainerActive: function() { var me = this, isActive = false, el, child, focusEl; el = me.getFocusableContainerEl(); if (el && el.isTabbable && el.isTabbable()) { isActive = true; } else { child = me.lastFocusedChild; focusEl = child && child.getFocusEl && child.getFocusEl(); if (focusEl && focusEl.isTabbable && focusEl.isTabbable()) { isActive = true; } } return isActive; }, onFocusableContainerMousedown: function(e, target) { var targetCmp = Ext.Component.fromElement(target); // Capture the timestamp for the mousedown. If we're navigating // into the container itself via the mouse we don't want to // default focus the first child like we would when using the keyboard. // By the time we get to the focusenter handling, we don't know what has caused // the focus to be triggered, so if the timestamp falls within some small epsilon, // the focus enter has been caused via the mouse and we can react accordingly. this.mousedownTimestamp = targetCmp === this ? Ext.Date.now() : 0; // Prevent focusing the container itself. DO NOT remove this clause, it is // untestable by our unit tests: injecting mousedown events will not cause // default action in the browser, the element never gets focus and tests // never fail. See http://www.w3.org/TR/DOM-Level-3-Events/#trusted-events // Must also check for mousedowns outside the focusable element // but still within the child component. (EXTJS-20297) if (targetCmp === this || !targetCmp.getFocusEl().contains(target)) { e.preventDefault(); } }, onFocusEnter: function(e) { var me = this, target = e.toComponent, mousedownTimestamp = me.mousedownTimestamp, epsilon = 50, child; if (!me.enableFocusableContainer) { return null; } me.mousedownTimestamp = 0; if (target === me) { if (!mousedownTimestamp || Ext.Date.now() - mousedownTimestamp > epsilon) { child = me.initDefaultFocusable(); if (child) { me.deactivateFocusableContainerEl(); child.focus(); } } } else { me.deactivateFocusableContainerEl(); } return target; }, onFocusLeave: function(e) { var me = this, lastFocused = me.lastFocusedChild; if (!me.enableFocusableContainer || me.destroying || me.destroyed) { return; } me.clearFocusables(); if (lastFocused && !lastFocused.disabled) { me.activateFocusable(lastFocused); } else { me.activateFocusableContainerEl(); } }, beforeFocusableChildBlur: Ext.privateFn, afterFocusableChildBlur: Ext.privateFn, beforeFocusableChildFocus: function(child) { var me = this; if (!me.enableFocusableContainer || me.destroying || me.destroyed) { return; } me.clearFocusables(); me.activateFocusable(child); if (child.needArrowKeys) { me.guardFocusableChild(child); } }, guardFocusableChild: function(child) { var me = this, index = me.activeChildTabIndex, guard; guard = me.findNextFocusableChild({ child: child, step: -1 }); if (guard) { guard.setTabIndex(index); } guard = me.findNextFocusableChild({ child: child, step: 1 }); if (guard) { guard.setTabIndex(index); } }, afterFocusableChildFocus: function(child) { var me = this; if (!me.enableFocusableContainer || me.destroying || me.destroyed) { return; } me.lastFocusedChild = child; }, onFocusableChildAdd: function(child) { if (this.enableFocusableContainer) { return this.doFocusableChildAdd(child); } }, doFocusableChildAdd: function(child) { if (child.focusable) { child.focusableContainer = this; } }, onFocusableChildRemove: function(child) { if (this.enableFocusableContainer) { return this.doFocusableChildRemove(child); } child.focusableContainer = null; }, doFocusableChildRemove: function(child) { // If the focused child is being removed, we reactivate the FocusableContainer // so that it returns to the tabbing order. For example, locking a grid column // must return the owning HeaderContainer to tabbability. if (child === this.lastFocusedChild) { this.lastFocusedChild = null; this.activateFocusableContainerEl(); } }, beforeFocusableChildEnable: Ext.privateFn, onFocusableChildEnable: function(child) { var me = this; if (!me.enableFocusableContainer || me.destroying || me.destroyed) { return; } // Some Components like Buttons do not render tabIndex attribute // when they start their lifecycle disabled, or remove tabIndex // if they get disabled later. Subsequently, such Components will // reset their tabIndex to default configured value upon enabling. // We don't want these children to be tabbable so we reset their // tabIndex yet again, unless this child is the last focused one. if (child !== me.lastFocusedChild) { me.deactivateFocusable(child); if (!me.isFocusableContainerActive()) { me.activateFocusableContainerEl(); } } }, beforeFocusableChildDisable: function(child) { var me = this, nextTarget; if (!me.enableFocusableContainer || me.destroying || me.destroyed) { return; } // When currently focused child is about to be disabled, // it may lose the focus as well. For example, Buttons // will remove tabIndex attribute upon disabling, which // in turn will throw focus to the document body and cause // onFocusLeave to fire on the FocusableContainer. // We're focusing the next sibling to prevent that. if (child.hasFocus) { nextTarget = me.findNextFocusableChild({ child: child }) || child.findFocusTarget(); // Note that it is entirely possible not to find the nextTarget, // e.g. when we're disabling the last button in a toolbar rendered // directly into document body. We don't have a good way to handle // such cases at present. if (nextTarget) { nextTarget.focus(); } } }, onFocusableChildDisable: function(child) { var me = this, lastFocused = me.lastFocusedChild, firstFocusableChild; if (!me.enableFocusableContainer || me.destroying || me.destroyed) { return; } // If the disabled child was the last focused item of this // FocusableContainer, we have to reset the tabbability of // our container element. if (child === lastFocused) { me.activateFocusableContainerEl(); } // It is also possible that the disabled child was the last // focusable child of this container, in which case we need // to make the container untabbable. firstFocusableChild = me.findNextFocusableChild({ step: 1 }); if (!firstFocusableChild) { me.deactivateFocusableContainerEl(); } }, beforeFocusableChildHide: function(child) { return this.beforeFocusableChildDisable(child); }, onFocusableChildHide: function(child) { return this.onFocusableChildDisable(child); }, beforeFocusableChildShow: function(child) { return this.beforeFocusableChildEnable(child); }, onFocusableChildShow: function(child) { return this.onFocusableChildEnable(child); }, // TODO onFocusableChildMasked: Ext.privateFn, onFocusableChildDestroy: Ext.privateFn, onFocusableChildUpdate: Ext.privateFn } });
{ "content_hash": "ab8a14cdc449a8c89264d29026b0dd1f", "timestamp": "", "source": "github", "line_count": 680, "max_line_length": 95, "avg_line_length": 36.669117647058826, "alnum_prop": 0.5194706236214157, "repo_name": "san4osq/bindformext", "id": "705a9dc892256de3b9561b976a84b3a003601a03", "size": "24935", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ext/classic/classic/src/util/FocusableContainer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5992109" }, { "name": "HTML", "bytes": "131719" }, { "name": "JavaScript", "bytes": "76567214" }, { "name": "Ruby", "bytes": "9357" } ], "symlink_target": "" }
package com.udmurtlyk.extrainputmethod.dictionarypack; import android.app.DownloadManager; import android.app.DownloadManager.Query; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ProgressBar; public class DictionaryDownloadProgressBar extends ProgressBar { private static final String TAG = DictionaryDownloadProgressBar.class.getSimpleName(); private static final int NOT_A_DOWNLOADMANAGER_PENDING_ID = 0; private String mClientId; private String mWordlistId; private boolean mIsCurrentlyAttachedToWindow = false; private Thread mReporterThread = null; public DictionaryDownloadProgressBar(final Context context) { super(context); } public DictionaryDownloadProgressBar(final Context context, final AttributeSet attrs) { super(context, attrs); } public void setIds(final String clientId, final String wordlistId) { mClientId = clientId; mWordlistId = wordlistId; } static private int getDownloadManagerPendingIdFromWordlistId(final Context context, final String clientId, final String wordlistId) { final SQLiteDatabase db = MetadataDbHelper.getDb(context, clientId); final ContentValues wordlistValues = MetadataDbHelper.getContentValuesOfLatestAvailableWordlistById(db, wordlistId); if (null == wordlistValues) { // We don't know anything about a word list with this id. Bug? This should never // happen, but still return to prevent a crash. Log.e(TAG, "Unexpected word list ID: " + wordlistId); return NOT_A_DOWNLOADMANAGER_PENDING_ID; } return wordlistValues.getAsInteger(MetadataDbHelper.PENDINGID_COLUMN); } /* * This method will stop any running updater thread for this progress bar and create and run * a new one only if the progress bar is visible. * Hence, as a result of calling this method, the progress bar will have an updater thread * running if and only if the progress bar is visible. */ private void updateReporterThreadRunningStatusAccordingToVisibility() { if (null != mReporterThread) mReporterThread.interrupt(); if (mIsCurrentlyAttachedToWindow && View.VISIBLE == getVisibility()) { final int downloadManagerPendingId = getDownloadManagerPendingIdFromWordlistId(getContext(), mClientId, mWordlistId); if (NOT_A_DOWNLOADMANAGER_PENDING_ID == downloadManagerPendingId) { // Can't get the ID. This is never supposed to happen, but still clear the updater // thread and return to avoid a crash. mReporterThread = null; return; } final UpdaterThread updaterThread = new UpdaterThread(getContext(), downloadManagerPendingId); updaterThread.start(); mReporterThread = updaterThread; } else { // We're not going to restart the thread anyway, so we may as well garbage collect it. mReporterThread = null; } } @Override protected void onAttachedToWindow() { mIsCurrentlyAttachedToWindow = true; updateReporterThreadRunningStatusAccordingToVisibility(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mIsCurrentlyAttachedToWindow = false; updateReporterThreadRunningStatusAccordingToVisibility(); } private class UpdaterThread extends Thread { private final static int REPORT_PERIOD = 150; // how often to report progress, in ms final DownloadManagerWrapper mDownloadManagerWrapper; final int mId; public UpdaterThread(final Context context, final int id) { super(); mDownloadManagerWrapper = new DownloadManagerWrapper(context); mId = id; } @Override public void run() { try { final UpdateHelper updateHelper = new UpdateHelper(); final Query query = new Query().setFilterById(mId); setIndeterminate(true); while (!isInterrupted()) { final Cursor cursor = mDownloadManagerWrapper.query(query); if (null == cursor) { // Can't contact DownloadManager: this should never happen. return; } try { if (cursor.moveToNext()) { final int columnBytesDownloadedSoFar = cursor.getColumnIndex( DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR); final int bytesDownloadedSoFar = cursor.getInt(columnBytesDownloadedSoFar); updateHelper.setProgressFromAnotherThread(bytesDownloadedSoFar); } else { // Download has finished and DownloadManager has already been asked to // clean up the db entry. updateHelper.setProgressFromAnotherThread(getMax()); return; } } finally { cursor.close(); } Thread.sleep(REPORT_PERIOD); } } catch (InterruptedException e) { // Do nothing and terminate normally. } } private class UpdateHelper implements Runnable { private int mProgress; @Override public void run() { setIndeterminate(false); setProgress(mProgress); } public void setProgressFromAnotherThread(final int progress) { if (mProgress != progress) { mProgress = progress; // For some unknown reason, setProgress just does not work from a separate // thread, although the code in ProgressBar looks like it should. Thus, we // resort to a runnable posted to the handler of the view. final Handler handler = getHandler(); // It's possible to come here before this view has been laid out. If so, // just ignore the call - it will be updated again later. if (null == handler) return; handler.post(this); } } } } }
{ "content_hash": "64c82cd1446e6c8cde1cb107af28d614", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 100, "avg_line_length": 43.0377358490566, "alnum_prop": 0.6048516732427298, "repo_name": "vorgoron/Multilang-Keyboard", "id": "14453c3ca01dc58a6b9414ab2ad97cc5447606b7", "size": "7458", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/java/com/udmurtlyk/extrainputmethod/dictionarypack/DictionaryDownloadProgressBar.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2591847" }, { "name": "Roff", "bytes": "695601" } ], "symlink_target": "" }
package org.apache.geode.modules.util; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.HashSet; import org.junit.Before; import org.junit.Test; import org.apache.geode.LogWriter; import org.apache.geode.cache.Cache; import org.apache.geode.cache.Region; import org.apache.geode.cache.execute.FunctionContext; import org.apache.geode.cache.execute.RegionFunctionContext; import org.apache.geode.cache.execute.ResultSender; public class TouchReplicatedRegionEntriesFunctionTest { private final TouchReplicatedRegionEntriesFunction function = spy(new TouchReplicatedRegionEntriesFunction()); private final FunctionContext context = mock(RegionFunctionContext.class); private final Cache cache = mock(Cache.class); private final LogWriter logger = mock(LogWriter.class); private final Region region = mock(Region.class); private final ResultSender resultSender = mock(ResultSender.class); private final String regionName = "regionName"; private final HashSet<String> keys = new HashSet<>(); private final Object[] arguments = new Object[] {regionName, keys}; @Before public void setUp() { when(context.getArguments()).thenReturn(arguments); when(context.getCache()).thenReturn(cache); when(context.getResultSender()).thenReturn(resultSender); when(cache.getLogger()).thenReturn(logger); when(logger.fineEnabled()).thenReturn(false); } @Test public void executeDoesNotThrowExceptionWithProperlyDefinedContext() { when(cache.getRegion(regionName)).thenReturn(region); function.execute(context); verify(region).getAll(keys); verify(resultSender).lastResult(true); } @Test public void executeDoesNotThrowExceptionWithProperlyDefinedContextAndNullRegion() { when(cache.getRegion(regionName)).thenReturn(null); function.execute(context); verify(region, times(0)).getAll(keys); verify(resultSender).lastResult(true); } }
{ "content_hash": "144f5a04bb9b05a1cf418ad462a16f6b", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 85, "avg_line_length": 33.15873015873016, "alnum_prop": 0.7740545715653423, "repo_name": "davinash/geode", "id": "f7e80c84e7211fc5fb945d8307f115bd37f5b014", "size": "2878", "binary": false, "copies": "5", "ref": "refs/heads/develop", "path": "extensions/geode-modules/src/test/java/org/apache/geode/modules/util/TouchReplicatedRegionEntriesFunctionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "106707" }, { "name": "Go", "bytes": "1205" }, { "name": "Groovy", "bytes": "2783" }, { "name": "HTML", "bytes": "3917327" }, { "name": "Java", "bytes": "28126965" }, { "name": "JavaScript", "bytes": "1781013" }, { "name": "Python", "bytes": "5014" }, { "name": "Ruby", "bytes": "6686" }, { "name": "Shell", "bytes": "46841" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models class Book(models.Model): title = models.CharField(max_length=50) year = models.PositiveIntegerField(null=True, blank=True) author = models.ForeignKey(User, verbose_name="Verbose Author", related_name='books_authored', blank=True, null=True) contributors = models.ManyToManyField(User, verbose_name="Verbose Contributors", related_name='books_contributed', blank=True, null=True) is_best_seller = models.NullBooleanField(default=0) date_registered = models.DateField(null=True) no = models.IntegerField(verbose_name='number', blank=True, null=True) # This field is intentionally 2 characters long. See #16080. def __unicode__(self): return self.title class Department(models.Model): code = models.CharField(max_length=4, unique=True) description = models.CharField(max_length=50, blank=True, null=True) def __unicode__(self): return self.description class Employee(models.Model): department = models.ForeignKey(Department, to_field="code") name = models.CharField(max_length=100) def __unicode__(self): return self.name
{ "content_hash": "ff52bbf941f49eef32921c4b6394e2bf", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 141, "avg_line_length": 38.1875, "alnum_prop": 0.7242225859247136, "repo_name": "paulproteus/django", "id": "371c67061f2435e7dd0b4b2d4ad3773f2ca386e9", "size": "1222", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "tests/regressiontests/admin_filters/models.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/**************************************************************************** * os/arch/arm/src/imxrt/imxrt_start.c * * Copyright (C) 2018 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #include <stdint.h> #include <assert.h> #include <debug.h> #include <tinyara/init.h> #include <arch/board/board.h> #include "up_arch.h" #include "up_internal.h" #include "cache.h" #ifdef CONFIG_ARCH_FPU #include "nvic.h" #endif #include "imxrt_clockconfig.h" #include "imxrt_mpuinit.h" #include "imxrt_userspace.h" #include "imxrt_start.h" #include "imxrt_gpio.h" #if defined(CONFIG_ARCH_CHIP_FAMILY_IMXRT102x) #include "chip/imxrt102x_config.h" #elif defined(CONFIG_ARCH_CHIP_FAMILY_IMXRT105x) #include "chip/imxrt105x_config.h" #else #error Unrecognized i.MX RT architecture #endif /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Memory Map ***************************************************************/ /* 0x2020:0000 - Start of on-chip RAM (OCRAM) and start of .data (_sdata) * - End of .data (_edata) and start of .bss (_sbss) * - End of .bss (_ebss) and bottom of idle stack * - _ebss + CONFIG_IDLETHREAD_STACKSIZE = end of idle stack, * start of heap. NOTE that the ARM uses a decrement before * store stack so that the correct initial value is the end of * the stack + 4; * 0x2027:ffff - End of OCRAM and end of heap (assuming 512Kb OCRAM) * * NOTE: This assumes that all internal RAM is configured for OCRAM (vs. * ITCM or DTCM). The RAM that holds .data and .bss is called the "Primary * RAM". Many other configurations are possible, including configurations * where the primary ram is in external memory. Those are not considered * here. */ #define IDLE_STACK ((uintptr_t)&_ebss + CONFIG_IDLETHREAD_STACKSIZE - 4) #define HEAP_BASE ((uintptr_t)&_ebss + CONFIG_IDLETHREAD_STACKSIZE) /**************************************************************************** * Private Function prototypes ****************************************************************************/ #ifdef CONFIG_ARCH_FPU static inline void imxrt_fpuconfig(void); #endif #ifdef CONFIG_STACK_COLORATION static void go_os_start(void *pv, unsigned int nbytes) __attribute__((naked, no_instrument_function, noreturn)); #endif /**************************************************************************** * Private Functions ****************************************************************************/ #ifdef CONFIG_ARMV7M_STACKCHECK /* we need to get r10 set before we can allow instrumentation calls */ void __start(void) __attribute__((no_instrument_function)); #endif /**************************************************************************** * Name: imxrt_fpuconfig * * Description: * Configure the FPU. Relative bit settings: * * CPACR: Enables access to CP10 and CP11 * CONTROL.FPCA: Determines whether the FP extension is active in the * current context: * FPCCR.ASPEN: Enables automatic FP state preservation, then the * processor sets this bit to 1 on successful completion of any FP * instruction. * FPCCR.LSPEN: Enables lazy context save of FP state. When this is * done, the processor reserves space on the stack for the FP state, * but does not save that state information to the stack. * * Software must not change the value of the ASPEN bit or LSPEN bit while * either: * * - the CPACR permits access to CP10 and CP11, that give access to the FP * extension, or * - the CONTROL.FPCA bit is set to 1 * ****************************************************************************/ #ifdef CONFIG_ARCH_FPU #ifndef CONFIG_ARMV7M_LAZYFPU static inline void imxrt_fpuconfig(void) { uint32_t regval; /* Set CONTROL.FPCA so that we always get the extended context frame * with the volatile FP registers stacked above the basic context. */ regval = getcontrol(); regval |= (1 << 2); setcontrol(regval); /* Ensure that FPCCR.LSPEN is disabled, so that we don't have to contend * with the lazy FP context save behavior. Clear FPCCR.ASPEN since we * are going to turn on CONTROL.FPCA for all contexts. */ regval = getreg32(NVIC_FPCCR); regval &= ~((1 << 31) | (1 << 30)); putreg32(regval, NVIC_FPCCR); /* Enable full access to CP10 and CP11 */ regval = getreg32(NVIC_CPACR); regval |= ((3 << (2 * 10)) | (3 << (2 * 11))); putreg32(regval, NVIC_CPACR); } #else static inline void imxrt_fpuconfig(void) { uint32_t regval; /* Clear CONTROL.FPCA so that we do not get the extended context frame * with the volatile FP registers stacked in the saved context. */ regval = getcontrol(); regval &= ~(1 << 2); setcontrol(regval); /* Ensure that FPCCR.LSPEN is disabled, so that we don't have to contend * with the lazy FP context save behavior. Clear FPCCR.ASPEN since we * are going to keep CONTROL.FPCA off for all contexts. */ regval = getreg32(NVIC_FPCCR); regval &= ~((1 << 31) | (1 << 30)); putreg32(regval, NVIC_FPCCR); /* Enable full access to CP10 and CP11 */ regval = getreg32(NVIC_CPACR); regval |= ((3 << (2 * 10)) | (3 << (2 * 11))); putreg32(regval, NVIC_CPACR); } #endif #else #define imxrt_fpuconfig() #endif /**************************************************************************** * Name: imxrt_tcmenable * * Description: * Enable/disable tightly coupled memories. Size of tightly coupled * memory regions is controlled by GPNVM Bits 7-8. * ****************************************************************************/ static inline void imxrt_tcmenable(void) { uint32_t regval; ARM_DSB(); ARM_ISB(); /* Enabled/disabled ITCM */ #ifdef CONFIG_ARMV7M_ITCM regval = NVIC_TCMCR_EN | NVIC_TCMCR_RMW | NVIC_TCMCR_RETEN; #else regval = getreg32(NVIC_ITCMCR); regval &= ~NVIC_TCMCR_EN; #endif putreg32(regval, NVIC_ITCMCR); /* Enabled/disabled DTCM */ #ifdef CONFIG_ARMV7M_DTCM regval = NVIC_TCMCR_EN | NVIC_TCMCR_RMW | NVIC_TCMCR_RETEN; #else regval = getreg32(NVIC_DTCMCR); regval &= ~NVIC_TCMCR_EN; #endif putreg32(regval, NVIC_DTCMCR); ARM_DSB(); ARM_ISB(); #ifdef CONFIG_ARMV7M_ITCM /* Copy TCM code from flash to ITCM */ #warning Missing logic #endif } /**************************************************************************** * Name: go_os_start * * Description: * Set the IDLE stack to the * ****************************************************************************/ #ifdef CONFIG_STACK_COLORATION static void go_os_start(void *pv, unsigned int nbytes) { /* Set the IDLE stack to the stack coloration value then jump to * os_start(). We take extreme care here because were currently * executing on this stack. * * We want to avoid sneak stack access generated by the compiler. */ __asm__ __volatile__("\tmovs r1, r1, lsr #2\n" /* R1 = nwords = nbytes >> 2 */ "\tcmp r1, #0\n" /* Check (nwords == 0) */ "\tbeq 2f\n" /* (should not happen) */ "\tbic r0, r0, #3\n" /* R0 = Aligned stackptr */ "\tmovw r2, #0xbeef\n" /* R2 = STACK_COLOR = 0xdeadbeef */ "\tmovt r2, #0xdead\n" "1:\n" /* Top of the loop */ "\tsub r1, r1, #1\n" /* R1 nwords-- */ "\tcmp r1, #0\n" /* Check (nwords == 0) */ "\tstr r2, [r0], #4\n" /* Save stack color word, increment stackptr */ "\tbne 1b\n" /* Bottom of the loop */ "2:\n" "\tmov r14, #0\n" /* LR = return address (none) */ "\tb os_start\n" /* Branch to os_start */ ); } #endif /**************************************************************************** * Public Functions ****************************************************************************/ #ifdef CONFIG_ARMV7M_DTCM /**************************************************************************** * Name: imxrt_configure_dtcm * * Description: * Make configuration to use the entire 512KB FlexRAM as DTCM * ****************************************************************************/ static void imxrt_configure_dtcm(void) { /* Configure FlexRAM banks for DTCM and 64KB OCRAM */ #if defined(CONFIG_ARCH_CHIP_FAMILY_IMXRT102x) /* It is mandatory to have at least 32KB as OCRAM to boot the board */ IOMUXC_GPR->GPR17 |= IOMUXC_GPR_GPR17_FLEXRAM_BANK_CFG(0x00005aaa); #elif defined(CONFIG_ARCH_CHIP_FAMILY_IMXRT105x) /* It is mandatory to have at least 64KB as OCRAM to boot the board */ IOMUXC_GPR->GPR17 |= IOMUXC_GPR_GPR17_FLEXRAM_BANK_CFG(0x55aaaaaa); #endif IOMUXC_GPR->GPR16 |= IOMUXC_GPR_GPR16_FLEXRAM_BANK_CFG_SEL(0x1); /* Configure and enable DTCM for 256KB */ IOMUXC_GPR->GPR16 &= ~IOMUXC_GPR_GPR16_INIT_DTCM_EN_MASK; IOMUXC_GPR->GPR14 &= ~IOMUXC_GPR_GPR14_CM7_CFGDTCMSZ_MASK; IOMUXC_GPR->GPR14 |= IOMUXC_GPR_GPR14_CM7_CFGDTCMSZ(0x9); IOMUXC_GPR->GPR16 |= IOMUXC_GPR_GPR16_INIT_DTCM_EN_MASK; /* Disable ITCM */ IOMUXC_GPR->GPR16 &= ~IOMUXC_GPR_GPR16_INIT_ITCM_EN_MASK; IOMUXC_GPR->GPR14 &= ~IOMUXC_GPR_GPR14_CM7_CFGITCMSZ_MASK; IOMUXC_GPR->GPR14 |= IOMUXC_GPR_GPR14_CM7_CFGITCMSZ(0x0); } #else /**************************************************************************** * Name: imxrt_configure_ocram * * Description: * Make configuration to use the entire 512KB FlexRAM as OCRAM * ****************************************************************************/ static void imxrt_configure_ocram(void) { /* Configure FlexRAM banks for OCRAM*/ IOMUXC_GPR->GPR17 |= IOMUXC_GPR_GPR17_FLEXRAM_BANK_CFG(0x55555555); IOMUXC_GPR->GPR16 |= IOMUXC_GPR_GPR16_FLEXRAM_BANK_CFG_SEL(0x1); /* Disable DTCM */ IOMUXC_GPR->GPR16 &= ~IOMUXC_GPR_GPR16_INIT_DTCM_EN_MASK; IOMUXC_GPR->GPR14 &= ~IOMUXC_GPR_GPR14_CM7_CFGDTCMSZ_MASK; IOMUXC_GPR->GPR14 |= IOMUXC_GPR_GPR14_CM7_CFGDTCMSZ(0x0); /* Disable ITCM */ IOMUXC_GPR->GPR16 &= ~IOMUXC_GPR_GPR16_INIT_ITCM_EN_MASK; IOMUXC_GPR->GPR14 &= ~IOMUXC_GPR_GPR14_CM7_CFGITCMSZ_MASK; IOMUXC_GPR->GPR14 |= IOMUXC_GPR_GPR14_CM7_CFGITCMSZ(0x0); } #endif /**************************************************************************** * Name: _start * * Description: * This is the reset entry point. * ****************************************************************************/ void __start(void) { const uint32_t *src; uint32_t *dest; #ifdef CONFIG_ARMV7M_DTCM imxrt_configure_dtcm(); #else imxrt_configure_ocram(); #endif #ifdef CONFIG_ARMV7M_STACKCHECK /* Set the stack limit before we attempt to call any functions */ __asm__ volatile("sub r10, sp, %0" : : "r"(CONFIG_IDLETHREAD_STACKSIZE - 64) : ); #endif /* Clear .bss. We'll do this inline (vs. calling memset) just to be * certain that there are no issues with the state of global variables. */ for (dest = &_sbss; dest < &_ebss;) { *dest++ = 0; } /* Move the initialized data section from his temporary holding spot in * FLASH into the correct place in OCRAM. The correct place in OCRAM is * give by _sdata and _edata. The temporary location is in FLASH at the * end of all of the other read-only data (.text, .rodata) at _eronly. */ for (src = &_eronly, dest = &_sdata; dest < &_edata;) { *dest++ = *src++; } /* Copy any necessary code sections from FLASH to RAM. The correct * destination in OCRAM is given by _sramfuncs and _eramfuncs. The * temporary location is in flash after the data initialization code * at _framfuncs. This should be done before imxrt_clockconfig() is * called (in case it has some dependency on initialized C variables). */ #ifdef CONFIG_ARCH_RAMFUNCS for (src = &_framfuncs, dest = &_sramfuncs; dest < &_eramfuncs;) { *dest++ = *src++; } #endif /* Configure the UART so that we can get debug output as soon as possible */ imxrt_clockconfig(); imxrt_fpuconfig(); imxrt_lowsetup(); /* Enable/disable tightly coupled memories */ imxrt_tcmenable(); /* Initialize onboard resources */ imxrt_boardinitialize(); #ifdef CONFIG_BUILD_PROTECTED /* For the case of the separate user-/kernel-space build, perform whatever * platform specific initialization of the user memory is required. * Normally this just means initializing the user space .data and .bss * segments. */ imxrt_userspace(); #endif #ifdef CONFIG_ARMV7M_MPU /* Configure the MPU to permit user-space access to its FLASH and RAM (for * CONFIG_BUILD_PROTECTED) or to manage cache properties in external * memory regions. */ imxrt_mpu_initialize(); #endif /* Enable I- and D-Caches */ arch_dcache_writethrough(); arch_enable_icache(); arch_enable_dcache(); /* Perform early serial initialization */ #ifdef USE_EARLYSERIALINIT up_earlyserialinit(); #endif /* Then start TinyARA */ #ifdef CONFIG_STACK_COLORATION /* Set the IDLE stack to the coloration value and jump into os_start() */ go_os_start((FAR void *)&_ebss, CONFIG_IDLETHREAD_STACKSIZE); #else /* Call os_start() */ os_start(); /* Shouldn't get here */ for (;;) ; #endif }
{ "content_hash": "dc3b8fdbb24b28e866357f67c062ccde", "timestamp": "", "source": "github", "line_count": 470, "max_line_length": 82, "avg_line_length": 31.65531914893617, "alnum_prop": 0.5977281892727517, "repo_name": "davidfather/TizenRT", "id": "9f810b0e6467a387aff7411a32657d7e5cb824d2", "size": "15652", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "os/arch/arm/src/imxrt/imxrt_start.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "500718" }, { "name": "Batchfile", "bytes": "42646" }, { "name": "C", "bytes": "70126141" }, { "name": "C++", "bytes": "2848554" }, { "name": "HTML", "bytes": "2990" }, { "name": "Java", "bytes": "63595" }, { "name": "Makefile", "bytes": "751563" }, { "name": "Objective-C", "bytes": "61250" }, { "name": "Perl", "bytes": "4361" }, { "name": "PowerShell", "bytes": "8511" }, { "name": "Python", "bytes": "202562" }, { "name": "Roff", "bytes": "4401" }, { "name": "Shell", "bytes": "231975" }, { "name": "Tcl", "bytes": "163693" } ], "symlink_target": "" }
package com.oculusinfo.ml.distance; import static org.junit.Assert.assertTrue; import java.util.Collections; import org.junit.Test; import com.oculusinfo.ml.feature.spatial.GeoSpatialFeature; import com.oculusinfo.ml.feature.spatial.distance.SphericalCosineDistance; public class TestSphericalCosineDistance { double epsilon = 0.00001; private boolean isEqual(double d1, double d2) { return (Math.abs( d1 - d2 ) < epsilon ); } @Test public void testIdenticalPoints() { GeoSpatialFeature t1 = new GeoSpatialFeature(); double lat = 43.650514, lon = -79.363672; t1.setValue(lat, lon); GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(lat, lon); SphericalCosineDistance d = new SphericalCosineDistance(1); double distance = d.distance(t1, t2); assertTrue(isEqual(distance, 0)); distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); System.out.println(distance); assertTrue(isEqual(distance, 0)); } @Test public void testSymmetric1() { GeoSpatialFeature t1 = new GeoSpatialFeature(); double lat = 43.650514, lon = -79.363672; t1.setValue(lat, lon); GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(lat, lon); SphericalCosineDistance d = new SphericalCosineDistance(1); double d1 = d.distance(t1, t2); double d2 = d.distance(t2, t1); assertTrue(isEqual(d1, d2)); d1 = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); d2 = d.aveMinDistance(Collections.singletonList(t2), Collections.singletonList(t1)); assertTrue(isEqual(d1, d2)); } @Test public void testDistanceSameCity() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Oculus -79.3636716??W, 43.6505143N t1.setValue(43.6505143, -79.3636716); // Etobicoke -79.5440954??W, 43.6389057??N GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(43.6389057, -79.5440954); SphericalCosineDistance d = new SphericalCosineDistance(1); double distance = d.distance(t1, t2); System.out.println(distance); assertTrue(isEqual(distance, 7.281985816507403E-4)); distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); assertTrue(isEqual(distance, 7.281985816507403E-4)); } @Test public void testSymmetric2() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Oculus -79.3636716??W, 43.6505143N t1.setValue(43.6505143, -79.3636716); // Etobicoke -79.5440954??W, 43.6389057??N GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(43.6389057, -79.5440954); SphericalCosineDistance d = new SphericalCosineDistance(1); double d1 = d.distance(t1, t2); double d2 = d.distance(t2, t1); assertTrue(isEqual(d1, d2)); d1 = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); d2 = d.aveMinDistance(Collections.singletonList(t2), Collections.singletonList(t1)); assertTrue(isEqual(d1, d2)); } @Test public void testDistanceSameProvince() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Toronto -79.3831843??W, 43.6532260??N t1.setValue(43.6532260, -79.3831843); // Waterloo -80.5204096??W, 43.4642578??N GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(43.4642578, -80.5204096); SphericalCosineDistance d = new SphericalCosineDistance(1); double distance = d.distance(t1, t2); System.out.println(distance); // assertTrue(isEqual(distance, 0)); // distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); // assertTrue(isEqual(distance, 0)); } @Test public void testSymmetric3() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Toronto -79.3831843??W, 43.6532260??N t1.setValue(43.6532260, -79.3831843); // Waterloo -80.5204096??W, 43.4642578??N GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(43.4642578, -80.5204096); SphericalCosineDistance d = new SphericalCosineDistance(1); double d1 = d.distance(t1, t2); double d2 = d.distance(t2, t1); assertTrue(isEqual(d1, d2)); d1 = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); d2 = d.aveMinDistance(Collections.singletonList(t2), Collections.singletonList(t1)); assertTrue(isEqual(d1, d2)); } @Test public void testDistanceDifferentProvinces() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Ontario -85.3232139??W, 51.2537750??N t1.setValue(51.2537750, -85.3232139); // BC -127.6476206??W, 53.7266683??N GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(53.7266683, -127.6476206); SphericalCosineDistance d = new SphericalCosineDistance(1); double distance = d.distance(t1, t2); System.out.println(distance); // assertTrue(isEqual(distance, 0)); // distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); // assertTrue(isEqual(distance, 0)); } @Test public void testSymmetric4() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Ontario -85.3232139??W, 51.2537750??N t1.setValue(51.2537750, -85.3232139); // BC -127.6476206??W, 53.7266683??N GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(53.7266683, -127.6476206); SphericalCosineDistance d = new SphericalCosineDistance(1); double d1 = d.distance(t1, t2); double d2 = d.distance(t2, t1); assertTrue(isEqual(d1, d2)); d1 = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); d2 = d.aveMinDistance(Collections.singletonList(t2), Collections.singletonList(t1)); assertTrue(isEqual(d1, d2)); } @Test public void testDistanceDifferentContintent() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Canada -106.3467710??W, 56.1303660??N t1.setValue(56.1303660, -106.3467710); // Africa 34.5085230??E, -8.7831950??S GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(-8.7831950, 34.5085230); SphericalCosineDistance d = new SphericalCosineDistance(1); double distance = d.distance(t1, t2); System.out.println(distance); // assertTrue(isEqual(distance, 0)); // distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); // assertTrue(isEqual(distance, 0)); } @Test public void testSymmetric5() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Canada -106.3467710??W, 56.1303660??N t1.setValue(56.1303660, -106.3467710); // Africa 34.5085230??E, -8.7831950??S GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(-8.7831950, 34.5085230); SphericalCosineDistance d = new SphericalCosineDistance(1); double d1 = d.distance(t1, t2); double d2 = d.distance(t2, t1); assertTrue(isEqual(d1, d2)); d1 = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); d2 = d.aveMinDistance(Collections.singletonList(t2), Collections.singletonList(t1)); assertTrue(isEqual(d1, d2)); } @Test public void testDistanceNearPoles() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Antarctica -135.0000000??W, -82.8627519??S t1.setValue(-82.8627519, -135.0000000); // Arctic 45??E, 82.8627519??N GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(82.8627519, 45); SphericalCosineDistance d = new SphericalCosineDistance(1); double distance = d.distance(t1, t2); System.out.println(distance); // assertTrue(isEqual(distance, 0)); // distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); // assertTrue(isEqual(distance, 0)); } @Test public void testSymmetric6() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // Antarctica -135.0000000??W, -82.8627519??S t1.setValue(-82.8627519, -135.0000000); // Arctic 45??E, 82.8627519??N GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(82.8627519, 45); SphericalCosineDistance d = new SphericalCosineDistance(1); double d1 = d.distance(t1, t2); double d2 = d.distance(t2, t1); assertTrue(isEqual(d1, d2)); d1 = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); d2 = d.aveMinDistance(Collections.singletonList(t2), Collections.singletonList(t1)); assertTrue(isEqual(d1, d2)); } @Test public void testDistanceOppposite() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // -106.3467710??W, 56.1303660??N t1.setValue(56.1303660, -106.3467710); // 73.653229??E, -56.130366??S GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(-56.130366, 73.653229); SphericalCosineDistance d = new SphericalCosineDistance(1); double distance = d.distance(t1, t2); System.out.println(distance); // assertTrue(isEqual(distance, 0)); // distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); // assertTrue(isEqual(distance, 0)); } @Test public void testSymmetric7() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // -106.3467710??W, 56.1303660??N t1.setValue(56.1303660, -106.3467710); // 73.653229??E, -56.130366??S GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(-56.130366, 73.653229); SphericalCosineDistance d = new SphericalCosineDistance(1); double d1 = d.distance(t1, t2); double d2 = d.distance(t2, t1); assertTrue(isEqual(d1, d2)); d1 = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); d2 = d.aveMinDistance(Collections.singletonList(t2), Collections.singletonList(t1)); assertTrue(isEqual(d1, d2)); } @SuppressWarnings("unused") @Test public void testTiming() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // -106.3467710??W, 56.1303660??N t1.setValue(56.1303660, -106.3467710); // 73.653229??E, -56.130366??S GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(-56.130366, 73.653229); SphericalCosineDistance d = new SphericalCosineDistance(1); // EuclideanDistance d = new EuclideanDistance(1); long start = System.currentTimeMillis(); double distance = 0; for (int i=0; i < 30000*3000; i++) { // distance = d.distance(t1, t2); distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); } double distanceTime = System.currentTimeMillis() - start; System.out.println("Time: " + distanceTime/1000); } @SuppressWarnings("unused") @Test public void testDistance() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // -73.995008, 40.752842 t1.setValue(-73.995008, 40.752842); // -73.994905, 40.752798 GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(-73.994905, 40.752798); SphericalCosineDistance d = new SphericalCosineDistance(1); double distance = d.distance(t1, t2); // assertTrue(isEqual(distance, 0)); // distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); // assertTrue(isEqual(distance, 0)); } @Test public void testSymmetric8() { GeoSpatialFeature t1 = new GeoSpatialFeature(); // -73.995008, 40.752842 t1.setValue(-73.995008, 40.752842); // -73.994905, 40.752798 GeoSpatialFeature t2 = new GeoSpatialFeature(); t2.setValue(-73.994905, 40.752798); SphericalCosineDistance d = new SphericalCosineDistance(1); double d1 = d.distance(t1, t2); double d2 = d.distance(t2, t1); assertTrue(isEqual(d1, d2)); d1 = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2)); d2 = d.aveMinDistance(Collections.singletonList(t2), Collections.singletonList(t1)); assertTrue(isEqual(d1, d2)); } }
{ "content_hash": "3c5865af39420901ccac03c3c65dc458", "timestamp": "", "source": "github", "line_count": 360, "max_line_length": 94, "avg_line_length": 32.03055555555556, "alnum_prop": 0.7160697250888908, "repo_name": "unchartedsoftware/ensemble-clustering", "id": "84f0a4e7dcc91cb538692aa8a7d69d59cb8e56a8", "size": "12716", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ensemble-clustering/src/test/java/com/oculusinfo/ml/distance/TestSphericalCosineDistance.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21590" }, { "name": "Java", "bytes": "738810" } ], "symlink_target": "" }
external help file: AutomatedLab-help.xml Module Name: AutomatedLab online version: https://automatedlab.org/en/latest/AutomatedLab/en-us/Remove-LabAzureResourceGroup schema: 2.0.0 --- # Remove-LabAzureResourceGroup ## SYNOPSIS Remove a resource group ## SYNTAX ``` Remove-LabAzureResourceGroup [-ResourceGroupName] <String[]> [-Force] [<CommonParameters>] ``` ## DESCRIPTION Removes one or more resource groups from Azure and from the lab cache ## EXAMPLES ### Example 1 ```powershell PS C:\> Remove-LabAzureResourceGroup -ResourceGroupName MyLab ``` Removes the resource group MyLab - usually only used in Remove-Lab ## PARAMETERS ### -Force Indicates that the resource groups should be forcibly removed ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceGroupName The resource group names ```yaml Type: String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS
{ "content_hash": "42edc458e1e53720fec48eea8e7c9e7a", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 315, "avg_line_length": 21.166666666666668, "alnum_prop": 0.7677165354330708, "repo_name": "AutomatedLab/AutomatedLab", "id": "fd968ccc474442aeadba941c5fdd8351c9a91e79", "size": "1528", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Help/AutomatedLab/en-us/Remove-LabAzureResourceGroup.md", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "2463" }, { "name": "Batchfile", "bytes": "393" }, { "name": "C#", "bytes": "381374" }, { "name": "HTML", "bytes": "466" }, { "name": "PowerShell", "bytes": "2934330" } ], "symlink_target": "" }
"use strict"; var Github = require("github"); var _ = require("lodash"); var Promise = require("bluebird"); var debug = require("debug")("github-todos:github"); var ask = require("../ask"); var config = require("../config"); /** * Format of an issue: * * type: String - "issue" * * number: Number * * url: String * * title: String * * labels: [String] * * Format of a comment: * * type: String - "comment" * * issue: Number * * url: String **/ module.exports = { "meta": { "desc": "Github issue service", "repo": "user/repository", "conf": ["github.token"] }, "connect": connect, "findIssueByTitle": findIssueByTitle, "allIssues": allIssues, "getFileUrl": getFileUrl, "createIssue": createIssue, "commentIssue": commentIssue, "tagIssue": tagIssue, "guessRepoFromUrl": guessRepoFromUrl, "validateConfig": validateConfig }; // String → {user, repo} function extractRepo (repo) { var parts = repo.split("/"); return { "user": parts[0], "repo": parts[1] }; } // Grab first issue with given title // String, String ~→ Issue function findIssueByTitle (client, repo, title) { debug("findIssueByTitle", repo, title); title = title.toLowerCase(); return allIssues(client, repo).then(_.partialRight(_.find, function (issue) { return issue.title.toLowerCase() === title; })); } // Convert a Github issue into a lighter object // Object → Issue function fromGithubIssue (issue) { if (!issue) { return null; } return { "type": "issue", "number": issue.number, "url": issue.html_url, "title": issue.title, "labels": _.pluck(issue.labels, "name") }; } // String ~→ [Issue] function allIssues (client, repo) { debug("allIssues"); return client.repoIssues(extractRepo(repo)).then(_.partialRight(_.map, fromGithubIssue)); } // Generate Github URL to blob // String, String, Sha, Number → String function getFileUrl (repo, path, sha, line) { var url = "https://github.com/" + repo + "/blob/"; if (sha) { url += sha + "/"; } url += path; if (line) { url += "#L" + line; } return url; } // String, String, String, [String] ~→ Issue function createIssue (client, repo, title, body, labels) { debug("createIssue", repo, title, body); return client.createIssue(_.merge(extractRepo(repo), { "title": title, "body": body, "labels": labels })).then(fromGithubIssue); } // String, Number, String ~→ Comment function commentIssue (client, repo, number, comment) { debug("commentIssue", repo, number, comment); return client.commentIssue(_.merge(extractRepo(repo), { "number": number, "body": comment })).then(function (comment) { return { "type": "comment", "issue": number, "url": comment.html_url }; }); } // Add a label (append, not replace) // String, Number, String ~→ Issue function tagIssue (client, repo, number, label) { debug("tagIssue", repo, number, label); client.getIssue(_.merge(extractRepo(repo), { "number": number })).then(function (issue) { var labels = _.pluck(issue.labels, "name"); if (!_.contains(labels, label)) { return client.updateIssue(_.merge(extractRepo(repo), { "number": number, "labels": labels.concat([label]) })).then(fromGithubIssue); } else { return fromGithubIssue(issue); } }); } // Authenticate to Github (will enable all other APIs) // Object ~→ void function connect (conf) { debug("connect", conf); return config.defaults().then(function (defaults) { conf = _.merge({}, defaults, conf || {}); var client = new Github({ "debug": false, "host": conf["github.host"], "protocol": conf["github.secure"] ? "https" : "http", "version": conf["github.version"] }); var token = conf["github.token"]; if (token) { debug("token found: authenticate", token); client.authenticate({ type: "oauth", token: token }); return checkToken(client); } return getToken(client); }); } function promisifyClient (client) { return { "repoIssues": Promise.promisify(client.issues.repoIssues, client.issues), "createIssue": Promise.promisify(client.issues.create, client.issues), "commentIssue": Promise.promisify(client.issues.createComment, client.issues), "getIssue": Promise.promisify(client.issues.getRepoIssue, client.issues), "updateIssue": Promise.promisify(client.issues.edit, client.issues) }; } // Check if OAuth token is still working with a simple API call // Sets CLIENT (this enables "requireClient" functions) // Client ~→ void function checkToken (client) { debug("checkToken"); return Promise.promisify(client.user.get, client.user)({}) .then(null, function (err) { console.error("Failed to validate Github OAuth token: please check API access (network?) or force re-authentication with 'github-todos auth --force'"); throw err; }) .then(function () { // Store client for next API calls return promisifyClient(client); }); } // Authenticate then stores OAuth token to user's configuration for later use // Client ~→ void function getToken (client) { debug("getToken"); console.log("No token found to access Github API. I will now ask for your username and password to generate one."); console.log("Those information ARE NOT STORED, only the generated token will be stored in your global git configuration."); console.log("If you don't want to let this process go you'll have to generate a token yourself and then save it with 'github-todos config github.token <your token>'."); return ask([ {"type": "input", "message": "Github username", "name": "user"}, {"type": "password", "message": "Github password", "name": "password"} ]).then(function (answers) { client.authenticate({ "type": "basic", "username": answers.user, "password": answers.password }); var payload = { "note": "Github-Todos (" + (new Date()) + ")", "note_url": "https://github.com/naholyr/github-todos", "scopes": ["user", "repo"] }; return Promise.promisify(client.authorization.create, client.authorization)(payload) .then(null, function (err) { if (err && err.code === 401 && err.message && err.message.indexOf("OTP") !== -1) { // Two-factor authentication console.log("You are using two-factor authentication, please enter your code to finish:"); return twoFactorAuth(client, payload); } else { throw err; } }) .then(saveToken(client)); }); } function saveToken (client) { return function (res) { if (!res || !res.token) { throw new Error("No token generated"); } return config.set("github.token", res.token).then(function () { client.authenticate({ type: "oauth", token: res.token }); return promisifyClient(client); }); }; } function twoFactorAuth (client, payload) { return ask([{"type": "input", "message": "Code", "name": "code"}]).then(function (answers) { _.merge(payload, { "headers": { "X-GitHub-OTP": answers.code } }); return Promise.promisify(client.authorization.create, client.authorization)(payload); }); } function guessRepoFromUrl (url) { var match = url.match(/github\.com[:\/]([^\/]+\/[^\/]+?)(?:\.git)?$/); return match && match[1]; } function validateConfig (conf) { if (!conf.repo || !_.isString(conf.repo) || !conf.repo.match(/^[^\/]+\/[^\/]+$/)) { return Promise.reject(new Error("'repo': expected format '" + module.exports.meta.repo + "'")); } return Promise.resolve(conf); }
{ "content_hash": "c7d3e35a8e6c952b62224d97d5439423", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 170, "avg_line_length": 26.986206896551725, "alnum_prop": 0.6161512905698953, "repo_name": "naholyr/github-todos", "id": "682ee5359a862aff478b94ed7d01e37a006fadf8", "size": "7848", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/issue-service/github.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "64052" } ], "symlink_target": "" }
local CanvasTool = require("canvas.tools.CanvasTool") local CanvasPickPlane = require("canvas.tools.CanvasPickPlane") --------------------------------------------------------------------------------- -- -- @type SelectionTool -- --------------------------------------------------------------------------------- local SelectionTool = Class( CanvasTool, "SelectionTool" ) function SelectionTool:init() CanvasTool.init(self) end function SelectionTool:onLoad() local plane = self:addCanvasItem( CanvasPickPlane() ) local inputDevice = self.parent:getView():getInputDevice() plane:setPickCallback( function( picked ) if inputDevice:isCtrlDown() then toggleSelection( 'scene', unpack( picked ) ) elseif inputDevice:isShiftDown() then addSelection( 'scene', unpack( picked ) ) elseif inputDevice:isAltDown() then removeSelection( 'scene', unpack( picked ) ) else changeSelection( 'scene', unpack( picked ) ) end end ) self.plane = plane end --------------------------------------------------------------------------------- return SelectionTool
{ "content_hash": "3062af7425342054522c96b637a1fcac", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 81, "avg_line_length": 30.6, "alnum_prop": 0.5742296918767507, "repo_name": "RazielSun/juma-editor", "id": "8b988edca1fcf9da0b66965677a5d1a4fdd459de", "size": "1072", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "editor/lib/lua/editor/canvas/tools/SelectionTool.lua", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "431449" }, { "name": "C++", "bytes": "32787" }, { "name": "Lua", "bytes": "93013" }, { "name": "Makefile", "bytes": "6088" }, { "name": "Python", "bytes": "586510" }, { "name": "Shell", "bytes": "1229" } ], "symlink_target": "" }
<?php require_once("../includes/classService.php"); require_once("../includes/clientService.php"); if (!isset($_POST['submit'])) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>Book a client into class workflow</title> <link rel="stylesheet" type="text/css" href="../styles/site.css" /> </head> <body> <form method="post" action="bookClientIntoClass.php"> Source Name: <input type="text" size="25" name="sName"/><br/> Password: <input type="password" size="25" name="password"/><br/> SiteID: <input type="text" size="5" name="siteID" value="-99"/><br/> <input type="submit" value="submit" name="submit"/> </form> <?php } else { $sourcename = $_POST["sName"]; $password = $_POST["password"]; $siteID = $_POST["siteID"]; // initialize default credentials $creds = new SourceCredentials($sourcename, $password, array($siteID)); // initialize the services you are going to use $classService = new MBClassService(true); $classService->SetDefaultCredentials($creds); $clientService = new MBClientService(true); $clientService->SetDefaultCredentials($creds); // get a list of upcoming classes $result = $classService->GetClasses(array(), array(), array(), new DateTime("2010-11-28"), new DateTime("2010-12-04"), null, 10, 0); $classHtml = '<table><tr><td>ID</td><td>Name</td><td>Start Time</td></tr>'; $classes = toArray($result->GetClassesResult->Classes->Class); foreach ($classes as $class) { $classHtml .= sprintf('<tr><td>%d</td><td>%s</td><td>%s</td></tr>', $class->ID, $class->ClassDescription->Name, $class->StartDateTime); } $classHtml .= '</table>'; // pick a classID to sign a client into $classID = $classes[0]->ID; ?> <h2>Class List</h2> <?php echo($classHtml) ?> <p>Pick a classID to sign a client into: <?php echo($classID) ?></p> <?php // validate the current user's MB login information to identify the client $result = $clientService->ValidateLogin("foxmccloud", "foxmccloud1"); $clientHtml = '<table><tr><td>ID</td><td>Name</td><td>GUID</td></tr>'; $client = $result->ValidateLoginResult->Client; $guid = $result->ValidateLoginResult->GUID; if ($client != null) { $clientHtml .= sprintf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>', $client->ID, $client->FirstName . " " . $client->LastName, $guid); } $clientHtml .= '</table>'; ?> <h2>Selected Client</h2> <?php echo($clientHtml) ?> <?php // try to sign them up for the class $result = $classService->AddClientsToClasses(array($client->ID), array($classID)); /* $classHtml = '<table><tr><td>ID</td><td>Name</td><td>GUID</td></tr>'; if (count($result->AddClientsToClassesResult->Classes) > 0) { $classes = toArray($result->AddClientsToClassesResult->Classes->Class); foreach ($classes as $class) { $classHtml .= sprintf('<tr><td>%d</td><td>%s</td><td>%s</td></tr>', $class->ID, $class->ClassDescription->Name, $class->StartDateTime); } $classHtml .= '</table>'; } // find out if they have a service to pay for this class // if they do, sign them up // if they don't, purchase a service to pay for it */ } ?> </body> </html>
{ "content_hash": "f27ae273e62a726d96497390e5de62cd", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 137, "avg_line_length": 32, "alnum_prop": 0.6600765306122449, "repo_name": "janeeats/mind-body-test", "id": "7fccf0a33a1bd7e51e77d062f030538663f39b4d", "size": "3136", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "php/workflows/bookClientIntoClass.php", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "541" }, { "name": "C#", "bytes": "1255960" }, { "name": "CSS", "bytes": "5041" }, { "name": "CoffeeScript", "bytes": "229" }, { "name": "JavaScript", "bytes": "641" }, { "name": "PHP", "bytes": "43555" }, { "name": "Python", "bytes": "103815" }, { "name": "Ruby", "bytes": "21809" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Doctrine\Tests\Common\Collections\Expr; use Doctrine\Common\Collections\Expr\ExpressionVisitor; use Doctrine\Common\Collections\Expr\Value; use PHPUnit\Framework\TestCase; /** @covers \Doctrine\Common\Collections\Expr\Value */ class ValueTest extends TestCase { public function testGetter(): void { $value = 'foo'; $valueExpression = new Value($value); $actualValue = $valueExpression->getValue(); self::assertEquals($value, $actualValue); } public function testVisitor(): void { $visitor = $this->getMockForAbstractClass(ExpressionVisitor::class); $visitor ->expects($this->once()) ->method('walkValue'); $value = 'foo'; $valueExpression = new Value($value); $valueExpression->visit($visitor); } }
{ "content_hash": "60e71e6f298e50ff99101d6bd22fecf7", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 76, "avg_line_length": 25.4, "alnum_prop": 0.6321709786276716, "repo_name": "doctrine/collections", "id": "5a93294e4c21a0618a24e077575477a9725dd39e", "size": "889", "binary": false, "copies": "1", "ref": "refs/heads/2.1.x", "path": "tests/Common/Collections/Expr/ValueTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "113879" } ], "symlink_target": "" }
from django.contrib import admin from import_export.admin import ExportMixin from models import (Poll, PollComment, RadioPoll, RadioPollChoice, RangePoll, RangePollChoice, Vote) class RangePollChoiceInline(admin.StackedInline): """Poll Range Votes Inline.""" model = RangePollChoice extra = 0 readonly_fields = ['votes'] class RangePollInline(admin.StackedInline): """Range Poll Inline.""" model = RangePoll extra = 0 class RadioPollChoiceInline(admin.StackedInline): """Radio Poll Choice Inline.""" model = RadioPollChoice extra = 0 readonly_fields = ['votes'] class RadioPollInline(admin.StackedInline): """Poll Radio Inline.""" model = RadioPoll extra = 0 class RadioPollAdmin(ExportMixin, admin.ModelAdmin): inlines = [RadioPollChoiceInline] class RangePollAdmin(ExportMixin, admin.ModelAdmin): inlines = [RangePollChoiceInline] class PollCommentInline(admin.StackedInline): """PollComment Inline.""" model = PollComment class PollAdmin(ExportMixin, admin.ModelAdmin): """Voting Admin.""" inlines = [RangePollInline, RadioPollInline, PollCommentInline] search_fields = ['name'] list_display = ['name', 'start', 'end', 'valid_groups'] date_hierarchy = 'start' readonly_fields = ['task_start_id', 'task_end_id', 'bug'] list_filter = ['automated_poll', 'is_extended', 'comments_allowed'] class VoteAdmin(ExportMixin, admin.ModelAdmin): """Vote Admin""" model = Vote search_fields = ['user__first_name', 'user__last_name', 'poll__name'] list_display = ['user', 'poll', 'date_voted'] admin.site.register(Vote, VoteAdmin) admin.site.register(RangePoll, RangePollAdmin) admin.site.register(RadioPoll, RadioPollAdmin) admin.site.register(Poll, PollAdmin)
{ "content_hash": "33b382744f5ca2d1611017a9e1f0cc57", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 73, "avg_line_length": 27, "alnum_prop": 0.6976229961304589, "repo_name": "johngian/remo", "id": "5934a4dbf44ee1c339cb45c5607285147e6584ef", "size": "1809", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "remo/voting/admin.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "993" }, { "name": "Batchfile", "bytes": "4531" }, { "name": "CSS", "bytes": "372453" }, { "name": "HTML", "bytes": "373393" }, { "name": "JavaScript", "bytes": "606422" }, { "name": "Makefile", "bytes": "4630" }, { "name": "Puppet", "bytes": "7140" }, { "name": "Python", "bytes": "7472017" }, { "name": "Shell", "bytes": "3221" }, { "name": "Smarty", "bytes": "215" }, { "name": "TeX", "bytes": "1525" } ], "symlink_target": "" }
cask 'firealpaca' do version :latest sha256 :no_check url 'http://firealpaca.com/download.php?os=mac&key=17813449013210197561d4f66c5aca8c' name 'Fire Alpaca' homepage 'http://firealpaca.com/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'FireAlpaca.app' end
{ "content_hash": "85a0f543bb26bf068bab5b69221d87ee", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 115, "avg_line_length": 31.545454545454547, "alnum_prop": 0.7463976945244957, "repo_name": "gurghet/homebrew-cask", "id": "a6ed015e43b5f184943a06e8edac6e9af108dad8", "size": "347", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Casks/firealpaca.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "1765398" }, { "name": "Shell", "bytes": "52927" } ], "symlink_target": "" }
import React from 'react'; import { Router, Scene, ActionConst} from 'react-native-router-flux'; /** * Containers */ import Home from './containers/Home'; const routes = () => { return <Router> <Scene key='root' hideNavBar={true} > <Scene key='home' component={Home} title='Home' direction='vertical'/> </Scene> </Router> } export default routes;
{ "content_hash": "df9401c201f4882a2349105caa676fc4", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 82, "avg_line_length": 23.235294117647058, "alnum_prop": 0.610126582278481, "repo_name": "AWorkingApp/ReactNativeStarter", "id": "b331344738d122c69f51b01af0f6673e304bfee0", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/routes.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1685" }, { "name": "JavaScript", "bytes": "11816" }, { "name": "Objective-C", "bytes": "4437" }, { "name": "Python", "bytes": "1746" } ], "symlink_target": "" }
package org.apache.flex.forks.batik.ext.awt.image.codec.jpeg; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.WritableRaster; import java.io.IOException; import java.io.InputStream; import org.apache.flex.forks.batik.ext.awt.image.GraphicsUtil; import org.apache.flex.forks.batik.ext.awt.image.renderable.DeferRable; import org.apache.flex.forks.batik.ext.awt.image.renderable.Filter; import org.apache.flex.forks.batik.ext.awt.image.renderable.RedRable; import org.apache.flex.forks.batik.ext.awt.image.rendered.Any2sRGBRed; import org.apache.flex.forks.batik.ext.awt.image.rendered.FormatRed; import org.apache.flex.forks.batik.ext.awt.image.rendered.CachableRed; import org.apache.flex.forks.batik.ext.awt.image.spi.ImageTagRegistry; import org.apache.flex.forks.batik.ext.awt.image.spi.MagicNumberRegistryEntry; import org.apache.flex.forks.batik.util.ParsedURL; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageDecoder; import com.sun.image.codec.jpeg.TruncatedFileException; /** * * @version $Id: JPEGRegistryEntry.java 501094 2007-01-29 16:35:37Z deweese $ */ public class JPEGRegistryEntry extends MagicNumberRegistryEntry { static final byte [] sigJPEG = {(byte)0xFF, (byte)0xd8, (byte)0xFF}; static final String [] exts = {"jpeg", "jpg" }; static final String [] mimeTypes = {"image/jpeg", "image/jpg" }; static final MagicNumber [] magicNumbers = { new MagicNumber(0, sigJPEG) }; public JPEGRegistryEntry() { super("JPEG", exts, mimeTypes, magicNumbers); } /** * Decode the Stream into a RenderableImage * * @param inIS The input stream that contains the image. * @param origURL The original URL, if any, for documentation * purposes only. This may be null. * @param needRawData If true the image returned should not have * any default color correction the file may * specify applied. */ public Filter handleStream(InputStream inIS, ParsedURL origURL, boolean needRawData) { final DeferRable dr = new DeferRable(); final InputStream is = inIS; final String errCode; final Object [] errParam; if (origURL != null) { errCode = ERR_URL_FORMAT_UNREADABLE; errParam = new Object[] {"JPEG", origURL}; } else { errCode = ERR_STREAM_FORMAT_UNREADABLE; errParam = new Object[] {"JPEG"}; } Thread t = new Thread() { public void run() { Filter filt; try{ JPEGImageDecoder decoder; decoder = JPEGCodec.createJPEGDecoder(is); BufferedImage image; try { image = decoder.decodeAsBufferedImage(); } catch (TruncatedFileException tfe) { image = tfe.getBufferedImage(); // Should probably draw some indication // that this is a partial image.... if (image == null) throw new IOException ("JPEG File was truncated"); } dr.setBounds(new Rectangle2D.Double (0, 0, image.getWidth(), image.getHeight())); CachableRed cr; cr = GraphicsUtil.wrap(image); cr = new Any2sRGBRed(cr); cr = new FormatRed(cr, GraphicsUtil.sRGB_Unpre); WritableRaster wr = (WritableRaster)cr.getData(); ColorModel cm = cr.getColorModel(); image = new BufferedImage (cm, wr, cm.isAlphaPremultiplied(), null); cr = GraphicsUtil.wrap(image); filt = new RedRable(cr); } catch (IOException ioe) { // Something bad happened here... filt = ImageTagRegistry.getBrokenLinkImage (JPEGRegistryEntry.this, errCode, errParam); } catch (ThreadDeath td) { filt = ImageTagRegistry.getBrokenLinkImage (JPEGRegistryEntry.this, errCode, errParam); dr.setSource(filt); throw td; } catch (Throwable t) { filt = ImageTagRegistry.getBrokenLinkImage (JPEGRegistryEntry.this, errCode, errParam); } dr.setSource(filt); } }; t.start(); return dr; } }
{ "content_hash": "265efb16b5664896d37e6798395e796b", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 78, "avg_line_length": 42.78333333333333, "alnum_prop": 0.5385664199454616, "repo_name": "adufilie/flex-sdk", "id": "557a72f288652c1a99efddef1703218ef9cf7d94", "size": "5933", "binary": false, "copies": "9", "ref": "refs/heads/develop", "path": "modules/thirdparty/batik/sources/org/apache/flex/forks/batik/ext/awt/image/codec/jpeg/JPEGRegistryEntry.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AGS Script", "bytes": "478" }, { "name": "ASP", "bytes": "6381" }, { "name": "ActionScript", "bytes": "34995123" }, { "name": "Awk", "bytes": "1958" }, { "name": "Batchfile", "bytes": "40336" }, { "name": "C", "bytes": "4601" }, { "name": "C++", "bytes": "10259" }, { "name": "CSS", "bytes": "508448" }, { "name": "Groff", "bytes": "59633" }, { "name": "HTML", "bytes": "84174" }, { "name": "Java", "bytes": "15072764" }, { "name": "JavaScript", "bytes": "110516" }, { "name": "PureBasic", "bytes": "362" }, { "name": "Shell", "bytes": "306455" }, { "name": "Visual Basic", "bytes": "4498" }, { "name": "XSLT", "bytes": "757371" } ], "symlink_target": "" }
namespace autofill { class AutofillCountry; class PersonalDataManager; // A model for countries to be used to enter addresses. class CountryComboboxModel : public ui::ComboboxModel { public: using CountryVector = std::vector<std::unique_ptr<AutofillCountry>>; CountryComboboxModel(); ~CountryComboboxModel() override; // |filter| is passed each known country's country code. If |filter| returns // true, an item for that country is added to the model (else it's omitted). // |manager| determines the default choice. void SetCountries( const PersonalDataManager& manager, const base::RepeatingCallback<bool(const std::string&)>& filter, const std::string& app_locale); // ui::ComboboxModel implementation: int GetItemCount() const override; base::string16 GetItemAt(int index) override; bool IsItemSeparatorAt(int index) override; // The list of countries always has the default country at the top as well as // within the sorted vector. const CountryVector& countries() const { return countries_; } // Returns the default country code for this model. std::string GetDefaultCountryCode() const; private: // The countries to show in the model, including NULL for entries that are // not countries (the separator entry). CountryVector countries_; DISALLOW_COPY_AND_ASSIGN(CountryComboboxModel); }; } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_UI_COUNTRY_COMBOBOX_MODEL_H_
{ "content_hash": "32645b6d05668dc805fcf8238bc8a775", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 79, "avg_line_length": 33.27272727272727, "alnum_prop": 0.7424863387978142, "repo_name": "endlessm/chromium-browser", "id": "fb00d1627956329a0f82c236609b4e330bc6fdf3", "size": "1926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/autofill/core/browser/ui/country_combobox_model.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.keycloak.authentication.authenticators.browser; import org.jboss.logging.Logger; import org.keycloak.authentication.AbstractFormAuthenticator; import org.keycloak.authentication.AuthenticationFlowError; import org.keycloak.authentication.AuthenticationFlowContext; import org.keycloak.events.Details; import org.keycloak.events.Errors; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserModel; import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.services.managers.AuthenticationManager; import org.keycloak.services.messages.Messages; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.util.LinkedList; import java.util.List; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public abstract class AbstractUsernameFormAuthenticator extends AbstractFormAuthenticator { private static final Logger logger = Logger.getLogger(AbstractUsernameFormAuthenticator.class); public static final String REGISTRATION_FORM_ACTION = "registration_form"; public static final String ATTEMPTED_USERNAME = "ATTEMPTED_USERNAME"; @Override public void action(AuthenticationFlowContext context) { } protected Response invalidUser(AuthenticationFlowContext context) { return context.form() .setError(Messages.INVALID_USER) .createLogin(); } protected Response disabledUser(AuthenticationFlowContext context) { return context.form() .setError(Messages.ACCOUNT_DISABLED).createLogin(); } protected Response temporarilyDisabledUser(AuthenticationFlowContext context) { return context.form() .setError(Messages.ACCOUNT_TEMPORARILY_DISABLED).createLogin(); } protected Response invalidCredentials(AuthenticationFlowContext context) { return context.form() .setError(Messages.INVALID_USER).createLogin(); } protected Response setDuplicateUserChallenge(AuthenticationFlowContext context, String eventError, String loginFormError, AuthenticationFlowError authenticatorError) { context.getEvent().error(eventError); Response challengeResponse = context.form() .setError(loginFormError).createLogin(); context.failureChallenge(authenticatorError, challengeResponse); return challengeResponse; } public boolean invalidUser(AuthenticationFlowContext context, UserModel user) { if (user == null) { context.getEvent().error(Errors.USER_NOT_FOUND); Response challengeResponse = invalidUser(context); context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse); return true; } return false; } public boolean enabledUser(AuthenticationFlowContext context, UserModel user) { if (!user.isEnabled()) { context.getEvent().user(user); context.getEvent().error(Errors.USER_DISABLED); Response challengeResponse = disabledUser(context); context.failureChallenge(AuthenticationFlowError.USER_DISABLED, challengeResponse); return false; } if (context.getRealm().isBruteForceProtected()) { if (context.getProtector().isTemporarilyDisabled(context.getSession(), context.getRealm(), user.getUsername())) { context.getEvent().user(user); context.getEvent().error(Errors.USER_TEMPORARILY_DISABLED); Response challengeResponse = temporarilyDisabledUser(context); context.failureChallenge(AuthenticationFlowError.USER_TEMPORARILY_DISABLED, challengeResponse); return false; } } return true; } public boolean validateUserAndPassword(AuthenticationFlowContext context, MultivaluedMap<String, String> inputData) { String username = inputData.getFirst(AuthenticationManager.FORM_USERNAME); if (username == null) { context.getEvent().error(Errors.USER_NOT_FOUND); Response challengeResponse = invalidUser(context); context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse); return false; } context.getEvent().detail(Details.USERNAME, username); context.getClientSession().setNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username); UserModel user = null; try { user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username); } catch (ModelDuplicateException mde) { logger.error(mde.getMessage(), mde); // Could happen during federation import if (mde.getDuplicateFieldName() != null && mde.getDuplicateFieldName().equals(UserModel.EMAIL)) { setDuplicateUserChallenge(context, Errors.EMAIL_IN_USE, Messages.EMAIL_EXISTS, AuthenticationFlowError.INVALID_USER); } else { setDuplicateUserChallenge(context, Errors.USERNAME_IN_USE, Messages.USERNAME_EXISTS, AuthenticationFlowError.INVALID_USER); } return false; } if (invalidUser(context, user)){ return false; } if (!validatePassword(context, user, inputData)){ return false; } if(!enabledUser(context, user)){ return false; } String rememberMe = inputData.getFirst("rememberMe"); boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("on"); if (remember) { context.getClientSession().setNote(Details.REMEMBER_ME, "true"); context.getEvent().detail(Details.REMEMBER_ME, "true"); } else { context.getClientSession().removeNote(Details.REMEMBER_ME); } context.setUser(user); return true; } public boolean validatePassword(AuthenticationFlowContext context, UserModel user, MultivaluedMap<String, String> inputData) { List<UserCredentialModel> credentials = new LinkedList<>(); String password = inputData.getFirst(CredentialRepresentation.PASSWORD); credentials.add(UserCredentialModel.password(password)); boolean valid = context.getSession().users().validCredentials(context.getSession(), context.getRealm(), user, credentials); if (!valid) { context.getEvent().user(user); context.getEvent().error(Errors.INVALID_USER_CREDENTIALS); Response challengeResponse = invalidCredentials(context); context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challengeResponse); context.clearUser(); return false; } return true; } }
{ "content_hash": "7fa0b8ff1890e7addf72e166ea5a05fa", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 171, "avg_line_length": 42.63414634146341, "alnum_prop": 0.6916475972540046, "repo_name": "gregjones60/keycloak", "id": "68b036fa182263e1998776809e6349b3b69c94b7", "size": "6992", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "328" }, { "name": "ApacheConf", "bytes": "22819" }, { "name": "Batchfile", "bytes": "2114" }, { "name": "CSS", "bytes": "345677" }, { "name": "FreeMarker", "bytes": "59645" }, { "name": "HTML", "bytes": "405846" }, { "name": "Java", "bytes": "9388566" }, { "name": "JavaScript", "bytes": "695860" }, { "name": "Shell", "bytes": "11085" }, { "name": "XSLT", "bytes": "82496" } ], "symlink_target": "" }
using Aurora.EffectsEngine; using Aurora.Profiles; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace Aurora.Settings.Layers { public class PercentGradientLayerHandlerProperties : PercentLayerHandlerProperties<PercentGradientLayerHandlerProperties> { public PercentGradientLayerHandlerProperties() : base() { } public PercentGradientLayerHandlerProperties(bool empty = false) : base(empty) { } public EffectBrush _Gradient { get; set; } [JsonIgnore] public EffectBrush Gradient { get { return Logic._Gradient ?? _Gradient ?? new EffectBrush().SetBrushType(EffectBrush.BrushType.Linear); } } public override void Default() { base.Default(); this._Gradient = new EffectBrush().SetBrushType(EffectBrush.BrushType.Linear); } } public class PercentGradientLayerHandler : PercentLayerHandler<PercentGradientLayerHandlerProperties> { public PercentGradientLayerHandler() : base() { _ID = "PercentGradient"; } protected override UserControl CreateControl() { return new Control_PercentGradientLayer(this); } public override EffectLayer Render(IGameState state) { EffectLayer percent_layer = new EffectLayer(); double value = 0; if (!double.TryParse(Properties._VariablePath, out value) && !string.IsNullOrWhiteSpace(Properties._VariablePath)) { try { value = Convert.ToDouble(Utils.GameStateUtils.RetrieveGameStateParameter(state, Properties._VariablePath)); } catch (Exception exc) { value = 0; } } double maxvalue = 0; if (!double.TryParse(Properties._MaxVariablePath, out maxvalue) && !string.IsNullOrWhiteSpace(Properties._MaxVariablePath)) { try { maxvalue = Convert.ToDouble(Utils.GameStateUtils.RetrieveGameStateParameter(state, Properties._MaxVariablePath)); } catch (Exception exc) { maxvalue = 0; } } percent_layer.PercentEffect(Properties.Gradient.GetColorSpectrum(), Properties.Sequence, value, maxvalue, Properties.PercentType, Properties.BlinkThreshold, Properties.BlinkDirection); return percent_layer; } public override void SetApplication(Application profile) { if (profile != null) { double value; if (!double.TryParse(Properties._VariablePath, out value) && !string.IsNullOrWhiteSpace(Properties._VariablePath) && !profile.ParameterLookup.ContainsKey(Properties._VariablePath)) Properties._VariablePath = string.Empty; if (!double.TryParse(Properties._MaxVariablePath, out value) && !string.IsNullOrWhiteSpace(Properties._MaxVariablePath) && !profile.ParameterLookup.ContainsKey(Properties._MaxVariablePath)) Properties._MaxVariablePath = string.Empty; } (Control as Control_PercentGradientLayer).SetApplication(profile); this.Application = profile; } } }
{ "content_hash": "44f4c7e60ffae72a8b57020b682830d4", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 205, "avg_line_length": 37.294736842105266, "alnum_prop": 0.6164267569856055, "repo_name": "VoronFX/Aurora", "id": "faa437804ec8e9b6e5b0500c88d2b26959dad847", "size": "3545", "binary": false, "copies": "1", "ref": "refs/heads/voron-scripts-aurora-0.6.1", "path": "Project-Aurora/Project-Aurora/Settings/Layers/PercentGradientLayerHandler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "38358" }, { "name": "C#", "bytes": "2487330" }, { "name": "C++", "bytes": "175670" }, { "name": "Inno Setup", "bytes": "7541" }, { "name": "NewLisp", "bytes": "2424" }, { "name": "Python", "bytes": "3754" } ], "symlink_target": "" }
/** * Module dependencies. */ var express = require('express'), http = require('http'), https = require('https'), fs = require('fs'); var app = express(); // Modify as needed app.set('port', 3000); app.set('postssl', 3443); // Modify these to where your certs are var options = { key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; /** Safari will connect to this endpoint to look for your push package */ app.post('/v1/pushPackages/:websitePushID', function (req, res) { var file; // Load your push package .zip file or dynamically create one // Example: // file = fs.readFileSync('pushpackage.zip'); res.set({'Content-type': 'application/zip'}); res.send(file); }); /** Safari will connect to this endpoint to once the user allows push notifications. This is where you should probably do something with the token */ app.post('/v1/devices/:deviceToken/registrations/:websitePushID', function (req, res) { console.log('tokens', req.params.deviceToken); res.send(200); }); /** Safari will connect to this endpoint to if the user wants to remove push notifications. This is where you should probably remove the token from a database or something */ app.delete('/v1/devices/:deviceToken/registrations/:websitePushID', function (req, res) { console.log('tokens', req.params.deviceToken); res.send(200); }); /** Safari will connect to this endpoint when errors occur. */ app.post('/v1/log', function (req, res) { // Do Logging Stuff res.send(200); }); http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); https.createServer(options, app).listen(app.get('sslport'), function () { console.log('Express Secure server listening on port ' + app.get('sslport')); });
{ "content_hash": "08e32d080f48c6a4cd0e1568443d55fd", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 89, "avg_line_length": 27.114285714285714, "alnum_prop": 0.6828240252897787, "repo_name": "lholmquist/generator-safari-push", "id": "036045edb17a04e2ab85af8b58d2776732b54676", "size": "1898", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/templates/_server.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3954" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <config> <name>Comments</name> <params> <param name="enable_comments" type="radio" default="0" label="Enable comments" description="ENABLE_COMMENTING_SYSTEM"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="require_name_and_mail" type="radio" default="1" label="Name and e-mail required" description="Comment author must fill out name and e-mail"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="registered_users_only" type="radio" default="0" label="Registered users only" description="REGISTERED_USERS_ONLY"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="approved" type="list" default="0" label="Approved by default" description="Comments are approved by default"> <option value="0">not approved by default</option> <option value="1">approved by default</option> <option value="2">approval required only once</option> </param> <param name="time_between_user_posts" type="text" size="55" default="120" label="Time between user posts" description="TIME_BEFORE_ALLOWED_POST_AGAIN" /> <param name="@spacer" type="spacer" /> <param name="email_notification" type="text" size="55" default="" label="Email Notification" description="EMAIL_NOTIFICATION_DESCRIPTION" /> <param name="email_reply_notification" type="radio" default="0" label="Email on reply" description="EMAIL_REPLY_DESCRIPTION"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="@spacer" type="spacer" /> <param name="avatar" type="radio" default="1" label="Show avatar" description="Show avatar"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="order" type="list" default="ASC" label="Order of comments" description="Comment order"> <option value="DESC">Latest first</option> <option value="ASC">Latest last</option> </param> <param name="max_depth" type="list" default="5" label="Nested comments depth" description="Maximum depth of nested comments"> <option value="1">No nested comments</option> <option value="2">J2</option> <option value="3">J3</option> <option value="4">J4</option> <option value="5">J5</option> <option value="6">J6</option> <option value="7">J7</option> <option value="8">J8</option> <option value="9">J9</option> <option value="10">J10</option> </param> <param name="@spacer" type="spacer" /> <param name="facebook_enable" type="radio" default="0" label="Enable Facebook" description="COMMENT_FACEBOOK_AUTHENTICATION"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="facebook_app_id" type="text" size="55" default="" label="Facebook Application ID" description="FACEBOOK_APPLICATION_ID" /> <param name="facebook_app_secret" type="text" size="55" default="" label="Facebook Application Secret" description="FACEBOOK_APPLICATION_SECRET" /> <param name="@spacer" type="spacer" /> <param name="twitter_enable" type="radio" default="0" label="Enable Twitter" description="COMMENT_TWITTER_AUTHENTICATION"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="twitter_consumer_key" type="text" size="55" default="" label="Twitter Consumer Key" description="TWITTER_CONSUMER_KEY" /> <param name="twitter_consumer_secret" type="text" size="55" default="" label="Twitter Consumer Secret" description="TWITTER_CONSUMER_SECRET" /> <param name="@spacer" type="spacer" /> <param name="akismet_enable" type="radio" default="0" label="Enable Akismet" description="CHECK_AKISMET"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="akismet_api_key" type="text" size="55" default="" label="Wordpress API Key" description="WORDPRESS_APPLICATION_KEY" /> <param name="@spacer" type="spacer" /> <param name="mollom_enable" type="radio" default="0" label="Enable Mollom" description="CHECK_MOLLOM"> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="mollom_public_key" type="text" size="55" default="" label="Mollom Public Key" description="The Mollom public key." /> <param name="mollom_private_key" type="text" size="55" default="" label="Mollom Private Key" description="The Mollom private key." /> <param name="@spacer" type="spacer" /> <param name="captcha" type="zooplugin" default="" label="Enable Captcha" description="Enabled Captcha on comment submission" folder="captcha" /> <param name="captcha_guest_only" type="radio" default="1" label="Guests only" description=""> <option value="1">JYES</option> <option value="0">JNO</option> </param> <param name="@spacer" type="spacer" /> <param name="blacklist" type="textarea" cols="40" rows="10" default="" label="Blacklist" description="BLACKLIST_DESCRIPTION" /> </params> </config>
{ "content_hash": "8c80ef42a54a032bcdbcaf88aa4bca26", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 155, "avg_line_length": 57.68604651162791, "alnum_prop": 0.695021165087684, "repo_name": "notarget84/Grupo-Estudos-do-Pulmao", "id": "ca389f1cbc15b026f257f97fabe0657d58f7f384", "size": "4961", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "media/zoo/applications/page/config/comments.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1589000" }, { "name": "JavaScript", "bytes": "243108" }, { "name": "PHP", "bytes": "6222901" } ], "symlink_target": "" }
title: Weekday Abbreviations version: 1.0.0 signature: | // From 2.8.1 onward moment.locale('en', { weekdaysShort : String[] }); moment.locale('en', { weekdaysShort : Function }); // Deprecated in 2.8.1 moment.lang('en', { weekdaysShort : String[] }); moment.lang('en', { weekdaysShort : Function }); --- `Locale#weekdaysShort` should be an array of the weekdays abbreviations. ```javascript moment.locale('en', { weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] }); ``` `Locale#weekdaysShort` can be a callback function as well. ```javascript moment.locale('en', { weekdaysShort : function (momentToFormat, format) { return weekdaysShort[momentToFormat.day()]; } }); ```
{ "content_hash": "a1d53adb36637a523b7f0e155fb185db", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 72, "avg_line_length": 19.973684210526315, "alnum_prop": 0.619235836627141, "repo_name": "mibcadet/momentjs.com", "id": "38fa1318990aea9a44171f3fdf0a7898a80bd166", "size": "763", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "docs/moment/07-customization/04-weekday-abbreviations.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24219" }, { "name": "Handlebars", "bytes": "14890" }, { "name": "JavaScript", "bytes": "98685" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <!--[if lt IE 7]> <html lang="en" ng-app="rentfinds" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html lang="en" ng-app="rentfinds" class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html lang="en" ng-app="rentfinds" class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html lang="en" ng-app="rentfinds" class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Apartment Finder</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="bower_components/foundation/css/foundation.css"> <link rel="stylesheet" href="app.css"> </head> <body> <nav class="top-bar" data-topbar role="navigation"> <ul class="title-area"> <li class="name"> <h1><a href="#">Appartment Finder</a></h1> </li> </ul> </nav> <div ng-view></div> <!-- In production use: <script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script> --> <script src="bower_components/jquery/dist/jquery.js"></script> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-route/angular-route.js"></script> <script src="bower_components/firebase/firebase.js"></script> <script src="bower_components/angularfire/dist/angularfire.js"></script> <script src="bower_components/foundation/js/foundation.js"></script> <script src="app.js"></script> <script src="rentals/rentals.js"></script> </body> </html>
{ "content_hash": "7910ac1f837258e17c246a96bbfa4f7d", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 110, "avg_line_length": 47.17948717948718, "alnum_prop": 0.5635869565217392, "repo_name": "marb61a/appartment_finder", "id": "2164d4b598a22b7131013fe653ae4f1aeacf6e03", "size": "1840", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "834" }, { "name": "HTML", "bytes": "21934" }, { "name": "JavaScript", "bytes": "6833" } ], "symlink_target": "" }
using System; using System.Text; using System.Collections; using System.Collections.Generic; namespace Com.Aspose.Email.Model { public class MailServerFolder { public string Name { get; set; } public string Id { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.Append("class MailServerFolder {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
{ "content_hash": "1059317b92860b82a685067fa7ff06c1", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 54, "avg_line_length": 25.38095238095238, "alnum_prop": 0.6228893058161351, "repo_name": "asposeemail/Aspose_Email_Cloud", "id": "1200b45a87423cd55d677ee2a2f528cf06ea851e", "size": "533", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "SDKs/Aspose.Email-Cloud-SDK-for-.NET/src/Com/Aspose/Email/Model/MailServerFolder.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "203" }, { "name": "C#", "bytes": "121104" }, { "name": "Java", "bytes": "46866" }, { "name": "JavaScript", "bytes": "79666" }, { "name": "Objective-C", "bytes": "62346" }, { "name": "PHP", "bytes": "38146" }, { "name": "Python", "bytes": "49748" }, { "name": "Ruby", "bytes": "52788" } ], "symlink_target": "" }
package com.google.cloud.tasks.v2beta2.samples; // [START cloudtasks_v2beta2_generated_CloudTasks_ResumeQueue_async] import com.google.api.core.ApiFuture; import com.google.cloud.tasks.v2beta2.CloudTasksClient; import com.google.cloud.tasks.v2beta2.Queue; import com.google.cloud.tasks.v2beta2.QueueName; import com.google.cloud.tasks.v2beta2.ResumeQueueRequest; public class AsyncResumeQueue { public static void main(String[] args) throws Exception { asyncResumeQueue(); } public static void asyncResumeQueue() throws Exception { // This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (CloudTasksClient cloudTasksClient = CloudTasksClient.create()) { ResumeQueueRequest request = ResumeQueueRequest.newBuilder() .setName(QueueName.of("[PROJECT]", "[LOCATION]", "[QUEUE]").toString()) .build(); ApiFuture<Queue> future = cloudTasksClient.resumeQueueCallable().futureCall(request); // Do something. Queue response = future.get(); } } } // [END cloudtasks_v2beta2_generated_CloudTasks_ResumeQueue_async]
{ "content_hash": "3681bc79535e844a404ae2dae9aed731", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 100, "avg_line_length": 41.51428571428571, "alnum_prop": 0.7370956641431521, "repo_name": "googleapis/google-cloud-java", "id": "fca5488278b99962a98e1f0e26835352bfdf38e3", "size": "2048", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "java-tasks/samples/snippets/generated/com/google/cloud/tasks/v2beta2/cloudtasks/resumequeue/AsyncResumeQueue.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2614" }, { "name": "HCL", "bytes": "28592" }, { "name": "Java", "bytes": "826434232" }, { "name": "Jinja", "bytes": "2292" }, { "name": "Python", "bytes": "200408" }, { "name": "Shell", "bytes": "97954" } ], "symlink_target": "" }
using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Convert)] [Tooltip("Converts a Bool value to a String value.")] public class ConvertBoolToString : FsmStateAction { [RequiredField] [UIHint(UIHint.Variable)] [Tooltip("The Bool variable to test.")] public FsmBool boolVariable; [RequiredField] [UIHint(UIHint.Variable)] [Tooltip("The String variable to set based on the Bool variable value.")] public FsmString stringVariable; [Tooltip("String value if Bool variable is false.")] public FsmString falseString; [Tooltip("String value if Bool variable is true.")] public FsmString trueString; [Tooltip("Repeat every frame. Useful if the Bool variable is changing.")] public bool everyFrame; public override void Reset() { boolVariable = null; stringVariable = null; falseString = "False"; trueString = "True"; everyFrame = false; } public override void OnEnter() { DoConvertBoolToString(); if (!everyFrame) { Finish(); } } public override void OnUpdate() { DoConvertBoolToString(); } void DoConvertBoolToString() { stringVariable.Value = boolVariable.Value ? trueString.Value : falseString.Value; } } }
{ "content_hash": "0ed6d68534e766eeda4964081a65c61f", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 84, "avg_line_length": 22, "alnum_prop": 0.70414673046252, "repo_name": "omarrugu/EQ_elementos_de_quimica", "id": "dff950439603c0b596aeca603bb536f14bfbf5bc", "size": "1321", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "Unity/src/Prueba2/Assets/PlayMaker/Actions/ConvertBoolToString.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1647" }, { "name": "C#", "bytes": "1495472" }, { "name": "GLSL", "bytes": "16788" }, { "name": "Java", "bytes": "21945" }, { "name": "JavaScript", "bytes": "1692" }, { "name": "Objective-C", "bytes": "1212" }, { "name": "Objective-C++", "bytes": "4953" } ], "symlink_target": "" }
#include "soa/reference_type.hpp" #include "soa/table.hpp" #include "soa/dtable.hpp" #include "aosoa/table_array.hpp" #include "aosoa/table_vector.hpp" #include "aosoa/for_each_range.hpp" #include "aosoa/indexed_for_each.hpp" #include "aosoa/parallel_for_each_range.hpp" #include "aosoa/parallel_indexed_for_each.hpp" #include <ctime> #include <iostream> // define a class that can be used for // plain AOS C arrays, std::array, and std::vector. class C0 {public: float x, y, z;}; // define a class that can be used for // flat AOS and nested AOSOA representations. class Cr { public: float &x, &y, &z; // define reference type typedef soa::reference_type<float,float,float> reference; // convert from reference type to C Cr(const reference::type& ref) : x(reference::get<0>(ref)), y(reference::get<1>(ref)), z(reference::get<2>(ref)) {} Cr& operator= (const Cr& that) { x = that.x; y = that.y; z = that.z; return *this; } }; // define the benchmarks. constexpr size_t len = 100000; // constant for plain C arrays, std::array and aosoa::table_array constexpr size_t blocksize = 32; // constant, somewhat arbitrary choice, seems to yield good results for this particular test case size_t repeat; // repeat each benchmark this many times. not constant to prevent optimizations based on this value // (not sure if that is really important) // define the benchmark for flat AOS and SOA representations. // no special looping constructs needed, just plain indexing. template<typename A> void flat_benchmark(A& array, size_t len, size_t repeat) { for (size_t i=0; i<len; ++i) { array[i].x = i; array[i].y = i; array[i].z = i; } float global = 0; auto start = std::time(0); for (size_t r=0; r<repeat; ++r) { float local = 0; #pragma simd reduction(+:local) for (size_t i=0; i<len; ++i) { array[i].x += array[i].y * array[i].z; local += array[i].x; } global += local; } auto end = std::time(0); std::cout << "result: " << global << std::endl; std::cout << "time: " << end-start << std::endl; } // define the benchmark for std::array, std::vector, aosoa::table_array, and aosoa::table_vector. // special looping constructs used to hide away details of nested looping on // AOSOA representations. template<typename A> void nested_benchmark (A& array, size_t repeat) { typedef decltype(array[0]) C; aosoa::parallel_indexed_for_each(array.begin(), array.end(), [](size_t i, C& element){ element.x = i; element.y = i; element.z = i; }); float global = 0; auto start = std::time(0); for (size_t r=0; r<repeat; ++r) { float local = 0; aosoa::parallel_for_each_range (array.begin(), array.end(), [&local](size_t start, size_t end, typename soa::table_traits<A>::table_reference table){ #pragma simd for (size_t i=start; i<end; ++i) { table[i].x += table[i].y * table[i].z; } }); aosoa::for_each_range(array.begin(), array.end(), [&local](size_t start, size_t end, typename soa::table_traits<A>::table_reference table){ float c = 0; #pragma simd reduction(+:c) for (size_t i=start; i<end; ++i) { c += table[i].x; } local += c; }); global += local; } auto end = std::time(0); std::cout << "result: " << global << std::endl; std::cout << "time: " << end-start << std::endl; } // enumerate all the cases. main difference is in the local variable declarations. void flatAOS() { std::cout << "\nflat AOS array\n"; C0 array[len]; flat_benchmark(array, len, repeat); } void flatSOA() { std::cout << "\nflat SOA array\n"; soa::table<Cr,len> array; flat_benchmark(array, len, repeat); } void flatDSOA() { std::cout << "\nflat dynamic SOA array\n"; soa::dtable<Cr> array(len); flat_benchmark(array, len, repeat); } void stdAOS() { std::cout << "\nstd::array\n"; std::array<C0,len> array; nested_benchmark(array, repeat); } void nestedSOA2() { std::cout << "\nnested SOA array, blocksize 2\n"; aosoa::table_array<Cr,2,len> array; nested_benchmark(array, repeat); } void nestedSOAN() { std::cout << "\nnested SOA array, blocksize max\n"; aosoa::table_array<Cr,len,len> array; nested_benchmark(array, repeat); } void nestedSOAB() { std::cout << "\nnested SOA array, blocksize " << blocksize << std::endl; aosoa::table_array<Cr,blocksize,len> array; nested_benchmark(array, repeat); } void stdVOS() { std::cout << "\nstd::vector\n"; std::vector<C0> array(len); nested_benchmark(array, repeat); } void nestedSOV2() { std::cout << "\nnested SOA vector, blocksize 2\n"; aosoa::table_vector<Cr,2> array(len); nested_benchmark(array, repeat); } void nestedSOVN() { std::cout << "\nnested SOA vector, blocksize max\n"; aosoa::table_vector<Cr,len> array(len); nested_benchmark(array, repeat); } void nestedSOVB() { std::cout << "\nnested SOA vector, blocksize " << blocksize << std::endl; aosoa::table_vector<Cr,blocksize> array(len); nested_benchmark(array, repeat); } int main() { std::cout << "len: " << len << std::endl; std::cout << "repeat: "; std::cin >> repeat; flatAOS(); flatSOA(); flatDSOA(); stdAOS(); nestedSOA2(); nestedSOAN(); nestedSOAB(); stdVOS(); nestedSOV2(); nestedSOVN(); nestedSOVB(); }
{ "content_hash": "171de3a8ffb79d37ec540a7c5fddc6bb", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 140, "avg_line_length": 23.376106194690266, "alnum_prop": 0.6405451448040886, "repo_name": "ExaScience/arrow-street", "id": "f2553ce8bfb0988c4303110bbf664ef3d7665c67", "size": "6778", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/ittest1.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "228521" }, { "name": "Shell", "bytes": "153" } ], "symlink_target": "" }
namespace base { class SingleThreadTaskRunner; } namespace ui { /////////////////////////////////////////////////////////////////////////////// // A base class for all shell dialog implementations that handles showing a // shell dialog modally on its own thread. class SHELL_DIALOGS_EXPORT BaseShellDialogImpl { public: BaseShellDialogImpl(); virtual ~BaseShellDialogImpl(); // Disables the window |owner|. Can be run from either the ui or the dialog // thread. This function is called on the dialog thread after the modal // Windows Common dialog functions return because Windows automatically // re-enables the owning window when those functions return, but we don't // actually want them to be re-enabled until the response of the dialog // propagates back to the UI thread, so we disable the owner manually after // the Common dialog function returns. static void DisableOwner(HWND owner); protected: // Represents a run of a dialog. class SHELL_DIALOGS_EXPORT RunState { public: RunState(); ~RunState(); // Owning HWND, may be null. HWND owner; // Dedicated sequence on which the dialog runs. scoped_refptr<base::SingleThreadTaskRunner> dialog_task_runner; private: DISALLOW_COPY_AND_ASSIGN(RunState); }; // Called at the beginning of a modal dialog run. Disables the owner window // and tracks it. Returns the dedicated single-threaded sequence that the // dialog will be run on. std::unique_ptr<RunState> BeginRun(HWND owner); // Cleans up after a dialog run. If the run_state has a valid HWND this makes // sure that the window is enabled. This is essential because BeginRun // aggressively guards against multiple modal dialogs per HWND. Must be called // on the UI thread after the result of the dialog has been determined. void EndRun(std::unique_ptr<RunState> run_state); // Returns true if a modal shell dialog is currently active for the specified // owner. Must be called on the UI thread. bool IsRunningDialogForOwner(HWND owner) const; private: typedef std::set<HWND> Owners; // A list of windows that currently own active shell dialogs for this // instance. For example, if the DownloadManager owns an instance of this // object and there are two browser windows open both with Save As dialog // boxes active, this list will consist of the two browser windows' HWNDs. // The derived class must call EndRun once the dialog is done showing to // remove the owning HWND from this list. // This object is static since it is maintained for all instances of this // object - i.e. you can't have two file pickers open for the // same owner, even though they might be represented by different instances // of this object. // This set only contains non-null HWNDs. NULL hwnds are not added to this // list. static Owners& GetOwners(); static int instance_count_; DISALLOW_COPY_AND_ASSIGN(BaseShellDialogImpl); }; } // namespace ui #endif // UI_SHELL_DIALOGS_BASE_SHELL_DIALOG_WIN_H_
{ "content_hash": "8840de5605ecf906c2bb209b4447524d", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 80, "avg_line_length": 37.8625, "alnum_prop": 0.717068339385936, "repo_name": "endlessm/chromium-browser", "id": "4ee6b099d54166f15f274835edd28f54630de370", "size": "3519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/shell_dialogs/base_shell_dialog_win.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.netsteadfast.greenstep.po.hbm; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import com.netsteadfast.greenstep.base.model.BaseEntity; import com.netsteadfast.greenstep.base.model.EntityPK; import com.netsteadfast.greenstep.base.model.EntityUK; @Entity @Table( name="qc_olap_conf", uniqueConstraints = { @UniqueConstraint( columnNames = {"ID"} ) } ) public class QcOlapConf extends BaseEntity<String> implements java.io.Serializable { private static final long serialVersionUID = 2763021551091121484L; private String oid; private String id; private String name; private String jdbcDrivers; private String jdbcUrl; private String description; private String cuserid; private Date cdate; private String uuserid; private Date udate; @Override @Id @EntityPK(name="oid") @Column(name="OID") public String getOid() { return oid; } @Override public void setOid(String oid) { this.oid = oid; } @EntityUK(name="id") @Column(name="ID") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name="NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="JDBC_DRIVERS") public String getJdbcDrivers() { return jdbcDrivers; } public void setJdbcDrivers(String jdbcDrivers) { this.jdbcDrivers = jdbcDrivers; } @Column(name="JDBC_URL") public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } @Column(name="DESCRIPTION") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override @Column(name="CUSERID") public String getCuserid() { return this.cuserid; } @Override public void setCuserid(String cuserid) { this.cuserid = cuserid; } @Override @Column(name="CDATE") public Date getCdate() { return this.cdate; } @Override public void setCdate(Date cdate) { this.cdate = cdate; } @Override @Column(name="UUSERID") public String getUuserid() { return this.uuserid; } @Override public void setUuserid(String uuserid) { this.uuserid = uuserid; } @Override @Column(name="UDATE") public Date getUdate() { return this.udate; } @Override public void setUdate(Date udate) { this.udate = udate; } }
{ "content_hash": "d44a5a87f64a7a4e7d778cd5bf176fce", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 84, "avg_line_length": 19.56923076923077, "alnum_prop": 0.7169811320754716, "repo_name": "billchen198318/bamboobsc", "id": "3b1a114adb1a6548e46f14a1969b97095b67ecf6", "size": "2544", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "qcharts-persistence/src/com/netsteadfast/greenstep/po/hbm/QcOlapConf.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "232" }, { "name": "CSS", "bytes": "32196" }, { "name": "FreeMarker", "bytes": "187687" }, { "name": "Groovy", "bytes": "35207" }, { "name": "Java", "bytes": "36620734" }, { "name": "SQLPL", "bytes": "1487" }, { "name": "Shell", "bytes": "498" }, { "name": "TSQL", "bytes": "838169" } ], "symlink_target": "" }
 #include <aws/lightsail/model/GetRelationalDatabasesRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Lightsail::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; GetRelationalDatabasesRequest::GetRelationalDatabasesRequest() : m_pageTokenHasBeenSet(false) { } Aws::String GetRelationalDatabasesRequest::SerializePayload() const { JsonValue payload; if(m_pageTokenHasBeenSet) { payload.WithString("pageToken", m_pageToken); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection GetRelationalDatabasesRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Lightsail_20161128.GetRelationalDatabases")); return headers; }
{ "content_hash": "e130b6ad929ccf0e145889bebe86149e", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 106, "avg_line_length": 21, "alnum_prop": 0.7738095238095238, "repo_name": "JoyIfBam5/aws-sdk-cpp", "id": "3516cad329536c970a9418394368fc2fd3050ed4", "size": "1413", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-lightsail/source/model/GetRelationalDatabasesRequest.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11868" }, { "name": "C++", "bytes": "167818064" }, { "name": "CMake", "bytes": "591577" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "271801" }, { "name": "Python", "bytes": "85650" }, { "name": "Shell", "bytes": "5277" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Simple Tasks</title> <link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" /> <link rel="stylesheet" type="text/css" href="resources/css/tasks.css"> <script type="text/javascript" src="../../ext-all.js"></script> <script src="app.js"></script> </head> <body> </body> </html>
{ "content_hash": "061ab56875439e3927b727083d9aadb2", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 84, "avg_line_length": 25.571428571428573, "alnum_prop": 0.6201117318435754, "repo_name": "InnPad/Formall.NET", "id": "6d7482e6607e20c0ae44c7160b5fb5bb33cd7abf", "size": "358", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "Formall.MySql/branches/WebAppWithFileManagement/WebApp/Scripts/Ext/examples/simple-tasks/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "814" }, { "name": "C#", "bytes": "1608463" }, { "name": "CSS", "bytes": "6030860" }, { "name": "JavaScript", "bytes": "94974504" }, { "name": "PHP", "bytes": "82274" }, { "name": "Python", "bytes": "1965" }, { "name": "Ruby", "bytes": "587491" } ], "symlink_target": "" }
<?php namespace Magento\Sales\Model\Order\Invoice; use Magento\Framework\Api\AttributeValueFactory; use Magento\Sales\Api\Data\InvoiceItemInterface; use Magento\Sales\Model\AbstractModel; /** * @method \Magento\Sales\Model\ResourceModel\Order\Invoice\Item _getResource() * @method \Magento\Sales\Model\ResourceModel\Order\Invoice\Item getResource() * @method float getBaseWeeeTaxRowDisposition() * @method \Magento\Sales\Model\Order\Invoice\Item setBaseWeeeTaxRowDisposition(float $value) * @method float getWeeeTaxAppliedRowAmount() * @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxAppliedRowAmount(float $value) * @method float getBaseWeeeTaxAppliedAmount() * @method \Magento\Sales\Model\Order\Invoice\Item setBaseWeeeTaxAppliedAmount(float $value) * @method float getWeeeTaxRowDisposition() * @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxRowDisposition(float $value) * @method float getBaseWeeeTaxDisposition() * @method \Magento\Sales\Model\Order\Invoice\Item setBaseWeeeTaxDisposition(float $value) * @method float getWeeeTaxAppliedAmount() * @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxAppliedAmount(float $value) * @method float getWeeeTaxDisposition() * @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxDisposition(float $value) * @method float getBaseWeeeTaxAppliedRowAmnt() * @method \Magento\Sales\Model\Order\Invoice\Item setBaseWeeeTaxAppliedRowAmnt(float $value) * @method string getWeeeTaxApplied() * @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxApplied(string $value) * @SuppressWarnings(PHPMD.ExcessivePublicCount) */ class Item extends AbstractModel implements InvoiceItemInterface { /** * @var string */ protected $_eventPrefix = 'sales_invoice_item'; /** * @var string */ protected $_eventObject = 'invoice_item'; /** * @var \Magento\Sales\Model\Order\Item|null */ protected $_orderItem = null; /** * @var \Magento\Sales\Model\Order\ItemFactory */ protected $_orderItemFactory; /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory * @param AttributeValueFactory $customAttributeFactory * @param \Magento\Sales\Model\Order\ItemFactory $orderItemFactory * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param array $data */ public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory, AttributeValueFactory $customAttributeFactory, \Magento\Sales\Model\Order\ItemFactory $orderItemFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [] ) { parent::__construct( $context, $registry, $extensionFactory, $customAttributeFactory, $resource, $resourceCollection, $data ); $this->_orderItemFactory = $orderItemFactory; } /** * Initialize resource model * * @return void */ protected function _construct() { $this->_init('Magento\Sales\Model\ResourceModel\Order\Invoice\Item'); } /** * Declare invoice instance * * @param \Magento\Sales\Api\Data\InvoiceInterface $invoice * @return $this */ public function setInvoice(\Magento\Sales\Api\Data\InvoiceInterface $invoice) { return $this->setData(self::INVOICE, $invoice); } /** * Retrieve invoice instance * * @codeCoverageIgnore * * @return \Magento\Sales\Model\Order\Invoice */ public function getInvoice() { return $this->getData(self::INVOICE); } /** * Declare order item instance * * @param \Magento\Sales\Model\Order\Item $item * @return $this */ public function setOrderItem(\Magento\Sales\Model\Order\Item $item) { $this->_orderItem = $item; $this->setOrderItemId($item->getId()); return $this; } /** * Retrieve order item instance * * @return \Magento\Sales\Model\Order\Item */ public function getOrderItem() { if ($this->_orderItem === null) { if ($this->getInvoice()) { $this->_orderItem = $this->getInvoice()->getOrder()->getItemById($this->getOrderItemId()); } else { $this->_orderItem = $this->_orderItemFactory->create()->load($this->getOrderItemId()); } } return $this->_orderItem; } /** * Declare qty * * @codeCoverageIgnore * * @param float $qty * @return $this */ public function setQty($qty) { return $this->setData(self::QTY, $qty); } /** * Applying qty to order item * * @return $this */ public function register() { $orderItem = $this->getOrderItem(); $orderItem->setQtyInvoiced($orderItem->getQtyInvoiced() + $this->getQty()); $orderItem->setTaxInvoiced($orderItem->getTaxInvoiced() + $this->getTaxAmount()); $orderItem->setBaseTaxInvoiced($orderItem->getBaseTaxInvoiced() + $this->getBaseTaxAmount()); $orderItem->setDiscountTaxCompensationInvoiced( $orderItem->getDiscountTaxCompensationInvoiced() + $this->getDiscountTaxCompensationAmount() ); $orderItem->setBaseDiscountTaxCompensationInvoiced( $orderItem->getBaseDiscountTaxCompensationInvoiced() + $this->getBaseDiscountTaxCompensationAmount() ); $orderItem->setDiscountInvoiced($orderItem->getDiscountInvoiced() + $this->getDiscountAmount()); $orderItem->setBaseDiscountInvoiced($orderItem->getBaseDiscountInvoiced() + $this->getBaseDiscountAmount()); $orderItem->setRowInvoiced($orderItem->getRowInvoiced() + $this->getRowTotal()); $orderItem->setBaseRowInvoiced($orderItem->getBaseRowInvoiced() + $this->getBaseRowTotal()); return $this; } /** * Cancelling invoice item * * @return $this */ public function cancel() { $orderItem = $this->getOrderItem(); $orderItem->setQtyInvoiced($orderItem->getQtyInvoiced() - $this->getQty()); $orderItem->setTaxInvoiced($orderItem->getTaxInvoiced() - $this->getTaxAmount()); $orderItem->setBaseTaxInvoiced($orderItem->getBaseTaxInvoiced() - $this->getBaseTaxAmount()); $orderItem->setDiscountTaxCompensationInvoiced( $orderItem->getDiscountTaxCompensationInvoiced() - $this->getDiscountTaxCompensationAmount() ); $orderItem->setBaseDiscountTaxCompensationInvoiced( $orderItem->getBaseDiscountTaxCompensationInvoiced() - $this->getBaseDiscountTaxCompensationAmount() ); $orderItem->setDiscountInvoiced($orderItem->getDiscountInvoiced() - $this->getDiscountAmount()); $orderItem->setBaseDiscountInvoiced($orderItem->getBaseDiscountInvoiced() - $this->getBaseDiscountAmount()); $orderItem->setRowInvoiced($orderItem->getRowInvoiced() - $this->getRowTotal()); $orderItem->setBaseRowInvoiced($orderItem->getBaseRowInvoiced() - $this->getBaseRowTotal()); return $this; } /** * Invoice item row total calculation * * @return $this */ public function calcRowTotal() { $invoice = $this->getInvoice(); $orderItem = $this->getOrderItem(); $orderItemQty = $orderItem->getQtyOrdered(); $rowTotal = $orderItem->getRowTotal() - $orderItem->getRowInvoiced(); $baseRowTotal = $orderItem->getBaseRowTotal() - $orderItem->getBaseRowInvoiced(); $rowTotalInclTax = $orderItem->getRowTotalInclTax(); $baseRowTotalInclTax = $orderItem->getBaseRowTotalInclTax(); if (!$this->isLast()) { $availableQty = $orderItemQty - $orderItem->getQtyInvoiced(); $rowTotal = $invoice->roundPrice($rowTotal / $availableQty * $this->getQty()); $baseRowTotal = $invoice->roundPrice($baseRowTotal / $availableQty * $this->getQty(), 'base'); } $this->setRowTotal($rowTotal); $this->setBaseRowTotal($baseRowTotal); if ($rowTotalInclTax && $baseRowTotalInclTax) { $this->setRowTotalInclTax( $invoice->roundPrice($rowTotalInclTax / $orderItemQty * $this->getQty(), 'including') ); $this->setBaseRowTotalInclTax( $invoice->roundPrice($baseRowTotalInclTax / $orderItemQty * $this->getQty(), 'including_base') ); } return $this; } /** * Checking if the item is last * * @return bool */ public function isLast() { if ((string)(double)$this->getQty() == (string)(double)$this->getOrderItem()->getQtyToInvoice()) { return true; } return false; } //@codeCoverageIgnoreStart /** * Returns additional_data * * @return string */ public function getAdditionalData() { return $this->getData(InvoiceItemInterface::ADDITIONAL_DATA); } /** * Returns base_cost * * @return float */ public function getBaseCost() { return $this->getData(InvoiceItemInterface::BASE_COST); } /** * Returns base_discount_amount * * @return float */ public function getBaseDiscountAmount() { return $this->getData(InvoiceItemInterface::BASE_DISCOUNT_AMOUNT); } /** * Returns base_discount_tax_compensation_amount * * @return float */ public function getBaseDiscountTaxCompensationAmount() { return $this->getData(InvoiceItemInterface::BASE_DISCOUNT_TAX_COMPENSATION_AMOUNT); } /** * Returns base_price * * @return float */ public function getBasePrice() { return $this->getData(InvoiceItemInterface::BASE_PRICE); } /** * Returns base_price_incl_tax * * @return float */ public function getBasePriceInclTax() { return $this->getData(InvoiceItemInterface::BASE_PRICE_INCL_TAX); } /** * Returns base_row_total * * @return float */ public function getBaseRowTotal() { return $this->getData(InvoiceItemInterface::BASE_ROW_TOTAL); } /** * Returns base_row_total_incl_tax * * @return float */ public function getBaseRowTotalInclTax() { return $this->getData(InvoiceItemInterface::BASE_ROW_TOTAL_INCL_TAX); } /** * Returns base_tax_amount * * @return float */ public function getBaseTaxAmount() { return $this->getData(InvoiceItemInterface::BASE_TAX_AMOUNT); } /** * Returns description * * @return string */ public function getDescription() { return $this->getData(InvoiceItemInterface::DESCRIPTION); } /** * Returns discount_amount * * @return float */ public function getDiscountAmount() { return $this->getData(InvoiceItemInterface::DISCOUNT_AMOUNT); } /** * Returns discount_tax_compensation_amount * * @return float */ public function getDiscountTaxCompensationAmount() { return $this->getData(InvoiceItemInterface::DISCOUNT_TAX_COMPENSATION_AMOUNT); } /** * Returns name * * @return string */ public function getName() { return $this->getData(InvoiceItemInterface::NAME); } /** * Returns order_item_id * * @return int */ public function getOrderItemId() { return $this->getData(InvoiceItemInterface::ORDER_ITEM_ID); } /** * Returns parent_id * * @return int */ public function getParentId() { return $this->getData(InvoiceItemInterface::PARENT_ID); } /** * Returns price * * @return float */ public function getPrice() { return $this->getData(InvoiceItemInterface::PRICE); } /** * Returns price_incl_tax * * @return float */ public function getPriceInclTax() { return $this->getData(InvoiceItemInterface::PRICE_INCL_TAX); } /** * Returns product_id * * @return int */ public function getProductId() { return $this->getData(InvoiceItemInterface::PRODUCT_ID); } /** * Returns qty * * @return float */ public function getQty() { return $this->getData(InvoiceItemInterface::QTY); } /** * Returns row_total * * @return float */ public function getRowTotal() { return $this->getData(InvoiceItemInterface::ROW_TOTAL); } /** * Returns row_total_incl_tax * * @return float */ public function getRowTotalInclTax() { return $this->getData(InvoiceItemInterface::ROW_TOTAL_INCL_TAX); } /** * Returns sku * * @return string */ public function getSku() { return $this->getData(InvoiceItemInterface::SKU); } /** * Returns tax_amount * * @return float */ public function getTaxAmount() { return $this->getData(InvoiceItemInterface::TAX_AMOUNT); } /** * {@inheritdoc} */ public function setParentId($id) { return $this->setData(InvoiceItemInterface::PARENT_ID, $id); } /** * {@inheritdoc} */ public function setBasePrice($price) { return $this->setData(InvoiceItemInterface::BASE_PRICE, $price); } /** * {@inheritdoc} */ public function setTaxAmount($amount) { return $this->setData(InvoiceItemInterface::TAX_AMOUNT, $amount); } /** * {@inheritdoc} */ public function setBaseRowTotal($amount) { return $this->setData(InvoiceItemInterface::BASE_ROW_TOTAL, $amount); } /** * {@inheritdoc} */ public function setDiscountAmount($amount) { return $this->setData(InvoiceItemInterface::DISCOUNT_AMOUNT, $amount); } /** * {@inheritdoc} */ public function setRowTotal($amount) { return $this->setData(InvoiceItemInterface::ROW_TOTAL, $amount); } /** * {@inheritdoc} */ public function setBaseDiscountAmount($amount) { return $this->setData(InvoiceItemInterface::BASE_DISCOUNT_AMOUNT, $amount); } /** * {@inheritdoc} */ public function setPriceInclTax($amount) { return $this->setData(InvoiceItemInterface::PRICE_INCL_TAX, $amount); } /** * {@inheritdoc} */ public function setBaseTaxAmount($amount) { return $this->setData(InvoiceItemInterface::BASE_TAX_AMOUNT, $amount); } /** * {@inheritdoc} */ public function setBasePriceInclTax($amount) { return $this->setData(InvoiceItemInterface::BASE_PRICE_INCL_TAX, $amount); } /** * {@inheritdoc} */ public function setBaseCost($baseCost) { return $this->setData(InvoiceItemInterface::BASE_COST, $baseCost); } /** * {@inheritdoc} */ public function setPrice($price) { return $this->setData(InvoiceItemInterface::PRICE, $price); } /** * {@inheritdoc} */ public function setBaseRowTotalInclTax($amount) { return $this->setData(InvoiceItemInterface::BASE_ROW_TOTAL_INCL_TAX, $amount); } /** * {@inheritdoc} */ public function setRowTotalInclTax($amount) { return $this->setData(InvoiceItemInterface::ROW_TOTAL_INCL_TAX, $amount); } /** * {@inheritdoc} */ public function setProductId($id) { return $this->setData(InvoiceItemInterface::PRODUCT_ID, $id); } /** * {@inheritdoc} */ public function setOrderItemId($id) { return $this->setData(InvoiceItemInterface::ORDER_ITEM_ID, $id); } /** * {@inheritdoc} */ public function setAdditionalData($additionalData) { return $this->setData(InvoiceItemInterface::ADDITIONAL_DATA, $additionalData); } /** * {@inheritdoc} */ public function setDescription($description) { return $this->setData(InvoiceItemInterface::DESCRIPTION, $description); } /** * {@inheritdoc} */ public function setSku($sku) { return $this->setData(InvoiceItemInterface::SKU, $sku); } /** * {@inheritdoc} */ public function setName($name) { return $this->setData(InvoiceItemInterface::NAME, $name); } /** * {@inheritdoc} */ public function setDiscountTaxCompensationAmount($amount) { return $this->setData(InvoiceItemInterface::DISCOUNT_TAX_COMPENSATION_AMOUNT, $amount); } /** * {@inheritdoc} */ public function setBaseDiscountTaxCompensationAmount($amount) { return $this->setData(InvoiceItemInterface::BASE_DISCOUNT_TAX_COMPENSATION_AMOUNT, $amount); } /** * {@inheritdoc} * * @return \Magento\Sales\Api\Data\InvoiceItemExtensionInterface|null */ public function getExtensionAttributes() { return $this->_getExtensionAttributes(); } /** * {@inheritdoc} * * @param \Magento\Sales\Api\Data\InvoiceItemExtensionInterface $extensionAttributes * @return $this */ public function setExtensionAttributes(\Magento\Sales\Api\Data\InvoiceItemExtensionInterface $extensionAttributes) { return $this->_setExtensionAttributes($extensionAttributes); } //@codeCoverageIgnoreEnd }
{ "content_hash": "1883cac95eac7eba4b254c88eca06a37", "timestamp": "", "source": "github", "line_count": 693, "max_line_length": 118, "avg_line_length": 26.32034632034632, "alnum_prop": 0.6144736842105263, "repo_name": "enettolima/magento-training", "id": "2e8b66e891e82c9e240b876957aedc9abf363f60", "size": "18338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "magento2ce/app/code/Magento/Sales/Model/Order/Invoice/Item.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "22648" }, { "name": "CSS", "bytes": "3382928" }, { "name": "HTML", "bytes": "8749335" }, { "name": "JavaScript", "bytes": "7355635" }, { "name": "PHP", "bytes": "58607662" }, { "name": "Perl", "bytes": "10258" }, { "name": "Shell", "bytes": "41887" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
package net.sf.farrago.type.runtime; /** * NullableValue is an interface representing a runtime holder for a nullable * object. * * @author John V. Sichi * @version $Id$ */ public interface NullableValue extends DataValue { //~ Static fields/initializers --------------------------------------------- /** * Name of accessor method for null indicator. */ public static final String NULL_IND_ACCESSOR_NAME = "isNull"; /** * Name of accessor method for null indicator. */ public static final String NULL_IND_MUTATOR_NAME = "setNull"; //~ Methods ---------------------------------------------------------------- /** * Sets whether or not the value is null. Note that once a value has been * set to null, its data should not be updated until the null state has been * cleared with a call to setNull(false). * * @param isNull true to set a null value; false to indicate a non-null * value */ void setNull(boolean isNull); /** * @return whether the value has been set to null */ boolean isNull(); } // End NullableValue.java
{ "content_hash": "a2d80919f9174b59cd542089ec01f807", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 80, "avg_line_length": 25.931818181818183, "alnum_prop": 0.5810692375109553, "repo_name": "julianhyde/luciddb", "id": "5e2b1a7c857c4b36c4a534da288a631aaafaec7a", "size": "1939", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "farrago/src/net/sf/farrago/type/runtime/NullableValue.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Savvy::render() array test --FILE-- <?php require dirname(__FILE__) . '/../test_framework.php.inc'; chdir(__DIR__); $savvy = new Savvy(); $array = array(1,2,3); $test->assertEquals('123', $savvy->render($array), 'render array'); $array = array(1,2,3); $test->assertEquals('123', $savvy->render($array, 'echostring.tpl.php'), 'render array through custom template'); ?> ===DONE=== --EXPECT-- ===DONE===
{ "content_hash": "3f284e6ec2d710398f4b67378f373de4", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 113, "avg_line_length": 23.764705882352942, "alnum_prop": 0.6287128712871287, "repo_name": "unl/UNL_UCBCN_System", "id": "a049a9330242f049725daa353904709cb43c99c2", "size": "413", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/tests/phpsavant.com/Savvy/render/array.phpt", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "63804" }, { "name": "HTML", "bytes": "229362" }, { "name": "JavaScript", "bytes": "20896" }, { "name": "Makefile", "bytes": "1992" }, { "name": "PHP", "bytes": "622236" }, { "name": "Pascal", "bytes": "9896" }, { "name": "Puppet", "bytes": "1336688" }, { "name": "Ruby", "bytes": "2850606" }, { "name": "Shell", "bytes": "239415" }, { "name": "VimL", "bytes": "10274" } ], "symlink_target": "" }
"""Tests for the T9 model.""" from pynini.examples import t9 from absl.testing import absltest class T9Test(absltest.TestCase): t9: t9.T9 @classmethod def setUpClass(cls): super().setUpClass() lexicon = [ "the", "cool", "warthog", "escaped", "easily", "from", "baltimore", "zoo", "col" ] cls.t9 = t9.T9(lexicon) def testExample(self): example = "the cool warthog escaped easily from baltimore zoo" encoded = self.t9.encode(example) self.assertTrue(example in self.t9.decode(encoded).paths().ostrings()) if __name__ == "__main__": absltest.main()
{ "content_hash": "9cd3ec31a5360b3a9fe102026140589e", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 75, "avg_line_length": 21.03448275862069, "alnum_prop": 0.6360655737704918, "repo_name": "kylebgorman/pynini", "id": "3257ac269ef456c1d9c04717b4c56f5463c056ad", "size": "1287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/t9_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "173515" }, { "name": "Cython", "bytes": "285320" }, { "name": "Python", "bytes": "287089" }, { "name": "Shell", "bytes": "1897" }, { "name": "Starlark", "bytes": "31558" } ], "symlink_target": "" }
if [ -e /usr/local/bin/ ]; then INSTALLTO='/usr/local/bin' else INSTALLTO='/usr/bin' fi install -m 755 encdir.sh $INSTALLTO/ install -m 755 decdir.sh $INSTALLTO/ install -m 755 encfile.sh $INSTALLTO/ install -m 755 decfile.sh $INSTALLTO/
{ "content_hash": "8bfbb107163f97057ec9878e0cd30ff9", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 37, "avg_line_length": 24.1, "alnum_prop": 0.7178423236514523, "repo_name": "cmd184psu/fs-tools", "id": "7e948d77bec236fbbc40f5ff03b6027cef65f338", "size": "252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "encrypt/installscripts.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "353" }, { "name": "C++", "bytes": "314472" }, { "name": "Go", "bytes": "47957" }, { "name": "Makefile", "bytes": "15357" }, { "name": "Shell", "bytes": "19811" } ], "symlink_target": "" }
// // Copyright Microsoft Corporation. All rights reserved. // ericroz - Sept 2015 // using System; using System.Runtime.Serialization; namespace ProviderFactory.Speech.RxToProjectOxford.Exceptions { /// <summary> /// Exception thrown when initial silence in the audio exceeded the maximum limit. /// </summary> [Serializable] public class InitialSilenceTimeoutException : SpeechTimeoutException { /// <summary> /// Default constructor for <see cref="InitialSilenceTimeoutException"/>. /// </summary> public InitialSilenceTimeoutException() { } /// <summary> /// Message constructor for <see cref="InitialSilenceTimeoutException"/>. /// </summary> /// <param name="message">The exception message.</param> public InitialSilenceTimeoutException(string message) : base(message) { } /// <summary> /// Message and inner exception constructor for <see cref="InitialSilenceTimeoutException"/>. /// </summary> /// <param name="message">The exception message.</param> /// <param name="innerException">The inner exception.</param> public InitialSilenceTimeoutException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Serialization context constructor for <see cref="InitialSilenceTimeoutException"/>. /// </summary> /// <param name="info">The serialization info.</param> /// <param name="context">The serialization context.</param> protected InitialSilenceTimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
{ "content_hash": "e6658e39edce618a61e005422b7400d4", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 101, "avg_line_length": 35.86274509803921, "alnum_prop": 0.6183706943685073, "repo_name": "jpoon/SpotifySearch", "id": "73835718ac913c6a464485cfb704229926d76d5d", "size": "1831", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ProviderFactory/Speech/RxToProjectOxford/Exceptions/InitialSilenceTimeoutException.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "105" }, { "name": "C#", "bytes": "44496" }, { "name": "CSS", "bytes": "537" }, { "name": "JavaScript", "bytes": "19689" } ], "symlink_target": "" }
package org.apache.hadoop.hive.conf; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; /** * validate value for a ConfVar, return non-null string for fail message */ public interface Validator { String validate(String value); String toDescription(); class StringSet implements Validator { private final boolean caseSensitive; private final Set<String> expected = new LinkedHashSet<String>(); public StringSet(String... values) { this(false, values); } public StringSet(boolean caseSensitive, String... values) { this.caseSensitive = caseSensitive; for (String value : values) { expected.add(caseSensitive ? value : value.toLowerCase()); } } public Set<String> getExpected() { return new HashSet<String>(expected); } @Override public String validate(String value) { if (value == null || !expected.contains(caseSensitive ? value : value.toLowerCase())) { return "Invalid value.. expects one of " + expected; } return null; } @Override public String toDescription() { return "Expects one of " + expected; } } enum TYPE { INT { @Override protected boolean inRange(String value, Object lower, Object upper) { int ivalue = Integer.parseInt(value); if (lower != null && ivalue < (Integer)lower) { return false; } if (upper != null && ivalue > (Integer)upper) { return false; } return true; } }, LONG { @Override protected boolean inRange(String value, Object lower, Object upper) { long lvalue = Long.parseLong(value); if (lower != null && lvalue < (Long)lower) { return false; } if (upper != null && lvalue > (Long)upper) { return false; } return true; } }, FLOAT { @Override protected boolean inRange(String value, Object lower, Object upper) { float fvalue = Float.parseFloat(value); if (lower != null && fvalue < (Float)lower) { return false; } if (upper != null && fvalue > (Float)upper) { return false; } return true; } }; public static TYPE valueOf(Object lower, Object upper) { if (lower instanceof Integer || upper instanceof Integer) { return INT; } else if (lower instanceof Long || upper instanceof Long) { return LONG; } else if (lower instanceof Float || upper instanceof Float) { return FLOAT; } throw new IllegalArgumentException("invalid range from " + lower + " to " + upper); } protected abstract boolean inRange(String value, Object lower, Object upper); } class RangeValidator implements Validator { private final TYPE type; private final Object lower, upper; public RangeValidator(Object lower, Object upper) { this.lower = lower; this.upper = upper; this.type = TYPE.valueOf(lower, upper); } @Override public String validate(String value) { try { if (value == null) { return "Value cannot be null"; } if (!type.inRange(value.trim(), lower, upper)) { return "Invalid value " + value + ", which should be in between " + lower + " and " + upper; } } catch (Exception e) { return e.toString(); } return null; } @Override public String toDescription() { if (lower == null && upper == null) { return null; } if (lower != null && upper != null) { return "Expects value between " + lower + " and " + upper; } if (lower != null) { return "Expects value bigger than " + lower; } return "Expects value smaller than " + upper; } } class PatternSet implements Validator { private final List<Pattern> expected = new ArrayList<Pattern>(); public PatternSet(String... values) { for (String value : values) { expected.add(Pattern.compile(value)); } } @Override public String validate(String value) { if (value == null) { return "Invalid value.. expects one of patterns " + expected; } for (Pattern pattern : expected) { if (pattern.matcher(value).matches()) { return null; } } return "Invalid value.. expects one of patterns " + expected; } @Override public String toDescription() { return "Expects one of the pattern in " + expected; } } class RatioValidator implements Validator { @Override public String validate(String value) { try { float fvalue = Float.valueOf(value); if (fvalue < 0 || fvalue > 1) { return "Invalid ratio " + value + ", which should be in between 0 to 1"; } } catch (NumberFormatException e) { return e.toString(); } return null; } @Override public String toDescription() { return "Expects value between 0.0f and 1.0f"; } } class TimeValidator implements Validator { private final TimeUnit timeUnit; private final Long min; private final boolean minInclusive; private final Long max; private final boolean maxInclusive; public TimeValidator(TimeUnit timeUnit) { this(timeUnit, null, false, null, false); } public TimeValidator(TimeUnit timeUnit, Long min, boolean minInclusive, Long max, boolean maxInclusive) { this.timeUnit = timeUnit; this.min = min; this.minInclusive = minInclusive; this.max = max; this.maxInclusive = maxInclusive; } public TimeUnit getTimeUnit() { return timeUnit; } @Override public String validate(String value) { try { long time = HiveConf.toTime(value, timeUnit, timeUnit); if (min != null && (minInclusive ? time < min : time <= min)) { return value + " is smaller than " + timeString(min); } if (max != null && (maxInclusive ? time > max : time >= max)) { return value + " is bigger than " + timeString(max); } } catch (Exception e) { return e.toString(); } return null; } public String toDescription() { String description = "Expects a time value with unit " + "(d/day, h/hour, m/min, s/sec, ms/msec, us/usec, ns/nsec)" + ", which is " + HiveConf.stringFor(timeUnit) + " if not specified"; if (min != null && max != null) { description += ".\nThe time should be in between " + timeString(min) + (minInclusive ? " (inclusive)" : " (exclusive)") + " and " + timeString(max) + (maxInclusive ? " (inclusive)" : " (exclusive)"); } else if (min != null) { description += ".\nThe time should be bigger than " + (minInclusive ? "or equal to " : "") + timeString(min); } else if (max != null) { description += ".\nThe time should be smaller than " + (maxInclusive ? "or equal to " : "") + timeString(max); } return description; } private String timeString(long time) { return time + " " + HiveConf.stringFor(timeUnit); } } }
{ "content_hash": "b84d22d68955723bd97cc7cfcac10815", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 103, "avg_line_length": 27.809701492537314, "alnum_prop": 0.5847309808130954, "repo_name": "cschenyuan/hive-hack", "id": "04a305dbf15376c116ae660cdb8a42bc948ae6e3", "size": "8259", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "common/src/java/org/apache/hadoop/hive/conf/Validator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "46615" }, { "name": "C", "bytes": "120921" }, { "name": "C++", "bytes": "163812" }, { "name": "CSS", "bytes": "1372" }, { "name": "GAP", "bytes": "116185" }, { "name": "Groff", "bytes": "5379" }, { "name": "HTML", "bytes": "22057" }, { "name": "Java", "bytes": "24195278" }, { "name": "M", "bytes": "2173" }, { "name": "Makefile", "bytes": "6963" }, { "name": "PHP", "bytes": "1699131" }, { "name": "PLpgSQL", "bytes": "43781" }, { "name": "Perl", "bytes": "316328" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Protocol Buffer", "bytes": "6353" }, { "name": "Python", "bytes": "267896" }, { "name": "SQLPL", "bytes": "1414" }, { "name": "Shell", "bytes": "149965" }, { "name": "Thrift", "bytes": "92545" }, { "name": "XSLT", "bytes": "7619" } ], "symlink_target": "" }
BOOST_AUTO_TEST_CASE(check_pbool) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.pbool(false); const auto false_v = vm.top(); BOOST_CHECK_EQUAL(false_v.tag(), vv::tag::boolean); BOOST_CHECK(false_v.type() == vv::builtin::type::boolean); BOOST_CHECK_EQUAL(vv::value::get<vv::value::boolean>(false_v), false); vm.pbool(true); const auto true_v = vm.top(); BOOST_CHECK_EQUAL(true_v.tag(), vv::tag::boolean); BOOST_CHECK(true_v.type() == vv::builtin::type::boolean); BOOST_CHECK_EQUAL(vv::value::get<vv::value::boolean>(true_v), true); } void check_pchar(const char orig) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.pchar(orig); const auto val = vm.top(); BOOST_CHECK_EQUAL(val.tag(), vv::tag::character); BOOST_CHECK(val.type() == vv::builtin::type::character); BOOST_CHECK_EQUAL(vv::value::get<vv::value::character>(val), orig); } void check_pflt(const double orig) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.pflt(orig); const auto val = vm.top(); BOOST_CHECK_EQUAL(val.tag(), vv::tag::floating_point); BOOST_CHECK(val.type() == vv::builtin::type::floating_point); BOOST_CHECK_EQUAL(vv::value::get<vv::value::floating_point>(val), orig); } void check_pfn(const int argc) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.pfn({ argc, { {vv::vm::instruction::pnil} } }); const auto fn = vm.top(); BOOST_CHECK_EQUAL(fn.tag(), vv::tag::function); BOOST_CHECK(fn.type() == vv::builtin::type::function); BOOST_CHECK_EQUAL(vv::value::get<vv::value::function>(fn).argc, argc); const auto& body = vv::value::get<vv::value::function>(fn).body; BOOST_CHECK_EQUAL(body.size(), 1); BOOST_CHECK(body[0].instr == vv::vm::instruction::pnil); } void check_pint(const int orig) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.pint(orig); const auto val = vm.top(); BOOST_CHECK_EQUAL(val.tag(), vv::tag::integer); BOOST_CHECK(val.type() == vv::builtin::type::integer); BOOST_CHECK_EQUAL(vv::value::get<vv::value::integer>(val), orig); } BOOST_AUTO_TEST_CASE(check_pnil) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.pnil(); const auto nil = vm.top(); BOOST_CHECK_EQUAL(nil.tag(), vv::tag::nil); BOOST_CHECK(nil.type() == vv::builtin::type::nil); } void check_pstr(const std::string& orig) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.pstr(orig); const auto val = vm.top(); BOOST_CHECK_EQUAL(val.tag(), vv::tag::string); BOOST_CHECK(val.type() == vv::builtin::type::string); BOOST_CHECK_EQUAL(vv::value::get<vv::value::string>(val), orig); } void check_psym(const vv::symbol orig) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.psym(orig); const auto val = vm.top(); BOOST_CHECK_EQUAL(val.tag(), vv::tag::symbol); BOOST_CHECK(val.type() == vv::builtin::type::symbol); BOOST_CHECK_EQUAL(vv::value::get<vv::symbol>(val), orig); } BOOST_AUTO_TEST_CASE(check_parr) { vv::vm::machine vm{vv::vm::call_frame{}}; vm.parr(0); const auto val = vm.top(); BOOST_CHECK_EQUAL(val.tag(), vv::tag::array); BOOST_CHECK(val.type() == vv::builtin::type::array); BOOST_CHECK_EQUAL(vv::value::get<vv::value::array>(val).size(), 0); vm.pop(1); vm.pstr("sentinel"); for (auto i = 0; i != 10; ++i) vm.pint(i); vm.parr(10); const auto arr10 = vm.top(); BOOST_CHECK_EQUAL(arr10.tag(), vv::tag::array); BOOST_CHECK(arr10.type() == vv::builtin::type::array); BOOST_CHECK_EQUAL(vv::value::get<vv::value::array>(arr10).size(), 10); for (auto i = 0; i != 10; ++i) { const auto mem = vv::value::get<vv::value::array>(arr10)[i]; BOOST_CHECK_EQUAL(mem.tag(), vv::tag::integer); BOOST_CHECK_EQUAL(vv::value::get<vv::value::integer>(mem), i); } vm.pop(1); const auto sentinel = vm.top(); BOOST_CHECK_EQUAL(sentinel.tag(), vv::tag::string); BOOST_CHECK_EQUAL(vv::value::get<vv::value::string>(sentinel), "sentinel"); } BOOST_AUTO_TEST_CASE(check_read) { vv::vm::call_frame frame{}; frame.env().members[vv::symbol{"foo"}] = vv::gc::alloc<vv::value::integer>(vv::value::integer{1}); vv::vm::machine vm{std::move(frame)}; vm.read(vv::symbol{"foo"}); const auto foo = vm.top(); BOOST_CHECK_EQUAL(foo.tag(), vv::tag::integer); BOOST_CHECK_EQUAL(vv::value::get<vv::value::integer>(foo), 1); BOOST_CHECK_THROW(vm.read(vv::symbol{"I don't exist"}), vv::vm_error); } boost::unit_test::test_suite* init_unit_test_suite(int argc, char** argv) { vv::builtin::init(); std::array<int64_t, 1004> ints; ints[0] = std::numeric_limits<int32_t>::min(); ints[1] = std::numeric_limits<int32_t>::max(); ints[2] = int64_t{-1} << 47; ints[3] = (int64_t{1} << 47) - 1; std::iota(begin(ints) + 4, end(ints), -500); boost::unit_test::framework::master_test_suite().add( BOOST_PARAM_TEST_CASE(&check_pint, begin(ints), end(ints))); std::array<char, 256> chars; std::iota(begin(chars), end(chars), '\0'); boost::unit_test::framework::master_test_suite().add( BOOST_PARAM_TEST_CASE(&check_pchar, begin(chars), end(chars))); std::array<double, 1003> doubles; doubles[0] = std::numeric_limits<double>::min(); doubles[1] = std::numeric_limits<double>::max(); doubles[2] = 0.125; std::iota(begin(doubles) + 3, end(doubles), -500.0); std::array<int64_t, 1002> argcs; argcs[0] = std::numeric_limits<int32_t>::min(); argcs[1] = std::numeric_limits<int32_t>::max(); std::iota(begin(argcs) + 2, end(argcs), -500); boost::unit_test::framework::master_test_suite().add( BOOST_PARAM_TEST_CASE(&check_pfn, begin(argcs), end(argcs))); boost::unit_test::framework::master_test_suite().add( BOOST_PARAM_TEST_CASE(&check_pflt, begin(doubles), end(doubles))); const auto strings = { "", "foo", "hello world", // I don't really know what there is to test for this one. Check weird // attempts at parsing, maybe? "do", "let", "fn", // Or maybe escaped characters? "foo\"bar", "foo\\\n\tbar" }; boost::unit_test::framework::master_test_suite().add( BOOST_PARAM_TEST_CASE(&check_pstr, begin(strings), end(strings))); std::array<vv::symbol, 8> symbols {{ {"foo"}, {"bar"}, {"do"}, {"let"}, {"foo bar baz"}, // ensure repeats work correctly {"foo"}, {""}, {"Integer"} }}; boost::unit_test::framework::master_test_suite().add( BOOST_PARAM_TEST_CASE(&check_psym, begin(symbols), end(symbols))); return nullptr; }
{ "content_hash": "0d4e3eebda3144c4ca71754ef1135e03", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 100, "avg_line_length": 30.117924528301888, "alnum_prop": 0.6256851996867658, "repo_name": "jeorgun/Vivaldi", "id": "bb2ad328fc68585407c85be937850a28727c0ad3", "size": "6735", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/vm_instrs.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "390880" }, { "name": "CMake", "bytes": "5542" } ], "symlink_target": "" }
/* * ptf_id.hpp * * Created on: 2012-9-11 * Author: YH */ #ifndef PTF_ID_HPP_ #define PTF_ID_HPP_ namespace matrix { namespace platform { enum class PlatformID { Unix, Linux, Windows, MacOSX, Xbox, }; #if defined (__WINNT__) constexpr PlatformID kPlatformID = PlatformID::Windows; #elif defined(__linux__) constexpr PlatformID kPlatformID = PlatformID::Linux; #endif constexpr PlatformID getPlatformID() { return kPlatformID; } } // namespace platform } // namespace matrix #endif /* PTF_ID_HPP_ */
{ "content_hash": "a0bc9bf26650179b48f3dd2af48570a8", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 55, "avg_line_length": 15.17142857142857, "alnum_prop": 0.6741996233521658, "repo_name": "sy-yanghuan/Matrix", "id": "3ef6132f538fc7f89814018d67b58d00b40062bc", "size": "531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/matrix/platform/ptf_id.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "16890" }, { "name": "C++", "bytes": "101496" } ], "symlink_target": "" }
package org.redisson.client.handler; import java.util.List; import java.util.Queue; import org.redisson.client.protocol.CommandData; import org.redisson.client.protocol.QueueCommand; import org.redisson.client.protocol.QueueCommandHolder; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.util.AttributeKey; import io.netty.util.internal.PlatformDependent; /** * * * @author Nikita Koksharov * */ public class CommandsQueue extends ChannelDuplexHandler { public enum QueueCommands {NEXT_COMMAND} public static final AttributeKey<QueueCommand> REPLAY = AttributeKey.valueOf("promise"); private final Queue<QueueCommandHolder> queue = PlatformDependent.newMpscQueue(); @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == QueueCommands.NEXT_COMMAND) { queue.poll(); sendData(ctx); } else { super.userEventTriggered(ctx, evt); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof QueueCommand) { QueueCommand data = (QueueCommand) msg; if (queue.peek() != null && queue.peek().getCommand() == data) { super.write(ctx, msg, promise); } else { queue.add(new QueueCommandHolder(data, promise)); sendData(ctx); } } else { super.write(ctx, msg, promise); } } private void sendData(ChannelHandlerContext ctx) throws Exception { QueueCommandHolder command = queue.peek(); if (command != null && command.getSended().compareAndSet(false, true)) { QueueCommand data = command.getCommand(); List<CommandData<Object, Object>> pubSubOps = data.getPubSubOperations(); if (!pubSubOps.isEmpty()) { for (CommandData<Object, Object> cd : pubSubOps) { for (Object channel : cd.getParams()) { ctx.pipeline().get(CommandDecoder.class).addChannel(channel.toString(), cd); } } } else { ctx.channel().attr(REPLAY).set(data); } ctx.channel().writeAndFlush(data, command.getChannelPromise()); } } }
{ "content_hash": "e87626f032e41f08f9c2148d3973641c", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 103, "avg_line_length": 33.33783783783784, "alnum_prop": 0.6299148763680583, "repo_name": "fengshao0907/redisson", "id": "056e31b35e0546d0aaf200555a453eda34471e56", "size": "3083", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/main/java/org/redisson/client/handler/CommandsQueue.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "691502" } ], "symlink_target": "" }
 #pragma once #include <aws/frauddetector/FraudDetector_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace FraudDetector { namespace Model { /** * <p>Details for the external events data used for model version * training.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/frauddetector-2019-11-15/ExternalEventsDetail">AWS * API Reference</a></p> */ class AWS_FRAUDDETECTOR_API ExternalEventsDetail { public: ExternalEventsDetail(); ExternalEventsDetail(Aws::Utils::Json::JsonView jsonValue); ExternalEventsDetail& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The Amazon S3 bucket location for the data.</p> */ inline const Aws::String& GetDataLocation() const{ return m_dataLocation; } /** * <p>The Amazon S3 bucket location for the data.</p> */ inline bool DataLocationHasBeenSet() const { return m_dataLocationHasBeenSet; } /** * <p>The Amazon S3 bucket location for the data.</p> */ inline void SetDataLocation(const Aws::String& value) { m_dataLocationHasBeenSet = true; m_dataLocation = value; } /** * <p>The Amazon S3 bucket location for the data.</p> */ inline void SetDataLocation(Aws::String&& value) { m_dataLocationHasBeenSet = true; m_dataLocation = std::move(value); } /** * <p>The Amazon S3 bucket location for the data.</p> */ inline void SetDataLocation(const char* value) { m_dataLocationHasBeenSet = true; m_dataLocation.assign(value); } /** * <p>The Amazon S3 bucket location for the data.</p> */ inline ExternalEventsDetail& WithDataLocation(const Aws::String& value) { SetDataLocation(value); return *this;} /** * <p>The Amazon S3 bucket location for the data.</p> */ inline ExternalEventsDetail& WithDataLocation(Aws::String&& value) { SetDataLocation(std::move(value)); return *this;} /** * <p>The Amazon S3 bucket location for the data.</p> */ inline ExternalEventsDetail& WithDataLocation(const char* value) { SetDataLocation(value); return *this;} /** * <p>The ARN of the role that provides Amazon Fraud Detector access to the data * location.</p> */ inline const Aws::String& GetDataAccessRoleArn() const{ return m_dataAccessRoleArn; } /** * <p>The ARN of the role that provides Amazon Fraud Detector access to the data * location.</p> */ inline bool DataAccessRoleArnHasBeenSet() const { return m_dataAccessRoleArnHasBeenSet; } /** * <p>The ARN of the role that provides Amazon Fraud Detector access to the data * location.</p> */ inline void SetDataAccessRoleArn(const Aws::String& value) { m_dataAccessRoleArnHasBeenSet = true; m_dataAccessRoleArn = value; } /** * <p>The ARN of the role that provides Amazon Fraud Detector access to the data * location.</p> */ inline void SetDataAccessRoleArn(Aws::String&& value) { m_dataAccessRoleArnHasBeenSet = true; m_dataAccessRoleArn = std::move(value); } /** * <p>The ARN of the role that provides Amazon Fraud Detector access to the data * location.</p> */ inline void SetDataAccessRoleArn(const char* value) { m_dataAccessRoleArnHasBeenSet = true; m_dataAccessRoleArn.assign(value); } /** * <p>The ARN of the role that provides Amazon Fraud Detector access to the data * location.</p> */ inline ExternalEventsDetail& WithDataAccessRoleArn(const Aws::String& value) { SetDataAccessRoleArn(value); return *this;} /** * <p>The ARN of the role that provides Amazon Fraud Detector access to the data * location.</p> */ inline ExternalEventsDetail& WithDataAccessRoleArn(Aws::String&& value) { SetDataAccessRoleArn(std::move(value)); return *this;} /** * <p>The ARN of the role that provides Amazon Fraud Detector access to the data * location.</p> */ inline ExternalEventsDetail& WithDataAccessRoleArn(const char* value) { SetDataAccessRoleArn(value); return *this;} private: Aws::String m_dataLocation; bool m_dataLocationHasBeenSet; Aws::String m_dataAccessRoleArn; bool m_dataAccessRoleArnHasBeenSet; }; } // namespace Model } // namespace FraudDetector } // namespace Aws
{ "content_hash": "3947fcccddd73b27e71ee2d267901e4b", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 139, "avg_line_length": 32.69565217391305, "alnum_prop": 0.6784131205673759, "repo_name": "awslabs/aws-sdk-cpp", "id": "317d8ed7df5942cb4db8c2c3a8826691f126b61d", "size": "4631", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-cpp-sdk-frauddetector/include/aws/frauddetector/model/ExternalEventsDetail.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7596" }, { "name": "C++", "bytes": "61740540" }, { "name": "CMake", "bytes": "337520" }, { "name": "Java", "bytes": "223122" }, { "name": "Python", "bytes": "47357" } ], "symlink_target": "" }
<?php App::uses('Musicplayer', 'Musicplayer.Model'); /** * Musicplayer Test Case * */ class MusicplayerTest extends CakeTestCase { /** * Fixtures * * @var array */ public $fixtures = array( 'plugin.musicplayer.musicplayer', 'plugin.musicplayer.playlist' ); /** * setUp method * * @return void */ public function setUp() { parent::setUp(); $this->Musicplayer = ClassRegistry::init('Musicplayer.Musicplayer'); } /** * tearDown method * * @return void */ public function tearDown() { unset($this->Musicplayer); parent::tearDown(); } }
{ "content_hash": "7bfecfe3390552bf6a19a24b04ef96d0", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 70, "avg_line_length": 13.926829268292684, "alnum_prop": 0.6444833625218914, "repo_name": "zhkuskov/croogo_cms_2.0", "id": "45ff4ce8c026bac813a3102f9a76867d95e6c3d5", "size": "571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Vendor/croogo/croogo/Musicplayer/Test/Case/Model/MusicplayerTest.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Author: [email protected] (Megha Mohabey) // Unit-tests for FlushEarlyFlow. #include "pagespeed/automatic/flush_early_flow.h" #include "net/instaweb/http/public/http_cache.h" #include "net/instaweb/http/public/log_record.h" #include "net/instaweb/http/public/logging_proto_impl.h" #include "net/instaweb/http/public/mock_url_fetcher.h" #include "net/instaweb/http/public/request_context.h" #include "net/instaweb/http/public/request_timing_info.h" #include "net/instaweb/public/global_constants.h" #include "net/instaweb/rewriter/public/beacon_critical_line_info_finder.h" #include "net/instaweb/rewriter/public/critical_css_filter.h" #include "net/instaweb/rewriter/public/critical_selector_filter.h" #include "net/instaweb/rewriter/public/critical_selector_finder.h" #include "net/instaweb/rewriter/public/flush_early_content_writer_filter.h" #include "net/instaweb/rewriter/public/js_disable_filter.h" #include "net/instaweb/rewriter/public/lazyload_images_filter.h" #include "net/instaweb/rewriter/public/mock_critical_css_finder.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/server_context.h" #include "net/instaweb/rewriter/public/split_html_filter.h" #include "net/instaweb/rewriter/public/static_asset_manager.h" #include "net/instaweb/rewriter/public/test_rewrite_driver_factory.h" #include "net/instaweb/rewriter/public/test_url_namer.h" #include "net/instaweb/rewriter/static_asset_config.pb.h" #include "net/instaweb/util/public/mock_property_page.h" #include "net/instaweb/util/public/property_cache.h" #include "pagespeed/automatic/proxy_interface_test_base.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/mock_timer.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/statistics.h" #include "pagespeed/kernel/base/string.h" #include "pagespeed/kernel/base/string_util.h" #include "pagespeed/kernel/base/time_util.h" #include "pagespeed/kernel/base/timer.h" #include "pagespeed/kernel/cache/lru_cache.h" #include "pagespeed/kernel/html/html_parse_test_base.h" #include "pagespeed/kernel/http/content_type.h" #include "pagespeed/kernel/http/http_names.h" #include "pagespeed/kernel/http/request_headers.h" #include "pagespeed/kernel/http/response_headers.h" #include "pagespeed/kernel/http/user_agent_matcher.h" #include "pagespeed/kernel/http/user_agent_matcher_test_base.h" #include "pagespeed/opt/logging/enums.pb.h" namespace net_instaweb { namespace { const char kMockHashValue[] = "MDAwMD"; const char kCssContent[] = "* { display: none; }"; const char kFlushEarlyHtml[] = "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"/>" "<meta http-equiv=\"last-modified\" content=\"2012-08-09T11:03:27Z\"/>" "<meta charset=\"UTF-8\"/>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://test.com/1.css\">" "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://test.com/2.css\">" "<script src=\"http://test.com/1.js\"></script>" "<script src=\"http://test.com/2.js\"></script>" "<img src=\"http://test.com/1.jpg\"/>" "<script src=\"http://test.com/private.js\"></script>" "<script src=\"http://www.domain1.com/private.js\"></script>" "</head>" "<body>" "Hello, mod_pagespeed!" "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://test.com/3.css\">" "<script src=\"http://www.domain2.com/private.js\"></script>" "<link rel=\"stylesheet\" type=\"text/css\"" " href=\"http://www.domain3.com/3.css\">" "</body>" "</html>"; const char kFlushEarlyMoreResourcesInputHtml[] = "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"/>" "<meta http-equiv=\"last-modified\" content=\"2012-08-09T11:03:27Z\"/>" "<meta charset=\"UTF-8\"/>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://test.com/1.css\">" "</head>" "<body>" "<script src=\"http://test.com/1.js\"></script>" "Hello, mod_pagespeed!" "</body>" "</html>"; const char kCookieScript[] = "<script type=\"text/javascript\" pagespeed_no_defer>" "(function(){" "var data = [\"CG=US:CA:Mountain+View\",\"UA=chrome\",\"path=/\"];" "for (var i = 0; i < data.length; i++) {" "document.cookie = data[i];" "}})()" "</script>"; const char kPreHeadHtml[] = "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>"; const char kRewrittenHtml[] = "<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"/>" "<meta http-equiv=\"last-modified\" content=\"2012-08-09T11:03:27Z\"/>" "<meta charset=\"UTF-8\"/>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">" "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">" "<script src=\"%s\"></script>" "<script src=\"%s\"></script>" "<img src=\"%s\"/>" "<script src=\"http://test.com/private.js\"></script>" "<script src=\"http://www.domain1.com/private.js\"></script>" "</head>" "<body>%s" "Hello, mod_pagespeed!" "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">" "<script src=\"http://www.domain2.com/private.js\"></script>" "<link rel=\"stylesheet\" type=\"text/css\"" " href=\"http://www.domain3.com/3.css\">" "</body>" "</html>"; const char kRewrittenHtmlWithDeferJs[] = "%s" "<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"/>" "<meta http-equiv=\"last-modified\" content=\"2012-08-09T11:03:27Z\"/>" "<meta charset=\"UTF-8\"/>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">" "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">" "<script src=\"%s\" type=\"text/psajs\" orig_index=\"0\">" "</script>" "<script src=\"%s\" type=\"text/psajs\" orig_index=\"1\">" "</script>" "%s" "<script src=\"http://test.com/private.js\"" " type=\"text/psajs\"" " orig_index=\"2\"></script>" "<script src=\"http://www.domain1.com/private.js\"" " type=\"text/psajs\" orig_index=\"3\"></script>" "</head>" "<body>%s" "Hello, mod_pagespeed!" "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">" "<script src=\"http://www.domain2.com/private.js\"" " type=\"text/psajs\" orig_index=\"4\"></script>" "<link rel=\"stylesheet\" type=\"text/css\"" " href=\"http://www.domain3.com/3.css\">" "%s" "</body>" "</html>%s"; const char kRewrittenHtmlForRedirect[] = "<script type=\"text/javascript\">" "window.location.replace(\"%s\")" "</script>" "</head><body></body></html>"; const char kFlushEarlyRewrittenHtmlImageTag[] = "<script type=\"text/javascript\">(function(){" "new Image().src=\"%s\";" "new Image().src=\"%s\";})()</script>" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "%s" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = 5</script>"; const char kFlushEarlyRewrittenHtmlImageTagInsertDnsPrefetch[] = "<script type=\"text/javascript\">(function(){" "new Image().src=\"%s\";" "new Image().src=\"%s\";})()</script>" "<link rel=\"dns-prefetch\" href=\"//www.domain1.com\">" "<link rel=\"dns-prefetch\" href=\"//www.domain2.com\">" "<link rel=\"dns-prefetch\" href=\"//www.domain3.com\">" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "%s" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = 5</script>"; const char kFlushEarlyRewrittenHtmlLinkScript[] = "<link rel=\"stylesheet\" href=\"%s\"/>\n" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "<script type=\"psa_prefetch\" src=\"%s\"></script>\n" "<script type=\"psa_prefetch\" src=\"%s\"></script>\n" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "%s" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = 5</script>"; const char kFlushEarlyRewrittenHtmlWithLazyloadDeferJsScript[] = "<link rel=\"stylesheet\" href=\"%s\"/>\n" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "%s" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = %d</script>"; const char kFlushEarlyRewrittenLinkRelPrefetch[] = "<link rel=\"prefetch\" href=\"%s\"/>\n" "<link rel=\"prefetch\" href=\"%s\"/>\n" "<link rel=\"prefetch\" href=\"%s\"/>\n" "<link rel=\"prefetch\" href=\"%s\"/>\n" "<link rel=\"prefetch\" href=\"%s\"/>\n" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = 5</script>"; const char kFlushEarlyPdf[] = "This is a dummy pdf text."; } // namespace class FlushEarlyFlowTest : public ProxyInterfaceTestBase { protected: static const int kHtmlCacheTimeSec = 5000; FlushEarlyFlowTest() : start_time_ms_(0), request_url_(kTestDomain), noscript_redirect_url_(StrCat(kTestDomain, "?PageSpeed=noscript")), max_age_300_("max-age=300"), request_start_time_ms_(-1), set_httponly_cookie_(false) { ConvertTimeToString(MockTimer::kApr_5_2010_ms, &start_time_string_); ConvertTimeToString(MockTimer::kApr_5_2010_ms + 5 * Timer::kMinuteMs, &start_time_plus_300s_string_); ConvertTimeToString(MockTimer::kApr_5_2010_ms - 2 * Timer::kDayMs, &old_time_string_); } virtual ~FlushEarlyFlowTest() {} virtual void SetUp() { SetMockHashValue("00000"); // Base64 encodes to kMockHashValue. server_context_->set_enable_property_cache(true); const PropertyCache::Cohort* dom_cohort = SetupCohort(server_context_->page_property_cache(), RewriteDriver::kDomCohort); server_context_->set_dom_cohort(dom_cohort); RewriteOptions* options = server_context()->global_options(); options->ClearSignatureForTesting(); options->set_max_html_cache_time_ms(kHtmlCacheTimeSec * Timer::kSecondMs); options->set_in_place_rewriting_enabled(true); server_context()->ComputeSignature(options); ProxyInterfaceTestBase::SetUp(); // The original url_async_fetcher() is still owned by RewriteDriverFactory. background_fetch_fetcher_.reset(new BackgroundFetchCheckingUrlAsyncFetcher( factory()->ComputeUrlAsyncFetcher())); server_context()->set_default_system_fetcher( background_fetch_fetcher_.get()); start_time_ms_ = timer()->NowMs(); rewritten_css_url_1_ = Encode( kTestDomain, "cf", kMockHashValue, "1.css", "css"); rewritten_css_url_2_ = Encode( kTestDomain, "cf", kMockHashValue, "2.css", "css"); rewritten_css_url_3_ = Encode( kTestDomain, "cf", kMockHashValue, "3.css", "css"); rewritten_js_url_1_ = Encode( kTestDomain, "jm", kMockHashValue, "1.js", "js"); rewritten_js_url_2_ = Encode( kTestDomain, "jm", kMockHashValue, "2.js", "js"); rewritten_js_url_3_ = Encode( kTestDomain, "ce", kMockHashValue, "1.js", "js"); rewritten_img_url_1_ = Encode( kTestDomain, "ce", kMockHashValue, "1.jpg", "jpg"); } void SetupForFlushEarlyFlow() { // Setup ResponseHeaders headers; headers.Add(HttpAttributes::kContentType, kContentTypeHtml.mime_type()); headers.Add(HttpAttributes::kSetCookie, "CG=US:CA:Mountain+View"); headers.Add(HttpAttributes::kSetCookie, "UA=chrome"); headers.Add(HttpAttributes::kSetCookie, "path=/"); if (set_httponly_cookie_) { headers.Add(HttpAttributes::kSetCookie, "a=1; HttpOnly"); } headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(request_url_, headers, kFlushEarlyHtml); // Enable FlushSubresourcesFilter filter. RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->EnableFilter(RewriteOptions::kFlushSubresources); rewrite_options->EnableFilter(RewriteOptions::kCombineCss); rewrite_options->EnableFilter(RewriteOptions::kCombineJavascript); rewrite_options->EnableExtendCacheFilters(); // Disabling the inline filters so that the resources get flushed early // else our dummy resources are too small and always get inlined. rewrite_options->DisableFilter(RewriteOptions::kInlineCss); rewrite_options->DisableFilter(RewriteOptions::kInlineJavascript); rewrite_options->ComputeSignature(); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.css"), kContentTypeCss, kCssContent, kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "2.css"), kContentTypeCss, kCssContent, kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "3.css"), kContentTypeCss, kCssContent, kHtmlCacheTimeSec * 2); const char kContent[] = "function f() {alert('foo');}"; SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.js"), kContentTypeJavascript, kContent, kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "2.js"), kContentTypeJavascript, kContent, kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.jpg"), kContentTypeJpeg, "image", kHtmlCacheTimeSec * 2); ResponseHeaders private_headers; DefaultResponseHeaders(kContentTypeJavascript, kHtmlCacheTimeSec, &private_headers); private_headers.SetDateAndCaching(http_cache()->timer()->NowMs(), 300 * Timer::kSecondMs, ", private"); private_headers.ComputeCaching(); SetFetchResponse(AbsolutifyUrl("private.js"), private_headers, "a"); } void VerifyCharset(ResponseHeaders* headers) { EXPECT_TRUE(StringCaseEqual(headers->Lookup1(HttpAttributes::kContentType), "text/html; charset=utf-8")); } GoogleString GetDeferJsCode() { return StrCat("<script type=\"text/javascript\" src=\"", server_context()->static_asset_manager()->GetAssetUrl( StaticAssetEnum::DEFER_JS, options_), "\"></script>"); } GoogleString GetSplitHtmlSuffixCode() { return StringPrintf(SplitHtmlFilter::kSplitSuffixJsFormatString, "/psajs/blink.0.js", SplitHtmlFilter::kLoadHiResImages, 4, "{}", "false"); } GoogleString NoScriptRedirectHtml() { return StringPrintf(kNoScriptRedirectFormatter, noscript_redirect_url_.c_str(), noscript_redirect_url_.c_str()); } GoogleString GetJsDisableScriptSnippet() { if (options_->enable_defer_js_experimental()) { return StrCat("<script type=\"text/javascript\" pagespeed_no_defer>", JsDisableFilter::kEnableJsExperimental, "</script>"); } else { return ""; } } GoogleString RewrittenHtmlWithDeferJs(bool split_html_enabled, const GoogleString& image_tag, bool is_ie) { GoogleString defer_js_injected_html3; GoogleString defer_js_injected_html2 = GetJsDisableScriptSnippet(); if (split_html_enabled) { defer_js_injected_html3 = GetSplitHtmlSuffixCode(); } else { StrAppend(&defer_js_injected_html2, GetDeferJsCode()); } const char kCompatibleMetaTag[] = "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">"; return StringPrintf( kRewrittenHtmlWithDeferJs, (is_ie ? kCompatibleMetaTag : ""), rewritten_css_url_1_.c_str(), rewritten_css_url_2_.c_str(), rewritten_js_url_1_.c_str(), rewritten_js_url_2_.c_str(), image_tag.c_str(), NoScriptRedirectHtml().c_str(), rewritten_css_url_3_.c_str(), defer_js_injected_html2.c_str(), defer_js_injected_html3.c_str()); } GoogleString RewrittenHtml(const GoogleString& noscript_redirect) { return StringPrintf( kRewrittenHtml, rewritten_css_url_1_.c_str(), rewritten_css_url_2_.c_str(), rewritten_js_url_1_.c_str(), rewritten_js_url_2_.c_str(), rewritten_img_url_1_.c_str(), noscript_redirect.c_str(), rewritten_css_url_3_.c_str()); } GoogleString RewrittenHtmlForRedirect() { return StringPrintf(kRewrittenHtmlForRedirect, redirect_url_.c_str()); } GoogleString FlushEarlyRewrittenHtml( UserAgentMatcher::PrefetchMechanism value, bool defer_js_enabled, bool insert_dns_prefetch, bool ua_only_for_flush_early_html) { return FlushEarlyRewrittenHtml(value, defer_js_enabled, insert_dns_prefetch, false, false, false, ua_only_for_flush_early_html, false); } GoogleString GetLazyloadScriptFlushEarly() { return StrCat( "<script type=\"text/javascript\">", LazyloadImagesFilter::GetLazyloadJsSnippet( options_, server_context()->static_asset_manager()), "</script>"); } GoogleString FlushEarlyRewrittenHtml( UserAgentMatcher::PrefetchMechanism value, bool defer_js_enabled, bool insert_dns_prefetch, bool lazyload_enabled, bool redirect_psa_off, bool split_html_enabled, bool ua_only_for_flush_early_html, bool is_ie) { GoogleString flush_early_html; GoogleString cookie_script = kCookieScript; GoogleString rewritten_html; GoogleString expected_deferjs_url = split_html_enabled ? "/psajs/blink.0.js" : "/psajs/js_defer.0.js"; // Get rewritten html. if (defer_js_enabled && !ua_only_for_flush_early_html) { if (lazyload_enabled) { rewritten_html = RewrittenHtmlWithDeferJs( split_html_enabled, StrCat("<img pagespeed_lazy_src=\"", rewritten_img_url_1_, "\" src=\"/psajs/1.0.gif\" onload=\"", LazyloadImagesFilter::kImageOnloadCode, "\" onerror=\"this.onerror=null;", LazyloadImagesFilter::kImageOnloadCode, "\"/>" "<script type=\"text/javascript\" pagespeed_no_defer>" "pagespeed.lazyLoadImages.overrideAttributeFunctions();" "</script>"), is_ie); } else { rewritten_html = RewrittenHtmlWithDeferJs( split_html_enabled, StrCat("<img src=\"", rewritten_img_url_1_, "\"/>"), is_ie); } } else { if (redirect_psa_off) { rewritten_html = RewrittenHtmlForRedirect(); cookie_script = ""; } else if (value == UserAgentMatcher::kPrefetchNotSupported) { rewritten_html = RewrittenHtml(""); } else { rewritten_html = RewrittenHtml(NoScriptRedirectHtml()); } } // Get FlushEarly html. switch (value) { case UserAgentMatcher::kPrefetchLinkScriptTag: if (defer_js_enabled) { flush_early_html = StringPrintf( kFlushEarlyRewrittenHtmlWithLazyloadDeferJsScript, rewritten_css_url_1_.c_str(), rewritten_css_url_2_.c_str(), rewritten_css_url_3_.c_str(), StrCat("<script type=\"psa_prefetch\" src=\"", expected_deferjs_url, "\"></script>\n", FlushEarlyContentWriterFilter::kDisableLinkTag).c_str(), 4); if (lazyload_enabled) { StrAppend(&flush_early_html, GetLazyloadScriptFlushEarly()); } } else { flush_early_html = StringPrintf( kFlushEarlyRewrittenHtmlLinkScript, rewritten_css_url_1_.c_str(), rewritten_css_url_2_.c_str(), rewritten_js_url_1_.c_str(), rewritten_js_url_2_.c_str(), rewritten_css_url_3_.c_str(), FlushEarlyContentWriterFilter::kDisableLinkTag); } break; case UserAgentMatcher::kPrefetchImageTag: if (defer_js_enabled) { flush_early_html = StringPrintf( kFlushEarlyRewrittenHtmlWithLazyloadDeferJsScript, rewritten_css_url_1_.c_str(), rewritten_css_url_2_.c_str(), rewritten_css_url_3_.c_str(), FlushEarlyContentWriterFilter::kDisableLinkTag, 3); } else { GoogleString output_format; if (insert_dns_prefetch) { output_format = kFlushEarlyRewrittenHtmlImageTagInsertDnsPrefetch; } else { output_format = kFlushEarlyRewrittenHtmlImageTag; } flush_early_html = StringPrintf( output_format.c_str(), rewritten_js_url_1_.c_str(), rewritten_js_url_2_.c_str(), rewritten_css_url_1_.c_str(), rewritten_css_url_2_.c_str(), rewritten_css_url_3_.c_str(), FlushEarlyContentWriterFilter::kDisableLinkTag); } break; case UserAgentMatcher::kPrefetchLinkRelPrefetchTag: flush_early_html = StringPrintf( kFlushEarlyRewrittenLinkRelPrefetch, rewritten_css_url_1_.c_str(), rewritten_css_url_2_.c_str(), rewritten_js_url_1_.c_str(), rewritten_js_url_2_.c_str(), rewritten_css_url_3_.c_str()); break; case UserAgentMatcher::kPrefetchNotSupported: default: flush_early_html = ""; cookie_script = ""; break; } // Return combined html. return StrCat(kPreHeadHtml, flush_early_html, cookie_script, rewritten_html); } void ExperimentalFlushEarlyFlowTestHelper( const GoogleString& user_agent, UserAgentMatcher::PrefetchMechanism mechanism, bool inject_error) { ExperimentalFlushEarlyFlowTestHelperWithPropertyCache( user_agent, mechanism, false, false, inject_error); ExperimentalFlushEarlyFlowTestHelperWithPropertyCache( user_agent, mechanism, false, true, inject_error); ExperimentalFlushEarlyFlowTestHelperWithPropertyCache( user_agent, mechanism, true, true, inject_error); ExperimentalFlushEarlyFlowTestHelperWithPropertyCache( user_agent, mechanism, true, false, inject_error); } void ExperimentalFlushEarlyFlowTestHelperWithPropertyCache( const GoogleString& user_agent, UserAgentMatcher::PrefetchMechanism mechanism, bool delay_pcache, bool thread_pcache, bool inject_error) { lru_cache()->Clear(); SetupForFlushEarlyFlow(); GoogleString text; RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, user_agent); ResponseHeaders headers; TestPropertyCacheWithHeadersAndOutput( kTestDomain, delay_pcache, thread_pcache, true, false, false, false, request_headers, &headers, &text); if (inject_error) { ResponseHeaders error_headers; error_headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse( kTestDomain, error_headers, ""); } // Fetch the url again. This time FlushEarlyFlow should not be triggered. // None TestPropertyCacheWithHeadersAndOutput( kTestDomain, delay_pcache, thread_pcache, true, false, false, inject_error, request_headers, &headers, &text); GoogleString expected_output = FlushEarlyRewrittenHtml( mechanism, false, false, true); if (!inject_error) { EXPECT_STREQ(expected_output, text); VerifyCharset(&headers); } } void TestFlushEarlyFlow(const StringPiece& user_agent, UserAgentMatcher::PrefetchMechanism mechanism, bool ua_only_for_flush_early_html) { SetupForFlushEarlyFlow(); GoogleString text; RequestHeaders request_headers; ResponseHeaders headers; request_headers.Replace(HttpAttributes::kUserAgent, user_agent); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Check total number of cache inserts. // 7 for 1.css, 2.css, 3.css, 1.js, 2.js, 1.jpg and private.js. // 19 metadata cache enties - three for cf and jm, seven for ce and // six for fs. // 1 for DomCohort write in property cache. EXPECT_EQ(27, lru_cache()->num_inserts()); // Fetch the url again. This time FlushEarlyFlow should be triggered with // the appropriate prefetch mechanism. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_EQ(FlushEarlyRewrittenHtml(mechanism, false, false, ua_only_for_flush_early_html), text); VerifyCharset(&headers); if (mechanism != UserAgentMatcher::kPrefetchNotSupported) { EXPECT_STREQ("cf,ei,fs,jm", AppliedRewriterStringFromLog()); EXPECT_STREQ("cf,ei,fs,jm", headers.Lookup1(kPsaRewriterHeader)); } } void TestFlushLazyLoadJsEarly(bool is_mobile) { const char kInputHtml[] = "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<title>Flush Subresources Early example</title>" "</head>" "<body>" "<link rel=\"stylesheet\" type=\"text/css\"" " href=\"http://test.com/1.css\">" "<img src=http://test.com/1.jpg />" "Hello, mod_pagespeed!" "</body>" "</html>"; GoogleString redirect_url = StrCat(kTestDomain, "?PageSpeed=noscript"); GoogleString kNotMobileOutputHtml = StrCat( "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>", StringPrintf( "<link rel=\"stylesheet\" href=\"%s\"/>\n" "%s" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = 1" "</script>", rewritten_css_url_1_.c_str(), FlushEarlyContentWriterFilter::kDisableLinkTag), GetLazyloadScriptFlushEarly(), "<title>Flush Subresources Early example</title>" "</head>" "<body>", StringPrintf(kNoScriptRedirectFormatter, redirect_url.c_str(), redirect_url.c_str()), StringPrintf( "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">" "<img pagespeed_lazy_src=http://test.com/1.jpg.pagespeed.ce.%s.jpg" " src=\"/psajs/1.0.gif\"" " onload=\"%s\" onerror=\"this.onerror=null;%s\"/>", rewritten_css_url_1_.c_str(), kMockHashValue, LazyloadImagesFilter::kImageOnloadCode, LazyloadImagesFilter::kImageOnloadCode), "Hello, mod_pagespeed!", GetLazyloadPostscriptHtml(), "</body></html>"); GoogleString kMobileOutputHtml = StrCat( "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>", StringPrintf( "<link rel=\"stylesheet\" href=\"%s\"/>\n" "%s" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = 1" "</script>", rewritten_css_url_1_.c_str(), FlushEarlyContentWriterFilter::kDisableLinkTag), "<title>Flush Subresources Early example</title>", GetLazyloadScriptHtml(), "</head>" "<body>", StringPrintf(kNoScriptRedirectFormatter, redirect_url.c_str(), redirect_url.c_str()), StringPrintf( "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">", rewritten_css_url_1_.c_str()), StringPrintf( "<img pagespeed_lazy_src=http://test.com/1.jpg.pagespeed.ce.%s.jpg" " src=\"/psajs/1.0.gif\"" " onload=\"%s\" onerror=\"this.onerror=null;%s\"/>", kMockHashValue, LazyloadImagesFilter::kImageOnloadCode, LazyloadImagesFilter::kImageOnloadCode), "Hello, mod_pagespeed!", GetLazyloadPostscriptHtml(), "</body></html>"); ResponseHeaders headers; headers.Add(HttpAttributes::kContentType, kContentTypeHtml.mime_type()); headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(kTestDomain, headers, kInputHtml); // Enable FlushSubresourcesFilter filter. RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->EnableFilter(RewriteOptions::kFlushSubresources); rewrite_options->EnableExtendCacheFilters(); // Disabling the inline filters so that the resources get flushed early // else our dummy resources are too small and always get inlined. rewrite_options->DisableFilter(RewriteOptions::kInlineCss); rewrite_options->DisableFilter(RewriteOptions::kInlineJavascript); rewrite_options->ComputeSignature(); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.jpg"), kContentTypeJpeg, "image", kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.css"), kContentTypeCss, kCssContent, kHtmlCacheTimeSec * 2); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kLazyloadImages); SetRewriteOptions(custom_options.get()); GoogleString text; RequestHeaders request_headers; if (is_mobile) { request_headers.Replace( HttpAttributes::kUserAgent, UserAgentMatcherTestBase::kAndroidChrome21UserAgent); } else { request_headers.Replace(HttpAttributes::kUserAgent, "Chrome/ 9.0"); } FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered but no // lazyload js will be flushed early as no resource is present in the html. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); if (is_mobile) { EXPECT_STREQ(kMobileOutputHtml, text); } else { EXPECT_STREQ(kNotMobileOutputHtml, text); } } void TestFlushPreconnects(bool is_mobile) { SetHeaderLatencyMs(200); const char kInputHtml[] = "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\"" " href=\"http://test.com/1.css\">" "</head>" "<body>" "<img src=1.jpg />" "<img src=2.jpg />" "<img src=3.jpg />" "Hello, mod_pagespeed!" "</body>" "</html>"; GoogleString redirect_url = StrCat(kTestDomain, "?PageSpeed=noscript"); const char pre_connect_tag[] = "<link rel=\"stylesheet\" href=\"http://cdn.com/pre_connect?id=%s\"/>"; const char image_tag[] = "<img src=http://cdn.com/http/test.com/http/test.com/%s />"; GoogleString pre_connect_url = "http://cdn.com/pre_connect"; GoogleString kOutputHtml = StringPrintf( "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<link rel=\"stylesheet\" href=\"http://cdn.com/http/" "test.com/http/test.com/A.1.css.pagespeed.cf.%s.css\"/>\n" "%s" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(" "new Date());" "window.mod_pagespeed_num_resources_prefetched = 1</script>", kMockHashValue, FlushEarlyContentWriterFilter::kDisableLinkTag); if (!is_mobile) { StrAppend(&kOutputHtml, StringPrintf(pre_connect_tag, "0"), StringPrintf(pre_connect_tag, "1")); } StrAppend(&kOutputHtml, StringPrintf( "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://cdn.com/http/" "test.com/http/test.com/A.1.css.pagespeed.cf.%s.css\">" "</head>" "<body>", kMockHashValue), StrCat( StringPrintf(kNoScriptRedirectFormatter, redirect_url.c_str(), redirect_url.c_str()), StringPrintf(image_tag, StringPrintf("1.jpg.pagespeed.ce.%s.jpg", kMockHashValue).c_str()), StringPrintf(image_tag, StringPrintf("2.jpg.pagespeed.ce.%s.jpg", kMockHashValue).c_str()), StringPrintf(image_tag, StringPrintf("3.jpg.pagespeed.ce.%s.jpg", kMockHashValue).c_str()), "Hello, mod_pagespeed!" "</body>" "</html>")); ResponseHeaders headers; headers.Add(HttpAttributes::kContentType, kContentTypeHtml.mime_type()); headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(kTestDomain, headers, kInputHtml); // Enable FlushSubresourcesFilter filter. RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->EnableFilter(RewriteOptions::kFlushSubresources); rewrite_options->EnableExtendCacheFilters(); // Disabling the inline filters so that the resources get flushed early // else our dummy resources are too small and always get inlined. rewrite_options->DisableFilter(RewriteOptions::kInlineCss); rewrite_options->DisableFilter(RewriteOptions::kInlineJavascript); rewrite_options->set_pre_connect_url(pre_connect_url); rewrite_options->ComputeSignature(); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.css"), kContentTypeCss, kCssContent, kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.jpg"), kContentTypeJpeg, "image", kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "2.jpg"), kContentTypeJpeg, "image", kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "3.jpg"), kContentTypeJpeg, "image", kHtmlCacheTimeSec * 2); TestUrlNamer url_namer; server_context()->set_url_namer(&url_namer); url_namer.SetProxyMode(true); GoogleString text; RequestHeaders request_headers; if (is_mobile) { request_headers.Replace( HttpAttributes::kUserAgent, UserAgentMatcherTestBase::kAndroidChrome21UserAgent); } else { request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_image_tag"); } FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow and pre connect should be // triggered. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(kOutputHtml, text); } void SetHeaderLatencyMs(int64 latency_ms) { RequestTimingInfo* timing_info = mutable_timing_info(); timing_info->FetchStarted(); AdvanceTimeMs(latency_ms); timing_info->FetchHeaderReceived(); } scoped_ptr<BackgroundFetchCheckingUrlAsyncFetcher> background_fetch_fetcher_; int64 start_time_ms_; GoogleString start_time_string_; GoogleString start_time_plus_300s_string_; GoogleString old_time_string_; GoogleString rewritten_css_url_1_; GoogleString rewritten_css_url_2_; GoogleString rewritten_css_url_3_; GoogleString rewritten_js_url_1_; GoogleString rewritten_js_url_2_; GoogleString rewritten_js_url_3_; GoogleString rewritten_img_url_1_; GoogleString request_url_; GoogleString redirect_url_; GoogleString noscript_redirect_url_; const GoogleString max_age_300_; int64 request_start_time_ms_; bool set_httponly_cookie_; }; // TODO(mpalem): Add tests for max_prefetch_js_elements and defer Js. TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTest) { TestFlushEarlyFlow(NULL, UserAgentMatcher::kPrefetchNotSupported, true); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestPrefetch) { TestFlushEarlyFlow("prefetch_link_script_tag", UserAgentMatcher::kPrefetchLinkScriptTag, true); rewrite_driver_->log_record()->WriteLog(); EXPECT_EQ(5, logging_info()->rewriter_stats_size()); EXPECT_STREQ("fs", logging_info()->rewriter_stats(2).id()); const RewriterStats& stats = logging_info()->rewriter_stats(2); EXPECT_EQ(RewriterHtmlApplication::ACTIVE, stats.html_status()); EXPECT_EQ(2, stats.status_counts_size()); const RewriteStatusCount& applied = stats.status_counts(0); EXPECT_EQ(RewriterApplication::APPLIED_OK, applied.application_status()); EXPECT_EQ(6, applied.count()); const RewriteStatusCount& not_applied = stats.status_counts(1); EXPECT_EQ(RewriterApplication::NOT_APPLIED, not_applied.application_status()); EXPECT_EQ(2, not_applied.count()); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestPcacheMiss) { SetupForFlushEarlyFlow(); GoogleString text; RequestHeaders request_headers; ResponseHeaders headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_link_script_tag"); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); rewrite_driver_->log_record()->WriteLog(); EXPECT_EQ(5, logging_info()->rewriter_stats_size()); EXPECT_STREQ("fs", logging_info()->rewriter_stats(2).id()); const RewriterStats& stats = logging_info()->rewriter_stats(2); EXPECT_EQ(RewriterHtmlApplication::PROPERTY_CACHE_MISS, stats.html_status()); EXPECT_EQ(0, stats.status_counts_size()); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestFallbackPageUsage) { SetupForFlushEarlyFlow(); // Enable UseFallbackPropertyCacheValues. scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->set_use_fallback_property_cache_values(true); SetRewriteOptions(custom_options.get()); // Setting up mock responses for the url and fallback url. GoogleString url = StrCat(kTestDomain, "a.html?query=some"); GoogleString fallback_url = StrCat(kTestDomain, "a.html?different_query=some"); ResponseHeaders response_headers; response_headers.Add( HttpAttributes::kContentType, kContentTypeHtml.mime_type()); response_headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(url, response_headers, kFlushEarlyHtml); mock_url_fetcher_.SetResponse( fallback_url, response_headers, kFlushEarlyHtml); GoogleString text; RequestHeaders request_headers; ResponseHeaders headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_link_script_tag"); FetchFromProxy(url, request_headers, true, &text, &headers); // Request another url with different query params so that fallback values // will be used. FetchFromProxy(fallback_url, request_headers, true, &text, &headers); rewrite_driver_->log_record()->WriteLog(); EXPECT_EQ(5, logging_info()->rewriter_stats_size()); EXPECT_STREQ("fs", logging_info()->rewriter_stats(2).id()); const RewriterStats& fallback_stats = logging_info()->rewriter_stats(2); EXPECT_EQ(RewriterHtmlApplication::ACTIVE, fallback_stats.html_status()); EXPECT_EQ(2, fallback_stats.status_counts_size()); } TEST_F(FlushEarlyFlowTest, FallBackWithNonHtmlResourceIsRedirected) { SetupForFlushEarlyFlow(); // Enable UseFallbackPropertyCacheValues. scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->set_use_fallback_property_cache_values(true); SetRewriteOptions(custom_options.get()); // Setting up mock responses for the url and fallback url. GoogleString url = StrCat(kTestDomain, "a.html?different_query=some_pdf"); GoogleString fallback_url = StrCat(kTestDomain, "a.html?query=some_html"); ResponseHeaders response_headers; response_headers.Add( HttpAttributes::kContentType, kContentTypeHtml.mime_type()); response_headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(fallback_url, response_headers, kFlushEarlyHtml); // Set some non html response to the url. response_headers.Replace( HttpAttributes::kContentType, kContentTypePdf.mime_type()); mock_url_fetcher_.SetResponse(url, response_headers, kFlushEarlyPdf); noscript_redirect_url_ = StrCat(fallback_url, "&amp;PageSpeed=noscript"); GoogleString kOutputHtml = StrCat( kPreHeadHtml, StringPrintf(kFlushEarlyRewrittenHtmlLinkScript, rewritten_css_url_1_.c_str(), rewritten_css_url_2_.c_str(), rewritten_js_url_1_.c_str(), rewritten_js_url_2_.c_str(), rewritten_css_url_3_.c_str(), FlushEarlyContentWriterFilter::kDisableLinkTag), RewrittenHtml(NoScriptRedirectHtml())); GoogleString text; RequestHeaders request_headers; ResponseHeaders headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_link_script_tag"); FetchFromProxy(fallback_url, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(fallback_url, request_headers, true, &text, &headers); EXPECT_STREQ(kOutputHtml, text); EXPECT_EQ(0, TimedValue( FlushEarlyFlow::kNumFlushEarlyRequestsRedirected)); // Request another url with different query params so that fallback values // will be used. Since the content type is different here, this request // should be redirected. FetchFromProxy(url, request_headers, true, &text, &headers); redirect_url_ = StrCat(url, "&PageSpeed=noscript"); EXPECT_EQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchLinkScriptTag, false, false, false, true, false, true, false), text); EXPECT_EQ(1, TimedValue( FlushEarlyFlow::kNumFlushEarlyRequestsRedirected)); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestDisabled) { // Adding a httponly cookie in the response causes flush early to be disabled // for the second request. set_httponly_cookie_ = true; SetupForFlushEarlyFlow(); GoogleString text; RequestHeaders request_headers; ResponseHeaders headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_link_script_tag"); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_FALSE(headers.Has(kPsaRewriterHeader)); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_FALSE(headers.Has(kPsaRewriterHeader)); rewrite_driver_->log_record()->WriteLog(); EXPECT_EQ(5, logging_info()->rewriter_stats_size()); EXPECT_STREQ("fs", logging_info()->rewriter_stats(2).id()); const RewriterStats& stats = logging_info()->rewriter_stats(2); EXPECT_EQ(RewriterHtmlApplication::DISABLED, stats.html_status()); EXPECT_EQ(0, stats.status_counts_size()); // Change the fetcher's response to not set the http only cookie. We still // don't flush early. set_httponly_cookie_ = false; SetupForFlushEarlyFlow(); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_FALSE(headers.Has(kPsaRewriterHeader)); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_FALSE(headers.Has(kPsaRewriterHeader)); // Clear all the caches. We don't flush early on the first request since we // miss the pcache, but flush early on the second request. lru_cache()->Clear(); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_FALSE(headers.Has(kPsaRewriterHeader)); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_TRUE(headers.Has(kPsaRewriterHeader)); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestUnsupportedUserAgent) { SetupForFlushEarlyFlow(); GoogleString text; RequestHeaders request_headers; ResponseHeaders headers; request_headers.Replace(HttpAttributes::kUserAgent, ""); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); rewrite_driver_->log_record()->WriteLog(); EXPECT_EQ(5, logging_info()->rewriter_stats_size()); EXPECT_STREQ("fs", logging_info()->rewriter_stats(2).id()); const RewriterStats& stats = logging_info()->rewriter_stats(2); EXPECT_EQ(RewriterHtmlApplication::USER_AGENT_NOT_SUPPORTED, stats.html_status()); EXPECT_EQ(0, stats.status_counts_size()); } TEST_F(FlushEarlyFlowTest, ConditionalRequestHeaders) { SetupForFlushEarlyFlow(); GoogleString text; RequestHeaders request_headers; ResponseHeaders headers; request_headers.Add(HttpAttributes::kUserAgent, "prefetch_link_script_tag"); request_headers.Add(HttpAttributes::kIfNoneMatch, "etag"); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); rewrite_driver_->log_record()->WriteLog(); EXPECT_EQ(5, logging_info()->rewriter_stats_size()); EXPECT_STREQ("fs", logging_info()->rewriter_stats(2).id()); const RewriterStats& stats = logging_info()->rewriter_stats(2); EXPECT_EQ(RewriterHtmlApplication::DISABLED, stats.html_status()); EXPECT_EQ(0, stats.status_counts_size()); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowStatusCodeUnstable) { // Test that the flush early flow is not triggered when the status code is // unstable. request_url_ = "http://test.com/?q=1"; SetupForFlushEarlyFlow(); redirect_url_ = StrCat(request_url_, "&PageSpeed=noscript"); noscript_redirect_url_ = StrCat(request_url_, "&amp;PageSpeed=noscript"); GoogleString text; RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_link_script_tag"); ResponseHeaders headers; FetchFromProxy(request_url_, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(request_url_, request_headers, true, &text, &headers); EXPECT_EQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchLinkScriptTag, false, false, true), text); EXPECT_EQ(0, TimedValue( FlushEarlyFlow::kNumFlushEarlyRequestsRedirected)); SetFetchResponse404(request_url_); // Fetch again so that 404 is populated in response headers. // It should redirect to PageSpeed=noscript in this case. FetchFromProxy(request_url_, request_headers, true, &text, &headers); EXPECT_EQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchLinkScriptTag, false, false, false, true, false, true, false), text); EXPECT_EQ(1, TimedValue( FlushEarlyFlow::kNumFlushEarlyRequestsRedirected)); // Fetch the url again. This time FlushEarlyFlow should not be triggered as // the status code is not stable. FetchFromProxy(request_url_, request_headers, true, &text, &headers); EXPECT_EQ(HttpStatus::kNotFound, headers.status_code()); // Delete the 404 from cache and again set up for 200 response. lru_cache()->Delete(HttpCacheKey(request_url_)); SetupForFlushEarlyFlow(); // Flush early flow is again not triggered as the status code is not // stable for property_cache_http_status_stability_threshold number of // requests. for (int i = 0, n = server_context()->global_options()-> property_cache_http_status_stability_threshold(); i < n; ++i) { FetchFromProxy(request_url_, request_headers, true, &text, &headers); EXPECT_TRUE(text.find("mod_pagespeed_num_resources_prefetched") == GoogleString::npos); } // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(request_url_, request_headers, true, &text, &headers); EXPECT_EQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchLinkScriptTag, false, false, true), text); // Fetch again so that 404 is populated in response headers. // It should redirect to PageSpeed=noscript in this case. SetFetchResponse404(request_url_); FetchFromProxy(request_url_, request_headers, true, &text, &headers); EXPECT_EQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchLinkScriptTag, false, false, false, true, false, true, false), text); EXPECT_EQ(2, TimedValue( FlushEarlyFlow::kNumFlushEarlyRequestsRedirected)); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestMobile) { TestFlushEarlyFlow(UserAgentMatcherTestBase::kAndroidChrome21UserAgent, UserAgentMatcher::kPrefetchImageTag, false); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestImageTag) { TestFlushEarlyFlow("prefetch_image_tag", UserAgentMatcher::kPrefetchImageTag, true); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestLinkScript) { TestFlushEarlyFlow("prefetch_link_script_tag", UserAgentMatcher::kPrefetchLinkScriptTag, true); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestWithDeferJsImageTag) { SetupForFlushEarlyFlow(); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kDeferJavascript); SetRewriteOptions(custom_options.get()); GoogleString text; RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_image_tag"); ResponseHeaders headers; FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchImageTag, true, false, true), text); VerifyCharset(&headers); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestWithDeferJsPrefetch) { SetupForFlushEarlyFlow(); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kDeferJavascript); custom_options->set_max_prefetch_js_elements(0); SetRewriteOptions(custom_options.get()); GoogleString text; RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, "Firefox/ 9.0"); ResponseHeaders headers; FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchLinkScriptTag, true, false, false), text); VerifyCharset(&headers); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTest) { ExperimentalFlushEarlyFlowTestHelper( "", UserAgentMatcher::kPrefetchNotSupported, false); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTestError) { ExperimentalFlushEarlyFlowTestHelper( "", UserAgentMatcher::kPrefetchNotSupported, true); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTestImageTag) { ExperimentalFlushEarlyFlowTestHelper( "prefetch_image_tag", UserAgentMatcher::kPrefetchImageTag, false); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTestImageTagError) { ExperimentalFlushEarlyFlowTestHelper( "prefetch_image_tag", UserAgentMatcher::kPrefetchImageTag, true); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTestLinkScript) { ExperimentalFlushEarlyFlowTestHelper( "prefetch_link_script_tag", UserAgentMatcher::kPrefetchLinkScriptTag, false); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTestLinkScriptError) { ExperimentalFlushEarlyFlowTestHelper( "prefetch_link_script_tag", UserAgentMatcher::kPrefetchLinkScriptTag, true); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTestLinkRelPrefetch) { ExperimentalFlushEarlyFlowTestHelper( UserAgentMatcherTestBase::kChrome42UserAgent, UserAgentMatcher::kPrefetchLinkRelPrefetchTag, false); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTestLinkRelPrefetchError) { ExperimentalFlushEarlyFlowTestHelper( UserAgentMatcherTestBase::kChrome42UserAgent, UserAgentMatcher::kPrefetchLinkRelPrefetchTag, true); } TEST_F(FlushEarlyFlowTest, ExperimentalFlushEarlyFlowTestWithInsertDnsPrefetch) { SetupForFlushEarlyFlow(); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kInsertDnsPrefetch); SetRewriteOptions(custom_options.get()); GoogleString text; RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_image_tag"); ResponseHeaders headers; FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered but not // insert dns prefetch filter as domains are not yet stable. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time InsertDnsPrefetch filter should applied. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchImageTag, false, true, true), text); } TEST_F(FlushEarlyFlowTest, LazyloadAndDeferJsScriptFlushedEarly) { SetHeaderLatencyMs(600); SetupForFlushEarlyFlow(); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kDeferJavascript); custom_options->EnableFilter(RewriteOptions::kLazyloadImages); custom_options->set_max_prefetch_js_elements(0); custom_options->set_flush_more_resources_early_if_time_permits(true); SetRewriteOptions(custom_options.get()); GoogleString text; RequestHeaders request_headers; // Useragent is set to Firefox/ 9.0 because all flush early flow, defer // javascript and lazyload filter are enabled for this user agent. request_headers.Replace(HttpAttributes::kUserAgent, "Firefox/ 9.0"); ResponseHeaders headers; FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(FlushEarlyRewrittenHtml( UserAgentMatcher::kPrefetchLinkScriptTag, true, false, true, false, false, false, false), text); } TEST_F(FlushEarlyFlowTest, NoLazyloadScriptFlushedOutIfNoImagePresent) { // TODO(jmaessen): We now include the lazy load script (in <head>) even if // there are no images present. We could tighten this up, but it will require // a major redesign of the filter. const char kInputHtml[] = "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"/>" "<meta http-equiv=\"last-modified\" content=\"2012-08-09T11:03:27Z\"/>" "<meta charset=\"UTF-8\"/>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\"" " href=\"http://test.com/1.css\">" "</head>" "<body>" "Hello, mod_pagespeed!" "</body>" "</html>"; GoogleString redirect_url = StrCat(kTestDomain, "?PageSpeed=noscript"); GoogleString kOutputHtml = StrCat( "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<link rel=\"stylesheet\" href=\"", rewritten_css_url_1_.c_str(), "\"/>\n", FlushEarlyContentWriterFilter::kDisableLinkTag, "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = 1" "</script>", GetLazyloadScriptFlushEarly(), "<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"/>" "<meta http-equiv=\"last-modified\" content=\"2012-08-09T11:03:27Z\"/>" "<meta charset=\"UTF-8\"/>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\" href=\"", rewritten_css_url_1_.c_str(), "\"></head><body>", StringPrintf(kNoScriptRedirectFormatter, redirect_url.c_str(), redirect_url.c_str()), "Hello, mod_pagespeed!</body></html>"); ResponseHeaders headers; headers.Add(HttpAttributes::kContentType, kContentTypeHtml.mime_type()); headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(kTestDomain, headers, kInputHtml); // Enable FlushSubresourcesFilter filter. RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->EnableFilter(RewriteOptions::kFlushSubresources); rewrite_options->EnableExtendCacheFilters(); // Disabling the inline filters so that the resources get flushed early // else our dummy resources are too small and always get inlined. rewrite_options->DisableFilter(RewriteOptions::kInlineCss); rewrite_options->DisableFilter(RewriteOptions::kInlineJavascript); rewrite_options->ComputeSignature(); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.css"), kContentTypeCss, kCssContent, kHtmlCacheTimeSec * 2); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kLazyloadImages); SetRewriteOptions(custom_options.get()); GoogleString text; RequestHeaders request_headers; // Useragent is set to Firefox/ 9.0 because all flush early flow, defer // javascript and lazyload filter is enabled for this user agent. request_headers.Replace(HttpAttributes::kUserAgent, "Firefox/ 9.0"); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(kOutputHtml, text); } TEST_F(FlushEarlyFlowTest, FlushEarlyMoreResourcesIfTimePermits) { SetHeaderLatencyMs(600); StringSet* css_critical_images = new StringSet; css_critical_images->insert(StrCat(kTestDomain, "1.jpg")); SetCssCriticalImagesInFinder(css_critical_images); GoogleString redirect_url = StrCat(kTestDomain, "?PageSpeed=noscript"); GoogleString kOutputHtml = StringPrintf( "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<script type=\"text/javascript\">(function(){" "new Image().src=\"http://test.com/1.jpg.pagespeed.ce.%s.jpg\";" "new Image().src=\"%s\";})()</script>" "<link rel=\"stylesheet\" href=\"%s\"/>\n" "%s" "<script type='text/javascript'>" "window.mod_pagespeed_prefetch_start = Number(new Date());" "window.mod_pagespeed_num_resources_prefetched = 3" "</script>" "<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"/>" "<meta http-equiv=\"last-modified\" content=\"2012-08-09T11:03:27Z\"/>" "<meta charset=\"UTF-8\"/>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\"" " href=\"%s\"></head>" "<body>%s" "<script src=\"%s\"></script>" "Hello, mod_pagespeed!</body></html>", kMockHashValue, rewritten_js_url_3_.c_str(), rewritten_css_url_1_.c_str(), FlushEarlyContentWriterFilter::kDisableLinkTag, rewritten_css_url_1_.c_str(), StringPrintf(kNoScriptRedirectFormatter, redirect_url.c_str(), redirect_url.c_str()).c_str(), rewritten_js_url_3_.c_str()); ResponseHeaders headers; headers.Add(HttpAttributes::kContentType, kContentTypeHtml.mime_type()); headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(kTestDomain, headers, kFlushEarlyMoreResourcesInputHtml); // Enable FlushSubresourcesFilter filter. RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->EnableFilter(RewriteOptions::kFlushSubresources); rewrite_options->set_flush_more_resources_early_if_time_permits(true); rewrite_options->EnableExtendCacheFilters(); // Disabling the inline filters so that the resources get flushed early // else our dummy resources are too small and always get inlined. rewrite_options->DisableFilter(RewriteOptions::kInlineCss); rewrite_options->DisableFilter(RewriteOptions::kInlineJavascript); rewrite_options->DisableFilter(RewriteOptions::kInlineImages); rewrite_options->ComputeSignature(); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.jpg"), kContentTypeJpeg, "image", kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.css"), kContentTypeCss, kCssContent, kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.js"), kContentTypeJavascript, "javascript", kHtmlCacheTimeSec * 2); GoogleString text; RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_image_tag"); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered but // all resources may not be flushed. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time all resources based on time will be flushed. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(kOutputHtml, text); } TEST_F(FlushEarlyFlowTest, InsertLazyloadJsOnlyIfResourceHtmlNotEmpty) { const char kInputHtml[] = "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<title>Flush Subresources Early example</title>" "</head>" "<body>" "<img src=http://test.com/1.jpg />" "Hello, mod_pagespeed!" "</body>" "</html>"; GoogleString redirect_url = StrCat(kTestDomain, "?PageSpeed=noscript"); GoogleString kOutputHtml = StrCat( "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html>" "<head>" "<title>Flush Subresources Early example</title>", GetLazyloadScriptHtml(), "</head>" "<body>", StringPrintf(kNoScriptRedirectFormatter, redirect_url.c_str(), redirect_url.c_str()), StringPrintf( "<img pagespeed_lazy_src=http://test.com/1.jpg.pagespeed.ce.%s.jpg" " src=\"/psajs/1.0.gif\"" " onload=\"%s\" onerror=\"this.onerror=null;%s\"/>" "Hello, mod_pagespeed!" "<script type=\"text/javascript\" pagespeed_no_defer>" "pagespeed.lazyLoadImages.overrideAttributeFunctions();</script>" "</body></html>", kMockHashValue, LazyloadImagesFilter::kImageOnloadCode, LazyloadImagesFilter::kImageOnloadCode)); ResponseHeaders headers; headers.Add(HttpAttributes::kContentType, kContentTypeHtml.mime_type()); headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(kTestDomain, headers, kInputHtml); // Enable FlushSubresourcesFilter filter. RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->EnableFilter(RewriteOptions::kFlushSubresources); rewrite_options->EnableExtendCacheFilters(); // Disabling the inline filters so that the resources get flushed early // else our dummy resources are too small and always get inlined. rewrite_options->DisableFilter(RewriteOptions::kInlineCss); rewrite_options->DisableFilter(RewriteOptions::kInlineJavascript); rewrite_options->ComputeSignature(); SetResponseWithDefaultHeaders(StrCat(kTestDomain, "1.jpg"), kContentTypeJpeg, "image", kHtmlCacheTimeSec * 2); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kLazyloadImages); SetRewriteOptions(custom_options.get()); GoogleString text; RequestHeaders request_headers; // Useragent is set to Firefox/ 9.0 because all flush early flow, defer // javascript and lazyload filter is enabled for this user agent. request_headers.Replace(HttpAttributes::kUserAgent, "Firefox/ 9.0"); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered but no // lazyload js will be flushed early as no resource is present in the html. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(kOutputHtml, text); } TEST_F(FlushEarlyFlowTest, DontInsertLazyloadJsIfMobile) { TestFlushLazyLoadJsEarly(true); } TEST_F(FlushEarlyFlowTest, InsertLazyloadJsIfNotMobile) { TestFlushLazyLoadJsEarly(false); } TEST_F(FlushEarlyFlowTest, PreconnectTest) { TestFlushPreconnects(false); } TEST_F(FlushEarlyFlowTest, NoPreconnectForMobile) { TestFlushPreconnects(true); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowTestWithLocalStorageDoesNotCrash) { SetupForFlushEarlyFlow(); GoogleString text; RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, "prefetch_link_rel_subresource"); RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->EnableFilter(RewriteOptions::kLocalStorageCache); rewrite_options->ForceEnableFilter(RewriteOptions::kInlineImages); rewrite_options->ForceEnableFilter(RewriteOptions::kInlineCss); rewrite_options->ComputeSignature(); // This sequence of requests used to cause a crash earlier. Here, we just test // that this server doesn't crash and don't check the output. ResponseHeaders headers; FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowWithIEAddUACompatibilityHeader) { SetupForFlushEarlyFlow(); RequestHeaders request_headers; // Useragent is set to "MSIE 10." because we need to check if appropriate // HttpAttributes::kXUACompatible header is added, which happens only with // MSIE 9 and above, but IE9 is now blacklisted from defer_js. request_headers.Replace(HttpAttributes::kUserAgent, " MSIE 10."); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kDeferJavascript); custom_options->set_max_prefetch_js_elements(0); SetRewriteOptions(custom_options.get()); GoogleString text; ResponseHeaders headers; FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(FlushEarlyRewrittenHtml(UserAgentMatcher::kPrefetchLinkScriptTag, true, false, false, false, false, false, true), text); ConstStringStarVector values; EXPECT_TRUE(headers.Lookup(HttpAttributes::kXUACompatible, &values)); EXPECT_STREQ("IE=edge", *(values[0])); } TEST_F(FlushEarlyFlowTest, FlushEarlyFlowWithDeferJsAndSplitEnabled) { // The default finder class used by split_html is // BeaconCriticalLineInfoFinder, which requires the pcache to be setup, so do // that setup here. PropertyCache* pcache = server_context_->page_property_cache(); const PropertyCache::Cohort* beacon_cohort = SetupCohort(pcache, RewriteDriver::kBeaconCohort); server_context()->set_beacon_cohort(beacon_cohort); server_context()->set_critical_line_info_finder( new BeaconCriticalLineInfoFinder(server_context()->beacon_cohort(), factory()->nonce_generator())); SetupForFlushEarlyFlow(); RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, " MSIE 10."); scoped_ptr<RewriteOptions> custom_options( server_context()->global_options()->Clone()); custom_options->EnableFilter(RewriteOptions::kDeferJavascript); custom_options->EnableFilter(RewriteOptions::kSplitHtml); custom_options->set_max_prefetch_js_elements(0); SetRewriteOptions(custom_options.get()); GoogleString text; ResponseHeaders headers; FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(kTestDomain, request_headers, true, &text, &headers); EXPECT_STREQ(FlushEarlyRewrittenHtml(UserAgentMatcher::kPrefetchLinkScriptTag, true, false, false, false, true, false, true), text); } class FlushEarlyPrioritizeCriticalCssTest : public FlushEarlyFlowTest { public: virtual void SetUp() { FlushEarlyFlowTest::SetUp(); SetOptions(); InitializeResponses(); } void SetOptions() { // Enable FlushSubresourcesFilter filter. RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->EnableFilter(RewriteOptions::kFlushSubresources); rewrite_options->EnableFilter(RewriteOptions::kPrioritizeCriticalCss); // Disabling the inline filters so that the resources get flushed early // else our dummy resources are too small and always get inlined. rewrite_options->DisableFilter(RewriteOptions::kInlineCss); rewrite_options->DisableFilter(RewriteOptions::kRewriteJavascriptExternal); rewrite_options->DisableFilter(RewriteOptions::kRewriteJavascriptInline); rewrite_options->set_enable_flush_early_critical_css(true); rewrite_options->set_use_selectors_for_critical_css(false); rewrite_options->ComputeSignature(); } void InitializeResponses() { // Some weird but valid CSS. SetResponseWithDefaultHeaders("a.css", kContentTypeCss, "div,span,*::first-letter { display: block; }" "p { display: inline; }", kHtmlCacheTimeSec * 2); SetResponseWithDefaultHeaders("b.css?x=1&y=2", kContentTypeCss, "@media screen,print { * { margin: 0px; } }", kHtmlCacheTimeSec * 2); } GoogleString InputHtml() { return GoogleString( "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html><head>" "<title>Flush Subresources Early example</title>" "<link rel=\"stylesheet\" type=\"text/css\" href=\"a.css\">" "<link rel=\"stylesheet\" type=\"text/css\" href=\"b.css?x=1&y=2\">" "</head>" "<body>" "Hello, mod_pagespeed!" "</body></html>"); } GoogleString ExpectedHtml(GoogleString full_styles_html) { GoogleString expected_html = StrCat( "<!doctype html PUBLIC \"HTML 4.0.1 Strict>" "<html><head>", FlushedCss("div,*::first-letter{display:block}"), // a.css FlushedCss("@media screen{*{margin:0}}"), // b.css StringPrintf(FlushEarlyContentWriterFilter::kPrefetchStartTimeScript, 2 /* num_resources_flushed */), "<title>Flush Subresources Early example</title>"); StrAppend(&expected_html, ApplyFlushEarlyScript(), InvokeFlushEarlyScript(), // invoke a.css InvokeFlushEarlyScript(), // invoke b.css "</head><body>", NoScriptRedirectHtml(), "Hello, mod_pagespeed!", full_styles_html, "</body></html>"); return expected_html; } GoogleString FlushedCss(GoogleString critical_css) { return StrCat( "<script type=\"text/psa_flush_style\" id=\"", kMockHashValue, "\">", critical_css, "</script>"); } GoogleString ApplyFlushEarlyScript() { return StrCat( "<script id=\"psa_flush_style_early\"" " pagespeed_no_defer type=\"text/javascript\">", CriticalSelectorFilter::kApplyFlushEarlyCss, "</script>"); } GoogleString InvokeFlushEarlyScript() { // The test uses a fixed hash for all URLs. return StrCat( "<script pagespeed_no_defer type=\"text/javascript\">" "applyFlushedCriticalCss(\"", kMockHashValue, "\", \"\");" "</script>"); } GoogleString CssLinkEncodedHref(GoogleString url) { return StrCat( "<link rel=\"stylesheet\" type=\"text/css\" href=\"", Encode("", "cf", kMockHashValue, url, "css"), "\">"); } GoogleString url() { return kTestDomain; } void ValidateFlushEarly(const StringPiece& case_id, const GoogleString& input_html, const GoogleString& expected_html) { RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kUserAgent, UserAgentMatcherTestBase::kChrome18UserAgent); ResponseHeaders headers; headers.Add(HttpAttributes::kContentType, kContentTypeHtml.mime_type()); headers.SetStatusAndReason(HttpStatus::kOK); mock_url_fetcher_.SetResponse(url(), headers, input_html); GoogleString actual_html; FetchFromProxy(url(), request_headers, true, &actual_html, &headers); // Fetch the url again. This time FlushEarlyFlow should be triggered. FetchFromProxy(url(), request_headers, true, &actual_html, &headers); EXPECT_EQ(expected_html, actual_html) << "Test id:" << case_id; } }; TEST_F(FlushEarlyPrioritizeCriticalCssTest, FlushEarlyFlowWithCriticalCssEnabled) { // Add critical css rules. MockCriticalCssFinder* critical_css_finder = new MockCriticalCssFinder(rewrite_driver(), statistics()); server_context()->set_critical_css_finder(critical_css_finder); critical_css_finder->AddCriticalCss( "http://test.com/a.css", "div,*::first-letter{display:block}", 100); critical_css_finder->AddCriticalCss( "http://test.com/b.css?x=1&y=2", "@media screen{*{margin:0}}", 100); GoogleString full_styles_html = StrCat( "<noscript class=\"psa_add_styles\">", CssLinkEncodedHref("a.css"), CssLinkEncodedHref("b.css?x=1&y=2"), "</noscript>" "<script pagespeed_no_defer type=\"text/javascript\">", CriticalCssFilter::kAddStylesScript, "window['pagespeed'] = window['pagespeed'] || {};" "window['pagespeed']['criticalCss'] = {" " 'total_critical_inlined_size': 60," " 'total_original_external_size': 200," " 'total_overhead_size': 60," " 'num_replaced_links': 2," " 'num_unreplaced_links': 0};" "</script>"); ValidateFlushEarly( "critical_css", InputHtml(), ExpectedHtml(full_styles_html)); } class TestCriticalSelectorFinder : public CriticalSelectorFinder { public: TestCriticalSelectorFinder(const PropertyCache::Cohort* cohort, Statistics* stats) : CriticalSelectorFinder(cohort, NULL /* nonce_generator */, stats) {} virtual ~TestCriticalSelectorFinder() {} virtual int SupportInterval() const { return 1; } protected: virtual bool ShouldReplacePriorResult() const { return true; } private: DISALLOW_COPY_AND_ASSIGN(TestCriticalSelectorFinder); }; TEST_F(FlushEarlyPrioritizeCriticalCssTest, FlushEarlyFlowWithCriticalSelectorFilterEnabled) { PropertyCache* pcache = server_context_->page_property_cache(); const PropertyCache::Cohort* beacon_cohort = SetupCohort(pcache, RewriteDriver::kBeaconCohort); server_context()->set_beacon_cohort(beacon_cohort); rewrite_driver()->Clear(); rewrite_driver()->set_request_context( RequestContext::NewTestRequestContext(factory()->thread_system())); MockPropertyPage* page = NewMockPage( url(), server_context()->GetRewriteOptionsSignatureHash( server_context()->global_options()), UserAgentMatcher::kDesktop); rewrite_driver()->set_property_page(page); pcache->Read(page); RewriteOptions* rewrite_options = server_context()->global_options(); rewrite_options->ClearSignatureForTesting(); rewrite_options->set_use_selectors_for_critical_css(true); rewrite_options->ComputeSignature(); server_context()->set_critical_selector_finder(new TestCriticalSelectorFinder( server_context()->beacon_cohort(), statistics())); // Write critical selectors to property cache StringSet selectors; selectors.insert("div"); selectors.insert("*"); CriticalSelectorFinder* finder = server_context()->critical_selector_finder(); finder->WriteCriticalSelectorsToPropertyCache( selectors, "" /* last_nonce */, rewrite_driver()); rewrite_driver()->property_page()-> WriteCohort(server_context()->beacon_cohort()); EXPECT_TRUE(finder->IsCriticalSelector(rewrite_driver(), "div")); EXPECT_TRUE(finder->IsCriticalSelector(rewrite_driver(), "*")); GoogleString full_styles_html = StrCat( "<noscript class=\"psa_add_styles\">", CssLinkEncodedHref("a.css"), CssLinkEncodedHref("b.css?x=1&y=2"), "</noscript>" "<script pagespeed_no_defer type=\"text/javascript\">", rewrite_driver()->server_context()->static_asset_manager()->GetAsset( StaticAssetEnum::CRITICAL_CSS_LOADER_JS, rewrite_driver()->options()), "pagespeed.CriticalCssLoader.Run();</script>"); ValidateFlushEarly( "critical_selector", InputHtml(), ExpectedHtml(full_styles_html)); } } // namespace net_instaweb
{ "content_hash": "5a83c6aea9346de2094c94b92a4ab900", "timestamp": "", "source": "github", "line_count": 1870, "max_line_length": 80, "avg_line_length": 41.97860962566845, "alnum_prop": 0.671859872611465, "repo_name": "wanrui/mod_pagespeed", "id": "7fe5d0db487a840a328a2cf7cd371a90fc7c87cf", "size": "79095", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "pagespeed/automatic/flush_early_flow_test.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "1639" }, { "name": "C", "bytes": "16464" }, { "name": "C++", "bytes": "12425445" }, { "name": "CSS", "bytes": "65677" }, { "name": "HTML", "bytes": "203067" }, { "name": "JavaScript", "bytes": "2367267" }, { "name": "Makefile", "bytes": "46438" }, { "name": "Objective-C++", "bytes": "1308" }, { "name": "PHP", "bytes": "661" }, { "name": "Perl", "bytes": "14872" }, { "name": "Protocol Buffer", "bytes": "57074" }, { "name": "Python", "bytes": "188998" }, { "name": "Shell", "bytes": "394778" } ], "symlink_target": "" }
package com.google.gson.functional; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import junit.framework.TestCase; public class MapAsArrayTypeAdapterTest extends TestCase { public void testSerializeComplexMapWithTypeAdapter() { Type type = new TypeToken<Map<Point, String>>() {}.getType(); Gson gson = new GsonBuilder() .enableComplexMapKeySerialization() .create(); Map<Point, String> original = new LinkedHashMap<Point, String>(); original.put(new Point(5, 5), "a"); original.put(new Point(8, 8), "b"); String json = gson.toJson(original, type); assertEquals("[[{\"x\":5,\"y\":5},\"a\"],[{\"x\":8,\"y\":8},\"b\"]]", json); assertEquals(original, gson.<Map<Point, String>>fromJson(json, type)); // test that registering a type adapter for one map doesn't interfere with others Map<String, Boolean> otherMap = new LinkedHashMap<String, Boolean>(); otherMap.put("t", true); otherMap.put("f", false); assertEquals("{\"t\":true,\"f\":false}", gson.toJson(otherMap, Map.class)); assertEquals("{\"t\":true,\"f\":false}", gson.toJson(otherMap, new TypeToken<Map<String, Boolean>>() {}.getType())); assertEquals(otherMap, gson.<Object>fromJson("{\"t\":true,\"f\":false}", new TypeToken<Map<String, Boolean>>() {}.getType())); } public void disabled_testTwoTypesCollapseToOneSerialize() { Gson gson = new GsonBuilder() .enableComplexMapKeySerialization() .create(); Map<Number, String> original = new LinkedHashMap<Number, String>(); original.put(new Double(1.0), "a"); original.put(new Float(1.0), "b"); try { gson.toJson(original, new TypeToken<Map<Number, String>>() {}.getType()); fail(); // we no longer hash keys at serialization time } catch (JsonSyntaxException expected) { } } public void testTwoTypesCollapseToOneDeserialize() { Gson gson = new GsonBuilder() .enableComplexMapKeySerialization() .create(); String s = "[[\"1.00\",\"a\"],[\"1.0\",\"b\"]]"; try { gson.fromJson(s, new TypeToken<Map<Double, String>>() {}.getType()); fail(); } catch (JsonSyntaxException expected) { } } public void testMultipleEnableComplexKeyRegistrationHasNoEffect() throws Exception { Type type = new TypeToken<Map<Point, String>>() {}.getType(); Gson gson = new GsonBuilder() .enableComplexMapKeySerialization() .enableComplexMapKeySerialization() .create(); Map<Point, String> original = new LinkedHashMap<Point, String>(); original.put(new Point(6, 5), "abc"); original.put(new Point(1, 8), "def"); String json = gson.toJson(original, type); assertEquals("[[{\"x\":6,\"y\":5},\"abc\"],[{\"x\":1,\"y\":8},\"def\"]]", json); assertEquals(original, gson.<Map<Point, String>>fromJson(json, type)); } public void testMapWithTypeVariableSerialization() { Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); PointWithProperty<Point> map = new PointWithProperty<Point>(); map.map.put(new Point(2, 3), new Point(4, 5)); Type type = new TypeToken<PointWithProperty<Point>>(){}.getType(); String json = gson.toJson(map, type); assertEquals("{\"map\":[[{\"x\":2,\"y\":3},{\"x\":4,\"y\":5}]]}", json); } public void testMapWithTypeVariableDeserialization() { Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); String json = "{map:[[{x:2,y:3},{x:4,y:5}]]}"; Type type = new TypeToken<PointWithProperty<Point>>(){}.getType(); PointWithProperty<Point> map = gson.fromJson(json, type); Point key = map.map.keySet().iterator().next(); Point value = map.map.values().iterator().next(); assertEquals(new Point(2, 3), key); assertEquals(new Point(4, 5), value); } static class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } Point() {} @Override public boolean equals(Object o) { return o instanceof Point && ((Point) o).x == x && ((Point) o).y == y; } @Override public int hashCode() { return x * 37 + y; } @Override public String toString() { return "(" + x + "," + y + ")"; } } static class PointWithProperty<T> { Map<Point, T> map = new HashMap<Point, T>(); } }
{ "content_hash": "e914c8af7c484548fa029b4b8bda7918", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 86, "avg_line_length": 35.9765625, "alnum_prop": 0.6340933767643865, "repo_name": "bpiwowar/gson", "id": "249b51d328e2c5f062dd42d3b0b48cde37571895", "size": "5204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1022567" } ], "symlink_target": "" }
package com.stockmanager.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Categoria { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String descricao; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } }
{ "content_hash": "aa2ade363ac48c2c4a2be6149d75fd10", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 50, "avg_line_length": 19.214285714285715, "alnum_prop": 0.7565055762081785, "repo_name": "FelipeOliver/StockManager", "id": "a2ea1924ad55c8ee4cb40228d9cecbc833080ce9", "size": "538", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/stockmanager/entities/Categoria.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "199472" }, { "name": "Java", "bytes": "49654" }, { "name": "JavaScript", "bytes": "410644" } ], "symlink_target": "" }
<?php namespace app\controllers\api; /** * This is the class for REST controller "CustomerController". */ use yii\filters\AccessControl; use yii\helpers\ArrayHelper; class CustomerController extends \yii\rest\ActiveController { public $modelClass = 'app\models\Customer'; }
{ "content_hash": "adb1e8e71d7e0861a05951eefd9e2b5c", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 18.533333333333335, "alnum_prop": 0.7697841726618705, "repo_name": "fredyns/shippingweight", "id": "06aed64a830b6a92579f9b28b1700518a2545959", "size": "278", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "controllers/apivgm/CustomerController.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "244" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "3970" }, { "name": "PHP", "bytes": "557885" }, { "name": "SQLPL", "bytes": "3214" }, { "name": "Shell", "bytes": "736" } ], "symlink_target": "" }
%w( lexeme ).each do |file| require File.join(File.dirname(__FILE__), file) end require 'fileutils' module TracePreprocessor class DSL def initialize @lexemes = {} @code = "" workspace "~/.trace_preprocessor" end def init &block instance_eval &block end def define_lexeme name, options lexeme = @lexemes[name] || Lexeme.new(name, options) converter = options[:converter] converter_language = :c converter_language = :ruby if converter.instance_of? Proc lexeme.converter[converter_language] = converter @lexemes[lexeme.name] = lexeme lexeme end def use_default_lexemes default_lexemes_file_name = File.join(File.dirname(__FILE__), "default_lexemes.rb") eval open(default_lexemes_file_name, "r") { |fd| fd.read } end def common_code code @code += code end def output_token code @output_token_code = code end def workspace path @workspace_path = File.expand_path path if not File.exist? @workspace_path FileUtils.mkdir_p @workspace_path end end attr_accessor :lexemes attr_accessor :code, :output_token_code attr_accessor :workspace_path end end
{ "content_hash": "e889baf02196d2fc441fad4d31a2bb2f", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 89, "avg_line_length": 21.8, "alnum_prop": 0.6047400611620795, "repo_name": "mastedm/trace_preprocessor", "id": "176ba0a7170307cae35be0421d436c664bb0c324", "size": "1308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/trace_preprocessor/dsl.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "9144" } ], "symlink_target": "" }
package ca.uhn.fhir.tinder.util; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.OutputStreamWriter; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.dstu2.composite.NarrativeDt; import ca.uhn.fhir.model.dstu2.resource.BaseResource; import ca.uhn.fhir.model.dstu2.resource.Bundle; import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry; public class SyncUtil { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SyncUtil.class); public static void main(String[] args) throws Exception { FhirContext ctx = FhirContext.forDstu2(); String fileName = "src/main/resources/vs/dstu2/all-valuesets-bundle.xml"; FileReader fr = new FileReader(fileName); Bundle b = ctx.newXmlParser().parseResource(Bundle.class, fr); for (Entry nextEntry : b.getEntry()) { BaseResource nextRes = (BaseResource) nextEntry.getResource(); nextRes.setText(new NarrativeDt()); } File f = new File(fileName); OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(f, false), "UTF-8"); ctx.newXmlParser().encodeResourceToWriter(b, fw); fw.close(); ourLog.info("Fixed {} valuesets", b.getEntry().size()); } }
{ "content_hash": "9e4a29ce83bdc6ad5e633e200df2807e", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 97, "avg_line_length": 33.21621621621622, "alnum_prop": 0.7518307567127747, "repo_name": "cementsuf/hapi-fhir", "id": "950ce7c1b822888e03c0e14389f74ca99aed780d", "size": "1229", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "hapi-tinder-plugin/src/main/java/ca/uhn/fhir/tinder/util/SyncUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "228150" }, { "name": "Eagle", "bytes": "1134813" }, { "name": "HTML", "bytes": "189422" }, { "name": "Java", "bytes": "19890671" }, { "name": "JavaScript", "bytes": "23709" }, { "name": "KiCad", "bytes": "12030" }, { "name": "Ruby", "bytes": "238370" }, { "name": "Shell", "bytes": "10779" } ], "symlink_target": "" }
<?php /** * Filtra una cadena para que solo contenga numero enteros * * @category Kumbia * @package Filter * @subpackage BaseFilter */ class IntFilter implements FilterInterface { /** * Ejecuta el filtro * * @param string $s * @param array $options * @return int */ public static function execute($s, $options) { return (int) $s; } }
{ "content_hash": "293707fb20399d265a44eff534c0273a", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 58, "avg_line_length": 15.461538461538462, "alnum_prop": 0.582089552238806, "repo_name": "LionelBino/blion-web", "id": "f3e54b4ab0219a71d98ac9296498b13c4b36b809", "size": "1095", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/libs/filter/base_filter/int_filter.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "887" }, { "name": "CSS", "bytes": "126341" }, { "name": "HTML", "bytes": "115058" }, { "name": "JavaScript", "bytes": "6937" }, { "name": "PHP", "bytes": "707473" }, { "name": "Shell", "bytes": "110" } ], "symlink_target": "" }
package models.Entity; import controllers.Amphibious; import controllers.Arial; import controllers.Locomotion; import controllers.Terrestrial; import models.Equipment.Equipment; import models.Occupation.*; import models.StatContainer.*; import models.Inventory.*; import utilities.Direction.Direction; import utilities.KeyCommand.KeyCommand; import utilities.KeyCommand.MovementKeyCommand; import utilities.KeyCommand.SkillKeyCommand; import utilities.Location.Location; import models.Map.Map; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.util.HashMap; import java.util.Set; public class Avatar extends Entity { // private HashMap<Integer,KeyCommand> keyMap; public Avatar(int level, Occupation occupation) { setName("Avatar"); setLocation(new Location(0,0,0)); setDirection(utilities.Direction.Direction.South); setOccupation(occupation); setStats(new AvatarStats(occupationModifier(), level)); setInventory(new Inventory(25)); setCurrentState(States.ATTACK); setEquipment(new Equipment()); } public Image getImage(){ Image image = new ImageIcon("res/fireball.png").getImage(); return image; } public void setKeyCommand(Map map){ keyMap = new HashMap<>(); Locomotion locomotion = new Terrestrial(this, map); // Movement KeyCommand moveNorth = new MovementKeyCommand(map, this, Direction.North, locomotion); keyMap.put(KeyEvent.VK_8, moveNorth); KeyCommand moveNorthWest = new MovementKeyCommand(map, this, Direction.NorthWest, locomotion); keyMap.put(KeyEvent.VK_7, moveNorthWest); KeyCommand moveSouthWest = new MovementKeyCommand(map, this, Direction.SouthWest, locomotion); keyMap.put(KeyEvent.VK_1, moveSouthWest); KeyCommand moveSouth = new MovementKeyCommand(map, this, Direction.South, locomotion); keyMap.put(KeyEvent.VK_2, moveSouth); KeyCommand moveSouthEast = new MovementKeyCommand(map, this, Direction.SouthEast, locomotion); keyMap.put(KeyEvent.VK_3, moveSouthEast); KeyCommand moveNorthEast = new MovementKeyCommand(map, this, Direction.NorthEast, locomotion); keyMap.put(KeyEvent.VK_9, moveNorthEast); KeyCommand moveUp = new MovementKeyCommand(map, this, Direction.Up, locomotion); keyMap.put(KeyEvent.VK_SPACE, moveUp); KeyCommand moveDown = new MovementKeyCommand(map, this, Direction.Down, locomotion); keyMap.put(KeyEvent.VK_ENTER, moveDown); moveNorthWest = new MovementKeyCommand(map, this, Direction.NorthWest, locomotion); keyMap.put(KeyEvent.VK_Q, moveNorthWest); moveSouthWest = new MovementKeyCommand(map, this, Direction.SouthWest, locomotion); keyMap.put(KeyEvent.VK_A, moveSouthWest); moveSouth = new MovementKeyCommand(map, this, Direction.South, locomotion); keyMap.put(KeyEvent.VK_S, moveSouth); moveSouthEast = new MovementKeyCommand(map, this, Direction.SouthEast, locomotion); keyMap.put(KeyEvent.VK_D, moveSouthEast); moveNorthEast = new MovementKeyCommand(map, this, Direction.NorthEast, locomotion); keyMap.put(KeyEvent.VK_E, moveNorthEast); moveNorth = new MovementKeyCommand(map, this, Direction.North, locomotion); keyMap.put(KeyEvent.VK_W, moveNorth); KeyCommand skill1 = new SkillKeyCommand(map, this, 0); keyMap.put(KeyEvent.VK_1, skill1); KeyCommand skill2 = new SkillKeyCommand(map, this, 1); keyMap.put(KeyEvent.VK_2, skill2); KeyCommand skill3 = new SkillKeyCommand(map, this, 2); keyMap.put(KeyEvent.VK_3, skill3); KeyCommand skill4 = new SkillKeyCommand(map, this, 3); keyMap.put(KeyEvent.VK_4, skill4); } public HashMap<Integer,KeyCommand> getKeyMap(){ return keyMap; } public Set<Integer> getKeys(){ return keyMap.keySet(); } }
{ "content_hash": "93f4ee9c17fe5e0280ff8734c62218f4", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 102, "avg_line_length": 35.767857142857146, "alnum_prop": 0.7019470793809286, "repo_name": "Iteration3/Project", "id": "f2a788865e7726fa90176bfce080c6ce8e2e8df9", "size": "4006", "binary": false, "copies": "1", "ref": "refs/heads/clayCheck", "path": "src/models/Entity/Avatar.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "261835" } ], "symlink_target": "" }
require 'yaml' require 'rack/mock' require 'stringio' app = lambda { |env| req = Rack::Request.new(env) env["mock.postdata"] = env["rack.input"].read if req.GET["error"] env["rack.errors"].puts req.GET["error"] env["rack.errors"].flush end Rack::Response.new(env.to_yaml, req.GET["status"] || 200, "Content-Type" => "text/yaml").finish } describe Rack::MockRequest do should "return a MockResponse" do res = Rack::MockRequest.new(app).get("") res.should.be.kind_of Rack::MockResponse end should "be able to only return the environment" do env = Rack::MockRequest.env_for("") env.should.be.kind_of Hash env.should.include "rack.version" end should "provide sensible defaults" do res = Rack::MockRequest.new(app).request env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "GET" env["SERVER_NAME"].should.equal "example.org" env["SERVER_PORT"].should.equal "80" env["QUERY_STRING"].should.equal "" env["PATH_INFO"].should.equal "/" env["SCRIPT_NAME"].should.equal "" env["rack.url_scheme"].should.equal "http" env["mock.postdata"].should.be.empty end should "allow GET/POST/PUT/DELETE/HEAD" do res = Rack::MockRequest.new(app).get("", :input => "foo") env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "GET" res = Rack::MockRequest.new(app).post("", :input => "foo") env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "POST" res = Rack::MockRequest.new(app).put("", :input => "foo") env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "PUT" res = Rack::MockRequest.new(app).delete("", :input => "foo") env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "DELETE" res = Rack::MockRequest.new(app).head("", :input => "foo") env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "HEAD" Rack::MockRequest.env_for("/", :method => "OPTIONS")["REQUEST_METHOD"]. should.equal "OPTIONS" end should "set content length" do env = Rack::MockRequest.env_for("/", :input => "foo") env["CONTENT_LENGTH"].should.equal "3" end should "allow posting" do res = Rack::MockRequest.new(app).get("", :input => "foo") env = YAML.load(res.body) env["mock.postdata"].should.equal "foo" res = Rack::MockRequest.new(app).post("", :input => StringIO.new("foo")) env = YAML.load(res.body) env["mock.postdata"].should.equal "foo" end should "use all parts of an URL" do res = Rack::MockRequest.new(app). get("https://bla.example.org:9292/meh/foo?bar") res.should.be.kind_of Rack::MockResponse env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "GET" env["SERVER_NAME"].should.equal "bla.example.org" env["SERVER_PORT"].should.equal "9292" env["QUERY_STRING"].should.equal "bar" env["PATH_INFO"].should.equal "/meh/foo" env["rack.url_scheme"].should.equal "https" end should "set SSL port and HTTP flag on when using https" do res = Rack::MockRequest.new(app). get("https://example.org/foo") res.should.be.kind_of Rack::MockResponse env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "GET" env["SERVER_NAME"].should.equal "example.org" env["SERVER_PORT"].should.equal "443" env["QUERY_STRING"].should.equal "" env["PATH_INFO"].should.equal "/foo" env["rack.url_scheme"].should.equal "https" env["HTTPS"].should.equal "on" end should "prepend slash to uri path" do res = Rack::MockRequest.new(app). get("foo") res.should.be.kind_of Rack::MockResponse env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "GET" env["SERVER_NAME"].should.equal "example.org" env["SERVER_PORT"].should.equal "80" env["QUERY_STRING"].should.equal "" env["PATH_INFO"].should.equal "/foo" env["rack.url_scheme"].should.equal "http" end should "properly convert method name to an uppercase string" do res = Rack::MockRequest.new(app).request(:get) env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "GET" end should "accept params and build query string for GET requests" do res = Rack::MockRequest.new(app).get("/foo?baz=2", :params => {:foo => {:bar => "1"}}) env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "GET" env["QUERY_STRING"].should.include "baz=2" env["QUERY_STRING"].should.include "foo[bar]=1" env["PATH_INFO"].should.equal "/foo" env["mock.postdata"].should.equal "" end should "accept raw input in params for GET requests" do res = Rack::MockRequest.new(app).get("/foo?baz=2", :params => "foo[bar]=1") env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "GET" env["QUERY_STRING"].should.include "baz=2" env["QUERY_STRING"].should.include "foo[bar]=1" env["PATH_INFO"].should.equal "/foo" env["mock.postdata"].should.equal "" end should "accept params and build url encoded params for POST requests" do res = Rack::MockRequest.new(app).post("/foo", :params => {:foo => {:bar => "1"}}) env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "POST" env["QUERY_STRING"].should.equal "" env["PATH_INFO"].should.equal "/foo" env["CONTENT_TYPE"].should.equal "application/x-www-form-urlencoded" env["mock.postdata"].should.equal "foo[bar]=1" end should "accept raw input in params for POST requests" do res = Rack::MockRequest.new(app).post("/foo", :params => "foo[bar]=1") env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "POST" env["QUERY_STRING"].should.equal "" env["PATH_INFO"].should.equal "/foo" env["CONTENT_TYPE"].should.equal "application/x-www-form-urlencoded" env["mock.postdata"].should.equal "foo[bar]=1" end should "accept params and build multipart encoded params for POST requests" do files = Rack::Multipart::UploadedFile.new(File.join(File.dirname(__FILE__), "multipart", "file1.txt")) res = Rack::MockRequest.new(app).post("/foo", :params => { "submit-name" => "Larry", "files" => files }) env = YAML.load(res.body) env["REQUEST_METHOD"].should.equal "POST" env["QUERY_STRING"].should.equal "" env["PATH_INFO"].should.equal "/foo" env["CONTENT_TYPE"].should.equal "multipart/form-data; boundary=AaB03x" # The gsub accounts for differences in YAMLs affect on the data. env["mock.postdata"].gsub("\r", "").length.should.equal 206 end should "behave valid according to the Rack spec" do lambda { Rack::MockRequest.new(app). get("https://bla.example.org:9292/meh/foo?bar", :lint => true) }.should.not.raise(Rack::Lint::LintError) end should "call close on the original body object" do called = false body = Rack::BodyProxy.new(['hi']) { called = true } capp = proc { |e| [200, {'Content-Type' => 'text/plain'}, body] } called.should.equal false Rack::MockRequest.new(capp).get('/', :lint => true) called.should.equal true end end describe Rack::MockResponse do should "provide access to the HTTP status" do res = Rack::MockRequest.new(app).get("") res.should.be.successful res.should.be.ok res = Rack::MockRequest.new(app).get("/?status=404") res.should.not.be.successful res.should.be.client_error res.should.be.not_found res = Rack::MockRequest.new(app).get("/?status=501") res.should.not.be.successful res.should.be.server_error res = Rack::MockRequest.new(app).get("/?status=307") res.should.be.redirect res = Rack::MockRequest.new(app).get("/?status=201", :lint => true) res.should.be.empty end should "provide access to the HTTP headers" do res = Rack::MockRequest.new(app).get("") res.should.include "Content-Type" res.headers["Content-Type"].should.equal "text/yaml" res.original_headers["Content-Type"].should.equal "text/yaml" res["Content-Type"].should.equal "text/yaml" res.content_type.should.equal "text/yaml" res.content_length.should.not.equal 0 res.location.should.be.nil end should "provide access to the HTTP body" do res = Rack::MockRequest.new(app).get("") res.body.should =~ /rack/ res.should =~ /rack/ res.should.match(/rack/) res.should.satisfy { |r| r.match(/rack/) } end should "provide access to the Rack errors" do res = Rack::MockRequest.new(app).get("/?error=foo", :lint => true) res.should.be.ok res.errors.should.not.be.empty res.errors.should.include "foo" end should "allow calling body.close afterwards" do # this is exactly what rack-test does body = StringIO.new("hi") res = Rack::MockResponse.new(200, {}, body) body.close if body.respond_to?(:close) res.body.should == 'hi' end should "optionally make Rack errors fatal" do lambda { Rack::MockRequest.new(app).get("/?error=foo", :fatal => true) }.should.raise(Rack::MockRequest::FatalWarning) end end
{ "content_hash": "6caca5721d8e16e8486016d33c88f784", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 108, "avg_line_length": 34.24242424242424, "alnum_prop": 0.6462389380530974, "repo_name": "Waldixx/AppRails", "id": "cd144c6af63769395472d7cc40f03b64ba4fe725", "size": "9040", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "bundle/ruby/1.9.1/gems/rack-1.4.1/test/spec_mock.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1000404" }, { "name": "C++", "bytes": "238594" }, { "name": "CoffeeScript", "bytes": "2968" }, { "name": "Java", "bytes": "174755" }, { "name": "JavaScript", "bytes": "501490" }, { "name": "Objective-C", "bytes": "4770" }, { "name": "PHP", "bytes": "857" }, { "name": "Ruby", "bytes": "13702885" }, { "name": "Shell", "bytes": "439" }, { "name": "eC", "bytes": "2009" } ], "symlink_target": "" }
class non_copyable { int val; public: BOOST_THREAD_MOVABLE_ONLY(non_copyable) non_copyable(int v) : val(v){} non_copyable(BOOST_RV_REF(non_copyable) x): val(x.val) {} non_copyable& operator=(BOOST_RV_REF(non_copyable) x) { val=x.val; return *this; } bool operator==(non_copyable const& x) const {return val==x.val;} template <typename OSTREAM> friend OSTREAM& operator <<(OSTREAM& os, non_copyable const&x ) { os << x.val; return os; } }; #if defined BOOST_NO_CXX11_RVALUE_REFERENCES BOOST_STATIC_ASSERT( ! boost::is_copy_constructible<non_copyable>::value ); BOOST_STATIC_ASSERT( boost::has_move_emulation_enabled<non_copyable>::value ); #endif int main() { { // default queue invariants boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // default queue invariants boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // empty queue try_pull fails boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); int i; BOOST_TEST( boost::queue_op_status::empty == q.try_pull(i)); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // empty queue push rvalue/copyable succeeds boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); q.push(1); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } { // empty queue push lvalue/copyable succeeds boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); int i; q.push(i); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } #if 0 { // empty queue push rvalue/non_copyable succeeds boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_back<non_copyable> q(sq); q.push(non_copyable(1)); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } #endif { // empty queue push rvalue/non_copyable succeeds boost::deque_adaptor<boost::sync_deque<non_copyable> > q; //boost::sync_deque<non_copyable> q; //boost::deque_back<non_copyable> q(sq); non_copyable nc(1); q.push_back(boost::move(nc)); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } { // empty queue push rvalue succeeds boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); q.push(1); q.push(2); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 2u); BOOST_TEST(! q.closed()); } { // empty queue push lvalue succeeds boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); int i; q.push(i); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } { // empty queue try_push rvalue/copyable succeeds boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); BOOST_TEST(boost::queue_op_status::success == q.try_push(1)); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } { // empty queue try_push rvalue/copyable succeeds boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); BOOST_TEST(boost::queue_op_status::success == q.try_push(1)); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } #if 0 { // empty queue try_push rvalue/non-copyable succeeds boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_back<non_copyable> q(sq); non_copyable nc(1); BOOST_TEST(boost::queue_op_status::success == q.try_push(boost::move(nc))); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } #endif { // empty queue try_push lvalue succeeds boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); int i=0; BOOST_TEST(boost::queue_op_status::success == q.try_push(i)); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } { // empty queue try_push rvalue succeeds boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push(1)); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } #if 0 { // empty queue nonblocking_push_back rvalue/non-copyable succeeds boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_back<non_copyable> q(sq); BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push(non_copyable(1))); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } #endif { // empty queue nonblocking_push_back rvalue/non-copyable succeeds boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_back<non_copyable> q(sq); non_copyable nc(1); BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push(boost::move(nc))); BOOST_TEST(! q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 1u); BOOST_TEST(! q.closed()); } { // 1-element queue pull_front succeed boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); sq.push_back(1); int i; q.pull(i); BOOST_TEST_EQ(i, 1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue pull_front succeed boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_front<non_copyable> q(sq); non_copyable nc1(1); sq.push_back(boost::move(nc1)); non_copyable nc2(2); q.pull(nc2); BOOST_TEST_EQ(nc1, nc2); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue pull_front succeed boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); sq.push_back(1); int i = q.pull(); BOOST_TEST_EQ(i, 1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue pull_front succeed boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_front<non_copyable> q(sq); non_copyable nc1(1); sq.push_back(boost::move(nc1)); non_copyable nc = q.pull(); BOOST_TEST_EQ(nc, nc1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue try_pull_front succeed boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); sq.push_back(1); int i; BOOST_TEST(boost::queue_op_status::success == q.try_pull(i)); BOOST_TEST_EQ(i, 1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue try_pull_front succeed boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_front<non_copyable> q(sq); non_copyable nc1(1); sq.push_back(boost::move(nc1)); non_copyable nc(2); BOOST_TEST(boost::queue_op_status::success == q.try_pull(nc)); BOOST_TEST_EQ(nc, nc1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue nonblocking_pull_front succeed boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); sq.push_back(1); int i; BOOST_TEST(boost::queue_op_status::success == q.nonblocking_pull(i)); BOOST_TEST_EQ(i, 1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue nonblocking_pull_front succeed boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_front<non_copyable> q(sq); non_copyable nc1(1); sq.push_back(boost::move(nc1)); non_copyable nc(2); BOOST_TEST(boost::queue_op_status::success == q.nonblocking_pull(nc)); BOOST_TEST_EQ(nc, nc1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue wait_pull_front succeed boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_front<non_copyable> q(sq); non_copyable nc1(1); sq.push_back(boost::move(nc1)); non_copyable nc(2); BOOST_TEST(boost::queue_op_status::success == q.wait_pull(nc)); BOOST_TEST_EQ(nc, nc1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue wait_pull_front succeed boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); sq.push_back(1); int i; BOOST_TEST(boost::queue_op_status::success == q.wait_pull(i)); BOOST_TEST_EQ(i, 1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // 1-element queue wait_pull_front succeed boost::deque_adaptor<boost::sync_deque<non_copyable> > sq; boost::deque_front<non_copyable> q(sq); non_copyable nc1(1); sq.push_back(boost::move(nc1)); non_copyable nc(2); BOOST_TEST(boost::queue_op_status::success == q.wait_pull(nc)); BOOST_TEST_EQ(nc, nc1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(! q.closed()); } { // closed invariants boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); q.close(); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(q.closed()); } { // closed invariants boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); q.close(); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(q.closed()); } { // closed queue push fails boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_back<int> q(sq); q.close(); try { q.push(1); BOOST_TEST(false); } catch (...) { BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(q.closed()); } } { // 1-element closed queue pull succeed boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); sq.push_back(1); q.close(); int i; q.pull(i); BOOST_TEST_EQ(i, 1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(q.closed()); } { // 1-element closed queue wait_pull_front succeed boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); sq.push_back(1); q.close(); int i; BOOST_TEST(boost::queue_op_status::success == q.wait_pull(i)); BOOST_TEST_EQ(i, 1); BOOST_TEST(q.empty()); BOOST_TEST(! q.full()); BOOST_TEST_EQ(q.size(), 0u); BOOST_TEST(q.closed()); } { // closed empty queue wait_pull_front fails boost::deque_adaptor<boost::sync_deque<int> > sq; boost::deque_front<int> q(sq); q.close(); BOOST_TEST(q.empty()); BOOST_TEST(q.closed()); int i; BOOST_TEST(boost::queue_op_status::closed == q.wait_pull(i)); BOOST_TEST(q.empty()); BOOST_TEST(q.closed()); } return boost::report_errors(); }
{ "content_hash": "cfb8609be7ef7c690c2145f4fe81d319", "timestamp": "", "source": "github", "line_count": 434, "max_line_length": 89, "avg_line_length": 29.642857142857142, "alnum_prop": 0.5731830547998445, "repo_name": "hkernbach/arangodb", "id": "ba9c75b95bc279991cd7740b3d511953770d37a0", "size": "13482", "binary": false, "copies": "17", "ref": "refs/heads/devel", "path": "3rdParty/boost/1.62.0/libs/thread/test/sync/mutual_exclusion/deque_views/single_thread_pass.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "391227" }, { "name": "Awk", "bytes": "7502" }, { "name": "Batchfile", "bytes": "62496" }, { "name": "C", "bytes": "9184899" }, { "name": "C#", "bytes": "96431" }, { "name": "C++", "bytes": "278343201" }, { "name": "CMake", "bytes": "664691" }, { "name": "CSS", "bytes": "650173" }, { "name": "CWeb", "bytes": "174166" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "259402" }, { "name": "Emacs Lisp", "bytes": "14637" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Groovy", "bytes": "51836" }, { "name": "HTML", "bytes": "2415724" }, { "name": "Java", "bytes": "1048556" }, { "name": "JavaScript", "bytes": "54219725" }, { "name": "LLVM", "bytes": "24019" }, { "name": "Lex", "bytes": "1231" }, { "name": "Lua", "bytes": "17899" }, { "name": "M4", "bytes": "658700" }, { "name": "Makefile", "bytes": "522586" }, { "name": "Max", "bytes": "36857" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "42998" }, { "name": "Objective-C", "bytes": "98866" }, { "name": "Objective-C++", "bytes": "2503" }, { "name": "PHP", "bytes": "118092" }, { "name": "Pascal", "bytes": "150599" }, { "name": "Perl", "bytes": "906737" }, { "name": "Perl 6", "bytes": "25883" }, { "name": "PowerShell", "bytes": "20434" }, { "name": "Python", "bytes": "4557865" }, { "name": "QMake", "bytes": "16692" }, { "name": "R", "bytes": "5123" }, { "name": "Rebol", "bytes": "354" }, { "name": "Roff", "bytes": "1089418" }, { "name": "Ruby", "bytes": "1141022" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "508528" }, { "name": "Swift", "bytes": "116" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "Visual Basic", "bytes": "11568" }, { "name": "XSLT", "bytes": "567028" }, { "name": "Yacc", "bytes": "53063" } ], "symlink_target": "" }
<span class="environment-features"> </span>
{ "content_hash": "4c1d835e76b40b323956dff7f1d23325", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 35, "avg_line_length": 22, "alnum_prop": 0.7272727272727273, "repo_name": "wildbits/lead", "id": "378dae6c3ec06c30a1d4d2b28eb5a79fcc7f4194", "size": "44", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "www/templates/EnvironmentResultView.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "18560" }, { "name": "HTML", "bytes": "54453" }, { "name": "JavaScript", "bytes": "245155" } ], "symlink_target": "" }
package github.orius123.orchapp.web.rest; import github.orius123.orchapp.Application; import github.orius123.orchapp.repository.UserRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import javax.inject.Inject; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the UserResource REST controller. * * @see UserResource */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration public class UserResourceTest { @Inject private UserRepository userRepository; private MockMvc restUserMockMvc; @Before public void setup() { UserResource userResource = new UserResource(); ReflectionTestUtils.setField(userResource, "userRepository", userRepository); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource).build(); } @Test public void testGetExistingUser() throws Exception { restUserMockMvc.perform(get("/app/rest/users/admin") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.lastName").value("Administrator")); } @Test public void testGetUnknownUser() throws Exception { restUserMockMvc.perform(get("/app/rest/users/unknown") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } }
{ "content_hash": "5163e34ca546b89016b4b36cc44e70f7", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 86, "avg_line_length": 36.220338983050844, "alnum_prop": 0.7524567150210576, "repo_name": "orius123/slenkins", "id": "5b382b0d0778936193652ef9c2040045039458df", "size": "2137", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/github/orius123/orchapp/web/rest/UserResourceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2982" }, { "name": "Java", "bytes": "165229" }, { "name": "JavaScript", "bytes": "64634" }, { "name": "Slash", "bytes": "404" } ], "symlink_target": "" }
import { Observable } from '../../internal/Observable'; import { skip } from '../../internal/patching/operator/skip'; Observable.prototype.skip = skip; declare module '../../internal/Observable' { interface Observable<T> { skip: typeof skip; } }
{ "content_hash": "ccb0a5962c64b32268966631676f51ba", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 61, "avg_line_length": 25.6, "alnum_prop": 0.671875, "repo_name": "IgorMinar/RxJS", "id": "54902a49a393649a7de25dfeb5e64bf48c869bd2", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/add/operator/skip.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "509" }, { "name": "JavaScript", "bytes": "5880" } ], "symlink_target": "" }
package com.navercorp.pinpoint.profiler; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.bootstrap.instrument.DynamicTransformTrigger; import com.navercorp.pinpoint.common.util.Assert; import com.navercorp.pinpoint.profiler.instrument.InstrumentEngine; import com.navercorp.pinpoint.profiler.instrument.classreading.InternalClassMetadata; import com.navercorp.pinpoint.profiler.instrument.classreading.InternalClassMetadataReader; import com.navercorp.pinpoint.profiler.instrument.transformer.DebugTransformerRegistry; import com.navercorp.pinpoint.profiler.instrument.transformer.MatchableTransformerRegistry; import com.navercorp.pinpoint.profiler.instrument.transformer.TransformerRegistry; import com.navercorp.pinpoint.profiler.plugin.MatchableClassFileTransformer; import com.navercorp.pinpoint.profiler.plugin.PluginContextLoadResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; /** * @author jaehong.kim */ public class MatchableClassFileTransformerDispatcher implements ClassFileTransformerDispatcher { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); private final ClassLoader agentClassLoader = this.getClass().getClassLoader(); private final BaseClassFileTransformer baseClassFileTransformer; private final TransformerRegistry transformerRegistry; private final DynamicTransformerRegistry dynamicTransformerRegistry; private final TransformerRegistry debugTransformerRegistry; private final ClassFileFilter classLoaderFilter; private final ClassFileFilter pinpointClassFilter; private final ClassFileFilter unmodifiableFilter; private final boolean supportLambdaExpressions; public MatchableClassFileTransformerDispatcher(ProfilerConfig profilerConfig, PluginContextLoadResult pluginContextLoadResult, InstrumentEngine instrumentEngine, DynamicTransformTrigger dynamicTransformTrigger, DynamicTransformerRegistry dynamicTransformerRegistry) { Assert.requireNonNull(profilerConfig, "profilerConfig must not be null"); Assert.requireNonNull(pluginContextLoadResult, "pluginContexts must not be null"); Assert.requireNonNull(instrumentEngine, "instrumentEngine must not be null"); Assert.requireNonNull(dynamicTransformerRegistry, "dynamicTransformerRegistry must not be null"); this.baseClassFileTransformer = new BaseClassFileTransformer(agentClassLoader); this.debugTransformerRegistry = new DebugTransformerRegistry(profilerConfig, instrumentEngine, dynamicTransformTrigger); this.transformerRegistry = createTransformerRegistry(pluginContextLoadResult, profilerConfig); this.dynamicTransformerRegistry = dynamicTransformerRegistry; this.classLoaderFilter = new PinpointClassLoaderFilter(agentClassLoader); this.pinpointClassFilter = new PinpointClassFilter(); this.unmodifiableFilter = new UnmodifiableClassFilter(); this.supportLambdaExpressions = profilerConfig.isSupportLambdaExpressions(); } @Override public byte[] transform(ClassLoader classLoader, String classInternalName, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) throws IllegalClassFormatException { if (!classLoaderFilter.accept(classLoader, classInternalName, classBeingRedefined, protectionDomain, classFileBuffer)) { return null; } InternalClassMetadata classMetadata = null; String internalName = classInternalName; if (internalName == null) { if (this.supportLambdaExpressions) { // proxy-like class specific for lambda expressions. // e.g. Example$$Lambda$1/1072591677 try { classMetadata = InternalClassMetadataReader.readInternalClassMetadata(classFileBuffer); internalName = classMetadata.getClassInternalName(); } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Failed to read metadata of lambda expressions. classLoader={}", classLoader, e); } return null; } } else { // unsupported lambda expressions. return null; } } if (internalName == null) { return null; } if (!pinpointClassFilter.accept(classLoader, internalName, classBeingRedefined, protectionDomain, classFileBuffer)) { return null; } final ClassFileTransformer dynamicTransformer = dynamicTransformerRegistry.getTransformer(classLoader, internalName); if (dynamicTransformer != null) { return baseClassFileTransformer.transform(classLoader, internalName, classBeingRedefined, protectionDomain, classFileBuffer, dynamicTransformer); } if (!unmodifiableFilter.accept(classLoader, internalName, classBeingRedefined, protectionDomain, classFileBuffer)) { return null; } ClassFileTransformer transformer = this.transformerRegistry.findTransformer(classLoader, internalName, classFileBuffer, classMetadata); if (transformer == null) { // For debug // TODO What if a modifier is duplicated? transformer = this.debugTransformerRegistry.findTransformer(classLoader, internalName, classFileBuffer); if (transformer == null) { return null; } } return baseClassFileTransformer.transform(classLoader, internalName, classBeingRedefined, protectionDomain, classFileBuffer, transformer); } private TransformerRegistry createTransformerRegistry(PluginContextLoadResult pluginContexts, final ProfilerConfig profilerConfig) { final MatchableTransformerRegistry registry = new MatchableTransformerRegistry(profilerConfig); for (ClassFileTransformer transformer : pluginContexts.getClassFileTransformer()) { if (transformer instanceof MatchableClassFileTransformer) { MatchableClassFileTransformer t = (MatchableClassFileTransformer) transformer; if (logger.isInfoEnabled()) { logger.info("Registering class file transformer {} for {} ", t, t.getMatcher()); } try { registry.addTransformer(t.getMatcher(), t); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Failed to add transformer {}", transformer, e); } } } else { if (logger.isWarnEnabled()) { logger.warn("Ignore class file transformer {}", transformer); } } } return registry; } }
{ "content_hash": "88f8d4149305e0aae88e4ce2409ddf85", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 204, "avg_line_length": 49.69444444444444, "alnum_prop": 0.7122694242593628, "repo_name": "jiaqifeng/pinpoint", "id": "2cf6ef146384714637cff123a9cbd0d2050d3a0d", "size": "7750", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "profiler/src/main/java/com/navercorp/pinpoint/profiler/MatchableClassFileTransformerDispatcher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "27926" }, { "name": "CSS", "bytes": "156602" }, { "name": "CoffeeScript", "bytes": "10124" }, { "name": "Groovy", "bytes": "1423" }, { "name": "HTML", "bytes": "628369" }, { "name": "Java", "bytes": "12213165" }, { "name": "JavaScript", "bytes": "4789397" }, { "name": "Makefile", "bytes": "5246" }, { "name": "PLSQL", "bytes": "4156" }, { "name": "Python", "bytes": "3523" }, { "name": "Ruby", "bytes": "943" }, { "name": "Shell", "bytes": "37985" }, { "name": "Thrift", "bytes": "14006" } ], "symlink_target": "" }
module.exports = { "extends": "./node_modules/stylelint-config-standard", "rules": { "color-hex-case": "upper", "selector-max-id": 1, "selector-pseudo-element-colon-notation": "single", "no-missing-end-of-source-newline": null, "color-hex-length": "long", "max-nesting-depth": 4 } }
{ "content_hash": "951ff49717b423159080da54c76fae8c", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 59, "avg_line_length": 31.09090909090909, "alnum_prop": 0.5701754385964912, "repo_name": "stfalcon/fwdays", "id": "7b85ccb78fecce19539ca230e69daa00ea80b104", "size": "342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stylelintrc.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "59606" }, { "name": "Dockerfile", "bytes": "4459" }, { "name": "HTML", "bytes": "743032" }, { "name": "JavaScript", "bytes": "400833" }, { "name": "PHP", "bytes": "1138660" }, { "name": "SCSS", "bytes": "205362" }, { "name": "Shell", "bytes": "3401" }, { "name": "Twig", "bytes": "211574" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>QueryLayer Tests</title> <!-- META TAGS --> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <!-- CSS --> <link rel="stylesheet" type="text/css" href="../../esri/css/esri.css" /> <link rel="stylesheet" href="../../bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="../resources/App.css"> <style type='text/css'> body { padding: 50px; } #mapDiv { border: solid gray 1px; } .identify-widget { border: solid gray 1px; width: 270px; padding: 10px 6px 6px 10px; } </style> <!-- JAVASCRIPT --> <script type="text/javascript" src="../../jquery/dist/jquery.js"></script> <script type='text/javascript' src="../../bootstrap/dist/js/bootstrap.js"></script> <script type='text/javascript' src="../../dojo/dojo.js"></script> <script type='text/javascript' src="../../app/packages.js"></script> <script type="text/javascript"> var baseUrl = window.location.pathname.replace(/\/[^\/]+$/, '') + '/' + '../../'; var widgetUnderTest; require({ baseUrl: '../../' }, [ 'app/Identify', 'agrc/widgets/map/BaseMap', 'dojo/dom-construct', 'dojo/domReady!' ], function( Module, BaseMap, domConstruct ) { widgetUnderTest = new Module({map: new BaseMap('mapDiv')}); widgetUnderTest.startup(); domConstruct.place(widgetUnderTest.domNode, document.body); widgetUnderTest.onMapClick({ mapPoint: { x: 438888.5113211562, y: 4435618.118854405 } }); }); </script> </head> <body class='claro'> <div id="node"></div> <div id="mapDiv"></div> </body> </html>
{ "content_hash": "2ff869a251bc50ef5f7dd163ae836d24", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 90, "avg_line_length": 28.430555555555557, "alnum_prop": 0.5129457743038593, "repo_name": "keatonwalker/cell-tower-coverage", "id": "03143e201c7594cc9cd01b67ded65761f5530465", "size": "2047", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/tests/IdentifyTests.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2540" }, { "name": "HTML", "bytes": "9714" }, { "name": "JavaScript", "bytes": "53964" }, { "name": "Python", "bytes": "4158" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.3.xsd"> <changeSet author="maciek (generated)" id="1424807664109-1"> <createSequence sequenceName="Wasteland2NPC_SEQ"/> </changeSet> <changeSet author="maciek (generated)" id="1424807664109-2"> <createSequence sequenceName="Wasteland2Weapon_SEQ"/> </changeSet> <changeSet author="maciek (generated)" id="1424807664109-3"> <createTable tableName="Wasteland2NPC"> <column name="id" type="BIGINT"> <constraints nullable="false"/> </column> <column name="location" type="VARCHAR(255)"/> <column name="name" type="VARCHAR(255)"/> </createTable> </changeSet> <changeSet author="maciek (generated)" id="1424807664109-4"> <createTable tableName="Wasteland2Weapon"> <column name="id" type="BIGINT"> <constraints nullable="false"/> </column> <column name="name" type="VARCHAR(255)"/> <column name="type" type="VARCHAR(255)"/> </createTable> </changeSet> <changeSet author="maciek (generated)" id="1424807664109-5"> <addPrimaryKey columnNames="id" constraintName="Wasteland2NPCPK" tableName="Wasteland2NPC"/> </changeSet> <changeSet author="maciek (generated)" id="1424807664109-6"> <addPrimaryKey columnNames="id" constraintName="Wasteland2WeaponPK" tableName="Wasteland2Weapon"/> </changeSet> </databaseChangeLog>
{ "content_hash": "930c58c65d195b3148fe091ad2241830", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 426, "avg_line_length": 59.15151515151515, "alnum_prop": 0.6547131147540983, "repo_name": "mraszplewicz/springboottest", "id": "8c4908c53d61e0053760a1b7e49bfc9a1f3724d4", "size": "1952", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "model/db/liquibase/changelog/changelog-0.1.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "128" }, { "name": "HTML", "bytes": "457" }, { "name": "Java", "bytes": "52786" }, { "name": "JavaScript", "bytes": "1444" }, { "name": "TypeScript", "bytes": "523" } ], "symlink_target": "" }
/* Implementation of Boost.Python cross-module support. See root/libs/python/doc/cross_module.html for details. */ #ifndef CROSS_MODULE_HPP # define CROSS_MODULE_HPP # include <boost/python/class_builder.hpp> namespace boost { namespace python { struct BOOST_PYTHON_DECL import_error: error_already_set {}; struct BOOST_PYTHON_DECL export_error : error_already_set {}; void BOOST_PYTHON_DECL throw_import_error(); void BOOST_PYTHON_DECL throw_export_error(); namespace detail { // Concept: throw exception if api_major is changed // show warning on stderr if api_minor is changed const int export_converters_api_major = 4; const int export_converters_api_minor = 1; extern BOOST_PYTHON_DECL const char* converters_attribute_name; BOOST_PYTHON_DECL void* import_converter_object(const std::string& module_name, const std::string& py_class_name, const std::string& attribute_name); BOOST_PYTHON_DECL void check_export_converters_api(const int importing_major, const int importing_minor, const int imported_major, const int imported_minor); } }} // namespace boost::python // forward declaration namespace boost { namespace python { namespace detail { template <class T> class import_extension_class; }}} BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE /* This class template is instantiated by import_converters<T>. This class is a look-alike of class python_extension_class_converters. The converters in this class are wrappers that call converters imported from another module. To ensure that the dynamic loader resolves all symbols in the intended way, the signature of all friend functions is changed with respect to the original functions in class python_extension_class_converters by adding an arbitrary additional parameter with a default value, in this case "bool sig = false". See also: comments for class export_converter_object_base below. */ template <class T> class python_import_extension_class_converters { public: friend python_import_extension_class_converters py_extension_class_converters(boost::python::type<T>, bool sig = false) { return python_import_extension_class_converters(); } PyObject* to_python(const T& x) const { return boost::python::detail::import_extension_class<T>::get_converters()->to_python(x); } friend T* from_python(PyObject* p, boost::python::type<T*> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_Ts(p, t); } friend const T* from_python(PyObject* p, boost::python::type<const T*> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_cTs(p, t); } friend const T* from_python(PyObject* p, boost::python::type<const T*const&> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_cTscr(p, t); } friend T* from_python(PyObject* p, boost::python::type<T* const&> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_Tscr(p, t); } friend T& from_python(PyObject* p, boost::python::type<T&> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_Tr(p, t); } friend const T& from_python(PyObject* p, boost::python::type<const T&> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_cTr(p, t); } friend const T& from_python(PyObject* p, boost::python::type<T> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_T(p, t); } friend std::auto_ptr<T>& from_python(PyObject* p, boost::python::type<std::auto_ptr<T>&> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_aTr(p, t); } friend std::auto_ptr<T> from_python(PyObject* p, boost::python::type<std::auto_ptr<T> > t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_aT(p, t); } friend const std::auto_ptr<T>& from_python(PyObject* p, boost::python::type<const std::auto_ptr<T>&> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_caTr(p, t); } friend PyObject* to_python(std::auto_ptr<T> x, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->to_python(x); } friend boost::shared_ptr<T>& from_python(PyObject* p, boost::python::type<boost::shared_ptr<T>&> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_sTr(p, t); } friend const boost::shared_ptr<T>& from_python(PyObject* p, boost::python::type<boost::shared_ptr<T> > t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_sT(p, t); } friend const boost::shared_ptr<T>& from_python(PyObject* p, boost::python::type<const boost::shared_ptr<T>&> t, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->from_python_csTr(p, t); } friend PyObject* to_python(boost::shared_ptr<T> x, bool sig = false) { return boost::python::detail::import_extension_class<T>::get_converters()->to_python(x); } }; BOOST_PYTHON_END_CONVERSION_NAMESPACE namespace boost { namespace python { BOOST_PYTHON_IMPORT_CONVERSION(python_import_extension_class_converters); /* This class template is instantiated by export_converters(). A pointer to this class is exported/imported via the Python API. Using the Python API ensures maximum portability. All member functions are virtual. This is, what we export/import is essentially just a pointer to a vtbl. To work around a deficiency of Visual C++ 6.0, the name of each from_python() member functions is made unique by appending a few characters (derived in a ad-hoc manner from the corresponding type). */ template <class T> struct export_converter_object_base { virtual int get_api_major() const { return detail::export_converters_api_major; } virtual int get_api_minor() const { return detail::export_converters_api_minor; } virtual PyObject* to_python(const T& x) = 0; virtual T* from_python_Ts(PyObject* p, boost::python::type<T*> t) = 0; virtual const T* from_python_cTs(PyObject* p, boost::python::type<const T*> t) = 0; virtual const T* from_python_cTscr(PyObject* p, boost::python::type<const T*const&> t) = 0; virtual T* from_python_Tscr(PyObject* p, boost::python::type<T* const&> t) = 0; virtual T& from_python_Tr(PyObject* p, boost::python::type<T&> t) = 0; virtual const T& from_python_cTr(PyObject* p, boost::python::type<const T&> t) = 0; virtual const T& from_python_T(PyObject* p, boost::python::type<T> t) = 0; virtual std::auto_ptr<T>& from_python_aTr(PyObject* p, boost::python::type<std::auto_ptr<T>&> t) = 0; virtual std::auto_ptr<T> from_python_aT(PyObject* p, boost::python::type<std::auto_ptr<T> > t) = 0; virtual const std::auto_ptr<T>& from_python_caTr(PyObject* p, boost::python::type<const std::auto_ptr<T>&> t) = 0; virtual PyObject* to_python(std::auto_ptr<T> x) = 0; virtual boost::shared_ptr<T>& from_python_sTr(PyObject* p, boost::python::type<boost::shared_ptr<T>&> t) = 0; virtual const boost::shared_ptr<T>& from_python_sT(PyObject* p, boost::python::type<boost::shared_ptr<T> > t) = 0; virtual const boost::shared_ptr<T>& from_python_csTr(PyObject* p, boost::python::type<const boost::shared_ptr<T>&> t) = 0; virtual PyObject* to_python(boost::shared_ptr<T> x) = 0; }; // Converters to be used if T is not copyable. template <class T> struct export_converter_object_noncopyable : export_converter_object_base<T> { virtual PyObject* to_python(const T& x) { PyErr_SetString(PyExc_RuntimeError, "to_python(const T&) converter not exported"); throw_import_error(); return 0; } virtual T* from_python_Ts(PyObject* p, boost::python::type<T*> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual const T* from_python_cTs(PyObject* p, boost::python::type<const T*> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual const T* from_python_cTscr(PyObject* p, boost::python::type<const T*const&> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual T* from_python_Tscr(PyObject* p, boost::python::type<T* const&> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual T& from_python_Tr(PyObject* p, boost::python::type<T&> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual const T& from_python_cTr(PyObject* p, boost::python::type<const T&> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual const T& from_python_T(PyObject* p, boost::python::type<T> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual std::auto_ptr<T>& from_python_aTr(PyObject* p, boost::python::type<std::auto_ptr<T>&> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual std::auto_ptr<T> from_python_aT(PyObject* p, boost::python::type<std::auto_ptr<T> > t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual const std::auto_ptr<T>& from_python_caTr(PyObject* p, boost::python::type<const std::auto_ptr<T>&> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual PyObject* to_python(std::auto_ptr<T> x) { return BOOST_PYTHON_CONVERSION::to_python(x); } virtual boost::shared_ptr<T>& from_python_sTr(PyObject* p, boost::python::type<boost::shared_ptr<T>&> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual const boost::shared_ptr<T>& from_python_sT(PyObject* p, boost::python::type<boost::shared_ptr<T> > t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual const boost::shared_ptr<T>& from_python_csTr(PyObject* p, boost::python::type<const boost::shared_ptr<T>&> t) { return BOOST_PYTHON_CONVERSION::from_python(p, t); } virtual PyObject* to_python(boost::shared_ptr<T> x) { return BOOST_PYTHON_CONVERSION::to_python(x); } }; // The addditional to_python() converter that can be used if T is copyable. template <class T> struct export_converter_object : export_converter_object_noncopyable<T> { virtual PyObject* to_python(const T& x) { return BOOST_PYTHON_CONVERSION::py_extension_class_converters(boost::python::type<T>()).to_python(x); } }; namespace detail { /* This class template is instantiated by import_converters<T>. Its purpose is to import the converter_object via the Python API. The actual import is only done once. The pointer to the imported converter object is kept in the static data member imported_converters. */ template <class T> class import_extension_class : public python_import_extension_class_converters<T> { public: inline import_extension_class(const char* module, const char* py_class) { m_module = module; m_py_class = py_class; } static boost::python::export_converter_object_base<T>* get_converters(); private: static std::string m_module; static std::string m_py_class; static boost::python::export_converter_object_base<T>* imported_converters; }; template <class T> std::string import_extension_class<T>::m_module; template <class T> std::string import_extension_class<T>::m_py_class; template <class T> boost::python::export_converter_object_base<T>* import_extension_class<T>::imported_converters = 0; template <class T> boost::python::export_converter_object_base<T>* import_extension_class<T>::get_converters() { if (imported_converters == 0) { void* cobject = import_converter_object(m_module, m_py_class, converters_attribute_name); imported_converters = static_cast<boost::python::export_converter_object_base<T>*>(cobject); check_export_converters_api( export_converters_api_major, export_converters_api_minor, imported_converters->get_api_major(), imported_converters->get_api_minor()); } return imported_converters; } }}} // namespace boost::python::detail namespace boost { namespace python { // Implementation of export_converters(). template <class T, class U> void export_converters(class_builder<T, U>& cb) { static export_converter_object<T> export_cvts; cb.add( ref(PyCObject_FromVoidPtr(reinterpret_cast<void*>(&export_cvts), NULL)), detail::converters_attribute_name); } // Implementation of export_converters_noncopyable(). template <class T, class U> void export_converters_noncopyable(class_builder<T, U>& cb) { static export_converter_object_noncopyable<T> export_cvts; cb.add( ref(PyCObject_FromVoidPtr(reinterpret_cast<void*>(&export_cvts), NULL)), detail::converters_attribute_name); } // Implementation of import_converters<T>. template <class T> class import_converters : python_import_extension_class_converters<T> // Works around MSVC6.x/GCC2.95.2 bug described // at the bottom of class_builder.hpp. { public: import_converters(const char* module, const char* py_class) : m_class(new detail::import_extension_class<T>(module, py_class)) { } private: boost::shared_ptr<detail::import_extension_class<T> > m_class; }; }} // namespace boost::python #endif // CROSS_MODULE_HPP
{ "content_hash": "be47df6faa80f814eec0b8dbd60ce44e", "timestamp": "", "source": "github", "line_count": 321, "max_line_length": 135, "avg_line_length": 44.08411214953271, "alnum_prop": 0.668503992650696, "repo_name": "Ezeer/VegaStrike_win32FR", "id": "c6ac8c22b1ed7985d33de5e55cc8e2033761940b", "size": "14565", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vegastrike/boost/1_28/boost/python/cross_module.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4197693" }, { "name": "C++", "bytes": "99169723" }, { "name": "Objective-C", "bytes": "135840" }, { "name": "Perl", "bytes": "21684" }, { "name": "Python", "bytes": "186872" }, { "name": "Shell", "bytes": "114240" }, { "name": "Standard ML", "bytes": "2678" } ], "symlink_target": "" }
title: TICKscript Language Reference menu: kapacitor_1_3: name: TICKscript identifier: tick weight: 3 --- Kapacitor uses a DSL named `TICKscript`. The DSL is used to define the pipelines for processing data in Kapacitor. The TICKscript language is an invocation chaining language. Each script has a flat scope and each variable in the scope defines methods that can be called on it. These methods come in two flavors. * Property methods -- Modifies the node they are called on and returns a reference to the same node. * Chaining methods -- Creates a new node as a child of the node they are called on and returns a reference to the new node. The reference documentation lists each node's `Property` and `Chaining` methods along with examples and descriptions. Every TICKscript will have either a `stream` or `batch` variable defined depending on the type of task you want to run. The `stream` and `batch` variables are an instance of a [StreamNode](/kapacitor/v1.3/nodes/stream_node/) or [BatchNode](/kapacitor/v1.3/nodes/batch_node/) respectively. Pipelines --------- Kapacitor uses TICKscripts to define data processing pipelines. A pipeline is set of nodes that process data and edges that connect the nodes. Pipelines in Kapacitor are directed acyclic graphs ([DAGs](https://en.wikipedia.org/wiki/Directed_acyclic_graph)) meaning each edge has a direction that data flows and there cannot be any cycles in the pipeline. Each edge has a type, one of the following: * StreamEdge -- an edge that transfers data a single data point at a time. * BatchEdge -- an edge that transfers data in chunks instead of one point at a time. When connecting nodes the TICKscript language will not prevent you from connecting edges of the wrong type but rather the check will be performed at runtime. So just be aware that a syntactically correct script may define a pipeline that is invalid. Example ------- ```javascript stream |from() .measurement('app') |eval(lambda: "errors" / "total") .as('error_percent') // Write the transformed data to InfluxDB |influxDBOut() .database('mydb') .retentionPolicy('myrp') .measurement('errors') .tag('kapacitor', 'true') .tag('version', '0.2') ```
{ "content_hash": "845ccf8c4ca73e8b0cd047525f4720f3", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 168, "avg_line_length": 38.57627118644068, "alnum_prop": 0.7368189806678384, "repo_name": "influxdb/docs.influxdata.com", "id": "7623f1aa0f43aa3cc2b591d6312b58324dae4587", "size": "2280", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "content/kapacitor/v1.3/tick/_index.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "67677" }, { "name": "HTML", "bytes": "27829" }, { "name": "JavaScript", "bytes": "1584" }, { "name": "Shell", "bytes": "807" } ], "symlink_target": "" }
/** _ __ __ _ (_) | \/ | (_) _ __ ___ ___ _ __ ___ _ __ ___ ___ _____| \ / | __ _ __ _ _ ___ | '__/ _ \/ __| '_ \ / _ \| '_ \/ __| \ \ / / _ \ |\/| |/ _` |/ _` | |/ __| | | | __/\__ \ |_) | (_) | | | \__ \ |\ V / __/ | | | (_| | (_| | | (__ |_| \___||___/ .__/ \___/|_| |_|___/_| \_/ \___|_| |_|\__,_|\__, |_|\___| | | __/ | |_| |___/ v1.0 - jQuery plugin created by Alvaro Prieto Lauroba. Licences: MIT & GPL */ /* ¿Como me lo imagino? * aplica zoom automáticamente y lo expone redimensiona el contenido del viewport posibilidad de agregar bordes (por resolucion) exponer al exterior la posicion del mouse posibilidad de multiples contenedores? */ (function($){ var SIGNATURE = "resizeMagic"; var INFINITY = 99999; var zoom = 1; var viewport = null; var screenWidth = 0; var body = $('body'); var head = $('head'); var html = $('html'); var wnd = $(window); var watchers = []; var handlers = {}; var cssClasses = ""; var displayClasses = ""; var displayClassesSelector = ""; var ranges = []; var currentRangeIndex = -1; var currentRange = null; var options = {}; var modes = { "tiny": [0, 480], "small": [481, 768], "medium": [769, 1024], "big": [1025, 1250], "huge": [1251, INFINITY] }; var magicContent = { "magic-src": { "selector": '', "elements": null, "init": 'magicSrcInit', "update": 'magicSrcUpdate' }, "magic-text": { "selector": '', "elements": null, "init": 'magicTextInit', "update": 'magicTextUpdate' }, "magic-hide": { "selector": '', "elements": null, "init": 'magicDisplayInit', "update": null }, "magic-show": { "selector": '', "elements": null, "init": 'magicDisplayInit', "update": null } }; var errors = [ "RANGE ERROR: first range must start with 0", // 0 "RANGE ERROR: ranges malformation", // 1 "RANGE ERROR: at least 2 ranges are needed in order to use this plugin", //2 "MATCHMEDIA ERROR: your browser does not support matchMedia. Use a polyfill for further compatibility" //3 ]; var styles = { ".resizeMagicDebug": "{font-size:20px; position: fixed; top: 0px; z-index: 99; opacity:0.6; color:black;}", ".resizeMagicDebug:hover": "{opacity:1; }", ".resizeMagicBtn": "{padding:10px; outline:none; border:1px solid #333; background-color:#bbb;}", ".resizeMagicBtn.active": "{background-color:lime; pointer-events:none;}", ".resizeMagicBtn:hover": "{background-color:yellow;}" }; var createDisplayClasses = function(){ var hide = [], show = [], hideDefault = [], displayCss = [], displayCssSelector = []; var range; for(var i = 0; i<ranges.length; i++){ range = ranges[i].name; hide.push( '.'+ range + ' .magic-hide-'+ range); show.push( '.'+ range + ' .magic-show-'+ range); hideDefault.push( '.magic-show-'+ range); displayCss.push( 'magic-hide-'+ range); displayCss.push( 'magic-show-'+ range); displayCssSelector.push( '.magic-hide-'+ range); displayCssSelector.push( '.magic-show-'+ range); } displayClassesSelector = displayCssSelector.join(','); displayClasses = displayCss.join(' '); return hide.join(',') + '{display:none;} '+ hideDefault.join(',') + '{display:none;} '+ show.join(',') + '{display:initial;}'; }; var setStyles = function(){ var cssString = ""; for (var selector in styles) { if( styles.hasOwnProperty( selector ) ) { cssString += selector + styles[selector]; } } cssString += createDisplayClasses(); head.append('<style type="text/css" class="resizeMagicStyles">'+ cssString +'</style>'); } var detectDevice = function(){ var ie = navigator.userAgent.indexOf('Trident/4.0')>0; console.log("Device: "); console.log("Browser: "); } var getCurrentRange = function(){ var range; for(var i = 0; i<ranges.length; i++){ range = ranges[i]; if(range.query.matches) break; } if(currentRangeIndex != i){ currentRangeIndex = i; currentRange = range; $(".resizeMagicBtn").removeClass("active"); $(".resizeMagicBtn." + currentRange.name).addClass("active"); html.removeClass( cssClasses ).addClass( currentRange.name ); updateWatchers(); wnd.trigger('mediaQuery', $.extend({}, range)); } } var throwError = function( errorCode ){ console.error( errors[ errorCode ] ); return -1; } var initRanges = function(){ var previousBottom = -1; var previousTop = -1; var bottom, top, range, lastRange; var query; for (var rangeName in modes) { if( modes.hasOwnProperty( rangeName ) ) { range = modes[rangeName]; bottom = range[0]; top = range[1]; if(previousBottom < 0 && bottom != 0) { return throwError(0); } if(previousBottom >= bottom || bottom >= top || bottom-1 != previousTop){ return throwError(1); } range = { bottom: bottom, top: top, name: rangeName, query: window.matchMedia('(min-width: '+ bottom +'px) and (max-width: '+ top +'px)'), viewport: top }; ranges.push(range); cssClasses += rangeName + ' '; previousBottom = bottom; previousTop = top; range.query.addListener(getCurrentRange); } } if(ranges.length < 2) return throwError(2); lastRange = ranges[ranges.length-1]; lastRange.isLast = true; lastRange.top = INFINITY; lastRange.viewport = bottom; return 1; } var findMagicElements = function(){ //construimos dinámicamente el selector que captura a todos los watchers var selector = [], attrName, fullAttrName, range, rangeSelector, group; for (var attrName in magicContent) { if( magicContent.hasOwnProperty( attrName ) ) { rangeSelector = []; for(var i = 0; i<ranges.length; i++){ range = ranges[i]; fullAttrName = '['+ attrName + '-' + range.name +']'; selector.push( fullAttrName ); rangeSelector.push( fullAttrName ); } group = magicContent[attrName]; if(rangeSelector.length){ group.selector = rangeSelector.join(','); group.elements = body.find(group.selector); } } } } var fillWatcherValues = function( watcher ){ var values = [], value, range; for(var i = 0; i<ranges.length; i++){ range = ranges[i]; value = watcher.element.attr(watcher.typeName + '-' + range.name); values.push( value || watcher.default ); } watcher.values = values; } var addDisplayClasses = function( watcher ){ var classes = [], hasAttr, range, element, currentClass; for(var i = 0; i<ranges.length; i++){ range = ranges[i]; element = watcher.element.get(0); currentClass = watcher.typeName + '-' + range.name; hasAttr = element.hasAttribute(currentClass); if(hasAttr) watcher.element.addClass( currentClass ); } } var initWatchers = function(){ findMagicElements(); var mc; for (var attrName in magicContent) { if( magicContent.hasOwnProperty( attrName ) ) { mc = magicContent[ attrName ]; mc.elements.each(function(index){ var el = $(this); var watcher = { 'type': mc, 'element': el, 'typeName': attrName, 'nodeType': el.prop('nodeName').toUpperCase() }; handlers[mc.init](watcher); if(mc.update) watchers.push(watcher); }); } } } var updateWatchers = function(){ var w, update; for(var i=0; i<watchers.length; i++){ w = watchers[i]; update = w.type.update; if(update) handlers[update](w); } }; var initDebug = function(){ if(options.debug){ var btn, html ="", text, range, debugBar; for(var i = 0; i<ranges.length; i++){ range = ranges[i]; text = range.name + ' [' + range.bottom + '-' + (range.isLast ? '∞' : range.top) + ']'; btn = '<button data-range="'+ i +'" class="resizeMagicBtn '+ range.name +'">' + text + '</button>'; html += btn; } debugBar = $('<div class="resizeMagicDebug">'); debugBar.append(html); body.append(debugBar); $(".resizeMagicBtn").click( onRangeButtonClick ); } } var onRangeButtonClick = function(e){ var url = window.location.href, btn = $(this), targetViewport = ranges[ btn.data('range')*1 ].viewport; window.open(url,'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+ targetViewport +',height=600'); } //image watcher handlers.magicSrcInit = function( watcher ){ watcher.default = watcher.element.attr("src"); fillWatcherValues( watcher ); } handlers.magicSrcUpdate = function( watcher ){ watcher.element.attr("src", watcher.values[ currentRangeIndex ]); } //text watcher handlers.magicTextInit = function( watcher ){ var valueNode = watcher.nodeType == "TEXTAREA" || watcher.nodeType == "INPUT"; watcher.default = valueNode ? watcher.element.val() : watcher.element.html(); fillWatcherValues( watcher ); } handlers.magicTextUpdate = function( watcher ){ var valueNode = watcher.nodeType == "TEXTAREA" || watcher.nodeType == "INPUT", value = watcher.values[ currentRangeIndex ]; if(valueNode){ watcher.element.val(value); }else{ watcher.element.html(value); } } //show / hide watcher handlers.magicDisplayInit = function( watcher ){ addDisplayClasses( watcher ); } var stretch = function(){ var width = $(window).width() * 1, viewportWidth; if(screenWidth != width){ screenWidth = width; viewportWidth = currentRange.viewport; zoom = 100 * screenWidth / viewportWidth; body.css("transform","scale("+zoom/100 +","+ zoom/100+")"); body.css("width", currentRange.viewport); body.css("position","absolute"); body.css("transform-origin","0 0 0"); /* body.css("zoom", zoom + "%"); $.zoom = zoom; */ $.zoom = zoom; } } $.fn.removeMagic = function() { $(window).unbind('resize.' + SIGNATURE); for(var i = 0; i<ranges.length; i++){ ranges[i].query.removeListener(getCurrentRange); } watchers = ranges = []; $(".resizeMagicDebug").remove(); $(".resizeMagicStyles").remove(); $(displayClassesSelector).removeClass(displayClasses); body.css("zoom", "100%"); html.removeClass(cssClasses); }; $.fn.responsiveMagic = function( settings ) { var defaults = { debug: true //TO-DO false o true por defecto? }; options = $.extend(defaults, settings); if( !matchMedia ) return throwError(3); if( initRanges() > 0){ setStyles(); initDebug(); initWatchers(); getCurrentRange(); $(window).bind('resize.' + SIGNATURE, stretch); stretch(); } } // $(window).trigger('exitBreakpoint' + options.breakpoints[x]); //bind resize event, to update grips position //$(window).bind('resize.'+SIGNATURE, onResize); })(jQuery);
{ "content_hash": "45397aa31cfd3403f309a4921037be87", "timestamp": "", "source": "github", "line_count": 415, "max_line_length": 117, "avg_line_length": 31.92289156626506, "alnum_prop": 0.4889039855072464, "repo_name": "alvaro-prieto/responsiveMagic", "id": "ecee6e3cceee4af361600e29c05e0ffb17ddb382", "size": "13253", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/resizeMagic.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "506" }, { "name": "HTML", "bytes": "80948" }, { "name": "JavaScript", "bytes": "51200" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <serializer> <!-- This file has been generated by the EasyExtends bundle ( https://sonata-project.org/bundles/easy-extends ) @author <yourname> <youremail> --> <class name="Application\Sonata\TimelineBundle\Entity\ActionComponent" exclusion-policy="all" xml-root-name="_action_component"> <property xml-attribute-map="true" name="id" type="integer" expose="true" since-version="1.0" groups="sonata_api_read,sonata_api_write,sonata_search" /> </class> </serializer>
{ "content_hash": "e90c49cc27c2c877af9e8583265f3006", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 160, "avg_line_length": 39.142857142857146, "alnum_prop": 0.6843065693430657, "repo_name": "bardius/BardisCMS", "id": "ecc8384a0a2987698f605cb079c7b9cd1eca3f26", "size": "548", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Application/Sonata/TimelineBundle/Resources/config/serializer/Entity.ActionComponent.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "14215" }, { "name": "Batchfile", "bytes": "618" }, { "name": "CSS", "bytes": "60140" }, { "name": "HTML", "bytes": "352947" }, { "name": "JavaScript", "bytes": "53945" }, { "name": "PHP", "bytes": "824586" }, { "name": "Shell", "bytes": "21888" } ], "symlink_target": "" }
namespace blink { PaymentMethodChangeEvent::~PaymentMethodChangeEvent() = default; // static PaymentMethodChangeEvent* PaymentMethodChangeEvent::Create( ScriptState* script_state, const AtomicString& type, const PaymentMethodChangeEventInit* init) { return MakeGarbageCollected<PaymentMethodChangeEvent>(script_state, type, init); } const String& PaymentMethodChangeEvent::methodName() const { return method_name_; } const ScriptValue PaymentMethodChangeEvent::methodDetails( ScriptState* script_state) const { if (method_details_.IsEmpty()) return ScriptValue::CreateNull(script_state->GetIsolate()); return ScriptValue(script_state->GetIsolate(), method_details_.GetAcrossWorld(script_state)); } void PaymentMethodChangeEvent::Trace(Visitor* visitor) const { visitor->Trace(method_details_); PaymentRequestUpdateEvent::Trace(visitor); } PaymentMethodChangeEvent::PaymentMethodChangeEvent( ScriptState* script_state, const AtomicString& type, const PaymentMethodChangeEventInit* init) : PaymentRequestUpdateEvent(ExecutionContext::From(script_state), type, init), method_name_(init->methodName()) { if (init->hasMethodDetails()) { method_details_.Set(script_state->GetIsolate(), init->methodDetails().V8Value()); } } } // namespace blink
{ "content_hash": "e8090f38326f6cc4e81006d97c3046fd", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 75, "avg_line_length": 32.75555555555555, "alnum_prop": 0.6763907734056988, "repo_name": "ric2b/Vivaldi-browser", "id": "7e9ac72adadc4a2d06ff495fd23e47f4f8809c17", "size": "1941", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE HTML> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <title>QUnit - sap.ui.fl.PreprocessorImpl</title> <script src="../shared-config.js"></script> <script id="sap-ui-bootstrap" src="../../../../../resources/sap-ui-core.js" data-sap-ui-noconflict="true" data-sap-ui-libs="sap.ui.fl"> </script> <link rel="stylesheet" href="../../../../../resources/sap/ui/thirdparty/qunit.css" type="text/css" media="screen"/> <script src="../../../../../resources/sap/ui/thirdparty/qunit.js"></script> <script src="../../../../../resources/sap/ui/qunit/qunit-junit.js"></script> <script src="../../../../../resources/sap/ui/qunit/qunit-coverage.js"></script> <script src="../../../../../resources/sap/ui/qunit/QUnitUtils.js"></script> <script src="../../../../../resources/sap/ui/thirdparty/sinon.js"></script> <script src="../../../../../resources/sap/ui/thirdparty/sinon-qunit.js"></script> <script src="PreprocessorImpl.qunit.js"></script> </head> <body id="body" class="sapUiBody"> <h1 id="qunit-header">QUnit Page for sap.ui.fl.PreprocessorImpl</h1> <h2 id="qunit-banner"></h2> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <div id="content"></div> </body> </html>
{ "content_hash": "511d8653025e487be7df43e92eba5207", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 116, "avg_line_length": 36.55882352941177, "alnum_prop": 0.6210780370072405, "repo_name": "olirogers/openui5", "id": "111bfd448d28fe054b67414c700ef2b254e68708", "size": "1243", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/sap.ui.fl/test/sap/ui/fl/qunit/PreprocessorImpl.qunit.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3013495" }, { "name": "Gherkin", "bytes": "16431" }, { "name": "HTML", "bytes": "16645544" }, { "name": "Java", "bytes": "82129" }, { "name": "JavaScript", "bytes": "39340810" } ], "symlink_target": "" }
'use strict'; angular.module('request-duration.services', []) .factory('RequestDurationService', function ($http, $q) { return { getDurationReport: function (filter) { var deferred = $q.defer(); $http({ method: 'GET', url: _contextPath + '/request/durationReport', params: filter }).success(function (data) { deferred.resolve(data); }).error(deferred.reject); return deferred.promise; } }; });
{ "content_hash": "c85c685fdc9ab6a24965222b6259b3e6", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 66, "avg_line_length": 30.2, "alnum_prop": 0.46192052980132453, "repo_name": "alexey-chumakov/performance-analytics", "id": "26673406a12b756ce512c17204be3a8078efe4d9", "size": "604", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/src/main/webapp/js/angular/duration/services.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "114048" }, { "name": "HTML", "bytes": "12406" }, { "name": "Java", "bytes": "121063" }, { "name": "JavaScript", "bytes": "241003" } ], "symlink_target": "" }
/** * */ package com.jolbox.bonecp; import static org.junit.Assert.*; import org.junit.Test; /** * @author Wallace * */ public class TestReplayLog { /** * Test method for {@link com.jolbox.bonecp.ReplayLog#ReplayLog(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])}. */ @Test public void testAllGettersAndSetters() { ReplayLog testClass = new ReplayLog(new Object(), this.getClass().getMethods()[0], new Object[]{String.class}); Object[] args = new Object[]{Integer.class}; testClass.setArgs(args); assertTrue(args == testClass.getArgs()); testClass.setMethod(this.getClass().getMethods()[0]); assertEquals(this.getClass().getMethods()[0], testClass.getMethod()); Object obj = new Object(); testClass.setTarget(obj); assertEquals(obj, testClass.getTarget()); testClass.toString(); testClass.setArgs(null); testClass.setTarget(null); testClass.setMethod(null); testClass.toString(); } }
{ "content_hash": "8ea4712487da64884b6fc75b09837f9a", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 130, "avg_line_length": 22.833333333333332, "alnum_prop": 0.6955161626694474, "repo_name": "squidsolutions/bonecp", "id": "99ffc7d882389782780f954f6132f6bb033cb81b", "size": "1584", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "bonecp/src/test/java/com/jolbox/bonecp/TestReplayLog.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "980893" } ], "symlink_target": "" }
namespace blink { void SVGImagePainter::paint(const PaintInfo& paintInfo) { ANNOTATE_GRAPHICS_CONTEXT(paintInfo, &m_renderSVGImage); if (paintInfo.phase != PaintPhaseForeground || m_renderSVGImage.style()->visibility() == HIDDEN || !m_renderSVGImage.imageResource()->hasImage()) return; FloatRect boundingBox = m_renderSVGImage.paintInvalidationRectInLocalCoordinates(); PaintInfo paintInfoBeforeFiltering(paintInfo); TransformRecorder transformRecorder(*paintInfoBeforeFiltering.context, m_renderSVGImage, m_renderSVGImage.localToParentTransform()); { SVGPaintContext paintContext(m_renderSVGImage, paintInfoBeforeFiltering); if (paintContext.applyClipMaskAndFilterIfNecessary()) { LayoutObjectDrawingRecorder recorder(*paintContext.paintInfo().context, m_renderSVGImage, paintContext.paintInfo().phase, boundingBox); if (!recorder.canUseCachedDrawing()) { if (m_renderSVGImage.style()->svgStyle().bufferedRendering() != BR_STATIC) { paintForeground(paintContext.paintInfo()); } else { RefPtr<const SkPicture>& bufferedForeground = m_renderSVGImage.bufferedForeground(); if (!bufferedForeground) { paintContext.paintInfo().context->beginRecording(m_renderSVGImage.objectBoundingBox()); paintForeground(paintContext.paintInfo()); bufferedForeground = paintContext.paintInfo().context->endRecording(); } paintContext.paintInfo().context->drawPicture(bufferedForeground.get()); } } } } if (m_renderSVGImage.style()->outlineWidth()) { LayoutRect layoutBoundingBox(boundingBox); ObjectPainter(m_renderSVGImage).paintOutline(paintInfoBeforeFiltering, layoutBoundingBox, layoutBoundingBox); } } void SVGImagePainter::paintForeground(const PaintInfo& paintInfo) { RefPtr<Image> image = m_renderSVGImage.imageResource()->image(); FloatRect destRect = m_renderSVGImage.objectBoundingBox(); FloatRect srcRect(0, 0, image->width(), image->height()); SVGImageElement* imageElement = toSVGImageElement(m_renderSVGImage.element()); imageElement->preserveAspectRatio()->currentValue()->transformRect(destRect, srcRect); InterpolationQuality interpolationQuality = InterpolationDefault; if (m_renderSVGImage.style()->svgStyle().bufferedRendering() != BR_STATIC) interpolationQuality = ImageQualityController::imageQualityController()->chooseInterpolationQuality(paintInfo.context, &m_renderSVGImage, image.get(), image.get(), LayoutSize(destRect.size())); InterpolationQuality previousInterpolationQuality = paintInfo.context->imageInterpolationQuality(); paintInfo.context->setImageInterpolationQuality(interpolationQuality); paintInfo.context->drawImage(image.get(), destRect, srcRect, SkXfermode::kSrcOver_Mode); paintInfo.context->setImageInterpolationQuality(previousInterpolationQuality); } } // namespace blink
{ "content_hash": "6f0b48578e206b7e968d38c8d9f25534", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 201, "avg_line_length": 50.33870967741935, "alnum_prop": 0.7081063761614868, "repo_name": "kurli/blink-crosswalk", "id": "719a75b27521a5f8aa2488539e37f43cb00e875d", "size": "3926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/core/paint/SVGImagePainter.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "1835" }, { "name": "Assembly", "bytes": "14768" }, { "name": "Batchfile", "bytes": "35" }, { "name": "Bison", "bytes": "64588" }, { "name": "C", "bytes": "124323" }, { "name": "C++", "bytes": "44371388" }, { "name": "CSS", "bytes": "565212" }, { "name": "CoffeeScript", "bytes": "163" }, { "name": "GLSL", "bytes": "11578" }, { "name": "Groff", "bytes": "28067" }, { "name": "HTML", "bytes": "58015328" }, { "name": "Java", "bytes": "109391" }, { "name": "JavaScript", "bytes": "24469331" }, { "name": "Objective-C", "bytes": "47687" }, { "name": "Objective-C++", "bytes": "301733" }, { "name": "PHP", "bytes": "184068" }, { "name": "Perl", "bytes": "585293" }, { "name": "Python", "bytes": "3817314" }, { "name": "Ruby", "bytes": "141818" }, { "name": "Shell", "bytes": "10037" }, { "name": "XSLT", "bytes": "49926" } ], "symlink_target": "" }
package org.apache.ambari.server.orm.entities; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Id; @SuppressWarnings("serial") public class ServiceDesiredStateEntityPK implements Serializable { private Long clusterId; @javax.persistence.Column(name = "cluster_id", nullable = false, insertable = true, updatable = true, length = 10) @Id public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } private String serviceName; @Id @Column(name = "service_name", nullable = false, insertable = true, updatable = true, length = 32672, precision = 0) public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ServiceDesiredStateEntityPK that = (ServiceDesiredStateEntityPK) o; if (clusterId != null ? !clusterId.equals(that.clusterId) : that.clusterId != null) return false; if (serviceName != null ? !serviceName.equals(that.serviceName) : that.serviceName != null) return false; return true; } @Override public int hashCode() { int result = clusterId != null ? clusterId.intValue() : 0; result = 31 * result + (serviceName != null ? serviceName.hashCode() : 0); return result; } }
{ "content_hash": "90835e47e307b9bd71083ebabb84290a", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 118, "avg_line_length": 27.21818181818182, "alnum_prop": 0.698062792251169, "repo_name": "arenadata/ambari", "id": "3fa5289a2409793f71ec9f4564a77f5f8e8f57db", "size": "2302", "binary": false, "copies": "4", "ref": "refs/heads/branch-adh-1.6", "path": "ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ServiceDesiredStateEntityPK.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "46700" }, { "name": "C", "bytes": "331204" }, { "name": "C#", "bytes": "215907" }, { "name": "C++", "bytes": "257" }, { "name": "CSS", "bytes": "343739" }, { "name": "CoffeeScript", "bytes": "8465" }, { "name": "Dockerfile", "bytes": "6387" }, { "name": "EJS", "bytes": "777" }, { "name": "FreeMarker", "bytes": "2654" }, { "name": "Gherkin", "bytes": "990" }, { "name": "Groovy", "bytes": "15882" }, { "name": "HTML", "bytes": "717983" }, { "name": "Handlebars", "bytes": "1819641" }, { "name": "Java", "bytes": "29172298" }, { "name": "JavaScript", "bytes": "18571926" }, { "name": "Jinja", "bytes": "1490416" }, { "name": "Less", "bytes": "412933" }, { "name": "Makefile", "bytes": "11111" }, { "name": "PHP", "bytes": "149648" }, { "name": "PLpgSQL", "bytes": "287501" }, { "name": "PowerShell", "bytes": "2090340" }, { "name": "Python", "bytes": "18507704" }, { "name": "R", "bytes": "3943" }, { "name": "Ruby", "bytes": "38590" }, { "name": "SCSS", "bytes": "40072" }, { "name": "Shell", "bytes": "924115" }, { "name": "Stylus", "bytes": "820" }, { "name": "TSQL", "bytes": "42351" }, { "name": "Vim script", "bytes": "5813" }, { "name": "sed", "bytes": "2303" } ], "symlink_target": "" }
<?php interface Mob_Construccion_Interface { public function getByUsuario($idUsuario); public function processQueue($v, $timestampEnviado); public function getCostoConstruccion($v); public function sendMessageNoRecursos($v, $timestampEnviado); public function getTipoCola(); public function procesarNuevaConstruccion($idEdificio, $lastFinalizacion); }
{ "content_hash": "54409717dff986d06005d64857eb3561", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 78, "avg_line_length": 34.18181818181818, "alnum_prop": 0.773936170212766, "repo_name": "rodsouto/vendetta-plus-legacy", "id": "150d318ae177adba1c8da202abae356ab542cd77", "size": "376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/Mob/Construccion/Interface.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13236" }, { "name": "JavaScript", "bytes": "39794" }, { "name": "PHP", "bytes": "15195431" } ], "symlink_target": "" }
license: > Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- # endcallbutton This event fires when the user presses the end call button. document.addEventListener("endcallbutton", yourCallbackFunction, false); ## Details The event overrides the default end call behavior. Applications typically should use `document.addEventListener` to attach an event listener once the `deviceready` event fires. ## Supported Platforms - BlackBerry WebWorks (OS 5.0 and higher) ## Quick Example document.addEventListener("endcallbutton", onEndCallKeyDown, false); function onEndCallKeyDown() { // Handle the end call button } ## Full Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>End Call Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("endcallbutton", onEndCallKeyDown, false); } // Handle the end call button // function onEndCallKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>
{ "content_hash": "f2865f60bd61a0df2f4d7a1d8e4dd84c", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 81, "avg_line_length": 30.03846153846154, "alnum_prop": 0.6641058472044388, "repo_name": "drbeermann/cordova-docs", "id": "66253db499bd9ff16ee4ee4e720b3e053f784adb", "size": "2347", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "docs/en/3.1.0/cordova/events/events.endcallbutton.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5116" }, { "name": "CSS", "bytes": "11129" }, { "name": "HTML", "bytes": "113105" }, { "name": "JavaScript", "bytes": "69082" } ], "symlink_target": "" }
@class NewsBlurAppDelegate; @interface AddSiteViewController : UIViewController <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, ASIHTTPRequestDelegate> - (void)reload; - (IBAction)addSite; - (void)autocompleteSite:(ASIHTTPRequest *)request; - (IBAction)doCancelButton; - (IBAction)doAddButton; - (NSString *)extractParentFolder; - (IBAction)checkSiteAddress; - (void)reloadSearchResults; - (IBAction)toggleAddFolder:(id)sender; - (NSArray *)folders; @property (nonatomic) IBOutlet NewsBlurAppDelegate *appDelegate; @property (nonatomic) IBOutlet UITextField *inFolderInput; @property (nonatomic) IBOutlet UITextField *addFolderInput; @property (nonatomic) IBOutlet UITextField *siteAddressInput; @property (nonatomic) IBOutlet UIBarButtonItem *addButton; @property (nonatomic) IBOutlet UIBarButtonItem *cancelButton; @property (nonatomic) IBOutlet UITableView *siteTable; @property (nonatomic) IBOutlet UIScrollView *siteScrollView; @property (nonatomic) IBOutlet UIButton *addFolderButton; @property (nonatomic) NSMutableData * jsonString; @property (nonatomic) NSMutableArray *autocompleteResults; @property (nonatomic) IBOutlet UINavigationBar *navBar; @property (nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator; @property (nonatomic) IBOutlet UIActivityIndicatorView *siteActivityIndicator; @property (nonatomic) IBOutlet UILabel *addingLabel; @property (nonatomic) IBOutlet UILabel *errorLabel; @end
{ "content_hash": "dd4ecd28e43a9053af4b5a9854443ff3", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 89, "avg_line_length": 40.138888888888886, "alnum_prop": 0.8207612456747405, "repo_name": "nriley/NewsBlur", "id": "2b94594636d5540a7358a736111c909c438677c6", "size": "1672", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "clients/ios/Classes/AddSiteViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "700037" }, { "name": "CoffeeScript", "bytes": "6755" }, { "name": "HTML", "bytes": "425011" }, { "name": "Java", "bytes": "742814" }, { "name": "JavaScript", "bytes": "1599307" }, { "name": "Nginx", "bytes": "897" }, { "name": "Objective-C", "bytes": "2692787" }, { "name": "Perl", "bytes": "55598" }, { "name": "Python", "bytes": "2484759" }, { "name": "R", "bytes": "527" }, { "name": "Ruby", "bytes": "870" }, { "name": "Shell", "bytes": "39936" } ], "symlink_target": "" }
from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/space/debris/shared_death_star_debris_f.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
{ "content_hash": "7f0a652702aa367a26aba6da9d319e7c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 78, "avg_line_length": 23.615384615384617, "alnum_prop": 0.6905537459283387, "repo_name": "obi-two/Rebelion", "id": "3262df0347889b464ed89f940627950e22998d6b", "size": "452", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "data/scripts/templates/object/static/space/debris/shared_death_star_debris_f.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "11818" }, { "name": "C", "bytes": "7699" }, { "name": "C++", "bytes": "2293610" }, { "name": "CMake", "bytes": "39727" }, { "name": "PLSQL", "bytes": "42065" }, { "name": "Python", "bytes": "7499185" }, { "name": "SQLPL", "bytes": "41864" } ], "symlink_target": "" }
package org.mifos.platform.questionnaire.service; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class QuestionGroupInstanceDetail implements Serializable { private static final long serialVersionUID = -7157295411344619153L; private QuestionGroupDetail questionGroupDetail; private Date dateCompleted; private Integer id; public String getQuestionGroupTitle() { return questionGroupDetail.getTitle(); } public QuestionGroupDetail getQuestionGroupDetail() { return questionGroupDetail; } public void setQuestionGroupDetail(QuestionGroupDetail questionGroupDetail) { this.questionGroupDetail = questionGroupDetail; } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="EI_EXPOSE_REP", justification="Date is mutable, but can't help method returning date.") public Date getDateCompleted() { return dateCompleted; } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="EI_EXPOSE_REP2", justification="Date is mutable, but needs initialization.") public void setDateCompleted(Date dateCompleted) { this.dateCompleted = dateCompleted; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDateCompletedAsString() { return new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(dateCompleted); } }
{ "content_hash": "3af471fcd04702fd421ddb0732aad534", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 148, "avg_line_length": 29.92, "alnum_prop": 0.7292780748663101, "repo_name": "jpodeszwik/mifos", "id": "94ae9795e7c0e419509bd987bff42f7a7aa00db5", "size": "2269", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "serviceInterfaces/src/main/java/org/mifos/platform/questionnaire/service/QuestionGroupInstanceDetail.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18421947" }, { "name": "JavaScript", "bytes": "809427" }, { "name": "Python", "bytes": "37612" }, { "name": "Shell", "bytes": "74390" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title></title> <link rel="Stylesheet" href="css/analysis.css" /> <script type="text/javascript"> function init() { if (window.location.hash) { var parentDiv, nodes, i, helpInfo, helpId, helpInfoArr, helpEnvFilter, envContent, hideEnvClass, hideNodes; helpInfo = window.location.hash.substring(1); if(helpInfo.indexOf("-")) { helpInfoArr = helpInfo.split("-"); helpId = helpInfoArr[0]; helpEnvFilter = helpInfoArr[1]; } else { helpId = helpInfo; } parentDiv = document.getElementById("topics"); nodes = parentDiv.children; hideEnvClass = (helpEnvFilter === "OnlineOnly"? "PortalOnly": "OnlineOnly"); if(document.getElementsByClassName) { hideNodes = document.getElementsByClassName(hideEnvClass); } else { hideNodes = document.querySelectorAll(hideEnvClass); } for(i=0; i < nodes.length; i++) { if(nodes[i].id !== helpId) { nodes[i].style.display ="none"; } } for(i=0; i < hideNodes.length; i++) { hideNodes[i].style.display ="none"; } } } </script> </head> <body onload="init()"> <div id="topics"> <div id="toolDescription" class="largesize"> <h2>Connect Origins to Destinations</h2><p/> <h2><img src="./images/GUID-7266D30B-0250-4132-B1A5-9B59F0212FAD-web.png" alt="Connect Origins to Destinations"></h2> <hr/> <p> Connect Origins to Destinations measures the travel time or distance between pairs of points. The tool can report straight-line distances; distances based on a travel mode, such as walking or driving; or trip durations based on a travel mode. Using this tool, you can do the following: </p> <p> <ul> <li>Calculate the total distance or time commuters travel on their home-to-work trips. </li> <li>Measure how far customers are traveling to shop at your stores. Use this information to define your market reach, especially when targeting advertising campaigns or choosing new store locations. </li> <li>Calculate the expected trip mileage for your fleet of vehicles. Afterward, run the Summarize Within tool to report mileage by state or other region. </li> </ul> </p> <p>You provide starting and ending points, and the tool returns a layer containing route lines, including measurements, between the paired origins and destinations. </p> <p>If <b>Use current map extent</b> is checked, only the features that are visible within the current map extent will be considered in the analysis. If unchecked, all features in the input layer will be considered, even if they are outside the current map extent. </p> </div> <!--Parameter divs for each param--> <div id="originsLayer"> <div><h2>Choose point layer representing the origin locations</h2></div> <hr/> <div> <p>Choose the point layer representing the origin or origins. The tool supports up to 5,000 origins and 5,000 destinations. </p> <p>If you choose a layer that has exactly one origin, it will connect to all destinations. </p> <p class="OnlineOnly">In addition to choosing a layer from your map, you can select <b>Choose Living Atlas Analysis Layer</b> or <b>Choose Analysis Layer</b> found at the bottom of the drop-down list. This opens a gallery containing a collection of layers useful for many analyses. </p> </div> </div> <div id="destinationsLayer"> <div><h2>Choose the destinations layer</h2></div> <hr/> <div> <p>Choose the layer representing the destination or destinations to which the origins should connect. The tool supports up to 5,000 origins and 5,000 destinations. </p> <p>If you choose a layer that has exactly one destination, all the origins will connect to that destination. </p> <p>If there is one origin and many destinations, the tool connects the origin to each of the destinations. </p> <p class="OnlineOnly">In addition to choosing a layer from your map, you can select <b>Choose Living Atlas Analysis Layer</b> or <b>Choose Analysis Layer</b> found at the bottom of the drop-down list. This opens a gallery containing a collection of layers useful for many analyses. </p> <p> If there are many origins and many destinations, you need to have two fields that describe the origin-destination pairs: <b>ID field in origins</b> and <b>Matching ID field in destinations</b>. The tool connects the origin-destination pairs during the analysis. For instance, imagine you have two origins with ID field values of <code>Rosie</code> and <code>Harold</code> and two destinations with the same ID values. The <code>Rosie</code> origin will connect to the <code>Rosie</code> destination, and <code>Harold</code> will connect to <code>Harold</code>. No other connections or measurements are made. </p> <p>The ID values must be unique within each layer; for instance, the destinations layer cannot have two <code>Rosie</code> values. The values in the origin and destination layers must match exactly to make pairs; <code>Harold</code> won't connect to the misspelled value, <code>Harodl</code>. </p> </div> </div> <div id="measurementType"> <div><h2>Measure</h2></div> <hr/> <div> <p>Choose whether to connect origins to destinations using straight-line distance or a travel mode. The output routes will follow roads or walkways and honor applicable rules, such as one-way streets and illegal turns for driving or trucking. The available travel modes are determined by the administrator of your organization. </p> <p>When you choose <b>Driving time</b>, you have options on how to measure the drive time. <ul> <li> <p>Uncheck <b>Use Traffic</b> to find the quickest routes based on fixed speeds. </p> <p>This is the option to choose if you want a general drive-time measurement, not one that is calculated using changing traffic conditions for a specific departure time. </p> </li> <li> <p>Check <b>Use Traffic</b> to find the quickest routes based on a given start time and changing traffic conditions. By also choosing the <b>Live traffic</b> option, the departure time from the origins is set to the current time, and current and predicted traffic speeds are referenced from sensors and feeds to create the routes. The predicted traffic speeds are calculated by referencing live traffic speeds, historical speeds, and current events such as weather. Traffic speeds are predicted 12 hours into the future, so you can move the slider to set the departure time ahead by up to 12 hours. </p> <p>Use these live-traffic settings to find the drive times for departing now, departing in one hour from now, and so on. </p> </li> <li> <p>By checking <b>Use Traffic</b> and choosing <b>Traffic based on typical conditions for</b> a day and time, the tool finds the quickest routes based on historical speed averages for every five-minute interval across a routine week. The results include traffic but remove the influence of current traffic conditions and events, which may vary significantly from the norm. </p> <p>You can use these historical traffic settings to ask, for instance, &quot;How long would it generally take to reach these destinations when departing at 11:30 a.m. on a Wednesday?&quot; </p> <p>The time you set refers to the time zone in which your origins are located. So if you set the time to 8:00 a.m. and have two origins, one in New York City and another in Los Angeles, the routes will be generated for a departure time of 8:00 a.m. Eastern Time and 8:00 a.m. Pacific Time, respectively. </p> </li> </ul> </p> <p>Note that as a vehicle drives away from the origin, time elapses and traffic conditions change. The Connect Origins to Destinations tool accounts for these variations when you check <b>Use traffic</b>; however, not all regions support traffic. Click the <b>See availability</b> link on the tool to find out whether it is offered in your study area. </p> </div> </div> <div id="outputLayer"> <div><h2>Result layer name</h2></div> <hr/> <div> <p>This is the name of the layer that will be created in <b>My Content</b> and added to the map. The default name is based on the tool name and the input layer name. If the layer already exists, you will be asked to provide another name. </p> <p>Using the <b>Save result in</b> drop-down box, you can specify the name of a folder in <b>My Content</b> where the result will be saved. </p> </div> </div> </div> </html>
{ "content_hash": "87fd253cb62a28cdceb1aa6d4ee500d9", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 629, "avg_line_length": 70.20422535211267, "alnum_prop": 0.6200220684120774, "repo_name": "darklilium/Factigis_2", "id": "350ca6713235656364f0d095b3017020a9b1c20f", "size": "9969", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "arcgis_js_api/library/3.17/3.17compact/esri/dijit/analysis/help/ConnectOriginsToDestinations.html", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "39908" }, { "name": "Batchfile", "bytes": "3178" }, { "name": "CSS", "bytes": "1885995" }, { "name": "HTML", "bytes": "21011190" }, { "name": "JavaScript", "bytes": "1065201" }, { "name": "PHP", "bytes": "76208" }, { "name": "Ruby", "bytes": "1264" }, { "name": "Shell", "bytes": "2052" }, { "name": "XSLT", "bytes": "94766" } ], "symlink_target": "" }
module HsLayoutPre(layoutPre,PosToken) where import HsTokens import HsLexerPos {-+ This is an implementation of Haskell layout, as specified in section 9.3 of the revised Haskell 98 report. This module contains the layout preprocessor that inserts the extra &lt;n&gt; and {n} tokens. -} type PosToken = (Token,(Pos,String)) layoutPre :: [PosToken] -> [PosToken] layoutPre = indent . open open = open1 {-+ If the first lexeme of a module is not { or module, then it is preceded by {n} where n is the indentation of the lexeme. -} open1 (t1@(Reservedid,(_,"module")):ts) = t1:open2 ts open1 (t1@(Special,(_,"{")):ts) = t1:open2 ts open1 ts@((t,(p,s)):_) = (Open (column p),(p,"")):open2 ts open1 [] = [] {-+ If a let, where, do, or of keyword is not followed by the lexeme {, the token {n} is inserted after the keyword, where n is the indentation of the next lexeme if there is one, or 0 if the end of file has been reached. -} open2 (t1:ts1) | isLtoken t1 = case ts1 of t2@(_,(p,_)):ts2 -> if notLBrace t2 then t1:(Open (column p),(p,"")):open2 ts1 else t1:t2:open2 ts2 [] -> t1:(Open 0,(fst (snd t1),"")):[] where isLtoken (Reservedid,(_,s)) = s `elem` ["let","where","do","of"] isLtoken _ = False notLBrace (Special,(_,"{")) = False notLBrace _ = True open2 (t:ts) = t:open2 ts open2 [] = [] {-+ (This is from the original Haskell 98 report.) The first token on each line (not including tokens already annotated) is preceeded by &lt;n&gt;, where n is the indentation of the token. -} indent (t1@(Open _,(p,_)):ts) = t1:indent2 (line p) ts indent (t1@(t,(p,s)):ts) = (Indent (column p),(p,"")):t1:indent2 (line p) ts indent [] = [] indent2 r (t1@(_,(p,_)):ts) | line p==r = t1:indent2 r ts indent2 r ts = indent ts
{ "content_hash": "d83f4c19c3a440bd1ed4a6d24b540c64", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 79, "avg_line_length": 30.081967213114755, "alnum_prop": 0.6201634877384197, "repo_name": "forste/haReFork", "id": "a272cdba4d526906d3584d67e0d868c0391d38a0", "size": "1835", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "tools/base/parse2/Lexer/HsLayoutPre.hs", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Emacs Lisp", "bytes": "57707" }, { "name": "Haskell", "bytes": "1694821" }, { "name": "VimL", "bytes": "35788" } ], "symlink_target": "" }
/** * Adds an icon to the ribbon bar on a classic page. * @param props The ribbon link information. */ export const RibbonLink: (props: ILinkInfo) => PromiseLike<HTMLAnchorElement>; /** * Adds an icon to the suite bar on a classic page. * If SharePoint Online is detected, then the icon will be rendered in the ribbon bar. */ export const SuiteBarLink: (props: ILinkInfo) => PromiseLike<HTMLAnchorElement>; /** * Link Information */ export interface ILinkInfo { /** True to append the link at the end of the list. */ appendFl?: boolean; /** The link class name */ className?: string; /** The link url */ href?: string; /** The link id */ id: string; /** The link click event */ onClick?: (ev?: MouseEvent) => void; /** The link title */ title: string; } /** * Ribbon Link */ export interface IRibbonLink { (props: ILinkInfo): PromiseLike<HTMLAnchorElement>; } /** * Suitebar Link */ export interface ISuiteBarLink { (props: ILinkInfo): PromiseLike<HTMLAnchorElement>; }
{ "content_hash": "2489edb0ad44d99c5f8182c0cf1f58bf", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 86, "avg_line_length": 21.75, "alnum_prop": 0.6561302681992337, "repo_name": "gunjandatta/sprest", "id": "9bc663788c945280f85477c449b9abd393173580", "size": "1044", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "@types/helper/linkInfo.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "2349" }, { "name": "HTML", "bytes": "2955" }, { "name": "JavaScript", "bytes": "33476" }, { "name": "TypeScript", "bytes": "652328" } ], "symlink_target": "" }
* Konzeptionsfehler * ursprünglich kooperativer Ansatz Ende der 60er Jahre * unvorhersehbare Entwicklung, insbesondere durch Kommerzialisierung * Programmierfehler * oft ungeprüfte Eingabe(puffer) * Stack-Overflow / Manipulation des Programmzeigers * Konfigurationsfehler (z.B. auf Webserver) * Falsche Berechtigungsvergabe auf Ebene des Filesystems * Unbedachte Owner von Serverprozessen (zu hohe Privilegien) * Systemanomalien * Einnisten/Verstecken von Malware jeglicher Art ## Was für Angrifssarten gibt es? * Passive Angriffe * Lauschen * Analyse des Datenverkehrs * sehr schwierig zu entecken * Aktive Angriffe * Verändern, Ergänzen oder Löschen von Daten * Spoofing Angriffe * Degradation-of-service oder denial-of-service attack ## Was gibt es für Zeritifikatsklassen? * Class 1 Certificates (wenig Sicherheit) * Keine Überprüfung der Identität des Antragsstellers * es wird nur der im Zerifikat eingetragee Namen überprüft * werden oft vollständig über das Internet beantragt * Class 2 Certificates (mittlere Sicherheit) * Überprüfung der Identität des Antragsstellers mithilfe von Dokumenten * Für Private: Kopie von Pass oder Identitätskarte * Für Firmen: Unterschrift & Handelsregistereintrag * Class 3 Certificates (hohe Sicherheit) * Überprüfung der Identität durch persönliches Vorsprechen * Überprüfen durch Vorweisen eines amtlichen Dokuments * Weitere Prüfungen * Qualified Certificates (höchste Sicherheit) * Analog Klasse 3 * Zusätzlich steht CA unter stattlicher Kontrolle
{ "content_hash": "63255a4435248df903af607edc6f364f", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 75, "avg_line_length": 40.84615384615385, "alnum_prop": 0.7702448210922788, "repo_name": "chefe/summaries", "id": "d15485d0bd51b0f06bd09c0813988cdc2156a4e0", "size": "1661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "isf/06-Bedrohungen.md", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1888" }, { "name": "TeX", "bytes": "1974" } ], "symlink_target": "" }
from __future__ import unicode_literals, print_function, division, absolute_import from pprint import pprint import threading import string import logging import multiprocessing from six.moves import queue import six import errors import settings import taskq import webservice import notifier logger = logging.getLogger(__name__) class Worker(threading.Thread): """ Thread executing tasks from a given tasks queue """ def __init__(self, tasks, *args, **kwargs): daemon = kwargs.pop('daemon', False) threading.Thread.__init__(self, *args, **kwargs) self.daemon = daemon self.tasks = tasks self.stop_flag = threading.Event() self.start() def run(self): while not self.stop_flag.is_set(): try: task = self.tasks.get(block=True, timeout=10) except queue.Empty: pass func, args, kwargs = task['func'], task['args'], task['kwargs'] options = task.get('options', {}) if 'name' in options: self.name = options['name'] try: func(*args, **kwargs) except Exception as e: # An exception happened in this thread logger.exception(e) finally: # Mark this task as done, whether an exception happened or not self.tasks.task_done() logger.debug('thread was flagged to stop') class ThreadPool(object): """ Pool of threads consuming tasks from a queue """ def __init__(self, max_threads): self.max_threads = max_threads self.tasks = queue.Queue(maxsize=max_threads) self.pool = [] for i in range(min(self.tasks.qsize(), max_threads)): worker = Worker(self.tasks, name='worker{}'.format(i+1)) self.pool.append(worker) def add_task(self, func_signature, **options): """ Add a task to the queue """ func, args, kwargs = func_signature['func'], func_signature['args'], func_signature['kwargs'] # worker threads should be daemonic, so that they exit when the main program exits, and there be no need for joining. daemon = options.pop('daemon', True) self.tasks.put({'func': func, 'args': args, 'kwargs': kwargs, 'options': options}) if self.tasks.qsize() > 0 and len(self.pool) < self.max_threads: worker = Worker(self.tasks, daemon=daemon, name='worker{}'.format(len(self.pool)+1)) self.pool.append(worker) def map(self, func, args_list): """ Add a list of tasks to the queue """ for args in args_list: self.add_task(func, args) def stop(self): for trd in self.pool: trd.stop_flag.set() trd.join() def wait_completion(self): """ Wait for completion of all the tasks in the queue """ self.tasks.join() class WebServiceThread(threading.Thread): def __init__(self, *args, **kwargs): self.qs = kwargs.pop('qs') self.daemon = True threading.Thread.__init__(self, *args, **kwargs) def run(self, *args, **kwargs): logger.info('webservice thread started') try: srv = webservice.Service(qs=self.qs) srv.run(*args, **kwargs) except errors.PontiacError as e: print('Pontiac Error. type: "{}", {}'.format(type(e), e)) logger.info('webservice thread finished') def webservice_func(*args, **kwargs): logger.info('webservice thread started') try: srv = webservice.Service(qs=kwargs.pop('qs')) srv.run(*args, **kwargs) except errors.PontiacError as e: print('Pontiac Error. type: "{}", {}'.format(type(e), e)) logger.info('webservice thread finished') class NotifierThread(threading.Thread): def __init__(self, *args, **kwargs): self.queue = kwargs.pop('queue') threading.Thread.__init__(self, *args, **kwargs) def run(self, *args, **kwargs): logger.info('notifier thread started') try: notifr = notifier.Notifier() while True: msg = self.queue.get() logger.debug('received a new message on notification queue: "{}"'.format(msg)) try: notifr.notify(msg=msg) except errors.DataValidationError as e: print('Data Validation Error: {}'.format(e)) except errors.PontiacError as e: print('Pontiac Error. type: "{}", {}'.format(type(e), e)) logger.info('notifier thread finished') def notifier_func(*args, **kwargs): logger.info('notifier thread started') try: notifr = notifier.Notifier() while True: msg = kwargs['queue'].get() logger.debug('received a new message on notification queue: "{}"'.format(msg)) try: notifr.notify(msg=msg) except errors.DataValidationError as e: print('Data Validation Error: {}'.format(e)) except errors.PontiacError as e: print('Pontiac Error. type: "{}", {}'.format(type(e), e)) logger.info('notifier thread finished') def run_multi_thread(args): """Run two threads for notification receiver (webservice) and notification processor (notifier) """ logger.info('running in multi-thread mode') if args.queuer == 'queue': q_class = taskq.MemoryQueue elif args.queuer == 'redis': q_class = taskq.RedisQueue else: raise NotImplementedError() qs = { 'notif': q_class(key='notif'), } pool = ThreadPool(max_threads=sum(settings.THREAD_COUNT.values())) logger.info('creating {} webservice threads'.format(settings.THREAD_COUNT['WEBSERVICE'])) pool.add_task({'func': webservice_func, 'args': (), 'kwargs': {'qs': qs}}, name='webservice', daemon=True) logger.info('creating {} notification threads'.format(settings.THREAD_COUNT['NOTIFICATION'])) for i in range(settings.THREAD_COUNT['NOTIFICATION']): pool.add_task({'func': notifier_func, 'args': (), 'kwargs': {'queue': qs['notif']}}, name='notifier{}'.format(i), daemon=True) pool.wait_completion() pool.stop()
{ "content_hash": "ea3ac577c4e3cc5c922853709db76a92", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 134, "avg_line_length": 35.93103448275862, "alnum_prop": 0.5937300063979527, "repo_name": "bisphon/pontiac", "id": "eacb80d63cd06412fcb44e898d63aec359b568a2", "size": "6252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "threaded.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "607" }, { "name": "Python", "bytes": "45165" } ], "symlink_target": "" }
#include "mem/ruby/network/garnet/fixed-pipeline/Router_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/GarnetNetwork_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/NetworkLink_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/CreditLink_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/InputUnit_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/OutputUnit_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/RoutingUnit_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/VCallocator_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/SWallocator_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/Switch_d.hh" using namespace std; Router_d::Router_d(int id, GarnetNetwork_d *network_ptr) { m_id = id; m_network_ptr = network_ptr; m_virtual_networks = network_ptr->getNumberOfVirtualNetworks(); m_vc_per_vnet = m_network_ptr->getVCsPerClass(); m_num_vcs = m_virtual_networks*m_vc_per_vnet; m_flit_width = m_network_ptr->getFlitSize(); m_routing_unit = new RoutingUnit_d(this); m_vc_alloc = new VCallocator_d(this); m_sw_alloc = new SWallocator_d(this); m_switch = new Switch_d(this); m_input_unit.clear(); m_output_unit.clear(); buf_read_count = 0; buf_write_count = 0; crossbar_count = 0; vc_local_arbit_count = 0; vc_global_arbit_count = 0; sw_local_arbit_count = 0; sw_global_arbit_count = 0; } Router_d::~Router_d() { m_input_unit.deletePointers(); m_output_unit.deletePointers(); delete m_routing_unit; delete m_vc_alloc; delete m_sw_alloc; delete m_switch; } void Router_d::init() { m_vc_alloc->init(); m_sw_alloc->init(); m_switch->init(); } void Router_d::addInPort(NetworkLink_d *in_link, CreditLink_d *credit_link) { int port_num = m_input_unit.size(); InputUnit_d *input_unit = new InputUnit_d(port_num, this); input_unit->set_in_link(in_link); input_unit->set_credit_link(credit_link); in_link->setLinkConsumer(input_unit); credit_link->setSourceQueue(input_unit->getCreditQueue()); m_input_unit.insertAtBottom(input_unit); } void Router_d::addOutPort(NetworkLink_d *out_link, const NetDest& routing_table_entry, int link_weight, CreditLink_d *credit_link) { int port_num = m_output_unit.size(); OutputUnit_d *output_unit = new OutputUnit_d(port_num, this); output_unit->set_out_link(out_link); output_unit->set_credit_link(credit_link); credit_link->setLinkConsumer(output_unit); out_link->setSourceQueue(output_unit->getOutQueue()); m_output_unit.insertAtBottom(output_unit); m_routing_unit->addRoute(routing_table_entry); m_routing_unit->addWeight(link_weight); } void Router_d::route_req(flit_d *t_flit, InputUnit_d *in_unit, int invc) { m_routing_unit->RC_stage(t_flit, in_unit, invc); } void Router_d::vcarb_req() { g_eventQueue_ptr->scheduleEvent(m_vc_alloc, 1); } void Router_d::swarb_req() { g_eventQueue_ptr->scheduleEvent(m_sw_alloc, 1); } void Router_d::update_incredit(int in_port, int in_vc, int credit) { m_input_unit[in_port]->update_credit(in_vc, credit); } void Router_d::update_sw_winner(int inport, flit_d *t_flit) { m_switch->update_sw_winner(inport, t_flit); g_eventQueue_ptr->scheduleEvent(m_switch, 1); } void Router_d::calculate_performance_numbers() { for(int i = 0; i < m_input_unit.size(); i++) { buf_read_count += m_input_unit[i]->get_buf_read_count(); buf_write_count += m_input_unit[i]->get_buf_write_count(); } crossbar_count = m_switch->get_crossbar_count(); vc_local_arbit_count = m_vc_alloc->get_local_arbit_count(); vc_global_arbit_count = m_vc_alloc->get_global_arbit_count(); sw_local_arbit_count = m_sw_alloc->get_local_arbit_count(); sw_global_arbit_count = m_sw_alloc->get_global_arbit_count(); } void Router_d::printConfig(ostream& out) { out << "[Router " << m_id << "] :: " << endl; out << "[inLink - "; for(int i = 0;i < m_input_unit.size(); i++) out << m_input_unit[i]->get_inlink_id() << " - "; out << "]" << endl; out << "[outLink - "; for(int i = 0;i < m_output_unit.size(); i++) out << m_output_unit[i]->get_outlink_id() << " - "; out << "]" << endl; }
{ "content_hash": "1906642e3f15863d514620913944f29b", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 130, "avg_line_length": 33.5735294117647, "alnum_prop": 0.6187034603591766, "repo_name": "liangwang/m5", "id": "428ba3260900f086553143eb92a12fd2b43117dd", "size": "6152", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/mem/ruby/network/garnet/fixed-pipeline/Router_d.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "490228" }, { "name": "C++", "bytes": "8617145" }, { "name": "Emacs Lisp", "bytes": "1969" }, { "name": "Python", "bytes": "2567844" }, { "name": "Shell", "bytes": "6722" }, { "name": "Visual Basic", "bytes": "2884" } ], "symlink_target": "" }
| Problem statement | Solution | |:-----------------------------|:--------------------------------:| | [Inheritance Introduction][] | [inheritance_introduction.cpp][] | | [Multi Level Inheritance][] | [multi_level_inheritance.cpp][] | | [Rectangle Area][] | [rectangle_area.cpp][] | [Inheritance Introduction]: https://www.hackerrank.com/challenges/inheritance-introduction [Multi Level Inheritance]: https://www.hackerrank.com/challenges/multi-level-inheritance-cpp [Rectangle Area]: https://www.hackerrank.com/challenges/rectangle-area [inheritance_introduction.cpp]: inheritance_introduction.cpp [multi_level_inheritance.cpp]: multi_level_inheritance.cpp [rectangle_area.cpp]: rectangle_area.cpp
{ "content_hash": "959f2648b8de65d10f3edfa4350b2bb6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 93, "avg_line_length": 60, "alnum_prop": 0.6269230769230769, "repo_name": "gshopov/competitive-programming-archive", "id": "056f8da75ea2a242e47e1deb5f22e44a61cc66b6", "size": "795", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hackerrank/c++/inheritance/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1238266" }, { "name": "Java", "bytes": "21451" }, { "name": "Python", "bytes": "21" } ], "symlink_target": "" }
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), ]
{ "content_hash": "9ec9e90112dca57b658ce92a499343c7", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 77, "avg_line_length": 36.22727272727273, "alnum_prop": 0.6938519447929736, "repo_name": "mishka28/NYU-Python", "id": "80e7b0447250710397a6ecae103cb13aa21341e8", "size": "797", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "advance_python_class_3/Homework4/mysite/mysite/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "206" }, { "name": "HTML", "bytes": "43267" }, { "name": "Makefile", "bytes": "561" }, { "name": "Python", "bytes": "100728" }, { "name": "Shell", "bytes": "7729" }, { "name": "Vim script", "bytes": "719" } ], "symlink_target": "" }
using System; using Robust.Shared.Map; using Robust.Shared.Maths; namespace Content.Server.Atmos { public static class EntityNetworkUtils { public static Vector2i CardinalToIntVec(this Direction dir) { switch (dir) { case Direction.North: return new Vector2i(0, 1); case Direction.East: return new Vector2i(1, 0); case Direction.South: return new Vector2i(0, -1); case Direction.West: return new Vector2i(-1, 0); default: throw new ArgumentException($"Direction dir {dir} is not a cardinal direction", nameof(dir)); } } public static Vector2i Offset(this Vector2i pos, Direction dir) { return pos + (Vector2i) dir.CardinalToIntVec(); } } }
{ "content_hash": "e7478f3a04021e4eea3dffb05b6ad8ba", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 113, "avg_line_length": 30, "alnum_prop": 0.5268817204301075, "repo_name": "space-wizards/space-station-14-content", "id": "1a00fe83b94c02a904379f457cc2d4376758d32b", "size": "930", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Content.Server/Atmos/EntityNetworkUtils.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "344" }, { "name": "C#", "bytes": "582784" }, { "name": "Python", "bytes": "13736" }, { "name": "Shell", "bytes": "429" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2012. Piraso Alvin R. de Leon. All Rights Reserved. ~ ~ See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ The Piraso licenses this file to You under the Apache License, Version 2.0 ~ (the "License"); you may not use this file except in compliance with ~ the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.piraso</groupId> <artifactId>context-logger</artifactId> <version>1.1-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>context-logger-proxy</artifactId> <packaging>jar</packaging> <name>context-logger-server-proxy</name> <dependencies> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2</version> <optional>true</optional> </dependency> </dependencies> </project>
{ "content_hash": "7c1e61d7bb813e81bd0867a286b29c4d", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 201, "avg_line_length": 37.89655172413793, "alnum_prop": 0.6524112829845314, "repo_name": "piraso/piraso", "id": "ca319199b9fa23134f55bc484ac6b45dead9dfdb", "size": "2198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "context-logger/proxy/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "72264" }, { "name": "Java", "bytes": "703739" }, { "name": "JavaScript", "bytes": "3956" } ], "symlink_target": "" }
'use strict'; var nodes = require('./nodes'); var lib = require('./lib'); var sym = 0; function gensym() { return 'hole_' + sym++; } // copy-on-write version of map function mapCOW(arr, func) { var res = null; for (let i = 0; i < arr.length; i++) { const item = func(arr[i]); if (item !== arr[i]) { if (!res) { res = arr.slice(); } res[i] = item; } } return res || arr; } function walk(ast, func, depthFirst) { if (!(ast instanceof nodes.Node)) { return ast; } if (!depthFirst) { const astT = func(ast); if (astT && astT !== ast) { return astT; } } if (ast instanceof nodes.NodeList) { const children = mapCOW(ast.children, (node) => walk(node, func, depthFirst)); if (children !== ast.children) { ast = new nodes[ast.typename](ast.lineno, ast.colno, children); } } else if (ast instanceof nodes.CallExtension) { const args = walk(ast.args, func, depthFirst); const contentArgs = mapCOW(ast.contentArgs, (node) => walk(node, func, depthFirst)); if (args !== ast.args || contentArgs !== ast.contentArgs) { ast = new nodes[ast.typename](ast.extName, ast.prop, args, contentArgs); } } else { const props = ast.fields.map((field) => ast[field]); const propsT = mapCOW(props, (prop) => walk(prop, func, depthFirst)); if (propsT !== props) { ast = new nodes[ast.typename](ast.lineno, ast.colno); propsT.forEach((prop, i) => { ast[ast.fields[i]] = prop; }); } } return depthFirst ? (func(ast) || ast) : ast; } function depthWalk(ast, func) { return walk(ast, func, true); } function _liftFilters(node, asyncFilters, prop) { var children = []; var walked = depthWalk(prop ? node[prop] : node, (descNode) => { let symbol; if (descNode instanceof nodes.Block) { return descNode; } else if ((descNode instanceof nodes.Filter && lib.indexOf(asyncFilters, descNode.name.value) !== -1) || descNode instanceof nodes.CallExtensionAsync) { symbol = new nodes.Symbol(descNode.lineno, descNode.colno, gensym()); children.push(new nodes.FilterAsync(descNode.lineno, descNode.colno, descNode.name, descNode.args, symbol)); } return symbol; }); if (prop) { node[prop] = walked; } else { node = walked; } if (children.length) { children.push(node); return new nodes.NodeList( node.lineno, node.colno, children ); } else { return node; } } function liftFilters(ast, asyncFilters) { return depthWalk(ast, (node) => { if (node instanceof nodes.Output) { return _liftFilters(node, asyncFilters); } else if (node instanceof nodes.Set) { return _liftFilters(node, asyncFilters, 'value'); } else if (node instanceof nodes.For) { return _liftFilters(node, asyncFilters, 'arr'); } else if (node instanceof nodes.If) { return _liftFilters(node, asyncFilters, 'cond'); } else if (node instanceof nodes.CallExtension) { return _liftFilters(node, asyncFilters, 'args'); } else { return undefined; } }); } function liftSuper(ast) { return walk(ast, (blockNode) => { if (!(blockNode instanceof nodes.Block)) { return; } let hasSuper = false; const symbol = gensym(); blockNode.body = walk(blockNode.body, (node) => { // eslint-disable-line consistent-return if (node instanceof nodes.FunCall && node.name.value === 'super') { hasSuper = true; return new nodes.Symbol(node.lineno, node.colno, symbol); } }); if (hasSuper) { blockNode.body.children.unshift(new nodes.Super( 0, 0, blockNode.name, new nodes.Symbol(0, 0, symbol) )); } }); } function convertStatements(ast) { return depthWalk(ast, (node) => { if (!(node instanceof nodes.If) && !(node instanceof nodes.For)) { return undefined; } let async = false; walk(node, (child) => { if (child instanceof nodes.FilterAsync || child instanceof nodes.IfAsync || child instanceof nodes.AsyncEach || child instanceof nodes.AsyncAll || child instanceof nodes.CallExtensionAsync) { async = true; // Stop iterating by returning the node return child; } return undefined; }); if (async) { if (node instanceof nodes.If) { return new nodes.IfAsync( node.lineno, node.colno, node.cond, node.body, node.else_ ); } else if (node instanceof nodes.For && !(node instanceof nodes.AsyncAll)) { return new nodes.AsyncEach( node.lineno, node.colno, node.arr, node.name, node.body, node.else_ ); } } return undefined; }); } function cps(ast, asyncFilters) { return convertStatements(liftSuper(liftFilters(ast, asyncFilters))); } function transform(ast, asyncFilters) { return cps(ast, asyncFilters || []); } // var parser = require('./parser'); // var src = 'hello {% foo %}{% endfoo %} end'; // var ast = transform(parser.parse(src, [new FooExtension()]), ['bar']); // nodes.printNodes(ast); module.exports = { transform: transform };
{ "content_hash": "ca1b9307fd861e9fb55a0fd26d933c2c", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 94, "avg_line_length": 24.571428571428573, "alnum_prop": 0.589834958739685, "repo_name": "devoidfury/nunjucks", "id": "aef6313011f8cf6c053bf6ae31563dae282560a7", "size": "5332", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "nunjucks/src/transformer.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "111" }, { "name": "HTML", "bytes": "25215" }, { "name": "JavaScript", "bytes": "355238" }, { "name": "Python", "bytes": "799" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="AppBundle\Entity\Sublegal" table="sublegal"> <indexes> <index name="id_base" columns="id_base"/> </indexes> <id name="id" type="integer" column="id"> <generator strategy="IDENTITY"/> </id> <field name="fio" type="string" column="fio" length="300" nullable="false"/> <many-to-one field="base" target-entity="Base"> <join-columns> <join-column name="id_base" referenced-column-name="id"/> </join-columns> </many-to-one> </entity> </doctrine-mapping>
{ "content_hash": "d8462c6f01d6d9610c546b7c4cf3944c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 276, "avg_line_length": 49.529411764705884, "alnum_prop": 0.6757719714964371, "repo_name": "x4devil/tourism.local", "id": "4bca9476b474075e950ea0338976a5f29c19b151", "size": "842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AppBundle/Resources/config/doctrine/Sublegal.orm.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3787" }, { "name": "CSS", "bytes": "1054" }, { "name": "HTML", "bytes": "53452" }, { "name": "JavaScript", "bytes": "484" }, { "name": "PHP", "bytes": "153236" } ], "symlink_target": "" }
module Shipit module Webhooks module Handlers module PullRequest class AssignedHandler < Shipit::Webhooks::Handlers::Handler params do requires :action, String requires :number, Integer requires :pull_request do requires :id, Integer requires :number, Integer requires :url, String requires :title, String requires :state, String requires :additions, Integer requires :deletions, Integer requires :head do requires :sha, String requires :ref, String end requires :user do requires :login, String end requires :assignees, Array do requires :login, String end requires :labels, Array do requires :name, String end end requires :repository do requires :full_name, String end requires :sender do requires :login, String end end def process return unless respond_to_assignee_change? pull_request.update(github_pull_request: params.pull_request) if pull_request.present? end private def respond_to_assignee_change? %w[assigned unassigned].include?(params.action) end def pull_request @pull_request ||= Shipit::PullRequest .joins(:stack, stack: :repository) .find_by( number: params.number, stacks: { repositories: { id: repository.id, }, } ) end def repository Shipit::Repository.from_github_repo_name(params.repository.full_name) || Shipit::NullRepository.new end end end end end end
{ "content_hash": "8f6f03503398b452a538366ec0cb70b7", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 111, "avg_line_length": 28.875, "alnum_prop": 0.48677248677248675, "repo_name": "Shopify/shipit-engine", "id": "a93757b2c4fa502469127c7379bf40a647dabb3e", "size": "2110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/shipit/webhooks/handlers/pull_request/assigned_handler.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "734" }, { "name": "CoffeeScript", "bytes": "20464" }, { "name": "HTML", "bytes": "65474" }, { "name": "JavaScript", "bytes": "9456" }, { "name": "Python", "bytes": "206" }, { "name": "Ruby", "bytes": "853529" }, { "name": "SCSS", "bytes": "38064" }, { "name": "Shell", "bytes": "9547" } ], "symlink_target": "" }
var src = null; var prev = null; var livetime = null; var msie = false; var stopped = false; var totStopped = false; var timer = null; var pr = 0; var liking = 0; var in_progress = false; var langSelect = false; var commentBusy = false; var last_popup_menu = null; var last_popup_button = null; var scroll_next = false; var next_page = 1; var page_load = true; var loadingPage = true; var pageHasMoreContent = true; var divmore_height = 400; var last_filestorage_id = null; var mediaPlaying = false; var contentHeightDiff = 0; var liveRecurse = 0; var savedTitle = ''; var initialLoad = true; // Clear the session and local storage if we switch channel or log out var cache_uid = ''; if(sessionStorage.getItem('uid') !== null) { cache_uid = sessionStorage.getItem('uid'); } if(cache_uid !== localUser.toString()) { sessionStorage.clear(); localStorage.clear(); sessionStorage.setItem('uid', localUser.toString()); } $.ajaxSetup({cache: false}); $(document).ready(function() { $(document).on('click focus', '.comment-edit-form', handle_comment_form); jQuery.timeago.settings.strings = { prefixAgo : aStr['t01'], prefixFromNow : aStr['t02'], suffixAgo : aStr['t03'], suffixFromNow : aStr['t04'], seconds : aStr['t05'], minute : aStr['t06'], minutes : aStr['t07'], hour : aStr['t08'], hours : aStr['t09'], day : aStr['t10'], days : aStr['t11'], month : aStr['t12'], months : aStr['t13'], year : aStr['t14'], years : aStr['t15'], wordSeparator : aStr['t16'], numbers : aStr['t17'], }; savedTitle = document.title; updateInit(); $('a.notification-link').click(function(e){ var notifyType = $(this).data('type'); if(! $('#nav-' + notifyType + '-sub').hasClass('show')) { loadNotificationItems(notifyType); sessionStorage.setItem('notification_open', notifyType); } else { sessionStorage.removeItem('notification_open'); } }); if(sessionStorage.getItem('notification_open') !== null) { var notifyType = sessionStorage.getItem('notification_open'); $('#nav-' + notifyType + '-sub').addClass('show'); loadNotificationItems(notifyType); } // Allow folks to stop the ajax page updates with the pause/break key $(document).keydown(function(event) { if(event.keyCode == '8') { var target = event.target || event.srcElement; if (!/input|textarea/i.test(target.nodeName)) { return false; } } if(event.keyCode == '19' || (event.ctrlKey && event.which == '32')) { event.preventDefault(); if(stopped === false) { stopped = true; if (event.ctrlKey) { totStopped = true; } $('#pause').html('<img src="images/pause.gif" alt="pause" style="border: 1px solid black;" />'); } else { unpause(); } } else { if (!totStopped) { unpause(); } } }); var e = document.getElementById('content-complete'); if(e) pageHasMoreContent = false; initialLoad = false; }); function datasrc2src(selector) { $(selector).each(function(i, el) { $(el).attr("src", $(el).data("src")); $(el).removeAttr("data-src"); }); } function confirmDelete() { return confirm(aStr.delitem); } function handle_comment_form(e) { e.stopPropagation(); //handle eventual expanded forms var expanded = $('.comment-edit-text.expanded'); var i = 0; if(expanded.length) { expanded.each(function() { var ex_form = $(expanded[i].form); var ex_fields = ex_form.find(':input[type=text], textarea'); var ex_fields_empty = true; ex_fields.each(function() { if($(this).val() != '') ex_fields_empty = false; }); if(ex_fields_empty) { ex_form.find('.comment-edit-text').removeClass('expanded').attr('placeholder', aStr.comment); ex_form.find(':not(.comment-edit-text)').hide(); } i++ }); } // handle clicked form var form = $(this); var fields = form.find(':input[type=text], textarea'); var fields_empty = true; if(form.find('.comment-edit-text').length) { var commentElm = form.find('.comment-edit-text').attr('id'); var submitElm = commentElm.replace(/text/,'submit'); $('#' + commentElm).addClass('expanded').removeAttr('placeholder'); $('#' + commentElm).attr('tabindex','9'); $('#' + submitElm).attr('tabindex','10'); form.find(':not(:visible)').show(); } // handle click outside of form (close empty forms) $(document).on('click', function(e) { fields.each(function() { if($(this).val() != '') fields_empty = false; }); if(fields_empty) { var emptyCommentElm = form.find('.comment-edit-text').attr('id'); var emptySubmitElm = commentElm.replace(/text/,'submit'); $('#' + emptyCommentElm).removeClass('expanded').attr('placeholder', aStr.comment); $('#' + emptyCommentElm).removeAttr('tabindex'); $('#' + emptySubmitElm).removeAttr('tabindex'); form.find(':not(.comment-edit-text)').hide(); } }); var commentSaveTimer = null; var emptyCommentElm = form.find('.comment-edit-text').attr('id'); var convId = emptyCommentElm.replace('comment-edit-text-',''); $(document).on('focusout','#' + emptyCommentElm,function(e){ if(commentSaveTimer) clearTimeout(commentSaveTimer); commentSaveChanges(convId,true); commentSaveTimer = null; }); $(document).on('focusin','#' + emptyCommentElm,function(e){ commentSaveTimer = setTimeout(function () { commentSaveChanges(convId,false); },10000); }); function commentSaveChanges(convId,isFinal = false) { if(auto_save_draft) { tmp = $('#' + emptyCommentElm).val(); if(tmp) { localStorage.setItem("comment_body-" + convId, tmp); } else { localStorage.removeItem("comment_body-" + convId); } if( !isFinal) { commentSaveTimer = setTimeout(commentSaveChanges,10000,convId); } } } } function commentClose(obj, id) { if(obj.value === '') { obj.value = aStr.comment; $("#comment-edit-text-" + id).removeClass("expanded"); $("#mod-cmnt-wrap-" + id).hide(); $("#comment-tools-" + id).hide(); $("#comment-edit-anon-" + id).hide(); return true; } return false; } function showHideCommentBox(id) { if( $('#comment-edit-form-' + id).is(':visible')) { $('#comment-edit-form-' + id).hide(); } else { $('#comment-edit-form-' + id).show(); } } function commentInsert(obj, id) { var tmpStr = $("#comment-edit-text-" + id).val(); if(tmpStr == '$comment') { tmpStr = ''; $("#comment-edit-text-" + id).addClass("expanded"); openMenu("comment-tools-" + id); } var ins = $(obj).html(); ins = ins.replace('&lt;','<'); ins = ins.replace('&gt;','>'); ins = ins.replace('&amp;','&'); ins = ins.replace('&quot;','"'); $("#comment-edit-text-" + id).val(tmpStr + ins); } function insertbbcomment(comment, BBcode, id) { // allow themes to override this if(typeof(insertFormatting) != 'undefined') return(insertFormatting(comment, BBcode, id)); var urlprefix = ((BBcode == 'url') ? '#^' : ''); var tmpStr = $("#comment-edit-text-" + id).val(); if(tmpStr == comment) { tmpStr = ""; $("#comment-edit-text-" + id).addClass("expanded"); openMenu("comment-tools-" + id); $("#comment-edit-text-" + id).val(tmpStr); } textarea = document.getElementById("comment-edit-text-" +id); if (document.selection) { textarea.focus(); selected = document.selection.createRange(); selected.text = urlprefix+"["+BBcode+"]" + selected.text + "[/"+BBcode+"]"; } else if (textarea.selectionStart || textarea.selectionStart == "0") { var start = textarea.selectionStart; var end = textarea.selectionEnd; textarea.value = textarea.value.substring(0, start) + urlprefix+"["+BBcode+"]" + textarea.value.substring(start, end) + "[/"+BBcode+"]" + textarea.value.substring(end, textarea.value.length); } return true; } function inserteditortag(BBcode, id) { // allow themes to override this if(typeof(insertEditorFormatting) != 'undefined') return(insertEditorFormatting(BBcode)); textarea = document.getElementById(id); if (document.selection) { textarea.focus(); selected = document.selection.createRange(); selected.text = urlprefix+"["+BBcode+"]" + selected.text + "[/"+BBcode+"]"; } else if (textarea.selectionStart || textarea.selectionStart == "0") { var start = textarea.selectionStart; var end = textarea.selectionEnd; textarea.value = textarea.value.substring(0, start) + "["+BBcode+"]" + textarea.value.substring(start, end) + "[/"+BBcode+"]" + textarea.value.substring(end, textarea.value.length); } return true; } function insertCommentAttach(comment,id) { activeCommentID = id; activeCommentText = comment; $('body').css('cursor', 'wait'); $('#invisible-comment-upload').trigger('click'); return false; } function insertCommentURL(comment, id) { reply = prompt(aStr.linkurl); if(reply && reply.length) { reply = bin2hex(reply); $('body').css('cursor', 'wait'); $.get('linkinfo?f=&binurl=' + reply, function(data) { var tmpStr = $("#comment-edit-text-" + id).val(); if(tmpStr == comment) { tmpStr = ""; $("#comment-edit-text-" + id).addClass("expanded"); openMenu("comment-tools-" + id); $("#comment-edit-text-" + id).val(tmpStr); } textarea = document.getElementById("comment-edit-text-" +id); textarea.value = textarea.value + data; preview_comment(id); $('body').css('cursor', 'auto'); }); } return true; } function doFollowAuthor(url) { $.get(url, function(data) { notificationsUpdate(); }); return true; } function viewsrc(id) { $.colorbox({href: 'viewsrc/' + id, maxWidth: '80%', maxHeight: '80%' }); } function showHideComments(id) { if( $('#collapsed-comments-' + id).is(':visible')) { $('#collapsed-comments-' + id + ' .autotime').timeago('dispose'); $('#collapsed-comments-' + id).slideUp(); $('#hide-comments-' + id).html(aStr.showmore); $('#hide-comments-total-' + id).show(); } else { $('#collapsed-comments-' + id + ' .autotime').timeago(); $('#collapsed-comments-' + id).slideDown(); $('#hide-comments-' + id).html(aStr.showfewer); $('#hide-comments-total-' + id).hide(); } } function openClose(theID) { if(document.getElementById(theID).style.display == "block") { document.getElementById(theID).style.display = "none"; } else { document.getElementById(theID).style.display = "block"; } } function openCloseTR(theID) { if(document.getElementById(theID).style.display == "table-row") { document.getElementById(theID).style.display = "none"; } else { document.getElementById(theID).style.display = "table-row"; } } function closeOpen(theID) { if(document.getElementById(theID).style.display == "none") { document.getElementById(theID).style.display = "block"; } else { document.getElementById(theID).style.display = "none"; } } function openMenu(theID) { document.getElementById(theID).style.display = "block"; } function closeMenu(theID) { document.getElementById(theID).style.display = "none"; } function markRead(notifType) { $.get('ping?f=&markRead='+notifType); $('.' + notifType + '-button').hide(); $('#nav-' + notifType + '-sub').removeClass('show'); sessionStorage.removeItem(notifType + '_notifications_cache'); sessionStorage.removeItem('notification_open'); if(timer) clearTimeout(timer); timer = setTimeout(updateInit,2000); } function markItemRead(itemId) { $.get('ping?f=&markItemRead='+itemId); $('.unseen-wall-indicator-'+itemId).hide(); } function notificationsUpdate(cached_data) { var pingCmd = 'ping' + ((localUser != 0) ? '?f=&uid=' + localUser : ''); if(cached_data !== undefined) { handleNotifications(cached_data); } else { $.get(pingCmd,function(data) { // Put the object into storage sessionStorage.setItem('notifications_cache', JSON.stringify(data)); if(data.invalid == 1) { window.location.href=window.location.href; } handleNotifications(data); $.jGrowl.defaults.closerTemplate = '<div>[ ' + aStr.closeAll + ']</div>'; $(data.notice).each(function() { $.jGrowl(this.message, { sticky: true, theme: 'notice' }); }); $(data.info).each(function(){ $.jGrowl(this.message, { sticky: false, theme: 'info', life: 10000 }); }); }); } var notifyType = null; if($('.notification-content.show').length) { notifyType = $('.notification-content.show').data('type'); } if(notifyType !== null) { loadNotificationItems(notifyType); } if(timer) clearTimeout(timer); timer = setTimeout(updateInit,updateInterval); } function handleNotifications(data) { if(data.network || data.home || data.intros || data.register || data.mail || data.all_events || data.notify || data.files || data.pubs) { $('.notifications-btn').css('opacity', 1); $('#no_notifications').hide(); } else { $('.notifications-btn').css('opacity', 0.5); $('#navbar-collapse-1').removeClass('show'); $('#no_notifications').show(); } if(data.home || data.intros || data.register || data.mail || data.notify || data.files) { $('.notifications-btn-icon').removeClass('fa-exclamation-circle'); $('.notifications-btn-icon').addClass('fa-exclamation-triangle'); } if(!data.home && !data.intros && !data.register && !data.mail && !data.notify && !data.files) { $('.notifications-btn-icon').removeClass('fa-exclamation-triangle'); $('.notifications-btn-icon').addClass('fa-exclamation-circle'); } if(data.all_events_today) { $('.all_events-update').removeClass('badge-secondary'); $('.all_events-update').addClass('badge-danger'); } else { $('.all_events-update').removeClass('badge-danger'); $('.all_events-update').addClass('badge-secondary'); } $.each(data, function(index, item) { //do not process those var arr = ['notice', 'info', 'invalid']; if(arr.indexOf(index) !== -1) return; if(item == 0) { $('.' + index + '-button').fadeOut(); sessionStorage.removeItem(index + '_notifications_cache'); } else { $('.' + index + '-button').fadeIn(); $('.' + index + '-update').html(item); } }); } function handleNotificationsItems(notifyType, data) { var notifications_tpl= unescape($("#nav-notifications-template[rel=template]").html()); var notify_menu = $("#nav-" + notifyType + "-menu"); notify_menu.html(''); $(data).each(function() { html = notifications_tpl.format(this.notify_link,this.photo,this.name,this.message,this.when,this.hclass,this.b64mid,this.notify_id,this.thread_top); notify_menu.append(html); }); datasrc2src('#notifications .notification img[data-src]'); if($('#tt-' + notifyType + '-only').hasClass('active')) $('#nav-' + notifyType + '-menu [data-thread_top=false]').hide(); if($('#cn-' + notifyType + '-input').length) { var filter = $('#cn-' + notifyType + '-input').val().toString().toLowerCase(); if(filter) { $('#nav-' + notifyType + '-menu .notification').each(function(i, el){ var cn = $(el).data('contact_name').toString().toLowerCase(); if(cn.indexOf(filter) === -1) $(el).addClass('d-none'); else $(el).removeClass('d-none'); }); } } } function contextualHelp() { var container = $("#contextual-help-content"); if(container.hasClass('contextual-help-content-open')) { container.removeClass('contextual-help-content-open'); $('main').css('margin-top', '') } else { container.addClass('contextual-help-content-open'); var mainTop = container.outerHeight(true); $('main').css('margin-top', mainTop + 'px'); } } function contextualHelpFocus(target, openSidePanel) { if($(target).length) { if (openSidePanel) { $("main").addClass('region_1-on'); // Open the side panel to highlight element } else { $("main").removeClass('region_1-on'); } var css_position = $(target).parent().css('position'); if (css_position === 'fixed') { $(target).parent().css('position', 'static'); } $('html,body').animate({ scrollTop: $(target).offset().top - $('nav').outerHeight(true) - $('#contextual-help-content').outerHeight(true)}, 'slow'); for (i = 0; i < 3; i++) { $(target).fadeTo('slow', 0.1).fadeTo('slow', 1.0); } $(target).parent().css('position', css_position); } } function updatePageItems(mode, data) { if(mode === 'append') { $(data).each(function() { $('#page-end').before($(this)); }); if(loadingPage) { loadingPage = false; } } var e = document.getElementById('content-complete'); if(e) { pageHasMoreContent = false; } collapseHeight(); } function updateConvItems(mode,data) { if(mode === 'update' || mode === 'replace') { prev = 'threads-begin'; } if(mode === 'append') { next = 'threads-end'; } if(mode === 'replace') { $('.thread-wrapper').remove(); // clear existing content } $('.thread-wrapper.toplevel_item',data).each(function() { var ident = $(this).attr('id'); var convId = ident.replace('thread-wrapper-',''); var commentWrap = $('#'+ident+' .collapsed-comments').attr('id'); var itmId = 0; var isVisible = false; // figure out the comment state if(typeof commentWrap !== 'undefined') itmId = commentWrap.replace('collapsed-comments-',''); if($('#collapsed-comments-'+itmId).is(':visible')) isVisible = true; // insert the content according to the mode and first_page // and whether or not the content exists already (overwrite it) if($('#' + ident).length == 0) { if((mode === 'update' || mode === 'replace') && profile_page == 1) { $('#' + prev).after($(this)); prev = ident; } if(mode === 'append') { $('#' + next).before($(this)); } } else { $('#' + ident).replaceWith($(this)); } // set the comment state to the state we discovered earlier if(isVisible) showHideComments(itmId); var commentBody = localStorage.getItem("comment_body-" + convId); if(commentBody) { var commentElm = $('#comment-edit-text-' + convId); if(auto_save_draft) { if($(commentElm).val() === '') { $('#comment-edit-form-' + convId).show(); $(commentElm).addClass("expanded"); openMenu("comment-tools-" + convId); $(commentElm).val(commentBody); } } else { localStorage.removeItem("comment_body-" + convId); } } // trigger the autotime function on all newly created content $("> .wall-item-outside-wrapper .autotime, > .thread-wrapper .autotime",this).timeago(); $("> .shared_header .autotime",this).timeago(); if((mode === 'append' || mode === 'replace') && (loadingPage)) { loadingPage = false; } // if single thread view and the item has a title, display it in the title bar if(mode === 'replace') { if (window.location.search.indexOf("mid=") != -1 || window.location.pathname.indexOf("display") != -1) { var title = $(".wall-item-title").text(); title.replace(/^\s+/, ''); title.replace(/\s+$/, ''); if (title) { savedTitle = title + " " + savedTitle; } } } }); // reset rotators and cursors we may have set before reaching this place $('.like-rotator').hide(); if(commentBusy) { commentBusy = false; $('body').css('cursor', 'auto'); } // Setup to determine if the media player is playing. This affects // some content loading decisions. $('video').off('playing'); $('video').off('pause'); $('audio').off('playing'); $('audio').off('pause'); $('video').on('playing', function() { mediaPlaying = true; }); $('video').on('pause', function() { mediaPlaying = false; }); $('audio').on('playing', function() { mediaPlaying = true; }); $('audio').on('pause', function() { mediaPlaying = false; }); /* autocomplete @nicknames */ $(".comment-edit-form textarea").editor_autocomplete(baseurl+"/acl?f=&n=1"); /* autocomplete bbcode */ $(".comment-edit-form textarea").bbco_autocomplete('bbcode'); var bimgs = ((preloadImages) ? false : $(".wall-item-body img").not(function() { return this.complete; })); var bimgcount = bimgs.length; if (bimgcount) { bimgs.on('load',function() { bimgcount--; if (! bimgcount) { collapseHeight(); } }); } else { collapseHeight(); } // auto-scroll to a particular comment in a thread (designated by mid) when in single-thread mode // use the same method to generate the submid as we use in ThreadItem, // base64_encode + replace(['+','='],['','']); var submid = ((bParam_mid.length) ? bParam_mid : 'abcdefg'); var encoded = ((submid.substr(0,4) == 'b64.') ? true : false); var submid_encoded = ((encoded) ? submid.substr(4) : window.btoa(submid)); submid_encoded = submid_encoded.replace(/[\+\=]/g,''); if($('.item_' + submid_encoded).length && !$('.item_' + submid_encoded).hasClass('toplevel_item') && mode == 'replace') { if($('.collapsed-comments').length) { var scrolltoid = $('.collapsed-comments').attr('id').substring(19); $('#collapsed-comments-' + scrolltoid + ' .autotime').timeago(); $('#collapsed-comments-' + scrolltoid).show(); $('#hide-comments-' + scrolltoid).html(aStr.showfewer); $('#hide-comments-total-' + scrolltoid).hide(); } $('html, body').animate({ scrollTop: $('.item_' + submid_encoded).offset().top - $('nav').outerHeight() }, 'slow'); $('.item_' + submid_encoded).addClass('item-highlight'); } $(document.body).trigger("sticky_kit:recalc"); } function collapseHeight() { var origContentHeight = Math.ceil($("#region_2").height()); var cDiff = 0; var i = 0; var position = $(window).scrollTop(); $(".wall-item-content, .directory-collapse").each(function() { var orgHeight = $(this).outerHeight(true); if(orgHeight > divmore_height) { if(! $(this).hasClass('divmore') && $(this).has('div.no-collapse').length == 0) { // check if we will collapse some content above the visible content and compensate the diff later if($(this).offset().top + divmore_height - $(window).scrollTop() + cDiff - ($(".divgrow-showmore").outerHeight() * i) < 65) { diff = orgHeight - divmore_height; cDiff = cDiff + diff; i++; } $(this).readmore({ speed: 0, heightMargin: 50, collapsedHeight: divmore_height, moreLink: '<a href="#" class="divgrow-showmore fakelink">' + aStr.divgrowmore + '</a>', lessLink: '<a href="#" class="divgrow-showmore fakelink">' + aStr.divgrowless + '</a>', beforeToggle: function(trigger, element, expanded) { if(expanded) { if((($(element).offset().top + divmore_height) - $(window).scrollTop()) < 65 ) { $(window).scrollTop($(window).scrollTop() - ($(element).outerHeight(true) - divmore_height)); } } } }); $(this).addClass('divmore'); } } }); var collapsedContentHeight = Math.ceil($("#region_2").height()); contentHeightDiff = origContentHeight - collapsedContentHeight; console.log('collapseHeight() - contentHeightDiff: ' + contentHeightDiff + 'px'); if(i){ var sval = position - cDiff + ($(".divgrow-showmore").outerHeight() * i); console.log('collapsed above viewport count: ' + i); $(window).scrollTop(sval); } } function updateInit() { if($('#live-network').length) { src = 'network'; } if($('#live-channel').length) { src = 'channel'; } if($('#live-pubstream').length) { src = 'pubstream'; } if($('#live-display').length) { src = 'display'; } if($('#live-hq').length) { src = 'hq'; } if($('#live-search').length) { src = 'search'; } // if($('#live-cards').length) { src = 'cards'; } // if($('#live-articles').length) { src = 'articles'; } if (initialLoad && (sessionStorage.getItem('notifications_cache') !== null)) { var cached_data = JSON.parse(sessionStorage.getItem('notifications_cache')); notificationsUpdate(cached_data); } if(! src) { notificationsUpdate(); } else { liveUpdate(); } if($('#live-photos').length || $('#live-cards').length || $('#live-articles').length ) { if(liking) { liking = 0; window.location.href=window.location.href; } } } function liveUpdate(notify_id) { if(typeof profile_uid === 'undefined') profile_uid = false; /* Should probably be unified with channelId defined in head.tpl */ if((src === null) || (stopped) || (! profile_uid)) { $('.like-rotator').hide(); return; } if(($('.comment-edit-text.expanded').length) || (in_progress) || (mediaPlaying)) { if(livetime) { clearTimeout(livetime); } livetime = setTimeout(liveUpdate, 10000); return; } if(timer) clearTimeout(timer); if(livetime !== null) livetime = null; prev = 'live-' + src; in_progress = true; var update_url; var update_mode; if(scroll_next) { bParam_page = next_page; page_load = true; } else { bParam_page = 1; } update_url = buildCmd(); if(page_load) { $("#page-spinner").show(); if(bParam_page == 1) update_mode = 'replace'; else update_mode = 'append'; } else { update_mode = 'update'; var orgHeight = $("#region_2").height(); } var dstart = new Date(); console.log('LOADING data...'); $.get(update_url, function(data) { // on shared hosts occasionally the live update process will be killed // leaving an incomplete HTML structure, which leads to conversations getting // truncated and the page messed up if all the divs aren't closed. We will try // again and give up if we can't get a valid HTML response after 10 tries. if((data.indexOf("<html>") != (-1)) && (data.indexOf("</html>") == (-1))) { console.log('Incomplete data. Reloading'); in_progress = false; liveRecurse ++; if(liveRecurse < 10) { liveUpdate(); } else { console.log('Incomplete data. Too many attempts. Giving up.'); } } // else data was valid - reset the recursion counter liveRecurse = 0; if(typeof notify_id !== 'undefined' && notify_id !== 'undefined') { $.post( "hq", { "notify_id" : notify_id } ); } var dready = new Date(); console.log('DATA ready in: ' + (dready - dstart)/1000 + ' seconds.'); if(update_mode === 'update' || preloadImages) { console.log('LOADING images...'); $('.wall-item-body, .wall-photo-item',data).imagesLoaded( function() { var iready = new Date(); console.log('IMAGES ready in: ' + (iready - dready)/1000 + ' seconds.'); page_load = false; scroll_next = false; updateConvItems(update_mode,data); $("#page-spinner").hide(); $("#profile-jot-text-loading").hide(); // adjust scroll position if new content was added above viewport if(update_mode === 'update') { $(window).scrollTop($(window).scrollTop() + $("#region_2").height() - orgHeight + contentHeightDiff); } in_progress = false; }); } else { page_load = false; scroll_next = false; updateConvItems(update_mode,data); $("#page-spinner").hide(); $("#profile-jot-text-loading").hide(); in_progress = false; } }) .done(function() { notificationsUpdate(); }); } function pageUpdate() { in_progress = true; var update_url; var update_mode; if(scroll_next) { bParam_page = next_page; page_load = true; } else { bParam_page = 1; } update_url = baseurl + '/' + page_query + '/?f=&aj=1&page=' + bParam_page + extra_args ; $("#page-spinner").show(); update_mode = 'append'; $.get(update_url,function(data) { page_load = false; scroll_next = false; updatePageItems(update_mode,data); $("#page-spinner").hide(); $(".autotime").timeago(); in_progress = false; }); } function justifyPhotos(id) { justifiedGalleryActive = true; $('#' + id).show(); $('#' + id).justifiedGallery({ selector: 'a, div:not(.spinner, #page-end)', margins: 3, border: 0, sizeRangeSuffixes: { 'lt100': '-3', 'lt240': '-3', 'lt320': '-3', 'lt500': '-2', 'lt640': '-2', 'lt1024': '-1' } }).on('jg.complete', function(e){ justifiedGalleryActive = false; }); } function justifyPhotosAjax(id) { justifiedGalleryActive = true; $('#' + id).justifiedGallery('norewind').on('jg.complete', function(e){ justifiedGalleryActive = false; }); } function loadNotificationItems(notifyType) { var pingExCmd = 'ping/' + notifyType + ((localUser != 0) ? '?f=&uid=' + localUser : ''); var clicked = $('[data-type=\'' + notifyType + '\']').data('clicked'); if((clicked === undefined) && (sessionStorage.getItem(notifyType + '_notifications_cache') !== null)) { var cached_data = JSON.parse(sessionStorage.getItem(notifyType + '_notifications_cache')); handleNotificationsItems(notifyType, cached_data); $('[data-type=\'' + notifyType + '\']').data('clicked',true); console.log('updating ' + notifyType + ' notifications from cache...'); } else { var cached_data = []; } console.log('updating ' + notifyType + ' notifications...'); $.get(pingExCmd, function(data) { if(data.invalid == 1) { window.location.href=window.location.href; } if(JSON.stringify(cached_data[0]) === JSON.stringify(data.notify[0])) { console.log(notifyType + ' notifications cache up to date - update deferred'); } else { handleNotificationsItems(notifyType, data.notify); sessionStorage.setItem(notifyType + '_notifications_cache', JSON.stringify(data.notify)); } }); } // Since our ajax calls are asynchronous, we will give a few // seconds for the first ajax call (setting like/dislike), then // run the updater to pick up any changes and display on the page. // The updater will turn any rotators off when it's done. // This function will have returned long before any of these // events have completed and therefore there won't be any // visible feedback that anything changed without all this // trickery. This still could cause confusion if the "like" ajax call // is delayed and updateInit runs before it completes. function dolike(ident, verb) { unpause(); $('#like-rotator-' + ident.toString()).show(); $.get('like/' + ident.toString() + '?verb=' + verb, updateInit ); liking = 1; } function doprofilelike(ident, verb) { $.get('like/' + ident + '?verb=' + verb, function() { window.location.href=window.location.href; }); } function dropItem(url, object) { var confirm = confirmDelete(); if(confirm) { $('body').css('cursor', 'wait'); $(object).fadeTo('fast', 0.33, function () { $.get(url).done(function() { $(object).remove(); $('body').css('cursor', 'auto'); }); }); return true; } else { return false; } } function dosubthread(ident) { unpause(); $('#like-rotator-' + ident.toString()).show(); $.get('subthread/sub/' + ident.toString(), updateInit ); liking = 1; } function dounsubthread(ident) { unpause(); $('#like-rotator-' + ident.toString()).show(); $.get('subthread/unsub/' + ident.toString(), updateInit ); liking = 1; } function dostar(ident) { ident = ident.toString(); $('#like-rotator-' + ident).show(); $.get('starred/' + ident, function(data) { if(data.result == 1) { $('#starred-' + ident).addClass('starred'); $('#starred-' + ident).removeClass('unstarred'); $('#starred-' + ident).addClass('fa-star'); $('#starred-' + ident).removeClass('fa-star-o'); $('#star-' + ident).addClass('hidden'); $('#unstar-' + ident).removeClass('hidden'); var btn_tpl = '<div class="btn-group" id="star-button-' + ident + '"><button type="button" class="btn btn-outline-secondary btn-sm wall-item-like" onclick="dostar(' + ident + ');"><i class="fa fa-star"></i></button></div>' $('#wall-item-tools-left-' + ident).prepend(btn_tpl); } else { $('#starred-' + ident).addClass('unstarred'); $('#starred-' + ident).removeClass('starred'); $('#starred-' + ident).addClass('fa-star-o'); $('#starred-' + ident).removeClass('fa-star'); $('#star-' + ident).removeClass('hidden'); $('#unstar-' + ident).addClass('hidden'); $('#star-button-' + ident).remove(); } $('#like-rotator-' + ident).hide(); }); } function getPosition(e) { var cursor = {x:0, y:0}; if ( e.pageX || e.pageY ) { cursor.x = e.pageX; cursor.y = e.pageY; } else { if( e.clientX || e.clientY ) { cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft; cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop; } else { if( e.x || e.y ) { cursor.x = e.x; cursor.y = e.y; } } } return cursor; } function lockview(type, id) { $.get('lockview/' + type + '/' + id, function(data) { $('#panel-' + id).html(data); }); } function filestorage(event, nick, id) { $('#cloud-index-' + last_filestorage_id).removeClass('cloud-index-active'); $('#perms-panel-' + last_filestorage_id).hide().html(''); $('#file-edit-' + id).show(); $.get('filestorage/' + nick + '/' + id + '/edit', function(data) { $('#cloud-index-' + id).addClass('cloud-index-active'); $('#perms-panel-' + id).html(data).show(); $('#file-edit-' + id).hide(); last_filestorage_id = id; }); } function post_comment(id) { unpause(); commentBusy = true; $('body').css('cursor', 'wait'); $("#comment-preview-inp-" + id).val("0"); $.post( "item", $("#comment-edit-form-" + id).serialize(), function(data) { if(data.success) { localStorage.removeItem("comment_body-" + id); $("#comment-edit-preview-" + id).hide(); $("#comment-edit-wrapper-" + id).hide(); $("#comment-edit-text-" + id).val(''); var tarea = document.getElementById("comment-edit-text-" + id); if(tarea) { commentClose(tarea, id); $(document).unbind( "click.commentOpen"); } if(timer) clearTimeout(timer); timer = setTimeout(updateInit,1500); } if(data.reload) { window.location.href=data.reload; } }, "json" ); return false; } function preview_comment(id) { $("#comment-preview-inp-" + id).val("1"); $("#comment-edit-preview-" + id).show(); $.post( "item", $("#comment-edit-form-" + id).serialize(), function(data) { if(data.preview) { $("#comment-edit-preview-" + id).html(data.preview); $("#comment-edit-preview-" + id + " .autotime").timeago(); $("#comment-edit-preview-" + id + " a").click(function() { return false; }); } }, "json" ); return true; } function importElement(elem) { $.post( "impel", { "element" : elem }, function(data) { if(timer) clearTimeout(timer); timer = setTimeout(updateInit,10); } ); return false; } function preview_post() { $("#jot-preview").val("1"); $("#jot-preview-content").show(); $.post( "item", $("#profile-jot-form").serialize(), function(data) { if(data.preview) { $("#jot-preview-content").html(data.preview); $("#jot-preview-content .autotime").timeago(); $("#jot-preview-content" + " a").click(function() { return false; }); } }, "json" ); $("#jot-preview").val("0"); return true; } function preview_mail() { $("#mail-preview").val("1"); $("#mail-preview-content").show(); $.post( "mail", $("#prvmail-form").serialize(), function(data) { if(data.preview) { $("#mail-preview-content").html(data.preview); $("#mail-preview-content" + " a").click(function() { return false; }); } }, "json" ); $("#mail-preview").val("0"); return true; } function unpause() { // unpause auto reloads if they are currently stopped totStopped = false; stopped = false; $('#pause').html(''); } function bin2hex(s) { // Converts the binary representation of data to hex // // version: 812.316 // discuss at: http://phpjs.org/functions/bin2hex // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Linuxworld // * example 1: bin2hex('Kev'); // * returns 1: '4b6576' // * example 2: bin2hex(String.fromCharCode(0x00)); // * returns 2: '00' var v,i, f = 0, a = []; s += ''; f = s.length; for (i = 0; i<f; i++) { a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1"); } return a.join(''); } function hex2bin(hex) { var bytes = [], str; for(var i=0; i< hex.length-1; i+=2) bytes.push(parseInt(hex.substr(i, 2), 16)); return String.fromCharCode.apply(String, bytes); } function groupChangeMember(gid, cid, sec_token) { $('body .fakelink').css('cursor', 'wait'); $.get('group/' + gid + '/' + cid + "?t=" + sec_token, function(data) { $('#group-update-wrapper').html(data); $('body .fakelink').css('cursor', 'auto'); }); } function profChangeMember(gid, cid) { $('body .fakelink').css('cursor', 'wait'); $.get('profperm/' + gid + '/' + cid, function(data) { $('#prof-update-wrapper').html(data); $('body .fakelink').css('cursor', 'auto'); }); } function contactgroupChangeMember(gid, cid) { $('body').css('cursor', 'wait'); $.get('contactgroup/' + gid + '/' + cid, function(data) { $('body').css('cursor', 'auto'); $('#group-' + gid).toggleClass('fa-check-square-o fa-square-o'); }); } function checkboxhighlight(box) { if($(box).is(':checked')) { $(box).addClass('checkeditem'); } else { $(box).removeClass('checkeditem'); } } /** * sprintf in javascript * "{0} and {1}".format('zero','uno'); */ String.prototype.format = function() { var formatted = this; for (var i = 0; i < arguments.length; i++) { var regexp = new RegExp('\\{'+i+'\\}', 'gi'); formatted = formatted.replace(regexp, arguments[i]); } return formatted; }; // Array Remove Array.prototype.remove = function(item) { to = undefined; from = this.indexOf(item); var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; function zFormError(elm,x) { if(x) { $(elm).addClass("zform-error"); $(elm).removeClass("zform-ok"); } else { $(elm).addClass("zform-ok"); $(elm).removeClass("zform-error"); } } $(window).scroll(function () { if(typeof buildCmd == 'function') { // This is a content page with items and/or conversations if($(window).scrollTop() + $(window).height() > $(document).height() - 300) { if((pageHasMoreContent) && (! loadingPage)) { next_page++; scroll_next = true; loadingPage = true; liveUpdate(); } } } else { // This is some other kind of page - perhaps a directory if($(window).scrollTop() + $(window).height() > $(document).height() - 300) { if((pageHasMoreContent) && (! loadingPage) && (! justifiedGalleryActive)) { next_page++; scroll_next = true; loadingPage = true; pageUpdate(); } } } }); var chanviewFullSize = false; function chanviewFull() { if(chanviewFullSize) { chanviewFullSize = false; $('#chanview-iframe-border').css({ 'position' : 'relative', 'z-index' : '10' }); $('#remote-channel').css({ 'position' : 'relative' , 'z-index' : '10' }); } else { chanviewFullSize = true; $('#chanview-iframe-border').css({ 'position' : 'fixed', 'top' : '0', 'left' : '0', 'z-index' : '150001' }); $('#remote-channel').css({ 'position' : 'fixed', 'top' : '0', 'left' : '0', 'z-index' : '150000' }); resize_iframe(); } } function addhtmltext(data) { data = h2b(data); addeditortext(data); } function loadText(textRegion,data) { var currentText = $(textRegion).val(); $(textRegion).val(currentText + data); } function addeditortext(data) { if(plaintext == 'none') { var currentText = $("#profile-jot-text").val(); $("#profile-jot-text").val(currentText + data); } } function h2b(s) { var y = s; function rep(re, str) { y = y.replace(re,str); } rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]"); rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi,"[size=$1]$2[/size]"); rep(/<span style=\"color:(.*?);\">(.*?)<\/span>/gi,"[color=$1]$2[/color]"); rep(/<font>(.*?)<\/font>/gi,"$1"); rep(/<img.*?width=\"(.*?)\".*?height=\"(.*?)\".*?src=\"(.*?)\".*?\/>/gi,"[img=$1x$2]$3[/img]"); rep(/<img.*?height=\"(.*?)\".*?width=\"(.*?)\".*?src=\"(.*?)\".*?\/>/gi,"[img=$2x$1]$3[/img]"); rep(/<img.*?src=\"(.*?)\".*?height=\"(.*?)\".*?width=\"(.*?)\".*?\/>/gi,"[img=$3x$2]$1[/img]"); rep(/<img.*?src=\"(.*?)\".*?width=\"(.*?)\".*?height=\"(.*?)\".*?\/>/gi,"[img=$2x$3]$1[/img]"); rep(/<img.*?src=\"(.*?)\".*?\/>/gi,"[img]$1[/img]"); rep(/<ul class=\"listbullet\" style=\"list-style-type\: circle\;\">(.*?)<\/ul>/gi,"[list]$1[/list]"); rep(/<ul class=\"listnone\" style=\"list-style-type\: none\;\">(.*?)<\/ul>/gi,"[list=]$1[/list]"); rep(/<ul class=\"listdecimal\" style=\"list-style-type\: decimal\;\">(.*?)<\/ul>/gi,"[list=1]$1[/list]"); rep(/<ul class=\"listlowerroman\" style=\"list-style-type\: lower-roman\;\">(.*?)<\/ul>/gi,"[list=i]$1[/list]"); rep(/<ul class=\"listupperroman\" style=\"list-style-type\: upper-roman\;\">(.*?)<\/ul>/gi,"[list=I]$1[/list]"); rep(/<ul class=\"listloweralpha\" style=\"list-style-type\: lower-alpha\;\">(.*?)<\/ul>/gi,"[list=a]$1[/list]"); rep(/<ul class=\"listupperalpha\" style=\"list-style-type\: upper-alpha\;\">(.*?)<\/ul>/gi,"[list=A]$1[/list]"); rep(/<li>(.*?)<\/li>/gi,"[li]$1[/li]"); rep(/<code>(.*?)<\/code>/gi,"[code]$1[/code]"); rep(/<\/(strong|b)>/gi,"[/b]"); rep(/<(strong|b)>/gi,"[b]"); rep(/<\/(em|i)>/gi,"[/i]"); rep(/<(em|i)>/gi,"[i]"); rep(/<\/u>/gi,"[/u]"); rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi,"[u]$1[/u]"); rep(/<u>/gi,"[u]"); rep(/<blockquote[^>]*>/gi,"[quote]"); rep(/<\/blockquote>/gi,"[/quote]"); rep(/<hr \/>/gi,"[hr]"); rep(/<br (.*?)\/>/gi,"\n"); rep(/<br\/>/gi,"\n"); rep(/<br>/gi,"\n"); rep(/<p>/gi,""); rep(/<\/p>/gi,"\n"); rep(/&nbsp;/gi," "); rep(/&quot;/gi,"\""); rep(/&lt;/gi,"<"); rep(/&gt;/gi,">"); rep(/&amp;/gi,"&"); return y; } function b2h(s) { var y = s; function rep(re, str) { y = y.replace(re,str); } rep(/\&/gi,"&amp;"); rep(/\</gi,"&lt;"); rep(/\>/gi,"&gt;"); rep(/\"/gi,"&quot;"); rep(/\n/gi,"<br />"); rep(/\[b\]/gi,"<strong>"); rep(/\[\/b\]/gi,"</strong>"); rep(/\[i\]/gi,"<em>"); rep(/\[\/i\]/gi,"</em>"); rep(/\[u\]/gi,"<u>"); rep(/\[\/u\]/gi,"</u>"); rep(/\[hr\]/gi,"<hr />"); rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>"); rep(/\[url\](.*?)\[\/url\]/gi,"<a href=\"$1\">$1</a>"); rep(/\[img=(.*?)x(.*?)\](.*?)\[\/img\]/gi,"<img width=\"$1\" height=\"$2\" src=\"$3\" />"); rep(/\[img\](.*?)\[\/img\]/gi,"<img src=\"$1\" />"); rep(/\[zrl=([^\]]+)\](.*?)\[\/zrl\]/gi,"<a href=\"$1" + '?f=&zid=' + zid + "\">$2</a>"); rep(/\[zrl\](.*?)\[\/zrl\]/gi,"<a href=\"$1" + '?f=&zid=' + zid + "\">$1</a>"); rep(/\[zmg=(.*?)x(.*?)\](.*?)\[\/zmg\]/gi,"<img width=\"$1\" height=\"$2\" src=\"$3" + '?f=&zid=' + zid + "\" />"); rep(/\[zmg\](.*?)\[\/zmg\]/gi,"<img src=\"$1" + '?f=&zid=' + zid + "\" />"); rep(/\[list\](.*?)\[\/list\]/gi, '<ul class="listbullet" style="list-style-type: circle;">$1</ul>'); rep(/\[list=\](.*?)\[\/list\]/gi, '<ul class="listnone" style="list-style-type: none;">$1</ul>'); rep(/\[list=1\](.*?)\[\/list\]/gi, '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>'); rep(/\[list=i\](.*?)\[\/list\]/gi,'<ul class="listlowerroman" style="list-style-type: lower-roman;">$1</ul>'); rep(/\[list=I\](.*?)\[\/list\]/gi, '<ul class="listupperroman" style="list-style-type: upper-roman;">$1</ul>'); rep(/\[list=a\](.*?)\[\/list\]/gi, '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$1</ul>'); rep(/\[list=A\](.*?)\[\/list\]/gi, '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$1</ul>'); rep(/\[li\](.*?)\[\/li\]/gi, '<li>$1</li>'); rep(/\[color=(.*?)\](.*?)\[\/color\]/gi,"<span style=\"color: $1;\">$2</span>"); rep(/\[size=(.*?)\](.*?)\[\/size\]/gi,"<span style=\"font-size: $1;\">$2</span>"); rep(/\[code\](.*?)\[\/code\]/gi,"<code>$1</code>"); rep(/\[quote.*?\](.*?)\[\/quote\]/gi,"<blockquote>$1</blockquote>"); rep(/\[video\](.*?)\[\/video\]/gi,"<a href=\"$1\">$1</a>"); rep(/\[audio\](.*?)\[\/audio\]/gi,"<a href=\"$1\">$1</a>"); rep(/\[\&amp\;([#a-z0-9]+)\;\]/gi,'&$1;'); rep(/\<(.*?)(src|href)=\"[^hfm](.*?)\>/gi,'<$1$2="">'); return y; } function zid(s) { if((! s.length) || (s.indexOf('zid=') != (-1))) return s; if(! zid.length) return s; var has_params = ((s.indexOf('?') == (-1)) ? false : true); var achar = ((has_params) ? '&' : '?'); s = s + achar + 'f=&zid=' + zid; return s; }
{ "content_hash": "8a7ccb13de4d85e6c9e9928c7e00c234", "timestamp": "", "source": "github", "line_count": 1533, "max_line_length": 225, "avg_line_length": 28.756033920417483, "alnum_prop": 0.5983939387065309, "repo_name": "sasiflo/hubzilla", "id": "acb9b462f69f3b168d50f8d6aa745363cec00de2", "size": "44083", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "view/js/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "276150" }, { "name": "Clojure", "bytes": "2274" }, { "name": "Gherkin", "bytes": "529" }, { "name": "Go", "bytes": "16039" }, { "name": "HTML", "bytes": "318982" }, { "name": "JavaScript", "bytes": "1857546" }, { "name": "Makefile", "bytes": "1203" }, { "name": "PHP", "bytes": "9386167" }, { "name": "Python", "bytes": "37904" }, { "name": "Shell", "bytes": "75660" }, { "name": "Smarty", "bytes": "646418" } ], "symlink_target": "" }
#ifndef color_generic_place_blue #define color_generic_place_blue // ::color::place::blue<category_name>() // ::color::place::_internal::blue<category_name>::position_enum #include "../trait/index.hpp" namespace color { namespace place { namespace _internal { template< typename category_name > struct blue { public: typedef typename ::color::trait::index< category_name >::instance_type index_instance_type; enum { position_enum = -3 }; enum { has_enum = false }; static /*constexpr*/ index_instance_type position() { return position_enum; } }; } template< typename category_name > inline /*constexpr*/ typename ::color::trait::index< category_name >::instance_type blue() { return ::color::place::_internal::blue<category_name>::position(); } } } #endif
{ "content_hash": "8ba62b355e97f773c65060b58e90cba5", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 102, "avg_line_length": 22.195652173913043, "alnum_prop": 0.5328109696376102, "repo_name": "dmilos/color", "id": "2185700dfa55d51fc29cbd93feb49843d5612b7f", "size": "1021", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/color/generic/place/blue.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "202084" }, { "name": "C++", "bytes": "5689078" }, { "name": "CMake", "bytes": "3786" }, { "name": "Python", "bytes": "11674" }, { "name": "Shell", "bytes": "153373" } ], "symlink_target": "" }
title: Object.prototype.propertyIsEnumerable localeTitle: Object.prototype.propertyIsEnumerable --- ## Object.prototype.propertyIsEnumerable Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/object/object-prototype-propertyisenumerable/index.md) . [Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) . #### Дополнительная информация:
{ "content_hash": "02e14ea7fb68e54df38ccef783e1a7a4", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 202, "avg_line_length": 51.7, "alnum_prop": 0.8239845261121856, "repo_name": "otavioarc/freeCodeCamp", "id": "347731b85b69c7863f2b0514884afd26a50c4bba", "size": "653", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "guide/russian/javascript/standard-objects/object/object-prototype-propertyisenumerable/index.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "35491" }, { "name": "HTML", "bytes": "17600" }, { "name": "JavaScript", "bytes": "777274" } ], "symlink_target": "" }
#include "includes.h" #include "common.h" #include "common/ieee802_11_defs.h" #include "p2p_i.h" #include "p2p.h" static struct wpabuf * p2p_build_dev_disc_req(struct p2p_data *p2p, struct p2p_device *go, const u8 *dev_id) { struct wpabuf *buf; u8 *len; buf = wpabuf_alloc(100); if (buf == NULL) return NULL; go->dialog_token++; if (go->dialog_token == 0) go->dialog_token = 1; p2p_buf_add_public_action_hdr(buf, P2P_DEV_DISC_REQ, go->dialog_token); len = p2p_buf_add_ie_hdr(buf); p2p_buf_add_device_id(buf, dev_id); p2p_buf_add_group_id(buf, go->info.p2p_device_addr, go->oper_ssid, go->oper_ssid_len); p2p_buf_update_ie_hdr(buf, len); return buf; } void p2p_dev_disc_req_cb(struct p2p_data *p2p, int success) { p2p_dbg(p2p, "Device Discoverability Request TX callback: success=%d", success); if (!success) { /* * Use P2P find, if needed, to find the other device or to * retry device discoverability. */ p2p_set_state(p2p, P2P_CONNECT); p2p_set_timeout(p2p, 0, 100000); return; } p2p_dbg(p2p, "GO acknowledged Device Discoverability Request - wait for response"); /* * TODO: is the remain-on-channel from Action frame TX long enough for * most cases or should we try to increase its duration and/or start * another remain-on-channel if needed once the previous one expires? */ } int p2p_send_dev_disc_req(struct p2p_data *p2p, struct p2p_device *dev) { struct p2p_device *go; struct wpabuf *req; unsigned int wait_time; go = p2p_get_device(p2p, dev->member_in_go_dev); if (go == NULL || dev->oper_freq <= 0) { p2p_dbg(p2p, "Could not find peer entry for GO and frequency to send Device Discoverability Request"); return -1; } req = p2p_build_dev_disc_req(p2p, go, dev->info.p2p_device_addr); if (req == NULL) return -1; p2p_dbg(p2p, "Sending Device Discoverability Request to GO " MACSTR " for client " MACSTR, MAC2STR(go->info.p2p_device_addr), MAC2STR(dev->info.p2p_device_addr)); p2p->pending_client_disc_go = go; os_memcpy(p2p->pending_client_disc_addr, dev->info.p2p_device_addr, ETH_ALEN); p2p->pending_action_state = P2P_PENDING_DEV_DISC_REQUEST; wait_time = 1000; if (p2p->cfg->max_listen && wait_time > p2p->cfg->max_listen) wait_time = p2p->cfg->max_listen; if (p2p_send_action(p2p, dev->oper_freq, go->info.p2p_device_addr, p2p->cfg->dev_addr, go->info.p2p_device_addr, wpabuf_head(req), wpabuf_len(req), wait_time) < 0) { p2p_dbg(p2p, "Failed to send Action frame"); wpabuf_free(req); /* TODO: how to recover from failure? */ return -1; } wpabuf_free(req); return 0; } static struct wpabuf * p2p_build_dev_disc_resp(u8 dialog_token, u8 status) { struct wpabuf *buf; u8 *len; buf = wpabuf_alloc(100); if (buf == NULL) return NULL; p2p_buf_add_public_action_hdr(buf, P2P_DEV_DISC_RESP, dialog_token); len = p2p_buf_add_ie_hdr(buf); p2p_buf_add_status(buf, status); p2p_buf_update_ie_hdr(buf, len); return buf; } void p2p_dev_disc_resp_cb(struct p2p_data *p2p, int success) { p2p_dbg(p2p, "Device Discoverability Response TX callback: success=%d", success); p2p->cfg->send_action_done(p2p->cfg->cb_ctx); } static void p2p_send_dev_disc_resp(struct p2p_data *p2p, u8 dialog_token, const u8 *addr, int freq, u8 status) { struct wpabuf *resp; resp = p2p_build_dev_disc_resp(dialog_token, status); if (resp == NULL) return; p2p_dbg(p2p, "Sending Device Discoverability Response to " MACSTR " (status %u freq %d)", MAC2STR(addr), status, freq); p2p->pending_action_state = P2P_PENDING_DEV_DISC_RESPONSE; if (p2p_send_action(p2p, freq, addr, p2p->cfg->dev_addr, p2p->cfg->dev_addr, wpabuf_head(resp), wpabuf_len(resp), 200) < 0) { p2p_dbg(p2p, "Failed to send Action frame"); } wpabuf_free(resp); } void p2p_process_dev_disc_req(struct p2p_data *p2p, const u8 *sa, const u8 *data, size_t len, int rx_freq) { struct p2p_message msg; size_t g; p2p_dbg(p2p, "Received Device Discoverability Request from " MACSTR " (freq=%d)", MAC2STR(sa), rx_freq); if (p2p_parse(data, len, &msg)) return; if (msg.dialog_token == 0) { p2p_dbg(p2p, "Invalid Dialog Token 0 (must be nonzero) in Device Discoverability Request"); p2p_send_dev_disc_resp(p2p, msg.dialog_token, sa, rx_freq, P2P_SC_FAIL_INVALID_PARAMS); p2p_parse_free(&msg); return; } if (msg.device_id == NULL) { p2p_dbg(p2p, "P2P Device ID attribute missing from Device Discoverability Request"); p2p_send_dev_disc_resp(p2p, msg.dialog_token, sa, rx_freq, P2P_SC_FAIL_INVALID_PARAMS); p2p_parse_free(&msg); return; } for (g = 0; g < p2p->num_groups; g++) { if (p2p_group_go_discover(p2p->groups[g], msg.device_id, sa, rx_freq) == 0) { p2p_dbg(p2p, "Scheduled GO Discoverability Request for the target device"); /* * P2P group code will use a callback to indicate TX * status, so that we can reply to the request once the * target client has acknowledged the request or it has * timed out. */ p2p->pending_dev_disc_dialog_token = msg.dialog_token; os_memcpy(p2p->pending_dev_disc_addr, sa, ETH_ALEN); p2p->pending_dev_disc_freq = rx_freq; p2p_parse_free(&msg); return; } } p2p_dbg(p2p, "Requested client was not found in any group or did not support client discoverability"); p2p_send_dev_disc_resp(p2p, msg.dialog_token, sa, rx_freq, P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE); p2p_parse_free(&msg); } void p2p_process_dev_disc_resp(struct p2p_data *p2p, const u8 *sa, const u8 *data, size_t len) { struct p2p_message msg; struct p2p_device *go; u8 status; p2p_dbg(p2p, "Received Device Discoverability Response from " MACSTR, MAC2STR(sa)); go = p2p->pending_client_disc_go; if (go == NULL || os_memcmp(sa, go->info.p2p_device_addr, ETH_ALEN) != 0) { p2p_dbg(p2p, "Ignore unexpected Device Discoverability Response"); return; } if (p2p_parse(data, len, &msg)) return; if (msg.status == NULL) { p2p_parse_free(&msg); return; } if (msg.dialog_token != go->dialog_token) { p2p_dbg(p2p, "Ignore Device Discoverability Response with unexpected dialog token %u (expected %u)", msg.dialog_token, go->dialog_token); p2p_parse_free(&msg); return; } status = *msg.status; p2p_parse_free(&msg); p2p_dbg(p2p, "Device Discoverability Response status %u", status); if (p2p->go_neg_peer == NULL || os_memcmp(p2p->pending_client_disc_addr, p2p->go_neg_peer->info.p2p_device_addr, ETH_ALEN) != 0 || os_memcmp(p2p->go_neg_peer->member_in_go_dev, go->info.p2p_device_addr, ETH_ALEN) != 0) { p2p_dbg(p2p, "No pending operation with the client discoverability peer anymore"); return; } if (status == 0) { /* * Peer is expected to be awake for at least 100 TU; try to * connect immediately. */ p2p_dbg(p2p, "Client discoverability request succeeded"); if (p2p->state == P2P_CONNECT) { /* * Change state to force the timeout to start in * P2P_CONNECT again without going through the short * Listen state. */ p2p_set_state(p2p, P2P_CONNECT_LISTEN); p2p->cfg->send_action_done(p2p->cfg->cb_ctx); } p2p_set_timeout(p2p, 0, 0); } else { /* * Client discoverability request failed; try to connect from * timeout. */ p2p_dbg(p2p, "Client discoverability request failed"); p2p_set_timeout(p2p, 0, 500000); } } void p2p_go_disc_req_cb(struct p2p_data *p2p, int success) { p2p_dbg(p2p, "GO Discoverability Request TX callback: success=%d", success); p2p->cfg->send_action_done(p2p->cfg->cb_ctx); if (p2p->pending_dev_disc_dialog_token == 0) { p2p_dbg(p2p, "No pending Device Discoverability Request"); return; } p2p_send_dev_disc_resp(p2p, p2p->pending_dev_disc_dialog_token, p2p->pending_dev_disc_addr, p2p->pending_dev_disc_freq, success ? P2P_SC_SUCCESS : P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE); p2p->pending_dev_disc_dialog_token = 0; } void p2p_process_go_disc_req(struct p2p_data *p2p, const u8 *da, const u8 *sa, const u8 *data, size_t len, int rx_freq) { unsigned int tu; struct wpabuf *ies; p2p_dbg(p2p, "Received GO Discoverability Request - remain awake for 100 TU"); ies = p2p_build_probe_resp_ies(p2p); if (ies == NULL) return; /* Remain awake 100 TU on operating channel */ p2p->pending_client_disc_freq = rx_freq; tu = 100; if (p2p->cfg->start_listen(p2p->cfg->cb_ctx, rx_freq, 1024 * tu / 1000, ies) < 0) { p2p_dbg(p2p, "Failed to start listen mode for client discoverability"); } wpabuf_free(ies); }
{ "content_hash": "055e9347c980835cc1dc95f17465e15b", "timestamp": "", "source": "github", "line_count": 323, "max_line_length": 104, "avg_line_length": 26.712074303405572, "alnum_prop": 0.6614510894761243, "repo_name": "execunix/vinos", "id": "86bae1a2c0db8c1f41ca23e43553abd4181e622d", "size": "8842", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "external/bsd/wpa/dist/src/p2p/p2p_dev_disc.c", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package utils import "sync" type queuenode struct { data interface{} next *queuenode } // A Queue is a go-routine safe FIFO (first in first out) data stucture. type Queue struct { head *queuenode tail *queuenode count int lock *sync.Mutex } // NewQueue creates a new pointer to a new queue. func NewQueue() *Queue { q := &Queue{} q.lock = &sync.Mutex{} return q } // Len returns the number of elements in the queue (i.e. size/length) func (q *Queue) Len() int { q.lock.Lock() defer q.lock.Unlock() return q.count } // Push inserts a value at the end/tail of the queue. // Note: this function does mutate the queue. func (q *Queue) Push(item interface{}) { q.lock.Lock() defer q.lock.Unlock() n := &queuenode{data: item} if q.tail == nil { q.tail = n q.head = n } else { q.tail.next = n q.tail = n } q.count++ } // Poll returns the value at the front of the queue. // i.e. the oldest value in the queue. // Note: this function does mutate the queue. func (q *Queue) Poll() interface{} { q.lock.Lock() defer q.lock.Unlock() if q.head == nil { return nil } n := q.head q.head = n.next if q.head == nil { q.tail = nil } q.count-- return n.data } // Peek returns a read value at the front of the queue. // i.e. the oldest value in the queue. // Note: this function does NOT mutate the queue. func (q *Queue) Peek() interface{} { q.lock.Lock() defer q.lock.Unlock() n := q.head if n == nil { return nil } return n.data }
{ "content_hash": "1e9630c0c1fdaad83a2285f6635ba9de", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 72, "avg_line_length": 17.44705882352941, "alnum_prop": 0.6466621712744437, "repo_name": "bign8/pipelines", "id": "6d36fbda98dafc919377436bb1d18a655f462f6f", "size": "2682", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "utils/queue.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "61006" }, { "name": "Protocol Buffer", "bytes": "960" }, { "name": "Python", "bytes": "1689" }, { "name": "Shell", "bytes": "626" } ], "symlink_target": "" }
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInitdfcd7adf42024fd980ce2678c623269d::getLoader();
{ "content_hash": "8efe0d06c66d00277a982c3946de0ac5", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 75, "avg_line_length": 26.142857142857142, "alnum_prop": 0.7595628415300546, "repo_name": "ElPepe101/DistriTaxi", "id": "e5daf134a38a9d97e7609d818db1f15ed3fb98f5", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/autoload.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1230" }, { "name": "JavaScript", "bytes": "83326" }, { "name": "PHP", "bytes": "49603" } ], "symlink_target": "" }
/* */ "format cjs"; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable));
{ "content_hash": "e6a8a43d957dfbd382133133a1e82043", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 105, "avg_line_length": 31.528846153846153, "alnum_prop": 0.5806648368405002, "repo_name": "cfraz89/moonrock-js-starter", "id": "81bea31a7ad1cdd00af1c643ed680f6fc945aa7a", "size": "3279", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "jspm_packages/npm/[email protected]/src/core/subjects/subject.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "819" }, { "name": "JavaScript", "bytes": "3474632" }, { "name": "TypeScript", "bytes": "28525" } ], "symlink_target": "" }