code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/webui/diagnostics_ui/backend/telemetry_log.h" #include <sstream> #include <utility> #include "base/i18n/time_formatting.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" namespace ash { namespace diagnostics { namespace { const char kNewline[] = "\n"; // SystemInfo constants: const char kSystemInfoSectionName[] = "--- System Info ---"; const char kSystemInfoCurrentTimeTitle[] = "Snapshot Time: "; const char kSystemInfoBoardNameTitle[] = "Board Name: "; const char kSystemInfoMarketingNameTitle[] = "Marketing Name: "; const char kSystemInfoCpuModelNameTitle[] = "CpuModel Name: "; const char kSystemInfoTotalMemoryTitle[] = "Total Memory (kib): "; const char kSystemInfoCpuThreadCountTitle[] = "Thread Count: "; const char kSystemInfoCpuMaxClockSpeedTitle[] = "Cpu Max Clock Speed (kHz): "; const char kSystemInfoMilestoneVersionTitle[] = "Version: "; const char kSystemInfoHasBatteryTitle[] = "Has Battery: "; // BatteryChargeStatus constants: const char kBatteryChargeStatusSectionName[] = "--- Battery Charge Status ---"; const char kBatteryChargeStatusBatteryStateTitle[] = "Battery State: "; const char kBatteryChargeStatusPowerSourceTitle[] = "Power Source: "; const char kBatteryChargeStatusPowerTimeTitle[] = "Power Time: "; const char kBatteryChargeStatusCurrentNowTitle[] = "Current Now (mA): "; const char kBatteryChargeStatusChargeNowTitle[] = "Chage Now (mAh): "; // BatteryHealth constants: const char kBatteryHealthSectionName[] = "--- Battery Health ---"; const char kBatteryHealthChargeFullNowTitle[] = "Charge Full Now (mAh): "; const char kBatteryHealthChargeFullDesignTitle[] = "Charge Full Design (mAh): "; const char kBatteryHealthCycleCountTitle[] = "Cycle Count: "; const char kBatteryHealthWearPercentageTitle[] = "Wear Percentage: "; // MemoryUsage constants: const char kMemoryUsageSectionName[] = "--- Memory Usage ---"; const char kMemoryUsageTotalMemoryTitle[] = "Total Memory (kib): "; const char kMemoryUsageAvailableMemoryTitle[] = "Available Memory (kib): "; const char kMemoryUsageFreeMemoryTitle[] = "Free Memory (kib): "; // CpuUsage constants: const char kCpuUsageSectionName[] = "--- Cpu Usage ---"; const char kCpuUsageUserTitle[] = "Usage User (%): "; const char kCpuUsageSystemTitle[] = "Usage System (%): "; const char kCpuUsageFreeTitle[] = "Usage Free (%): "; const char kCpuUsageAvgTempTitle[] = "Avg Temp (C): "; const char kCpuUsageScalingFrequencyTitle[] = "Current scaled frequency (kHz): "; std::string GetCurrentDateTimeWithTimeZoneAsString() { return base::UTF16ToUTF8( base::TimeFormatShortDateAndTimeWithTimeZone(base::Time::Now())); } } // namespace TelemetryLog::TelemetryLog() = default; TelemetryLog::~TelemetryLog() = default; void TelemetryLog::UpdateSystemInfo(mojom::SystemInfoPtr latest_system_info) { latest_system_info_ = std::move(latest_system_info); } void TelemetryLog::UpdateBatteryChargeStatus( mojom::BatteryChargeStatusPtr latest_battery_charge_status) { latest_battery_charge_status_ = std::move(latest_battery_charge_status); } void TelemetryLog::UpdateBatteryHealth( mojom::BatteryHealthPtr latest_battery_health) { latest_battery_health_ = std::move(latest_battery_health); } void TelemetryLog::UpdateMemoryUsage( mojom::MemoryUsagePtr latest_memory_usage) { latest_memory_usage_ = std::move(latest_memory_usage); } void TelemetryLog::UpdateCpuUsage(mojom::CpuUsagePtr latest_cpu_usage) { latest_cpu_usage_ = std::move(latest_cpu_usage); } std::string TelemetryLog::GetContents() const { std::stringstream output; if (latest_system_info_) { output << kSystemInfoSectionName << kNewline << kSystemInfoCurrentTimeTitle << GetCurrentDateTimeWithTimeZoneAsString() << kNewline << kSystemInfoBoardNameTitle << latest_system_info_->board_name << kNewline << kSystemInfoMarketingNameTitle << latest_system_info_->marketing_name << kNewline << kSystemInfoCpuModelNameTitle << latest_system_info_->cpu_model_name << kNewline << kSystemInfoTotalMemoryTitle << latest_system_info_->total_memory_kib << kNewline << kSystemInfoCpuThreadCountTitle << latest_system_info_->cpu_threads_count << kNewline << kSystemInfoCpuMaxClockSpeedTitle << latest_system_info_->cpu_max_clock_speed_khz << kNewline << kSystemInfoMilestoneVersionTitle << latest_system_info_->version_info->full_version_string << kNewline << kSystemInfoHasBatteryTitle << ((latest_system_info_->device_capabilities->has_battery) ? "true" : "false") << kNewline << kNewline; } if (latest_battery_charge_status_) { output << kBatteryChargeStatusSectionName << kNewline << kBatteryChargeStatusBatteryStateTitle << latest_battery_charge_status_->battery_state << kNewline << kBatteryChargeStatusPowerSourceTitle << latest_battery_charge_status_->power_adapter_status << kNewline << kBatteryChargeStatusPowerTimeTitle << latest_battery_charge_status_->power_time << kNewline << kBatteryChargeStatusCurrentNowTitle << latest_battery_charge_status_->current_now_milliamps << kNewline << kBatteryChargeStatusChargeNowTitle << latest_battery_charge_status_->charge_now_milliamp_hours << kNewline << kNewline; } if (latest_battery_health_) { output << kBatteryHealthSectionName << kNewline << kBatteryHealthChargeFullNowTitle << latest_battery_health_->charge_full_now_milliamp_hours << kNewline << kBatteryHealthChargeFullDesignTitle << latest_battery_health_->charge_full_design_milliamp_hours << kNewline << kBatteryHealthCycleCountTitle << latest_battery_health_->cycle_count << kNewline << kBatteryHealthWearPercentageTitle << base::NumberToString( latest_battery_health_->battery_wear_percentage) << kNewline << kNewline; } if (latest_memory_usage_) { output << kMemoryUsageSectionName << kNewline << kMemoryUsageTotalMemoryTitle << latest_memory_usage_->total_memory_kib << kNewline << kMemoryUsageAvailableMemoryTitle << latest_memory_usage_->available_memory_kib << kNewline << kMemoryUsageFreeMemoryTitle << latest_memory_usage_->free_memory_kib << kNewline << kNewline; } if (latest_cpu_usage_) { output << kCpuUsageSectionName << kNewline << kCpuUsageUserTitle << base::NumberToString(latest_cpu_usage_->percent_usage_user) << kNewline << kCpuUsageSystemTitle << base::NumberToString(latest_cpu_usage_->percent_usage_system) << kNewline << kCpuUsageFreeTitle << base::NumberToString(latest_cpu_usage_->percent_usage_free) << kNewline << kCpuUsageAvgTempTitle << latest_cpu_usage_->average_cpu_temp_celsius << kNewline << kCpuUsageScalingFrequencyTitle << latest_cpu_usage_->scaling_current_frequency_khz << kNewline << kNewline; } return output.str(); } } // namespace diagnostics } // namespace ash
ric2b/Vivaldi-browser
chromium/ash/webui/diagnostics_ui/backend/telemetry_log.cc
C++
bsd-3-clause
7,539
/* * MPC85xx cpu type detection * * Copyright 2011-2012 Freescale Semiconductor, Inc. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #ifndef __ASM_PPC_MPC85XX_H #define __ASM_PPC_MPC85XX_H #define SVR_REV(svr) ((svr) & 0xFF) /* SOC design resision */ #define SVR_MAJ(svr) (((svr) >> 4) & 0xF) /* Major revision field*/ #define SVR_MIN(svr) (((svr) >> 0) & 0xF) /* Minor revision field*/ /* Some parts define SVR[0:23] as the SOC version */ #define SVR_SOC_VER(svr) (((svr) >> 8) & 0xFFF7FF) /* SOC Version fields */ #define SVR_8533 0x803400 #define SVR_8535 0x803701 #define SVR_8536 0x803700 #define SVR_8540 0x803000 #define SVR_8541 0x807200 #define SVR_8543 0x803200 #define SVR_8544 0x803401 #define SVR_8545 0x803102 #define SVR_8547 0x803101 #define SVR_8548 0x803100 #define SVR_8555 0x807100 #define SVR_8560 0x807000 #define SVR_8567 0x807501 #define SVR_8568 0x807500 #define SVR_8569 0x808000 #define SVR_8572 0x80E000 #define SVR_P1010 0x80F100 #define SVR_P1011 0x80E500 #define SVR_P1012 0x80E501 #define SVR_P1013 0x80E700 #define SVR_P1014 0x80F101 #define SVR_P1017 0x80F700 #define SVR_P1020 0x80E400 #define SVR_P1021 0x80E401 #define SVR_P1022 0x80E600 #define SVR_P1023 0x80F600 #define SVR_P1024 0x80E402 #define SVR_P1025 0x80E403 #define SVR_P2010 0x80E300 #define SVR_P2020 0x80E200 #define SVR_P2040 0x821000 #define SVR_P2041 0x821001 #define SVR_P3041 0x821103 #define SVR_P4040 0x820100 #define SVR_P4080 0x820000 #define SVR_P5010 0x822100 #define SVR_P5020 0x822000 #define SVR_P5021 0X820500 #define SVR_P5040 0x820400 #define SVR_T4240 0x824000 #define SVR_T4120 0x824001 #define SVR_T4160 0x824100 #define SVR_C291 0x850000 #define SVR_C292 0x850020 #define SVR_C293 0x850030 #define SVR_B4860 0X868000 #define SVR_G4860 0x868001 #define SVR_G4060 0x868003 #define SVR_B4440 0x868100 #define SVR_G4440 0x868101 #define SVR_B4420 0x868102 #define SVR_B4220 0x868103 #define SVR_T1040 0x852000 #define SVR_T1041 0x852001 #define SVR_T1042 0x852002 #define SVR_T1020 0x852100 #define SVR_T1021 0x852101 #define SVR_T1022 0x852102 #define SVR_8610 0x80A000 #define SVR_8641 0x809000 #define SVR_8641D 0x809001 #define SVR_9130 0x860001 #define SVR_9131 0x860000 #define SVR_9132 0x861000 #define SVR_9232 0x861400 #define SVR_Unknown 0xFFFFFF #endif
ziqiaozhou/cachebar
source/arch/powerpc/include/asm/mpc85xx.h
C
gpl-2.0
2,500
#define _GNU_SOURCE #include <stdlib.h> #include <string.h> #include <search.h> /* open addressing hash table with 2^n table size quadratic probing is used in case of hash collision tab indices and hash are size_t after resize fails with ENOMEM the state of tab is still usable with the posix api items cannot be iterated and length cannot be queried */ #define MINSIZE 8 #define MAXSIZE ((size_t)-1/2 + 1) struct __tab { ENTRY *entries; size_t mask; size_t used; }; static struct hsearch_data htab; static int __hcreate_r(size_t, struct hsearch_data *); static void __hdestroy_r(struct hsearch_data *); static int __hsearch_r(ENTRY, ACTION, ENTRY **, struct hsearch_data *); static size_t keyhash(char *k) { unsigned char *p = (void *)k; size_t h = 0; while (*p) h = 31*h + *p++; return h; } static int resize(size_t nel, struct hsearch_data *htab) { size_t newsize; size_t i, j; ENTRY *e, *newe; ENTRY *oldtab = htab->__tab->entries; ENTRY *oldend = htab->__tab->entries + htab->__tab->mask + 1; if (nel > MAXSIZE) nel = MAXSIZE; for (newsize = MINSIZE; newsize < nel; newsize *= 2); htab->__tab->entries = calloc(newsize, sizeof *htab->__tab->entries); if (!htab->__tab->entries) { htab->__tab->entries = oldtab; return 0; } htab->__tab->mask = newsize - 1; if (!oldtab) return 1; for (e = oldtab; e < oldend; e++) if (e->key) { for (i=keyhash(e->key),j=1; ; i+=j++) { newe = htab->__tab->entries + (i & htab->__tab->mask); if (!newe->key) break; } *newe = *e; } free(oldtab); return 1; } int hcreate(size_t nel) { return __hcreate_r(nel, &htab); } void hdestroy(void) { __hdestroy_r(&htab); } static ENTRY *lookup(char *key, size_t hash, struct hsearch_data *htab) { size_t i, j; ENTRY *e; for (i=hash,j=1; ; i+=j++) { e = htab->__tab->entries + (i & htab->__tab->mask); if (!e->key || strcmp(e->key, key) == 0) break; } return e; } ENTRY *hsearch(ENTRY item, ACTION action) { ENTRY *e; __hsearch_r(item, action, &e, &htab); return e; } static int __hcreate_r(size_t nel, struct hsearch_data *htab) { int r; htab->__tab = calloc(1, sizeof *htab->__tab); if (!htab->__tab) return 0; r = resize(nel, htab); if (r == 0) { free(htab->__tab); htab->__tab = 0; } return r; } weak_alias(__hcreate_r, hcreate_r); static void __hdestroy_r(struct hsearch_data *htab) { if (htab->__tab) free(htab->__tab->entries); free(htab->__tab); htab->__tab = 0; } weak_alias(__hdestroy_r, hdestroy_r); static int __hsearch_r(ENTRY item, ACTION action, ENTRY **retval, struct hsearch_data *htab) { size_t hash = keyhash(item.key); ENTRY *e = lookup(item.key, hash, htab); if (e->key) { *retval = e; return 1; } if (action == FIND) { *retval = 0; return 0; } *e = item; if (++htab->__tab->used > htab->__tab->mask - htab->__tab->mask/4) { if (!resize(2*htab->__tab->used, htab)) { htab->__tab->used--; e->key = 0; *retval = 0; return 0; } e = lookup(item.key, hash, htab); } *retval = e; return 1; } weak_alias(__hsearch_r, hsearch_r);
heatd/Onyx
musl/src/search/hsearch.c
C
mit
3,065
require "spec_helper" describe Mongoid::Criteria::Queryable::Pipeline do describe "#__deep_copy" do let(:project) do { "$project" => { "name" => 1 }} end let(:pipeline) do described_class.new end before do pipeline.push(project) end let(:copied) do pipeline.__deep_copy__ end it "clones all the objects in the pipeline" do expect(copied.first).to_not equal(project) end it "clones the pipeline" do expect(copied).to_not equal(pipeline) end end describe "#group" do context "when the expression fields are not aliased" do let(:pipeline) do described_class.new end context "when using full notation" do before do pipeline.group(count: { "$sum" => 1 }, max: { "$max" => "likes" }) end it "adds the group operation to the pipeline" do expect(pipeline).to eq([ { "$group" => { "count" => { "$sum" => 1 }, "max" => { "$max" => "likes" }}} ]) end end context "when using symbol shortcuts" do before do pipeline.group(:count.sum => 1, :max.max => "likes") end it "adds the group operation to the pipeline" do expect(pipeline).to eq([ { "$group" => { "count" => { "$sum" => 1 }, "max" => { "$max" => "likes" }}} ]) end end end end describe "#initialize" do context "when provided aliases" do let(:aliases) do { "id" => "_id" } end let(:pipeline) do described_class.new(aliases) end it "sets the aliases" do expect(pipeline.aliases).to eq(aliases) end end context "when not provided aliases" do let(:pipeline) do described_class.new end it "sets the aliases to an empty hash" do expect(pipeline.aliases).to be_empty end end end describe "#project" do let(:pipeline) do described_class.new("id" => "_id") end context "when the field is not aliased" do before do pipeline.project(name: 1) end it "sets the aliased projection" do expect(pipeline).to eq([ { "$project" => { "name" => 1 }} ]) end end context "when the field is aliased" do before do pipeline.project(id: 1) end it "sets the aliased projection" do expect(pipeline).to eq([ { "$project" => { "_id" => 1 }} ]) end end end describe "#unwind" do let(:pipeline) do described_class.new("alias" => "a") end context "when provided a symbol" do context "when the symbol begins with $" do before do pipeline.unwind(:$author) end it "converts the symbol to a string" do expect(pipeline).to eq([{ "$unwind" => "$author" }]) end end context "when the symbol does not begin with $" do before do pipeline.unwind(:author) end it "converts the symbol to a string and prepends $" do expect(pipeline).to eq([{ "$unwind" => "$author" }]) end end end context "when provided a string" do context "when the string begins with $" do before do pipeline.unwind("$author") end it "sets the string" do expect(pipeline).to eq([{ "$unwind" => "$author" }]) end end context "when the string does not begin with $" do before do pipeline.unwind(:author) end it "prepends $ to the string" do expect(pipeline).to eq([{ "$unwind" => "$author" }]) end end end context "when provided a string alias" do context "when the string does not begin with $" do before do pipeline.unwind(:alias) end it "prepends $ to the string" do expect(pipeline).to eq([{ "$unwind" => "$a" }]) end end end end end
uniiverse/mongoid
spec/mongoid/criteria/queryable/pipeline_spec.rb
Ruby
mit
4,083
/** * @license AngularJS v1.7.1 * (c) 2010-2018 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular) {'use strict'; /** * @ngdoc module * @name ngCookies * @description * * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. * * See {@link ngCookies.$cookies `$cookies`} for usage. */ angular.module('ngCookies', ['ng']). info({ angularVersion: '1.7.1' }). /** * @ngdoc provider * @name $cookiesProvider * @description * Use `$cookiesProvider` to change the default behavior of the {@link ngCookies.$cookies $cookies} service. * */ provider('$cookies', [/** @this */function $CookiesProvider() { /** * @ngdoc property * @name $cookiesProvider#defaults * @description * * Object containing default options to pass when setting cookies. * * The object may have following properties: * * - **path** - `{string}` - The cookie will be available only for this path and its * sub-paths. By default, this is the URL that appears in your `<base>` tag. * - **domain** - `{string}` - The cookie will be available only for this domain and * its sub-domains. For security reasons the user agent will not accept the cookie * if the current domain is not a sub-domain of this domain or equal to it. * - **expires** - `{string|Date}` - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" * or a Date object indicating the exact date/time this cookie will expire. * - **secure** - `{boolean}` - If `true`, then the cookie will only be available through a * secured connection. * - **samesite** - `{string}` - prevents the browser from sending the cookie along with cross-site requests. * Accepts the values `lax` and `strict`. See the [OWASP Wiki](https://www.owasp.org/index.php/SameSite) * for more info. Note that as of May 2018, not all browsers support `SameSite`, * so it cannot be used as a single measure against Cross-Site-Request-Forgery (CSRF) attacks. * * Note: By default, the address that appears in your `<base>` tag will be used as the path. * This is important so that cookies will be visible for all routes when html5mode is enabled. * * @example * * ```js * angular.module('cookiesProviderExample', ['ngCookies']) * .config(['$cookiesProvider', function($cookiesProvider) { * // Setting default options * $cookiesProvider.defaults.domain = 'foo.com'; * $cookiesProvider.defaults.secure = true; * }]); * ``` **/ var defaults = this.defaults = {}; function calcOptions(options) { return options ? angular.extend({}, defaults, options) : defaults; } /** * @ngdoc service * @name $cookies * * @description * Provides read/write access to browser's cookies. * * <div class="alert alert-info"> * Up until AngularJS 1.3, `$cookies` exposed properties that represented the * current browser cookie values. In version 1.4, this behavior has changed, and * `$cookies` now provides a standard api of getters, setters etc. * </div> * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * angular.module('cookiesExample', ['ngCookies']) * .controller('ExampleController', ['$cookies', function($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.get('myFavorite'); * // Setting a cookie * $cookies.put('myFavorite', 'oatmeal'); * }]); * ``` */ this.$get = ['$$cookieReader', '$$cookieWriter', function($$cookieReader, $$cookieWriter) { return { /** * @ngdoc method * @name $cookies#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {string} Raw cookie value. */ get: function(key) { return $$cookieReader()[key]; }, /** * @ngdoc method * @name $cookies#getObject * * @description * Returns the deserialized value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ getObject: function(key) { var value = this.get(key); return value ? angular.fromJson(value) : value; }, /** * @ngdoc method * @name $cookies#getAll * * @description * Returns a key value object with all the cookies * * @returns {Object} All cookies */ getAll: function() { return $$cookieReader(); }, /** * @ngdoc method * @name $cookies#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {string} value Raw value to be stored. * @param {Object=} options Options object. * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} */ put: function(key, value, options) { $$cookieWriter(key, value, calcOptions(options)); }, /** * @ngdoc method * @name $cookies#putObject * * @description * Serializes and sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. * @param {Object=} options Options object. * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} */ putObject: function(key, value, options) { this.put(key, angular.toJson(value), options); }, /** * @ngdoc method * @name $cookies#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. * @param {Object=} options Options object. * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} */ remove: function(key, options) { $$cookieWriter(key, undefined, calcOptions(options)); } }; }]; }]); /** * @name $$cookieWriter * @requires $document * * @description * This is a private service for writing cookies * * @param {string} name Cookie name * @param {string=} value Cookie value (if undefined, cookie will be deleted) * @param {Object=} options Object with options that need to be stored for the cookie. */ function $$CookieWriter($document, $log, $browser) { var cookiePath = $browser.baseHref(); var rawDocument = $document[0]; function buildCookieString(name, value, options) { var path, expires; options = options || {}; expires = options.expires; path = angular.isDefined(options.path) ? options.path : cookiePath; if (angular.isUndefined(value)) { expires = 'Thu, 01 Jan 1970 00:00:00 GMT'; value = ''; } if (angular.isString(expires)) { expires = new Date(expires); } var str = encodeURIComponent(name) + '=' + encodeURIComponent(value); str += path ? ';path=' + path : ''; str += options.domain ? ';domain=' + options.domain : ''; str += expires ? ';expires=' + expires.toUTCString() : ''; str += options.secure ? ';secure' : ''; str += options.samesite ? ';samesite=' + options.samesite : ''; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie var cookieLength = str.length + 1; if (cookieLength > 4096) { $log.warn('Cookie \'' + name + '\' possibly not set or overflowed because it was too large (' + cookieLength + ' > 4096 bytes)!'); } return str; } return function(name, value, options) { rawDocument.cookie = buildCookieString(name, value, options); }; } $$CookieWriter.$inject = ['$document', '$log', '$browser']; angular.module('ngCookies').provider('$$cookieWriter', /** @this */ function $$CookieWriterProvider() { this.$get = $$CookieWriter; }); })(window, window.angular);
seogi1004/cdnjs
ajax/libs/angular.js/1.7.1/angular-cookies.js
JavaScript
mit
8,463
{ "locales.en": "English", "locales.zh-CN": "Chinese(Simplified)", "i18n": "Internationalization and Localization" }
Seldszar/lusty
test/hooks/i18n/fixtures/en.js
JavaScript
mit
123
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'specialchar', 'no', { options: 'Alternativer for spesialtegn', title: 'Velg spesialtegn', toolbar: 'Sett inn spesialtegn' });
webmasterETSI/web
web/ckeditor/plugins/specialchar/lang/no.js
JavaScript
mit
313
module PageObject module Platforms module SeleniumWebDriver module Form # # Submit the form. # def submit element.submit end end end end end
bootstraponline/page_object
lib/page-object/platforms/selenium_webdriver/form.rb
Ruby
mit
217
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX _typeInfo XX XX XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ /***************************************************************************** This header file is named _typeInfo.h to be distinguished from typeinfo.h in the NT SDK ******************************************************************************/ /*****************************************************************************/ #ifndef _TYPEINFO_H_ #define _TYPEINFO_H_ /*****************************************************************************/ enum ti_types { #define DEF_TI(ti, nm) ti, #include "titypes.h" #undef DEF_TI TI_ONLY_ENUM = TI_METHOD, //Enum values above this are completely described by the enumeration TI_COUNT }; #if defined(_TARGET_64BIT_) #define TI_I_IMPL TI_LONG #else #define TI_I_IMPL TI_INT #endif #ifdef DEBUG #if VERBOSE_VERIFY #define TI_DUMP_PADDING " " #ifdef _MSC_VER namespace { #endif // _MSC_VER SELECTANY const char* g_ti_type_names_map[] = { #define DEF_TI(ti, nm) nm, #include "titypes.h" #undef DEF_TI }; #ifdef _MSC_VER } #endif // _MSC_VER #endif // VERBOSE_VERIFY #endif // DEBUG #ifdef _MSC_VER namespace { #endif // _MSC_VER SELECTANY const ti_types g_jit_types_map[] = { #define DEF_TP(tn,nm,jitType,verType,sz,sze,asze,st,al,tf,howUsed) verType, #include "typelist.h" #undef DEF_TP }; #ifdef _MSC_VER } #endif // _MSC_VER #ifdef DEBUG #if VERBOSE_VERIFY inline const char* tiType2Str(ti_types type) { return g_ti_type_names_map[type]; } #endif // VERBOSE_VERIFY #endif // DEBUG // typeInfo does not care about distinction between signed/unsigned // This routine converts all unsigned types to signed ones inline ti_types varType2tiType(var_types type) { assert(g_jit_types_map[TYP_BYTE] == TI_BYTE); assert(g_jit_types_map[TYP_INT] == TI_INT); assert(g_jit_types_map[TYP_UINT] == TI_INT); assert(g_jit_types_map[TYP_FLOAT] == TI_FLOAT); assert(g_jit_types_map[TYP_BYREF] == TI_ERROR); assert(g_jit_types_map[type] != TI_ERROR); return g_jit_types_map[type]; } #ifdef _MSC_VER namespace { #endif // _MSC_VER SELECTANY const ti_types g_ti_types_map[CORINFO_TYPE_COUNT] = { // see the definition of enum CorInfoType in file inc/corinfo.h TI_ERROR, // CORINFO_TYPE_UNDEF = 0x0, TI_ERROR, // CORINFO_TYPE_VOID = 0x1, TI_BYTE, // CORINFO_TYPE_BOOL = 0x2, TI_SHORT, // CORINFO_TYPE_CHAR = 0x3, TI_BYTE, // CORINFO_TYPE_BYTE = 0x4, TI_BYTE, // CORINFO_TYPE_UBYTE = 0x5, TI_SHORT, // CORINFO_TYPE_SHORT = 0x6, TI_SHORT, // CORINFO_TYPE_USHORT = 0x7, TI_INT, // CORINFO_TYPE_INT = 0x8, TI_INT, // CORINFO_TYPE_UINT = 0x9, TI_LONG, // CORINFO_TYPE_LONG = 0xa, TI_LONG, // CORINFO_TYPE_ULONG = 0xb, TI_I_IMPL, // CORINFO_TYPE_NATIVEINT = 0xc, TI_I_IMPL, // CORINFO_TYPE_NATIVEUINT = 0xd, TI_FLOAT, // CORINFO_TYPE_FLOAT = 0xe, TI_DOUBLE, // CORINFO_TYPE_DOUBLE = 0xf, TI_REF, // CORINFO_TYPE_STRING = 0x10, TI_ERROR, // CORINFO_TYPE_PTR = 0x11, TI_ERROR, // CORINFO_TYPE_BYREF = 0x12, TI_STRUCT, // CORINFO_TYPE_VALUECLASS = 0x13, TI_REF, // CORINFO_TYPE_CLASS = 0x14, TI_STRUCT, // CORINFO_TYPE_REFANY = 0x15, TI_REF, // CORINFO_TYPE_VAR = 0x16, }; #ifdef _MSC_VER } #endif // _MSC_VER // Convert the type returned from the VM to a ti_type. inline ti_types JITtype2tiType(CorInfoType type) { // spot check to make certain enumerations have not changed assert(g_ti_types_map[CORINFO_TYPE_CLASS] == TI_REF); assert(g_ti_types_map[CORINFO_TYPE_BYREF] == TI_ERROR); assert(g_ti_types_map[CORINFO_TYPE_DOUBLE] == TI_DOUBLE); assert(g_ti_types_map[CORINFO_TYPE_VALUECLASS] == TI_STRUCT); assert(g_ti_types_map[CORINFO_TYPE_STRING] == TI_REF); type = CorInfoType(type & CORINFO_TYPE_MASK); // strip off modifiers assert(type < CORINFO_TYPE_COUNT); assert(g_ti_types_map[type] != TI_ERROR || type == CORINFO_TYPE_VOID); return g_ti_types_map[type]; }; /***************************************************************************** * Declares the typeInfo class, which represents the type of an entity on the * stack, in a local variable or an argument. * * Flags: LLLLLLLLLLLLLLLLffffffffffTTTTTT * * L = local var # or instance field # * x = unused * f = flags * T = type * * The lower bits are used to store the type component, and may be one of: * * TI_* (primitive) - see tyelist.h for enumeration (BYTE, SHORT, INT..) * TI_REF - OBJREF / ARRAY use m_cls for the type * (including arrays and null objref) * TI_STRUCT - VALUE type, use m_cls for the actual type * * NOTE carefully that BYREF info is not stored here. You will never see a * TI_BYREF in this component. For example, the type component * of a "byref TI_INT" is TI_FLAG_BYREF | TI_INT. * * NOTE carefully that Generic Type Variable info is * only stored here in part. Values of type "T" (e.g "!0" in ILASM syntax), * i.e. some generic variable type, appear only when verifying generic * code. They come in two flavours: unboxed and boxed. Unboxed * is the norm, e.g. a local, field or argument of type T. Boxed * values arise from an IL instruction such as "box !0". * The EE provides type handles for each different type * variable and the EE's "canCast" operation decides casting * for boxed type variable. Thus: * * (TI_REF, <type-variable-type-handle>) == boxed type variable * * (TI_REF, <type-variable-type-handle>) * + TI_FLAG_GENERIC_TYPE_VAR == unboxed type variable * * Using TI_REF for these may seem odd but using TI_STRUCT means the * code-generation parts of the importer get confused when they * can't work out the size, GC-ness etc. of the "struct". So using TI_REF * just tricks these backend parts into generating pseudo-trees for * the generic code we're verifying. These trees then get thrown away * anyway as we do verification of genreic code in import-only mode. * */ // TI_COUNT is less than or equal to TI_FLAG_DATA_MASK #define TI_FLAG_DATA_BITS 6 #define TI_FLAG_DATA_MASK ((1 << TI_FLAG_DATA_BITS)-1) // Flag indicating this item is uninitialized // Note that if UNINIT and BYREF are both set, // it means byref (uninit x) - i.e. we are pointing to an uninit <something> #define TI_FLAG_UNINIT_OBJREF 0x00000040 // Flag indicating this item is a byref <something> #define TI_FLAG_BYREF 0x00000080 // This item is a byref generated using the readonly. prefix // to a ldelema or Address function on an array type. The // runtime type check is ignored in these cases, but the // resulting byref can only be used in order to perform a // constraint call. #define TI_FLAG_BYREF_READONLY 0x00000100 // This item is the MSIL 'I' type which is pointer-sized // (different size depending on platform) but which on ALL platforms // is implicitly convertible with a 32-bit int but not with a 64-bit one. // Note: this flag is currently used only in 64-bit systems to annotate // native int types. In 32 bits, since you can transparently coalesce int32 // and native-int and both are the same size, JIT32 had no need to model // native-ints as a separate entity. For 64-bit though, since they have // different size, it's important to discern between a long and a native int // since conversions between them are not verifiable. #define TI_FLAG_NATIVE_INT 0x00000200 // This item contains the 'this' pointer (used for tracking) #define TI_FLAG_THIS_PTR 0x00001000 // This item is a byref to something which has a permanent home // (e.g. a static field, or instance field of an object in GC heap, as // opposed to the stack or a local variable). TI_FLAG_BYREF must also be // set. This information is useful for tail calls and return byrefs. // // Instructions that generate a permanent home byref: // // ldelema // ldflda of a ref object or another permanent home byref // array element address Get() helper // call or calli to a method that returns a byref and is verifiable or SkipVerify // dup // unbox #define TI_FLAG_BYREF_PERMANENT_HOME 0x00002000 // This is for use when verifying generic code. // This indicates that the type handle is really an unboxed // generic type variable (e.g. the result of loading an argument // of type T in a class List<T>). Without this flag // the same type handle indicates a boxed generic value, // e.g. the result of a "box T" instruction. #define TI_FLAG_GENERIC_TYPE_VAR 0x00004000 // Number of bits local var # is shifted #define TI_FLAG_LOCAL_VAR_SHIFT 16 #define TI_FLAG_LOCAL_VAR_MASK 0xFFFF0000 // Field info uses the same space as the local info #define TI_FLAG_FIELD_SHIFT TI_FLAG_LOCAL_VAR_SHIFT #define TI_FLAG_FIELD_MASK TI_FLAG_LOCAL_VAR_MASK #define TI_ALL_BYREF_FLAGS (TI_FLAG_BYREF| \ TI_FLAG_BYREF_READONLY | \ TI_FLAG_BYREF_PERMANENT_HOME) /***************************************************************************** * A typeInfo can be one of several types: * - A primitive type (I4,I8,R4,R8,I) * - A type (ref, array, value type) (m_cls describes the type) * - An array (m_cls describes the array type) * - A byref (byref flag set, otherwise the same as the above), * - A Function Pointer (m_method) * - A byref local variable (byref and byref local flags set), can be * uninitialized * * The reason that there can be 2 types of byrefs (general byrefs, and byref * locals) is that byref locals initially point to uninitialized items. * Therefore these byrefs must be tracked specialy. */ class typeInfo { private: union { struct { ti_types type : 6; unsigned uninitobj : 1; // used unsigned byref : 1; // used unsigned byref_readonly : 1; // used unsigned nativeInt : 1; // used unsigned : 2; // unused unsigned thisPtr : 1; // used unsigned thisPermHome : 1; // used unsigned generic_type_var : 1; // used } m_bits; DWORD m_flags; }; union { CORINFO_CLASS_HANDLE m_cls; // Valid only for type TI_METHOD CORINFO_METHOD_HANDLE m_method; }; public: typeInfo():m_flags(TI_ERROR) { m_cls = NO_CLASS_HANDLE; } typeInfo(ti_types tiType) { assert((tiType >= TI_BYTE) && (tiType <= TI_NULL)); assert(tiType <= TI_FLAG_DATA_MASK); m_flags = (DWORD) tiType; m_cls = NO_CLASS_HANDLE; } typeInfo(var_types varType) { m_flags = (DWORD) varType2tiType(varType); m_cls = NO_CLASS_HANDLE; } static typeInfo nativeInt() { typeInfo result = typeInfo(TI_I_IMPL); #ifdef _TARGET_64BIT_ result.m_flags |= TI_FLAG_NATIVE_INT; #endif return result; } typeInfo(ti_types tiType, CORINFO_CLASS_HANDLE cls, bool typeVar = false) { assert(tiType == TI_STRUCT || tiType == TI_REF); assert(cls != 0 && cls != CORINFO_CLASS_HANDLE(NOT_WIN64(0xcccccccc) WIN64_ONLY(0xcccccccccccccccc))); m_flags = tiType; if (typeVar) m_flags |= TI_FLAG_GENERIC_TYPE_VAR; m_cls = cls; } typeInfo(CORINFO_METHOD_HANDLE method) { assert(method != 0 && method != CORINFO_METHOD_HANDLE(NOT_WIN64(0xcccccccc) WIN64_ONLY(0xcccccccccccccccc))); m_flags = TI_METHOD; m_method = method; } #ifdef DEBUG #if VERBOSE_VERIFY void Dump() const; #endif // VERBOSE_VERIFY #endif // DEBUG public: // Note that we specifically ignore the permanent byref here. The rationale is that // the type system doesn't know about this (it's jit only), ie, signatures don't specify if // a byref is safe, so they are fully equivalent for the jit, except for the RET instruction // , instructions that load safe byrefs and the stack merging logic, which need to know about // the bit static bool AreEquivalent(const typeInfo& li, const typeInfo& ti) { DWORD allFlags = TI_FLAG_DATA_MASK|TI_FLAG_BYREF|TI_FLAG_BYREF_READONLY|TI_FLAG_GENERIC_TYPE_VAR|TI_FLAG_UNINIT_OBJREF; #ifdef _TARGET_64BIT_ allFlags |= TI_FLAG_NATIVE_INT; #endif // _TARGET_64BIT_ if ((li.m_flags & allFlags) != (ti.m_flags & allFlags)) { return false; } unsigned type = li.m_flags & TI_FLAG_DATA_MASK; assert(TI_ERROR < TI_ONLY_ENUM); // TI_ERROR looks like it needs more than enum. This optimises the success case a bit if (type > TI_ONLY_ENUM) return true; if (type == TI_ERROR) return false; // TI_ERROR != TI_ERROR assert(li.m_cls != NO_CLASS_HANDLE && ti.m_cls != NO_CLASS_HANDLE); return li.m_cls == ti.m_cls; } #ifdef DEBUG // On 64-bit systems, nodes whose "proper" type is "native int" get labeled TYP_LONG. // In the verification type system, we always transform "native int" to "TI_LONG" with the // native int flag set. // Ideally, we would keep track of which nodes labeled "TYP_LONG" are really "native int", but // attempts to do that have proved too difficult. So in situations where we try to compare the // verification type system and the node type system, we use this method, which allows the specific // mismatch where "verTi" is TI_LONG with the native int flag and "nodeTi" is TI_LONG without the // native int flag set. static bool AreEquivalentModuloNativeInt(const typeInfo& verTi, const typeInfo& nodeTi) { if (AreEquivalent(verTi, nodeTi)) return true; // Otherwise... #ifdef _TARGET_64BIT_ return (nodeTi.IsType(TI_I_IMPL) && tiCompatibleWith(0, verTi, typeInfo::nativeInt(), true)) || (verTi.IsType(TI_I_IMPL) && tiCompatibleWith(0, typeInfo::nativeInt(), nodeTi, true)); #else // _TARGET_64BIT_ return false; #endif // !_TARGET_64BIT_ } #endif // DEBUG static BOOL tiMergeToCommonParent (COMP_HANDLE CompHnd, typeInfo *pDest, const typeInfo *pSrc, bool* changed) ; static BOOL tiCompatibleWith (COMP_HANDLE CompHnd, const typeInfo& child, const typeInfo& parent, bool normalisedForStack) ; static BOOL tiMergeCompatibleWith (COMP_HANDLE CompHnd, const typeInfo& child, const typeInfo& parent, bool normalisedForStack) ; ///////////////////////////////////////////////////////////////////////// // Operations ///////////////////////////////////////////////////////////////////////// void SetIsThisPtr() { m_flags |= TI_FLAG_THIS_PTR; assert(m_bits.thisPtr); } void ClearThisPtr() { m_flags &= ~(TI_FLAG_THIS_PTR); } void SetIsPermanentHomeByRef() { assert(IsByRef()); m_flags |= TI_FLAG_BYREF_PERMANENT_HOME; } void SetIsReadonlyByRef() { assert(IsByRef()); m_flags |= TI_FLAG_BYREF_READONLY; } // Set that this item is uninitialized. void SetUninitialisedObjRef() { assert((IsObjRef() && IsThisPtr())); // For now, this is used only to track uninit this ptrs in ctors m_flags |= TI_FLAG_UNINIT_OBJREF; assert(m_bits.uninitobj); } // Set that this item is initialised. void SetInitialisedObjRef() { assert((IsObjRef() && IsThisPtr())); // For now, this is used only to track uninit this ptrs in ctors m_flags &= ~TI_FLAG_UNINIT_OBJREF; } typeInfo& DereferenceByRef() { if (!IsByRef()) { m_flags = TI_ERROR; INDEBUG(m_cls = NO_CLASS_HANDLE); } m_flags &= ~(TI_FLAG_THIS_PTR | TI_ALL_BYREF_FLAGS); return *this; } typeInfo& MakeByRef() { assert(!IsByRef()); m_flags &= ~(TI_FLAG_THIS_PTR); m_flags |= TI_FLAG_BYREF; return *this; } // I1,I2 --> I4 // FLOAT --> DOUBLE // objref, arrays, byrefs, value classes are unchanged // typeInfo& NormaliseForStack() { switch (GetType()) { case TI_BYTE: case TI_SHORT: m_flags = TI_INT; break; case TI_FLOAT: m_flags = TI_DOUBLE; break; default: break; } return (*this); } ///////////////////////////////////////////////////////////////////////// // Getters ///////////////////////////////////////////////////////////////////////// CORINFO_CLASS_HANDLE GetClassHandle() const { return m_cls; } CORINFO_CLASS_HANDLE GetClassHandleForValueClass() const { assert(IsType(TI_STRUCT)); assert(m_cls != NO_CLASS_HANDLE); return m_cls; } CORINFO_CLASS_HANDLE GetClassHandleForObjRef() const { assert(IsType(TI_REF)); assert(m_cls != NO_CLASS_HANDLE); return m_cls; } CORINFO_METHOD_HANDLE GetMethod() const { assert(GetType() == TI_METHOD); return m_method; } // Get this item's type // If primitive, returns the primitive type (TI_*) // If not primitive, returns: // - TI_ERROR if a byref anything // - TI_REF if a class or array or null or a generic type variable // - TI_STRUCT if a value class ti_types GetType() const { if (m_flags & TI_FLAG_BYREF) return TI_ERROR; // objref/array/null (objref), value class, ptr, primitive return (ti_types)(m_flags & TI_FLAG_DATA_MASK); } BOOL IsType(ti_types type) const { assert(type != TI_ERROR); return (m_flags & (TI_FLAG_DATA_MASK|TI_FLAG_BYREF|TI_FLAG_BYREF_READONLY| TI_FLAG_BYREF_PERMANENT_HOME|TI_FLAG_GENERIC_TYPE_VAR)) == DWORD(type); } // Returns whether this is an objref BOOL IsObjRef() const { return IsType(TI_REF) || IsType(TI_NULL); } // Returns whether this is a by-ref BOOL IsByRef() const { return (m_flags & TI_FLAG_BYREF); } // Returns whether this is the this pointer BOOL IsThisPtr() const { return (m_flags & TI_FLAG_THIS_PTR); } BOOL IsUnboxedGenericTypeVar() const { return !IsByRef() && (m_flags & TI_FLAG_GENERIC_TYPE_VAR); } BOOL IsReadonlyByRef() const { return IsByRef() && (m_flags & TI_FLAG_BYREF_READONLY); } BOOL IsPermanentHomeByRef() const { return IsByRef() && (m_flags & TI_FLAG_BYREF_PERMANENT_HOME); } // Returns whether this is a method desc BOOL IsMethod() const { return (GetType() == TI_METHOD); } BOOL IsStruct() const { return IsType(TI_STRUCT); } // A byref value class is NOT a value class BOOL IsValueClass() const { return (IsStruct() || IsPrimitiveType()); } // Does not return true for primitives. Will return true for value types that behave // as primitives BOOL IsValueClassWithClsHnd() const { if ((GetType() == TI_STRUCT) || (m_cls && GetType() != TI_REF && GetType() != TI_METHOD && GetType() != TI_ERROR)) // necessary because if byref bit is set, we return TI_ERROR) { return TRUE; } else { return FALSE; } } // Returns whether this is an integer or real number // NOTE: Use NormaliseToPrimitiveType() if you think you may have a // System.Int32 etc., because those types are not considered number // types by this function. BOOL IsNumberType() const { ti_types Type = GetType(); // I1, I2, Boolean, character etc. cannot exist plainly - // everything is at least an I4 return (Type == TI_INT || Type == TI_LONG || Type == TI_DOUBLE); } // Returns whether this is an integer // NOTE: Use NormaliseToPrimitiveType() if you think you may have a // System.Int32 etc., because those types are not considered number // types by this function. BOOL IsIntegerType() const { ti_types Type = GetType(); // I1, I2, Boolean, character etc. cannot exist plainly - // everything is at least an I4 return (Type == TI_INT || Type == TI_LONG); } // Returns true whether this is an integer or a native int. BOOL IsIntOrNativeIntType() const { #ifdef _TARGET_64BIT_ return (GetType() == TI_INT) || AreEquivalent(*this, nativeInt()); #else return IsType(TI_INT); #endif } BOOL IsNativeIntType() const { return AreEquivalent(*this, nativeInt()); } // Returns whether this is a primitive type (not a byref, objref, // array, null, value class, invalid value) // May Need to normalise first (m/r/I4 --> I4) BOOL IsPrimitiveType() const { DWORD Type = GetType(); // boolean, char, u1,u2 never appear on the operand stack return (Type == TI_BYTE || Type == TI_SHORT || Type == TI_INT || Type == TI_LONG || Type == TI_FLOAT || Type == TI_DOUBLE); } // Returns whether this is the null objref BOOL IsNullObjRef() const { return (IsType(TI_NULL)); } // must be for a local which is an object type (i.e. has a slot >= 0) // for primitive locals, use the liveness bitmap instead // Note that this works if the error is 'Byref' BOOL IsDead() const { return (m_flags & (TI_FLAG_DATA_MASK)) == TI_ERROR; } BOOL IsUninitialisedObjRef() const { return (m_flags & TI_FLAG_UNINIT_OBJREF); } private: // used to make functions that return typeinfo efficient. typeInfo(DWORD flags, CORINFO_CLASS_HANDLE cls) { m_cls = cls; m_flags = flags; } friend typeInfo ByRef(const typeInfo& ti); friend typeInfo DereferenceByRef(const typeInfo& ti); friend typeInfo NormaliseForStack(const typeInfo& ti); }; inline typeInfo NormaliseForStack(const typeInfo& ti) { return typeInfo(ti).NormaliseForStack(); } // given ti make a byref to that type. inline typeInfo ByRef(const typeInfo& ti) { return typeInfo(ti).MakeByRef(); } // given ti which is a byref, return the type it points at inline typeInfo DereferenceByRef(const typeInfo& ti) { return typeInfo(ti).DereferenceByRef(); } /*****************************************************************************/ #endif // _TYPEINFO_H_ /*****************************************************************************/
sperling/coreclr
src/jit/_typeinfo.h
C
mit
24,786
module.exports = function (buf) { return Buffer.isBuffer(buf); }; module.exports.a = function () { return Buffer.from('abcd', 'hex'); };
substack/insert-module-globals
test/isbuffer/both.js
JavaScript
mit
145
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AbstractType, Type} from '../interface/type'; import {InjectionToken} from './injection_token'; /** * @description * * Token that can be used to retrieve an instance from an injector or through a query. * * @publicApi */ export type ProviderToken<T> = Type<T>|AbstractType<T>|InjectionToken<T>;
ocombe/angular
packages/core/src/di/provider_token.ts
TypeScript
mit
513
from ee.utils import test from ee.cli.main import get_test_app class CliTestCaseStack(test.EETestCase): def test_ee_cli(self): self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_remove_web(self): self.app = get_test_app(argv=['stack', 'remove', '--web']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_admin(self): self.app = get_test_app(argv=['stack', 'remove', '--admin']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_mail(self): self.app = get_test_app(argv=['stack', 'remove', '--mail']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_nginx(self): self.app = get_test_app(argv=['stack', 'remove', '--nginx']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_php(self): self.app = get_test_app(argv=['stack', 'remove', '--php']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_mysql(self): self.app = get_test_app(argv=['stack', 'remove', '--mysql']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_postfix(self): self.app = get_test_app(argv=['stack', 'remove', '--postfix']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_wpcli(self): self.app = get_test_app(argv=['stack', 'remove', '--wpcli']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_phpmyadmin(self): self.app = get_test_app(argv=['stack', 'remove', '--phpmyadmin']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_adminer(self): self.app = get_test_app(argv=['stack', 'remove', '--adminer']) self.app.setup() self.app.run() self.app.close() def test_ee_cli_stack_install_utils(self): self.app = get_test_app(argv=['stack', 'remove', '--utils']) self.app.setup() self.app.run() self.app.close()
rjdp/Easynginedemoplugin
tests/cli/test_stack_remove.py
Python
mit
2,304
'use strict'; var regex = require('../../configfile').regex; var _set_up = function (done) { this.flat = require('../../cfreader/flat'); done(); }; exports.load = { setUp: _set_up, 'module is required' : function (test) { test.expect(1); test.ok(this.flat); test.done(); }, 'has a load function': function(test) { test.expect(1); test.ok(typeof this.flat.load === 'function'); test.done(); }, 'throws when file is non-existent': function(test) { test.expect(2); try { this.flat.load('tests/config/non-existent.flat'); } catch (e) { test.equal(e.code, 'ENOENT'); test.ok(/no such file or dir/.test(e.message)); } test.done(); }, 'loads the test flat file, as list': function(test) { test.expect(1); var result = this.flat.load( 'tests/config/test.flat', 'list', null, regex); test.deepEqual(result, [ 'line1', 'line2', 'line3', 'line5' ]); test.done(); }, 'loads the test flat file, unspecified type': function(test) { test.expect(1); var result = this.flat.load( 'tests/config/test.flat', null, null, regex); test.deepEqual(result, 'line1'); test.done(); }, };
jaredj/Haraka
tests/cfreader/flat.js
JavaScript
mit
1,344
require 'tzinfo/timezone_definition' module TZInfo module Definitions module Africa module Kigali include TimezoneDefinition timezone 'Africa/Kigali' do |tz| tz.offset :o0, 7216, 0, :LMT tz.offset :o1, 7200, 0, :CAT tz.transition 1935, 5, :o1, 13110953849, 5400 end end end end end
dustin/seinfeld
vendor/tzinfo-0.3.11/lib/tzinfo/definitions/Africa/Kigali.rb
Ruby
mit
381
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CodeIgniter User Guide</title> <style type='text/css' media='all'>@import url('../userguide.css');</style> <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> <script type="text/javascript" src="../nav/nav.js"></script> <script type="text/javascript" src="../nav/prototype.lite.js"></script> <script type="text/javascript" src="../nav/moo.fx.js"></script> <script type="text/javascript" src="../nav/user_guide_menu.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> <meta name='author' content='ExpressionEngine Dev Team' /> <meta name='description' content='CodeIgniter User Guide' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> <div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> <div id="masthead"> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td><h1>CodeIgniter User Guide Version 2.2.3</h1></td> <td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td> </tr> </table> </div> <!-- END NAVIGATION --> <!-- START BREADCRUMB --> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td id="breadcrumb"> <a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp; <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp;Upgrading from 1.5.2 to 1.5.3 </td> <td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td> </tr> </table> <!-- END BREADCRUMB --> <br clear="all" /> <!-- START CONTENT --> <div id="content"> <h1>Upgrading from 1.5.2 to 1.5.3</h1> <p>Before performing an update you should take your site offline by replacing the index.php file with a static one.</p> <h2>Step 1: Update your CodeIgniter files</h2> <p>Replace these files and directories in your "system" folder with the new versions:</p> <ul> <li><dfn>system/database/drivers</dfn></li> <li><dfn>system/helpers</dfn></li> <li><dfn>system/libraries/Input.php</dfn></li> <li><dfn>system/libraries/Loader.php</dfn></li> <li><dfn>system/libraries/Profiler.php</dfn></li> <li><dfn>system/libraries/Table.php</dfn></li> </ul> <p class="important"><strong>Note:</strong> If you have any custom developed files in these folders please make copies of them first.</p> <h2>Step 2: Update your user guide</h2> <p>Please also replace your local copy of the user guide with the new version.</p> </div> <!-- END CONTENT --> <div id="footer"> <p> Previous Topic:&nbsp;&nbsp;<a href="index.html">Installation Instructions</a> &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; Next Topic:&nbsp;&nbsp;<a href="troubleshooting.html">Troubleshooting</a> </p> <p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 - 2014 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">EllisLab, Inc.</a> &nbsp;&middot;&nbsp; Copyright &#169; 2014 - 2015 &nbsp;&middot;&nbsp; <a href="http://bcit.ca/">British Columbia Institute of Technology</a></p> </div> </body> </html>
rafaellimati/limajacket
user_guide/installation/upgrade_153.html
HTML
mit
4,032
'use strict'; var deferred = require('../../../deferred'); module.exports = { Deferred: function (a) { var defer = deferred(), x = {}, y = { foo: x } , invoked = false; defer.resolve(y).get('foo').done(function (r) { invoked = true; a(r, x); }); a(invoked, true, "Resolved in current tick"); }, Promise: function (a) { var x = {}, y = { foo: x }; deferred(y).get('foo').done(function (r) { a(r, x); }); }, Nested: function (a) { var x = {}, y = { foo: { bar: x } }; deferred(y).get('foo', 'bar').done(function (r) { a(r, x); }); }, "Safe for extensions": function (a) { a.throws(function () { var x = deferred(); x.promise.get('foo').done(function () { throw new Error('Error'); }); x.resolve({ foo: 'bar' }); }); } };
xiaoyi910821/schedule
sample/demo_multi/node_modules/deferred/test/ext/promise/get.js
JavaScript
mit
785
/*! * Copyright (c) Metaways Infosystems GmbH, 2011 * LGPLv3, http://opensource.org/licenses/LGPL-3.0 */ Ext.ns('Ext.ux.AdvancedSearch'); Ext.ux.AdvancedSearch.NumberFilter = Ext.extend(Ext.ux.AdvancedSearch.Filter, { operators : ['>', '>=', '==', '!=', '<', '<='], defaultOperator : '==', defaultValue : '', initComponent : function() { Ext.ux.AdvancedSearch.NumberFilter.superclass.initComponent.call(this); } }); Ext.reg('ux.numberfilter', Ext.ux.AdvancedSearch.NumberFilter);
sidmahata/betacap
public_html/bundles/aimeosshop/client/extjs/lib/ext.ux/AdvancedSearch/NumberFilter.js
JavaScript
mit
517
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title></title> </head> <body> <h3>Nested Frame</h3> <p> <iframe id="three" src="nested_frame_3.html"></iframe> </p> </body> </html>
titusfortner/watir
spec/watirspec/html/nested_iframe_2.html
HTML
mit
228
// Load modules var Crypto = require('crypto'); var Fs = require('fs'); var Os = require('os'); var Path = require('path'); var Stream = require('stream'); var Zlib = require('zlib'); var Boom = require('boom'); var Content = require('content'); var Hoek = require('hoek'); var Pez = require('pez'); var Qs = require('qs'); var Wreck = require('wreck'); // Declare internals var internals = {}; exports.parse = function (req, tap, options, next) { Hoek.assert(options, 'Missing options'); Hoek.assert(options.parse !== undefined, 'Missing parse option setting'); Hoek.assert(options.output !== undefined, 'Missing output option setting'); var parser = new internals.Parser(req, tap, options, next); return parser.read(); }; internals.Parser = function (req, tap, options, next) { var self = this; this.req = req; this.settings = options; this.tap = tap; this.result = {}; this.next = function (err) { return next(err, self.result); }; }; internals.Parser.prototype.read = function () { var next = this.next; // Content size var req = this.req; var contentLength = req.headers['content-length']; if (this.settings.maxBytes !== undefined && contentLength && parseInt(contentLength, 10) > this.settings.maxBytes) { return next(Boom.badRequest('Payload content length greater than maximum allowed: ' + this.settings.maxBytes)); } // Content type var contentType = Content.type(this.settings.override || req.headers['content-type'] || this.settings.defaultContentType || 'application/octet-stream'); if (contentType.isBoom) { return next(contentType); } this.result.contentType = contentType; this.result.mime = contentType.mime; if (this.settings.allow && this.settings.allow.indexOf(contentType.mime) === -1) { return next(Boom.unsupportedMediaType()); } // Parse: true if (this.settings.parse === true) { return this.parse(contentType); } // Parse: false, 'gunzip' return this.raw(); }; internals.Parser.prototype.parse = function (contentType) { var self = this; var next = this.next; var output = this.settings.output; // Output: 'data', 'stream', 'file' var source = this.req; // Content-encoding var contentEncoding = source.headers['content-encoding']; if (contentEncoding === 'gzip' || contentEncoding === 'deflate') { var decoder = (contentEncoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate()); next = Hoek.once(next); // Modify next() for async events this.next = next; decoder.once('error', function (err) { return next(Boom.badRequest('Invalid compressed payload', err)); }); source = source.pipe(decoder); } // Tap request if (this.tap) { source = source.pipe(this.tap); } // Multipart if (this.result.contentType.mime === 'multipart/form-data') { return this.multipart(source, contentType); } // Output: 'stream' if (output === 'stream') { this.result.payload = source; return next(); } // Output: 'file' if (output === 'file') { this.writeFile(source, function (err, path, bytes) { if (err) { return next(err); } self.result.payload = { path: path, bytes: bytes }; return next(); }); return; } // Output: 'data' return Wreck.read(source, { timeout: this.settings.timeout, maxBytes: this.settings.maxBytes }, function (err, payload) { if (err) { return next(err); } internals.object(payload, self.result.contentType.mime, self.settings, function (err, result) { if (err) { self.result.payload = null; return next(err); } self.result.payload = result; return next(); }); }); }; internals.Parser.prototype.raw = function () { var self = this; var next = this.next; var output = this.settings.output; // Output: 'data', 'stream', 'file' var source = this.req; // Content-encoding if (this.settings.parse === 'gunzip') { var contentEncoding = source.headers['content-encoding']; if (contentEncoding === 'gzip' || contentEncoding === 'deflate') { var decoder = (contentEncoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate()); next = Hoek.once(next); // Modify next() for async events decoder.once('error', function (err) { return next(Boom.badRequest('Invalid compressed payload', err)); }); source = source.pipe(decoder); } } // Setup source if (this.tap) { source = source.pipe(this.tap); } // Output: 'stream' if (output === 'stream') { this.result.payload = source; return next(); } // Output: 'file' if (output === 'file') { this.writeFile(source, function (err, path, bytes) { if (err) { return next(err); } self.result.payload = { path: path, bytes: bytes }; return next(); }); return; } // Output: 'data' return Wreck.read(source, { timeout: this.settings.timeout, maxBytes: this.settings.maxBytes }, function (err, payload) { if (err) { return next(err); } self.result.payload = payload; return next(); }); }; internals.object = function (payload, mime, options, next) { // Binary if (mime === 'application/octet-stream') { return next(null, payload.length ? payload : null); } // Text if (mime.match(/^text\/.+$/)) { return next(null, payload.toString('utf8')); } // JSON if (/^application\/(?:.+\+)?json$/.test(mime)) { return internals.jsonParse(payload, next); // Isolate try...catch for V8 optimization } // Form-encoded if (mime === 'application/x-www-form-urlencoded') { return next(null, payload.length ? Qs.parse(payload.toString('utf8'), options.qs) : {}); } return next(Boom.unsupportedMediaType()); }; internals.jsonParse = function (payload, next) { if (!payload.length) { return next(null, null); } try { var parsed = JSON.parse(payload.toString('utf8')); } catch (err) { return next(Boom.badRequest('Invalid request payload JSON format', err)); } return next(null, parsed); }; internals.Parser.prototype.multipart = function (source, contentType) { var self = this; var next = this.next; next = Hoek.once(next); // Modify next() for async events this.next = next; var dispenser = new Pez.Dispenser(contentType); var onError = function (err) { return next(Boom.badRequest('Invalid multipart payload format', err)); }; dispenser.once('error', onError); var arrayFields = false; var data = {}; var finalize = function () { dispenser.removeListener('error', onError); dispenser.removeListener('part', onPart); dispenser.removeListener('field', onField); dispenser.removeListener('close', onClose); if (arrayFields) { data = Qs.parse(data, self.settings.qs); } self.result.payload = data; return next(); }; var set = function (name, value) { arrayFields = arrayFields || (name.indexOf('[') !== -1); if (!data.hasOwnProperty(name)) { data[name] = value; } else if (Array.isArray(data[name])) { data[name].push(value); } else { data[name] = [data[name], value]; } }; var pendingFiles = {}; var nextId = 0; var closed = false; var onPart = function (part) { if (self.settings.output === 'file') { // Output: 'file' var id = nextId++; pendingFiles[id] = true; self.writeFile(part, function (err, path, bytes) { delete pendingFiles[id]; if (err) { return next(err); } var item = { filename: part.filename, path: path, headers: part.headers, bytes: bytes }; set(part.name, item); if (closed && !Object.keys(pendingFiles).length) { return finalize(data); } }); } else { // Output: 'data' Wreck.read(part, {}, function (err, payload) { // err handled by dispenser.once('error') if (self.settings.output === 'stream') { // Output: 'stream' var item = Wreck.toReadableStream(payload); item.hapi = { filename: part.filename, headers: part.headers }; return set(part.name, item); } var ct = part.headers['content-type'] || ''; var mime = ct.split(';')[0].trim().toLowerCase(); if (!mime) { return set(part.name, payload); } if (!payload.length) { return set(part.name, {}); } internals.object(payload, mime, self.settings, function (err, result) { return set(part.name, err ? payload : result); }); }); } }; dispenser.on('part', onPart); var onField = function (name, value) { set(name, value); }; dispenser.on('field', onField); var onClose = function () { if (Object.keys(pendingFiles).length) { closed = true; return; } return finalize(data); }; dispenser.once('close', onClose); source.pipe(dispenser); }; internals.Parser.prototype.writeFile = function (stream, callback) { var self = this; var path = Hoek.uniqueFilename(this.settings.uploads || Os.tmpDir()); var file = Fs.createWriteStream(path, { flags: 'wx' }); var counter = new internals.Counter(); var finalize = Hoek.once(function (err) { self.req.removeListener('aborted', onAbort); file.removeListener('close', finalize); file.removeListener('error', finalize); if (!err) { return callback(null, path, counter.bytes); } file.destroy(); Fs.unlink(path, function (/* fsErr */) { // Ignore unlink errors return callback(err); }); }); file.once('close', finalize); file.once('error', finalize); var onAbort = function () { return finalize(Boom.badRequest('Client connection aborted')); }; this.req.once('aborted', onAbort); stream.pipe(counter).pipe(file); }; internals.Counter = function () { Stream.Transform.call(this); this.bytes = 0; }; Hoek.inherits(internals.Counter, Stream.Transform); internals.Counter.prototype._transform = function (chunk, encoding, next) { this.bytes += chunk.length; return next(null, chunk); };
Neener54/es6_tilt
test/dummy/app/assets/javascripts/node_modules/hapi/node_modules/subtext/lib/index.js
JavaScript
mit
11,853
using System; using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core.Cache; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; namespace Umbraco.Tests.Persistence.Repositories { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class TagRepositoryTest : TestWithDatabaseBase { [Test] public void Can_Perform_Add_On_Repository() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var repository = CreateRepository(provider); var tag = new Tag { Group = "Test", Text = "Test" }; repository.Save(tag); Assert.That(tag.HasIdentity, Is.True); } } [Test] public void Can_Perform_Multiple_Adds_On_Repository() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var repository = CreateRepository(provider); var tag = new Tag { Group = "Test", Text = "Test" }; repository.Save(tag); var tag2 = new Tag { Group = "Test", Text = "Test2" }; repository.Save(tag2); Assert.That(tag.HasIdentity, Is.True); Assert.That(tag2.HasIdentity, Is.True); Assert.AreNotEqual(tag.Id, tag2.Id); } } [Test] public void Can_Create_Tag_Relations() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); // create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content); var repository = CreateRepository(provider); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, }, false); Assert.AreEqual(2, repository.GetTagsForEntity(content.Id).Count()); } } [Test] public void Can_Append_Tag_Relations() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content); var repository = CreateRepository(provider); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, }, false); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"}, }, false); Assert.AreEqual(4, repository.GetTagsForEntity(content.Id).Count()); } } [Test] public void Can_Replace_Tag_Relations() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content); var repository = CreateRepository(provider); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, }, false); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"}, }, true); var result = repository.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(2, result.Length); Assert.AreEqual("tag3", result[0].Text); Assert.AreEqual("tag4", result[1].Text); } } [Test] public void Can_Merge_Tag_Relations() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content); var repository = CreateRepository(provider); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, }, false); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, }, false); var result = repository.GetTagsForEntity(content.Id); Assert.AreEqual(3, result.Count()); } } [Test] public void Can_Clear_Tag_Relations() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content); var repository = CreateRepository(provider); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, }, false); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, Enumerable.Empty<ITag>(), true); var result = repository.GetTagsForEntity(content.Id); Assert.AreEqual(0, result.Count()); } } [Test] public void Can_Remove_Specific_Tags_From_Property() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content); var repository = CreateRepository(provider); repository.Assign( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"} }, false); repository.Remove( content.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"} }); var result = repository.GetTagsForEntity(content.Id).ToArray(); Assert.AreEqual(2, result.Length); Assert.AreEqual("tag1", result[0].Text); Assert.AreEqual("tag4", result[1].Text); } } [Test] public void Can_Get_Tags_For_Content_By_Id() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var content2 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content2); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"} }, false); repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"} }, false); var result = repository.GetTagsForEntity(content2.Id); Assert.AreEqual(2, result.Count()); } } [Test] public void Can_Get_Tags_For_Content_By_Key() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var content2 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content2); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"} }, false); repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"} }, false); //get by key var result = repository.GetTagsForEntity(content2.Key); Assert.AreEqual(2, result.Count()); } } [Test] public void Can_Get_All() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var content2 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content2); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"} }, false); var result = repository.GetMany(); Assert.AreEqual(4, result.Count()); } } [Test] public void Can_Get_All_With_Ids() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var content2 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content2); var repository = CreateRepository(provider); var tags = new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"} }; repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, tags, false); // TODO: This would be nice to be able to map the ids back but unfortunately we are not doing this //var result = repository.GetAll(new[] {tags[0].Id, tags[1].Id, tags[2].Id}); var all = repository.GetMany().ToArray(); var result = repository.GetMany(all[0].Id, all[1].Id, all[2].Id); Assert.AreEqual(3, result.Count()); } } [Test] public void Can_Get_Tags_For_Content_For_Group() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var content2 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content2); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test1"} }, false); repository.Assign( content2.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"} }, false); var result = repository.GetTagsForEntity(content1.Id, "test1"); Assert.AreEqual(2, result.Count()); } } [Test] public void Can_Get_Tags_For_Property_By_Id() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"} }, false); repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"} }, false); var result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias).ToArray(); var result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias).ToArray(); Assert.AreEqual(4, result1.Length); Assert.AreEqual(2, result2.Length); } } [Test] public void Can_Get_Tags_For_Property_By_Key() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"} }, false); repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"} }, false); var result1 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.First().Alias).ToArray(); var result2 = repository.GetTagsForProperty(content1.Key, contentType.PropertyTypes.Last().Alias).ToArray(); Assert.AreEqual(4, result1.Length); Assert.AreEqual(2, result2.Length); } } [Test] public void Can_Get_Tags_For_Property_For_Group() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test1"} }, false); repository.Assign( content1.Id, contentType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"} }, false); var result1 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.First().Alias, "test1").ToArray(); var result2 = repository.GetTagsForProperty(content1.Id, contentType.PropertyTypes.Last().Alias, "test1").ToArray(); Assert.AreEqual(2, result1.Length); Assert.AreEqual(1, result2.Length); } } [Test] public void Can_Get_Tags_For_Entity_Type() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); var mediaRepository = CreateMediaRepository(provider, out var mediaTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var mediaType = MockedContentTypes.CreateImageMediaType("image2"); mediaTypeRepository.Save(mediaType); var media1 = MockedMedia.CreateMediaImage(mediaType, -1); mediaRepository.Save(media1); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"}, new Tag {Text = "tag3", Group = "test"} }, false); repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag4", Group = "test1"} }, false); var result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content).ToArray(); var result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media).ToArray(); var result3 = repository.GetTagsForEntityType(TaggableObjectTypes.All).ToArray(); Assert.AreEqual(3, result1.Length); Assert.AreEqual(2, result2.Length); Assert.AreEqual(4, result3.Length); Assert.AreEqual(1, result1.Single(x => x.Text == "tag1").NodeCount); Assert.AreEqual(2, result3.Single(x => x.Text == "tag1").NodeCount); Assert.AreEqual(1, result3.Single(x => x.Text == "tag4").NodeCount); } } [Test] public void Can_Get_Tags_For_Entity_Type_For_Group() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); var mediaRepository = CreateMediaRepository(provider, out var mediaTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var mediaType = MockedContentTypes.CreateImageMediaType("image2"); mediaTypeRepository.Save(mediaType); var media1 = MockedMedia.CreateMediaImage(mediaType, -1); mediaRepository.Save(media1); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test1"} }, false); repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"} }, false); var result1 = repository.GetTagsForEntityType(TaggableObjectTypes.Content, "test1").ToArray(); var result2 = repository.GetTagsForEntityType(TaggableObjectTypes.Media, "test1").ToArray(); Assert.AreEqual(2, result1.Length); Assert.AreEqual(1, result2.Length); } } [Test] public void Cascade_Deletes_Tag_Relations() { var provider = TestObjects.GetScopeProvider(Logger); using (var scope = ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test"}, new Tag {Text = "tag3", Group = "test"}, new Tag {Text = "tag4", Group = "test"} }, false); contentRepository.Delete(content1); Assert.AreEqual(0, scope.Database.ExecuteScalar<int>( "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId", new { nodeId = content1.Id, propTypeId = contentType.PropertyTypes.First().Id })); } } [Test] public void Can_Get_Tagged_Entities_For_Tag_Group() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); var mediaRepository = CreateMediaRepository(provider, out var mediaTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var content2 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content2); var mediaType = MockedContentTypes.CreateImageMediaType("image2"); mediaTypeRepository.Save(mediaType); var media1 = MockedMedia.CreateMediaImage(mediaType, -1); mediaRepository.Save(media1); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"}, new Tag {Text = "tag3", Group = "test"} }, false); repository.Assign( content2.Id, contentType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"}, new Tag {Text = "tag3", Group = "test"} }, false); repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"} }, false); var contentTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test").ToArray(); //there are two content items tagged against the 'test' group Assert.AreEqual(2, contentTestIds.Length); //there are a total of two property types tagged against the 'test' group Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).Count()); //there are a total of 2 tags tagged against the 'test' group Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); var contentTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, "test1").ToArray(); //there are two content items tagged against the 'test1' group Assert.AreEqual(2, contentTest1Ids.Length); //there are a total of two property types tagged against the 'test1' group Assert.AreEqual(2, contentTest1Ids.SelectMany(x => x.TaggedProperties).Count()); //there are a total of 1 tags tagged against the 'test1' group Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); var mediaTestIds = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test"); Assert.AreEqual(1, mediaTestIds.Count()); var mediaTest1Ids = repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, "test1"); Assert.AreEqual(1, mediaTest1Ids.Count()); } } [Test] public void Can_Get_Tagged_Entities_For_Tag() { var provider = TestObjects.GetScopeProvider(Logger); using (ScopeProvider.CreateScope()) { var contentRepository = CreateDocumentRepository(provider, out var contentTypeRepository); var mediaRepository = CreateMediaRepository(provider, out var mediaTypeRepository); //create data to relate to var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! contentTypeRepository.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content1); var content2 = MockedContent.CreateSimpleContent(contentType); contentRepository.Save(content2); var mediaType = MockedContentTypes.CreateImageMediaType("image2"); mediaTypeRepository.Save(mediaType); var media1 = MockedMedia.CreateMediaImage(mediaType, -1); mediaRepository.Save(media1); var repository = CreateRepository(provider); repository.Assign( content1.Id, contentType.PropertyTypes.First().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"}, new Tag {Text = "tag3", Group = "test"} }, false); repository.Assign( content2.Id, contentType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"}, }, false); repository.Assign( media1.Id, mediaType.PropertyTypes.Last().Id, new[] { new Tag {Text = "tag1", Group = "test"}, new Tag {Text = "tag2", Group = "test1"} }, false); var contentTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag1").ToArray(); //there are two content items tagged against the 'tag1' tag Assert.AreEqual(2, contentTestIds.Length); //there are a total of two property types tagged against the 'tag1' tag Assert.AreEqual(2, contentTestIds.SelectMany(x => x.TaggedProperties).Count()); //there are a total of 1 tags since we're only looking against one tag Assert.AreEqual(1, contentTestIds.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); var contentTest1Ids = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, "tag3").ToArray(); //there are 1 content items tagged against the 'tag3' tag Assert.AreEqual(1, contentTest1Ids.Length); //there are a total of two property types tagged against the 'tag3' tag Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).Count()); //there are a total of 1 tags since we're only looking against one tag Assert.AreEqual(1, contentTest1Ids.SelectMany(x => x.TaggedProperties).SelectMany(x => x.Tags).Select(x => x.Id).Distinct().Count()); var mediaTestIds = repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Media, "tag1"); Assert.AreEqual(1, mediaTestIds.Count()); } } private TagRepository CreateRepository(IScopeProvider provider) { return new TagRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); } private DocumentRepository CreateDocumentRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; var templateRepository = new TemplateRepository(accessor, AppCaches.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(accessor, AppCaches.Disabled, Logger); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches.Disabled); var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, Logger); contentTypeRepository = new ContentTypeRepository(accessor, AppCaches.Disabled, Logger, commonRepository, languageRepository); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, Logger); var entityRepository = new EntityRepository(accessor); var relationRepository = new RelationRepository(accessor, Logger, relationTypeRepository, entityRepository); var propertyEditors = new Lazy<PropertyEditorCollection>(() => new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty<IDataEditor>()))); var dataValueReferences = new DataValueReferenceFactoryCollection(Enumerable.Empty<IDataValueReferenceFactory>()); var repository = new DocumentRepository(accessor, AppCaches.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, relationRepository, relationTypeRepository, propertyEditors, dataValueReferences); return repository; } private MediaRepository CreateMediaRepository(IScopeProvider provider, out MediaTypeRepository mediaTypeRepository) { var accessor = (IScopeAccessor) provider; var templateRepository = new TemplateRepository(accessor, AppCaches.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(accessor, AppCaches.Disabled, Logger); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches.Disabled); var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, Logger); mediaTypeRepository = new MediaTypeRepository(accessor, AppCaches.Disabled, Logger, commonRepository, languageRepository); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, Logger); var entityRepository = new EntityRepository(accessor); var relationRepository = new RelationRepository(accessor, Logger, relationTypeRepository, entityRepository); var propertyEditors = new Lazy<PropertyEditorCollection>(() => new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty<IDataEditor>()))); var dataValueReferences = new DataValueReferenceFactoryCollection(Enumerable.Empty<IDataValueReferenceFactory>()); var repository = new MediaRepository(accessor, AppCaches.Disabled, Logger, mediaTypeRepository, tagRepository, Mock.Of<ILanguageRepository>(), relationRepository, relationTypeRepository, propertyEditors, dataValueReferences); return repository; } } }
tcmorris/Umbraco-CMS
src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs
C#
mit
45,035
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Logic { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// WorkflowVersionsOperations operations. /// </summary> public partial interface IWorkflowVersionsOperations { /// <summary> /// Gets a list of workflow versions. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='top'> /// The number of items to be included in the result. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<WorkflowVersion>>> ListWithHttpMessagesAsync(string resourceGroupName, string workflowName, int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a workflow version. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='versionId'> /// The workflow versionId. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<WorkflowVersion>> GetWithHttpMessagesAsync(string resourceGroupName, string workflowName, string versionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of workflow versions. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<WorkflowVersion>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
ayeletshpigelman/azure-sdk-for-net
sdk/logic/Microsoft.Azure.Management.Logic/src/Generated/IWorkflowVersionsOperations.cs
C#
mit
4,538
import os import os.path as op from io import BytesIO from nose.tools import eq_, ok_ from flask import Flask, url_for from flask_admin import form, helpers def _create_temp(): path = op.join(op.dirname(__file__), 'tmp') if not op.exists(path): os.mkdir(path) inner = op.join(path, 'inner') if not op.exists(inner): os.mkdir(inner) return path def safe_delete(path, name): try: os.remove(op.join(path, name)) except: pass def test_upload_field(): app = Flask(__name__) path = _create_temp() def _remove_testfiles(): safe_delete(path, 'test1.txt') safe_delete(path, 'test2.txt') class TestForm(form.BaseForm): upload = form.FileUploadField('Upload', base_path=path) class TestNoOverWriteForm(form.BaseForm): upload = form.FileUploadField('Upload', base_path=path, allow_overwrite=False) class Dummy(object): pass my_form = TestForm() eq_(my_form.upload.base_path, path) _remove_testfiles() dummy = Dummy() # Check upload with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 1'), 'test1.txt')}): my_form = TestForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, 'test1.txt') ok_(op.exists(op.join(path, 'test1.txt'))) # Check replace with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 2'), 'test2.txt')}): my_form = TestForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, 'test2.txt') ok_(not op.exists(op.join(path, 'test1.txt'))) ok_(op.exists(op.join(path, 'test2.txt'))) # Check delete with app.test_request_context(method='POST', data={'_upload-delete': 'checked'}): my_form = TestForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, None) ok_(not op.exists(op.join(path, 'test2.txt'))) # Check overwrite _remove_testfiles() my_form_ow = TestNoOverWriteForm() with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hullo'), 'test1.txt')}): my_form_ow = TestNoOverWriteForm(helpers.get_form_data()) ok_(my_form_ow.validate()) my_form_ow.populate_obj(dummy) eq_(dummy.upload, 'test1.txt') ok_(op.exists(op.join(path, 'test1.txt'))) with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hullo'), 'test1.txt')}): my_form_ow = TestNoOverWriteForm(helpers.get_form_data()) ok_(not my_form_ow.validate()) _remove_testfiles() def test_image_upload_field(): app = Flask(__name__) path = _create_temp() def _remove_testimages(): safe_delete(path, 'test1.png') safe_delete(path, 'test1_thumb.jpg') safe_delete(path, 'test2.png') safe_delete(path, 'test2_thumb.jpg') safe_delete(path, 'test1.jpg') safe_delete(path, 'test1.jpeg') safe_delete(path, 'test1.gif') safe_delete(path, 'test1.png') safe_delete(path, 'test1.tiff') class TestForm(form.BaseForm): upload = form.ImageUploadField('Upload', base_path=path, thumbnail_size=(100, 100, True)) class TestNoResizeForm(form.BaseForm): upload = form.ImageUploadField('Upload', base_path=path, endpoint='test') class TestAutoResizeForm(form.BaseForm): upload = form.ImageUploadField('Upload', base_path=path, max_size=(64, 64, True)) class Dummy(object): pass my_form = TestForm() eq_(my_form.upload.base_path, path) eq_(my_form.upload.endpoint, 'static') _remove_testimages() dummy = Dummy() # Check upload filename = op.join(op.dirname(__file__), 'data', 'copyleft.png') with open(filename, 'rb') as fp: with app.test_request_context(method='POST', data={'upload': (fp, 'test1.png')}): my_form = TestForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, 'test1.png') ok_(op.exists(op.join(path, 'test1.png'))) ok_(op.exists(op.join(path, 'test1_thumb.png'))) # Check replace with open(filename, 'rb') as fp: with app.test_request_context(method='POST', data={'upload': (fp, 'test2.png')}): my_form = TestForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, 'test2.png') ok_(op.exists(op.join(path, 'test2.png'))) ok_(op.exists(op.join(path, 'test2_thumb.png'))) ok_(not op.exists(op.join(path, 'test1.png'))) ok_(not op.exists(op.join(path, 'test1_thumb.jpg'))) # Check delete with app.test_request_context(method='POST', data={'_upload-delete': 'checked'}): my_form = TestForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, None) ok_(not op.exists(op.join(path, 'test2.png'))) ok_(not op.exists(op.join(path, 'test2_thumb.png'))) # Check upload no-resize with open(filename, 'rb') as fp: with app.test_request_context(method='POST', data={'upload': (fp, 'test1.png')}): my_form = TestNoResizeForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, 'test1.png') ok_(op.exists(op.join(path, 'test1.png'))) ok_(not op.exists(op.join(path, 'test1_thumb.png'))) # Check upload, auto-resize filename = op.join(op.dirname(__file__), 'data', 'copyleft.png') with open(filename, 'rb') as fp: with app.test_request_context(method='POST', data={'upload': (fp, 'test1.png')}): my_form = TestAutoResizeForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, 'test1.png') ok_(op.exists(op.join(path, 'test1.png'))) filename = op.join(op.dirname(__file__), 'data', 'copyleft.tiff') with open(filename, 'rb') as fp: with app.test_request_context(method='POST', data={'upload': (fp, 'test1.tiff')}): my_form = TestAutoResizeForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, 'test1.jpg') ok_(op.exists(op.join(path, 'test1.jpg'))) # check allowed extensions for extension in ('gif', 'jpg', 'jpeg', 'png', 'tiff'): filename = 'copyleft.' + extension filepath = op.join(op.dirname(__file__), 'data', filename) with open(filepath, 'rb') as fp: with app.test_request_context(method='POST', data={'upload': (fp, filename)}): my_form = TestNoResizeForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, my_form.upload.data.filename) # check case-sensitivity for extensions filename = op.join(op.dirname(__file__), 'data', 'copyleft.jpg') with open(filename, 'rb') as fp: with app.test_request_context(method='POST', data={'upload': (fp, 'copyleft.JPG')}): my_form = TestNoResizeForm(helpers.get_form_data()) ok_(my_form.validate()) def test_relative_path(): app = Flask(__name__) path = _create_temp() def _remove_testfiles(): safe_delete(path, 'test1.txt') class TestForm(form.BaseForm): upload = form.FileUploadField('Upload', base_path=path, relative_path='inner/') class Dummy(object): pass my_form = TestForm() eq_(my_form.upload.base_path, path) eq_(my_form.upload.relative_path, 'inner/') _remove_testfiles() dummy = Dummy() # Check upload with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 1'), 'test1.txt')}): my_form = TestForm(helpers.get_form_data()) ok_(my_form.validate()) my_form.populate_obj(dummy) eq_(dummy.upload, 'inner/test1.txt') ok_(op.exists(op.join(path, 'inner/test1.txt'))) eq_(url_for('static', filename=dummy.upload), '/static/inner/test1.txt')
Widiot/simpleblog
venv/lib/python3.5/site-packages/flask_admin/tests/test_form_upload.py
Python
mit
8,637
<?php namespace Symfony\Component\Serializer\Encoder; use Symfony\Component\Serializer\SerializerInterface; /* * This file is part of the Symfony framework. * * (c) Fabien Potencier <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ /** * Defines the interface of encoders * * @author Jordi Boggiano <[email protected]> */ interface DecoderInterface { /** * Decodes a string into PHP data * * @param string $data data to decode * @param string $format format to decode from * @return mixed * @api */ function decode($data, $format); }
radzikowski/alf
vendor/symfony/src/Symfony/Component/Serializer/Encoder/DecoderInterface.php
PHP
mit
679
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace XUnit.Runner.Uap { internal static class Helpers { public static async Task<StorageFile> GetStorageFileAsync(string test) { var folder = await KnownFolders.DocumentsLibrary.CreateFolderAsync("TestResults", CreationCollisionOption.OpenIfExists); return await folder.CreateFileAsync(test, CreationCollisionOption.ReplaceExisting); } public static async Task<StreamWriter> GetFileStreamWriterInLocalStorageAsync(string fileName) { var localFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("AC", CreationCollisionOption.OpenIfExists); var file = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); return new StreamWriter(await file.OpenStreamForWriteAsync()) { AutoFlush = true }; } } }
karajas/buildtools
src/xunit.runner.uap/Helpers.cs
C#
mit
1,070
<?php require_once __DIR__.'/../Base.php'; use Kanboard\Event\TaskEvent; use Kanboard\Model\TaskCreationModel; use Kanboard\Model\TaskFinderModel; use Kanboard\Model\ProjectModel; use Kanboard\Model\TaskModel; use Kanboard\Action\TaskAssignCurrentUserColumn; class TaskAssignCurrentUserColumnTest extends Base { public function testChangeUser() { $this->container['sessionStorage']->user = array('id' => 1); $projectModel = new ProjectModel($this->container); $taskCreationModel = new TaskCreationModel($this->container); $taskFinderModel = new TaskFinderModel($this->container); $this->assertEquals(1, $projectModel->create(array('name' => 'test1'))); $this->assertEquals(1, $taskCreationModel->create(array('project_id' => 1, 'title' => 'test'))); $event = new TaskEvent(array( 'task_id' => 1, 'task' => array( 'project_id' => 1, 'column_id' => 2, ) )); $action = new TaskAssignCurrentUserColumn($this->container); $action->setProjectId(1); $action->setParam('column_id', 2); $this->assertTrue($action->execute($event, TaskModel::EVENT_MOVE_COLUMN)); $task = $taskFinderModel->getById(1); $this->assertNotEmpty($task); $this->assertEquals(1, $task['owner_id']); } public function testWithWrongColumn() { $this->container['sessionStorage']->user = array('id' => 1); $projectModel = new ProjectModel($this->container); $taskCreationModel = new TaskCreationModel($this->container); $this->assertEquals(1, $projectModel->create(array('name' => 'test1'))); $this->assertEquals(1, $taskCreationModel->create(array('project_id' => 1, 'title' => 'test'))); $event = new TaskEvent(array( 'task_id' => 1, 'task' => array( 'project_id' => 1, 'column_id' => 3, ) )); $action = new TaskAssignCurrentUserColumn($this->container); $action->setProjectId(1); $action->setParam('column_id', 2); $this->assertFalse($action->execute($event, TaskModel::EVENT_MOVE_COLUMN)); } public function testWithNoUserSession() { $projectModel = new ProjectModel($this->container); $taskCreationModel = new TaskCreationModel($this->container); $this->assertEquals(1, $projectModel->create(array('name' => 'test1'))); $this->assertEquals(1, $taskCreationModel->create(array('project_id' => 1, 'title' => 'test'))); $event = new TaskEvent(array( 'task_id' => 1, 'task' => array( 'project_id' => 1, 'column_id' => 2, ) )); $action = new TaskAssignCurrentUserColumn($this->container); $action->setProjectId(1); $action->setParam('column_id', 2); $this->assertFalse($action->execute($event, TaskModel::EVENT_MOVE_COLUMN)); } }
Busfreak/kanboard
tests/units/Action/TaskAssignCurrentUserColumnTest.php
PHP
mit
3,039
package codechicken.nei.config; public class OptionToggleButton extends OptionButton { public final boolean prefixed; public OptionToggleButton(String name, boolean prefixed) { super(name); this.prefixed = prefixed; } public OptionToggleButton(String name) { this(name, false); } public boolean state() { return renderTag().getBooleanValue(); } public String getButtonText() { return translateN(name + (state() ? ".true" : ".false")); } @Override public String getPrefix() { return prefixed ? translateN(name) : null; } @Override public boolean onClick(int button) { getTag().setBooleanValue(!state()); return true; } }
Chicken-Bones/NotEnoughItems
src/codechicken/nei/config/OptionToggleButton.java
Java
mit
751
# frozen_string_literal: true require 'spec_helper' describe Ethon::Easy::Http do let(:easy) { Ethon::Easy.new } describe "#http_request" do let(:url) { "http://localhost:3001/" } let(:action_name) { :get } let(:options) { {} } let(:get) { double(:setup) } let(:get_class) { Ethon::Easy::Http::Get } it "instanciates action" do expect(get).to receive(:setup) expect(get_class).to receive(:new).and_return(get) easy.http_request(url, action_name, options) end context "when requesting" do [ :get, :post, :put, :delete, :head, :patch, :options ].map do |action| it "returns ok" do easy.http_request(url, action, options) easy.perform expect(easy.return_code).to be(:ok) end unless action == :head it "makes a #{action.to_s.upcase} request" do easy.http_request(url, action, options) easy.perform expect(easy.response_body).to include("\"REQUEST_METHOD\":\"#{action.to_s.upcase}\"") end it "streams the response body from the #{action.to_s.upcase} request" do bytes_read = 0 easy.on_body { |chunk, response| bytes_read += chunk.bytesize } easy.http_request(url, action, options) easy.perform content_length = ((easy.response_headers =~ /Content-Length: (\d+)/) && $1.to_i) expect(bytes_read).to eq(content_length) expect(easy.response_body).to eq("") end it "notifies when headers are ready" do headers = [] easy.on_headers { |r| headers << r.response_headers } easy.http_request(url, action, options) easy.perform expect(headers).to eq([easy.response_headers]) expect(headers.first).to match(/Content-Length: (\d+)/) end end end it "makes requests with custom HTTP verbs" do easy.http_request(url, :purge, options) easy.perform expect(easy.response_body).to include(%{"REQUEST_METHOD":"PURGE"}) end end end end
joisadler/joisadler.github.io
vendor/bundle/ruby/3.0.0/gems/ethon-0.14.0/spec/ethon/easy/http_spec.rb
Ruby
mit
2,140
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "nRF5xGattServer.h" #ifdef YOTTA_CFG_MBED_OS #include "mbed-drivers/mbed.h" #else #include "mbed.h" #endif #include "common/common.h" #include "btle/custom/custom_helper.h" #include "nRF5xn.h" /**************************************************************************/ /*! @brief Adds a new service to the GATT table on the peripheral @returns ble_error_t @retval BLE_ERROR_NONE Everything executed properly @section EXAMPLE @code @endcode */ /**************************************************************************/ ble_error_t nRF5xGattServer::addService(GattService &service) { /* ToDo: Make sure this service UUID doesn't already exist (?) */ /* ToDo: Basic validation */ /* Add the service to the nRF51 */ ble_uuid_t nordicUUID; nordicUUID = custom_convert_to_nordic_uuid(service.getUUID()); uint16_t serviceHandle; ASSERT( ERROR_NONE == sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &nordicUUID, &serviceHandle), BLE_ERROR_PARAM_OUT_OF_RANGE ); service.setHandle(serviceHandle); /* Add characteristics to the service */ for (uint8_t i = 0; i < service.getCharacteristicCount(); i++) { if (characteristicCount >= BLE_TOTAL_CHARACTERISTICS) { return BLE_ERROR_NO_MEM; } GattCharacteristic *p_char = service.getCharacteristic(i); /* Skip any incompletely defined, read-only characteristics. */ if ((p_char->getValueAttribute().getValuePtr() == NULL) && (p_char->getValueAttribute().getLength() == 0) && (p_char->getProperties() == GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ)) { continue; } nordicUUID = custom_convert_to_nordic_uuid(p_char->getValueAttribute().getUUID()); /* The user-description descriptor is a special case which needs to be * handled at the time of adding the characteristic. The following block * is meant to discover its presence. */ const uint8_t *userDescriptionDescriptorValuePtr = NULL; uint16_t userDescriptionDescriptorValueLen = 0; for (uint8_t j = 0; j < p_char->getDescriptorCount(); j++) { GattAttribute *p_desc = p_char->getDescriptor(j); if (p_desc->getUUID() == BLE_UUID_DESCRIPTOR_CHAR_USER_DESC) { userDescriptionDescriptorValuePtr = p_desc->getValuePtr(); userDescriptionDescriptorValueLen = p_desc->getLength(); } } ASSERT ( ERROR_NONE == custom_add_in_characteristic(BLE_GATT_HANDLE_INVALID, &nordicUUID, p_char->getProperties(), p_char->getRequiredSecurity(), p_char->getValueAttribute().getValuePtr(), p_char->getValueAttribute().getLength(), p_char->getValueAttribute().getMaxLength(), p_char->getValueAttribute().hasVariableLength(), userDescriptionDescriptorValuePtr, userDescriptionDescriptorValueLen, p_char->isReadAuthorizationEnabled(), p_char->isWriteAuthorizationEnabled(), &nrfCharacteristicHandles[characteristicCount]), BLE_ERROR_PARAM_OUT_OF_RANGE ); /* Update the characteristic handle */ p_characteristics[characteristicCount] = p_char; p_char->getValueAttribute().setHandle(nrfCharacteristicHandles[characteristicCount].value_handle); characteristicCount++; /* Add optional descriptors if any */ for (uint8_t j = 0; j < p_char->getDescriptorCount(); j++) { if (descriptorCount >= BLE_TOTAL_DESCRIPTORS) { return BLE_ERROR_NO_MEM; } GattAttribute *p_desc = p_char->getDescriptor(j); /* skip the user-description-descriptor here; this has already been handled when adding the characteristic (above). */ if (p_desc->getUUID() == BLE_UUID_DESCRIPTOR_CHAR_USER_DESC) { continue; } nordicUUID = custom_convert_to_nordic_uuid(p_desc->getUUID()); ASSERT(ERROR_NONE == custom_add_in_descriptor(BLE_GATT_HANDLE_INVALID, &nordicUUID, p_desc->getValuePtr(), p_desc->getLength(), p_desc->getMaxLength(), p_desc->hasVariableLength(), &nrfDescriptorHandles[descriptorCount]), BLE_ERROR_PARAM_OUT_OF_RANGE); p_descriptors[descriptorCount] = p_desc; p_desc->setHandle(nrfDescriptorHandles[descriptorCount]); descriptorCount++; } } serviceCount++; return BLE_ERROR_NONE; } /**************************************************************************/ /*! @brief Reads the value of a characteristic, based on the service and characteristic index fields @param[in] attributeHandle The handle of the GattCharacteristic to read from @param[in] buffer Buffer to hold the the characteristic's value (raw byte array in LSB format) @param[in/out] len input: Length in bytes to be read. output: Total length of attribute value upon successful return. @returns ble_error_t @retval BLE_ERROR_NONE Everything executed properly */ /**************************************************************************/ ble_error_t nRF5xGattServer::read(GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP) { return read(BLE_CONN_HANDLE_INVALID, attributeHandle, buffer, lengthP); } ble_error_t nRF5xGattServer::read(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP) { ble_gatts_value_t value = { .len = *lengthP, .offset = 0, .p_value = buffer, }; ASSERT( ERROR_NONE == sd_ble_gatts_value_get(connectionHandle, attributeHandle, &value), BLE_ERROR_PARAM_OUT_OF_RANGE); *lengthP = value.len; return BLE_ERROR_NONE; } /**************************************************************************/ /*! @brief Updates the value of a characteristic, based on the service and characteristic index fields @param[in] charHandle The handle of the GattCharacteristic to write to @param[in] buffer Data to use when updating the characteristic's value (raw byte array in LSB format) @param[in] len The number of bytes in buffer @returns ble_error_t @retval BLE_ERROR_NONE Everything executed properly */ /**************************************************************************/ ble_error_t nRF5xGattServer::write(GattAttribute::Handle_t attributeHandle, const uint8_t buffer[], uint16_t len, bool localOnly) { return write(BLE_CONN_HANDLE_INVALID, attributeHandle, buffer, len, localOnly); } ble_error_t nRF5xGattServer::write(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t buffer[], uint16_t len, bool localOnly) { ble_error_t returnValue = BLE_ERROR_NONE; ble_gatts_value_t value = { .len = len, .offset = 0, .p_value = const_cast<uint8_t *>(buffer), }; if (localOnly) { /* Only update locally regardless of notify/indicate */ ASSERT_INT( ERROR_NONE, sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value), BLE_ERROR_PARAM_OUT_OF_RANGE ); return BLE_ERROR_NONE; } int characteristicIndex = resolveValueHandleToCharIndex(attributeHandle); if ((characteristicIndex != -1) && (p_characteristics[characteristicIndex]->getProperties() & (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY))) { /* HVX update for the characteristic value */ ble_gatts_hvx_params_t hvx_params; hvx_params.handle = attributeHandle; hvx_params.type = (p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) ? BLE_GATT_HVX_NOTIFICATION : BLE_GATT_HVX_INDICATION; hvx_params.offset = 0; hvx_params.p_data = const_cast<uint8_t *>(buffer); hvx_params.p_len = &len; if (connectionHandle == BLE_CONN_HANDLE_INVALID) { /* use the default connection handle if the caller hasn't specified a valid connectionHandle. */ nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap(); connectionHandle = gap.getConnectionHandle(); } error_t error = (error_t) sd_ble_gatts_hvx(connectionHandle, &hvx_params); if (error != ERROR_NONE) { switch (error) { case ERROR_BLE_NO_TX_BUFFERS: /* Notifications consume application buffers. The return value can be used for resending notifications. */ case ERROR_BUSY: returnValue = BLE_STACK_BUSY; break; case ERROR_INVALID_STATE: case ERROR_BLEGATTS_SYS_ATTR_MISSING: returnValue = BLE_ERROR_INVALID_STATE; break; default : ASSERT_INT( ERROR_NONE, sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value), BLE_ERROR_PARAM_OUT_OF_RANGE ); /* Notifications consume application buffers. The return value can * be used for resending notifications. */ returnValue = BLE_STACK_BUSY; break; } } } else { uint32_t err = sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value); switch(err) { case NRF_SUCCESS: returnValue = BLE_ERROR_NONE; break; case NRF_ERROR_INVALID_ADDR: case NRF_ERROR_INVALID_PARAM: returnValue = BLE_ERROR_INVALID_PARAM; break; case NRF_ERROR_NOT_FOUND: case NRF_ERROR_DATA_SIZE: case BLE_ERROR_INVALID_CONN_HANDLE: case BLE_ERROR_GATTS_INVALID_ATTR_TYPE: returnValue = BLE_ERROR_PARAM_OUT_OF_RANGE; break; case NRF_ERROR_FORBIDDEN: returnValue = BLE_ERROR_OPERATION_NOT_PERMITTED; break; default: returnValue = BLE_ERROR_UNSPECIFIED; break; } } return returnValue; } ble_error_t nRF5xGattServer::areUpdatesEnabled(const GattCharacteristic &characteristic, bool *enabledP) { /* Forward the call with the default connection handle. */ nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap(); return areUpdatesEnabled(gap.getConnectionHandle(), characteristic, enabledP); } ble_error_t nRF5xGattServer::areUpdatesEnabled(Gap::Handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP) { int characteristicIndex = resolveValueHandleToCharIndex(characteristic.getValueHandle()); if (characteristicIndex == -1) { return BLE_ERROR_INVALID_PARAM; } /* Read the cccd value from the GATT server. */ GattAttribute::Handle_t cccdHandle = nrfCharacteristicHandles[characteristicIndex].cccd_handle; uint16_t cccdValue; uint16_t length = sizeof(cccdValue); ble_error_t rc = read(connectionHandle, cccdHandle, reinterpret_cast<uint8_t *>(&cccdValue), &length); if (rc != BLE_ERROR_NONE) { return rc; } if (length != sizeof(cccdValue)) { return BLE_ERROR_INVALID_STATE; } /* Check for NOTFICATION or INDICATION in CCCD. */ if ((cccdValue & BLE_GATT_HVX_NOTIFICATION) || (cccdValue & BLE_GATT_HVX_INDICATION)) { *enabledP = true; } return BLE_ERROR_NONE; } /**************************************************************************/ /*! @brief Clear nRF5xGattServer's state. @returns ble_error_t @retval BLE_ERROR_NONE Everything executed properly */ /**************************************************************************/ ble_error_t nRF5xGattServer::reset(void) { /* Clear all state that is from the parent, including private members */ if (GattServer::reset() != BLE_ERROR_NONE) { return BLE_ERROR_INVALID_STATE; } /* Clear derived class members */ memset(p_characteristics, 0, sizeof(p_characteristics)); memset(p_descriptors, 0, sizeof(p_descriptors)); memset(nrfCharacteristicHandles, 0, sizeof(ble_gatts_char_handles_t)); memset(nrfDescriptorHandles, 0, sizeof(nrfDescriptorHandles)); descriptorCount = 0; return BLE_ERROR_NONE; } /**************************************************************************/ /*! @brief Callback handler for events getting pushed up from the SD */ /**************************************************************************/ void nRF5xGattServer::hwCallback(ble_evt_t *p_ble_evt) { GattAttribute::Handle_t handle_value; GattServerEvents::gattEvent_t eventType; const ble_gatts_evt_t *gattsEventP = &p_ble_evt->evt.gatts_evt; switch (p_ble_evt->header.evt_id) { case BLE_GATTS_EVT_WRITE: { /* There are 2 use case here: Values being updated & CCCD (indicate/notify) enabled */ /* 1.) Handle CCCD changes */ handle_value = gattsEventP->params.write.handle; int characteristicIndex = resolveCCCDHandleToCharIndex(handle_value); if ((characteristicIndex != -1) && (p_characteristics[characteristicIndex]->getProperties() & (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY))) { uint16_t cccd_value = (gattsEventP->params.write.data[1] << 8) | gattsEventP->params.write.data[0]; /* Little Endian but M0 may be mis-aligned */ if (((p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE) && (cccd_value & BLE_GATT_HVX_INDICATION)) || ((p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) && (cccd_value & BLE_GATT_HVX_NOTIFICATION))) { eventType = GattServerEvents::GATT_EVENT_UPDATES_ENABLED; } else { eventType = GattServerEvents::GATT_EVENT_UPDATES_DISABLED; } handleEvent(eventType, p_characteristics[characteristicIndex]->getValueHandle()); return; } /* 2.) Changes to the characteristic value will be handled with other events below */ eventType = GattServerEvents::GATT_EVENT_DATA_WRITTEN; } break; case BLE_GATTS_EVT_HVC: /* Indication confirmation received */ eventType = GattServerEvents::GATT_EVENT_CONFIRMATION_RECEIVED; handle_value = gattsEventP->params.hvc.handle; break; case BLE_EVT_TX_COMPLETE: { handleDataSentEvent(p_ble_evt->evt.common_evt.params.tx_complete.count); return; } case BLE_GATTS_EVT_SYS_ATTR_MISSING: sd_ble_gatts_sys_attr_set(gattsEventP->conn_handle, NULL, 0, 0); return; case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST: switch (gattsEventP->params.authorize_request.type) { case BLE_GATTS_AUTHORIZE_TYPE_READ: eventType = GattServerEvents::GATT_EVENT_READ_AUTHORIZATION_REQ; handle_value = gattsEventP->params.authorize_request.request.read.handle; break; case BLE_GATTS_AUTHORIZE_TYPE_WRITE: eventType = GattServerEvents::GATT_EVENT_WRITE_AUTHORIZATION_REQ; handle_value = gattsEventP->params.authorize_request.request.write.handle; break; default: return; } break; default: return; } int characteristicIndex = resolveValueHandleToCharIndex(handle_value); if (characteristicIndex == -1) { return; } /* Find index (charHandle) in the pool */ switch (eventType) { case GattServerEvents::GATT_EVENT_DATA_WRITTEN: { GattWriteCallbackParams cbParams = { .connHandle = gattsEventP->conn_handle, .handle = handle_value, .writeOp = static_cast<GattWriteCallbackParams::WriteOp_t>(gattsEventP->params.write.op), .offset = gattsEventP->params.write.offset, .len = gattsEventP->params.write.len, .data = gattsEventP->params.write.data }; handleDataWrittenEvent(&cbParams); break; } case GattServerEvents::GATT_EVENT_WRITE_AUTHORIZATION_REQ: { GattWriteAuthCallbackParams cbParams = { .connHandle = gattsEventP->conn_handle, .handle = handle_value, .offset = gattsEventP->params.authorize_request.request.write.offset, .len = gattsEventP->params.authorize_request.request.write.len, .data = gattsEventP->params.authorize_request.request.write.data, .authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS /* the callback handler must leave this member * set to AUTH_CALLBACK_REPLY_SUCCESS if the client * request is to proceed. */ }; ble_gatts_rw_authorize_reply_params_t reply = { .type = BLE_GATTS_AUTHORIZE_TYPE_WRITE, .params = { .write = { .gatt_status = p_characteristics[characteristicIndex]->authorizeWrite(&cbParams) } } }; sd_ble_gatts_rw_authorize_reply(gattsEventP->conn_handle, &reply); /* * If write-authorization is enabled for a characteristic, * AUTHORIZATION_REQ event (if replied with true) is *not* * followed by another DATA_WRITTEN event; so we still need * to invoke handleDataWritten(), much the same as we would * have done if write-authorization had not been enabled. */ if (reply.params.write.gatt_status == BLE_GATT_STATUS_SUCCESS) { GattWriteCallbackParams cbParams = { .connHandle = gattsEventP->conn_handle, .handle = handle_value, .writeOp = static_cast<GattWriteCallbackParams::WriteOp_t>(gattsEventP->params.authorize_request.request.write.op), .offset = gattsEventP->params.authorize_request.request.write.offset, .len = gattsEventP->params.authorize_request.request.write.len, .data = gattsEventP->params.authorize_request.request.write.data, }; handleDataWrittenEvent(&cbParams); } break; } case GattServerEvents::GATT_EVENT_READ_AUTHORIZATION_REQ: { GattReadAuthCallbackParams cbParams = { .connHandle = gattsEventP->conn_handle, .handle = handle_value, .offset = gattsEventP->params.authorize_request.request.read.offset, .len = 0, .data = NULL, .authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS /* the callback handler must leave this member * set to AUTH_CALLBACK_REPLY_SUCCESS if the client * request is to proceed. */ }; ble_gatts_rw_authorize_reply_params_t reply = { .type = BLE_GATTS_AUTHORIZE_TYPE_READ, .params = { .read = { .gatt_status = p_characteristics[characteristicIndex]->authorizeRead(&cbParams) } } }; if (cbParams.authorizationReply == BLE_GATT_STATUS_SUCCESS) { if (cbParams.data != NULL) { reply.params.read.update = 1; reply.params.read.offset = cbParams.offset; reply.params.read.len = cbParams.len; reply.params.read.p_data = cbParams.data; } } sd_ble_gatts_rw_authorize_reply(gattsEventP->conn_handle, &reply); break; } default: handleEvent(eventType, handle_value); break; } }
Neuromancer2701/mbedROS2_STF7
mbed-os/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_MCU_NRF51822/source/nRF5xGattServer.cpp
C++
mit
22,735
<!DOCTYPE html> <!--html5--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <!-- Mirrored from www.arduino.cc/en/Reference/GSMServerStop by HTTrack Website Copier/3.x [XR&CO'2010], Mon, 26 Oct 2015 14:07:54 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack --> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charset="utf-8" /> <title>Arduino - GSMServerStop </title> <link rel="shortcut icon" type="image/x-icon" href="../favicon.png" /> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <link rel="stylesheet" href="../../fonts/fonts.css" type="text/css" /> <link rel="stylesheet" href="../../css/arduino-icons.css"> <link rel="stylesheet" href="../../css/animation.css"><!--[if IE 7]> <link rel="stylesheet" href="//arduino.cc/css/arduino-icons-ie7.css"><![endif]--> <!--[if gte IE 9]><!--> <link rel='stylesheet' href='../../css/foundation2.css' type='text/css' /> <!--<![endif]--> <!--[if IE 8]> <link rel='stylesheet' href='//arduino.cc/css/foundation_ie8.css' type='text/css' /> <![endif]--> <link rel='stylesheet' href='../../css/arduino_code_highlight.css' type='text/css' /> <link rel="stylesheet" type="text/css" media="screen" href="../../css/typeplate.css"> <link rel='stylesheet' href='../pub/skins/arduinoWide_SSO/css/arduinoWide_SSO.css' type='text/css' /> <link rel='stylesheet' href='../../css/common.css' type='text/css' /> <link rel="stylesheet" href="../../css/download_page.css" /> <link href="https://plus.google.com/114839908922424087554" rel="publisher" /> <!-- embedded JS and CSS from PmWiki plugins --> <!--HeaderText--><style type='text/css'><!-- ul, ol, pre, dl, p { margin-top:0px; margin-bottom:0px; } code { white-space: nowrap; } .vspace { margin-top:1.33em; } .indent { margin-left:40px; } .outdent { margin-left:40px; text-indent:-40px; } a.createlinktext { text-decoration:none; border-bottom:1px dotted gray; } a.createlink { text-decoration:none; position:relative; top:-0.5em; font-weight:bold; font-size:smaller; border-bottom:none; } img { border:0px; } span.anchor { float: left; font-size: 10px; margin-left: -10px; width: 10px; position:relative; top:-0.1em; text-align: center; } span.anchor a { text-decoration: none; } span.anchor a:hover { text-decoration: underline; } ol.toc { text-indent:-20px; list-style: none; } ol.toc ol.toc { text-indent:-40px; } div.tocfloat { font-size: smaller; margin-bottom: 10px; border-top: 1px dotted #555555; border-bottom: 1px dotted #555555; padding-top: 5px; padding-bottom: 5px; width: 38%; float: right; margin-left: 10px; clear: right; margin-right:-13px; padding-right: 13px; padding-left: 13px; background-color: #eeeeee; } div.toc { font-size: smaller; padding: 5px; border: 1px dotted #cccccc; background: #f7f7f7; margin-bottom: 10px; } div.toc p { background-color: #f9f6d6; margin-top:-5px; padding-top: 5px; margin-left:-5px; padding-left: 5px; margin-right:-5px; padding-right: 5px; padding-bottom: 3px; border-bottom: 1px dotted #cccccc; }.editconflict { color:green; font-style:italic; margin-top:1.33em; margin-bottom:1.33em; } table.markup { border: 2px dotted #ccf; width:90%; } td.markup1, td.markup2 { padding-left:10px; padding-right:10px; } td.markup1 { border-bottom: 1px solid #ccf; } div.faq { margin-left:2em; } div.faq p.question { margin: 1em 0 0.75em -2em; font-weight:bold; } div.faq hr { margin-left: -2em; } .frame { border:1px solid #cccccc; padding:4px; background-color:#f9f9f9; } .lfloat { float:left; margin-right:0.5em; } .rfloat { float:right; margin-left:0.5em; } a.varlink { text-decoration:none; } --></style><script type="text/javascript"> function toggle(obj) { var elstyle = document.getElementById(obj).style; var text = document.getElementById(obj + "tog"); if (elstyle.display == 'none') { elstyle.display = 'block'; text.innerHTML = "hide"; } else { elstyle.display = 'none'; text.innerHTML = "show"; } } </script><script src="http://www.arduino.cc/en/pub/galleria/galleria-1.2.6.min.js"></script><script type="text/javascript">Galleria.loadTheme("http://www.arduino.cc/en/pub/galleria/themes/classic/galleria.classic.min.js");</script> <meta name='robots' content='index,follow' /> <script src="http://arduino.cc/js/vendor/custom.modernizr.js"></script> <!-- do not remove none of those lines, comments embedding in pages will break! --> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" type="text/javascript"></script> <script src="http://arduino.cc/en/pub/js/newsletter_subscribe_popup.js" type="text/javascript"></script> <script src="https://checkout.stripe.com/checkout.js" type="text/javascript"></script> <script src="https://www.arduino.cc/en/pub/js/software_download.js" type="text/javascript"></script><!-- keep https! --> <link rel='stylesheet' href='../../../code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.min.css' type='text/css' /> </head> <body> <div id="menuWings" class="fixed"></div> <div id="page"> <script> var userAgent = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase(); if(userAgent.indexOf('mac')>0){ $("head").append('<style type="text/css">@-moz-document url-prefix() {h1 a, h2 a, h3 a, h4 a, h5 a, h1 a:hover, h2 a:hover, th a, th a:hover, h3 a:hover, h4 a:hover, h5 a:hover, #wikitext h2 a:hover, #wikitext h3 a:hover, #wikitext h4 a:hover {padding-bottom: 0.5em!important;} #pageheader .search input{font-family: "TyponineSans Regular 18";} #pagefooter .monospace{margin-top: -4px;} #navWrapper ul.left &gt; li{margin-top: -2px; padding-bottom: 2px;}#navWrapper ul.right &gt; li{margin-top: -5px; padding-bottom: 5px;}#navWrapper ul.right &gt; li ul{margin-top: 4px;} .slider-container .fixed-caption p{padding:8px 0 14px 0}}</style>'); } </script> <!--[if IE]> <link rel='stylesheet' href='https://id.arduino.cc//css/ie-monospace.css' type='text/css' /> <![endif]--> <div id="menuWings" class="fixed"></div> <!--[if IE 8]> <div class="alert-box panel ie8alert"> <p><strong>Arduino.cc offers limited compatibility for Internet Explorer 8. Get a modern browser as Chrome, Firefox or Safari.</strong></p> <a href="" class="close">&times;</a> </div> <![endif]--> <div id="pageheader"> <div class="row" class="contain-to-grid"> <div class="small-6 large-8 eight columns"> <div class="title"><a href="http://www.arduino.cc/">Arduino</a></div> </div> <div class="small-6 large-4 four columns search"> <div class="row collapse"> <form method="GET" action="http://www.google.com/search"> <div class="small-12 twelve columns"> <i class="icon-search-2"></i> <input type="hidden" name="ie" value="UTF-8"> <input type="hidden" name="oe" value="UTF-8"> <input type="text" name="q" size="25" maxlength="255" value="" placeholder="Search the Arduino Website"> <input type="submit" name="btnG" VALUE="search"> <input type="hidden" name="domains" value="http://www.arduino.cc"> <input type="hidden" name="sitesearch" value="http://www.arduino.cc"> </div> </form> </div> </div> </div> <!--[if gte IE 9]><!--> <div id="navWrapper" class="sticky"> <!--<![endif]--> <!--[if IE 8]> <div id="navWrapper"> <![endif]--> <nav class="top-bar" data-options="is_hover:true" > <ul class="title-area"> <li class="name"></li> </ul> <section class="top-bar-section"> <ul class="left"> <li id="navLogo"> <a href="http://www.arduino.cc/"> <img src="../../img/logo_46.png" alt="userpicture" /> </a> </li> <li id="navHome"><a href="http://www.arduino.cc/">Home</a></li> <li><a href="http://store.arduino.cc/">Buy</a></li> <li><a href="http://www.arduino.cc/en/Main/Software">Download</a></li> <li class="has-dropdown"><a href="#">Products</a> <ul class="dropdown"> <li><a href="http://www.arduino.cc/en/Main/Products">Arduino <span class="menudescription">(USA only)</span></a></li> <li><a href="http://www.arduino.cc/en/Main/GenuinoProducts">Genuino <span class="menudescription">(outside USA)</span></a></li> <li><a href="http://www.arduino.cc/en/ArduinoAtHeart/Products">AtHeart</a></li> <li><a href="http://www.arduino.cc/en/ArduinoCertified/Products">Certified</a></li> </ul> </li> <li class="has-dropdown active"><a href="#">Learning</a> <ul class="dropdown"> <li><a href="http://www.arduino.cc/en/Guide/HomePage">Getting started</a></li> <li><a href="http://www.arduino.cc/en/Tutorial/HomePage">Tutorials</a></li> <li><a href="HomePage.html">Reference</a></li> <li><a href="http://www.arduino.cc/en/Main/CTCprogram">CTC Program</a></li> <li><a href="http://playground.arduino.cc/">Playground</a></li> </ul> </li> <li><a href="http://forum.arduino.cc/">Forum</a></li> <li class="has-dropdown"><a href="#">Support</a> <ul class="dropdown"> <li><a href="http://www.arduino.cc/en/Main/FAQ">FAQ</a></li> <li><a href="http://www.arduino.cc/en/ContactUs">Contact Us</a></li> </ul> </li> <li><a href="http://blog.arduino.cc/">Blog</a></li> </ul> <ul class="right"> <li><a href="https://id.arduino.cc/auth/login/?returnurl=http%3A%2F%2Fwww.arduino.cc%2Fen%2FReference%2FGSMServerStop" class="cart">LOG IN</a></li> <li><a href="https://id.arduino.cc/auth/signup" class="cart">SIGN UP</a></li> </ul> </section> </nav> </div> </div> <br class="clear"/> <div id="pagetext"> <!--PageText--> <div id='wikitext'> <p><strong>Reference</strong> &nbsp; <a class='wikilink' href='HomePage.html'>Language</a> | <a class='wikilink' href='Libraries.html'>Libraries</a> | <a class='wikilink' href='Comparison.html'>Comparison</a> | <a class='wikilink' href='Changes.html'>Changes</a> </p> <p class='vspace'></p><p><a class='wikilink' href='GSM.html'>GSM</a> : <em><span class='wikiword'>GSMServer</span></em> class </p> <p class='vspace'></p><h2>stop()</h2> <h4>Description</h4> <p>Tells the server to stop listening for incoming connections. </p> <p class='vspace'></p><h4>Syntax</h4> <p><em>server</em>.stop() </p> <p class='vspace'></p><h4>Parameters</h4> <p>none </p> <p class='vspace'></p><h4>Returns</h4> <p>none </p> <p class='vspace'></p><h4>See Also</h4> <ul><li><a class='wikilink' href='GSMServerReady.html'>ready()</a> </li><li><a class='wikilink' href='GSMServerBeginWrite.html'>beginWrite()</a> </li><li><a class='wikilink' href='GSMServerWrite.html'>write()</a> </li><li><a class='wikilink' href='GSMServerEndWrite.html'>endWrite()</a> </li><li><a class='wikilink' href='GSMServerRead.html'>read()</a> </li><li><a class='wikilink' href='GSMServerAvailable.html'>available()</a> </li><li><a class='selflink' href='GSMServerStop.html'>stop()</a> </li></ul><p><a class='wikilink' href='HomePage.html'>Reference Home</a> </p> <p class='vspace'></p><p><em>Corrections, suggestions, and new documentation should be posted to the <a class='urllink' href='http://arduino.cc/forum/index.php/board,23.0.html' rel='nofollow'>Forum</a>.</em> </p> <p class='vspace'></p><p>The text of the Arduino reference is licensed under a <a class='urllink' href='http://creativecommons.org/licenses/by-sa/3.0/' rel='nofollow'>Creative Commons Attribution-ShareAlike 3.0 License</a>. Code samples in the reference are released into the public domain. </p> </div> <!-- AddThis Button Style BEGIN --> <style> .addthis_toolbox { margin: 2em 0 1em; } .addthis_toolbox img { float: left; height: 25px; margin-right: 10px; width: auto; } .addthis_toolbox .social-container { float: left; height: 27px; width: auto; } .addthis_toolbox .social-container .social-content { float: left; margin-top: 2px; max-width: 0; overflow: hidden; -moz-transition: max-width .3s ease-out; -webkit-transition: max-width .3s ease-out; -o-transition: max-width .3s ease-out; transition: max-width .3s ease-out; } .addthis_toolbox .social-container:hover .social-content { max-width: 100px; -moz-transition: max-width .2s ease-in; -webkit-transition: max-width .2s ease-in; -o-transition: max-width .2s ease-in; transition: max-width .2s ease-in; } .addthis_toolbox .social-container .social-content a { float: left; margin-right: 5px; } .addthis_toolbox h3 { font-size: 24px; text-align: left; } </style> <!-- AddThis Button Style END --> <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style"> <h3>Share</h3> <!-- FACEBOOK --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/facebook.png" /> <div class="social-content"> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> </div> </div> <!-- TWITTER --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/twitter.png"> <div class="social-content"> <a class="addthis_button_tweet"></a> </div> </div> <!-- PINTEREST --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/pinterest.png"> <div class="social-content"> <a class="addthis_button_pinterest_pinit" pi:pinit:url="//www.addthis.com/features/pinterest" pi:pinit:media="//www.addthis.com/cms-content/images/features/pinterest-lg.png"></a> </div> </div> <!-- G+ --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/gplus.png"> <div class="social-content"> <a class="addthis_button_google_plusone" g:plusone:size="medium"></a> </div> </div> <script type="text/javascript">var addthis_config = {"data_track_addressbar":false};</script> <script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-50573fab238b0d34"></script> </div> <!-- AddThis Button END --> </div> <!-- eof pagetext --> </div> <!-- eof page --> <!--PageFooterFmt--> <div id="pagefooter"> <div id="newsletterModal" class="reveal-modal small"> <form action="http://www.arduino.cc/subscribe.php" method="post" name="sendy-subscribe-form" id="sendy-subscribe-form" class="form-popup"> <div class="modalHeader"> <h3 style="line-height: 1.8rem;" class="modal-header-alt">This link has expired. <br>Please re-subscribe to our Newsletters.</h3> <h3 class="modal-header-main">Subscribe to our Newsletters</h3> </div> <div class="modalBody" id="newsletterModalBody"> <div id="newsletterEmailField" class="row" style="padding-left: 0"> <div class="large-2 columns"> <label for="email" class="newsletter-form-label inline">Email</label> </div> <div class="large-10 columns" style="padding-left: 0"> <input placeholder="Enter your email address" type="email" name="email" class="subscribe-form-input" /> <p id="emailMissing" class="newsletterPopupError">Please enter a valid email to subscribe</p> </div> </div> <div style="margin-left:20px"> <div style="margin-bottom:0.3em"> <input style="display:none" type="checkbox" checked name="list[]" value="arduino_newsletter_id" id="worldwide" class="newsletter-form-checkbox" /> <label for="worldwide"></label> <div style="display:inline-block" class="newsletter-form-label">Arduino Newsletter</div> </div> <div> <input style="display:none" type="checkbox" checked name="list[]" value="arduino_store_newsletter_id" id="store" class="newsletter-form-checkbox" /> <label for="store"></label> <div style="display:inline-block" class="newsletter-form-label">Arduino Store Newsletter</div> </div> </div> <div> <p class="newsletterPopupError2" id="newsletterSubscribeStatus"></p> </div> </div> <div class="row modalFooter"> <div class="form-buttons-row"> <button type="button" value="Cancel" class="popup-form-button white cancel-modal close-reveal-modal">Cancel</button> <button type="submit" name="Subscribe" id="subscribe-submit-btn" class="popup-form-button">Next</button> </div> </div> </form> <!-- step 2, confirm popup --> <div class="confirm-popup" style="margin-bottom:1em"> <div class="modalHeader"> <h3>Confirm your email address</h3> </div> <div class="modalBody" id="newsletterModalBody" style="padding-right:1em;margin-bottom:0"> <p style="margin-bottom:1em;font-size:15px"> We need to confirm your email address.<br> To complete the subscription, please click the link in the email we just sent you. </p> <p style="margin-bottom:1em;font-size:15px"> Thank you for subscribing! </p> <p style="margin-bottom:1em;font-size:15px"> Arduino<br> via Egeo 16<br> Torino, 10131<br> Italy<br> </p> </div> <div class="row modalFooter"> <div class="form-buttons-row"> <button name="Ok" class="popup-form-button" id="close-confirm-popup">Ok</button> </div> </div> </div> </div> <div id="pagefooter" class="pagefooter"> <div class="row"> <div class="large-8 eight columns"> <div class="large-4 four columns newsletter-box"> <!-- Begin Sendy Signup Form --> <h6>Newsletter</h6> <div> <input type="email" name="email" class="email" id="sendy-EMAIL" placeholder="Enter your email to sign up"> <i class="icon-right-small"></i> <input value="Subscribe" name="subscribe" id="sendy-subscribe" class="newsletter-button"> </div> <!--End sendy_embed_signup--> </div> <div class="clearfix"></div> <ul class="inline-list"> <li class="monospace">&copy;2015 Arduino</li> <li><a href="http://www.arduino.cc/en/Main/CopyrightNotice">Copyright Notice</a></li> <li><a href='http://www.arduino.cc/en/Main/ContactUs'>Contact us</a></li> <li><a href='http://www.arduino.cc/en/Main/AboutUs'>About us</a></li> <li><a href='http://www.arduino.cc/Careers'>Careers</a></li> </ul> </div> <div class="large-4 four columns"> <ul id="arduinoSocialLinks" class="arduino-social-links"> <li> <a href="https://twitter.com/arduino"> <img src="../../img/twitter.png" /> </a> </li> <li> <a href="https://www.facebook.com/official.arduino"> <img src="../../img/facebook.png" /> </a> </li> <li> <a href="https://plus.google.com/+Arduino"> <img src="../../img/gplus.png" /> </a> </li> <li> <a href="https://www.flickr.com/photos/arduino_cc"> <img src="../../img/flickr.png" /> </a> </li> <li> <a href="https://youtube.com/arduinoteam"> <img src="../../img/youtube.png" /> </a> </li> </ul> </div> </div> </div> </div> <!--/PageFooterFmt--> <!--[if gte IE 9]><!--> <script src="http://arduino.cc/js/foundation.min.js"></script> <script src="http://arduino.cc/js/foundation.topbar.custom.js"></script> <script> $(document).foundation(); </script> <!--<![endif]--> <!--[if IE 8]> <script src="//arduino.cc/js/foundation_ie8.min.js"></script> <script src="//arduino.cc/js/ie8/jquery.foundation.orbit.js"></script> <script src="//arduino.cc/js/ie8/jquery.foundation.alerts.js"></script> <script src="//arduino.cc/js/app.js"></script> <script> $(window).load(function(){ $("#featured").orbit(); }); </script> <![endif]--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-22581631-3']); _gaq.push(['_setDomainName', 'arduino.cc']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script> $(window).load(function(){ $('a').each (function () { href = $(this).attr ('href'); if (href !== undefined && href.substring (0, 4) == 'http' && href.indexOf ('https://www.arduino.cc/en/Reference/arduino.cc') == -1) $(this).attr ('target', '_blank'); }); // js for language dropdown $('.language-dropdown .current').on('click', function(e){ e.stopPropagation(); $('.language-dropdown ul').toggle(); }); $('.language-dropdown .selector').on('click', function(e){ e.stopPropagation(); $('.language-dropdown ul').toggle(); }); $(document).on('click', function(){ $('.language-dropdown ul:visible').hide(); }); $('.language-dropdown li a').on('click', function(e){ $('.language-dropdown .current').text($(this).text()); }); //js for product pages navbar var menu = $(".product-page-nav"); var menuItems = menu.find("a"); var timeoutId = null; var limitTop = 600; var menuOffset = $('.product-page-nav li').first().offset(); if(menuOffset) { limitTop = menuOffset.top; } var limitBottom = $('.addthis_toolbox').offset().top; var activateSection = function($sectionToActivate) { var label=$sectionToActivate.attr('label'); $(".product-page-nav").find('li').removeClass('active'); $sectionToActivate.addClass('active'); }; menuItems.click(function(e){ e.preventDefault(); var href = $(this).attr("href"), offsetTop = href === "#" ? 0 : $(href).offset().top, adjust = 0; if($(this).parent('li').hasClass('active') === false) { adjust = 80; $('html, body').animate({ scrollTop: offsetTop - adjust }, 1500, 'easeOutExpo'); } }); $(window).scroll(function () { var windscroll = $(window).scrollTop(); if(windscroll < limitTop) { $('.menu').removeClass('sticky'); $('.menu').removeClass('fixed'); } else { $('.menu').addClass('sticky'); } var menuEdgeBottomOffset = $('.menu.columns').offset(); var menuEdgeBottom = 0; if(menuEdgeBottomOffset) { menuEdgeBottom = menuEdgeBottomOffset.top + $('.menu.columns').height(); } if(menuEdgeBottom > limitBottom) { $('.menu').fadeOut(); } else { $('.menu').fadeIn(); } menuItems.each(function(i) { var href = $(this).attr("href"); if ($(href).offset().top <= windscroll + 150) { if(timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(activateSection, 60, $(".product-page-nav").find('li').eq(i)); } }); }); }); </script> </body> <!-- Mirrored from www.arduino.cc/en/Reference/GSMServerStop by HTTrack Website Copier/3.x [XR&CO'2010], Mon, 26 Oct 2015 14:07:54 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack --> </html>
Open-farm/openfarm-core-avr
thirdparty/arduino/reference/www.arduino.cc/en/Reference/GSMServerStop.html
HTML
mit
23,772
require "spec_helper" describe "bundle update" do before :each do build_repo2 install_gemfile <<-G source "file://#{gem_repo2}" gem "activesupport" gem "rack-obama" G end describe "with no arguments" do it "updates the entire bundle" do update_repo2 do build_gem "activesupport", "3.0" end bundle "update" should_be_installed "rack 1.2", "rack-obama 1.0", "activesupport 3.0" end it "doesn't delete the Gemfile.lock file if something goes wrong" do gemfile <<-G source "file://#{gem_repo2}" gem "activesupport" gem "rack-obama" exit! G bundle "update" expect(bundled_app("Gemfile.lock")).to exist end end describe "--quiet argument" do it "shows UI messages without --quiet argument" do bundle "update" expect(out).to include("Fetching source") end it "does not show UI messages with --quiet argument" do bundle "update --quiet" expect(out).not_to include("Fetching source") end end describe "with a top level dependency" do it "unlocks all child dependencies that are unrelated to other locked dependencies" do update_repo2 do build_gem "activesupport", "3.0" end bundle "update rack-obama" should_be_installed "rack 1.2", "rack-obama 1.0", "activesupport 2.3.5" end end describe "with an unknown dependency" do it "should inform the user" do bundle "update halting-problem-solver", :expect_err=>true expect(out).to include "Could not find gem 'halting-problem-solver'" end it "should suggest alternatives" do bundle "update active-support", :expect_err=>true expect(out).to include "Did you mean activesupport?" end end describe "with a child dependency" do it "should update the child dependency" do update_repo2 bundle "update rack" should_be_installed "rack 1.2" end end describe "with --local option" do it "doesn't hit repo2" do FileUtils.rm_rf(gem_repo2) bundle "update --local" expect(out).not_to match(/Fetching source index/) end end end describe "bundle update in more complicated situations" do before :each do build_repo2 end it "will eagerly unlock dependencies of a specified gem" do install_gemfile <<-G source "file://#{gem_repo2}" gem "thin" gem "rack-obama" G update_repo2 do build_gem "thin" , '2.0' do |s| s.add_dependency "rack" end end bundle "update thin" should_be_installed "thin 2.0", "rack 1.2", "rack-obama 1.0" end end describe "bundle update without a Gemfile.lock" do it "should not explode" do build_repo2 gemfile <<-G source "file://#{gem_repo2}" gem "rack", "1.0" G bundle "update" should_be_installed "rack 1.0.0" end end describe "bundle update when a gem depends on a newer version of bundler" do before(:each) do build_repo2 do build_gem "rails", "3.0.1" do |s| s.add_dependency "bundler", Bundler::VERSION.succ end end gemfile <<-G source "file://#{gem_repo2}" gem "rails", "3.0.1" G end it "should not explode" do bundle "update" expect(err).to be_empty end it "should explain that bundler conflicted" do bundle "update" expect(out).not_to match(/in snapshot/i) expect(out).to match(/current Bundler version/i) expect(out).to match(/perhaps you need to update bundler/i) end end
rkh/bundler
spec/update/gems_spec.rb
Ruby
mit
3,576
#!/bin/sh set -e set -x sudo dd if=/dev/zero of=/EMPTY bs=1M || : sudo rm /EMPTY # In CentOS 7, blkid returns duplicate devices swap_device_uuid=`sudo /sbin/blkid -t TYPE=swap -o value -s UUID | uniq` swap_device_label=`sudo /sbin/blkid -t TYPE=swap -o value -s LABEL | uniq` if [ -n "$swap_device_uuid" ]; then swap_device=`readlink -f /dev/disk/by-uuid/"$swap_device_uuid"` elif [ -n "$swap_device_label" ]; then swap_device=`readlink -f /dev/disk/by-label/"$swap_device_label"` fi sudo /sbin/swapoff "$swap_device" sudo dd if=/dev/zero of="$swap_device" bs=1M || : sudo /sbin/mkswap ${swap_device_label:+-L "$swap_device_label"} ${swap_device_uuid:+-U "$swap_device_uuid"} "$swap_device"
sachalin/packer_centos
scripts/common/minimize.sh
Shell
mit
698
# From 3.0 to 3.1 *Make sure you view this [upgrade guide from the `master` branch](../../../master/doc/update/3.0-to-3.1.md) for the most up to date instructions.* **IMPORTANT!** In this release **we moved Resque jobs under own gitlab namespace** Despite a lot of advantages it requires from our users to **replace gitolite post-receive hook with new one**. Most of projects has post-receive file as symlink to gitolite `/home/git/.gitolite/hooks/post-receive`. But some of them may have a real file. In this case you should rewrite it with symlink to gitolite hook. I wrote a bash script which will do it automatically for you. Just make sure all path inside is valid for you ## 1. Stop server & resque sudo service gitlab stop ## 2. Update GitLab ```bash # Get latest code sudo -u gitlab -H git fetch sudo -u gitlab -H git checkout v3.1.0 # Install new charlock_holmes sudo gem install charlock_holmes --version '0.6.9' # The Modernizr gem was yanked from RubyGems. It is required for GitLab >= 2.8.0 # Edit `Gemfile` and change `gem "modernizr", "2.5.3"` to # `gem "modernizr-rails", "2.7.1"`` sudo -u gitlab -H vim Gemfile # Install gems for MySQL sudo -u gitlab -H bundle install --without development test postgres sqlite # Migrate db sudo -u gitlab -H bundle exec rake db:migrate RAILS_ENV=production ``` ## 3. Update post-receive hooks ### Gitolite 3 Step 1: Rewrite post-receive hook ```bash # Rewrite hook for gitolite 3 sudo cp ./lib/hooks/post-receive /home/git/.gitolite/hooks/common/post-receive sudo chown git:git /home/git/.gitolite/hooks/common/post-receive ``` Step 2: Rewrite hooks in all projects to symlink gitolite hook ```bash # 1. Check for valid path sudo -u gitlab -H vim lib/support/rewrite-hooks.sh # 2. Run script sudo -u git -H lib/support/rewrite-hooks.sh ``` ### Gitolite v2 Step 1: rewrite post-receive hook for gitolite 2 ``` sudo cp ./lib/hooks/post-receive /home/git/share/gitolite/hooks/common/post-receive sudo chown git:git /home/git/share/gitolite/hooks/common/post-receive ``` Step 2: Replace symlinks in project to valid place #!/bin/bash src="/home/git/repositories" for dir in `ls "$src/"` do if [ -d "$src/$dir" ]; then if [ "$dir" = "gitolite-admin.git" ] then continue fi project_hook="$src/$dir/hooks/post-receive" gitolite_hook="/home/git/share/gitolite/hooks/common/post-receive" ln -s -f $gitolite_hook $project_hook fi done ## 4. Check app status ```bash # Check APP Status sudo -u gitlab -H bundle exec rake gitlab:app:status RAILS_ENV=production ``` ## 5. Start all sudo service gitlab start
mr-dxdy/gitlabhq
doc/update/3.0-to-3.1.md
Markdown
mit
2,679
require "active_support/notifications" require "active_support/dependencies" require "active_support/descendants_tracker" module Rails class Application module Bootstrap include Initializable initializer :load_environment_hook, group: :all do end initializer :load_active_support, group: :all do require "active_support/all" unless config.active_support.bare end initializer :set_eager_load, group: :all do if config.eager_load.nil? warn <<-INFO config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly: * development - set it to false * test - set it to false (unless you use a tool that preloads your test environment) * production - set it to true INFO config.eager_load = config.cache_classes end end # Initialize the logger early in the stack in case we need to log some deprecation. initializer :initialize_logger, group: :all do Rails.logger ||= config.logger || begin path = config.paths["log"].first unless File.exist? File.dirname path FileUtils.mkdir_p File.dirname path end f = File.open path, 'a' f.binmode f.sync = config.autoflush_log # if true make sure every write flushes logger = ActiveSupport::Logger.new f logger.formatter = config.log_formatter logger = ActiveSupport::TaggedLogging.new(logger) logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase) logger rescue StandardError logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR)) logger.level = ActiveSupport::Logger::WARN logger.warn( "Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " + "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." ) logger end end # Initialize cache early in the stack so railties can make use of it. initializer :initialize_cache, group: :all do unless Rails.cache Rails.cache = ActiveSupport::Cache.lookup_store(config.cache_store) if Rails.cache.respond_to?(:middleware) config.middleware.insert_before("Rack::Runtime", Rails.cache.middleware) end end end # Sets the dependency loading mechanism. initializer :initialize_dependency_mechanism, group: :all do ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load end initializer :bootstrap_hook, group: :all do |app| ActiveSupport.run_load_hooks(:before_initialize, app) end end end end
Rifu/caa-rails
vendor/gems/ruby/2.0.0/gems/railties-4.0.0/lib/rails/application/bootstrap.rb
Ruby
mit
2,815
package p; class A{ void m(int t){ } }
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/StructureSelectionAction/A_test9.java
Java
epl-1.0
40
/******************************************************************************* * Copyright (c) 2014, Bruno Medeiros and other Contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bruno Medeiros - initial API and implementation *******************************************************************************/ package melnorme.lang.tooling.ops; import static melnorme.utilbox.core.Assert.AssertNamespace.assertNotNull; import static melnorme.utilbox.core.CoreUtil.areEqual; import melnorme.utilbox.misc.HashcodeUtil; import melnorme.utilbox.misc.Location; public class FindDefinitionResult { protected final Location fileLocation; protected final SourceLineColumnRange sourceRange; protected final String infoMessage; public FindDefinitionResult(Location fileLocation, SourceLineColumnRange sourceRange, String infoMessage) { this.fileLocation = assertNotNull(fileLocation); this.infoMessage = infoMessage; this.sourceRange = assertNotNull(sourceRange); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(!(obj instanceof FindDefinitionResult)) return false; FindDefinitionResult other = (FindDefinitionResult) obj; return areEqual(fileLocation, other.fileLocation) && areEqual(infoMessage, other.infoMessage) && areEqual(sourceRange, other.sourceRange); } @Override public int hashCode() { return HashcodeUtil.combinedHashCode(infoMessage, sourceRange); } @Override public String toString() { return "ResolveResult[" + (infoMessage != null ? infoMessage +"," : "") + fileLocation + " " + sourceRange.toString() + "]"; } /* ----------------- ----------------- */ public String getInfoMessage() { return infoMessage; } public SourceLineColumnRange getSourceRange() { return sourceRange; } public Location getFileLocation() { return fileLocation; } }
fredyw/goclipse
plugin_tooling/src-lang/melnorme/lang/tooling/ops/FindDefinitionResult.java
Java
epl-1.0
2,185
// Copyright 2008 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #pragma once #include <cstddef> #include <string> #include <vector> #include "Common/ChunkFile.h" #include "Common/CommonTypes.h" #include "Common/Logging/Log.h" #include "Core/IOS/IOS.h" namespace IOS { namespace HLE { enum ReturnCode : s32 { IPC_SUCCESS = 0, // Success IPC_EACCES = -1, // Permission denied IPC_EEXIST = -2, // File exists IPC_EINVAL = -4, // Invalid argument or fd IPC_EMAX = -5, // Too many file descriptors open IPC_ENOENT = -6, // File not found IPC_EQUEUEFULL = -8, // Queue full IPC_EIO = -12, // ECC error IPC_ENOMEM = -22, // Alloc failed during request FS_EINVAL = -101, // Invalid path FS_EACCESS = -102, // Permission denied FS_ECORRUPT = -103, // Corrupted NAND FS_EEXIST = -105, // File exists FS_ENOENT = -106, // No such file or directory FS_ENFILE = -107, // Too many fds open FS_EFBIG = -108, // Max block count reached? FS_EFDEXHAUSTED = -109, // Too many fds open FS_ENAMELEN = -110, // Pathname is too long FS_EFDOPEN = -111, // FD is already open FS_EIO = -114, // ECC error FS_ENOTEMPTY = -115, // Directory not empty FS_EDIRDEPTH = -116, // Max directory depth exceeded FS_EBUSY = -118, // Resource busy ES_SHORT_READ = -1009, // Short read ES_EIO = -1010, // Write failure ES_INVALID_SIGNATURE_TYPE = -1012, ES_FD_EXHAUSTED = -1016, // Max of 3 ES handles exceeded ES_EINVAL = -1017, // Invalid argument ES_DEVICE_ID_MISMATCH = -1020, ES_HASH_MISMATCH = -1022, // Decrypted content hash doesn't match with the hash from the TMD ES_ENOMEM = -1024, // Alloc failed during request ES_EACCES = -1026, // Incorrect access rights (according to TMD) ES_UNKNOWN_ISSUER = -1027, ES_NO_TICKET = -1028, ES_INVALID_TICKET = -1029, IOSC_EACCES = -2000, IOSC_EEXIST = -2001, IOSC_EINVAL = -2002, IOSC_EMAX = -2003, IOSC_ENOENT = -2004, IOSC_INVALID_OBJTYPE = -2005, IOSC_INVALID_RNG = -2006, IOSC_INVALID_FLAG = -2007, IOSC_INVALID_FORMAT = -2008, IOSC_INVALID_VERSION = -2009, IOSC_INVALID_SIGNER = -2010, IOSC_FAIL_CHECKVALUE = -2011, IOSC_FAIL_INTERNAL = -2012, IOSC_FAIL_ALLOC = -2013, IOSC_INVALID_SIZE = -2014, IOSC_INVALID_ADDR = -2015, IOSC_INVALID_ALIGN = -2016, USB_ECANCELED = -7022, // USB OH0 insertion hook cancelled }; struct Request { u32 address = 0; IPCCommandType command = IPC_CMD_OPEN; u32 fd = 0; explicit Request(u32 address); virtual ~Request() = default; }; enum OpenMode : s32 { IOS_OPEN_NONE = 0, IOS_OPEN_READ = 1, IOS_OPEN_WRITE = 2, IOS_OPEN_RW = (IOS_OPEN_READ | IOS_OPEN_WRITE) }; struct OpenRequest final : Request { std::string path; OpenMode flags = IOS_OPEN_READ; // The UID and GID are not part of the IPC request sent from the PPC to the Starlet, // but they are set after they reach IOS and are dispatched to the appropriate module. u32 uid = 0; u16 gid = 0; explicit OpenRequest(u32 address); }; struct ReadWriteRequest final : Request { u32 buffer = 0; u32 size = 0; explicit ReadWriteRequest(u32 address); }; enum SeekMode : s32 { IOS_SEEK_SET = 0, IOS_SEEK_CUR = 1, IOS_SEEK_END = 2, }; struct SeekRequest final : Request { u32 offset = 0; SeekMode mode = IOS_SEEK_SET; explicit SeekRequest(u32 address); }; struct IOCtlRequest final : Request { u32 request = 0; u32 buffer_in = 0; u32 buffer_in_size = 0; // Contrary to the name, the output buffer can also be used for input. u32 buffer_out = 0; u32 buffer_out_size = 0; explicit IOCtlRequest(u32 address); void Log(const std::string& description, LogTypes::LOG_TYPE type = LogTypes::IOS, LogTypes::LOG_LEVELS level = LogTypes::LINFO) const; void Dump(const std::string& description, LogTypes::LOG_TYPE type = LogTypes::IOS, LogTypes::LOG_LEVELS level = LogTypes::LINFO) const; void DumpUnknown(const std::string& description, LogTypes::LOG_TYPE type = LogTypes::IOS, LogTypes::LOG_LEVELS level = LogTypes::LERROR) const; }; struct IOCtlVRequest final : Request { struct IOVector { u32 address = 0; u32 size = 0; }; u32 request = 0; // In vectors are *mostly* used for input buffers. Sometimes they are also used as // output buffers (notably in the network code). // IO vectors are *mostly* used for output buffers. However, as indicated in the name, // they're also used as input buffers. // So both of them are technically IO vectors. But we're keeping them separated because // merging them into a single std::vector would make using the first out vector more complicated. std::vector<IOVector> in_vectors; std::vector<IOVector> io_vectors; explicit IOCtlVRequest(u32 address); bool HasNumberOfValidVectors(size_t in_count, size_t io_count) const; void Dump(const std::string& description, LogTypes::LOG_TYPE type = LogTypes::IOS, LogTypes::LOG_LEVELS level = LogTypes::LINFO) const; void DumpUnknown(const std::string& description, LogTypes::LOG_TYPE type = LogTypes::IOS, LogTypes::LOG_LEVELS level = LogTypes::LERROR) const; }; namespace Device { class Device { public: enum class DeviceType : u32 { Static, // Devices which appear in s_device_map. FileIO, // FileIO devices which are created dynamically. OH0, // OH0 child devices which are created dynamically. }; Device(Kernel& ios, const std::string& device_name, DeviceType type = DeviceType::Static); virtual ~Device() = default; // Release any resources which might interfere with savestating. virtual void PrepareForState(PointerWrap::Mode mode) {} virtual void DoState(PointerWrap& p); void DoStateShared(PointerWrap& p); const std::string& GetDeviceName() const { return m_name; } // Replies to Open and Close requests are sent by the IPC request handler (HandleCommand), // not by the devices themselves. virtual ReturnCode Open(const OpenRequest& request); virtual ReturnCode Close(u32 fd); virtual IPCCommandResult Seek(const SeekRequest& seek) { return Unsupported(seek); } virtual IPCCommandResult Read(const ReadWriteRequest& read) { return Unsupported(read); } virtual IPCCommandResult Write(const ReadWriteRequest& write) { return Unsupported(write); } virtual IPCCommandResult IOCtl(const IOCtlRequest& ioctl) { return Unsupported(ioctl); } virtual IPCCommandResult IOCtlV(const IOCtlVRequest& ioctlv) { return Unsupported(ioctlv); } virtual void Update() {} virtual void UpdateWantDeterminism(bool new_want_determinism) {} virtual DeviceType GetDeviceType() const { return m_device_type; } virtual bool IsOpened() const { return m_is_active; } static IPCCommandResult GetDefaultReply(s32 return_value); static IPCCommandResult GetNoReply(); protected: Kernel& m_ios; std::string m_name; // STATE_TO_SAVE DeviceType m_device_type; bool m_is_active = false; private: IPCCommandResult Unsupported(const Request& request); }; } // namespace Device } // namespace HLE } // namespace IOS
Mushman/dolphin
Source/Core/Core/IOS/Device.h
C
gpl-2.0
7,277
<?php namespace Drupal\Tests\options\Kernel; use Drupal\field\Entity\FieldConfig; use Drupal\Tests\field\Kernel\FieldKernelTestBase; use Drupal\field\Entity\FieldStorageConfig; /** * Base class for Options module integration tests. */ abstract class OptionsFieldUnitTestBase extends FieldKernelTestBase { /** * Modules to enable. * * @var array */ protected static $modules = ['options']; /** * The field name used in the test. * * @var string */ protected $fieldName = 'test_options'; /** * The field storage definition used to created the field storage. * * @var array */ protected $fieldStorageDefinition; /** * The list field storage used in the test. * * @var \Drupal\field\Entity\FieldStorageConfig */ protected $fieldStorage; /** * The list field used in the test. * * @var \Drupal\field\Entity\FieldConfig */ protected $field; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->fieldStorageDefinition = [ 'field_name' => $this->fieldName, 'entity_type' => 'entity_test', 'type' => 'list_integer', 'cardinality' => 1, 'settings' => [ 'allowed_values' => [1 => 'One', 2 => 'Two', 3 => 'Three'], ], ]; $this->fieldStorage = FieldStorageConfig::create($this->fieldStorageDefinition); $this->fieldStorage->save(); $this->field = FieldConfig::create([ 'field_storage' => $this->fieldStorage, 'bundle' => 'entity_test', ]); $this->field->save(); \Drupal::service('entity_display.repository') ->getFormDisplay('entity_test', 'entity_test') ->setComponent($this->fieldName, [ 'type' => 'options_buttons', ]) ->save(); } }
tobiasbuhrer/tobiasb
web/core/modules/options/tests/src/Kernel/OptionsFieldUnitTestBase.php
PHP
gpl-2.0
1,777
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "common/ptr.h" #include "common/stream.h" #include "common/textconsole.h" #include "graphics/wincursor.h" namespace Graphics { /** A Windows cursor. */ class WinCursor : public Cursor { public: WinCursor(); ~WinCursor(); /** Return the cursor's width. */ uint16 getWidth() const; /** Return the cursor's height. */ uint16 getHeight() const; /** Return the cursor's hotspot's x coordinate. */ uint16 getHotspotX() const; /** Return the cursor's hotspot's y coordinate. */ uint16 getHotspotY() const; /** Return the cursor's transparent key. */ byte getKeyColor() const; const byte *getSurface() const { return _surface; } const byte *getPalette() const { return _palette; } byte getPaletteStartIndex() const { return 0; } uint16 getPaletteCount() const { return 256; } /** Read the cursor's data out of a stream. */ bool readFromStream(Common::SeekableReadStream &stream); private: byte *_surface; byte _palette[256 * 3]; uint16 _width; ///< The cursor's width. uint16 _height; ///< The cursor's height. uint16 _hotspotX; ///< The cursor's hotspot's x coordinate. uint16 _hotspotY; ///< The cursor's hotspot's y coordinate. byte _keyColor; ///< The cursor's transparent key /** Clear the cursor. */ void clear(); }; WinCursor::WinCursor() { _width = 0; _height = 0; _hotspotX = 0; _hotspotY = 0; _surface = 0; _keyColor = 0; memset(_palette, 0, 256 * 3); } WinCursor::~WinCursor() { clear(); } uint16 WinCursor::getWidth() const { return _width; } uint16 WinCursor::getHeight() const { return _height; } uint16 WinCursor::getHotspotX() const { return _hotspotX; } uint16 WinCursor::getHotspotY() const { return _hotspotY; } byte WinCursor::getKeyColor() const { return _keyColor; } bool WinCursor::readFromStream(Common::SeekableReadStream &stream) { clear(); _hotspotX = stream.readUint16LE(); _hotspotY = stream.readUint16LE(); // Check header size if (stream.readUint32LE() != 40) return false; // Check dimensions _width = stream.readUint32LE(); _height = stream.readUint32LE() / 2; if (_width & 3) { // Cursors should always be a power of 2 // Of course, it wouldn't be hard to handle but if we have no examples... warning("Non-divisible-by-4 width cursor found"); return false; } // Color planes if (stream.readUint16LE() != 1) return false; // Only 1bpp, 4bpp and 8bpp supported uint16 bitsPerPixel = stream.readUint16LE(); if (bitsPerPixel != 1 && bitsPerPixel != 4 && bitsPerPixel != 8) return false; // Compression if (stream.readUint32LE() != 0) return false; // Image size + X resolution + Y resolution stream.skip(12); uint32 numColors = stream.readUint32LE(); // If the color count is 0, then it uses up the maximum amount if (numColors == 0) numColors = 1 << bitsPerPixel; // Reading the palette stream.seek(40 + 4); for (uint32 i = 0 ; i < numColors; i++) { _palette[i * 3 + 2] = stream.readByte(); _palette[i * 3 + 1] = stream.readByte(); _palette[i * 3 ] = stream.readByte(); stream.readByte(); } // Reading the bitmap data uint32 dataSize = stream.size() - stream.pos(); byte *initialSource = new byte[dataSize]; stream.read(initialSource, dataSize); // Parse the XOR map const byte *src = initialSource; _surface = new byte[_width * _height]; byte *dest = _surface + _width * (_height - 1); uint32 imagePitch = _width * bitsPerPixel / 8; for (uint32 i = 0; i < _height; i++) { byte *rowDest = dest; if (bitsPerPixel == 1) { // 1bpp for (uint16 j = 0; j < (_width / 8); j++) { byte p = src[j]; for (int k = 0; k < 8; k++, rowDest++, p <<= 1) { if ((p & 0x80) == 0x80) *rowDest = 1; else *rowDest = 0; } } } else if (bitsPerPixel == 4) { // 4bpp for (uint16 j = 0; j < (_width / 2); j++) { byte p = src[j]; *rowDest++ = p >> 4; *rowDest++ = p & 0x0f; } } else { // 8bpp memcpy(rowDest, src, _width); } dest -= _width; src += imagePitch; } // Calculate our key color if (numColors < 256) { // If we're not using the maximum colors in a byte, we can fit it in _keyColor = numColors; } else { // HACK: Try to find a color that's not being used so it can become // our keycolor. It's quite impossible to fit 257 entries into 256... for (uint32 i = 0; i < 256; i++) { for (int j = 0; j < _width * _height; j++) { // TODO: Also check to see if the space is transparent if (_surface[j] == i) break; if (j == _width * _height - 1) { _keyColor = i; i = 256; break; } } } } // Now go through and apply the AND map to get the transparency uint32 andWidth = (_width + 7) / 8; src += andWidth * (_height - 1); for (uint32 y = 0; y < _height; y++) { for (uint32 x = 0; x < _width; x++) if (src[x / 8] & (1 << (7 - x % 8))) _surface[y * _width + x] = _keyColor; src -= andWidth; } delete[] initialSource; return true; } void WinCursor::clear() { delete[] _surface; _surface = 0; } WinCursorGroup::WinCursorGroup() { } WinCursorGroup::~WinCursorGroup() { for (uint32 i = 0; i < cursors.size(); i++) delete cursors[i].cursor; } WinCursorGroup *WinCursorGroup::createCursorGroup(Common::WinResources *exe, const Common::WinResourceID &id) { Common::ScopedPtr<Common::SeekableReadStream> stream(exe->getResource(Common::kWinGroupCursor, id)); if (!stream || stream->size() <= 6) return 0; stream->skip(4); uint32 cursorCount = stream->readUint16LE(); if ((uint32)stream->size() < (6 + cursorCount * 14)) return 0; WinCursorGroup *group = new WinCursorGroup(); group->cursors.reserve(cursorCount); for (uint32 i = 0; i < cursorCount; i++) { stream->readUint16LE(); // width stream->readUint16LE(); // height // Plane count if (stream->readUint16LE() != 1) { warning("PlaneCount is not 1."); } stream->readUint16LE(); // bits per pixel stream->readUint32LE(); // data size uint32 cursorId = stream->readUint16LE(); Common::ScopedPtr<Common::SeekableReadStream> cursorStream(exe->getResource(Common::kWinCursor, cursorId)); if (!cursorStream) { delete group; return 0; } WinCursor *cursor = new WinCursor(); if (!cursor->readFromStream(*cursorStream)) { delete cursor; delete group; return 0; } CursorItem item; item.id = cursorId; item.cursor = cursor; group->cursors.push_back(item); } return group; } /** * The default Windows cursor */ class DefaultWinCursor : public Cursor { public: DefaultWinCursor() {} ~DefaultWinCursor() {} uint16 getWidth() const { return 12; } uint16 getHeight() const { return 20; } uint16 getHotspotX() const { return 0; } uint16 getHotspotY() const { return 0; } byte getKeyColor() const { return 0; } const byte *getSurface() const { static const byte defaultCursor[] = { 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 1, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 1, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 1, 0, 0, 0, 0, 1, 2, 2, 1, 1, 2, 2, 1, 0, 0, 0, 0, 1, 2, 1, 0, 1, 1, 2, 2, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 2, 2, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 }; return defaultCursor; } const byte *getPalette() const { static const byte bwPalette[] = { 0x00, 0x00, 0x00, // Black 0xFF, 0xFF, 0xFF // White }; return bwPalette; } byte getPaletteStartIndex() const { return 1; } uint16 getPaletteCount() const { return 2; } }; Cursor *makeDefaultWinCursor() { return new DefaultWinCursor(); } /** * The Windows busy cursor */ class BusyWinCursor : public Cursor { public: BusyWinCursor() {} ~BusyWinCursor() {} uint16 getWidth() const { return 15; } uint16 getHeight() const { return 27; } uint16 getHotspotX() const { return 7; } uint16 getHotspotY() const { return 13; } byte getKeyColor() const { return 0; } const byte *getSurface() const { static const byte busyCursor[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 1, 0, 0, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 0, 0, 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 1, 0, 0, 0, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1, 1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 1, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 1, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 1, 0, 0, 1, 1, 2, 2, 2, 1, 2, 1, 2, 2, 2, 1, 1, 0, 0, 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 1, 0, 0, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; return busyCursor; } const byte *getPalette() const { static const byte bwPalette[] = { 0x00, 0x00, 0x00, // Black 0xFF, 0xFF, 0xFF // White }; return bwPalette; } byte getPaletteStartIndex() const { return 1; } uint16 getPaletteCount() const { return 2; } }; Cursor *makeBusyWinCursor() { return new BusyWinCursor(); } } // End of namespace Graphics
vanfanel/scummvm
graphics/wincursor.cpp
C++
gpl-2.0
10,995
/* * kernel/sched/debug.c * * Print the CFS rbtree * * Copyright(C) 2007, Red Hat, Inc., Ingo Molnar * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/proc_fs.h> #include <linux/sched.h> #include <linux/seq_file.h> #include <linux/kallsyms.h> #include <linux/utsname.h> #include "sched.h" static DEFINE_SPINLOCK(sched_debug_lock); /* * This allows printing both to /proc/sched_debug and * to the console */ #define SEQ_printf(m, x...) \ do { \ if (m) \ seq_printf(m, x); \ else \ printk(x); \ } while (0) /* * Ease the printing of nsec fields: */ static long long nsec_high(unsigned long long nsec) { if ((long long)nsec < 0) { nsec = -nsec; do_div(nsec, 1000000); return -nsec; } do_div(nsec, 1000000); return nsec; } static unsigned long nsec_low(unsigned long long nsec) { if ((long long)nsec < 0) nsec = -nsec; return do_div(nsec, 1000000); } #define SPLIT_NS(x) nsec_high(x), nsec_low(x) #ifdef CONFIG_FAIR_GROUP_SCHED static void print_cfs_group_stats(struct seq_file *m, int cpu, struct task_group *tg) { struct sched_entity *se = tg->se[cpu]; #define P(F) \ SEQ_printf(m, " .%-30s: %lld\n", #F, (long long)F) #define PN(F) \ SEQ_printf(m, " .%-30s: %lld.%06ld\n", #F, SPLIT_NS((long long)F)) if (!se) { struct sched_avg *avg = &cpu_rq(cpu)->avg; P(avg->runnable_avg_sum); P(avg->runnable_avg_period); return; } PN(se->exec_start); PN(se->vruntime); PN(se->sum_exec_runtime); #ifdef CONFIG_SCHEDSTATS PN(se->statistics.wait_start); PN(se->statistics.sleep_start); PN(se->statistics.block_start); PN(se->statistics.sleep_max); PN(se->statistics.block_max); PN(se->statistics.exec_max); PN(se->statistics.slice_max); PN(se->statistics.wait_max); PN(se->statistics.wait_sum); P(se->statistics.wait_count); #endif P(se->load.weight); #ifdef CONFIG_SMP P(se->avg.runnable_avg_sum); P(se->avg.runnable_avg_period); P(se->avg.load_avg_contrib); P(se->avg.decay_count); #endif #undef PN #undef P } #endif #ifdef CONFIG_CGROUP_SCHED static char group_path[PATH_MAX]; static char *task_group_path(struct task_group *tg) { if (autogroup_path(tg, group_path, PATH_MAX)) return group_path; cgroup_path(tg->css.cgroup, group_path, PATH_MAX); return group_path; } #endif static void print_task(struct seq_file *m, struct rq *rq, struct task_struct *p) { if (rq->curr == p) SEQ_printf(m, "R"); else SEQ_printf(m, " "); SEQ_printf(m, "%15s %5d %9Ld.%06ld %9Ld %5d ", p->comm, p->pid, SPLIT_NS(p->se.vruntime), (long long)(p->nvcsw + p->nivcsw), p->prio); #ifdef CONFIG_SCHEDSTATS SEQ_printf(m, "%9Ld.%06ld %9Ld.%06ld %9Ld.%06ld", SPLIT_NS(p->se.vruntime), SPLIT_NS(p->se.sum_exec_runtime), SPLIT_NS(p->se.statistics.sum_sleep_runtime)); #else SEQ_printf(m, "%15Ld %15Ld %15Ld.%06ld %15Ld.%06ld %15Ld.%06ld", 0LL, 0LL, 0LL, 0L, 0LL, 0L, 0LL, 0L); #endif #ifdef CONFIG_CGROUP_SCHED SEQ_printf(m, " %s", task_group_path(task_group(p))); #endif SEQ_printf(m, "\n"); } static void print_rq(struct seq_file *m, struct rq *rq, int rq_cpu) { struct task_struct *g, *p; unsigned long flags; SEQ_printf(m, "\nrunnable tasks:\n" " task PID tree-key switches prio" " exec-runtime sum-exec sum-sleep\n" "------------------------------------------------------" "----------------------------------------------------\n"); read_lock_irqsave(&tasklist_lock, flags); do_each_thread(g, p) { if (!p->on_rq || task_cpu(p) != rq_cpu) continue; print_task(m, rq, p); } while_each_thread(g, p); read_unlock_irqrestore(&tasklist_lock, flags); } void print_cfs_rq(struct seq_file *m, int cpu, struct cfs_rq *cfs_rq) { s64 MIN_vruntime = -1, min_vruntime, max_vruntime = -1, spread, rq0_min_vruntime, spread0; struct rq *rq = cpu_rq(cpu); struct sched_entity *last; unsigned long flags; #ifdef CONFIG_FAIR_GROUP_SCHED SEQ_printf(m, "\ncfs_rq[%d]:%s\n", cpu, task_group_path(cfs_rq->tg)); #else SEQ_printf(m, "\ncfs_rq[%d]:\n", cpu); #endif SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "exec_clock", SPLIT_NS(cfs_rq->exec_clock)); raw_spin_lock_irqsave(&rq->lock, flags); if (cfs_rq->rb_leftmost) MIN_vruntime = (__pick_first_entity(cfs_rq))->vruntime; last = __pick_last_entity(cfs_rq); if (last) max_vruntime = last->vruntime; min_vruntime = cfs_rq->min_vruntime; rq0_min_vruntime = cpu_rq(0)->cfs.min_vruntime; raw_spin_unlock_irqrestore(&rq->lock, flags); SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "MIN_vruntime", SPLIT_NS(MIN_vruntime)); SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "min_vruntime", SPLIT_NS(min_vruntime)); SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "max_vruntime", SPLIT_NS(max_vruntime)); spread = max_vruntime - MIN_vruntime; SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "spread", SPLIT_NS(spread)); spread0 = min_vruntime - rq0_min_vruntime; SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "spread0", SPLIT_NS(spread0)); SEQ_printf(m, " .%-30s: %d\n", "nr_spread_over", cfs_rq->nr_spread_over); SEQ_printf(m, " .%-30s: %d\n", "nr_running", cfs_rq->nr_running); SEQ_printf(m, " .%-30s: %ld\n", "load", cfs_rq->load.weight); #ifdef CONFIG_FAIR_GROUP_SCHED #ifdef CONFIG_SMP SEQ_printf(m, " .%-30s: %ld\n", "runnable_load_avg", cfs_rq->runnable_load_avg); SEQ_printf(m, " .%-30s: %ld\n", "blocked_load_avg", cfs_rq->blocked_load_avg); SEQ_printf(m, " .%-30s: %ld\n", "tg_load_avg", atomic_long_read(&cfs_rq->tg->load_avg)); SEQ_printf(m, " .%-30s: %ld\n", "tg_load_contrib", cfs_rq->tg_load_contrib); SEQ_printf(m, " .%-30s: %d\n", "tg_runnable_contrib", cfs_rq->tg_runnable_contrib); SEQ_printf(m, " .%-30s: %d\n", "tg->runnable_avg", atomic_read(&cfs_rq->tg->runnable_avg)); #endif #ifdef CONFIG_CFS_BANDWIDTH SEQ_printf(m, " .%-30s: %d\n", "tg->cfs_bandwidth.timer_active", cfs_rq->tg->cfs_bandwidth.timer_active); SEQ_printf(m, " .%-30s: %d\n", "throttled", cfs_rq->throttled); SEQ_printf(m, " .%-30s: %d\n", "throttle_count", cfs_rq->throttle_count); #endif print_cfs_group_stats(m, cpu, cfs_rq->tg); #endif } void print_rt_rq(struct seq_file *m, int cpu, struct rt_rq *rt_rq) { #ifdef CONFIG_RT_GROUP_SCHED SEQ_printf(m, "\nrt_rq[%d]:%s\n", cpu, task_group_path(rt_rq->tg)); #else SEQ_printf(m, "\nrt_rq[%d]:\n", cpu); #endif #define P(x) \ SEQ_printf(m, " .%-30s: %Ld\n", #x, (long long)(rt_rq->x)) #define PN(x) \ SEQ_printf(m, " .%-30s: %Ld.%06ld\n", #x, SPLIT_NS(rt_rq->x)) P(rt_nr_running); P(rt_throttled); PN(rt_time); PN(rt_runtime); #undef PN #undef P } extern __read_mostly int sched_clock_running; static void print_cpu(struct seq_file *m, int cpu) { struct rq *rq = cpu_rq(cpu); unsigned long flags; #ifdef CONFIG_X86 { unsigned int freq = cpu_khz ? : 1; SEQ_printf(m, "cpu#%d, %u.%03u MHz\n", cpu, freq / 1000, (freq % 1000)); } #else SEQ_printf(m, "cpu#%d\n", cpu); #endif #define P(x) \ do { \ if (sizeof(rq->x) == 4) \ SEQ_printf(m, " .%-30s: %ld\n", #x, (long)(rq->x)); \ else \ SEQ_printf(m, " .%-30s: %Ld\n", #x, (long long)(rq->x));\ } while (0) #define PN(x) \ SEQ_printf(m, " .%-30s: %Ld.%06ld\n", #x, SPLIT_NS(rq->x)) P(nr_running); SEQ_printf(m, " .%-30s: %lu\n", "load", rq->load.weight); P(nr_switches); P(nr_load_updates); P(nr_uninterruptible); PN(next_balance); P(curr->pid); PN(clock); P(cpu_load[0]); P(cpu_load[1]); P(cpu_load[2]); P(cpu_load[3]); P(cpu_load[4]); #undef P #undef PN #ifdef CONFIG_SCHEDSTATS #define P(n) SEQ_printf(m, " .%-30s: %d\n", #n, rq->n); #define P64(n) SEQ_printf(m, " .%-30s: %Ld\n", #n, rq->n); P(yld_count); P(sched_count); P(sched_goidle); #ifdef CONFIG_SMP P64(avg_idle); #endif P(ttwu_count); P(ttwu_local); P(util); #undef P #undef P64 #endif spin_lock_irqsave(&sched_debug_lock, flags); print_cfs_stats(m, cpu); print_rt_stats(m, cpu); rcu_read_lock(); print_rq(m, rq, cpu); rcu_read_unlock(); spin_unlock_irqrestore(&sched_debug_lock, flags); SEQ_printf(m, "\n"); } static const char *sched_tunable_scaling_names[] = { "none", "logaritmic", "linear" }; static void sched_debug_header(struct seq_file *m) { u64 ktime, sched_clk, cpu_clk; unsigned long flags; local_irq_save(flags); ktime = ktime_to_ns(ktime_get()); sched_clk = sched_clock(); cpu_clk = local_clock(); local_irq_restore(flags); SEQ_printf(m, "Sched Debug Version: v0.10, %s %.*s\n", init_utsname()->release, (int)strcspn(init_utsname()->version, " "), init_utsname()->version); #define P(x) \ SEQ_printf(m, "%-40s: %Ld\n", #x, (long long)(x)) #define PN(x) \ SEQ_printf(m, "%-40s: %Ld.%06ld\n", #x, SPLIT_NS(x)) PN(ktime); PN(sched_clk); PN(cpu_clk); P(jiffies); #ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK P(sched_clock_stable); #endif #undef PN #undef P SEQ_printf(m, "\n"); SEQ_printf(m, "sysctl_sched\n"); #define P(x) \ SEQ_printf(m, " .%-40s: %Ld\n", #x, (long long)(x)) #define PN(x) \ SEQ_printf(m, " .%-40s: %Ld.%06ld\n", #x, SPLIT_NS(x)) PN(sysctl_sched_latency); PN(sysctl_sched_min_granularity); PN(sysctl_sched_wakeup_granularity); P(sysctl_sched_child_runs_first); P(sysctl_sched_features); #undef PN #undef P SEQ_printf(m, " .%-40s: %d (%s)\n", "sysctl_sched_tunable_scaling", sysctl_sched_tunable_scaling, sched_tunable_scaling_names[sysctl_sched_tunable_scaling]); SEQ_printf(m, "\n"); } static int sched_debug_show(struct seq_file *m, void *v) { int cpu = (unsigned long)(v - 2); if (cpu != -1) print_cpu(m, cpu); else sched_debug_header(m); return 0; } #ifdef CONFIG_SYSRQ_SCHED_DEBUG void sysrq_sched_debug_show(void) { int cpu; sched_debug_header(NULL); for_each_online_cpu(cpu) print_cpu(NULL, cpu); } #endif /* * This itererator needs some explanation. * It returns 1 for the header position. * This means 2 is cpu 0. * In a hotplugged system some cpus, including cpu 0, may be missing so we have * to use cpumask_* to iterate over the cpus. */ static void *sched_debug_start(struct seq_file *file, loff_t *offset) { unsigned long n = *offset; if (n == 0) return (void *) 1; n--; if (n > 0) n = cpumask_next(n - 1, cpu_online_mask); else n = cpumask_first(cpu_online_mask); *offset = n + 1; if (n < nr_cpu_ids) return (void *)(unsigned long)(n + 2); return NULL; } static void *sched_debug_next(struct seq_file *file, void *data, loff_t *offset) { (*offset)++; return sched_debug_start(file, offset); } static void sched_debug_stop(struct seq_file *file, void *data) { } static const struct seq_operations sched_debug_sops = { .start = sched_debug_start, .next = sched_debug_next, .stop = sched_debug_stop, .show = sched_debug_show, }; static int sched_debug_release(struct inode *inode, struct file *file) { seq_release(inode, file); return 0; } static int sched_debug_open(struct inode *inode, struct file *filp) { int ret = 0; ret = seq_open(filp, &sched_debug_sops); return ret; } static const struct file_operations sched_debug_fops = { .open = sched_debug_open, .read = seq_read, .llseek = seq_lseek, .release = sched_debug_release, }; static int __init init_sched_debug_procfs(void) { struct proc_dir_entry *pe; pe = proc_create("sched_debug", 0444, NULL, &sched_debug_fops); if (!pe) return -ENOMEM; return 0; } __initcall(init_sched_debug_procfs); void proc_sched_show_task(struct task_struct *p, struct seq_file *m) { unsigned long nr_switches; SEQ_printf(m, "%s (%d, #threads: %d)\n", p->comm, p->pid, get_nr_threads(p)); SEQ_printf(m, "---------------------------------------------------------\n"); #define __P(F) \ SEQ_printf(m, "%-35s:%21Ld\n", #F, (long long)F) #define P(F) \ SEQ_printf(m, "%-35s:%21Ld\n", #F, (long long)p->F) #define __PN(F) \ SEQ_printf(m, "%-35s:%14Ld.%06ld\n", #F, SPLIT_NS((long long)F)) #define PN(F) \ SEQ_printf(m, "%-35s:%14Ld.%06ld\n", #F, SPLIT_NS((long long)p->F)) PN(se.exec_start); PN(se.vruntime); PN(se.sum_exec_runtime); nr_switches = p->nvcsw + p->nivcsw; #ifdef CONFIG_SCHEDSTATS PN(se.statistics.wait_start); PN(se.statistics.sleep_start); PN(se.statistics.block_start); PN(se.statistics.sleep_max); PN(se.statistics.block_max); PN(se.statistics.exec_max); PN(se.statistics.slice_max); PN(se.statistics.wait_max); PN(se.statistics.wait_sum); P(se.statistics.wait_count); PN(se.statistics.iowait_sum); P(se.statistics.iowait_count); P(se.nr_migrations); P(se.statistics.nr_migrations_cold); P(se.statistics.nr_failed_migrations_affine); P(se.statistics.nr_failed_migrations_running); P(se.statistics.nr_failed_migrations_hot); P(se.statistics.nr_forced_migrations); P(se.statistics.nr_wakeups); P(se.statistics.nr_wakeups_sync); P(se.statistics.nr_wakeups_migrate); P(se.statistics.nr_wakeups_local); P(se.statistics.nr_wakeups_remote); P(se.statistics.nr_wakeups_affine); P(se.statistics.nr_wakeups_affine_attempts); P(se.statistics.nr_wakeups_passive); P(se.statistics.nr_wakeups_idle); { u64 avg_atom, avg_per_cpu; avg_atom = p->se.sum_exec_runtime; if (nr_switches) avg_atom = div64_ul(avg_atom, nr_switches); else avg_atom = -1LL; avg_per_cpu = p->se.sum_exec_runtime; if (p->se.nr_migrations) { avg_per_cpu = div64_u64(avg_per_cpu, p->se.nr_migrations); } else { avg_per_cpu = -1LL; } __PN(avg_atom); __PN(avg_per_cpu); } #endif __P(nr_switches); SEQ_printf(m, "%-35s:%21Ld\n", "nr_voluntary_switches", (long long)p->nvcsw); SEQ_printf(m, "%-35s:%21Ld\n", "nr_involuntary_switches", (long long)p->nivcsw); P(se.load.weight); P(policy); P(prio); #undef PN #undef __PN #undef P #undef __P { unsigned int this_cpu = raw_smp_processor_id(); u64 t0, t1; t0 = cpu_clock(this_cpu); t1 = cpu_clock(this_cpu); SEQ_printf(m, "%-35s:%21Ld\n", "clock-delta", (long long)(t1-t0)); } } void proc_sched_set_task(struct task_struct *p) { #ifdef CONFIG_SCHEDSTATS memset(&p->se.statistics, 0, sizeof(p->se.statistics)); #endif }
scotthartbti/android_kernel_samsung_trlte
kernel/sched/debug.c
C
gpl-2.0
14,128
/* Copyright (c) 2010-2012, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/cdev.h> #include <linux/device.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/list.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/uaccess.h> #include <linux/wait.h> #include <linux/workqueue.h> #include <linux/android_pmem.h> #include <linux/clk.h> #include <linux/delay.h> #include <linux/debugfs.h> #include <mach/clk.h> #include <linux/pm_runtime.h> #include <mach/msm_subsystem_map.h> #include <media/msm/vcd_api.h> #include <media/msm/vidc_init.h> #include "vidc_init_internal.h" #include "vcd_res_tracker_api.h" #if DEBUG #define DBG(x...) printk(KERN_DEBUG x) #else #define DBG(x...) #endif #define VIDC_NAME "msm_vidc_reg" #define ERR(x...) printk(KERN_ERR x) static struct vidc_dev *vidc_device_p; static dev_t vidc_dev_num; static struct class *vidc_class; static unsigned int vidc_mmu_subsystem[] = {MSM_SUBSYSTEM_VIDEO}; static const struct file_operations vidc_fops = { .owner = THIS_MODULE, .open = NULL, .release = NULL, .unlocked_ioctl = NULL, }; struct workqueue_struct *vidc_wq; struct workqueue_struct *vidc_timer_wq; static irqreturn_t vidc_isr(int irq, void *dev); static spinlock_t vidc_spin_lock; u32 vidc_msg_timing, vidc_msg_pmem; #ifdef VIDC_ENABLE_DBGFS struct dentry *vidc_debugfs_root; struct dentry *vidc_get_debugfs_root(void) { if (vidc_debugfs_root == NULL) vidc_debugfs_root = debugfs_create_dir("vidc", NULL); return vidc_debugfs_root; } void vidc_debugfs_file_create(struct dentry *root, const char *name, u32 *var) { struct dentry *vidc_debugfs_file = debugfs_create_u32(name, S_IRUGO | S_IWUSR, root, var); if (!vidc_debugfs_file) ERR("%s(): Error creating/opening file %s\n", __func__, name); } #endif static void vidc_timer_fn(unsigned long data) { unsigned long flag; struct vidc_timer *hw_timer = NULL; ERR("%s() Timer expired\n", __func__); spin_lock_irqsave(&vidc_spin_lock, flag); hw_timer = (struct vidc_timer *)data; list_add_tail(&hw_timer->list, &vidc_device_p->vidc_timer_queue); spin_unlock_irqrestore(&vidc_spin_lock, flag); DBG("Queue the work for timer\n"); queue_work(vidc_timer_wq, &vidc_device_p->vidc_timer_worker); } static void vidc_timer_handler(struct work_struct *work) { unsigned long flag = 0; u32 islist_empty = 0; struct vidc_timer *hw_timer = NULL; ERR("%s() Timer expired\n", __func__); do { spin_lock_irqsave(&vidc_spin_lock, flag); islist_empty = list_empty(&vidc_device_p->vidc_timer_queue); if (!islist_empty) { hw_timer = list_first_entry( &vidc_device_p->vidc_timer_queue, struct vidc_timer, list); list_del(&hw_timer->list); } spin_unlock_irqrestore(&vidc_spin_lock, flag); if (!islist_empty && hw_timer && hw_timer->cb_func) hw_timer->cb_func(hw_timer->userdata); } while (!islist_empty); } static void vidc_work_handler(struct work_struct *work) { DBG("vidc_work_handler()"); vcd_read_and_clear_interrupt(); vcd_response_handler(); enable_irq(vidc_device_p->irq); DBG("vidc_work_handler() done"); } static DECLARE_WORK(vidc_work, vidc_work_handler); static int __devinit vidc_720p_probe(struct platform_device *pdev) { struct resource *resource; DBG("Enter %s()\n", __func__); if (pdev->id) { ERR("Invalid plaform device ID = %d\n", pdev->id); return -EINVAL; } vidc_device_p->irq = platform_get_irq(pdev, 0); if (unlikely(vidc_device_p->irq < 0)) { ERR("%s(): Invalid irq = %d\n", __func__, vidc_device_p->irq); return -ENXIO; } resource = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (unlikely(!resource)) { ERR("%s(): Invalid resource\n", __func__); return -ENXIO; } vidc_device_p->phys_base = resource->start; vidc_device_p->virt_base = ioremap(resource->start, resource->end - resource->start + 1); if (!vidc_device_p->virt_base) { ERR("%s() : ioremap failed\n", __func__); return -ENOMEM; } vidc_device_p->device = &pdev->dev; mutex_init(&vidc_device_p->lock); vidc_wq = create_singlethread_workqueue("vidc_worker_queue"); if (!vidc_wq) { ERR("%s: create workque failed\n", __func__); return -ENOMEM; } pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); return 0; } static int __devexit vidc_720p_remove(struct platform_device *pdev) { if (pdev->id) { ERR("Invalid plaform device ID = %d\n", pdev->id); return -EINVAL; } pm_runtime_disable(&pdev->dev); return 0; } static int vidc_runtime_suspend(struct device *dev) { dev_dbg(dev, "pm_runtime: suspending...\n"); return 0; } static int vidc_runtime_resume(struct device *dev) { dev_dbg(dev, "pm_runtime: resuming...\n"); return 0; } static const struct dev_pm_ops vidc_dev_pm_ops = { .runtime_suspend = vidc_runtime_suspend, .runtime_resume = vidc_runtime_resume, }; static struct platform_driver msm_vidc_720p_platform_driver = { .probe = vidc_720p_probe, .remove = vidc_720p_remove, .driver = { .name = "msm_vidc", .pm = &vidc_dev_pm_ops, }, }; static void __exit vidc_exit(void) { platform_driver_unregister(&msm_vidc_720p_platform_driver); } static irqreturn_t vidc_isr(int irq, void *dev) { DBG("\n vidc_isr() %d ", irq); disable_irq_nosync(irq); queue_work(vidc_wq, &vidc_work); return IRQ_HANDLED; } static int __init vidc_init(void) { int rc = 0; struct device *class_devp; #ifdef VIDC_ENABLE_DBGFS struct dentry *root = NULL; #endif vidc_device_p = kzalloc(sizeof(struct vidc_dev), GFP_KERNEL); if (!vidc_device_p) { ERR("%s Unable to allocate memory for vidc_dev\n", __func__); return -ENOMEM; } rc = alloc_chrdev_region(&vidc_dev_num, 0, 1, VIDC_NAME); if (rc < 0) { ERR("%s: alloc_chrdev_region Failed rc = %d\n", __func__, rc); goto error_vidc_alloc_chrdev_region; } vidc_class = class_create(THIS_MODULE, VIDC_NAME); if (IS_ERR(vidc_class)) { rc = PTR_ERR(vidc_class); ERR("%s: couldn't create vidc_class rc = %d\n", __func__, rc); goto error_vidc_class_create; } class_devp = device_create(vidc_class, NULL, vidc_dev_num, NULL, VIDC_NAME); if (IS_ERR(class_devp)) { rc = PTR_ERR(class_devp); ERR("%s: class device_create failed %d\n", __func__, rc); goto error_vidc_class_device_create; } cdev_init(&vidc_device_p->cdev, &vidc_fops); vidc_device_p->cdev.owner = THIS_MODULE; rc = cdev_add(&(vidc_device_p->cdev), vidc_dev_num, 1); if (rc < 0) { ERR("%s: cdev_add failed %d\n", __func__, rc); goto error_vidc_cdev_add; } rc = platform_driver_register(&msm_vidc_720p_platform_driver); if (rc) { ERR("%s failed to load\n", __func__); goto error_vidc_platfom_register; } rc = request_irq(vidc_device_p->irq, vidc_isr, IRQF_TRIGGER_HIGH, "vidc", vidc_device_p->device); if (unlikely(rc)) { ERR("%s() :request_irq failed\n", __func__); goto error_vidc_request_irq; } res_trk_init(vidc_device_p->device, vidc_device_p->irq); vidc_timer_wq = create_singlethread_workqueue("vidc_timer_wq"); if (!vidc_timer_wq) { ERR("%s: create workque failed\n", __func__); rc = -ENOMEM; goto error_vidc_create_workqueue; } DBG("Disabling IRQ in %s()\n", __func__); disable_irq_nosync(vidc_device_p->irq); INIT_WORK(&vidc_device_p->vidc_timer_worker, vidc_timer_handler); spin_lock_init(&vidc_spin_lock); INIT_LIST_HEAD(&vidc_device_p->vidc_timer_queue); vidc_device_p->ref_count = 0; vidc_device_p->firmware_refcount = 0; vidc_device_p->get_firmware = 0; #ifdef VIDC_ENABLE_DBGFS root = vidc_get_debugfs_root(); if (root) { vidc_debugfs_file_create(root, "vidc_msg_timing", (u32 *) &vidc_msg_timing); vidc_debugfs_file_create(root, "vidc_msg_pmem", (u32 *) &vidc_msg_pmem); } #endif return 0; error_vidc_create_workqueue: free_irq(vidc_device_p->irq, vidc_device_p->device); error_vidc_request_irq: platform_driver_unregister(&msm_vidc_720p_platform_driver); error_vidc_platfom_register: cdev_del(&(vidc_device_p->cdev)); error_vidc_cdev_add: device_destroy(vidc_class, vidc_dev_num); error_vidc_class_device_create: class_destroy(vidc_class); error_vidc_class_create: unregister_chrdev_region(vidc_dev_num, 1); error_vidc_alloc_chrdev_region: kfree(vidc_device_p); return rc; } void __iomem *vidc_get_ioaddr(void) { return (u8 *)vidc_device_p->virt_base; } EXPORT_SYMBOL(vidc_get_ioaddr); int vidc_load_firmware(void) { u32 status = true; if (!res_trk_check_for_sec_session()) { mutex_lock(&vidc_device_p->lock); if (!vidc_device_p->get_firmware) { status = res_trk_download_firmware(); if (!status) goto error; vidc_device_p->get_firmware = 1; } vidc_device_p->firmware_refcount++; error: mutex_unlock(&vidc_device_p->lock); } return status; } EXPORT_SYMBOL(vidc_load_firmware); void vidc_release_firmware(void) { if (!res_trk_check_for_sec_session()) { mutex_lock(&vidc_device_p->lock); if (vidc_device_p->firmware_refcount > 0) vidc_device_p->firmware_refcount--; else vidc_device_p->firmware_refcount = 0; mutex_unlock(&vidc_device_p->lock); } } EXPORT_SYMBOL(vidc_release_firmware); u32 vidc_get_fd_info(struct video_client_ctx *client_ctx, enum buffer_dir buffer, int pmem_fd, unsigned long kvaddr, int index, struct ion_handle **buff_handle) { struct buf_addr_table *buf_addr_table; u32 rc = 0; if (!client_ctx) return false; if (buffer == BUFFER_TYPE_INPUT) buf_addr_table = client_ctx->input_buf_addr_table; else buf_addr_table = client_ctx->output_buf_addr_table; if (buf_addr_table[index].pmem_fd == pmem_fd) { if (buf_addr_table[index].kernel_vaddr == kvaddr) rc = buf_addr_table[index].buff_ion_flag; *buff_handle = buf_addr_table[index].buff_ion_handle; } return rc; } EXPORT_SYMBOL(vidc_get_fd_info); void vidc_cleanup_addr_table(struct video_client_ctx *client_ctx, enum buffer_dir buffer) { u32 *num_of_buffers = NULL; u32 i = 0; struct buf_addr_table *buf_addr_table; if (buffer == BUFFER_TYPE_INPUT) { buf_addr_table = client_ctx->input_buf_addr_table; num_of_buffers = &client_ctx->num_of_input_buffers; DBG("%s(): buffer = INPUT\n", __func__); } else { buf_addr_table = client_ctx->output_buf_addr_table; num_of_buffers = &client_ctx->num_of_output_buffers; DBG("%s(): buffer = OUTPUT\n", __func__); } if (!*num_of_buffers) goto bail_out_cleanup; if (!client_ctx->user_ion_client) goto bail_out_cleanup; for (i = 0; i < *num_of_buffers; ++i) { if (buf_addr_table[i].client_data) { msm_subsystem_unmap_buffer( (struct msm_mapped_buffer *) buf_addr_table[i].client_data); buf_addr_table[i].client_data = NULL; } if (!IS_ERR_OR_NULL(buf_addr_table[i].buff_ion_handle)) { if (!IS_ERR_OR_NULL(client_ctx->user_ion_client)) { ion_unmap_kernel(client_ctx->user_ion_client, buf_addr_table[i]. buff_ion_handle); if (!res_trk_check_for_sec_session()) { ion_unmap_iommu( client_ctx->user_ion_client, buf_addr_table[i]. buff_ion_handle, VIDEO_DOMAIN, VIDEO_MAIN_POOL); } ion_free(client_ctx->user_ion_client, buf_addr_table[i]. buff_ion_handle); buf_addr_table[i].buff_ion_handle = NULL; } } } if (client_ctx->vcd_h264_mv_buffer.client_data) { msm_subsystem_unmap_buffer((struct msm_mapped_buffer *) client_ctx->vcd_h264_mv_buffer.client_data); client_ctx->vcd_h264_mv_buffer.client_data = NULL; } if (!IS_ERR_OR_NULL(client_ctx->h264_mv_ion_handle)) { if (!IS_ERR_OR_NULL(client_ctx->user_ion_client)) { ion_unmap_kernel(client_ctx->user_ion_client, client_ctx->h264_mv_ion_handle); if (!res_trk_check_for_sec_session()) { ion_unmap_iommu(client_ctx->user_ion_client, client_ctx->h264_mv_ion_handle, VIDEO_DOMAIN, VIDEO_MAIN_POOL); } ion_free(client_ctx->user_ion_client, client_ctx->h264_mv_ion_handle); client_ctx->h264_mv_ion_handle = NULL; } } bail_out_cleanup: return; } EXPORT_SYMBOL(vidc_cleanup_addr_table); u32 vidc_lookup_addr_table(struct video_client_ctx *client_ctx, enum buffer_dir buffer, u32 search_with_user_vaddr, unsigned long *user_vaddr, unsigned long *kernel_vaddr, unsigned long *phy_addr, int *pmem_fd, struct file **file, s32 *buffer_index) { u32 num_of_buffers; u32 i; struct buf_addr_table *buf_addr_table; u32 found = false; if (!client_ctx) return false; mutex_lock(&client_ctx->enrty_queue_lock); if (buffer == BUFFER_TYPE_INPUT) { buf_addr_table = client_ctx->input_buf_addr_table; num_of_buffers = client_ctx->num_of_input_buffers; DBG("%s(): buffer = INPUT\n", __func__); } else { buf_addr_table = client_ctx->output_buf_addr_table; num_of_buffers = client_ctx->num_of_output_buffers; DBG("%s(): buffer = OUTPUT\n", __func__); } for (i = 0; i < num_of_buffers; ++i) { if (search_with_user_vaddr) { if (*user_vaddr == buf_addr_table[i].user_vaddr) { *kernel_vaddr = buf_addr_table[i].kernel_vaddr; found = true; DBG("%s() : client_ctx = %p." " user_virt_addr = 0x%08lx is found", __func__, client_ctx, *user_vaddr); break; } } else { if (*kernel_vaddr == buf_addr_table[i].kernel_vaddr) { *user_vaddr = buf_addr_table[i].user_vaddr; found = true; DBG("%s() : client_ctx = %p." " kernel_virt_addr = 0x%08lx is found", __func__, client_ctx, *kernel_vaddr); break; } } } if (found) { *phy_addr = buf_addr_table[i].dev_addr; *pmem_fd = buf_addr_table[i].pmem_fd; *file = buf_addr_table[i].file; *buffer_index = i; if (search_with_user_vaddr) DBG("kernel_vaddr = 0x%08lx, phy_addr = 0x%08lx " " pmem_fd = %d, struct *file = %p " "buffer_index = %d\n", *kernel_vaddr, *phy_addr, *pmem_fd, *file, *buffer_index); else DBG("user_vaddr = 0x%08lx, phy_addr = 0x%08lx " " pmem_fd = %d, struct *file = %p " "buffer_index = %d\n", *user_vaddr, *phy_addr, *pmem_fd, *file, *buffer_index); mutex_unlock(&client_ctx->enrty_queue_lock); return true; } else { if (search_with_user_vaddr) DBG("%s() : client_ctx = %p user_virt_addr = 0x%08lx" " Not Found.\n", __func__, client_ctx, *user_vaddr); else DBG("%s() : client_ctx = %p kernel_virt_addr = 0x%08lx" " Not Found.\n", __func__, client_ctx, *kernel_vaddr); mutex_unlock(&client_ctx->enrty_queue_lock); return false; } } EXPORT_SYMBOL(vidc_lookup_addr_table); u32 vidc_insert_addr_table(struct video_client_ctx *client_ctx, enum buffer_dir buffer, unsigned long user_vaddr, unsigned long *kernel_vaddr, int pmem_fd, unsigned long buffer_addr_offset, unsigned int max_num_buffers, unsigned long length) { unsigned long len, phys_addr; struct file *file = NULL; u32 *num_of_buffers = NULL; u32 i, flags; struct buf_addr_table *buf_addr_table; struct msm_mapped_buffer *mapped_buffer = NULL; struct ion_handle *buff_ion_handle = NULL; unsigned long ionflag = 0; unsigned long iova = 0; int ret = 0; unsigned long buffer_size = 0; size_t ion_len; if (!client_ctx || !length) return false; mutex_lock(&client_ctx->enrty_queue_lock); if (buffer == BUFFER_TYPE_INPUT) { buf_addr_table = client_ctx->input_buf_addr_table; num_of_buffers = &client_ctx->num_of_input_buffers; DBG("%s(): buffer = INPUT #Buf = %d\n", __func__, *num_of_buffers); } else { buf_addr_table = client_ctx->output_buf_addr_table; num_of_buffers = &client_ctx->num_of_output_buffers; DBG("%s(): buffer = OUTPUT #Buf = %d\n", __func__, *num_of_buffers); length = length * 2; /* workaround for iommu video h/w bug */ } if (*num_of_buffers == max_num_buffers) { ERR("%s(): Num of buffers reached max value : %d", __func__, max_num_buffers); goto bail_out_add; } i = 0; while (i < *num_of_buffers && user_vaddr != buf_addr_table[i].user_vaddr) i++; if (i < *num_of_buffers) { DBG("%s() : client_ctx = %p." " user_virt_addr = 0x%08lx already set", __func__, client_ctx, user_vaddr); goto bail_out_add; } else { if (!vcd_get_ion_status()) { if (get_pmem_file(pmem_fd, &phys_addr, kernel_vaddr, &len, &file)) { ERR("%s(): get_pmem_file failed\n", __func__); goto bail_out_add; } put_pmem_file(file); flags = (buffer == BUFFER_TYPE_INPUT) ? MSM_SUBSYSTEM_MAP_IOVA : MSM_SUBSYSTEM_MAP_IOVA|MSM_SUBSYSTEM_ALIGN_IOVA_8K; mapped_buffer = msm_subsystem_map_buffer(phys_addr, length, flags, vidc_mmu_subsystem, sizeof(vidc_mmu_subsystem)/sizeof(unsigned int)); if (IS_ERR(mapped_buffer)) { pr_err("buffer map failed"); goto bail_out_add; } buf_addr_table[*num_of_buffers].client_data = (void *) mapped_buffer; buf_addr_table[*num_of_buffers].dev_addr = mapped_buffer->iova[0]; } else { buff_ion_handle = ion_import_fd( client_ctx->user_ion_client, pmem_fd); if (IS_ERR_OR_NULL(buff_ion_handle)) { ERR("%s(): get_ION_handle failed\n", __func__); goto bail_out_add; } if (ion_handle_get_flags(client_ctx->user_ion_client, buff_ion_handle, &ionflag)) { ERR("%s():ION flags fail\n", __func__); goto bail_out_add; } *kernel_vaddr = (unsigned long) ion_map_kernel( client_ctx->user_ion_client, buff_ion_handle, ionflag); if (!(*kernel_vaddr)) { ERR("%s():ION virtual addr fail\n", __func__); *kernel_vaddr = (unsigned long)NULL; goto ion_free_error; } if (res_trk_check_for_sec_session()) { if (ion_phys(client_ctx->user_ion_client, buff_ion_handle, &phys_addr, &ion_len)) { ERR("%s():ION physical addr fail\n", __func__); goto ion_map_error; } len = (unsigned long) ion_len; buf_addr_table[*num_of_buffers].client_data = NULL; buf_addr_table[*num_of_buffers].dev_addr = phys_addr; } else { ret = ion_map_iommu(client_ctx->user_ion_client, buff_ion_handle, VIDEO_DOMAIN, VIDEO_MAIN_POOL, SZ_8K, length, (unsigned long *) &iova, (unsigned long *) &buffer_size, UNCACHED, ION_IOMMU_UNMAP_DELAYED); if (ret) { ERR("%s():ION iommu map fail\n", __func__); goto ion_map_error; } phys_addr = iova; buf_addr_table[*num_of_buffers].client_data = NULL; buf_addr_table[*num_of_buffers].dev_addr = iova; } } phys_addr += buffer_addr_offset; (*kernel_vaddr) += buffer_addr_offset; buf_addr_table[*num_of_buffers].user_vaddr = user_vaddr; buf_addr_table[*num_of_buffers].kernel_vaddr = *kernel_vaddr; buf_addr_table[*num_of_buffers].pmem_fd = pmem_fd; buf_addr_table[*num_of_buffers].file = file; buf_addr_table[*num_of_buffers].phy_addr = phys_addr; buf_addr_table[*num_of_buffers].buff_ion_handle = buff_ion_handle; buf_addr_table[*num_of_buffers].buff_ion_flag = ionflag; *num_of_buffers = *num_of_buffers + 1; DBG("%s() : client_ctx = %p, user_virt_addr = 0x%08lx, " "kernel_vaddr = 0x%08lx phys_addr=%lu inserted!", __func__, client_ctx, user_vaddr, *kernel_vaddr, phys_addr); } mutex_unlock(&client_ctx->enrty_queue_lock); return true; ion_map_error: if (*kernel_vaddr && buff_ion_handle) ion_unmap_kernel(client_ctx->user_ion_client, buff_ion_handle); ion_free_error: if (!IS_ERR_OR_NULL(buff_ion_handle)) ion_free(client_ctx->user_ion_client, buff_ion_handle); bail_out_add: mutex_unlock(&client_ctx->enrty_queue_lock); return false; } EXPORT_SYMBOL(vidc_insert_addr_table); /* * Similar to vidc_insert_addr_table except intended for in-kernel * use where buffers have already been alloced and mapped properly */ u32 vidc_insert_addr_table_kernel(struct video_client_ctx *client_ctx, enum buffer_dir buffer, unsigned long user_vaddr, unsigned long kernel_vaddr, unsigned long phys_addr, unsigned int max_num_buffers, unsigned long length) { u32 *num_of_buffers = NULL; u32 i; struct buf_addr_table *buf_addr_table; struct msm_mapped_buffer *mapped_buffer = NULL; if (!client_ctx || !length || !kernel_vaddr || !phys_addr) return false; mutex_lock(&client_ctx->enrty_queue_lock); if (buffer == BUFFER_TYPE_INPUT) { buf_addr_table = client_ctx->input_buf_addr_table; num_of_buffers = &client_ctx->num_of_input_buffers; DBG("%s(): buffer = INPUT #Buf = %d\n", __func__, *num_of_buffers); } else { buf_addr_table = client_ctx->output_buf_addr_table; num_of_buffers = &client_ctx->num_of_output_buffers; DBG("%s(): buffer = OUTPUT #Buf = %d\n", __func__, *num_of_buffers); } if (*num_of_buffers == max_num_buffers) { ERR("%s(): Num of buffers reached max value : %d", __func__, max_num_buffers); goto bail_out_add; } i = 0; while (i < *num_of_buffers && user_vaddr != buf_addr_table[i].user_vaddr) { i++; } if (i < *num_of_buffers) { DBG("%s() : client_ctx = %p." " user_virt_addr = 0x%08lx already set", __func__, client_ctx, user_vaddr); goto bail_out_add; } else { mapped_buffer = NULL; buf_addr_table[*num_of_buffers].client_data = (void *) mapped_buffer; buf_addr_table[*num_of_buffers].dev_addr = phys_addr; buf_addr_table[*num_of_buffers].user_vaddr = user_vaddr; buf_addr_table[*num_of_buffers].kernel_vaddr = kernel_vaddr; buf_addr_table[*num_of_buffers].pmem_fd = -1; buf_addr_table[*num_of_buffers].file = NULL; buf_addr_table[*num_of_buffers].phy_addr = phys_addr; buf_addr_table[*num_of_buffers].buff_ion_handle = NULL; *num_of_buffers = *num_of_buffers + 1; DBG("%s() : client_ctx = %p, user_virt_addr = 0x%08lx, " "kernel_vaddr = 0x%08lx inserted!", __func__, client_ctx, user_vaddr, *kernel_vaddr); } mutex_unlock(&client_ctx->enrty_queue_lock); return true; bail_out_add: mutex_unlock(&client_ctx->enrty_queue_lock); return false; } EXPORT_SYMBOL(vidc_insert_addr_table_kernel); u32 vidc_delete_addr_table(struct video_client_ctx *client_ctx, enum buffer_dir buffer, unsigned long user_vaddr, unsigned long *kernel_vaddr) { u32 *num_of_buffers = NULL; u32 i; struct buf_addr_table *buf_addr_table; if (!client_ctx) return false; mutex_lock(&client_ctx->enrty_queue_lock); if (buffer == BUFFER_TYPE_INPUT) { buf_addr_table = client_ctx->input_buf_addr_table; num_of_buffers = &client_ctx->num_of_input_buffers; } else { buf_addr_table = client_ctx->output_buf_addr_table; num_of_buffers = &client_ctx->num_of_output_buffers; } if (!*num_of_buffers) goto bail_out_del; i = 0; while (i < *num_of_buffers && user_vaddr != buf_addr_table[i].user_vaddr) i++; if (i == *num_of_buffers) { pr_err("%s() : client_ctx = %p." " user_virt_addr = 0x%08lx NOT found", __func__, client_ctx, user_vaddr); goto bail_out_del; } if (buf_addr_table[i].client_data) { msm_subsystem_unmap_buffer( (struct msm_mapped_buffer *)buf_addr_table[i].client_data); buf_addr_table[i].client_data = NULL; } *kernel_vaddr = buf_addr_table[i].kernel_vaddr; if (buf_addr_table[i].buff_ion_handle) { ion_unmap_kernel(client_ctx->user_ion_client, buf_addr_table[i].buff_ion_handle); if (!res_trk_check_for_sec_session()) { ion_unmap_iommu(client_ctx->user_ion_client, buf_addr_table[i].buff_ion_handle, VIDEO_DOMAIN, VIDEO_MAIN_POOL); } ion_free(client_ctx->user_ion_client, buf_addr_table[i].buff_ion_handle); buf_addr_table[i].buff_ion_handle = NULL; } if (i < (*num_of_buffers - 1)) { buf_addr_table[i].client_data = buf_addr_table[*num_of_buffers - 1].client_data; buf_addr_table[i].dev_addr = buf_addr_table[*num_of_buffers - 1].dev_addr; buf_addr_table[i].user_vaddr = buf_addr_table[*num_of_buffers - 1].user_vaddr; buf_addr_table[i].kernel_vaddr = buf_addr_table[*num_of_buffers - 1].kernel_vaddr; buf_addr_table[i].phy_addr = buf_addr_table[*num_of_buffers - 1].phy_addr; buf_addr_table[i].pmem_fd = buf_addr_table[*num_of_buffers - 1].pmem_fd; buf_addr_table[i].file = buf_addr_table[*num_of_buffers - 1].file; buf_addr_table[i].buff_ion_handle = buf_addr_table[*num_of_buffers - 1].buff_ion_handle; } *num_of_buffers = *num_of_buffers - 1; DBG("%s() : client_ctx = %p." " user_virt_addr = 0x%08lx is found and deleted", __func__, client_ctx, user_vaddr); mutex_unlock(&client_ctx->enrty_queue_lock); return true; bail_out_del: mutex_unlock(&client_ctx->enrty_queue_lock); return false; } EXPORT_SYMBOL(vidc_delete_addr_table); u32 vidc_timer_create(void (*timer_handler)(void *), void *user_data, void **timer_handle) { struct vidc_timer *hw_timer = NULL; if (!timer_handler || !timer_handle) { DBG("%s(): timer creation failed\n ", __func__); return false; } hw_timer = kzalloc(sizeof(struct vidc_timer), GFP_KERNEL); if (!hw_timer) { DBG("%s(): timer creation failed in allocation\n ", __func__); return false; } init_timer(&hw_timer->hw_timeout); hw_timer->hw_timeout.data = (unsigned long)hw_timer; hw_timer->hw_timeout.function = vidc_timer_fn; hw_timer->cb_func = timer_handler; hw_timer->userdata = user_data; *timer_handle = hw_timer; return true; } EXPORT_SYMBOL(vidc_timer_create); void vidc_timer_release(void *timer_handle) { kfree(timer_handle); } EXPORT_SYMBOL(vidc_timer_release); void vidc_timer_start(void *timer_handle, u32 time_out) { struct vidc_timer *hw_timer = (struct vidc_timer *)timer_handle; DBG("%s(): start timer\n ", __func__); if (hw_timer) { hw_timer->hw_timeout.expires = jiffies + 1*HZ; add_timer(&hw_timer->hw_timeout); } } EXPORT_SYMBOL(vidc_timer_start); void vidc_timer_stop(void *timer_handle) { struct vidc_timer *hw_timer = (struct vidc_timer *)timer_handle; DBG("%s(): stop timer\n ", __func__); if (hw_timer) del_timer(&hw_timer->hw_timeout); } EXPORT_SYMBOL(vidc_timer_stop); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("Video decoder/encoder driver Init Module"); MODULE_VERSION("1.0"); module_init(vidc_init); module_exit(vidc_exit);
androidarmv6/android_kernel_lge_msm7x27-3.0.x
drivers/video/msm/vidc/common/init/vidc_init.c
C
gpl-2.0
26,236
#ifndef _LINUX_RMAP_H #define _LINUX_RMAP_H /* * Declarations for Reverse Mapping functions in mm/rmap.c */ #include <linux/list.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/spinlock.h> #include <linux/memcontrol.h> /* * The anon_vma heads a list of private "related" vmas, to scan if * an anonymous page pointing to this anon_vma needs to be unmapped: * the vmas on the list will be related by forking, or by splitting. * * Since vmas come and go as they are split and merged (particularly * in mprotect), the mapping field of an anonymous page cannot point * directly to a vma: instead it points to an anon_vma, on whose list * the related vmas can be easily linked or unlinked. * * After unlinking the last vma on the list, we must garbage collect * the anon_vma object itself: we're guaranteed no page can be * pointing to this anon_vma once its vma list is empty. */ struct anon_vma { spinlock_t lock; /* Serialize access to vma list */ /* * NOTE: the LSB of the head.next is set by * mm_take_all_locks() _after_ taking the above lock. So the * head must only be read/written after taking the above lock * to be sure to see a valid next pointer. The LSB bit itself * is serialized by a system wide lock only visible to * mm_take_all_locks() (mm_all_locks_mutex). */ struct list_head head; /* List of private "related" vmas */ }; #ifdef CONFIG_MMU static inline struct anon_vma *page_anon_vma(struct page *page) { if (((unsigned long)page->mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON) return NULL; return page_rmapping(page); } static inline void anon_vma_lock(struct vm_area_struct *vma) { struct anon_vma *anon_vma = vma->anon_vma; if (anon_vma) spin_lock(&anon_vma->lock); } static inline void anon_vma_unlock(struct vm_area_struct *vma) { struct anon_vma *anon_vma = vma->anon_vma; if (anon_vma) spin_unlock(&anon_vma->lock); } /* * anon_vma helper functions. */ void anon_vma_init(void); /* create anon_vma_cachep */ int anon_vma_prepare(struct vm_area_struct *); void __anon_vma_merge(struct vm_area_struct *, struct vm_area_struct *); void anon_vma_unlink(struct vm_area_struct *); void anon_vma_link(struct vm_area_struct *); void __anon_vma_link(struct vm_area_struct *); /* * rmap interfaces called when adding or removing pte of page */ void page_add_anon_rmap(struct page *, struct vm_area_struct *, unsigned long); void page_add_new_anon_rmap(struct page *, struct vm_area_struct *, unsigned long); void page_add_file_rmap(struct page *); void page_remove_rmap(struct page *); static inline void page_dup_rmap(struct page *page) { atomic_inc(&page->_mapcount); } /* * Called from mm/vmscan.c to handle paging out */ int page_referenced(struct page *, int is_locked, struct mem_cgroup *cnt, unsigned long *vm_flags); enum ttu_flags { TTU_UNMAP = 0, /* unmap mode */ TTU_MIGRATION = 1, /* migration mode */ TTU_MUNLOCK = 2, /* munlock mode */ TTU_ACTION_MASK = 0xff, TTU_IGNORE_MLOCK = (1 << 8), /* ignore mlock */ TTU_IGNORE_ACCESS = (1 << 9), /* don't age */ TTU_IGNORE_HWPOISON = (1 << 10),/* corrupted page is recoverable */ }; #define TTU_ACTION(x) ((x) & TTU_ACTION_MASK) int try_to_unmap(struct page *, enum ttu_flags flags); /* * Called from mm/filemap_xip.c to unmap empty zero page */ pte_t *page_check_address(struct page *, struct mm_struct *, unsigned long, spinlock_t **, int); /* * Used by swapoff to help locate where page is expected in vma. */ unsigned long page_address_in_vma(struct page *, struct vm_area_struct *); /* * Cleans the PTEs of shared mappings. * (and since clean PTEs should also be readonly, write protects them too) * * returns the number of cleaned PTEs. */ int page_mkclean(struct page *); /* * called in munlock()/munmap() path to check for other vmas holding * the page mlocked. */ int try_to_munlock(struct page *); /* * Called by memory-failure.c to kill processes. */ struct anon_vma *page_lock_anon_vma(struct page *page); void page_unlock_anon_vma(struct anon_vma *anon_vma); int page_mapped_in_vma(struct page *page, struct vm_area_struct *vma); #else /* !CONFIG_MMU */ #define anon_vma_init() do {} while (0) #define anon_vma_prepare(vma) (0) #define anon_vma_link(vma) do {} while (0) static inline int page_referenced(struct page *page, int is_locked, struct mem_cgroup *cnt, unsigned long *vm_flags) { *vm_flags = 0; return TestClearPageReferenced(page); } #define try_to_unmap(page, refs) SWAP_FAIL static inline int page_mkclean(struct page *page) { return 0; } #endif /* CONFIG_MMU */ /* * Return values of try_to_unmap */ #define SWAP_SUCCESS 0 #define SWAP_AGAIN 1 #define SWAP_FAIL 2 #define SWAP_MLOCK 3 #endif /* _LINUX_RMAP_H */
MartinsAD/xperia-kernel-msm7x30
include/linux/rmap.h
C
gpl-2.0
4,761
SET @s = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmstats.pl' ) > 0 AND ( SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmstats' ) = 0 , "ALTER TABLE Servers CHANGE COLUMN `zmstats.pl` `zmstats` BOOLEAN NOT NULL DEFAULT FALSE", "SELECT 'zmstats.pl has already been changed to zmstats'" )); PREPARE stmt FROM @s; EXECUTE stmt; SET @s = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmstats.pl' ) > 0, "ALTER TABLE Servers DROP COLUMN `zmstats.pl`", "SELECT 'zmstats.pl has already been removed'" )); PREPARE stmt FROM @s; EXECUTE stmt; SET @s = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmaudit.pl' ) > 0 AND ( SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmaudit' ) = 0 , "ALTER TABLE Servers CHANGE COLUMN `zmaudit.pl` `zmaudit` BOOLEAN NOT NULL DEFAULT FALSE", "SELECT 'zmaudit.pl has already been changed to zmaudit'" )); PREPARE stmt FROM @s; EXECUTE stmt; SET @s = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmaudit.pl' ) > 0, "ALTER TABLE Servers DROP COLUMN `zmaudit.pl`", "SELECT 'zmaudit.pl has already been removed'" )); PREPARE stmt FROM @s; EXECUTE stmt; SET @s = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmtrigger.pl' ) > 0 AND ( SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmtrigger' ) = 0 , "ALTER TABLE Servers CHANGE COLUMN `zmtrigger.pl` `zmtrigger` BOOLEAN NOT NULL DEFAULT FALSE", "SELECT 'zmtrigger.pl has already been changed to zmtrigger'" )); PREPARE stmt FROM @s; EXECUTE stmt; SET @s = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() AND table_name = 'Servers' AND column_name = 'zmtrigger.pl' ) > 0, "ALTER TABLE Servers DROP COLUMN `zmtrigger.pl`", "SELECT 'zmtrigger.pl has already been removed'" )); PREPARE stmt FROM @s; EXECUTE stmt;
SteveGilvarry/ZoneMinder
db/zm_update-1.31.23.sql
SQL
gpl-2.0
2,718
/* * Copyright (C) 2009 Google, Inc. * Copyright (C) 2010 HTC Corporation. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ /* Control bluetooth power for shooter platform */ #include <linux/platform_device.h> #include <linux/module.h> #include <linux/device.h> #include <linux/rfkill.h> #include <linux/delay.h> #include <linux/gpio.h> #include <asm/mach-types.h> #include <linux/mfd/pmic8058.h> #include "board-shooter.h" #ifdef CONFIG_MACH_SHOOTER_U #include <mach/htc_sleep_clk.h> #endif static struct rfkill *bt_rfk; static const char bt_name[] = "bcm4329"; /* bt on configuration */ static uint32_t shooter_bt_on_table[] = { /* BT_RTS */ GPIO_CFG(shooter_GPIO_BT_UART1_RTS, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), /* BT_CTS */ GPIO_CFG(shooter_GPIO_BT_UART1_CTS, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), /* BT_RX */ GPIO_CFG(shooter_GPIO_BT_UART1_RX, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), /* BT_TX */ GPIO_CFG(shooter_GPIO_BT_UART1_TX, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), /* BT_HOST_WAKE */ GPIO_CFG(shooter_GPIO_BT_HOST_WAKE, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), /* BT_CHIP_WAKE */ GPIO_CFG(shooter_GPIO_BT_CHIP_WAKE, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), /* BT_RESET_N */ GPIO_CFG(shooter_GPIO_BT_RESET_N, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), /* BT_SHUTDOWN_N */ GPIO_CFG(shooter_GPIO_BT_SHUTDOWN_N, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), }; /* bt off configuration */ static uint32_t shooter_bt_off_table[] = { /* BT_RTS */ GPIO_CFG(shooter_GPIO_BT_UART1_RTS, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), /* BT_CTS */ GPIO_CFG(shooter_GPIO_BT_UART1_CTS, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), /* BT_RX */ GPIO_CFG(shooter_GPIO_BT_UART1_RX, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), /* BT_TX */ GPIO_CFG(shooter_GPIO_BT_UART1_TX, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), /* BT_RESET_N */ GPIO_CFG(shooter_GPIO_BT_RESET_N, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), /* BT_SHUTDOWN_N */ GPIO_CFG(shooter_GPIO_BT_SHUTDOWN_N, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), /* BT_HOST_WAKE */ GPIO_CFG(shooter_GPIO_BT_HOST_WAKE, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_4MA), /* BT_CHIP_WAKE */ GPIO_CFG(shooter_GPIO_BT_CHIP_WAKE, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), }; static void config_bt_table(uint32_t *table, int len) { int n, rc; for (n = 0; n < len; n++) { rc = gpio_tlmm_config(table[n], GPIO_CFG_ENABLE); if (rc) { pr_err("[BT]%s: gpio_tlmm_config(%#x)=%d\n", __func__, table[n], rc); break; } } } static void shooter_config_bt_on(void) { printk(KERN_INFO "[BT]-- R ON --\n"); /* set bt on configuration*/ config_bt_table(shooter_bt_on_table, ARRAY_SIZE(shooter_bt_on_table)); mdelay(5); /* BT_SHUTDOWN_N */ gpio_set_value(shooter_GPIO_BT_SHUTDOWN_N, 1); /*mdelay(2);*/ /* BT_RESET_N */ gpio_set_value(shooter_GPIO_BT_RESET_N, 1); mdelay(2); } static void shooter_config_bt_off(void) { printk(KERN_INFO "[BT]-- R OFF --\n"); /* BT_RESET_N */ gpio_set_value(shooter_GPIO_BT_RESET_N, 0); /*mdelay(2);*/ /* BT_SHUTDOWN_N */ gpio_set_value(shooter_GPIO_BT_SHUTDOWN_N, 0); mdelay(2); /* set bt off configuration*/ config_bt_table(shooter_bt_off_table, ARRAY_SIZE(shooter_bt_off_table)); mdelay(5); /* BT_RTS */ gpio_set_value(shooter_GPIO_BT_UART1_RTS, 1); /* BT_CTS */ /* BT_RX */ /* BT_TX */ gpio_set_value(shooter_GPIO_BT_UART1_TX, 0); /* BT_HOST_WAKE */ /* BT_CHIP_WAKE */ gpio_set_value(shooter_GPIO_BT_CHIP_WAKE, 0); } static int bluetooth_set_power(void *data, bool blocked) { if (!blocked) shooter_config_bt_on(); else shooter_config_bt_off(); return 0; } static struct rfkill_ops shooter_rfkill_ops = { .set_block = bluetooth_set_power, }; static int shooter_rfkill_probe(struct platform_device *pdev) { int rc = 0; bool default_state = true; /* off */ #ifdef CONFIG_MACH_SHOOTER_U rc = gpio_request(shooter_GPIO_BT_RESET_N, "bt_reset"); if (rc) goto err_gpio_reset; rc = gpio_request(shooter_GPIO_BT_SHUTDOWN_N, "bt_shutdown"); if (rc) goto err_gpio_shutdown; htc_wifi_bt_sleep_clk_ctl(CLK_ON, ID_BT); #endif mdelay(2); bluetooth_set_power(NULL, default_state); bt_rfk = rfkill_alloc(bt_name, &pdev->dev, RFKILL_TYPE_BLUETOOTH, &shooter_rfkill_ops, NULL); if (!bt_rfk) { rc = -ENOMEM; goto err_rfkill_alloc; } rfkill_set_states(bt_rfk, default_state, false); /* userspace cannot take exclusive control */ rc = rfkill_register(bt_rfk); if (rc) goto err_rfkill_reg; return 0; err_rfkill_reg: rfkill_destroy(bt_rfk); err_rfkill_alloc: #ifdef CONFIG_MACH_SHOOTER_U gpio_free(shooter_GPIO_BT_SHUTDOWN_N); err_gpio_shutdown: gpio_free(shooter_GPIO_BT_RESET_N); err_gpio_reset: #endif return rc; } static int shooter_rfkill_remove(struct platform_device *dev) { rfkill_unregister(bt_rfk); /*rfkill_free(bt_rfk);*/ rfkill_destroy(bt_rfk); #ifdef CONFIG_MACH_SHOOTER_U gpio_free(shooter_GPIO_BT_SHUTDOWN_N); gpio_free(shooter_GPIO_BT_RESET_N); #endif return 0; } static struct platform_driver shooter_rfkill_driver = { .probe = shooter_rfkill_probe, .remove = shooter_rfkill_remove, .driver = { .name = "shooter_rfkill", .owner = THIS_MODULE, }, }; static int __init shooter_rfkill_init(void) { return platform_driver_register(&shooter_rfkill_driver); } static void __exit shooter_rfkill_exit(void) { platform_driver_unregister(&shooter_rfkill_driver); } module_init(shooter_rfkill_init); module_exit(shooter_rfkill_exit); MODULE_DESCRIPTION("shooter rfkill"); MODULE_AUTHOR("Nick Pelly <[email protected]>"); MODULE_LICENSE("GPL");
TheBootloader/android_kernel_shooter
arch/arm/mach-msm/board-shooter-rfkill.c
C
gpl-2.0
6,410
<?php /** * CSV Parsing class for TablePress, used for import of CSV files * * @package TablePress * @subpackage Import * @author Tobias Bäthge * @since 1.0.0 */ // Prohibit direct script loading defined( 'ABSPATH' ) || die( 'No direct script access allowed!' ); /** * CSV Parsing class * @package TablePress * @subpackage Import * @author Tobias Bäthge * @since 1.0.0 */ class CSV_Parser { // enclosure (double quote) protected $enclosure = '"'; // number of rows to analyze when attempting to auto-detect delimiter protected $delimiter_search_max_lines = 15; // characters to ignore when attempting to auto-detect delimiter protected $non_delimiter_chars = "a-zA-Z0-9\n\r"; // preferred delimiter characters, only used when all filtering method // returns multiple possible delimiters (happens very rarely) protected $preferred_delimiter_chars = ";,\t"; // data to import protected $import_data; // error while parsing input data // 0 = No errors found. Everything should be fine :) // 1 = Hopefully correctable syntax error was found. // 2 = Enclosure character (double quote by default) was found in non-enclosed field. // This means the file is either corrupt, or does not standard CSV formatting. // Please validate the parsed data yourself. public $error = 0; // detailed error info public $error_info = array(); /** * Constructor * * @since 1.0.0 */ public function __construct() { // intentionally left blank } /** * Load data that shall be parsed * * @since 1.0.0 * * @param string $data Data to be parsed */ public function load_data( $data ) { // check for mandatory trailing line break if ( substr( $data, -1 ) != "\n" ) { $data .= "\n"; } $this->import_data = &$data; } /** * Detect the CSV delimiter, by analyzing some rows to determine most probable delimiter character * * @since 1.0.0 * * @return string Most probable delimiter character */ public function find_delimiter() { $data = &$this->import_data; $delimiter_count = array(); $enclosed = false; $current_line = 0; // walk through each character in the CSV string (up to $this->delimiter_search_max_lines) // and search potential delimiter characters $data_length = strlen( $data ); for ( $i = 0; $i < $data_length; $i++ ) { $prev_char = ( $i-1 >= 0 ) ? $data[$i-1] : ''; $curr_char = $data[$i]; $next_char = ( $i+1 < $data_length ) ? $data[$i+1] : ''; if ( $curr_char == $this->enclosure ) { // open and closing quotes if ( ! $enclosed || $next_char != $this->enclosure ) { $enclosed = ! $enclosed; // flip bool } elseif ( $enclosed ) { $i++; // skip next character } } elseif ( ( "\n" == $curr_char && "\r" != $prev_char || "\r" == $curr_char ) && ! $enclosed ) { // reached end of a line $current_line++; if ( $current_line >= $this->delimiter_search_max_lines ) { break; } } elseif ( ! $enclosed ) { // at this point $curr_char seems to be used as a delimiter, as it is not enclosed // count $curr_char if it is not in the non_delimiter_chars list if ( 0 === preg_match( '#[' . $this->non_delimiter_chars . ']#i', $curr_char ) ) { if ( ! isset( $delimiter_count[$curr_char][$current_line] ) ) { $delimiter_count[$curr_char][$current_line] = 0; // init empty } $delimiter_count[$curr_char][$current_line]++; } } } // find most probable delimiter, by sorting their counts $potential_delimiters = array(); foreach ( $delimiter_count as $char => $line_counts ) { $is_possible_delimiter = $this->_check_delimiter_count( $char, $line_counts, $current_line ); if ( false !== $is_possible_delimiter ) { $potential_delimiters[$is_possible_delimiter] = $char; } } ksort( $potential_delimiters ); // return first array element, as that has the highest count return array_shift( $potential_delimiters ); } /** * Check if passed character can be a delimiter, by checking counts in each line * * @since 1.0.0 * * @param string|char $char Character to check * @param array $line_counts * @param int $number_lines * @return bool|string False if delimiter is not possible, string to be used as a sort key if character could be a delimiter */ protected function _check_delimiter_count( $char, array $line_counts, $number_lines ) { // was potential delimiter found in every line? if ( count( $line_counts ) != $number_lines ) { return false; } // check if count in every line is the same (or one higher for "almost") $first = null; $equal = null; $almost = false; foreach ( $line_counts as $line => $count ) { if ( null == $first ) { $first = $count; } elseif ( $count == $first && false !== $equal ) { $equal = true; } elseif ( $count == $first + 1 && false !== $equal ) { $equal = true; $almost = true; } else { $equal = false; } } // check equality only if more than one row if ( $number_lines > 1 && ! $equal ) { return false; } // at this point, count is equal in all lines, determine a string to sort priority $match = ( $almost ) ? 2 : 1 ; $pref = strpos( $this->preferred_delimiter_chars, $char ); $pref = ( false !== $pref ) ? str_pad( $pref, 3, '0', STR_PAD_LEFT ) : '999'; return $pref . $match . '.' . ( 99999 - str_pad( $first, 5, '0', STR_PAD_LEFT ) ); } /** * Parse CSV string into 2D array * * @since 1.0.0 * * @param string $delimiter Delimiter character for the CSV parsing * @return array 2D array with the data from the CSV string */ public function parse( $delimiter ) { $data = &$this->import_data; $white_spaces = str_replace( $delimiter, '', " \t\x0B\0" ); // filter delimiter from the list, if it is a white-space character $rows = array(); // complete rows $row = array(); // row that is currently built $column = 0; // current column index $cell_content = ''; // content of the currently processed cell $enclosed = false; $was_enclosed = false; // to determine if cell content will be trimmed of white-space (only for enclosed cells) // walk through each character in the CSV string $data_length = strlen( $data ); for ( $i = 0; $i < $data_length; $i++ ) { $curr_char = $data[$i]; $next_char = ( $i+1 < $data_length ) ? $data[$i+1] : ''; if ( $curr_char == $this->enclosure ) { // open/close quotes, and inline quotes if ( ! $enclosed ) { if ( '' == ltrim( $cell_content, $white_spaces ) ) { $enclosed = true; $was_enclosed = true; } else { $this->error = 2; $error_line = count( $rows ) + 1; $error_column = $column + 1; if ( ! isset( $this->error_info[ $error_line.'-'.$error_column ] ) ) { $this->error_info[ $error_line.'-'.$error_column ] = array( 'type' => 2, 'info' => "Syntax error found in line {$error_line}. Non-enclosed fields can not contain double-quotes.", 'line' => $error_line, 'column' => $error_column ); } $cell_content .= $curr_char; } } elseif ( $next_char == $this->enclosure ) { // enclosure character within enclosed cell (" encoded as "") $cell_content .= $curr_char; $i++; // skip next character } elseif ( $next_char != $delimiter && "\r" != $next_char && "\n" != $next_char ) { // for-loop (instead of while-loop) that skips white-space for ( $x = ( $i+1 ); isset( $data[$x] ) && '' == ltrim( $data[$x], $white_spaces ); $x++ ) {} if ( $data[$x] == $delimiter ) { $enclosed = false; $i = $x; } else { if ( $this->error < 1 ) { $this->error = 1; } $error_line = count( $rows ) + 1; $error_column = $column + 1; if ( ! isset( $this->error_info[ $error_line.'-'.$error_column ] ) ) { $this->error_info[ $error_line.'-'.$error_column ] = array( 'type' => 1, 'info' => "Syntax error found in line {$error_line}. A single double-quote was found within an enclosed string. Enclosed double-quotes must be escaped with a second double-quote.", 'line' => $error_line, 'column' => $error_column ); } $cell_content .= $curr_char; $enclosed = false; } } else { // the " was the closing one for the cell $enclosed = false; } } elseif ( ( $curr_char == $delimiter || "\n" == $curr_char || "\r" == $curr_char ) && ! $enclosed ) { // end of cell (by $delimiter), or end of line (by line break, and not enclosed!) $row[$column] = ( $was_enclosed ) ? $cell_content : trim( $cell_content ); $cell_content = ''; $was_enclosed = false; $column++; // end of line if ( "\n" == $curr_char || "\r" == $curr_char ) { // append completed row $rows[] = $row; $row = array(); $column = 0; if ( "\r" == $curr_char && "\n" == $next_char ) { $i++; // skip next character in \r\n line breaks } } } else { // append character to current cell $cell_content .= $curr_char; } } return $rows; } } // class CSV_Parser
AmrutHunashyal/wordpress
wp-content/plugins/tablepress/libraries/csv-parser.class.php
PHP
gpl-2.0
9,087
require 'spec_helper' describe IncomingLinksReport do describe 'integration' do it 'runs correctly' do p1 = create_post IncomingLink.add( referer: 'http://test.com', host: 'http://boo.com', topic_id: p1.topic.id, ip_address: '10.0.0.2', username: p1.user.username ) c = IncomingLinksReport.link_count_per_topic c[p1.topic_id].should == 1 c = IncomingLinksReport.link_count_per_domain c["test.com"].should == 1 c = IncomingLinksReport.topic_count_per_domain(['test.com', 'foo.com']) c["test.com"].should == 1 c = IncomingLinksReport.topic_count_per_user() c[p1.username].should == 1 end end describe 'top_referrers' do subject(:top_referrers) { IncomingLinksReport.find('top_referrers').as_json } def stub_empty_referrers_data IncomingLinksReport.stubs(:link_count_per_user).returns({}) IncomingLinksReport.stubs(:topic_count_per_user).returns({}) end it 'returns localized titles' do stub_empty_referrers_data top_referrers[:title].should be_present top_referrers[:xaxis].should be_present top_referrers[:ytitles].should be_present top_referrers[:ytitles][:num_clicks].should be_present top_referrers[:ytitles][:num_topics].should be_present end it 'with no IncomingLink records, it returns correct data' do stub_empty_referrers_data top_referrers[:data].should have(0).records end it 'with some IncomingLink records, it returns correct data' do IncomingLinksReport.stubs(:link_count_per_user).returns({'luke' => 4, 'chewie' => 2}) IncomingLinksReport.stubs(:topic_count_per_user).returns({'luke' => 2, 'chewie' => 1}) top_referrers[:data][0].should == {username: 'luke', num_clicks: 4, num_topics: 2} top_referrers[:data][1].should == {username: 'chewie', num_clicks: 2, num_topics: 1} end end describe 'top_traffic_sources' do subject(:top_traffic_sources) { IncomingLinksReport.find('top_traffic_sources').as_json } def stub_empty_traffic_source_data IncomingLinksReport.stubs(:link_count_per_domain).returns({}) IncomingLinksReport.stubs(:topic_count_per_domain).returns({}) IncomingLinksReport.stubs(:user_count_per_domain).returns({}) end it 'returns localized titles' do stub_empty_traffic_source_data top_traffic_sources[:title].should be_present top_traffic_sources[:xaxis].should be_present top_traffic_sources[:ytitles].should be_present top_traffic_sources[:ytitles][:num_clicks].should be_present top_traffic_sources[:ytitles][:num_topics].should be_present top_traffic_sources[:ytitles][:num_users].should be_present end it 'with no IncomingLink records, it returns correct data' do stub_empty_traffic_source_data top_traffic_sources[:data].should have(0).records end it 'with some IncomingLink records, it returns correct data' do IncomingLinksReport.stubs(:link_count_per_domain).returns({'twitter.com' => 8, 'facebook.com' => 3}) IncomingLinksReport.stubs(:topic_count_per_domain).returns({'twitter.com' => 2, 'facebook.com' => 3}) top_traffic_sources[:data][0].should == {domain: 'twitter.com', num_clicks: 8, num_topics: 2} top_traffic_sources[:data][1].should == {domain: 'facebook.com', num_clicks: 3, num_topics: 3} end end describe 'top_referred_topics' do subject(:top_referred_topics) { IncomingLinksReport.find('top_referred_topics').as_json } def stub_empty_referred_topics_data IncomingLinksReport.stubs(:link_count_per_topic).returns({}) end it 'returns localized titles' do stub_empty_referred_topics_data top_referred_topics[:title].should be_present top_referred_topics[:xaxis].should be_present top_referred_topics[:ytitles].should be_present top_referred_topics[:ytitles][:num_clicks].should be_present end it 'with no IncomingLink records, it returns correct data' do stub_empty_referred_topics_data top_referred_topics[:data].should have(0).records end it 'with some IncomingLink records, it returns correct data' do topic1 = Fabricate.build(:topic, id: 123); topic2 = Fabricate.build(:topic, id: 234) IncomingLinksReport.stubs(:link_count_per_topic).returns({topic1.id => 8, topic2.id => 3}) Topic.stubs(:select).returns(Topic); Topic.stubs(:where).returns(Topic) # bypass some activerecord methods Topic.stubs(:all).returns([topic1, topic2]) top_referred_topics[:data][0].should == {topic_id: topic1.id, topic_title: topic1.title, topic_slug: topic1.slug, num_clicks: 8 } top_referred_topics[:data][1].should == {topic_id: topic2.id, topic_title: topic2.title, topic_slug: topic2.slug, num_clicks: 3 } end end end
DeanMarkTaylor/discourse
spec/models/incoming_links_report_spec.rb
Ruby
gpl-2.0
4,878
/* Overhauled routines for dealing with different mmap regions of flash */ #ifndef __LINUX_MTD_MAP_H__ #define __LINUX_MTD_MAP_H__ #include <linux/types.h> #include <linux/list.h> #include <linux/string.h> #include <linux/mtd/compatmac.h> #include <asm/unaligned.h> #include <asm/system.h> #include <asm/io.h> #ifdef CONFIG_MTD_MAP_BANK_WIDTH_1 #define map_bankwidth(map) 1 #define map_bankwidth_is_1(map) (map_bankwidth(map) == 1) #define map_bankwidth_is_large(map) (0) #define map_words(map) (1) #define MAX_MAP_BANKWIDTH 1 #else #define map_bankwidth_is_1(map) (0) #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_2 # ifdef map_bankwidth # undef map_bankwidth # define map_bankwidth(map) ((map)->bankwidth) # else # define map_bankwidth(map) 2 # define map_bankwidth_is_large(map) (0) # define map_words(map) (1) # endif #define map_bankwidth_is_2(map) (map_bankwidth(map) == 2) #undef MAX_MAP_BANKWIDTH #define MAX_MAP_BANKWIDTH 2 #else #define map_bankwidth_is_2(map) (0) #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_4 # ifdef map_bankwidth # undef map_bankwidth # define map_bankwidth(map) ((map)->bankwidth) # else # define map_bankwidth(map) 4 # define map_bankwidth_is_large(map) (0) # define map_words(map) (1) # endif #define map_bankwidth_is_4(map) (map_bankwidth(map) == 4) #undef MAX_MAP_BANKWIDTH #define MAX_MAP_BANKWIDTH 4 #else #define map_bankwidth_is_4(map) (0) #endif /* ensure we never evaluate anything shorted than an unsigned long * to zero, and ensure we'll never miss the end of an comparison (bjd) */ #define map_calc_words(map) ((map_bankwidth(map) + (sizeof(unsigned long)-1))/ sizeof(unsigned long)) #ifdef CONFIG_MTD_MAP_BANK_WIDTH_8 # ifdef map_bankwidth # undef map_bankwidth # define map_bankwidth(map) ((map)->bankwidth) # if BITS_PER_LONG < 64 # undef map_bankwidth_is_large # define map_bankwidth_is_large(map) (map_bankwidth(map) > BITS_PER_LONG/8) # undef map_words # define map_words(map) map_calc_words(map) # endif # else # define map_bankwidth(map) 8 # define map_bankwidth_is_large(map) (BITS_PER_LONG < 64) # define map_words(map) map_calc_words(map) # endif #define map_bankwidth_is_8(map) (map_bankwidth(map) == 8) #undef MAX_MAP_BANKWIDTH #define MAX_MAP_BANKWIDTH 8 #else #define map_bankwidth_is_8(map) (0) #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_16 # ifdef map_bankwidth # undef map_bankwidth # define map_bankwidth(map) ((map)->bankwidth) # undef map_bankwidth_is_large # define map_bankwidth_is_large(map) (map_bankwidth(map) > BITS_PER_LONG/8) # undef map_words # define map_words(map) map_calc_words(map) # else # define map_bankwidth(map) 16 # define map_bankwidth_is_large(map) (1) # define map_words(map) map_calc_words(map) # endif #define map_bankwidth_is_16(map) (map_bankwidth(map) == 16) #undef MAX_MAP_BANKWIDTH #define MAX_MAP_BANKWIDTH 16 #else #define map_bankwidth_is_16(map) (0) #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_32 # ifdef map_bankwidth # undef map_bankwidth # define map_bankwidth(map) ((map)->bankwidth) # undef map_bankwidth_is_large # define map_bankwidth_is_large(map) (map_bankwidth(map) > BITS_PER_LONG/8) # undef map_words # define map_words(map) map_calc_words(map) # else # define map_bankwidth(map) 32 # define map_bankwidth_is_large(map) (1) # define map_words(map) map_calc_words(map) # endif #define map_bankwidth_is_32(map) (map_bankwidth(map) == 32) #undef MAX_MAP_BANKWIDTH #define MAX_MAP_BANKWIDTH 32 #else #define map_bankwidth_is_32(map) (0) #endif #ifndef map_bankwidth #warning "No CONFIG_MTD_MAP_BANK_WIDTH_xx selected. No NOR chip support can work" static inline int map_bankwidth(void *map) { BUG(); return 0; } #define map_bankwidth_is_large(map) (0) #define map_words(map) (0) #define MAX_MAP_BANKWIDTH 1 #endif static inline int map_bankwidth_supported(int w) { switch (w) { #ifdef CONFIG_MTD_MAP_BANK_WIDTH_1 case 1: #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_2 case 2: #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_4 case 4: #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_8 case 8: #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_16 case 16: #endif #ifdef CONFIG_MTD_MAP_BANK_WIDTH_32 case 32: #endif return 1; default: return 0; } } #define MAX_MAP_LONGS ( ((MAX_MAP_BANKWIDTH*8) + BITS_PER_LONG - 1) / BITS_PER_LONG ) typedef union { unsigned long x[MAX_MAP_LONGS]; } map_word; /* The map stuff is very simple. You fill in your struct map_info with a handful of routines for accessing the device, making sure they handle paging etc. correctly if your device needs it. Then you pass it off to a chip probe routine -- either JEDEC or CFI probe or both -- via do_map_probe(). If a chip is recognised, the probe code will invoke the appropriate chip driver (if present) and return a struct mtd_info. At which point, you fill in the mtd->module with your own module address, and register it with the MTD core code. Or you could partition it and register the partitions instead, or keep it for your own private use; whatever. The mtd->priv field will point to the struct map_info, and any further private data required by the chip driver is linked from the mtd->priv->fldrv_priv field. This allows the map driver to get at the destructor function map->fldrv_destroy() when it's tired of living. */ struct map_info { const char *name; unsigned long size; resource_size_t phys; #define NO_XIP (-1UL) void __iomem *virt; void *cached; int bankwidth; /* in octets. This isn't necessarily the width of actual bus cycles -- it's the repeat interval in bytes, before you are talking to the first chip again. */ #ifdef CONFIG_MTD_COMPLEX_MAPPINGS map_word (*read)(struct map_info *, unsigned long); void (*copy_from)(struct map_info *, void *, unsigned long, ssize_t); void (*write)(struct map_info *, const map_word, unsigned long); void (*copy_to)(struct map_info *, unsigned long, const void *, ssize_t); /* We can perhaps put in 'point' and 'unpoint' methods, if we really want to enable XIP for non-linear mappings. Not yet though. */ #endif /* It's possible for the map driver to use cached memory in its copy_from implementation (and _only_ with copy_from). However, when the chip driver knows some flash area has changed contents, it will signal it to the map driver through this routine to let the map driver invalidate the corresponding cache as needed. If there is no cache to care about this can be set to NULL. */ void (*inval_cache)(struct map_info *, unsigned long, ssize_t); /* set_vpp() must handle being reentered -- enable, enable, disable must leave it enabled. */ void (*set_vpp)(struct map_info *, int); unsigned long pfow_base; unsigned long map_priv_1; unsigned long map_priv_2; void *fldrv_priv; struct mtd_chip_driver *fldrv; }; struct mtd_chip_driver { struct mtd_info *(*probe)(struct map_info *map); void (*destroy)(struct mtd_info *); struct module *module; char *name; struct list_head list; }; void register_mtd_chip_driver(struct mtd_chip_driver *); void unregister_mtd_chip_driver(struct mtd_chip_driver *); struct mtd_info *do_map_probe(const char *name, struct map_info *map); void map_destroy(struct mtd_info *mtd); #define ENABLE_VPP(map) do { if(map->set_vpp) map->set_vpp(map, 1); } while(0) #define DISABLE_VPP(map) do { if(map->set_vpp) map->set_vpp(map, 0); } while(0) #define INVALIDATE_CACHED_RANGE(map, from, size) \ do { if(map->inval_cache) map->inval_cache(map, from, size); } while(0) static inline int map_word_equal(struct map_info *map, map_word val1, map_word val2) { int i; for (i=0; i<map_words(map); i++) { if (val1.x[i] != val2.x[i]) return 0; } return 1; } static inline map_word map_word_and(struct map_info *map, map_word val1, map_word val2) { map_word r; int i; for (i=0; i<map_words(map); i++) { r.x[i] = val1.x[i] & val2.x[i]; } return r; } static inline map_word map_word_clr(struct map_info *map, map_word val1, map_word val2) { map_word r; int i; for (i=0; i<map_words(map); i++) { r.x[i] = val1.x[i] & ~val2.x[i]; } return r; } static inline map_word map_word_or(struct map_info *map, map_word val1, map_word val2) { map_word r; int i; for (i=0; i<map_words(map); i++) { r.x[i] = val1.x[i] | val2.x[i]; } return r; } #define map_word_andequal(m, a, b, z) map_word_equal(m, z, map_word_and(m, a, b)) static inline int map_word_bitsset(struct map_info *map, map_word val1, map_word val2) { int i; for (i=0; i<map_words(map); i++) { if (val1.x[i] & val2.x[i]) return 1; } return 0; } static inline map_word map_word_load(struct map_info *map, const void *ptr) { map_word r; if (map_bankwidth_is_1(map)) r.x[0] = *(unsigned char *)ptr; else if (map_bankwidth_is_2(map)) r.x[0] = get_unaligned((uint16_t *)ptr); else if (map_bankwidth_is_4(map)) r.x[0] = get_unaligned((uint32_t *)ptr); #if BITS_PER_LONG >= 64 else if (map_bankwidth_is_8(map)) r.x[0] = get_unaligned((uint64_t *)ptr); #endif else if (map_bankwidth_is_large(map)) memcpy(r.x, ptr, map->bankwidth); return r; } static inline map_word map_word_load_partial(struct map_info *map, map_word orig, const unsigned char *buf, int start, int len) { int i; if (map_bankwidth_is_large(map)) { char *dest = (char *)&orig; memcpy(dest+start, buf, len); } else { for (i=start; i < start+len; i++) { int bitpos; #ifdef __LITTLE_ENDIAN bitpos = i*8; #else /* __BIG_ENDIAN */ bitpos = (map_bankwidth(map)-1-i)*8; #endif orig.x[0] &= ~(0xff << bitpos); orig.x[0] |= buf[i-start] << bitpos; } } return orig; } #if BITS_PER_LONG < 64 #define MAP_FF_LIMIT 4 #else #define MAP_FF_LIMIT 8 #endif static inline map_word map_word_ff(struct map_info *map) { map_word r; int i; if (map_bankwidth(map) < MAP_FF_LIMIT) { int bw = 8 * map_bankwidth(map); r.x[0] = (1 << bw) - 1; } else { for (i=0; i<map_words(map); i++) r.x[i] = ~0UL; } return r; } static inline map_word inline_map_read(struct map_info *map, unsigned long ofs) { map_word r; if (map_bankwidth_is_1(map)) r.x[0] = __raw_readb(map->virt + ofs); else if (map_bankwidth_is_2(map)) r.x[0] = __raw_readw(map->virt + ofs); else if (map_bankwidth_is_4(map)) r.x[0] = __raw_readl(map->virt + ofs); #if BITS_PER_LONG >= 64 else if (map_bankwidth_is_8(map)) r.x[0] = __raw_readq(map->virt + ofs); #endif else if (map_bankwidth_is_large(map)) memcpy_fromio(r.x, map->virt+ofs, map->bankwidth); return r; } static inline void inline_map_write(struct map_info *map, const map_word datum, unsigned long ofs) { if (map_bankwidth_is_1(map)) __raw_writeb(datum.x[0], map->virt + ofs); else if (map_bankwidth_is_2(map)) __raw_writew(datum.x[0], map->virt + ofs); else if (map_bankwidth_is_4(map)) __raw_writel(datum.x[0], map->virt + ofs); #if BITS_PER_LONG >= 64 else if (map_bankwidth_is_8(map)) __raw_writeq(datum.x[0], map->virt + ofs); #endif else if (map_bankwidth_is_large(map)) memcpy_toio(map->virt+ofs, datum.x, map->bankwidth); mb(); } static inline void inline_map_copy_from(struct map_info *map, void *to, unsigned long from, ssize_t len) { if (map->cached) memcpy(to, (char *)map->cached + from, len); else #if defined(memcpy_fromiow) || defined(memcpy_fromiol) if (len & 1 || map_bankwidth_is_1(map)) #endif memcpy_fromio(to, map->virt + from, len); #ifdef memcpy_fromiow else if (map_bankwidth_is_2(map)) memcpy_fromiow(to, map->virt + from, len); #endif #ifdef memcpy_fromiol else if (map_bankwidth_is_4(map)) memcpy_fromiol(to, map->virt + from, len); #endif #if defined(memcpy_fromiow) || defined(memcpy_fromiol) else BUG(); #endif } static inline void inline_map_copy_to(struct map_info *map, unsigned long to, const void *from, ssize_t len) { #if defined(memcpy_toiow) || defined(memcpy_toiol) if (len & 1 || map_bankwidth_is_1(map)) #endif memcpy_toio(map->virt + to, from, len); #ifdef memcpy_toiow else if (map_bankwidth_is_2(map)) memcpy_toiow(map->virt + to, from, len); #endif #ifdef memcpy_toiol else if (map_bankwidth_is_4(map)) memcpy_toiol(map->virt + to, from, len); #endif #if defined(memcpy_toiow) || defined(memcpy_toiol) else BUG(); #endif } #ifdef CONFIG_MTD_COMPLEX_MAPPINGS #define map_read(map, ofs) (map)->read(map, ofs) #define map_copy_from(map, to, from, len) (map)->copy_from(map, to, from, len) #define map_write(map, datum, ofs) (map)->write(map, datum, ofs) #define map_copy_to(map, to, from, len) (map)->copy_to(map, to, from, len) extern void simple_map_init(struct map_info *); #define map_is_linear(map) (map->phys != NO_XIP) #else #define map_read(map, ofs) inline_map_read(map, ofs) #define map_copy_from(map, to, from, len) inline_map_copy_from(map, to, from, len) #define map_write(map, datum, ofs) inline_map_write(map, datum, ofs) #define map_copy_to(map, to, from, len) inline_map_copy_to(map, to, from, len) #define simple_map_init(map) BUG_ON(!map_bankwidth_supported((map)->bankwidth)) #define map_is_linear(map) ({ (void)(map); 1; }) #endif /* !CONFIG_MTD_COMPLEX_MAPPINGS */ #endif /* __LINUX_MTD_MAP_H__ */
thanhnhiel/linux-emcraft
include/linux/mtd/map.h
C
gpl-2.0
13,086
/* * Copyright (C) 2004-2006, Eric Lund * http://www.mvpmc.org/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * proglist.c - functions to manage MythTV timestamps. Primarily, * these allocate timestamps and convert between string * and cmyth_proglist_t and between long long and * cmyth_proglist_t. */ #include <sys/types.h> #include <stdlib.h> #ifndef _MSC_VER #include <unistd.h> #endif #include <stdio.h> #include <errno.h> #include <string.h> #include <cmyth_local.h> /* * cmyth_proglist_destroy(void) * * Scope: PRIVATE (static) * * Description * * Destroy and free a timestamp structure. This should only be called * by ref_release(). All others should use * ref_release() to release references to time stamps. * * Return Value: * * None. */ static void cmyth_proglist_destroy(cmyth_proglist_t pl) { int i; cmyth_dbg(CMYTH_DBG_DEBUG, "%s\n", __FUNCTION__); if (!pl) { return; } for (i = 0; i < pl->proglist_count; ++i) { if (pl->proglist_list[i]) { ref_release(pl->proglist_list[i]); } pl->proglist_list[i] = NULL; } if (pl->proglist_list) { free(pl->proglist_list); } } /* * cmyth_proglist_create(void) * * Scope: PUBLIC * * Description * * Create a timestamp structure and return a pointer to the structure. * * Return Value: * * Success: A non-NULL cmyth_proglist_t (this type is a pointer) * * Failure: A NULL cmyth_proglist_t */ cmyth_proglist_t cmyth_proglist_create(void) { cmyth_proglist_t ret; cmyth_dbg(CMYTH_DBG_DEBUG, "%s\n", __FUNCTION__); ret = ref_alloc(sizeof(*ret)); if (!ret) { return(NULL); } ref_set_destroy(ret, (ref_destroy_t)cmyth_proglist_destroy); ret->proglist_list = NULL; ret->proglist_count = 0; return ret; } /* * cmyth_proglist_get_item(cmyth_proglist_t pl, int index) * * Scope: PUBLIC * * Description: * * Retrieve the program information structure found at index 'index' * in the list in 'pl'. Return the program information structure * held. Before forgetting the reference to this program info structure * the caller must call ref_release(). * * Return Value: * * Success: A non-null cmyth_proginfo_t (this is a pointer type) * * Failure: A NULL cmyth_proginfo_t */ cmyth_proginfo_t cmyth_proglist_get_item(cmyth_proglist_t pl, int index) { if (!pl) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: NULL program list\n", __FUNCTION__); return NULL; } if (!pl->proglist_list) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: NULL list\n", __FUNCTION__); return NULL; } if ((index < 0) || (index >= pl->proglist_count)) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: index %d out of range\n", __FUNCTION__, index); return NULL; } ref_hold(pl->proglist_list[index]); return pl->proglist_list[index]; } int cmyth_proglist_delete_item(cmyth_proglist_t pl, cmyth_proginfo_t prog) { int i; cmyth_proginfo_t old; int ret = -EINVAL; if (!pl) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: NULL program list\n", __FUNCTION__); return -EINVAL; } if (!prog) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: NULL program item\n", __FUNCTION__); return -EINVAL; } pthread_mutex_lock(&mutex); for (i=0; i<pl->proglist_count; i++) { if (cmyth_proginfo_compare(prog, pl->proglist_list[i]) == 0) { old = pl->proglist_list[i]; memmove(pl->proglist_list+i, pl->proglist_list+i+1, (pl->proglist_count-i-1)*sizeof(cmyth_proginfo_t)); pl->proglist_count--; ref_release(old); ret = 0; goto out; } } out: pthread_mutex_unlock(&mutex); return ret; } /* * cmyth_proglist_get_count(cmyth_proglist_t pl) * * Scope: PUBLIC * * Description: * * Retrieve the number of elements in the program information * structure in 'pl'. * * Return Value: * * Success: A number >= 0 indicating the number of items in 'pl' * * Failure: -errno */ int cmyth_proglist_get_count(cmyth_proglist_t pl) { if (!pl) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: NULL program list\n", __FUNCTION__); return -EINVAL; } return pl->proglist_count; } /* * cmyth_proglist_get_list(cmyth_conn_t conn, * cmyth_proglist_t proglist, * char *msg, char *func) * * Scope: PRIVATE (static) * * Description * * Obtain a program list from the query specified in 'msg' from the * function 'func'. Make the query on 'conn' and put the results in * 'proglist'. * * Return Value: * * Success: 0 * * Failure: -(ERRNO) */ static int cmyth_proglist_get_list(cmyth_conn_t conn, cmyth_proglist_t proglist, char *msg, const char *func) { int err = 0; int count; int ret; if (!conn) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: no connection\n", func); return -EINVAL; } if (!proglist) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: no program list\n", func); return -EINVAL; } pthread_mutex_lock(&mutex); if ((err = cmyth_send_message(conn, msg)) < 0) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_send_message() failed (%d)\n", func, err); ret = err; goto out; } count = cmyth_rcv_length(conn); if (count < 0) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_rcv_length() failed (%d)\n", func, count); ret = count; goto out; } if (strcmp(msg, "QUERY_GETALLPENDING") == 0) { long c; int r; if ((r=cmyth_rcv_long(conn, &err, &c, count)) < 0) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_rcv_length() failed (%d)\n", __FUNCTION__, r); ret = err; goto out; } count -= r; } if (cmyth_rcv_proglist(conn, &err, proglist, count) != count) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_rcv_proglist() < count\n", func); } if (err) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_rcv_proglist() failed (%d)\n", func, err); ret = -1 * err; goto out; } ret = 0; out: pthread_mutex_unlock(&mutex); return ret; } /* * cmyth_proglist_get_all_recorded(cmyth_conn_t control, * cmyth_proglist_t *proglist) * * Scope: PUBLIC * * Description * * Make a request on the control connection 'control' to obtain a list * of completed or in-progress recordings. Build a list of program * information structures and put a malloc'ed pointer to the list (an * array of pointers) in proglist. * * Return Value: * * Success: A held, noon-NULL cmyth_proglist_t * * Failure: NULL */ cmyth_proglist_t cmyth_proglist_get_all_recorded(cmyth_conn_t control) { cmyth_proglist_t proglist = cmyth_proglist_create(); if (proglist == NULL) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_proglist_create() failed\n", __FUNCTION__); return NULL; } if (cmyth_proglist_get_list(control, proglist, "QUERY_RECORDINGS Play", __FUNCTION__) < 0) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_proglist_get_list() failed\n", __FUNCTION__); ref_release(proglist); return NULL; } return proglist; } /* * cmyth_proglist_get_all_pending(cmyth_conn_t control, * cmyth_proglist_t *proglist) * * Scope: PUBLIC * * Description * * Make a request on the control connection 'control' to obtain a list * of pending recordings. Build a list of program information * structures and put a malloc'ed pointer to the list (an array of * pointers) in proglist. * * Return Value: * * Success: A held, noon-NULL cmyth_proglist_t * * Failure: NULL */ cmyth_proglist_t cmyth_proglist_get_all_pending(cmyth_conn_t control) { cmyth_proglist_t proglist = cmyth_proglist_create(); if (proglist == NULL) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_proglist_create() failed\n", __FUNCTION__); return NULL; } if (cmyth_proglist_get_list(control, proglist, "QUERY_GETALLPENDING", __FUNCTION__) < 0) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_proglist_get_list() failed\n", __FUNCTION__); ref_release(proglist); return NULL; } return proglist; } /* * cmyth_proglist_get_all_scheduled(cmyth_conn_t control, * cmyth_proglist_t *proglist) * * Scope: PUBLIC * * Description * * Make a request on the control connection 'control' to obtain a list * of scheduled recordings. Build a list of program information * structures and put a malloc'ed pointer to the list (an array of * pointers) in proglist. * * Return Value: * * Success: A held, noon-NULL cmyth_proglist_t * * Failure: NULL */ cmyth_proglist_t cmyth_proglist_get_all_scheduled(cmyth_conn_t control) { cmyth_proglist_t proglist = cmyth_proglist_create(); if (proglist == NULL) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_proglist_create() failed\n", __FUNCTION__); return NULL; } if (cmyth_proglist_get_list(control, proglist, "QUERY_GETALLSCHEDULED", __FUNCTION__) < 0) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_proglist_get_list() failed\n", __FUNCTION__); ref_release(proglist); return NULL; } return proglist; } /* * cmyth_proglist_get_conflicting(cmyth_conn_t control, * cmyth_proglist_t *proglist) * * Scope: PUBLIC * * Description * * Make a request on the control connection 'control' to obtain a list * of conflicting recordings. Build a list of program information * structures and put a malloc'ed pointer to the list (an array of * pointers) in proglist. * * Return Value: * * Success: A held, noon-NULL cmyth_proglist_t * * Failure: NULL */ cmyth_proglist_t cmyth_proglist_get_conflicting(cmyth_conn_t control) { cmyth_proglist_t proglist = cmyth_proglist_create(); if (proglist == NULL) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_proglist_create() failed\n", __FUNCTION__); return NULL; } if (cmyth_proglist_get_list(control, proglist, "QUERY_GETCONFLICTING", __FUNCTION__) < 0) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_proglist_get_list() failed\n", __FUNCTION__); ref_release(proglist); return NULL; } return proglist; } /* * sort_timestamp(const void *a, const void *b) * * Scope: PRIVATE * * Description * * Return an integer value to specify the relative position of the timestamp * This is a helper function for the sort function called by qsort. It will * sort any of the timetstamps for the qsort functions * * Return Value: * * Same Date/Time: 0 * Date a > b: 1 * Date a < b: -1 * */ static int sort_timestamp(cmyth_timestamp_t X, cmyth_timestamp_t Y) { if (X->timestamp_year > Y->timestamp_year) return 1; else if (X->timestamp_year < Y->timestamp_year) return -1; else /* X->timestamp_year == Y->timestamp_year */ { if (X->timestamp_month > Y->timestamp_month) return 1; else if (X->timestamp_month < Y->timestamp_month) return -1; else /* X->timestamp_month == Y->timestamp_month */ { if (X->timestamp_day > Y->timestamp_day) return 1; else if (X->timestamp_day < Y->timestamp_day) return -1; else /* X->timestamp_day == Y->timestamp_day */ { if (X->timestamp_hour > Y->timestamp_hour) return 1; else if (X->timestamp_hour < Y->timestamp_hour) return -1; else /* X->timestamp_hour == Y->timestamp_hour */ { if (X->timestamp_minute > Y->timestamp_minute) return 1; else if (X->timestamp_minute < Y->timestamp_minute) return -1; else /* X->timestamp_minute == Y->timestamp_minute */ { if (X->timestamp_second > Y->timestamp_second) return 1; else if (X->timestamp_second < Y->timestamp_second) return -1; else /* X->timestamp_second == Y->timestamp_second */ return 0; } } } } } } /* * recorded_compare(const void *a, const void *b) * * Scope: PRIVATE * * Description * * Return an integer value to a qsort function to specify the relative * position of the recorded date * * Return Value: * * Same Day: 0 * Date a > b: 1 * Date a < b: -1 * */ static int recorded_compare(const void *a, const void *b) { const cmyth_proginfo_t x = *(cmyth_proginfo_t *)a; const cmyth_proginfo_t y = *(cmyth_proginfo_t *)b; cmyth_timestamp_t X = x->proginfo_rec_start_ts; cmyth_timestamp_t Y = y->proginfo_rec_start_ts; return sort_timestamp(X, Y); } /* * airdate_compare(const void *a, const void *b) * * Scope: PRIVATE * * Description * * Return an integer value to a qsort function to specify the relative * position of the original airdate * * Return Value: * * Same Day: 0 * Date a > b: 1 * Date a < b: -1 * */ static int airdate_compare(const void *a, const void *b) { const cmyth_proginfo_t x = *(cmyth_proginfo_t *)a; const cmyth_proginfo_t y = *(cmyth_proginfo_t *)b; const cmyth_timestamp_t X = x->proginfo_originalairdate; const cmyth_timestamp_t Y = y->proginfo_originalairdate; return sort_timestamp(X, Y); } /* * cmyth_proglist_sort(cmyth_proglist_t pl, int count, int sort) * * Scope: PUBLIC * * Description * * Sort the epispde list by mythtv_sort setting. Check to ensure that the * program list is not null and pass the proglist_list to the qsort function * * Return Value: * * Success = 0 * Failure = -1 */ int cmyth_proglist_sort(cmyth_proglist_t pl, int count, cmyth_proglist_sort_t sort) { if (!pl) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: NULL program list\n", __FUNCTION__); return -1; } if (!pl->proglist_list) { cmyth_dbg(CMYTH_DBG_ERROR, "%s: NULL list\n", __FUNCTION__); return -1; } cmyth_dbg(CMYTH_DBG_ERROR, "cmyth_proglist_sort\n"); switch (sort) { case MYTHTV_SORT_DATE_RECORDED: /* Default Date Recorded */ qsort((cmyth_proginfo_t)pl->proglist_list, count, sizeof(pl->proglist_list) , recorded_compare); break; case MYTHTV_SORT_ORIGINAL_AIRDATE: /*Default Date Recorded */ qsort((cmyth_proginfo_t)pl->proglist_list, count, sizeof(pl->proglist_list) , airdate_compare); break; default: printf("Unsupported MythTV sort type\n"); } cmyth_dbg(CMYTH_DBG_ERROR, "end cmyth_proglist_sort\n"); return 0; }
xbmc/atv2
xbmc/lib/cmyth/libcmyth/proglist.c
C
gpl-2.0
14,784
/* Conversion from and to ISO_2033-1983. Copyright (C) 1998-2013 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 1998. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <stdint.h> /* Get the conversion table. */ #define TABLES <iso_2033.h> #define CHARSET_NAME "ISO_2033//" #define HAS_HOLES 1 /* Not all 256 character are defined. */ #include <8bit-gap.c>
SanDisk-Open-Source/SSD_Dashboard
uefi/userspace/glibc/iconvdata/iso_2033.c
C
gpl-2.0
1,093
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Thu Aug 12 23:36:37 CEST 2010 --> <TITLE> Uses of Package org.mt4j.test.sceneManagement </TITLE> <META NAME="date" CONTENT="2010-08-12"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.mt4j.test.sceneManagement"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/mt4j/test/sceneManagement/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Package<br>org.mt4j.test.sceneManagement</B></H2> </CENTER> No usage of org.mt4j.test.sceneManagement <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/mt4j/test/sceneManagement/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
AdalbertoJoseToledoEscalona/catalogo_productos_old_version
pantallaMT v0.95/MT4j/doc/org/mt4j/test/sceneManagement/package-use.html
HTML
gpl-2.0
5,720
#ifndef CPUSWITCH_HH #define CPUSWITCH_HH #include <click/element.hh> /* * =c * CPUSwitch() * =s threads * classifies packets by cpu * =d * Can have any number of outputs. * Chooses the output on which to emit each packet based on the thread's cpu. * =a * RoundRobinSwitch, StrideSwitch, HashSwitch */ class CPUSwitch : public Element { public: CPUSwitch() CLICK_COLD; ~CPUSwitch() CLICK_COLD; const char *class_name() const { return "CPUSwitch"; } const char *port_count() const { return "1/1-"; } const char *processing() const { return PUSH; } void push(int port, Packet *); }; #endif
neunenak/click
elements/standard/cpuswitch.hh
C++
gpl-2.0
622
/** * Simple header class which is used for on {@link Ext.panel.Panel} and {@link Ext.window.Window}. */ Ext.define('Ext.panel.Header', { extend: 'Ext.panel.Bar', xtype: 'header', requires: [ 'Ext.panel.Title', 'Ext.panel.Tool' ], mixins: [ 'Ext.util.FocusableContainer' ], /** * @property {Boolean} isHeader * `true` in this class to identify an object as an instantiated Header, or subclass thereof. */ isHeader: true, defaultType: 'tool', indicateDrag: false, weight: -1, shrinkWrap: 3, // For performance reasons we give the following configs their default values on // the class body. This prevents the updaters from running on initialization in the // default configuration scenario iconAlign: 'left', titleAlign: 'left', titlePosition: 0, titleRotation: 'default', autoEl: { role: 'presentation' }, beforeRenderConfig: { /** * @cfg {Number/String} glyph * @accessor * A numeric unicode character code to use as the icon. The default font-family * for glyphs can be set globally using * {@link Ext.app.Application#glyphFontFamily glyphFontFamily} application * config or the {@link Ext#setGlyphFontFamily Ext.setGlyphFontFamily()} method. * * The following shows how to set the glyph using the font icons provided in the * SDK (assuming the font-family has been configured globally): * * // assumes the glyphFontFamily is "FontAwesome" * glyph: 'xf005' // the "home" icon * * // assumes the glyphFontFamily is "Pictos" * glyph: 'H' // the "home" icon * * Alternatively, this config option accepts a string with the charCode and * font-family separated by the `@` symbol. * * // using Font Awesome * glyph: 'xf005@FontAwesome' // the "home" icon * * // using Pictos * glyph: 'H@Pictos' // the "home" icon * * Depending on the theme you're using, you may need include the font icon * packages in your application in order to use the icons included in the * SDK. For more information see: * * - [Font Awesome icons](http://fortawesome.github.io/Font-Awesome/cheatsheet/) * - [Pictos icons](http://docs.sencha.com/extjs/6.0/core_concepts/font_ext.html) * - [Theming Guide](http://docs.sencha.com/extjs/6.0/core_concepts/theming.html) */ glyph: null, /** * @cfg {String} icon * Path to an image to use as an icon. * * For instructions on how you can use icon fonts including those distributed in * the SDK see {@link #iconCls}. * @accessor */ icon: null, /** * @cfg {String} iconCls * @accessor * One or more space separated CSS classes to be applied to the icon element. * The CSS rule(s) applied should specify a background image to be used as the * icon. * * An example of specifying a custom icon class would be something like: * * // specify the property in the config for the class: * iconCls: 'my-home-icon' * * // css rule specifying the background image to be used as the icon image: * .my-home-icon { * background-image: url(../images/my-home-icon.gif) !important; * } * * In addition to specifying your own classes, you can use the font icons * provided in the SDK using the following syntax: * * // using Font Awesome * iconCls: 'x-fa fa-home' * * // using Pictos * iconCls: 'pictos pictos-home' * * Depending on the theme you're using, you may need include the font icon * packages in your application in order to use the icons included in the * SDK. For more information see: * * - [Font Awesome icons](http://fortawesome.github.io/Font-Awesome/cheatsheet/) * - [Pictos icons](http://docs.sencha.com/extjs/6.0/core_concepts/font_ext.html) * - [Theming Guide](http://docs.sencha.com/extjs/6.0/core_concepts/theming.html) */ iconCls: null, /** * @cfg {'top'/'right'/'bottom'/'left'} [iconAlign='left'] * The side of the title to render the icon. * @accessor */ iconAlign: null, /** * @cfg {String/Ext.panel.Title} * The title text or config object for the {@link Ext.panel.Title Title} component. * @accessor */ title: { $value: { xtype: 'title', flex: 1 }, merge: function(newValue, oldValue) { if (typeof newValue !== 'object') { newValue = { text: newValue }; } return Ext.merge(oldValue ? Ext.Object.chain(oldValue) : {}, newValue); } }, /** * @cfg {'left'/'center'/'right'} [titleAlign='left'] * The alignment of the title text within the available space between the * icon and the tools. * @accessor */ titleAlign: null, /** * @cfg {Number} [titlePosition=0] * The ordinal position among the header items (tools and other components specified using the {@link #cfg-items} config) * at which the title component is inserted. See {@link Ext.panel.Panel#cfg-header Panel's header config}. * * If not specified, the title is inserted after any {@link #cfg-items}, but *before* any {@link Ext.panel.Panel#tools}. * * Note that if an {@link #icon} or {@link #iconCls} has been configured, then the icon component will be the * first item before all specified tools or {@link #cfg-items}. This configuration does not include the icon. * @accessor */ titlePosition: null, /** * @cfg {'default'/0/1/2} [titleRotation='default'] * @accessor * The rotation of the header's title text. Can be one of the following values: * * - `'default'` - use the default rotation, depending on the dock position of the header * - `0` - no rotation * - `1` - rotate 90deg clockwise * - `2` - rotate 90deg counter-clockwise * * The default behavior of this config depends on the dock position of the header: * * - `'top'` or `'bottom'` - `0` * - `'right'` - `1` * - `'left'` - `1` */ titleRotation: null }, // a class for styling that is shared between panel and window headers headerCls: Ext.baseCSSPrefix + 'header', /** * @event click * Fires when the header is clicked. This event will not be fired * if the click was on a {@link Ext.panel.Tool} * @param {Ext.panel.Header} this * @param {Ext.event.Event} e */ /** * @event dblclick * Fires when the header is double clicked. This event will not * be fired if the click was on a {@link Ext.panel.Tool} * @param {Ext.panel.Header} this * @param {Ext.event.Event} e */ /** * @cfg {Number} [itemPosition] * The index at which the any {@link #cfg-items} will be inserted into the Header's * items collection. By default this will effectively be the `1` position * placing the items following the panel {@link Ext.panel.Panel#title title}. * * Set to `0` to have the items {@link #insert inserted} before the panel title. * * Ext.create('Ext.panel.Panel', { * title: 'Hello', * width: 200, * html: '<p>World!</p>', * renderTo: Ext.getBody(), * tools: [{ * type: 'pin' * }], * header: { * //itemPosition: 0, // before panel title * //itemPosition: 1, // after panel title * //itemPosition: 2, // after pin tool * items: [{ * xtype: 'button', * text: 'Header Button' * }] * } * }); */ initComponent: function() { var me = this, items = me.items, itemPosition = me.itemPosition, cls = [me.headerCls]; me.tools = me.tools || []; me.items = items = (items ? items.slice() : []); if (itemPosition !== undefined) { me._userItems = items.slice(); me.items = items = []; } me.indicateDragCls = me.headerCls + '-draggable'; if (me.indicateDrag) { cls.push(me.indicateDragCls); } me.addCls(cls); me.syncNoBorderCls(); me.enableFocusableContainer = !me.isAccordionHeader && me.tools.length > 0; if (me.enableFocusableContainer) { me.ariaRole = 'toolbar'; } // Add Tools Ext.Array.push(items, me.tools); // Clear the tools so we can have only the instances. Intentional mutation of passed in array // Owning code in Panel uses this array as its public tools property. me.tools.length = 0; me.callParent(); me.on({ dblclick: me.onDblClick, click: me.onClick, element: 'el', scope: me }); }, /** * Add a tool to the header * @param {Object} tool */ addTool: function(tool) { var me = this; // Even though the defaultType is tool, it may be changed, // so let's be safe and forcibly specify tool me.add(Ext.ComponentManager.create(tool, 'tool')); if (!me.isAccordionHeader && me.tools.length > 0 && !me.enableFocusableContainer) { me.enableFocusableContainer = true; me.ariaRole = 'toolbar'; if (me.rendered) { me.ariaEl.dom.setAttribute('role', 'toolbar'); me.initFocusableContainer(true); } } }, afterLayout: function() { var me = this, frameBR, frameTR, frameTL, xPos; if (me.vertical) { frameTR = me.frameTR; if (frameTR) { // The corners sprite currently requires knowledge of the vertical header's // width to correctly set the background position of the bottom right corner. // TODO: rearrange the sprite so that this can be done with pure css. frameBR = me.frameBR; frameTL = me.frameTL; xPos = (me.getWidth() - frameTR.getPadding('r') - ((frameTL) ? frameTL.getPadding('l') : me.el.getBorderWidth('l'))) + 'px'; frameBR.setStyle('background-position-x', xPos); frameTR.setStyle('background-position-x', xPos); } } this.callParent(); }, applyTitle: function(title, oldTitle) { var me = this, isString, configHasRotation; title = title || ''; isString = typeof title === 'string'; if (isString) { title = { text: title }; } if (oldTitle) { // several title configs can trigger layouts, so suspend before setting // configs in bulk Ext.suspendLayouts(); oldTitle.setConfig(title); Ext.resumeLayouts(true); title = oldTitle; } else { if (isString) { title.xtype = 'title'; } title.ui = me.ui; configHasRotation = ('rotation' in title); // Important Panel attribute aria-labelledby depends on title textEl id title.id = me.id + '-title'; if (me.isAccordionHeader) { title.ariaRole = 'tab'; title.textElRole = null; title.focusable = true; } title = Ext.create(title); // avoid calling the title's rotation updater on initial startup in the default scenario if (!configHasRotation && me.vertical && me.titleRotation === 'default') { title.rotation = 1; } } return title; }, applyTitlePosition: function(position) { var max = this.items.getCount(); if (this._titleInItems) { --max; } return Math.max(Math.min(position, max), 0); }, beforeLayout: function () { this.callParent(); this.syncBeforeAfterTitleClasses(); }, beforeRender: function() { var me = this, itemPosition = me.itemPosition; me.protoEl.unselectable(); me.callParent(); if (itemPosition !== undefined) { me.insert(itemPosition, me._userItems); } }, /** * Gets the tools for this header. * @return {Ext.panel.Tool[]} The tools */ getTools: function(){ return this.tools.slice(); }, onAdd: function(component, index) { var tools = this.tools; this.callParent([component, index]); if (component.isTool) { tools.push(component); tools[component.type] = component; } }, onAdded: function(container, pos, instanced) { this.syncNoBorderCls(); this.callParent([container, pos, instanced]); }, onRemoved: function(container, pos, instanced) { this.syncNoBorderCls(); this.callParent([container, pos, instanced]); }, setDock: function(dock) { var me = this, title = me.getTitle(), rotation = me.getTitleRotation(), titleRotation = title.getRotation(); Ext.suspendLayouts(); me.callParent([dock]); if (rotation === 'default') { rotation = (me.vertical ? 1 : 0); if (rotation !== titleRotation) { title.setRotation(rotation); } if (me.rendered) { // remove margins set on items by box layout last time around. // TODO: this will no longer be needed when EXTJS-13359 is fixed me.resetItemMargins(); } } Ext.resumeLayouts(true); }, updateGlyph: function(glyph) { this.getTitle().setGlyph(glyph); }, updateIcon: function(icon) { this.getTitle().setIcon(icon); }, updateIconAlign: function(align, oldAlign) { this.getTitle().setIconAlign(align); }, updateIconCls: function(cls) { this.getTitle().setIconCls(cls); }, updateTitle: function(title, oldTitle) { if (!oldTitle) { this.insert(this.getTitlePosition(), title); this._titleInItems = true; } // for backward compat with 4.x, set titleCmp property this.titleCmp = title; }, updateTitleAlign: function(align, oldAlign) { this.getTitle().setTextAlign(align); }, updateTitlePosition: function(position) { this.insert(position, this.getTitle()); }, updateTitleRotation: function(rotation) { if (rotation === 'default') { rotation = (this.vertical ? 1 : 0); } this.getTitle().setRotation(rotation); }, privates: { fireClickEvent: function(type, e){ var toolCls = '.' + Ext.panel.Tool.prototype.baseCls; if (!e.getTarget(toolCls)) { this.fireEvent(type, this, e); } }, getFramingInfoCls: function(){ var me = this, cls = me.callParent(), owner = me.ownerCt; if (!me.expanding && owner && (owner.collapsed || me.isCollapsedExpander)) { cls += '-' + owner.collapsedCls; } return cls + '-' + me.dock; }, onClick: function(e) { this.fireClickEvent('click', e); }, onDblClick: function(e){ this.fireClickEvent('dblclick', e); }, onFocusableContainerMousedown: function(e, target) { var targetCmp = Ext.Component.fromElement(target); // We don't want to focus the header on mousedown if (targetCmp === this) { e.preventDefault(); } else { this.mixins.focusablecontainer.onFocusableContainerMousedown.apply(this, arguments); } }, syncBeforeAfterTitleClasses: function(force) { var me = this, items = me.items, childItems = items.items, titlePosition = me.getTitlePosition(), itemCount = childItems.length, itemGeneration = items.generation, syncGen = me.syncBeforeAfterGen, afterCls, beforeCls, i, item; if (!force && (syncGen === itemGeneration)) { return; } me.syncBeforeAfterGen = itemGeneration; for (i = 0; i < itemCount; ++i) { item = childItems[i]; afterCls = item.afterTitleCls || (item.afterTitleCls = item.baseCls + '-after-title'); beforeCls = item.beforeTitleCls || (item.beforeTitleCls = item.baseCls + '-before-title'); if (!me.title || i < titlePosition) { if (syncGen) { item.removeCls(afterCls); } // else first time we won't need to remove anything... item.addCls(beforeCls); } else if (i > titlePosition) { if (syncGen) { item.removeCls(beforeCls); } item.addCls(afterCls); } } }, syncNoBorderCls: function() { var me = this, ownerCt = this.ownerCt, noBorderCls = me.headerCls + '-noborder'; // test for border === false is needed because undefined is the same as true if (ownerCt ? (ownerCt.border === false && !ownerCt.frame) : me.border === false) { me.addCls(noBorderCls); } else { me.removeCls(noBorderCls); } } } // private });
turtlerrrrr/myapp
web/src/main/webapp/WEB-INF/app/ext/classic/classic/src/panel/Header.js
JavaScript
gpl-2.0
19,585
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _ASM_X86_PTRACE_H #define _ASM_X86_PTRACE_H #include <asm/segment.h> #include <asm/page_types.h> #include <uapi/asm/ptrace.h> #ifndef __ASSEMBLY__ #ifdef __i386__ struct pt_regs { /* * NB: 32-bit x86 CPUs are inconsistent as what happens in the * following cases (where %seg represents a segment register): * * - pushl %seg: some do a 16-bit write and leave the high * bits alone * - movl %seg, [mem]: some do a 16-bit write despite the movl * - IDT entry: some (e.g. 486) will leave the high bits of CS * and (if applicable) SS undefined. * * Fortunately, x86-32 doesn't read the high bits on POP or IRET, * so we can just treat all of the segment registers as 16-bit * values. */ unsigned long bx; unsigned long cx; unsigned long dx; unsigned long si; unsigned long di; unsigned long bp; unsigned long ax; unsigned short ds; unsigned short __dsh; unsigned short es; unsigned short __esh; unsigned short fs; unsigned short __fsh; /* On interrupt, gs and __gsh store the vector number. */ unsigned short gs; unsigned short __gsh; /* On interrupt, this is the error code. */ unsigned long orig_ax; unsigned long ip; unsigned short cs; unsigned short __csh; unsigned long flags; unsigned long sp; unsigned short ss; unsigned short __ssh; }; #else /* __i386__ */ struct pt_regs { /* * C ABI says these regs are callee-preserved. They aren't saved on kernel entry * unless syscall needs a complete, fully filled "struct pt_regs". */ unsigned long r15; unsigned long r14; unsigned long r13; unsigned long r12; unsigned long bp; unsigned long bx; /* These regs are callee-clobbered. Always saved on kernel entry. */ unsigned long r11; unsigned long r10; unsigned long r9; unsigned long r8; unsigned long ax; unsigned long cx; unsigned long dx; unsigned long si; unsigned long di; /* * On syscall entry, this is syscall#. On CPU exception, this is error code. * On hw interrupt, it's IRQ number: */ unsigned long orig_ax; /* Return frame for iretq */ unsigned long ip; unsigned long cs; unsigned long flags; unsigned long sp; unsigned long ss; /* top of stack page */ }; #endif /* !__i386__ */ #ifdef CONFIG_PARAVIRT #include <asm/paravirt_types.h> #endif struct cpuinfo_x86; struct task_struct; extern unsigned long profile_pc(struct pt_regs *regs); extern unsigned long convert_ip_to_linear(struct task_struct *child, struct pt_regs *regs); extern void send_sigtrap(struct pt_regs *regs, int error_code, int si_code); static inline unsigned long regs_return_value(struct pt_regs *regs) { return regs->ax; } static inline void regs_set_return_value(struct pt_regs *regs, unsigned long rc) { regs->ax = rc; } /* * user_mode(regs) determines whether a register set came from user * mode. On x86_32, this is true if V8086 mode was enabled OR if the * register set was from protected mode with RPL-3 CS value. This * tricky test checks that with one comparison. * * On x86_64, vm86 mode is mercifully nonexistent, and we don't need * the extra check. */ static inline int user_mode(struct pt_regs *regs) { #ifdef CONFIG_X86_32 return ((regs->cs & SEGMENT_RPL_MASK) | (regs->flags & X86_VM_MASK)) >= USER_RPL; #else return !!(regs->cs & 3); #endif } static inline int v8086_mode(struct pt_regs *regs) { #ifdef CONFIG_X86_32 return (regs->flags & X86_VM_MASK); #else return 0; /* No V86 mode support in long mode */ #endif } static inline bool user_64bit_mode(struct pt_regs *regs) { #ifdef CONFIG_X86_64 #ifndef CONFIG_PARAVIRT_XXL /* * On non-paravirt systems, this is the only long mode CPL 3 * selector. We do not allow long mode selectors in the LDT. */ return regs->cs == __USER_CS; #else /* Headers are too twisted for this to go in paravirt.h. */ return regs->cs == __USER_CS || regs->cs == pv_info.extra_user_64bit_cs; #endif #else /* !CONFIG_X86_64 */ return false; #endif } #ifdef CONFIG_X86_64 #define current_user_stack_pointer() current_pt_regs()->sp #define compat_user_stack_pointer() current_pt_regs()->sp #endif static inline unsigned long kernel_stack_pointer(struct pt_regs *regs) { return regs->sp; } static inline unsigned long instruction_pointer(struct pt_regs *regs) { return regs->ip; } static inline void instruction_pointer_set(struct pt_regs *regs, unsigned long val) { regs->ip = val; } static inline unsigned long frame_pointer(struct pt_regs *regs) { return regs->bp; } static inline unsigned long user_stack_pointer(struct pt_regs *regs) { return regs->sp; } static inline void user_stack_pointer_set(struct pt_regs *regs, unsigned long val) { regs->sp = val; } /* Query offset/name of register from its name/offset */ extern int regs_query_register_offset(const char *name); extern const char *regs_query_register_name(unsigned int offset); #define MAX_REG_OFFSET (offsetof(struct pt_regs, ss)) /** * regs_get_register() - get register value from its offset * @regs: pt_regs from which register value is gotten. * @offset: offset number of the register. * * regs_get_register returns the value of a register. The @offset is the * offset of the register in struct pt_regs address which specified by @regs. * If @offset is bigger than MAX_REG_OFFSET, this returns 0. */ static inline unsigned long regs_get_register(struct pt_regs *regs, unsigned int offset) { if (unlikely(offset > MAX_REG_OFFSET)) return 0; #ifdef CONFIG_X86_32 /* The selector fields are 16-bit. */ if (offset == offsetof(struct pt_regs, cs) || offset == offsetof(struct pt_regs, ss) || offset == offsetof(struct pt_regs, ds) || offset == offsetof(struct pt_regs, es) || offset == offsetof(struct pt_regs, fs) || offset == offsetof(struct pt_regs, gs)) { return *(u16 *)((unsigned long)regs + offset); } #endif return *(unsigned long *)((unsigned long)regs + offset); } /** * regs_within_kernel_stack() - check the address in the stack * @regs: pt_regs which contains kernel stack pointer. * @addr: address which is checked. * * regs_within_kernel_stack() checks @addr is within the kernel stack page(s). * If @addr is within the kernel stack, it returns true. If not, returns false. */ static inline int regs_within_kernel_stack(struct pt_regs *regs, unsigned long addr) { return ((addr & ~(THREAD_SIZE - 1)) == (regs->sp & ~(THREAD_SIZE - 1))); } /** * regs_get_kernel_stack_nth_addr() - get the address of the Nth entry on stack * @regs: pt_regs which contains kernel stack pointer. * @n: stack entry number. * * regs_get_kernel_stack_nth() returns the address of the @n th entry of the * kernel stack which is specified by @regs. If the @n th entry is NOT in * the kernel stack, this returns NULL. */ static inline unsigned long *regs_get_kernel_stack_nth_addr(struct pt_regs *regs, unsigned int n) { unsigned long *addr = (unsigned long *)regs->sp; addr += n; if (regs_within_kernel_stack(regs, (unsigned long)addr)) return addr; else return NULL; } /* To avoid include hell, we can't include uaccess.h */ extern long probe_kernel_read(void *dst, const void *src, size_t size); /** * regs_get_kernel_stack_nth() - get Nth entry of the stack * @regs: pt_regs which contains kernel stack pointer. * @n: stack entry number. * * regs_get_kernel_stack_nth() returns @n th entry of the kernel stack which * is specified by @regs. If the @n th entry is NOT in the kernel stack * this returns 0. */ static inline unsigned long regs_get_kernel_stack_nth(struct pt_regs *regs, unsigned int n) { unsigned long *addr; unsigned long val; long ret; addr = regs_get_kernel_stack_nth_addr(regs, n); if (addr) { ret = probe_kernel_read(&val, addr, sizeof(val)); if (!ret) return val; } return 0; } /** * regs_get_kernel_argument() - get Nth function argument in kernel * @regs: pt_regs of that context * @n: function argument number (start from 0) * * regs_get_argument() returns @n th argument of the function call. * Note that this chooses most probably assignment, in some case * it can be incorrect. * This is expected to be called from kprobes or ftrace with regs * where the top of stack is the return address. */ static inline unsigned long regs_get_kernel_argument(struct pt_regs *regs, unsigned int n) { static const unsigned int argument_offs[] = { #ifdef __i386__ offsetof(struct pt_regs, ax), offsetof(struct pt_regs, cx), offsetof(struct pt_regs, dx), #define NR_REG_ARGUMENTS 3 #else offsetof(struct pt_regs, di), offsetof(struct pt_regs, si), offsetof(struct pt_regs, dx), offsetof(struct pt_regs, cx), offsetof(struct pt_regs, r8), offsetof(struct pt_regs, r9), #define NR_REG_ARGUMENTS 6 #endif }; if (n >= NR_REG_ARGUMENTS) { n -= NR_REG_ARGUMENTS - 1; return regs_get_kernel_stack_nth(regs, n); } else return regs_get_register(regs, argument_offs[n]); } #define arch_has_single_step() (1) #ifdef CONFIG_X86_DEBUGCTLMSR #define arch_has_block_step() (1) #else #define arch_has_block_step() (boot_cpu_data.x86 >= 6) #endif #define ARCH_HAS_USER_SINGLE_STEP_REPORT /* * When hitting ptrace_stop(), we cannot return using SYSRET because * that does not restore the full CPU state, only a minimal set. The * ptracer can change arbitrary register values, which is usually okay * because the usual ptrace stops run off the signal delivery path which * forces IRET; however, ptrace_event() stops happen in arbitrary places * in the kernel and don't force IRET path. * * So force IRET path after a ptrace stop. */ #define arch_ptrace_stop_needed(code, info) \ ({ \ force_iret(); \ false; \ }) struct user_desc; extern int do_get_thread_area(struct task_struct *p, int idx, struct user_desc __user *info); extern int do_set_thread_area(struct task_struct *p, int idx, struct user_desc __user *info, int can_allocate); #ifdef CONFIG_X86_64 # define do_set_thread_area_64(p, s, t) do_arch_prctl_64(p, s, t) #else # define do_set_thread_area_64(p, s, t) (0) #endif #endif /* !__ASSEMBLY__ */ #endif /* _ASM_X86_PTRACE_H */
Pingmin/linux
arch/x86/include/asm/ptrace.h
C
gpl-2.0
10,140
/* * Copyright (C) 2011-2015 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2015 MaNGOS <http://getmangos.com/> * Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ObjectMgr.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "GridNotifiers.h" #include "Player.h" #include "halls_of_origination.h" enum Texts { SAY_AGGRO = 0, SAY_SHIELD = 1, EMOTE_SHIELD = 2, EMOTE_UNSHIELD = 3, SAY_KILL = 4, SAY_DEATH = 5 }; enum Events { EVENT_DIVINE_RECKONING = 1, EVENT_BURNING_LIGHT = 2, EVENT_SEAR = 3, }; enum Spells { SPELL_DIVINE_RECKONING = 75592, SPELL_BURNING_LIGHT = 75115, SPELL_REVERBERATING_HYMN = 75322, SPELL_SHIELD_OF_LIGHT = 74938, SPELL_ACTIVATE_BEACONS = 76599, SPELL_TELEPORT = 74969, SPELL_SHIELD_VISUAL_RIGHT = 83698, SPELL_BEAM_OF_LIGHT_RIGHT = 76573, SPELL_SHIELD_VISUAL_LEFT = 83697, SPELL_BEAM_OF_LIGHT_LEFT = 74930, SPELL_SEARING_LIGHT = 75194, }; enum Phases { PHASE_SHIELDED = 0, PHASE_FIRST_SHIELD = 1, // Ready to be shielded for the first time PHASE_SECOND_SHIELD = 2, // First shield already happened, ready to be shielded a second time PHASE_FINAL = 3 // Already shielded twice, ready to finish the encounter normally. }; enum Actions { ACTION_DISABLE_BEACON, }; class boss_temple_guardian_anhuur : public CreatureScript { public: boss_temple_guardian_anhuur() : CreatureScript("boss_temple_guardian_anhuur") { } struct boss_temple_guardian_anhuurAI : public BossAI { boss_temple_guardian_anhuurAI(Creature* creature) : BossAI(creature, DATA_TEMPLE_GUARDIAN_ANHUUR) { } void CleanStalkers() { std::list<Creature*> stalkers; GetCreatureListWithEntryInGrid(stalkers, me, NPC_CAVE_IN_STALKER, 100.0f); for (std::list<Creature*>::iterator itr = stalkers.begin(); itr != stalkers.end(); ++itr) { (*itr)->RemoveAurasDueToSpell(SPELL_BEAM_OF_LIGHT_RIGHT); (*itr)->RemoveAurasDueToSpell(SPELL_BEAM_OF_LIGHT_LEFT); } } void Reset() OVERRIDE { _phase = PHASE_FIRST_SHIELD; _oldPhase = PHASE_FIRST_SHIELD; _beacons = 0; _Reset(); CleanStalkers(); me->RemoveAurasDueToSpell(SPELL_SHIELD_OF_LIGHT); events.ScheduleEvent(EVENT_DIVINE_RECKONING, urand(10000, 12000)); events.ScheduleEvent(EVENT_BURNING_LIGHT, 12000); } void DamageTaken(Unit* /*attacker*/, uint32& damage) OVERRIDE { if ((me->HealthBelowPctDamaged(66, damage) && _phase == PHASE_FIRST_SHIELD) || (me->HealthBelowPctDamaged(33, damage) && _phase == PHASE_SECOND_SHIELD)) { _beacons = 2; _phase++; // Increase the phase _oldPhase = _phase; _phase = PHASE_SHIELDED; me->InterruptNonMeleeSpells(true); me->AttackStop(); DoCast(me, SPELL_TELEPORT); DoCast(me, SPELL_SHIELD_OF_LIGHT); me->SetFlag(UNIT_FIELD_FLAGS, uint32(UNIT_FLAG_UNK_31)); DoCastAOE(SPELL_ACTIVATE_BEACONS); std::list<Creature*> stalkers; GameObject* door = ObjectAccessor::GetGameObject(*me, instance->GetData64(DATA_ANHUUR_DOOR)); GetCreatureListWithEntryInGrid(stalkers, me, NPC_CAVE_IN_STALKER, 100.0f); stalkers.remove_if(Trinity::HeightDifferenceCheck(door, 0.0f, false)); // Target only the bottom ones for (std::list<Creature*>::iterator itr = stalkers.begin(); itr != stalkers.end(); ++itr) { if ((*itr)->GetPositionX() > door->GetPositionX()) { (*itr)->CastSpell((*itr), SPELL_SHIELD_VISUAL_LEFT, true); (*itr)->CastSpell((*itr), SPELL_BEAM_OF_LIGHT_LEFT, true); } else { (*itr)->CastSpell((*itr), SPELL_SHIELD_VISUAL_RIGHT, true); (*itr)->CastSpell((*itr), SPELL_BEAM_OF_LIGHT_RIGHT, true); } } DoCast(me, SPELL_REVERBERATING_HYMN); Talk(EMOTE_SHIELD); Talk(SAY_SHIELD); } } void DoAction(int32 action) OVERRIDE { if (action == ACTION_DISABLE_BEACON) { --_beacons; if (!_beacons) { me->RemoveAurasDueToSpell(SPELL_SHIELD_OF_LIGHT); Talk(EMOTE_UNSHIELD); _phase = _oldPhase; } } } void EnterCombat(Unit* /*who*/) OVERRIDE { instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me, 1); Talk(SAY_AGGRO); _EnterCombat(); } void JustDied(Unit* /*killer*/) OVERRIDE { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); Talk(SAY_DEATH); _JustDied(); } void KilledUnit(Unit* victim) OVERRIDE { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void JustReachedHome() OVERRIDE { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); _JustReachedHome(); instance->SetBossState(DATA_TEMPLE_GUARDIAN_ANHUUR, FAIL); } void UpdateAI(uint32 diff) OVERRIDE { if (!UpdateVictim() || !CheckInRoom() || me->GetCurrentSpell(CURRENT_CHANNELED_SPELL) || _phase == PHASE_SHIELDED) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_DIVINE_RECKONING: DoCastVictim(SPELL_DIVINE_RECKONING); events.ScheduleEvent(EVENT_DIVINE_RECKONING, urand(10000, 12000)); break; case EVENT_BURNING_LIGHT: { Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0, NonTankTargetSelector(me)); if (!unit) unit = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true); DoCast(unit, SPELL_BURNING_LIGHT); events.ScheduleEvent(EVENT_SEAR, 2000); events.ScheduleEvent(EVENT_BURNING_LIGHT, 12000); break; } case EVENT_SEAR: { Unit* target = me->FindNearestCreature(NPC_SEARING_LIGHT, 100.0f); if (!target) break; std::list<Creature*> stalkers; GetCreatureListWithEntryInGrid(stalkers, me, NPC_CAVE_IN_STALKER, 100.0f); stalkers.remove_if(Trinity::HeightDifferenceCheck(ObjectAccessor::GetGameObject(*me, instance->GetData64(DATA_ANHUUR_DOOR)), 5.0f, true)); if (stalkers.empty()) break; stalkers.sort(Trinity::ObjectDistanceOrderPred(target)); // Get the closest statue face (any of its eyes) Creature* eye1 = stalkers.front(); stalkers.remove(eye1); // Remove the eye. stalkers.sort(Trinity::ObjectDistanceOrderPred(eye1)); // Find the second eye. Creature* eye2 = stalkers.front(); eye1->CastSpell(eye1, SPELL_SEARING_LIGHT, true); eye2->CastSpell(eye2, SPELL_SEARING_LIGHT, true); break; } } } DoMeleeAttackIfReady(); } private: uint8 _phase; uint8 _oldPhase; uint8 _beacons; }; CreatureAI* GetAI(Creature* creature) const OVERRIDE { return GetHallsOfOriginationAI<boss_temple_guardian_anhuurAI>(creature); } }; class spell_anhuur_shield_of_light : public SpellScriptLoader { public: spell_anhuur_shield_of_light() : SpellScriptLoader("spell_anhuur_shield_of_light") { } class spell_anhuur_shield_of_light_SpellScript : public SpellScript { PrepareSpellScript(spell_anhuur_shield_of_light_SpellScript); void FilterTargets(std::list<WorldObject*>& targets) { if (InstanceMap* instance = GetCaster()->GetMap()->ToInstanceMap()) { if (InstanceScript* const script = instance->GetInstanceScript()) { if (GameObject* go = ObjectAccessor::GetGameObject(*GetCaster(), script->GetData64(DATA_ANHUUR_DOOR))) { targets.remove_if(Trinity::HeightDifferenceCheck(go, 5.0f, false)); targets.remove(GetCaster()); targets.sort(Trinity::ObjectDistanceOrderPred(GetCaster())); targets.resize(2); } } } } void Register() OVERRIDE { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_anhuur_shield_of_light_SpellScript::FilterTargets, EFFECT_1, TARGET_UNIT_SRC_AREA_ENTRY); } }; SpellScript* GetSpellScript() const OVERRIDE { return new spell_anhuur_shield_of_light_SpellScript(); } }; class spell_anhuur_disable_beacon_beams : public SpellScriptLoader { public: spell_anhuur_disable_beacon_beams() : SpellScriptLoader("spell_anhuur_disable_beacon_beams") { } class spell_anhuur_disable_beacon_beams_SpellScript : public SpellScript { PrepareSpellScript(spell_anhuur_disable_beacon_beams_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { GetHitUnit()->RemoveAurasDueToSpell(GetEffectValue()); } void Notify(SpellEffIndex /*index*/) { if (InstanceMap* instance = GetCaster()->GetMap()->ToInstanceMap()) if (InstanceScript* const script = instance->GetInstanceScript()) if (Creature* anhuur = instance->GetCreature(script->GetData64(DATA_ANHUUR_GUID))) anhuur->AI()->DoAction(ACTION_DISABLE_BEACON); } void Register() OVERRIDE { OnEffectHitTarget += SpellEffectFn(spell_anhuur_disable_beacon_beams_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); OnEffectHit += SpellEffectFn(spell_anhuur_disable_beacon_beams_SpellScript::Notify, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const OVERRIDE { return new spell_anhuur_disable_beacon_beams_SpellScript(); } }; class spell_anhuur_activate_beacons : public SpellScriptLoader { public: spell_anhuur_activate_beacons() : SpellScriptLoader("spell_anhuur_activate_beacons") { } class spell_anhuur_activate_beacons_SpellScript : public SpellScript { PrepareSpellScript(spell_anhuur_activate_beacons_SpellScript); void Activate(SpellEffIndex index) { PreventHitDefaultEffect(index); GetHitGObj()->RemoveFlag(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_NOT_SELECTABLE); } void Register() OVERRIDE { OnEffectHitTarget += SpellEffectFn(spell_anhuur_activate_beacons_SpellScript::Activate, EFFECT_0, SPELL_EFFECT_ACTIVATE_OBJECT); } }; SpellScript* GetSpellScript() const OVERRIDE { return new spell_anhuur_activate_beacons_SpellScript(); } }; class spell_anhuur_divine_reckoning : public SpellScriptLoader { public: spell_anhuur_divine_reckoning() : SpellScriptLoader("spell_anhuur_divine_reckoning") { } class spell_anhuur_divine_reckoning_AuraScript : public AuraScript { PrepareAuraScript(spell_anhuur_divine_reckoning_AuraScript); void OnPeriodic(AuraEffect const* aurEff) { if (Unit* caster = GetCaster()) { CustomSpellValues values; values.AddSpellMod(SPELLVALUE_BASE_POINT0, aurEff->GetAmount()); caster->CastCustomSpell(GetSpellInfo()->Effects[EFFECT_0].TriggerSpell, values, GetTarget()); } } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_anhuur_divine_reckoning_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; AuraScript* GetAuraScript() const { return new spell_anhuur_divine_reckoning_AuraScript(); } }; void AddSC_boss_temple_guardian_anhuur() { new boss_temple_guardian_anhuur(); new spell_anhuur_shield_of_light(); new spell_anhuur_disable_beacon_beams(); new spell_anhuur_activate_beacons(); new spell_anhuur_divine_reckoning(); }
xtypeluki/mop548
src/server/scripts/Kalimdor/HallsOfOrigination/boss_temple_guardian_anhuur.cpp
C++
gpl-2.0
14,685
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing authors: Stephen Foiles (SNL), Murray Daw (SNL) ------------------------------------------------------------------------- */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pair_eam.h" #include "atom.h" #include "force.h" #include "comm.h" #include "neighbor.h" #include "neigh_list.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; #define MAXLINE 1024 /* ---------------------------------------------------------------------- */ PairEAM::PairEAM(LAMMPS *lmp) : Pair(lmp) { restartinfo = 0; manybody_flag = 1; nmax = 0; rho = NULL; fp = NULL; map = NULL; type2frho = NULL; nfuncfl = 0; funcfl = NULL; setfl = NULL; fs = NULL; frho = NULL; rhor = NULL; z2r = NULL; scale = NULL; frho_spline = NULL; rhor_spline = NULL; z2r_spline = NULL; // set comm size needed by this Pair comm_forward = 1; comm_reverse = 1; } /* ---------------------------------------------------------------------- check if allocated, since class can be destructed when incomplete ------------------------------------------------------------------------- */ PairEAM::~PairEAM() { if (copymode) return; memory->destroy(rho); memory->destroy(fp); if (allocated) { memory->destroy(setflag); memory->destroy(cutsq); delete [] map; delete [] type2frho; map = NULL; type2frho = NULL; memory->destroy(type2rhor); memory->destroy(type2z2r); memory->destroy(scale); } if (funcfl) { for (int i = 0; i < nfuncfl; i++) { delete [] funcfl[i].file; memory->destroy(funcfl[i].frho); memory->destroy(funcfl[i].rhor); memory->destroy(funcfl[i].zr); } memory->sfree(funcfl); funcfl = NULL; } if (setfl) { for (int i = 0; i < setfl->nelements; i++) delete [] setfl->elements[i]; delete [] setfl->elements; delete [] setfl->mass; memory->destroy(setfl->frho); memory->destroy(setfl->rhor); memory->destroy(setfl->z2r); delete setfl; setfl = NULL; } if (fs) { for (int i = 0; i < fs->nelements; i++) delete [] fs->elements[i]; delete [] fs->elements; delete [] fs->mass; memory->destroy(fs->frho); memory->destroy(fs->rhor); memory->destroy(fs->z2r); delete fs; fs = NULL; } memory->destroy(frho); memory->destroy(rhor); memory->destroy(z2r); memory->destroy(frho_spline); memory->destroy(rhor_spline); memory->destroy(z2r_spline); } /* ---------------------------------------------------------------------- */ void PairEAM::compute(int eflag, int vflag) { int i,j,ii,jj,m,inum,jnum,itype,jtype; double xtmp,ytmp,ztmp,delx,dely,delz,evdwl,fpair; double rsq,r,p,rhoip,rhojp,z2,z2p,recip,phip,psip,phi; double *coeff; int *ilist,*jlist,*numneigh,**firstneigh; evdwl = 0.0; if (eflag || vflag) ev_setup(eflag,vflag); else evflag = vflag_fdotr = eflag_global = eflag_atom = 0; // grow energy and fp arrays if necessary // need to be atom->nmax in length if (atom->nmax > nmax) { memory->destroy(rho); memory->destroy(fp); nmax = atom->nmax; memory->create(rho,nmax,"pair:rho"); memory->create(fp,nmax,"pair:fp"); } double **x = atom->x; double **f = atom->f; int *type = atom->type; int nlocal = atom->nlocal; int nall = nlocal + atom->nghost; int newton_pair = force->newton_pair; inum = list->inum; ilist = list->ilist; numneigh = list->numneigh; firstneigh = list->firstneigh; // zero out density if (newton_pair) { for (i = 0; i < nall; i++) rho[i] = 0.0; } else for (i = 0; i < nlocal; i++) rho[i] = 0.0; // rho = density at each atom // loop over neighbors of my atoms for (ii = 0; ii < inum; ii++) { i = ilist[ii]; xtmp = x[i][0]; ytmp = x[i][1]; ztmp = x[i][2]; itype = type[i]; jlist = firstneigh[i]; jnum = numneigh[i]; for (jj = 0; jj < jnum; jj++) { j = jlist[jj]; j &= NEIGHMASK; delx = xtmp - x[j][0]; dely = ytmp - x[j][1]; delz = ztmp - x[j][2]; rsq = delx*delx + dely*dely + delz*delz; if (rsq < cutforcesq) { jtype = type[j]; p = sqrt(rsq)*rdr + 1.0; m = static_cast<int> (p); m = MIN(m,nr-1); p -= m; p = MIN(p,1.0); coeff = rhor_spline[type2rhor[jtype][itype]][m]; rho[i] += ((coeff[3]*p + coeff[4])*p + coeff[5])*p + coeff[6]; if (newton_pair || j < nlocal) { coeff = rhor_spline[type2rhor[itype][jtype]][m]; rho[j] += ((coeff[3]*p + coeff[4])*p + coeff[5])*p + coeff[6]; } } } } // communicate and sum densities if (newton_pair) comm->reverse_comm_pair(this); // fp = derivative of embedding energy at each atom // phi = embedding energy at each atom // if rho > rhomax (e.g. due to close approach of two atoms), // will exceed table, so add linear term to conserve energy for (ii = 0; ii < inum; ii++) { i = ilist[ii]; p = rho[i]*rdrho + 1.0; m = static_cast<int> (p); m = MAX(1,MIN(m,nrho-1)); p -= m; p = MIN(p,1.0); coeff = frho_spline[type2frho[type[i]]][m]; fp[i] = (coeff[0]*p + coeff[1])*p + coeff[2]; if (eflag) { phi = ((coeff[3]*p + coeff[4])*p + coeff[5])*p + coeff[6]; if (rho[i] > rhomax) phi += fp[i] * (rho[i]-rhomax); phi *= scale[type[i]][type[i]]; if (eflag_global) eng_vdwl += phi; if (eflag_atom) eatom[i] += phi; } } // communicate derivative of embedding function comm->forward_comm_pair(this); // compute forces on each atom // loop over neighbors of my atoms for (ii = 0; ii < inum; ii++) { i = ilist[ii]; xtmp = x[i][0]; ytmp = x[i][1]; ztmp = x[i][2]; itype = type[i]; jlist = firstneigh[i]; jnum = numneigh[i]; for (jj = 0; jj < jnum; jj++) { j = jlist[jj]; j &= NEIGHMASK; delx = xtmp - x[j][0]; dely = ytmp - x[j][1]; delz = ztmp - x[j][2]; rsq = delx*delx + dely*dely + delz*delz; if (rsq < cutforcesq) { jtype = type[j]; r = sqrt(rsq); p = r*rdr + 1.0; m = static_cast<int> (p); m = MIN(m,nr-1); p -= m; p = MIN(p,1.0); // rhoip = derivative of (density at atom j due to atom i) // rhojp = derivative of (density at atom i due to atom j) // phi = pair potential energy // phip = phi' // z2 = phi * r // z2p = (phi * r)' = (phi' r) + phi // psip needs both fp[i] and fp[j] terms since r_ij appears in two // terms of embed eng: Fi(sum rho_ij) and Fj(sum rho_ji) // hence embed' = Fi(sum rho_ij) rhojp + Fj(sum rho_ji) rhoip // scale factor can be applied by thermodynamic integration coeff = rhor_spline[type2rhor[itype][jtype]][m]; rhoip = (coeff[0]*p + coeff[1])*p + coeff[2]; coeff = rhor_spline[type2rhor[jtype][itype]][m]; rhojp = (coeff[0]*p + coeff[1])*p + coeff[2]; coeff = z2r_spline[type2z2r[itype][jtype]][m]; z2p = (coeff[0]*p + coeff[1])*p + coeff[2]; z2 = ((coeff[3]*p + coeff[4])*p + coeff[5])*p + coeff[6]; recip = 1.0/r; phi = z2*recip; phip = z2p*recip - phi*recip; psip = fp[i]*rhojp + fp[j]*rhoip + phip; fpair = -scale[itype][jtype]*psip*recip; f[i][0] += delx*fpair; f[i][1] += dely*fpair; f[i][2] += delz*fpair; if (newton_pair || j < nlocal) { f[j][0] -= delx*fpair; f[j][1] -= dely*fpair; f[j][2] -= delz*fpair; } if (eflag) evdwl = scale[itype][jtype]*phi; if (evflag) ev_tally(i,j,nlocal,newton_pair, evdwl,0.0,fpair,delx,dely,delz); } } } if (vflag_fdotr) virial_fdotr_compute(); } /* ---------------------------------------------------------------------- allocate all arrays ------------------------------------------------------------------------- */ void PairEAM::allocate() { allocated = 1; int n = atom->ntypes; memory->create(setflag,n+1,n+1,"pair:setflag"); for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) setflag[i][j] = 0; memory->create(cutsq,n+1,n+1,"pair:cutsq"); map = new int[n+1]; for (int i = 1; i <= n; i++) map[i] = -1; type2frho = new int[n+1]; memory->create(type2rhor,n+1,n+1,"pair:type2rhor"); memory->create(type2z2r,n+1,n+1,"pair:type2z2r"); memory->create(scale,n+1,n+1,"pair:scale"); } /* ---------------------------------------------------------------------- global settings ------------------------------------------------------------------------- */ void PairEAM::settings(int narg, char **arg) { if (narg > 0) error->all(FLERR,"Illegal pair_style command"); } /* ---------------------------------------------------------------------- set coeffs for one or more type pairs read DYNAMO funcfl file ------------------------------------------------------------------------- */ void PairEAM::coeff(int narg, char **arg) { if (!allocated) allocate(); if (narg != 3) error->all(FLERR,"Incorrect args for pair coefficients"); // parse pair of atom types int ilo,ihi,jlo,jhi; force->bounds(FLERR,arg[0],atom->ntypes,ilo,ihi); force->bounds(FLERR,arg[1],atom->ntypes,jlo,jhi); // read funcfl file if hasn't already been read // store filename in Funcfl data struct int ifuncfl; for (ifuncfl = 0; ifuncfl < nfuncfl; ifuncfl++) if (strcmp(arg[2],funcfl[ifuncfl].file) == 0) break; if (ifuncfl == nfuncfl) { nfuncfl++; funcfl = (Funcfl *) memory->srealloc(funcfl,nfuncfl*sizeof(Funcfl),"pair:funcfl"); read_file(arg[2]); int n = strlen(arg[2]) + 1; funcfl[ifuncfl].file = new char[n]; strcpy(funcfl[ifuncfl].file,arg[2]); } // set setflag and map only for i,i type pairs // set mass of atom type if i = j int count = 0; for (int i = ilo; i <= ihi; i++) { for (int j = MAX(jlo,i); j <= jhi; j++) { if (i == j) { setflag[i][i] = 1; map[i] = ifuncfl; atom->set_mass(FLERR,i,funcfl[ifuncfl].mass); count++; } scale[i][j] = 1.0; } } if (count == 0) error->all(FLERR,"Incorrect args for pair coefficients"); } /* ---------------------------------------------------------------------- init specific to this pair style ------------------------------------------------------------------------- */ void PairEAM::init_style() { // convert read-in file(s) to arrays and spline them file2array(); array2spline(); neighbor->request(this,instance_me); } /* ---------------------------------------------------------------------- init for one type pair i,j and corresponding j,i ------------------------------------------------------------------------- */ double PairEAM::init_one(int i, int j) { // single global cutoff = max of cut from all files read in // for funcfl could be multiple files // for setfl or fs, just one file if (setflag[i][j] == 0) scale[i][j] = 1.0; scale[j][i] = scale[i][j]; if (funcfl) { cutmax = 0.0; for (int m = 0; m < nfuncfl; m++) cutmax = MAX(cutmax,funcfl[m].cut); } else if (setfl) cutmax = setfl->cut; else if (fs) cutmax = fs->cut; cutforcesq = cutmax*cutmax; return cutmax; } /* ---------------------------------------------------------------------- read potential values from a DYNAMO single element funcfl file ------------------------------------------------------------------------- */ void PairEAM::read_file(char *filename) { Funcfl *file = &funcfl[nfuncfl-1]; int me = comm->me; FILE *fptr; char line[MAXLINE]; if (me == 0) { fptr = force->open_potential(filename); if (fptr == NULL) { char str[128]; sprintf(str,"Cannot open EAM potential file %s",filename); error->one(FLERR,str); } } int tmp,nwords; if (me == 0) { fgets(line,MAXLINE,fptr); fgets(line,MAXLINE,fptr); sscanf(line,"%d %lg",&tmp,&file->mass); fgets(line,MAXLINE,fptr); nwords = sscanf(line,"%d %lg %d %lg %lg", &file->nrho,&file->drho,&file->nr,&file->dr,&file->cut); } MPI_Bcast(&nwords,1,MPI_INT,0,world); MPI_Bcast(&file->mass,1,MPI_DOUBLE,0,world); MPI_Bcast(&file->nrho,1,MPI_INT,0,world); MPI_Bcast(&file->drho,1,MPI_DOUBLE,0,world); MPI_Bcast(&file->nr,1,MPI_INT,0,world); MPI_Bcast(&file->dr,1,MPI_DOUBLE,0,world); MPI_Bcast(&file->cut,1,MPI_DOUBLE,0,world); if ((nwords != 5) || (file->nrho <= 0) || (file->nr <= 0) || (file->dr <= 0.0)) error->all(FLERR,"Invalid EAM potential file"); memory->create(file->frho,(file->nrho+1),"pair:frho"); memory->create(file->rhor,(file->nr+1),"pair:rhor"); memory->create(file->zr,(file->nr+1),"pair:zr"); if (me == 0) grab(fptr,file->nrho,&file->frho[1]); MPI_Bcast(&file->frho[1],file->nrho,MPI_DOUBLE,0,world); if (me == 0) grab(fptr,file->nr,&file->zr[1]); MPI_Bcast(&file->zr[1],file->nr,MPI_DOUBLE,0,world); if (me == 0) grab(fptr,file->nr,&file->rhor[1]); MPI_Bcast(&file->rhor[1],file->nr,MPI_DOUBLE,0,world); if (me == 0) fclose(fptr); } /* ---------------------------------------------------------------------- convert read-in funcfl potential(s) to standard array format interpolate all file values to a single grid and cutoff ------------------------------------------------------------------------- */ void PairEAM::file2array() { int i,j,k,m,n; int ntypes = atom->ntypes; double sixth = 1.0/6.0; // determine max function params from all active funcfl files // active means some element is pointing at it via map int active; double rmax; dr = drho = rmax = rhomax = 0.0; for (int i = 0; i < nfuncfl; i++) { active = 0; for (j = 1; j <= ntypes; j++) if (map[j] == i) active = 1; if (active == 0) continue; Funcfl *file = &funcfl[i]; dr = MAX(dr,file->dr); drho = MAX(drho,file->drho); rmax = MAX(rmax,(file->nr-1) * file->dr); rhomax = MAX(rhomax,(file->nrho-1) * file->drho); } // set nr,nrho from cutoff and spacings // 0.5 is for round-off in divide nr = static_cast<int> (rmax/dr + 0.5); nrho = static_cast<int> (rhomax/drho + 0.5); // ------------------------------------------------------------------ // setup frho arrays // ------------------------------------------------------------------ // allocate frho arrays // nfrho = # of funcfl files + 1 for zero array nfrho = nfuncfl + 1; memory->destroy(frho); memory->create(frho,nfrho,nrho+1,"pair:frho"); // interpolate each file's frho to a single grid and cutoff double r,p,cof1,cof2,cof3,cof4; n = 0; for (i = 0; i < nfuncfl; i++) { Funcfl *file = &funcfl[i]; for (m = 1; m <= nrho; m++) { r = (m-1)*drho; p = r/file->drho + 1.0; k = static_cast<int> (p); k = MIN(k,file->nrho-2); k = MAX(k,2); p -= k; p = MIN(p,2.0); cof1 = -sixth*p*(p-1.0)*(p-2.0); cof2 = 0.5*(p*p-1.0)*(p-2.0); cof3 = -0.5*p*(p+1.0)*(p-2.0); cof4 = sixth*p*(p*p-1.0); frho[n][m] = cof1*file->frho[k-1] + cof2*file->frho[k] + cof3*file->frho[k+1] + cof4*file->frho[k+2]; } n++; } // add extra frho of zeroes for non-EAM types to point to (pair hybrid) // this is necessary b/c fp is still computed for non-EAM atoms for (m = 1; m <= nrho; m++) frho[nfrho-1][m] = 0.0; // type2frho[i] = which frho array (0 to nfrho-1) each atom type maps to // if atom type doesn't point to file (non-EAM atom in pair hybrid) // then map it to last frho array of zeroes for (i = 1; i <= ntypes; i++) if (map[i] >= 0) type2frho[i] = map[i]; else type2frho[i] = nfrho-1; // ------------------------------------------------------------------ // setup rhor arrays // ------------------------------------------------------------------ // allocate rhor arrays // nrhor = # of funcfl files nrhor = nfuncfl; memory->destroy(rhor); memory->create(rhor,nrhor,nr+1,"pair:rhor"); // interpolate each file's rhor to a single grid and cutoff n = 0; for (i = 0; i < nfuncfl; i++) { Funcfl *file = &funcfl[i]; for (m = 1; m <= nr; m++) { r = (m-1)*dr; p = r/file->dr + 1.0; k = static_cast<int> (p); k = MIN(k,file->nr-2); k = MAX(k,2); p -= k; p = MIN(p,2.0); cof1 = -sixth*p*(p-1.0)*(p-2.0); cof2 = 0.5*(p*p-1.0)*(p-2.0); cof3 = -0.5*p*(p+1.0)*(p-2.0); cof4 = sixth*p*(p*p-1.0); rhor[n][m] = cof1*file->rhor[k-1] + cof2*file->rhor[k] + cof3*file->rhor[k+1] + cof4*file->rhor[k+2]; } n++; } // type2rhor[i][j] = which rhor array (0 to nrhor-1) each type pair maps to // for funcfl files, I,J mapping only depends on I // OK if map = -1 (non-EAM atom in pair hybrid) b/c type2rhor not used for (i = 1; i <= ntypes; i++) for (j = 1; j <= ntypes; j++) type2rhor[i][j] = map[i]; // ------------------------------------------------------------------ // setup z2r arrays // ------------------------------------------------------------------ // allocate z2r arrays // nz2r = N*(N+1)/2 where N = # of funcfl files nz2r = nfuncfl*(nfuncfl+1)/2; memory->destroy(z2r); memory->create(z2r,nz2r,nr+1,"pair:z2r"); // create a z2r array for each file against other files, only for I >= J // interpolate zri and zrj to a single grid and cutoff double zri,zrj; n = 0; for (i = 0; i < nfuncfl; i++) { Funcfl *ifile = &funcfl[i]; for (j = 0; j <= i; j++) { Funcfl *jfile = &funcfl[j]; for (m = 1; m <= nr; m++) { r = (m-1)*dr; p = r/ifile->dr + 1.0; k = static_cast<int> (p); k = MIN(k,ifile->nr-2); k = MAX(k,2); p -= k; p = MIN(p,2.0); cof1 = -sixth*p*(p-1.0)*(p-2.0); cof2 = 0.5*(p*p-1.0)*(p-2.0); cof3 = -0.5*p*(p+1.0)*(p-2.0); cof4 = sixth*p*(p*p-1.0); zri = cof1*ifile->zr[k-1] + cof2*ifile->zr[k] + cof3*ifile->zr[k+1] + cof4*ifile->zr[k+2]; p = r/jfile->dr + 1.0; k = static_cast<int> (p); k = MIN(k,jfile->nr-2); k = MAX(k,2); p -= k; p = MIN(p,2.0); cof1 = -sixth*p*(p-1.0)*(p-2.0); cof2 = 0.5*(p*p-1.0)*(p-2.0); cof3 = -0.5*p*(p+1.0)*(p-2.0); cof4 = sixth*p*(p*p-1.0); zrj = cof1*jfile->zr[k-1] + cof2*jfile->zr[k] + cof3*jfile->zr[k+1] + cof4*jfile->zr[k+2]; z2r[n][m] = 27.2*0.529 * zri*zrj; } n++; } } // type2z2r[i][j] = which z2r array (0 to nz2r-1) each type pair maps to // set of z2r arrays only fill lower triangular Nelement matrix // value = n = sum over rows of lower-triangular matrix until reach irow,icol // swap indices when irow < icol to stay lower triangular // if map = -1 (non-EAM atom in pair hybrid): // type2z2r is not used by non-opt // but set type2z2r to 0 since accessed by opt int irow,icol; for (i = 1; i <= ntypes; i++) { for (j = 1; j <= ntypes; j++) { irow = map[i]; icol = map[j]; if (irow == -1 || icol == -1) { type2z2r[i][j] = 0; continue; } if (irow < icol) { irow = map[j]; icol = map[i]; } n = 0; for (m = 0; m < irow; m++) n += m + 1; n += icol; type2z2r[i][j] = n; } } } /* ---------------------------------------------------------------------- */ void PairEAM::array2spline() { rdr = 1.0/dr; rdrho = 1.0/drho; memory->destroy(frho_spline); memory->destroy(rhor_spline); memory->destroy(z2r_spline); memory->create(frho_spline,nfrho,nrho+1,7,"pair:frho"); memory->create(rhor_spline,nrhor,nr+1,7,"pair:rhor"); memory->create(z2r_spline,nz2r,nr+1,7,"pair:z2r"); for (int i = 0; i < nfrho; i++) interpolate(nrho,drho,frho[i],frho_spline[i]); for (int i = 0; i < nrhor; i++) interpolate(nr,dr,rhor[i],rhor_spline[i]); for (int i = 0; i < nz2r; i++) interpolate(nr,dr,z2r[i],z2r_spline[i]); } /* ---------------------------------------------------------------------- */ void PairEAM::interpolate(int n, double delta, double *f, double **spline) { for (int m = 1; m <= n; m++) spline[m][6] = f[m]; spline[1][5] = spline[2][6] - spline[1][6]; spline[2][5] = 0.5 * (spline[3][6]-spline[1][6]); spline[n-1][5] = 0.5 * (spline[n][6]-spline[n-2][6]); spline[n][5] = spline[n][6] - spline[n-1][6]; for (int m = 3; m <= n-2; m++) spline[m][5] = ((spline[m-2][6]-spline[m+2][6]) + 8.0*(spline[m+1][6]-spline[m-1][6])) / 12.0; for (int m = 1; m <= n-1; m++) { spline[m][4] = 3.0*(spline[m+1][6]-spline[m][6]) - 2.0*spline[m][5] - spline[m+1][5]; spline[m][3] = spline[m][5] + spline[m+1][5] - 2.0*(spline[m+1][6]-spline[m][6]); } spline[n][4] = 0.0; spline[n][3] = 0.0; for (int m = 1; m <= n; m++) { spline[m][2] = spline[m][5]/delta; spline[m][1] = 2.0*spline[m][4]/delta; spline[m][0] = 3.0*spline[m][3]/delta; } } /* ---------------------------------------------------------------------- grab n values from file fp and put them in list values can be several to a line only called by proc 0 ------------------------------------------------------------------------- */ void PairEAM::grab(FILE *fptr, int n, double *list) { char *ptr; char line[MAXLINE]; int i = 0; while (i < n) { fgets(line,MAXLINE,fptr); ptr = strtok(line," \t\n\r\f"); list[i++] = atof(ptr); while ((ptr = strtok(NULL," \t\n\r\f"))) list[i++] = atof(ptr); } } /* ---------------------------------------------------------------------- */ double PairEAM::single(int i, int j, int itype, int jtype, double rsq, double factor_coul, double factor_lj, double &fforce) { int m; double r,p,rhoip,rhojp,z2,z2p,recip,phi,phip,psip; double *coeff; r = sqrt(rsq); p = r*rdr + 1.0; m = static_cast<int> (p); m = MIN(m,nr-1); p -= m; p = MIN(p,1.0); coeff = rhor_spline[type2rhor[itype][jtype]][m]; rhoip = (coeff[0]*p + coeff[1])*p + coeff[2]; coeff = rhor_spline[type2rhor[jtype][itype]][m]; rhojp = (coeff[0]*p + coeff[1])*p + coeff[2]; coeff = z2r_spline[type2z2r[itype][jtype]][m]; z2p = (coeff[0]*p + coeff[1])*p + coeff[2]; z2 = ((coeff[3]*p + coeff[4])*p + coeff[5])*p + coeff[6]; recip = 1.0/r; phi = z2*recip; phip = z2p*recip - phi*recip; psip = fp[i]*rhojp + fp[j]*rhoip + phip; fforce = -psip*recip; return phi; } /* ---------------------------------------------------------------------- */ int PairEAM::pack_forward_comm(int n, int *list, double *buf, int pbc_flag, int *pbc) { int i,j,m; m = 0; for (i = 0; i < n; i++) { j = list[i]; buf[m++] = fp[j]; } return m; } /* ---------------------------------------------------------------------- */ void PairEAM::unpack_forward_comm(int n, int first, double *buf) { int i,m,last; m = 0; last = first + n; for (i = first; i < last; i++) fp[i] = buf[m++]; } /* ---------------------------------------------------------------------- */ int PairEAM::pack_reverse_comm(int n, int first, double *buf) { int i,m,last; m = 0; last = first + n; for (i = first; i < last; i++) buf[m++] = rho[i]; return m; } /* ---------------------------------------------------------------------- */ void PairEAM::unpack_reverse_comm(int n, int *list, double *buf) { int i,j,m; m = 0; for (i = 0; i < n; i++) { j = list[i]; rho[j] += buf[m++]; } } /* ---------------------------------------------------------------------- memory usage of local atom-based arrays ------------------------------------------------------------------------- */ double PairEAM::memory_usage() { double bytes = maxeatom * sizeof(double); bytes += maxvatom*6 * sizeof(double); bytes += 2 * nmax * sizeof(double); return bytes; } /* ---------------------------------------------------------------------- swap fp array with one passed in by caller ------------------------------------------------------------------------- */ void PairEAM::swap_eam(double *fp_caller, double **fp_caller_hold) { double *tmp = fp; fp = fp_caller; *fp_caller_hold = tmp; } /* ---------------------------------------------------------------------- */ void *PairEAM::extract(const char *str, int &dim) { dim = 2; if (strcmp(str,"scale") == 0) return (void *) scale; return NULL; }
ramisetti/lammps
src/MANYBODY/pair_eam.cpp
C++
gpl-2.0
25,263
/* Copyright (C) 2005-2013 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* Type used for the representation of TLS information in the GOT. */ typedef struct { unsigned long int ti_module; unsigned long int ti_offset; } tls_index; extern void *__tls_get_addr (tls_index *ti); /* Value used for dtv entries for which the allocation is delayed. */ #define TLS_DTV_UNALLOCATED ((void *) -1l)
SanDisk-Open-Source/SSD_Dashboard
uefi/userspace/glibc/ports/sysdeps/aarch64/dl-tls.h
C
gpl-2.0
1,115
#!/usr/bin/perl # Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2.0, # as published by the Free Software Foundation. # # This program is also distributed with certain software (including # but not limited to OpenSSL) that is licensed under separate terms, # as designated in a particular file or component or in included license # documentation. The authors of MySQL hereby grant you an additional # permission to link the program and your derivative works with the # separately licensed software that they have included with MySQL. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License, version 2.0, for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # ====================================================================== # MySQL server stress test system # ====================================================================== # ########################################################################## # # SCENARIOS AND REQUIREMENTS # # The system should perform stress testing of MySQL server with # following requirements and basic scenarios: # # Basic requirements: # # Design of stress script should allow one: # # - to use for stress testing mysqltest binary as test engine # - to use for stress testing both regular test suite and any # additional test suites (e.g. mysql-test-extra-5.0) # - to specify files with lists of tests both for initialization of # stress db and for further testing itself # - to define number of threads that will be concurrently used in testing # - to define limitations for test run. e.g. number of tests or loops # for execution or duration of testing, delay between test executions, etc. # - to get readable log file which can be used for identification of # errors arose during testing # # Basic scenarios: # # * It should be possible to run stress script in standalone mode # which will allow to create various scenarios of stress workloads: # # simple ones: # # box #1: # - one instance of script with list of tests #1 # # and more advanced ones: # # box #1: # - one instance of script with list of tests #1 # - another instance of script with list of tests #2 # box #2: # - one instance of script with list of tests #3 # - another instance of script with list of tests #4 # that will recreate whole database to back it to clean # state # # One kind of such complex scenarios maybe continued testing # when we want to run stress tests from many boxes with various # lists of tests that will last very long time. And in such case # we need some wrapper for MySQL server that will restart it in # case of crashes. # # * It should be possible to run stress script in ad-hoc mode from # shell or perl versions of mysql-test-run. This allows developers # to reproduce and debug errors that was found in continued stress # testing # # 2009-01-28 OBN Additions and modifications per WL#4685 # ######################################################################## use Config; if (!defined($Config{useithreads})) { die <<EOF; It is unable to run threaded version of stress test on this system due to disabled ithreads. Please check that installed perl binary was built with support of ithreads. EOF } use threads; use threads::shared; use IO::Socket; use Sys::Hostname; use File::Copy; use File::Spec; use File::Find; use File::Basename; use File::Path; use Cwd; use Data::Dumper; use Getopt::Long; my $stress_suite_version="1.0"; $|=1; $opt_server_host=""; $opt_server_logs_dir=""; $opt_help=""; $opt_server_port=""; $opt_server_socket=""; $opt_server_user=""; $opt_server_password=""; $opt_server_database=""; $opt_cleanup=""; $opt_verbose=""; $opt_log_error_details=""; $opt_suite="main"; $opt_stress_suite_basedir=""; $opt_stress_basedir=""; $opt_stress_datadir=""; $opt_test_suffix=""; $opt_stress_mode="random"; $opt_loop_count=0; $opt_test_count=0; $opt_test_duration=0; # OBN: Changing abort-on-error default to -1 (for WL-4626/4685): -1 means no abort $opt_abort_on_error=-1; $opt_sleep_time = 0; $opt_threads=1; $pid_file="mysql_stress_test.pid"; $opt_mysqltest= ($^O =~ /mswin32/i) ? "mysqltest.exe" : "mysqltest"; $opt_check_tests_file=""; # OBM adding a setting for 'max-connect-retries=20' the default of 500 is to high @mysqltest_args=("--silent", "-v", "--max-connect-retries=20"); # Client ip address $client_ip=inet_ntoa((gethostbyname(hostname()))[4]); $client_ip=~ s/\.//g; %tests_files=(client => {mtime => 0, data => []}, initdb => {mtime => 0, data => []}); # Error codes and sub-strings with corresponding severity # # S1 - Critical errors - cause immediately abort of testing. These errors # could be caused by server crash or impossibility # of test execution. # # S2 - Serious errors - these errors are bugs for sure as it knowns that # they shouldn't appear during stress testing # # S3 - Unknown errors - Errors were returned but we don't know what they are # so script can't determine if they are OK or not # # S4 - Non-seriuos errros - these errors could be caused by fact that # we execute simultaneously statements that # affect tests executed by other threads %error_strings = ( 'Failed in mysql_real_connect()' => S1, 'Can\'t connect' => S1, 'not found (Errcode: 2)' => S1, 'does not exist' => S1, 'Could not open connection \'default\' after \d+ attempts' => S1, 'wrong errno ' => S3, 'Result length mismatch' => S4, 'Result content mismatch' => S4); %error_codes = ( 1012 => S2, 1015 => S2, 1021 => S2, 1027 => S2, 1037 => S2, 1038 => S2, 1039 => S2, 1040 => S2, 1046 => S2, 1053 => S2, 1180 => S2, 1181 => S2, 1203 => S2, 1205 => S4, 1206 => S2, 1207 => S2, 1213 => S4, 1223 => S2, 2002 => S1, 2003 => S1, 2006 => S1, 2013 => S1 ); share(%test_counters); %test_counters=( loop_count => 0, test_count=>0); share($exiting); $exiting=0; # OBN Code and 'set_exit_code' function added by ES to set an exit code based on the error category returned # in combination with the --abort-on-error value see WL#4685) use constant ABORT_MAKEWEIGHT => 20; share($gExitCode); $gExitCode = 0; # global exit code sub set_exit_code { my $severity = shift; my $code = 0; if ( $severity =~ /^S(\d+)/ ) { $severity = $1; $code = 11 - $severity; # S1=10, S2=9, ... -- as per WL } else { # we know how we call the sub: severity should be S<num>; so, we should never be here... print STDERR "Unknown severity format: $severity; setting to S1\n"; $severity = 1; } $abort = 0; if ( $severity <= $opt_abort_on_error ) { # the test finished with a failure severe enough to abort. We are adding the 'abort flag' to the exit code $code += ABORT_MAKEWEIGHT; # but are not exiting just yet -- we need to update global exit code first $abort = 1; } lock $gExitCode; # we can use lock here because the script uses threads anyway $gExitCode = $code if $code > $gExitCode; kill INT, $$ if $abort; # this is just a way to call sig_INT_handler: it will set exiting flag, which should do the rest } share($test_counters_lock); $test_counters_lock=0; share($log_file_lock); $log_file_lock=0; $SIG{INT}= \&sig_INT_handler; $SIG{TERM}= \&sig_TERM_handler; GetOptions("server-host=s", "server-logs-dir=s", "server-port=s", "server-socket=s", "server-user=s", "server-password=s", "server-database=s", "stress-suite-basedir=s", "suite=s", "stress-init-file:s", "stress-tests-file:s", "stress-basedir=s", "stress-mode=s", "stress-datadir=s", "threads=s", "sleep-time=s", "loop-count=i", "test-count=i", "test-duration=i", "test-suffix=s", "check-tests-file", "verbose", "log-error-details", "cleanup", "mysqltest=s", # OBN: (changing 'abort-on-error' to numberic for WL-4626/4685) "abort-on-error=i" => \$opt_abort_on_error, "help") || usage(1); usage(0) if ($opt_help); #$opt_abort_on_error=1; $test_dirname=get_timestamp(); $test_dirname.="-$opt_test_suffix" if ($opt_test_suffix ne ''); print <<EOF; ############################################################# CONFIGURATION STAGE ############################################################# EOF if ($opt_stress_basedir eq '' || $opt_stress_suite_basedir eq '' || $opt_server_logs_dir eq '') { die <<EOF; Options --stress-basedir, --stress-suite-basedir and --server-logs-dir are required. Please use these options to specify proper basedir for client, test suite and location of server logs. stress-basedir: '$opt_stress_basedir' stress-suite-basedir: '$opt_stress_suite_basedir' server-logs-dir: '$opt_server_logs_dir' EOF } #Workaround for case when we got relative but not absolute path $opt_stress_basedir=File::Spec->rel2abs($opt_stress_basedir); $opt_stress_suite_basedir=File::Spec->rel2abs($opt_stress_suite_basedir); $opt_server_logs_dir=File::Spec->rel2abs($opt_server_logs_dir); if ($opt_stress_datadir ne '') { $opt_stress_datadir=File::Spec->rel2abs($opt_stress_datadir); } if (! -d "$opt_stress_basedir") { die <<EOF; Directory '$opt_stress_basedir' does not exist. Use --stress-basedir option to specify proper basedir for client EOF } if (!-d $opt_stress_suite_basedir) { die <<EOF; Directory '$opt_stress_suite_basedir' does not exist. Use --stress-suite-basedir option to specify proper basedir for test suite EOF } $test_dataset_dir=$opt_stress_suite_basedir; if ($opt_stress_datadir ne '') { if (-d $opt_stress_datadir) { $test_dataset_dir=$opt_stress_datadir; } else { die <<EOF; Directory '$opt_stress_datadir' not exists. Please specify proper one with --stress-datadir option. EOF } } if ($^O =~ /mswin32/i) { $test_dataset_dir=~ s/\\/\\\\/g; } else { $test_dataset_dir.="/"; } if (!-d $opt_server_logs_dir) { die <<EOF; Directory server-logs-dir '$opt_server_logs_dir' does not exist. Use --server-logs-dir option to specify proper directory for storing logs EOF } else { #Create sub-directory for test session logs mkpath(File::Spec->catdir($opt_server_logs_dir, $test_dirname), 0, 0755); #Define filename of global session log file $stress_log_file=File::Spec->catfile($opt_server_logs_dir, $test_dirname, "mysql-stress-test.log"); } if ($opt_suite ne '' && $opt_suite ne 'main' && $opt_suite ne 'default') { $test_suite_dir=File::Spec->catdir($opt_stress_suite_basedir, "suite", $opt_suite); } else { $test_suite_dir= $opt_stress_suite_basedir; } if (!-d $test_suite_dir) { die <<EOF Directory '$test_suite_dir' does not exist. Use --suite options to specify proper dir for test suite EOF } $test_suite_t_path=File::Spec->catdir($test_suite_dir,'t'); $test_suite_r_path=File::Spec->catdir($test_suite_dir,'r'); foreach my $suite_dir ($test_suite_t_path, $test_suite_r_path) { if (!-d $suite_dir) { die <<EOF; Directory '$suite_dir' does not exist. Please ensure that you specified proper source location for test/result files with --stress-suite-basedir option and name of test suite with --suite option EOF } } $test_t_path=File::Spec->catdir($opt_stress_basedir,'t'); $test_r_path=File::Spec->catdir($opt_stress_basedir,'r'); foreach $test_dir ($test_t_path, $test_r_path) { if (-d $test_dir) { if ($opt_cleanup) { #Delete existing 't', 'r', 'r/*' subfolders in $stress_basedir rmtree("$test_dir", 0, 0); print "Cleanup $test_dir\n"; } else { die <<EOF; Directory '$test_dir' already exist. Please ensure that you specified proper location of working dir for current test run with --stress-basedir option or in case of staled directories use --cleanup option to remove ones EOF } } #Create empty 't', 'r' subfolders that will be filled later mkpath("$test_dir", 0, 0777); } if (!defined($opt_stress_tests_file) && !defined($opt_stress_init_file)) { die <<EOF; You should run stress script either with --stress-tests-file or with --stress-init-file otions. See help for details. EOF } if (defined($opt_stress_tests_file)) { if ($opt_stress_tests_file eq '') { #Default location of file with set of tests for current test run $tests_files{client}->{filename}= File::Spec->catfile($opt_stress_suite_basedir, "testslist_client.txt"); } else { $tests_files{client}->{filename}= $opt_stress_tests_file; } if (!-f $tests_files{client}->{filename}) { die <<EOF; File '$tests_files{client}->{filename}' with list of tests not exists. Please ensure that this file exists, readable or specify another one with --stress-tests-file option. EOF } } if (defined($opt_stress_init_file)) { if ($opt_stress_init_file eq '') { #Default location of file with set of tests for current test run $tests_files{initdb}->{filename}= File::Spec->catfile($opt_stress_suite_basedir, "testslist_initdb.txt"); } else { $tests_files{initdb}->{filename}= $opt_stress_init_file; } if (!-f $tests_files{initdb}->{filename}) { die <<EOF; File '$tests_files{initdb}->{filename}' with list of tests for initialization of database for stress test not exists. Please ensure that this file exists, readable or specify another one with --stress-init-file option. EOF } } if ($opt_stress_mode !~ /^(random|seq)$/) { die <<EOF Was specified wrong --stress-mode. Correct values 'random' and 'seq'. EOF } if (open(TEST, "$opt_mysqltest -V |")) { $mysqltest_version=join("",<TEST>); close(TEST); print "FOUND MYSQLTEST BINARY: ", $mysqltest_version,"\n"; } else { die <<EOF; ERROR: mysqltest binary $opt_mysqltest not found $!. You must either specify file location explicitly using --mysqltest option, or make sure path to mysqltest binary is listed in your PATH environment variable. EOF } # #Adding mysql server specific command line options for mysqltest binary # $opt_server_host= $opt_server_host ? $opt_server_host : "localhost"; $opt_server_port= $opt_server_port ? $opt_server_port : "3306"; $opt_server_user= $opt_server_user ? $opt_server_user : "root"; $opt_server_socket= $opt_server_socket ? $opt_server_socket : "/tmp/mysql.sock"; $opt_server_database= $opt_server_database ? $opt_server_database : "test"; unshift @mysqltest_args, "--host=$opt_server_host"; unshift @mysqltest_args, "--port=$opt_server_port"; unshift @mysqltest_args, "--user=$opt_server_user"; unshift @mysqltest_args, "--password=$opt_server_password"; unshift @mysqltest_args, "--socket=$opt_server_socket"; unshift @mysqltest_args, "--database=$opt_server_database"; #Export variables that could be used in tests $ENV{MYSQL_TEST_DIR}=$test_dataset_dir; $ENV{MASTER_MYPORT}=$opt_server_port; $ENV{MASTER_MYSOCK}=$opt_server_socket; print <<EOF; TEST-SUITE-BASEDIR: $opt_stress_suite_basedir SUITE: $opt_suite TEST-BASE-DIR: $opt_stress_basedir TEST-DATADIR: $test_dataset_dir SERVER-LOGS-DIR: $opt_server_logs_dir THREADS: $opt_threads TEST-MODE: $opt_stress_mode EOF #------------------------------------------------------------------------------- #At this stage we've already checked all needed pathes/files #and ready to start the test #------------------------------------------------------------------------------- if (defined($opt_stress_tests_file) || defined($opt_stress_init_file)) { print <<EOF; ############################################################# PREPARATION STAGE ############################################################# EOF #Copy Test files from network share to 't' folder print "\nCopying Test files from $test_suite_t_path to $test_t_path folder..."; find({wanted=>\&copy_test_files, bydepth=>1}, "$test_suite_t_path"); print "Done\n"; #$test_r_path/r0 dir reserved for initdb $count_start= defined($opt_stress_init_file) ? 0 : 1; our $r_folder=''; print "\nCreating 'r' folder and copying Protocol files to each 'r#' sub-folder..."; for($count=$count_start; $count <= $opt_threads; $count++) { $r_folder = File::Spec->catdir($test_r_path, "r".$count); mkpath("$r_folder", 0, 0777); find(\&copy_result_files,"$test_suite_r_path"); } print "Done\n\n"; } if (defined($opt_stress_init_file)) { print <<EOF; ############################################################# INITIALIZATION STAGE ############################################################# EOF #Set limits for stress db initialization %limits=(loop_count => 1, test_count => undef); #Read list of tests from $opt_stress_init_file read_tests_names($tests_files{initdb}); test_loop($client_ip, 0, 'seq', $tests_files{initdb}); #print Dumper($tests_files{initdb}),"\n"; print <<EOF; Done initialization of stress database by tests from $tests_files{initdb}->{filename} file. EOF } if (defined($opt_stress_tests_file)) { print <<EOF; ############################################################# STRESS TEST RUNNING STAGE ############################################################# EOF $exiting=0; #Read list of tests from $opt_stress_tests_file read_tests_names($tests_files{client}); #Reset current counter and set limits %test_counters=( loop_count => 0, test_count=>0); %limits=(loop_count => $opt_loop_count, test_count => $opt_test_count); if (($opt_loop_count && $opt_threads > $opt_loop_count) || ($opt_test_count && $opt_threads > $opt_test_count)) { warn <<EOF; WARNING: Possible inaccuracies in number of executed loops or tests because number of threads bigger than number of loops or tests: Threads will be started: $opt_threads Loops will be executed: $opt_loop_count Tests will be executed: $opt_test_count EOF } #Create threads (number depending on the variable ) for ($id=1; $id<=$opt_threads && !$exiting; $id++) { $thrd[$id] = threads->create("test_loop", $client_ip, $id, $opt_stress_mode, $tests_files{client}); print "main: Thread ID $id TID ",$thrd[$id]->tid," started\n"; select(undef, undef, undef, 0.5); } if ($opt_test_duration) { # OBN - At this point we need to wait for the duration of the test, hoever # we need to be able to quit if an 'abort-on-error' condition has happend # with one of the children (WL#4685). Using solution by ES and replacing # the 'sleep' command with a loop checking the abort condition every second foreach ( 1..$opt_test_duration ) { last if $exiting; sleep 1; } kill INT, $$; #Interrupt child threads } #Let other threads to process INT signal sleep(1); for ($id=1; $id<=$opt_threads;$id++) { if (defined($thrd[$id])) { $thrd[$id]->join(); } } print "EXIT\n"; } exit $gExitCode; # ES WL#4685: script should return a meaningful exit code sub test_init { my ($env)=@_; $env->{session_id}=$env->{ip}."_".$env->{thread_id}; $env->{r_folder}='r'.$env->{thread_id}; $env->{screen_logs}=File::Spec->catdir($opt_server_logs_dir, $test_dirname, "screen_logs", $env->{session_id}); $env->{reject_logs}=File::Spec->catdir($opt_server_logs_dir, $test_dirname, "reject_logs", $env->{session_id}); mkpath($env->{screen_logs}, 0, 0755) unless (-d $env->{screen_logs}); mkpath($env->{reject_logs}, 0, 0755) unless (-d $env->{reject_logs}); $env->{session_log}= File::Spec->catfile($env->{screen_logs}, $env->{session_id}.".log"); } sub test_execute { my $env= shift; my $test_name= shift; my $g_start= ""; my $g_end= ""; my $mysqltest_cmd= ""; my @mysqltest_test_args=(); my @stderr=(); #Get time stamp $g_start = get_timestamp(); $env->{errors}={}; @{$env->{test_status}}=(); my $test_file= $test_name.".test"; my $result_file= $test_name.".result"; my $reject_file = $test_name.'.reject'; my $output_file = $env->{session_id}.'_'.$test_name.'_'.$g_start."_".$env->{test_count}.'.txt'; my $test_filename = File::Spec->catfile($test_t_path, $test_file); my $result_filename = File::Spec->catdir($test_r_path, $env->{r_folder}, $result_file); my $reject_filename = File::Spec->catdir($test_r_path, $env->{r_folder}, $reject_file); my $output_filename = File::Spec->catfile($env->{screen_logs}, $output_file); push @mysqltest_test_args, "--basedir=$opt_stress_suite_basedir/", "--tmpdir=$opt_stress_basedir", "-x $test_filename", "-R $result_filename", "2>$output_filename"; $cmd= "$opt_mysqltest --no-defaults ".join(" ", @mysqltest_args)." ". join(" ", @mysqltest_test_args); system($cmd); $exit_value = $? >> 8; $signal_num = $? & 127; $dumped_core = $? & 128; my $tid= threads->self->tid; if (-s $output_filename > 0) { #Read stderr for further analysis open (STDERR_LOG, $output_filename) or warn "Can't open file $output_filename"; @stderr=<STDERR_LOG>; close(STDERR_LOG); if ($opt_verbose) { $session_debug_file="$opt_stress_basedir/error$tid.txt"; stress_log($session_debug_file, "Something wrong happened during execution of this command line:"); stress_log($session_debug_file, "MYSQLTEST CMD - $cmd"); stress_log($session_debug_file, "STDERR:".join("",@stderr)); stress_log($session_debug_file, "EXIT STATUS:\n1. EXIT: $exit_value \n". "2. SIGNAL: $signal_num\n". "3. CORE: $dumped_core\n"); } } #If something wrong trying to analyse stderr if ($exit_value || $signal_num) { if (@stderr) { foreach my $line (@stderr) { #FIXME: we should handle case when for one sub-string/code # we have several different error messages # Now for both codes/substrings we assume that # first found message will represent error #Check line for error codes if (($err_msg, $err_code)= $line=~/failed: ((\d+):.+?$)/) { if (!exists($error_codes{$err_code})) { # OBN Changing severity level to S4 from S3 as S3 now reserved # for the case where the error is unknown (for WL#4626/4685 $severity="S4"; $err_code=0; } else { $severity=$error_codes{$err_code}; } if (!exists($env->{errors}->{$severity}->{$err_code})) { $env->{errors}->{$severity}->{$err_code}=[0, $err_msg]; } $env->{errors}->{$severity}->{$err_code}->[0]++; $env->{errors}->{$severity}->{total}++; } #Check line for error patterns foreach $err_string (keys %error_strings) { $pattern= quotemeta $err_string; if ($line =~ /$pattern/i) { my $severity= $error_strings{$err_string}; if (!exists($env->{errors}->{$severity}->{$err_string})) { $env->{errors}->{$severity}->{$err_string}=[0, $line]; } $env->{errors}->{$severity}->{$err_string}->[0]++; $env->{errors}->{$severity}->{total}++; } } } } else { $env->{errors}->{S3}->{'Unknown error'}= [1,"Unknown error. Nothing was output to STDERR"]; $env->{errors}->{S3}->{total}=1; } } # #FIXME: Here we can perform further analysis of recognized # error codes # foreach my $severity (sort {$a cmp $b} keys %{$env->{errors}}) { my $total=$env->{errors}->{$severity}->{total}; if ($total) { push @{$env->{test_status}}, "Severity $severity: $total"; $env->{errors}->{total}=+$total; set_exit_code($severity); } } #FIXME: Should we take into account $exit_value here? # Now we assume that all stringified errors(i.e. errors without # error codes) which are not exist in %error_string structure # are OK if (!$env->{errors}->{total}) { push @{$env->{test_status}},"No Errors. Test Passed OK"; } log_session_errors($env, $test_file); #OBN Removing the case of S1 and abort-on-error as that is now set # inside the set_exit_code function (for WL#4626/4685) #if (!$exiting && ($signal_num == 2 || $signal_num == 15 || # ($opt_abort_on_error && $env->{errors}->{S1} > 0))) if (!$exiting && ($signal_num == 2 || $signal_num == 15)) { #mysqltest was interrupted with INT or TERM signals #so we assume that we should cancel testing and exit $exiting=1; # OBN - Adjusted text to exclude case of S1 and abort-on-error that # was mentioned (for WL#4626/4685) print STDERR<<EOF; WARNING: mysqltest was interrupted with INT or TERM signals so we assume that we should cancel testing and exit. Please check log file for this thread in $stress_log_file or inspect below output of the last test case executed with mysqltest to find out cause of error. Output of mysqltest: @stderr EOF } if (-e $reject_filename) { move_to_logs($env->{reject_logs}, $reject_filename, $reject_file); } if (-e $output_filename) { move_to_logs($env->{screen_logs}, $output_filename, $output_file); } } sub test_loop { my %client_env=(); my $test_name=""; # KEY for session identification: IP-THREAD_ID $client_env{ip} = shift; $client_env{thread_id} = shift; $client_env{mode} = shift; $client_env{tests_file}=shift; $client_env{test_seq_idx}=0; #Initialize session variables test_init(\%client_env); LOOP: while(!$exiting) { if ($opt_check_tests_file) { #Check if tests_file was modified and reread it in this case read_tests_names($client_env{tests_file}, 0); } { lock($test_counters_lock); if (($limits{loop_count} && $limits{loop_count} <= $test_counters{loop_count}*1) || ($limits{test_count} && $limits{test_count} <= $test_counters{test_count}*1) ) { $exiting=1; next LOOP; } } #Get random file name if (($test_name = get_test(\%client_env)) ne '') { { lock($test_counters_lock); #Save current counters values $client_env{loop_count}=$test_counters{loop_count}; $client_env{test_count}=$test_counters{test_count}; } #Run test and analyze results test_execute(\%client_env, $test_name); print "test_loop[".$limits{loop_count}.":". $limits{test_count}." ". $client_env{loop_count}.":". $client_env{test_count}."]:". " TID ".$client_env{thread_id}. " test: '$test_name' ". " Errors: ".join(" ",@{$client_env{test_status}}). ( $exiting ? " (thread aborting)" : "" )."\n"; } # OBN - At this point we need to wait until the 'wait' time between test # executions passes (in case it is specifed) passes, hoever we need # to be able to quit and break out of the test if an 'abort-on-error' # condition has happend with one of the other children (WL#4685). # Using solution by ES and replacing the 'sleep' command with a loop # checking the abort condition every second if ( $opt_sleep_time ) { foreach ( 1..$opt_sleep_time ) { last if $exiting; sleep 1; } } } } sub move_to_logs ($$$) { my $path_to_logs = shift; my $src_file = shift; my $random_filename = shift; my $dst_file = File::Spec->catfile($path_to_logs, $random_filename); move ($src_file, $dst_file) or warn<<EOF; ERROR: move_to_logs: File $src_file cannot be moved to $dst_file: $! EOF } sub copy_test_files () { if (/\.test$/) { $src_file = $File::Find::name; #print "## $File::Find::topdir - $File::Find::dir - $src_file\n"; if ($File::Find::topdir eq $File::Find::dir && $src_file !~ /SCCS/) { $test_filename = basename($src_file); $dst_file = File::Spec->catfile($test_t_path, $test_filename); copy($src_file, $dst_file) or die "ERROR: copy_test_files: File cannot be copied. $!"; } } } sub copy_result_files () { if (/\.result$/) { $src_file = $File::Find::name; if ($File::Find::topdir eq $File::Find::dir && $src_file !~ /SCCS/) { $result_filename = basename($src_file) ; $dst_file = File::Spec->catfile($r_folder, $result_filename); copy($src_file, $dst_file) or die "ERROR: copy_result_files: File cannot be copied. $!"; } } } sub get_timestamp { my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = localtime(); return sprintf("%04d%02d%02d%02d%02d%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec); } sub read_tests_names { my $tests_file = shift; my $force_load = shift; if ($force_load || ( (stat($tests_file->{filename}))[9] != $tests_file->{mtime}) ) { open (TEST, $tests_file->{filename}) || die ("Could not open file <". $tests_file->{filename}."> $!"); @{$tests_file->{data}}= grep {!/^[#\r\n]|^$/} map { s/[\r\n]//g; $_ } <TEST>; close (TEST); $tests_file->{mtime}=(stat(_))[9]; } } sub get_random_test { my $envt=shift; my $tests= $envt->{tests_file}->{data}; my $random = int(rand(@{$tests})); my $test = $tests->[$random]; return $test; } sub get_next_test { my $envt=shift; my $test; if (@{$envt->{tests_file}->{data}}) { $test=${$envt->{tests_file}->{data}}[$envt->{test_seq_idx}]; $envt->{test_seq_idx}++; } #If we reach bound of array, reset seq index and increment loop counter if ($envt->{test_seq_idx} == scalar(@{$envt->{tests_file}->{data}})) { $envt->{test_seq_idx}=0; { lock($test_counters_lock); $test_counters{loop_count}++; } } return $test; } sub get_test { my $envt=shift; { lock($test_counters_lock); $test_counters{test_count}++; } if ($envt->{mode} eq 'seq') { return get_next_test($envt); } elsif ($envt->{mode} eq 'random') { return get_random_test($envt); } } sub stress_log { my ($log_file, $line)=@_; { open(SLOG,">>$log_file") or warn "Error during opening log file $log_file"; print SLOG $line,"\n"; close(SLOG); } } sub log_session_errors { my ($env, $test_name) = @_; my $line=''; { lock ($log_file_lock); #header in the begining of log file if (!-e $stress_log_file) { stress_log($stress_log_file, "TestID TID Suite TestFileName Found Errors"); stress_log($stress_log_file, "======================================================="); } $line=sprintf('%6d %3d %10s %20s %s', $env->{test_count}, threads->self->tid, $opt_suite, $test_name, join(",", @{$env->{test_status}})); stress_log($stress_log_file, $line); #stress_log_with_lock($stress_log_file, "\n"); if ($opt_log_error_details) { foreach $severity (sort {$a cmp $b} keys %{$env->{errors}}) { stress_log($stress_log_file, ""); foreach $error (keys %{$env->{errors}->{$severity}}) { if ($error ne 'total') { stress_log($stress_log_file, "$severity: Count:". $env->{errors}->{$severity}->{$error}->[0]. " Error:". $env->{errors}->{$severity}->{$error}->[1]); } } } } } } sub sig_INT_handler { $SIG{INT}= \&sig_INT_handler; $exiting=1; print STDERR "$$: Got INT signal-------------------------------------------\n"; } sub sig_TERM_handler { $SIG{TERM}= \&sig_TERM_handler; $exiting=1; print STDERR "$$: Got TERM signal\n"; } sub usage { my $retcode= shift; print <<EOF; The MySQL Stress suite Ver $stress_suite_version mysql-stress-test.pl --stress-basedir=<dir> --stress-suite-basedir=<dir> --server-logs-dir=<dir> --server-host --server-port --server-socket --server-user --server-password --server-logs-dir Directory where all clients session logs will be stored. Usually this is shared directory associated with server that used in testing Required option. --stress-suite-basedir=<dir> Directory that has r/ t/ subfolders with test/result files which will be used for testing. Also by default we are looking in this directory for 'stress-tests.txt' file which contains list of tests. It is possible to specify other location of this file with --stress-tests-file option. Required option. --stress-basedir=<dir> Working directory for this test run. This directory will be used as temporary location for results tracking during testing Required option. --stress-datadir=<dir> Location of data files used which will be used in testing. By default we search for these files in <dir>/data where dir is value of --stress-suite-basedir option. --stress-init-file[=/path/to/file with tests for initialization of stress db] Using of this option allows to perform initialization of database by execution of test files. List of tests will be taken either from specified file or if it omited from default file 'stress-init.txt' located in <--stress-suite-basedir/--suite> dir --stress-tests-file[=/path/to/file with tests] Using of this option allows to run stress test itself. Tests for testing will be taken either from specified file or if it omited from default file 'stress-tests.txt' located in <--stress-suite-basedir/--suite> dir --stress-mode= [random|seq] There are two possible modes which affect order of selecting tests from the list: - in random mode tests will be selected in random order - in seq mode each thread will execute tests in the loop one by one as they specified in the list file. --sleep-time=<time in seconds> Delay between test execution. Could be usefull in continued testsing when one of instance of stress script perform periodical cleanup or recreating of some database objects --threads=#number of threads Define number of threads --check-tests-file Check file with list of tests. If file was modified it will force to reread list of tests. Could be usefull in continued testing for adding/removing tests without script interruption --mysqltest=/path/to/mysqltest binary --verbose --cleanup Force to clean up working directory (specified with --stress-basedir) --abort-on-error=<number> Causes the script to abort if an error with severity <= number was encounterd --log-error-details Enable errors details in the global error log file. (Default: off) --test-count=<number of executed tests before we have to exit> --loop-count=<number of executed loops in sequential mode before we have to exit> --test-duration=<number of seconds that stress test should run> Example of tool usage: perl mysql-stress-test.pl \ --stress-suite-basedir=/opt/qa/mysql-test-extra-5.0/mysql-test \ --stress-basedir=/opt/qa/test \ --server-logs-dir=/opt/qa/logs \ --test-count=20 \ --stress-tests-file=innodb-tests.txt \ --stress-init-file=innodb-init.txt \ --threads=5 \ --suite=funcs_1 \ --mysqltest=/opt/mysql/mysql-5.0/client/mysqltest \ --server-user=root \ --server-database=test \ --cleanup \ EOF exit($retcode); }
XeLabs/tokudb
mysql-test/mysql-stress-test.pl
Perl
gpl-2.0
37,263
/* Copyright (C) 2011-2013 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 2011. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <math.h> #include <math_private.h> static long double __attribute__ ((noinline)) sysv_scalbl (long double x, long double fn) { long double z = __ieee754_scalbl (x, fn); if (__builtin_expect (__isinfl (z), 0)) { if (__finitel (x)) return __kernel_standard_l (x, fn, 232); /* scalb overflow */ else __set_errno (ERANGE); } else if (__builtin_expect (z == 0.0L, 0) && z != x) return __kernel_standard_l (x, fn, 233); /* scalb underflow */ return z; } /* Wrapper scalbl */ long double __scalbl (long double x, long double fn) { return (__builtin_expect (_LIB_VERSION == _SVID_, 0) ? sysv_scalbl (x, fn) : __ieee754_scalbl (x, fn)); } weak_alias (__scalbl, scalbl)
SanDisk-Open-Source/SSD_Dashboard
uefi/userspace/glibc/math/w_scalbl.c
C
gpl-2.0
1,585
<?php /** * Development Tools Controller * * PHP Version 5 * * Copyright (C) Villanova University 2011. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind2 * @package Controller * @author Mark Triggs <[email protected]> * @author Chris Hallberg <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/alphabetical_heading_browse Wiki */ namespace VuFindDevTools\Controller; use Zend\I18n\Translator\TextDomain; /** * Development Tools Controller * * @category VuFind2 * @package Controller * @author Mark Triggs <[email protected]> * @author Chris Hallberg <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/alphabetical_heading_browse Wiki */ class DevtoolsController extends \VuFind\Controller\AbstractBase { /** * Get a list of help files in the specified language. * * @param string $language Language to check. * * @return array */ protected function getHelpFiles($language) { $dir = APPLICATION_PATH . '/themes/root/templates/HelpTranslations/' . $language; if (!file_exists($dir) || !is_dir($dir)) { return []; } $handle = opendir($dir); $files = []; while ($file = readdir($handle)) { if (substr($file, -6) == '.phtml') { $files[] = $file; } } closedir($handle); return $files; } /** * Get a list of languages supported by VuFind: * * @return array */ protected function getLanguages() { $langs = []; $dir = opendir(APPLICATION_PATH . '/languages'); while ($file = readdir($dir)) { if (substr($file, -4) == '.ini') { $lang = current(explode('.', $file)); if ('native' != $lang) { $langs[] = $lang; } } } closedir($dir); return $langs; } /** * Find strings that are absent from a language file. * * @param TextDomain $lang1 Left side of comparison * @param TextDomain $lang2 Right side of comparison * * @return array */ protected function findMissingLanguageStrings($lang1, $lang2) { // Find strings missing from language 2: return array_values( array_diff(array_keys((array)$lang1), array_keys((array)$lang2)) ); } /** * Compare two languages and return an array of details about how they differ. * * @param TextDomain $lang1 Left side of comparison * @param TextDomain $lang2 Right side of comparison * * @return array */ protected function compareLanguages($lang1, $lang2) { return [ 'notInL1' => $this->findMissingLanguageStrings($lang2, $lang1), 'notInL2' => $this->findMissingLanguageStrings($lang1, $lang2), 'l1Percent' => number_format(count($lang1) / count($lang2) * 100, 2), 'l2Percent' => number_format(count($lang2) / count($lang1) * 100, 2), ]; } /** * Get English name of language * * @param string $lang Language code * * @return string */ public function getLangName($lang) { $config = $this->getConfig(); if (isset($config->Languages->$lang)) { return $config->Languages->$lang; } switch($lang) { case 'en-gb': return 'British English'; case 'pt-br': return 'Brazilian Portuguese'; default: return $lang; } } /** * Language action * * @return array */ public function languageAction() { // Test languages with no local overrides and no fallback: $loader = new \VuFind\I18n\Translator\Loader\ExtendedIni( [APPLICATION_PATH . '/languages'] ); $mainLanguage = $this->params()->fromQuery('main', 'en'); $main = $loader->load($mainLanguage, null); $details = []; $allLangs = $this->getLanguages(); sort($allLangs); foreach ($allLangs as $langCode) { $lang = $loader->load($langCode, null); if (isset($lang['@parent_ini'])) { // don't count macros in comparison: unset($lang['@parent_ini']); } $details[$langCode] = $this->compareLanguages($main, $lang); $details[$langCode]['object'] = $lang; $details[$langCode]['name'] = $this->getLangName($langCode); $details[$langCode]['helpFiles'] = $this->getHelpFiles($langCode); } return [ 'details' => $details, 'mainCode' => $mainLanguage, 'mainName' => $this->getLangName($mainLanguage), 'main' => $main, ]; } }
ajturpei/NDL-VuFind2
module/VuFindDevTools/src/VuFindDevTools/Controller/DevtoolsController.php
PHP
gpl-2.0
5,680
/* * i386 helpers (without register variable usage) * * Copyright (c) 2003 Fabrice Bellard * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #include "cpu.h" #include "sysemu/kvm.h" #include "kvm_i386.h" #ifndef CONFIG_USER_ONLY #include "sysemu/sysemu.h" #include "monitor/monitor.h" #endif static void cpu_x86_version(CPUX86State *env, int *family, int *model) { int cpuver = env->cpuid_version; if (family == NULL || model == NULL) { return; } *family = (cpuver >> 8) & 0x0f; *model = ((cpuver >> 12) & 0xf0) + ((cpuver >> 4) & 0x0f); } /* Broadcast MCA signal for processor version 06H_EH and above */ int cpu_x86_support_mca_broadcast(CPUX86State *env) { int family = 0; int model = 0; cpu_x86_version(env, &family, &model); if ((family == 6 && model >= 14) || family > 6) { return 1; } return 0; } /***********************************************************/ /* x86 debug */ static const char *cc_op_str[CC_OP_NB] = { "DYNAMIC", "EFLAGS", "MULB", "MULW", "MULL", "MULQ", "ADDB", "ADDW", "ADDL", "ADDQ", "ADCB", "ADCW", "ADCL", "ADCQ", "SUBB", "SUBW", "SUBL", "SUBQ", "SBBB", "SBBW", "SBBL", "SBBQ", "LOGICB", "LOGICW", "LOGICL", "LOGICQ", "INCB", "INCW", "INCL", "INCQ", "DECB", "DECW", "DECL", "DECQ", "SHLB", "SHLW", "SHLL", "SHLQ", "SARB", "SARW", "SARL", "SARQ", "BMILGB", "BMILGW", "BMILGL", "BMILGQ", "ADCX", "ADOX", "ADCOX", "CLR", }; static void cpu_x86_dump_seg_cache(CPUX86State *env, FILE *f, fprintf_function cpu_fprintf, const char *name, struct SegmentCache *sc) { #ifdef TARGET_X86_64 if (env->hflags & HF_CS64_MASK) { cpu_fprintf(f, "%-3s=%04x %016" PRIx64 " %08x %08x", name, sc->selector, sc->base, sc->limit, sc->flags & 0x00ffff00); } else #endif { cpu_fprintf(f, "%-3s=%04x %08x %08x %08x", name, sc->selector, (uint32_t)sc->base, sc->limit, sc->flags & 0x00ffff00); } if (!(env->hflags & HF_PE_MASK) || !(sc->flags & DESC_P_MASK)) goto done; cpu_fprintf(f, " DPL=%d ", (sc->flags & DESC_DPL_MASK) >> DESC_DPL_SHIFT); if (sc->flags & DESC_S_MASK) { if (sc->flags & DESC_CS_MASK) { cpu_fprintf(f, (sc->flags & DESC_L_MASK) ? "CS64" : ((sc->flags & DESC_B_MASK) ? "CS32" : "CS16")); cpu_fprintf(f, " [%c%c", (sc->flags & DESC_C_MASK) ? 'C' : '-', (sc->flags & DESC_R_MASK) ? 'R' : '-'); } else { cpu_fprintf(f, (sc->flags & DESC_B_MASK || env->hflags & HF_LMA_MASK) ? "DS " : "DS16"); cpu_fprintf(f, " [%c%c", (sc->flags & DESC_E_MASK) ? 'E' : '-', (sc->flags & DESC_W_MASK) ? 'W' : '-'); } cpu_fprintf(f, "%c]", (sc->flags & DESC_A_MASK) ? 'A' : '-'); } else { static const char *sys_type_name[2][16] = { { /* 32 bit mode */ "Reserved", "TSS16-avl", "LDT", "TSS16-busy", "CallGate16", "TaskGate", "IntGate16", "TrapGate16", "Reserved", "TSS32-avl", "Reserved", "TSS32-busy", "CallGate32", "Reserved", "IntGate32", "TrapGate32" }, { /* 64 bit mode */ "<hiword>", "Reserved", "LDT", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "TSS64-avl", "Reserved", "TSS64-busy", "CallGate64", "Reserved", "IntGate64", "TrapGate64" } }; cpu_fprintf(f, "%s", sys_type_name[(env->hflags & HF_LMA_MASK) ? 1 : 0] [(sc->flags & DESC_TYPE_MASK) >> DESC_TYPE_SHIFT]); } done: cpu_fprintf(f, "\n"); } #define DUMP_CODE_BYTES_TOTAL 50 #define DUMP_CODE_BYTES_BACKWARD 20 void x86_cpu_dump_state(CPUState *cs, FILE *f, fprintf_function cpu_fprintf, int flags) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; int eflags, i, nb; char cc_op_name[32]; static const char *seg_name[6] = { "ES", "CS", "SS", "DS", "FS", "GS" }; eflags = cpu_compute_eflags(env); #ifdef TARGET_X86_64 if (env->hflags & HF_CS64_MASK) { cpu_fprintf(f, "RAX=%016" PRIx64 " RBX=%016" PRIx64 " RCX=%016" PRIx64 " RDX=%016" PRIx64 "\n" "RSI=%016" PRIx64 " RDI=%016" PRIx64 " RBP=%016" PRIx64 " RSP=%016" PRIx64 "\n" "R8 =%016" PRIx64 " R9 =%016" PRIx64 " R10=%016" PRIx64 " R11=%016" PRIx64 "\n" "R12=%016" PRIx64 " R13=%016" PRIx64 " R14=%016" PRIx64 " R15=%016" PRIx64 "\n" "RIP=%016" PRIx64 " RFL=%08x [%c%c%c%c%c%c%c] CPL=%d II=%d A20=%d SMM=%d HLT=%d\n", env->regs[R_EAX], env->regs[R_EBX], env->regs[R_ECX], env->regs[R_EDX], env->regs[R_ESI], env->regs[R_EDI], env->regs[R_EBP], env->regs[R_ESP], env->regs[8], env->regs[9], env->regs[10], env->regs[11], env->regs[12], env->regs[13], env->regs[14], env->regs[15], env->eip, eflags, eflags & DF_MASK ? 'D' : '-', eflags & CC_O ? 'O' : '-', eflags & CC_S ? 'S' : '-', eflags & CC_Z ? 'Z' : '-', eflags & CC_A ? 'A' : '-', eflags & CC_P ? 'P' : '-', eflags & CC_C ? 'C' : '-', env->hflags & HF_CPL_MASK, (env->hflags >> HF_INHIBIT_IRQ_SHIFT) & 1, (env->a20_mask >> 20) & 1, (env->hflags >> HF_SMM_SHIFT) & 1, cs->halted); } else #endif { cpu_fprintf(f, "EAX=%08x EBX=%08x ECX=%08x EDX=%08x\n" "ESI=%08x EDI=%08x EBP=%08x ESP=%08x\n" "EIP=%08x EFL=%08x [%c%c%c%c%c%c%c] CPL=%d II=%d A20=%d SMM=%d HLT=%d\n", (uint32_t)env->regs[R_EAX], (uint32_t)env->regs[R_EBX], (uint32_t)env->regs[R_ECX], (uint32_t)env->regs[R_EDX], (uint32_t)env->regs[R_ESI], (uint32_t)env->regs[R_EDI], (uint32_t)env->regs[R_EBP], (uint32_t)env->regs[R_ESP], (uint32_t)env->eip, eflags, eflags & DF_MASK ? 'D' : '-', eflags & CC_O ? 'O' : '-', eflags & CC_S ? 'S' : '-', eflags & CC_Z ? 'Z' : '-', eflags & CC_A ? 'A' : '-', eflags & CC_P ? 'P' : '-', eflags & CC_C ? 'C' : '-', env->hflags & HF_CPL_MASK, (env->hflags >> HF_INHIBIT_IRQ_SHIFT) & 1, (env->a20_mask >> 20) & 1, (env->hflags >> HF_SMM_SHIFT) & 1, cs->halted); } for(i = 0; i < 6; i++) { cpu_x86_dump_seg_cache(env, f, cpu_fprintf, seg_name[i], &env->segs[i]); } cpu_x86_dump_seg_cache(env, f, cpu_fprintf, "LDT", &env->ldt); cpu_x86_dump_seg_cache(env, f, cpu_fprintf, "TR", &env->tr); #ifdef TARGET_X86_64 if (env->hflags & HF_LMA_MASK) { cpu_fprintf(f, "GDT= %016" PRIx64 " %08x\n", env->gdt.base, env->gdt.limit); cpu_fprintf(f, "IDT= %016" PRIx64 " %08x\n", env->idt.base, env->idt.limit); cpu_fprintf(f, "CR0=%08x CR2=%016" PRIx64 " CR3=%016" PRIx64 " CR4=%08x\n", (uint32_t)env->cr[0], env->cr[2], env->cr[3], (uint32_t)env->cr[4]); for(i = 0; i < 4; i++) cpu_fprintf(f, "DR%d=%016" PRIx64 " ", i, env->dr[i]); cpu_fprintf(f, "\nDR6=%016" PRIx64 " DR7=%016" PRIx64 "\n", env->dr[6], env->dr[7]); } else #endif { cpu_fprintf(f, "GDT= %08x %08x\n", (uint32_t)env->gdt.base, env->gdt.limit); cpu_fprintf(f, "IDT= %08x %08x\n", (uint32_t)env->idt.base, env->idt.limit); cpu_fprintf(f, "CR0=%08x CR2=%08x CR3=%08x CR4=%08x\n", (uint32_t)env->cr[0], (uint32_t)env->cr[2], (uint32_t)env->cr[3], (uint32_t)env->cr[4]); for(i = 0; i < 4; i++) { cpu_fprintf(f, "DR%d=" TARGET_FMT_lx " ", i, env->dr[i]); } cpu_fprintf(f, "\nDR6=" TARGET_FMT_lx " DR7=" TARGET_FMT_lx "\n", env->dr[6], env->dr[7]); } if (flags & CPU_DUMP_CCOP) { if ((unsigned)env->cc_op < CC_OP_NB) snprintf(cc_op_name, sizeof(cc_op_name), "%s", cc_op_str[env->cc_op]); else snprintf(cc_op_name, sizeof(cc_op_name), "[%d]", env->cc_op); #ifdef TARGET_X86_64 if (env->hflags & HF_CS64_MASK) { cpu_fprintf(f, "CCS=%016" PRIx64 " CCD=%016" PRIx64 " CCO=%-8s\n", env->cc_src, env->cc_dst, cc_op_name); } else #endif { cpu_fprintf(f, "CCS=%08x CCD=%08x CCO=%-8s\n", (uint32_t)env->cc_src, (uint32_t)env->cc_dst, cc_op_name); } } cpu_fprintf(f, "EFER=%016" PRIx64 "\n", env->efer); if (flags & CPU_DUMP_FPU) { int fptag; fptag = 0; for(i = 0; i < 8; i++) { fptag |= ((!env->fptags[i]) << i); } cpu_fprintf(f, "FCW=%04x FSW=%04x [ST=%d] FTW=%02x MXCSR=%08x\n", env->fpuc, (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11, env->fpstt, fptag, env->mxcsr); for(i=0;i<8;i++) { CPU_LDoubleU u; u.d = env->fpregs[i].d; cpu_fprintf(f, "FPR%d=%016" PRIx64 " %04x", i, u.l.lower, u.l.upper); if ((i & 1) == 1) cpu_fprintf(f, "\n"); else cpu_fprintf(f, " "); } if (env->hflags & HF_CS64_MASK) nb = 16; else nb = 8; for(i=0;i<nb;i++) { cpu_fprintf(f, "XMM%02d=%08x%08x%08x%08x", i, env->xmm_regs[i].XMM_L(3), env->xmm_regs[i].XMM_L(2), env->xmm_regs[i].XMM_L(1), env->xmm_regs[i].XMM_L(0)); if ((i & 1) == 1) cpu_fprintf(f, "\n"); else cpu_fprintf(f, " "); } } if (flags & CPU_DUMP_CODE) { target_ulong base = env->segs[R_CS].base + env->eip; target_ulong offs = MIN(env->eip, DUMP_CODE_BYTES_BACKWARD); uint8_t code; char codestr[3]; cpu_fprintf(f, "Code="); for (i = 0; i < DUMP_CODE_BYTES_TOTAL; i++) { if (cpu_memory_rw_debug(cs, base - offs + i, &code, 1, 0) == 0) { snprintf(codestr, sizeof(codestr), "%02x", code); } else { snprintf(codestr, sizeof(codestr), "??"); } cpu_fprintf(f, "%s%s%s%s", i > 0 ? " " : "", i == offs ? "<" : "", codestr, i == offs ? ">" : ""); } cpu_fprintf(f, "\n"); } } /***********************************************************/ /* x86 mmu */ /* XXX: add PGE support */ void x86_cpu_set_a20(X86CPU *cpu, int a20_state) { CPUX86State *env = &cpu->env; a20_state = (a20_state != 0); if (a20_state != ((env->a20_mask >> 20) & 1)) { CPUState *cs = CPU(cpu); qemu_log_mask(CPU_LOG_MMU, "A20 update: a20=%d\n", a20_state); /* if the cpu is currently executing code, we must unlink it and all the potentially executing TB */ cpu_interrupt(cs, CPU_INTERRUPT_EXITTB); /* when a20 is changed, all the MMU mappings are invalid, so we must flush everything */ tlb_flush(cs, 1); env->a20_mask = ~(1 << 20) | (a20_state << 20); } } void cpu_x86_update_cr0(CPUX86State *env, uint32_t new_cr0) { X86CPU *cpu = x86_env_get_cpu(env); int pe_state; qemu_log_mask(CPU_LOG_MMU, "CR0 update: CR0=0x%08x\n", new_cr0); if ((new_cr0 & (CR0_PG_MASK | CR0_WP_MASK | CR0_PE_MASK)) != (env->cr[0] & (CR0_PG_MASK | CR0_WP_MASK | CR0_PE_MASK))) { tlb_flush(CPU(cpu), 1); } #ifdef TARGET_X86_64 if (!(env->cr[0] & CR0_PG_MASK) && (new_cr0 & CR0_PG_MASK) && (env->efer & MSR_EFER_LME)) { /* enter in long mode */ /* XXX: generate an exception */ if (!(env->cr[4] & CR4_PAE_MASK)) return; env->efer |= MSR_EFER_LMA; env->hflags |= HF_LMA_MASK; } else if ((env->cr[0] & CR0_PG_MASK) && !(new_cr0 & CR0_PG_MASK) && (env->efer & MSR_EFER_LMA)) { /* exit long mode */ env->efer &= ~MSR_EFER_LMA; env->hflags &= ~(HF_LMA_MASK | HF_CS64_MASK); env->eip &= 0xffffffff; } #endif env->cr[0] = new_cr0 | CR0_ET_MASK; /* update PE flag in hidden flags */ pe_state = (env->cr[0] & CR0_PE_MASK); env->hflags = (env->hflags & ~HF_PE_MASK) | (pe_state << HF_PE_SHIFT); /* ensure that ADDSEG is always set in real mode */ env->hflags |= ((pe_state ^ 1) << HF_ADDSEG_SHIFT); /* update FPU flags */ env->hflags = (env->hflags & ~(HF_MP_MASK | HF_EM_MASK | HF_TS_MASK)) | ((new_cr0 << (HF_MP_SHIFT - 1)) & (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK)); } /* XXX: in legacy PAE mode, generate a GPF if reserved bits are set in the PDPT */ void cpu_x86_update_cr3(CPUX86State *env, target_ulong new_cr3) { X86CPU *cpu = x86_env_get_cpu(env); env->cr[3] = new_cr3; if (env->cr[0] & CR0_PG_MASK) { qemu_log_mask(CPU_LOG_MMU, "CR3 update: CR3=" TARGET_FMT_lx "\n", new_cr3); tlb_flush(CPU(cpu), 0); } } void cpu_x86_update_cr4(CPUX86State *env, uint32_t new_cr4) { X86CPU *cpu = x86_env_get_cpu(env); #if defined(DEBUG_MMU) printf("CR4 update: CR4=%08x\n", (uint32_t)env->cr[4]); #endif if ((new_cr4 ^ env->cr[4]) & (CR4_PGE_MASK | CR4_PAE_MASK | CR4_PSE_MASK | CR4_SMEP_MASK | CR4_SMAP_MASK)) { tlb_flush(CPU(cpu), 1); } /* SSE handling */ if (!(env->features[FEAT_1_EDX] & CPUID_SSE)) { new_cr4 &= ~CR4_OSFXSR_MASK; } env->hflags &= ~HF_OSFXSR_MASK; if (new_cr4 & CR4_OSFXSR_MASK) { env->hflags |= HF_OSFXSR_MASK; } if (!(env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_SMAP)) { new_cr4 &= ~CR4_SMAP_MASK; } env->hflags &= ~HF_SMAP_MASK; if (new_cr4 & CR4_SMAP_MASK) { env->hflags |= HF_SMAP_MASK; } env->cr[4] = new_cr4; } #if defined(CONFIG_USER_ONLY) int x86_cpu_handle_mmu_fault(CPUState *cs, vaddr addr, int is_write, int mmu_idx) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; /* user mode only emulation */ is_write &= 1; env->cr[2] = addr; env->error_code = (is_write << PG_ERROR_W_BIT); env->error_code |= PG_ERROR_U_MASK; cs->exception_index = EXCP0E_PAGE; return 1; } #else /* return value: * -1 = cannot handle fault * 0 = nothing more to do * 1 = generate PF fault */ int x86_cpu_handle_mmu_fault(CPUState *cs, vaddr addr, int is_write1, int mmu_idx) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; uint64_t ptep, pte; target_ulong pde_addr, pte_addr; int error_code = 0; int is_dirty, prot, page_size, is_write, is_user; hwaddr paddr; uint64_t rsvd_mask = PG_HI_RSVD_MASK; uint32_t page_offset; target_ulong vaddr; is_user = mmu_idx == MMU_USER_IDX; #if defined(DEBUG_MMU) printf("MMU fault: addr=%" VADDR_PRIx " w=%d u=%d eip=" TARGET_FMT_lx "\n", addr, is_write1, is_user, env->eip); #endif is_write = is_write1 & 1; if (!(env->cr[0] & CR0_PG_MASK)) { pte = addr; #ifdef TARGET_X86_64 if (!(env->hflags & HF_LMA_MASK)) { /* Without long mode we can only address 32bits in real mode */ pte = (uint32_t)pte; } #endif prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC; page_size = 4096; goto do_mapping; } if (!(env->efer & MSR_EFER_NXE)) { rsvd_mask |= PG_NX_MASK; } if (env->cr[4] & CR4_PAE_MASK) { uint64_t pde, pdpe; target_ulong pdpe_addr; #ifdef TARGET_X86_64 if (env->hflags & HF_LMA_MASK) { uint64_t pml4e_addr, pml4e; int32_t sext; /* test virtual address sign extension */ sext = (int64_t)addr >> 47; if (sext != 0 && sext != -1) { env->error_code = 0; cs->exception_index = EXCP0D_GPF; return 1; } pml4e_addr = ((env->cr[3] & ~0xfff) + (((addr >> 39) & 0x1ff) << 3)) & env->a20_mask; pml4e = x86_ldq_phys(cs, pml4e_addr); if (!(pml4e & PG_PRESENT_MASK)) { goto do_fault; } if (pml4e & (rsvd_mask | PG_PSE_MASK)) { goto do_fault_rsvd; } if (!(pml4e & PG_ACCESSED_MASK)) { pml4e |= PG_ACCESSED_MASK; x86_stl_phys_notdirty(cs, pml4e_addr, pml4e); } ptep = pml4e ^ PG_NX_MASK; pdpe_addr = ((pml4e & PG_ADDRESS_MASK) + (((addr >> 30) & 0x1ff) << 3)) & env->a20_mask; pdpe = x86_ldq_phys(cs, pdpe_addr); if (!(pdpe & PG_PRESENT_MASK)) { goto do_fault; } if (pdpe & rsvd_mask) { goto do_fault_rsvd; } ptep &= pdpe ^ PG_NX_MASK; if (!(pdpe & PG_ACCESSED_MASK)) { pdpe |= PG_ACCESSED_MASK; x86_stl_phys_notdirty(cs, pdpe_addr, pdpe); } if (pdpe & PG_PSE_MASK) { /* 1 GB page */ page_size = 1024 * 1024 * 1024; pte_addr = pdpe_addr; pte = pdpe; goto do_check_protect; } } else #endif { /* XXX: load them when cr3 is loaded ? */ pdpe_addr = ((env->cr[3] & ~0x1f) + ((addr >> 27) & 0x18)) & env->a20_mask; pdpe = x86_ldq_phys(cs, pdpe_addr); if (!(pdpe & PG_PRESENT_MASK)) { goto do_fault; } rsvd_mask |= PG_HI_USER_MASK; if (pdpe & (rsvd_mask | PG_NX_MASK)) { goto do_fault_rsvd; } ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK; } pde_addr = ((pdpe & PG_ADDRESS_MASK) + (((addr >> 21) & 0x1ff) << 3)) & env->a20_mask; pde = x86_ldq_phys(cs, pde_addr); if (!(pde & PG_PRESENT_MASK)) { goto do_fault; } if (pde & rsvd_mask) { goto do_fault_rsvd; } ptep &= pde ^ PG_NX_MASK; if (pde & PG_PSE_MASK) { /* 2 MB page */ page_size = 2048 * 1024; pte_addr = pde_addr; pte = pde; goto do_check_protect; } /* 4 KB page */ if (!(pde & PG_ACCESSED_MASK)) { pde |= PG_ACCESSED_MASK; x86_stl_phys_notdirty(cs, pde_addr, pde); } pte_addr = ((pde & PG_ADDRESS_MASK) + (((addr >> 12) & 0x1ff) << 3)) & env->a20_mask; pte = x86_ldq_phys(cs, pte_addr); if (!(pte & PG_PRESENT_MASK)) { goto do_fault; } if (pte & rsvd_mask) { goto do_fault_rsvd; } /* combine pde and pte nx, user and rw protections */ ptep &= pte ^ PG_NX_MASK; page_size = 4096; } else { uint32_t pde; /* page directory entry */ pde_addr = ((env->cr[3] & ~0xfff) + ((addr >> 20) & 0xffc)) & env->a20_mask; pde = x86_ldl_phys(cs, pde_addr); if (!(pde & PG_PRESENT_MASK)) { goto do_fault; } ptep = pde | PG_NX_MASK; /* if PSE bit is set, then we use a 4MB page */ if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) { page_size = 4096 * 1024; pte_addr = pde_addr; /* Bits 20-13 provide bits 39-32 of the address, bit 21 is reserved. * Leave bits 20-13 in place for setting accessed/dirty bits below. */ pte = pde | ((pde & 0x1fe000) << (32 - 13)); rsvd_mask = 0x200000; goto do_check_protect_pse36; } if (!(pde & PG_ACCESSED_MASK)) { pde |= PG_ACCESSED_MASK; x86_stl_phys_notdirty(cs, pde_addr, pde); } /* page directory entry */ pte_addr = ((pde & ~0xfff) + ((addr >> 10) & 0xffc)) & env->a20_mask; pte = x86_ldl_phys(cs, pte_addr); if (!(pte & PG_PRESENT_MASK)) { goto do_fault; } /* combine pde and pte user and rw protections */ ptep &= pte | PG_NX_MASK; page_size = 4096; rsvd_mask = 0; } do_check_protect: rsvd_mask |= (page_size - 1) & PG_ADDRESS_MASK & ~PG_PSE_PAT_MASK; do_check_protect_pse36: if (pte & rsvd_mask) { goto do_fault_rsvd; } ptep ^= PG_NX_MASK; if ((ptep & PG_NX_MASK) && is_write1 == 2) { goto do_fault_protect; } switch (mmu_idx) { case MMU_USER_IDX: if (!(ptep & PG_USER_MASK)) { goto do_fault_protect; } if (is_write && !(ptep & PG_RW_MASK)) { goto do_fault_protect; } break; case MMU_KSMAP_IDX: if (is_write1 != 2 && (ptep & PG_USER_MASK)) { goto do_fault_protect; } /* fall through */ case MMU_KNOSMAP_IDX: if (is_write1 == 2 && (env->cr[4] & CR4_SMEP_MASK) && (ptep & PG_USER_MASK)) { goto do_fault_protect; } if ((env->cr[0] & CR0_WP_MASK) && is_write && !(ptep & PG_RW_MASK)) { goto do_fault_protect; } break; default: /* cannot happen */ break; } is_dirty = is_write && !(pte & PG_DIRTY_MASK); if (!(pte & PG_ACCESSED_MASK) || is_dirty) { pte |= PG_ACCESSED_MASK; if (is_dirty) { pte |= PG_DIRTY_MASK; } x86_stl_phys_notdirty(cs, pte_addr, pte); } /* the page can be put in the TLB */ prot = PAGE_READ; if (!(ptep & PG_NX_MASK) && (mmu_idx == MMU_USER_IDX || !((env->cr[4] & CR4_SMEP_MASK) && (ptep & PG_USER_MASK)))) { prot |= PAGE_EXEC; } if (pte & PG_DIRTY_MASK) { /* only set write access if already dirty... otherwise wait for dirty access */ if (is_user) { if (ptep & PG_RW_MASK) prot |= PAGE_WRITE; } else { if (!(env->cr[0] & CR0_WP_MASK) || (ptep & PG_RW_MASK)) prot |= PAGE_WRITE; } } do_mapping: pte = pte & env->a20_mask; /* align to page_size */ pte &= PG_ADDRESS_MASK & ~(page_size - 1); /* Even if 4MB pages, we map only one 4KB page in the cache to avoid filling it too fast */ vaddr = addr & TARGET_PAGE_MASK; page_offset = vaddr & (page_size - 1); paddr = pte + page_offset; tlb_set_page_with_attrs(cs, vaddr, paddr, cpu_get_mem_attrs(env), prot, mmu_idx, page_size); return 0; do_fault_rsvd: error_code |= PG_ERROR_RSVD_MASK; do_fault_protect: error_code |= PG_ERROR_P_MASK; do_fault: error_code |= (is_write << PG_ERROR_W_BIT); if (is_user) error_code |= PG_ERROR_U_MASK; if (is_write1 == 2 && (((env->efer & MSR_EFER_NXE) && (env->cr[4] & CR4_PAE_MASK)) || (env->cr[4] & CR4_SMEP_MASK))) error_code |= PG_ERROR_I_D_MASK; if (env->intercept_exceptions & (1 << EXCP0E_PAGE)) { /* cr2 is not modified in case of exceptions */ x86_stq_phys(cs, env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), addr); } else { env->cr[2] = addr; } env->error_code = error_code; cs->exception_index = EXCP0E_PAGE; return 1; } hwaddr x86_cpu_get_phys_page_debug(CPUState *cs, vaddr addr) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; target_ulong pde_addr, pte_addr; uint64_t pte; uint32_t page_offset; int page_size; if (!(env->cr[0] & CR0_PG_MASK)) { pte = addr & env->a20_mask; page_size = 4096; } else if (env->cr[4] & CR4_PAE_MASK) { target_ulong pdpe_addr; uint64_t pde, pdpe; #ifdef TARGET_X86_64 if (env->hflags & HF_LMA_MASK) { uint64_t pml4e_addr, pml4e; int32_t sext; /* test virtual address sign extension */ sext = (int64_t)addr >> 47; if (sext != 0 && sext != -1) { return -1; } pml4e_addr = ((env->cr[3] & ~0xfff) + (((addr >> 39) & 0x1ff) << 3)) & env->a20_mask; pml4e = x86_ldq_phys(cs, pml4e_addr); if (!(pml4e & PG_PRESENT_MASK)) { return -1; } pdpe_addr = ((pml4e & PG_ADDRESS_MASK) + (((addr >> 30) & 0x1ff) << 3)) & env->a20_mask; pdpe = x86_ldq_phys(cs, pdpe_addr); if (!(pdpe & PG_PRESENT_MASK)) { return -1; } if (pdpe & PG_PSE_MASK) { page_size = 1024 * 1024 * 1024; pte = pdpe; goto out; } } else #endif { pdpe_addr = ((env->cr[3] & ~0x1f) + ((addr >> 27) & 0x18)) & env->a20_mask; pdpe = x86_ldq_phys(cs, pdpe_addr); if (!(pdpe & PG_PRESENT_MASK)) return -1; } pde_addr = ((pdpe & PG_ADDRESS_MASK) + (((addr >> 21) & 0x1ff) << 3)) & env->a20_mask; pde = x86_ldq_phys(cs, pde_addr); if (!(pde & PG_PRESENT_MASK)) { return -1; } if (pde & PG_PSE_MASK) { /* 2 MB page */ page_size = 2048 * 1024; pte = pde; } else { /* 4 KB page */ pte_addr = ((pde & PG_ADDRESS_MASK) + (((addr >> 12) & 0x1ff) << 3)) & env->a20_mask; page_size = 4096; pte = x86_ldq_phys(cs, pte_addr); } if (!(pte & PG_PRESENT_MASK)) { return -1; } } else { uint32_t pde; /* page directory entry */ pde_addr = ((env->cr[3] & ~0xfff) + ((addr >> 20) & 0xffc)) & env->a20_mask; pde = x86_ldl_phys(cs, pde_addr); if (!(pde & PG_PRESENT_MASK)) return -1; if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) { pte = pde | ((pde & 0x1fe000) << (32 - 13)); page_size = 4096 * 1024; } else { /* page directory entry */ pte_addr = ((pde & ~0xfff) + ((addr >> 10) & 0xffc)) & env->a20_mask; pte = x86_ldl_phys(cs, pte_addr); if (!(pte & PG_PRESENT_MASK)) { return -1; } page_size = 4096; } pte = pte & env->a20_mask; } #ifdef TARGET_X86_64 out: #endif pte &= PG_ADDRESS_MASK & ~(page_size - 1); page_offset = (addr & TARGET_PAGE_MASK) & (page_size - 1); return pte | page_offset; } void hw_breakpoint_insert(CPUX86State *env, int index) { CPUState *cs = CPU(x86_env_get_cpu(env)); int type = 0, err = 0; switch (hw_breakpoint_type(env->dr[7], index)) { case DR7_TYPE_BP_INST: if (hw_breakpoint_enabled(env->dr[7], index)) { err = cpu_breakpoint_insert(cs, env->dr[index], BP_CPU, &env->cpu_breakpoint[index]); } break; case DR7_TYPE_DATA_WR: type = BP_CPU | BP_MEM_WRITE; break; case DR7_TYPE_IO_RW: /* No support for I/O watchpoints yet */ break; case DR7_TYPE_DATA_RW: type = BP_CPU | BP_MEM_ACCESS; break; } if (type != 0) { err = cpu_watchpoint_insert(cs, env->dr[index], hw_breakpoint_len(env->dr[7], index), type, &env->cpu_watchpoint[index]); } if (err) { env->cpu_breakpoint[index] = NULL; } } void hw_breakpoint_remove(CPUX86State *env, int index) { CPUState *cs; if (!env->cpu_breakpoint[index]) { return; } cs = CPU(x86_env_get_cpu(env)); switch (hw_breakpoint_type(env->dr[7], index)) { case DR7_TYPE_BP_INST: if (hw_breakpoint_enabled(env->dr[7], index)) { cpu_breakpoint_remove_by_ref(cs, env->cpu_breakpoint[index]); } break; case DR7_TYPE_DATA_WR: case DR7_TYPE_DATA_RW: cpu_watchpoint_remove_by_ref(cs, env->cpu_watchpoint[index]); break; case DR7_TYPE_IO_RW: /* No support for I/O watchpoints yet */ break; } } bool check_hw_breakpoints(CPUX86State *env, bool force_dr6_update) { target_ulong dr6; int reg; bool hit_enabled = false; dr6 = env->dr[6] & ~0xf; for (reg = 0; reg < DR7_MAX_BP; reg++) { bool bp_match = false; bool wp_match = false; switch (hw_breakpoint_type(env->dr[7], reg)) { case DR7_TYPE_BP_INST: if (env->dr[reg] == env->eip) { bp_match = true; } break; case DR7_TYPE_DATA_WR: case DR7_TYPE_DATA_RW: if (env->cpu_watchpoint[reg] && env->cpu_watchpoint[reg]->flags & BP_WATCHPOINT_HIT) { wp_match = true; } break; case DR7_TYPE_IO_RW: break; } if (bp_match || wp_match) { dr6 |= 1 << reg; if (hw_breakpoint_enabled(env->dr[7], reg)) { hit_enabled = true; } } } if (hit_enabled || force_dr6_update) { env->dr[6] = dr6; } return hit_enabled; } void breakpoint_handler(CPUState *cs) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; CPUBreakpoint *bp; if (cs->watchpoint_hit) { if (cs->watchpoint_hit->flags & BP_CPU) { cs->watchpoint_hit = NULL; if (check_hw_breakpoints(env, false)) { raise_exception(env, EXCP01_DB); } else { cpu_resume_from_signal(cs, NULL); } } } else { QTAILQ_FOREACH(bp, &cs->breakpoints, entry) { if (bp->pc == env->eip) { if (bp->flags & BP_CPU) { check_hw_breakpoints(env, true); raise_exception(env, EXCP01_DB); } break; } } } } typedef struct MCEInjectionParams { Monitor *mon; X86CPU *cpu; int bank; uint64_t status; uint64_t mcg_status; uint64_t addr; uint64_t misc; int flags; } MCEInjectionParams; static void do_inject_x86_mce(void *data) { MCEInjectionParams *params = data; CPUX86State *cenv = &params->cpu->env; CPUState *cpu = CPU(params->cpu); uint64_t *banks = cenv->mce_banks + 4 * params->bank; cpu_synchronize_state(cpu); /* * If there is an MCE exception being processed, ignore this SRAO MCE * unless unconditional injection was requested. */ if (!(params->flags & MCE_INJECT_UNCOND_AO) && !(params->status & MCI_STATUS_AR) && (cenv->mcg_status & MCG_STATUS_MCIP)) { return; } if (params->status & MCI_STATUS_UC) { /* * if MSR_MCG_CTL is not all 1s, the uncorrected error * reporting is disabled */ if ((cenv->mcg_cap & MCG_CTL_P) && cenv->mcg_ctl != ~(uint64_t)0) { monitor_printf(params->mon, "CPU %d: Uncorrected error reporting disabled\n", cpu->cpu_index); return; } /* * if MSR_MCi_CTL is not all 1s, the uncorrected error * reporting is disabled for the bank */ if (banks[0] != ~(uint64_t)0) { monitor_printf(params->mon, "CPU %d: Uncorrected error reporting disabled for" " bank %d\n", cpu->cpu_index, params->bank); return; } if ((cenv->mcg_status & MCG_STATUS_MCIP) || !(cenv->cr[4] & CR4_MCE_MASK)) { monitor_printf(params->mon, "CPU %d: Previous MCE still in progress, raising" " triple fault\n", cpu->cpu_index); qemu_log_mask(CPU_LOG_RESET, "Triple fault\n"); qemu_system_reset_request(); return; } if (banks[1] & MCI_STATUS_VAL) { params->status |= MCI_STATUS_OVER; } banks[2] = params->addr; banks[3] = params->misc; cenv->mcg_status = params->mcg_status; banks[1] = params->status; cpu_interrupt(cpu, CPU_INTERRUPT_MCE); } else if (!(banks[1] & MCI_STATUS_VAL) || !(banks[1] & MCI_STATUS_UC)) { if (banks[1] & MCI_STATUS_VAL) { params->status |= MCI_STATUS_OVER; } banks[2] = params->addr; banks[3] = params->misc; banks[1] = params->status; } else { banks[1] |= MCI_STATUS_OVER; } } void cpu_x86_inject_mce(Monitor *mon, X86CPU *cpu, int bank, uint64_t status, uint64_t mcg_status, uint64_t addr, uint64_t misc, int flags) { CPUState *cs = CPU(cpu); CPUX86State *cenv = &cpu->env; MCEInjectionParams params = { .mon = mon, .cpu = cpu, .bank = bank, .status = status, .mcg_status = mcg_status, .addr = addr, .misc = misc, .flags = flags, }; unsigned bank_num = cenv->mcg_cap & 0xff; if (!cenv->mcg_cap) { monitor_printf(mon, "MCE injection not supported\n"); return; } if (bank >= bank_num) { monitor_printf(mon, "Invalid MCE bank number\n"); return; } if (!(status & MCI_STATUS_VAL)) { monitor_printf(mon, "Invalid MCE status code\n"); return; } if ((flags & MCE_INJECT_BROADCAST) && !cpu_x86_support_mca_broadcast(cenv)) { monitor_printf(mon, "Guest CPU does not support MCA broadcast\n"); return; } run_on_cpu(cs, do_inject_x86_mce, &params); if (flags & MCE_INJECT_BROADCAST) { CPUState *other_cs; params.bank = 1; params.status = MCI_STATUS_VAL | MCI_STATUS_UC; params.mcg_status = MCG_STATUS_MCIP | MCG_STATUS_RIPV; params.addr = 0; params.misc = 0; CPU_FOREACH(other_cs) { if (other_cs == cs) { continue; } params.cpu = X86_CPU(other_cs); run_on_cpu(other_cs, do_inject_x86_mce, &params); } } } void cpu_report_tpr_access(CPUX86State *env, TPRAccess access) { X86CPU *cpu = x86_env_get_cpu(env); CPUState *cs = CPU(cpu); if (kvm_enabled()) { env->tpr_access_type = access; cpu_interrupt(cs, CPU_INTERRUPT_TPR); } else { cpu_restore_state(cs, cs->mem_io_pc); apic_handle_tpr_access_report(cpu->apic_state, env->eip, access); } } #endif /* !CONFIG_USER_ONLY */ int cpu_x86_get_descr_debug(CPUX86State *env, unsigned int selector, target_ulong *base, unsigned int *limit, unsigned int *flags) { X86CPU *cpu = x86_env_get_cpu(env); CPUState *cs = CPU(cpu); SegmentCache *dt; target_ulong ptr; uint32_t e1, e2; int index; if (selector & 0x4) dt = &env->ldt; else dt = &env->gdt; index = selector & ~7; ptr = dt->base + index; if ((index + 7) > dt->limit || cpu_memory_rw_debug(cs, ptr, (uint8_t *)&e1, sizeof(e1), 0) != 0 || cpu_memory_rw_debug(cs, ptr+4, (uint8_t *)&e2, sizeof(e2), 0) != 0) return 0; *base = ((e1 >> 16) | ((e2 & 0xff) << 16) | (e2 & 0xff000000)); *limit = (e1 & 0xffff) | (e2 & 0x000f0000); if (e2 & DESC_G_MASK) *limit = (*limit << 12) | 0xfff; *flags = e2; return 1; } #if !defined(CONFIG_USER_ONLY) void do_cpu_init(X86CPU *cpu) { CPUState *cs = CPU(cpu); CPUX86State *env = &cpu->env; CPUX86State *save = g_new(CPUX86State, 1); int sipi = cs->interrupt_request & CPU_INTERRUPT_SIPI; *save = *env; cpu_reset(cs); cs->interrupt_request = sipi; memcpy(&env->start_init_save, &save->start_init_save, offsetof(CPUX86State, end_init_save) - offsetof(CPUX86State, start_init_save)); g_free(save); if (kvm_enabled()) { kvm_arch_do_init_vcpu(cpu); } apic_init_reset(cpu->apic_state); } void do_cpu_sipi(X86CPU *cpu) { apic_sipi(cpu->apic_state); } #else void do_cpu_init(X86CPU *cpu) { } void do_cpu_sipi(X86CPU *cpu) { } #endif /* Frob eflags into and out of the CPU temporary format. */ void x86_cpu_exec_enter(CPUState *cs) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; CC_SRC = env->eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C); env->df = 1 - (2 * ((env->eflags >> 10) & 1)); CC_OP = CC_OP_EFLAGS; env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C); } void x86_cpu_exec_exit(CPUState *cs) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; env->eflags = cpu_compute_eflags(env); } #ifndef CONFIG_USER_ONLY uint8_t x86_ldub_phys(CPUState *cs, hwaddr addr) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; return address_space_ldub(cs->as, addr, cpu_get_mem_attrs(env), NULL); } uint32_t x86_lduw_phys(CPUState *cs, hwaddr addr) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; return address_space_lduw(cs->as, addr, cpu_get_mem_attrs(env), NULL); } uint32_t x86_ldl_phys(CPUState *cs, hwaddr addr) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; return address_space_ldl(cs->as, addr, cpu_get_mem_attrs(env), NULL); } uint64_t x86_ldq_phys(CPUState *cs, hwaddr addr) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; return address_space_ldq(cs->as, addr, cpu_get_mem_attrs(env), NULL); } void x86_stb_phys(CPUState *cs, hwaddr addr, uint8_t val) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; address_space_stb(cs->as, addr, val, cpu_get_mem_attrs(env), NULL); } void x86_stl_phys_notdirty(CPUState *cs, hwaddr addr, uint32_t val) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; address_space_stl_notdirty(cs->as, addr, val, cpu_get_mem_attrs(env), NULL); } void x86_stw_phys(CPUState *cs, hwaddr addr, uint32_t val) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; address_space_stw(cs->as, addr, val, cpu_get_mem_attrs(env), NULL); } void x86_stl_phys(CPUState *cs, hwaddr addr, uint32_t val) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; address_space_stl(cs->as, addr, val, cpu_get_mem_attrs(env), NULL); } void x86_stq_phys(CPUState *cs, hwaddr addr, uint64_t val) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; address_space_stq(cs->as, addr, val, cpu_get_mem_attrs(env), NULL); } #endif
hinesmr/qemu
target-i386/helper.c
C
gpl-2.0
41,726
// { dg-do compile { target c++20 } } template<class T, class U> concept Same = __is_same_as(T, U); template<typename T> concept C1 = true; template<typename T, typename U> concept C2 = true; C1 auto c1 = 0; C2<int> auto c2 = 0; Same<int> auto s1 = 'a'; // { dg-error "does not satisfy|is_same" }
Gurgel100/gcc
gcc/testsuite/g++.dg/cpp2a/concepts-placeholder1.C
C++
gpl-2.0
310
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 1996, 1997, 1998, 1999, 2000 * Sleepycat Software. All rights reserved. */ /* * Copyright (c) 1996 * The President and Fellows of Harvard University. All rights reserved. * * 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 of the University 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 REGENTS 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 REGENTS 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. */ #include "db_config.h" #ifndef lint static const char revid[] = "$Id: txn_rec.c,v 11.15 2001/01/11 18:19:55 bostic Exp $"; #endif /* not lint */ #ifndef NO_SYSTEM_INCLUDES #include <sys/types.h> #endif #include "db_int.h" #include "db_page.h" #include "txn.h" #include "db_am.h" #include "db_dispatch.h" #include "log.h" #include "common_ext.h" static int __txn_restore_txn __P((DB_ENV *, DB_LSN *, __txn_xa_regop_args *)); #define IS_XA_TXN(R) (R->xid.size != 0) /* * PUBLIC: int __txn_regop_recover * PUBLIC: __P((DB_ENV *, DBT *, DB_LSN *, db_recops, void *)); * * These records are only ever written for commits. Normally, we redo any * committed transaction, however if we are doing recovery to a timestamp, then * we may treat transactions that commited after the timestamp as aborted. */ int __txn_regop_recover(dbenv, dbtp, lsnp, op, info) DB_ENV *dbenv; DBT *dbtp; DB_LSN *lsnp; db_recops op; void *info; { __txn_regop_args *argp; int ret; #ifdef DEBUG_RECOVER (void)__txn_regop_print(dbenv, dbtp, lsnp, op, info); #endif if ((ret = __txn_regop_read(dbenv, dbtp->data, &argp)) != 0) return (ret); if (argp->opcode != TXN_COMMIT) { ret = EINVAL; goto err; } if (op == DB_TXN_FORWARD_ROLL) ret = __db_txnlist_remove(info, argp->txnid->txnid); else if (dbenv->tx_timestamp == 0 || argp->timestamp <= (int32_t)dbenv->tx_timestamp) /* * We know this is the backward roll case because we * are never called during ABORT or OPENFILES. */ ret = __db_txnlist_add(dbenv, info, argp->txnid->txnid, 0); else /* * This is commit record, but we failed the timestamp check * so we should treat it as an abort and add it to the list * as an aborted record. */ ret = __db_txnlist_add(dbenv, info, argp->txnid->txnid, 1); if (ret == 0) *lsnp = argp->prev_lsn; err: __os_free(argp, 0); return (ret); } /* * PUBLIC: int __txn_xa_regop_recover * PUBLIC: __P((DB_ENV *, DBT *, DB_LSN *, db_recops, void *)); * * These records are only ever written for prepares. */ int __txn_xa_regop_recover(dbenv, dbtp, lsnp, op, info) DB_ENV *dbenv; DBT *dbtp; DB_LSN *lsnp; db_recops op; void *info; { __txn_xa_regop_args *argp; int ret; #ifdef DEBUG_RECOVER (void)__txn_xa_regop_print(dbenv, dbtp, lsnp, op, info); #endif if ((ret = __txn_xa_regop_read(dbenv, dbtp->data, &argp)) != 0) return (ret); if (argp->opcode != TXN_PREPARE) { ret = EINVAL; goto err; } ret = __db_txnlist_find(info, argp->txnid->txnid); /* * If we are rolling forward, then an aborted prepare * indicates that this is the last record we'll see for * this transaction ID and we should remove it from the * list. */ if (op == DB_TXN_FORWARD_ROLL && ret == 1) ret = __db_txnlist_remove(info, argp->txnid->txnid); else if (op == DB_TXN_BACKWARD_ROLL && ret != 0) { /* * On the backward pass, we have three possibilities: * 1. The transaction is already committed, no-op. * 2. The transaction is not committed and we are XA, treat * like commited and roll forward so that can be committed * or aborted late. * 3. The transaction is not committed and we are not XA * mark the transaction as aborted. * * Cases 2 and 3 are handled here. */ /* * Should never have seen this transaction unless it was * commited. */ DB_ASSERT(ret == DB_NOTFOUND); if (IS_XA_TXN(argp)) { /* * This is an XA prepared, but not yet committed * transaction. We need to add it to the * transaction list, so that it gets rolled * forward. We also have to add it to the region's * internal state so it can be properly aborted * or recovered. */ if ((ret = __db_txnlist_add(dbenv, info, argp->txnid->txnid, 0)) == 0) ret = __txn_restore_txn(dbenv, lsnp, argp); } else ret = __db_txnlist_add(dbenv, info, argp->txnid->txnid, 1); } else ret = 0; if (ret == 0) *lsnp = argp->prev_lsn; err: __os_free(argp, 0); return (ret); } /* * PUBLIC: int __txn_ckp_recover * PUBLIC: __P((DB_ENV *, DBT *, DB_LSN *, db_recops, void *)); */ int __txn_ckp_recover(dbenv, dbtp, lsnp, op, info) DB_ENV *dbenv; DBT *dbtp; DB_LSN *lsnp; db_recops op; void *info; { __txn_ckp_args *argp; int ret; #ifdef DEBUG_RECOVER __txn_ckp_print(dbenv, dbtp, lsnp, op, info); #endif COMPQUIET(dbenv, NULL); if ((ret = __txn_ckp_read(dbenv, dbtp->data, &argp)) != 0) return (ret); /* * Check for 'restart' checkpoint record. This occurs when the * checkpoint lsn is equal to the lsn of the checkpoint record * and means that we could set the transaction ID back to 1, so * that we don't exhaust the transaction ID name space. */ if (argp->ckp_lsn.file == lsnp->file && argp->ckp_lsn.offset == lsnp->offset) __db_txnlist_gen(info, DB_REDO(op) ? -1 : 1); *lsnp = argp->last_ckp; __os_free(argp, 0); return (DB_TXN_CKP); } /* * __txn_child_recover * Recover a commit record for a child transaction. * * PUBLIC: int __txn_child_recover * PUBLIC: __P((DB_ENV *, DBT *, DB_LSN *, db_recops, void *)); */ int __txn_child_recover(dbenv, dbtp, lsnp, op, info) DB_ENV *dbenv; DBT *dbtp; DB_LSN *lsnp; db_recops op; void *info; { __txn_child_args *argp; int ret; #ifdef DEBUG_RECOVER (void)__txn_child_print(dbenv, dbtp, lsnp, op, info); #endif if ((ret = __txn_child_read(dbenv, dbtp->data, &argp)) != 0) return (ret); /* * This is a record in a PARENT's log trail indicating that a * child commited. If we are aborting, we need to update the * parent's LSN array. If we are in recovery, then if the * parent is commiting, we set ourselves up to commit, else * we do nothing. */ if (op == DB_TXN_ABORT) { /* Note that __db_txnlist_lsnadd rewrites its LSN * parameter, so you cannot reuse the argp->c_lsn field. */ ret = __db_txnlist_lsnadd(dbenv, info, &argp->c_lsn, TXNLIST_NEW); } else if (op == DB_TXN_BACKWARD_ROLL) { if (__db_txnlist_find(info, argp->txnid->txnid) == 0) ret = __db_txnlist_add(dbenv, info, argp->child, 0); else ret = __db_txnlist_add(dbenv, info, argp->child, 1); } else ret = __db_txnlist_remove(info, argp->child); if (ret == 0) *lsnp = argp->prev_lsn; __os_free(argp, 0); return (ret); } /* * __txn_restore_txn -- * Using only during XA recovery. If we find any transactions that are * prepared, but not yet committed, then we need to restore the transaction's * state into the shared region, because the TM is going to issue a txn_abort * or txn_commit and we need to respond correctly. * * lsnp is the LSN of the returned LSN * argp is the perpare record (in an appropriate structure) */ static int __txn_restore_txn(dbenv, lsnp, argp) DB_ENV *dbenv; DB_LSN *lsnp; __txn_xa_regop_args *argp; { DB_TXNMGR *mgr; TXN_DETAIL *td; DB_TXNREGION *region; int ret; if (argp->xid.size == 0) return (0); mgr = dbenv->tx_handle; region = mgr->reginfo.primary; R_LOCK(dbenv, &mgr->reginfo); /* Allocate a new transaction detail structure. */ if ((ret = __db_shalloc(mgr->reginfo.addr, sizeof(TXN_DETAIL), 0, &td)) != 0) return (ret); /* Place transaction on active transaction list. */ SH_TAILQ_INSERT_HEAD(&region->active_txn, td, links, __txn_detail); td->txnid = argp->txnid->txnid; td->begin_lsn = argp->begin_lsn; td->last_lsn = *lsnp; td->parent = 0; td->status = TXN_PREPARED; td->xa_status = TXN_XA_PREPARED; memcpy(td->xid, argp->xid.data, argp->xid.size); td->bqual = argp->bqual; td->gtrid = argp->gtrid; td->format = argp->formatID; R_UNLOCK(dbenv, &mgr->reginfo); return (0); }
rhuitl/uClinux
user/mysql/bdb/txn/txn_rec.c
C
gpl-2.0
9,350
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * Free SoftwareFoundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.vfs; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; /** * Always returns <code>FileNotFound</code> for any open attempt. * <code>NotFoundPath</code> is a useful utility Path for MergePath when * the path doesn't exist in any of the merged paths. * * @since Resin 1.2 */ public class NotFoundPath extends Path { private String _url; /** * Creates new NotFoundPath */ public NotFoundPath(SchemeMap schemeMap, String url) { super(schemeMap); _url = url; } /** * Dummy return. */ public Path schemeWalk(String userPath, Map<String,Object> attributes, String path, int offset) { return this; } /** * The URL is error */ public String getURL() { return _url; } public String getScheme() { return "error"; } /** * Returns the URL which can't be found. */ public String getPath() { return _url; } /** * Throws a FileNotFoundException for any read. */ public StreamImpl openReadImpl() throws IOException { throw new FileNotFoundException(getURL()); } protected Path copyCache() { return null; } /** * Only identical is equals */ public boolean equals(Object obj) { return false; } }
dwango/quercus
src/main/java/com/caucho/vfs/NotFoundPath.java
Java
gpl-2.0
2,369
----------------------------------- -- Area: Dynamis - Qufim -- Mob: Goblin Statue ----------------------------------- require("scripts/globals/dynamis") ----------------------------------- function onMobDeath(mob, player, isKiller) dynamis.timeExtensionOnDeath(mob, player, isKiller) end
zynjec/darkstar
scripts/zones/Dynamis-Qufim/mobs/Goblin_Statue.lua
Lua
gpl-3.0
295
(function () { var textcolor = (function () { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); var getCurrentColor = function (editor, format) { var color; editor.dom.getParents(editor.selection.getStart(), function (elm) { var value; if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) { color = value; } }); return color; }; var mapColors = function (colorMap) { var i; var colors = []; for (i = 0; i < colorMap.length; i += 2) { colors.push({ text: colorMap[i + 1], color: '#' + colorMap[i] }); } return colors; }; var applyFormat = function (editor, format, value) { editor.undoManager.transact(function () { editor.focus(); editor.formatter.apply(format, { value: value }); editor.nodeChanged(); }); }; var removeFormat = function (editor, format) { editor.undoManager.transact(function () { editor.focus(); editor.formatter.remove(format, { value: null }, null, true); editor.nodeChanged(); }); }; var $_1d7gtwqsjh8lz35z = { getCurrentColor: getCurrentColor, mapColors: mapColors, applyFormat: applyFormat, removeFormat: removeFormat }; var register = function (editor) { editor.addCommand('mceApplyTextcolor', function (format, value) { $_1d7gtwqsjh8lz35z.applyFormat(editor, format, value); }); editor.addCommand('mceRemoveTextcolor', function (format) { $_1d7gtwqsjh8lz35z.removeFormat(editor, format); }); }; var $_9kt0cyqrjh8lz35y = { register: register }; var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools'); var defaultColorMap = [ '000000', 'Black', '993300', 'Burnt orange', '333300', 'Dark olive', '003300', 'Dark green', '003366', 'Dark azure', '000080', 'Navy Blue', '333399', 'Indigo', '333333', 'Very dark gray', '800000', 'Maroon', 'FF6600', 'Orange', '808000', 'Olive', '008000', 'Green', '008080', 'Teal', '0000FF', 'Blue', '666699', 'Grayish blue', '808080', 'Gray', 'FF0000', 'Red', 'FF9900', 'Amber', '99CC00', 'Yellow green', '339966', 'Sea green', '33CCCC', 'Turquoise', '3366FF', 'Royal blue', '800080', 'Purple', '999999', 'Medium gray', 'FF00FF', 'Magenta', 'FFCC00', 'Gold', 'FFFF00', 'Yellow', '00FF00', 'Lime', '00FFFF', 'Aqua', '00CCFF', 'Sky blue', '993366', 'Red violet', 'FFFFFF', 'White', 'FF99CC', 'Pink', 'FFCC99', 'Peach', 'FFFF99', 'Light yellow', 'CCFFCC', 'Pale green', 'CCFFFF', 'Pale cyan', '99CCFF', 'Light sky blue', 'CC99FF', 'Plum' ]; var getTextColorMap = function (editor) { return editor.getParam('textcolor_map', defaultColorMap); }; var getForeColorMap = function (editor) { return editor.getParam('forecolor_map', getTextColorMap(editor)); }; var getBackColorMap = function (editor) { return editor.getParam('backcolor_map', getTextColorMap(editor)); }; var getTextColorRows = function (editor) { return editor.getParam('textcolor_rows', 5); }; var getTextColorCols = function (editor) { return editor.getParam('textcolor_cols', 8); }; var getForeColorRows = function (editor) { return editor.getParam('forecolor_rows', getTextColorRows(editor)); }; var getBackColorRows = function (editor) { return editor.getParam('backcolor_rows', getTextColorRows(editor)); }; var getForeColorCols = function (editor) { return editor.getParam('forecolor_cols', getTextColorCols(editor)); }; var getBackColorCols = function (editor) { return editor.getParam('backcolor_cols', getTextColorCols(editor)); }; var getColorPickerCallback = function (editor) { return editor.getParam('color_picker_callback', null); }; var hasColorPicker = function (editor) { return typeof getColorPickerCallback(editor) === 'function'; }; var $_cupc58qwjh8lz366 = { getForeColorMap: getForeColorMap, getBackColorMap: getBackColorMap, getForeColorRows: getForeColorRows, getBackColorRows: getBackColorRows, getForeColorCols: getForeColorCols, getBackColorCols: getBackColorCols, getColorPickerCallback: getColorPickerCallback, hasColorPicker: hasColorPicker }; var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n'); var getHtml = function (cols, rows, colorMap, hasColorPicker) { var colors, color, html, last, x, y, i, count = 0; var id = global$1.DOM.uniqueId('mcearia'); var getColorCellHtml = function (color, title) { var isNoColor = color === 'transparent'; return '<td class="mce-grid-cell' + (isNoColor ? ' mce-colorbtn-trans' : '') + '">' + '<div id="' + id + '-' + count++ + '"' + ' data-mce-color="' + (color ? color : '') + '"' + ' role="option"' + ' tabIndex="-1"' + ' style="' + (color ? 'background-color: ' + color : '') + '"' + ' title="' + global$3.translate(title) + '">' + (isNoColor ? '&#215;' : '') + '</div>' + '</td>'; }; colors = $_1d7gtwqsjh8lz35z.mapColors(colorMap); colors.push({ text: global$3.translate('No color'), color: 'transparent' }); html = '<table class="mce-grid mce-grid-border mce-colorbutton-grid" role="list" cellspacing="0"><tbody>'; last = colors.length - 1; for (y = 0; y < rows; y++) { html += '<tr>'; for (x = 0; x < cols; x++) { i = y * cols + x; if (i > last) { html += '<td></td>'; } else { color = colors[i]; html += getColorCellHtml(color.color, color.text); } } html += '</tr>'; } if (hasColorPicker) { html += '<tr>' + '<td colspan="' + cols + '" class="mce-custom-color-btn">' + '<div id="' + id + '-c" class="mce-widget mce-btn mce-btn-small mce-btn-flat" ' + 'role="button" tabindex="-1" aria-labelledby="' + id + '-c" style="width: 100%">' + '<button type="button" role="presentation" tabindex="-1">' + global$3.translate('Custom...') + '</button>' + '</div>' + '</td>' + '</tr>'; html += '<tr>'; for (x = 0; x < cols; x++) { html += getColorCellHtml('', 'Custom color'); } html += '</tr>'; } html += '</tbody></table>'; return html; }; var $_yigkpqxjh8lz368 = { getHtml: getHtml }; var setDivColor = function setDivColor(div, value) { div.style.background = value; div.setAttribute('data-mce-color', value); }; var onButtonClick = function (editor) { return function (e) { var ctrl = e.control; if (ctrl._color) { editor.execCommand('mceApplyTextcolor', ctrl.settings.format, ctrl._color); } else { editor.execCommand('mceRemoveTextcolor', ctrl.settings.format); } }; }; var onPanelClick = function (editor, cols) { return function (e) { var buttonCtrl = this.parent(); var value; var currentColor = $_1d7gtwqsjh8lz35z.getCurrentColor(editor, buttonCtrl.settings.format); var selectColor = function (value) { editor.execCommand('mceApplyTextcolor', buttonCtrl.settings.format, value); buttonCtrl.hidePanel(); buttonCtrl.color(value); }; var resetColor = function () { editor.execCommand('mceRemoveTextcolor', buttonCtrl.settings.format); buttonCtrl.hidePanel(); buttonCtrl.resetColor(); }; if (global$1.DOM.getParent(e.target, '.mce-custom-color-btn')) { buttonCtrl.hidePanel(); var colorPickerCallback = $_cupc58qwjh8lz366.getColorPickerCallback(editor); colorPickerCallback.call(editor, function (value) { var tableElm = buttonCtrl.panel.getEl().getElementsByTagName('table')[0]; var customColorCells, div, i; customColorCells = global$2.map(tableElm.rows[tableElm.rows.length - 1].childNodes, function (elm) { return elm.firstChild; }); for (i = 0; i < customColorCells.length; i++) { div = customColorCells[i]; if (!div.getAttribute('data-mce-color')) { break; } } if (i === cols) { for (i = 0; i < cols - 1; i++) { setDivColor(customColorCells[i], customColorCells[i + 1].getAttribute('data-mce-color')); } } setDivColor(div, value); selectColor(value); }, currentColor); } value = e.target.getAttribute('data-mce-color'); if (value) { if (this.lastId) { global$1.DOM.get(this.lastId).setAttribute('aria-selected', 'false'); } e.target.setAttribute('aria-selected', true); this.lastId = e.target.id; if (value === 'transparent') { resetColor(); } else { selectColor(value); } } else if (value !== null) { buttonCtrl.hidePanel(); } }; }; var renderColorPicker = function (editor, foreColor) { return function () { var cols = foreColor ? $_cupc58qwjh8lz366.getForeColorCols(editor) : $_cupc58qwjh8lz366.getBackColorCols(editor); var rows = foreColor ? $_cupc58qwjh8lz366.getForeColorRows(editor) : $_cupc58qwjh8lz366.getBackColorRows(editor); var colorMap = foreColor ? $_cupc58qwjh8lz366.getForeColorMap(editor) : $_cupc58qwjh8lz366.getBackColorMap(editor); var hasColorPicker = $_cupc58qwjh8lz366.hasColorPicker(editor); return $_yigkpqxjh8lz368.getHtml(cols, rows, colorMap, hasColorPicker); }; }; var register$1 = function (editor) { editor.addButton('forecolor', { type: 'colorbutton', tooltip: 'Text color', format: 'forecolor', panel: { role: 'application', ariaRemember: true, html: renderColorPicker(editor, true), onclick: onPanelClick(editor, $_cupc58qwjh8lz366.getForeColorCols(editor)) }, onclick: onButtonClick(editor) }); editor.addButton('backcolor', { type: 'colorbutton', tooltip: 'Background color', format: 'hilitecolor', panel: { role: 'application', ariaRemember: true, html: renderColorPicker(editor, false), onclick: onPanelClick(editor, $_cupc58qwjh8lz366.getBackColorCols(editor)) }, onclick: onButtonClick(editor) }); }; var $_dk5fhnqtjh8lz361 = { register: register$1 }; global.add('textcolor', function (editor) { $_9kt0cyqrjh8lz35y.register(editor); $_dk5fhnqtjh8lz361.register(editor); }); function Plugin () { } return Plugin; }()); })();
nemiah/poolPi
public_html/backend/libraries/tinymce/plugins/textcolor/plugin.js
JavaScript
gpl-3.0
10,835
/* lzo2a.h -- public interface of the LZO2A compression algorithm This file is part of the LZO real-time data compression library. Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer <[email protected]> http://www.oberhumer.com/opensource/lzo/ */ #ifndef __LZO2A_H_INCLUDED #define __LZO2A_H_INCLUDED 1 #ifndef __LZOCONF_H_INCLUDED #include <lzo/lzoconf.h> #endif #ifdef __cplusplus extern "C" { #endif /*********************************************************************** // ************************************************************************/ #define LZO2A_MEM_DECOMPRESS (0) /* decompression */ LZO_EXTERN(int) lzo2a_decompress ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem /* NOT USED */ ); /* safe decompression with overrun testing */ LZO_EXTERN(int) lzo2a_decompress_safe ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem /* NOT USED */ ); /*********************************************************************** // better compression ratio at the cost of more memory and time ************************************************************************/ #define LZO2A_999_MEM_COMPRESS ((lzo_uint32_t) (8 * 16384L * sizeof(short))) LZO_EXTERN(int) lzo2a_999_compress ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem ); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* already included */ /* vim:set ts=4 sw=4 et: */
John-Yu/Simple_PE_packer
lzo-2.10/include/lzo/lzo2a.h
C
gpl-3.0
2,525
define(['app'], function (app) { app.controller('FloorplanEditController', ['$scope', '$rootScope', '$location', '$http', '$interval', 'permissions', function ($scope, $rootScope, $location, $http, $interval, permissions) { ImageLoaded = function () { if ((typeof $("#floorplanimagesize") != 'undefined') && (typeof $("#floorplanimagesize")[0] != 'undefined') && ($("#floorplanimagesize")[0].naturalWidth != 'undefined')) { $('#helptext').attr("title", 'Image width is: ' + $("#floorplanimagesize")[0].naturalWidth + ", Height is: " + $("#floorplanimagesize")[0].naturalHeight); $("#svgcontainer")[0].setAttribute("viewBox", "0 0 " + $("#floorplanimagesize")[0].naturalWidth + " " + $("#floorplanimagesize")[0].naturalHeight); Device.xImageSize = $("#floorplanimagesize")[0].naturalWidth; Device.yImageSize = $("#floorplanimagesize")[0].naturalHeight; $("#svgcontainer")[0].setAttribute("style", "display:inline"); $scope.SVGContainerResize(); } } $scope.SVGContainerResize = function () { var svgHeight; if ((typeof $("#floorplaneditor") != 'undefined') && (typeof $("#floorplanimagesize") != 'undefined') && (typeof $("#floorplanimagesize")[0] != 'undefined') && ($("#floorplanimagesize")[0].naturalWidth != 'undefined')) { $("#floorplaneditor")[0].setAttribute('naturalWidth', $("#floorplanimagesize")[0].naturalWidth); $("#floorplaneditor")[0].setAttribute('naturalHeight', $("#floorplanimagesize")[0].naturalHeight); $("#floorplaneditor")[0].setAttribute('svgwidth', $("#svgcontainer").width()); var ratio = $("#floorplanimagesize")[0].naturalWidth / $("#floorplanimagesize")[0].naturalHeight; $("#floorplaneditor")[0].setAttribute('ratio', ratio); svgHeight = $("#floorplaneditor").width() / ratio; $("#floorplaneditor").height(svgHeight); } } PolyClick = function (click) { if ($("#floorplangroup")[0].getAttribute("zoomed") == "true") { $("#floorplangroup")[0].setAttribute("transform", "translate(0,0) scale(1)"); $("#DeviceContainer")[0].setAttribute("transform", "translate(0,0) scale(1)"); $("#floorplangroup")[0].setAttribute("zoomed", "false"); } else { var borderRect = click.target.getBBox(); // polygon bounding box var margin = 0.1; // 10% margin around polygon var marginX = borderRect.width * margin; var marginY = borderRect.height * margin; var scaleX = Device.xImageSize / (borderRect.width + (marginX * 2)); var scaleY = Device.yImageSize / (borderRect.height + (marginY * 2)); var scale = ((scaleX > scaleY) ? scaleY : scaleX); var attr = 'scale(' + scale + ')' + ' translate(' + (borderRect.x - marginX) * -1 + ',' + (borderRect.y - marginY) * -1 + ')'; // this actually needs to centre in the direction its not scaling but close enough for v1.0 $("#floorplangroup")[0].setAttribute("transform", attr); $("#DeviceContainer")[0].setAttribute("transform", attr); $("#floorplangroup")[0].setAttribute("zoomed", "true"); } window.myglobals.LastUpdate = 0; RefreshDevices(); // force redraw to change 'moveability' of icons } FloorplanClick = function (click) { // make sure we aren't zoomed in. if ($("#floorplangroup")[0].getAttribute("zoomed") != "true") { if ($("#roompolyarea").attr("title") != "") { var Scale = Device.xImageSize / $("#floorplaneditor").width(); var offset = $("#floorplanimage").offset(); var points = $("#roompolyarea").attr("points"); var xPoint = Math.round((click.pageX - offset.left) * Scale); var yPoint = Math.round((click.pageY - offset.top) * Scale); if (points != "") { points = points + ","; } else { $("#floorplangroup")[0].appendChild(makeSVGnode('circle', { id: "firstclick", cx: xPoint, cy: yPoint, r: 2, class: 'hoverable' }, '')); $(".hoverable").css({ 'fill': $.myglobals.RoomColour, 'fill-opacity': $.myglobals.ActiveRoomOpacity / 100, 'stroke': $.myglobals.RoomColour, 'stroke-opacity': 90 }); } points = points + xPoint + "," + yPoint; $("#roompolyarea").attr("points", points); $('#floorplaneditcontent #delclractive #activeplanupdate').attr("class", "btnstyle3"); } else ShowNotify('Select a Floorplan and Room first.', 2500, true); } else { PolyClick(click); } } SetButtonStates = function () { $('#updelclr #floorplanadd').attr("class", "btnstyle3-dis"); $('#updelclr #floorplanedit').attr("class", "btnstyle3-dis"); $('#updelclr #floorplandelete').attr("class", "btnstyle3-dis"); $('#floorplaneditcontent #delclractive #activeplanadd').attr("class", "btnstyle3-dis"); $('#floorplaneditcontent #delclractive #activeplanclear').attr("class", "btnstyle3-dis"); $('#floorplaneditcontent #delclractive #activeplandelete').attr("class", "btnstyle3-dis"); $('#floorplaneditcontent #delclractive #activeplanupdate').attr("class", "btnstyle3-dis"); var anSelected = fnGetSelected($('#floorplantable').dataTable()); if (anSelected.length !== 0) { $('#updelclr #floorplanedit').attr("class", "btnstyle3"); $('#updelclr #floorplandelete').attr("class", "btnstyle3"); if ($("#floorplaneditcontent #comboactiveplan").children().length > 0) { $('#floorplaneditcontent #delclractive #activeplanadd').attr("class", "btnstyle3"); } anSelected = fnGetSelected($('#plantable2').dataTable()); if (anSelected.length !== 0) { $('#floorplaneditcontent #delclractive #activeplandelete').attr("class", "btnstyle3"); var data = $('#plantable2').dataTable().fnGetData(anSelected[0]); if (data["Area"].length != 0) { $('#floorplaneditcontent #delclractive #activeplanclear').attr("class", "btnstyle3"); } } } else { $('#updelclr #floorplanadd').attr("class", "btnstyle3"); } } ChangeFloorplanOrder = function (order, floorplanid) { if (!permissions.hasPermission("Admin")) { HideNotify(); ShowNotify($.t('You do not have permission to do that!'), 2500, true); return; } $.ajax({ url: "json.htm?type=command&param=changefloorplanorder&idx=" + floorplanid + "&way=" + order, async: false, dataType: 'json', success: function (data) { RefreshFloorPlanTable(); } }); } LoadImageNames = function () { var oTable = $('#imagetable').dataTable(); oTable.fnClearTable(); $.ajax({ url: "json.htm?type=command&param=getfloorplanimages", async: false, dataType: 'json', success: function (data) { if (typeof data.result != 'undefined') { $.each(data.result, function (tag, images) { for (var i = 0; i < images.length; i++) { var addId = oTable.fnAddData({ "DT_RowId": i, "ImageName": images[i], "0": images[i] }); } }); $('#imagetable tbody').off(); /* Add a click handler to the rows - this could be used as a callback */ $('#imagetable tbody').on('click', 'tr', function () { if ($(this).hasClass('row_selected')) { $(this).removeClass('row_selected'); $("#dialog-add-edit-floorplan #imagename").val(''); } else { oTable.$('tr.row_selected').removeClass('row_selected'); $(this).addClass('row_selected'); var anSelected = fnGetSelected(oTable); if (anSelected.length !== 0) { var data = oTable.fnGetData(anSelected[0]); $("#dialog-add-edit-floorplan #imagename").val('images/floorplans/' + data["ImageName"]); } } }); } } }); } AddNewFloorplan = function () { LoadImageNames(); $("#dialog-add-edit-floorplan #floorplanname").val(''); $("#dialog-add-edit-floorplan #imagename").val(''); $("#dialog-add-edit-floorplan #scalefactor").val('1.0'); $("#dialog-add-edit-floorplan").dialog({ resizable: false, width: 460, height: 540, modal: true, title: 'Add New Floorplan', buttons: { "Cancel": function () { $(this).dialog("close"); }, "Add": function () { var csettings = GetFloorplanSettings(); if (typeof csettings == 'undefined') { return; } $(this).dialog("close"); AddFloorplan(); } }, close: function () { $(this).dialog("close"); } }); } EditFloorplan = function (idx) { LoadImageNames(); $("#dialog-add-edit-floorplan").dialog({ resizable: false, width: 460, height: 540, modal: true, title: 'Edit Floorplan', buttons: { "Cancel": function () { $(this).dialog("close"); }, "Update": function () { var csettings = GetFloorplanSettings(); if (typeof csettings == 'undefined') { return; } $(this).dialog("close"); UpdateFloorplan(idx); } }, close: function () { $(this).dialog("close"); } }); } DeleteFloorplan = function (idx) { bootbox.confirm($.t("Are you sure you want to delete this Floorplan?"), function (result) { if (result == true) { $.ajax({ url: "json.htm?type=command&param=deletefloorplan&idx=" + idx, async: false, dataType: 'json', error: function () { HideNotify(); ShowNotify('Problem deleting Floorplan!', 2500, true); } }); RefreshUnusedDevicesComboArray(); RefreshFloorPlanTable(); } }); } GetFloorplanSettings = function () { var csettings = {}; csettings.name = $("#dialog-add-edit-floorplan #floorplanname").val(); if (csettings.name == "") { ShowNotify('Please enter a Name!', 2500, true); return; } csettings.image = $("#dialog-add-edit-floorplan #imagename").val(); if (csettings.image == "") { ShowNotify('Please enter an image filename!', 2500, true); return; } csettings.scalefactor = $("#dialog-add-edit-floorplan #scalefactor").val(); if (!$.isNumeric(csettings.scalefactor)) { ShowNotify($.t('Icon Scale can only contain numbers...'), 2000, true); return; } return csettings; } UpdateFloorplan = function (idx) { var csettings = GetFloorplanSettings(); if (typeof csettings == 'undefined') { return; } $.ajax({ url: "json.htm?type=command&param=updatefloorplan&idx=" + idx + "&name=" + csettings.name + "&image=" + csettings.image + "&scalefactor=" + csettings.scalefactor, async: false, dataType: 'json', success: function (data) { RefreshFloorPlanTable(); }, error: function () { ShowNotify('Problem updating Plan settings!', 2500, true); } }); } AddFloorplan = function () { var csettings = GetFloorplanSettings(); if (typeof csettings == 'undefined') { return; } $.ajax({ url: "json.htm?type=command&param=addfloorplan&name=" + csettings.name + "&image=" + csettings.image + "&scalefactor=1.0", async: false, dataType: 'json', success: function (data) { RefreshFloorPlanTable(); }, error: function () { ShowNotify('Problem adding Floorplan!', 2500, true); } }); } RefreshFloorPlanTable = function () { $('#modal').show(); $.devIdx = -1; $("#roomplangroup").empty(); $("#floorplanimage").attr("xlink:href", ""); $("#floorplanimagesize").attr("src", ""); if (typeof $scope.mytimer != 'undefined') { $interval.cancel($scope.mytimer); $scope.mytimer = undefined; } Device.initialise(); var oTable = $('#floorplaneditcontent #plantable2').dataTable(); oTable.fnClearTable(); oTable = $('#floorplantable').dataTable(); oTable.fnClearTable(); $.ajax({ url: "json.htm?type=floorplans", async: false, dataType: 'json', success: function (data) { if (typeof data.result != 'undefined') { var totalItems = data.result.length; $.each(data.result, function (i, item) { var updownImg = ""; if (i != totalItems - 1) { //Add Down Image if (updownImg != "") { updownImg += "&nbsp;"; } updownImg += '<img src="images/down.png" onclick="ChangeFloorplanOrder(1,' + item.idx + ');" class="lcursor" width="16" height="16"></img>'; } else { updownImg += '<img src="images/empty16.png" width="16" height="16"></img>'; } if (i != 0) { //Add Up image if (updownImg != "") { updownImg += "&nbsp;"; } updownImg += '<img src="images/up.png" onclick="ChangeFloorplanOrder(0,' + item.idx + ');" class="lcursor" width="16" height="16"></img>'; } var addId = oTable.fnAddData({ "DT_RowId": item.idx, "Name": item.Name, "Image": item.Image, "ScaleFactor": item.ScaleFactor, "Order": item.Order, "0": item.Name, "1": item.Image, "2": item.ScaleFactor, "3": updownImg }); }); // handle settings if (typeof data.RoomColour != 'undefined') { $.myglobals.RoomColour = data.RoomColour; } if (typeof data.ActiveRoomOpacity != 'undefined') { $.myglobals.ActiveRoomOpacity = data.ActiveRoomOpacity; $(".hoverable").css({ 'fill': $.myglobals.RoomColour, 'fill-opacity': $.myglobals.ActiveRoomOpacity / 100, 'stroke': $.myglobals.RoomColour, 'stroke-opacity': 90 }); } if (typeof data.InactiveRoomOpacity != 'undefined') { $.myglobals.InactiveRoomOpacity = data.InactiveRoomOpacity; } if (typeof data.PopupDelay != 'undefined') { Device.popupDelay = data.PopupDelay; } if (typeof data.ShowSensorValues != 'undefined') { Device.showSensorValues = (data.ShowSensorValues == 1); } if (typeof data.ShowSwitchValues != 'undefined') { Device.showSwitchValues = (data.ShowSwitchValues == 1); } if (typeof data.ShowSceneNames != 'undefined') { Device.showSceneNames = (data.ShowSceneNames == 1); } /* Add a click handler to the rows - this could be used as a callback */ $('#floorplantable tbody').off() .on('click', 'tr', function () { $.devIdx = -1; ConfirmNoUpdate(this, function (param) { if ($(param).hasClass('row_selected')) { $(param).removeClass('row_selected'); $("#dialog-add-edit-floorplan #floorplanname").val(""); $("#dialog-add-edit-floorplan #imagename").val(""); $("#dialog-add-edit-floorplan #scalefactor").val("1.0"); $("#floorplangroup").attr("scalefactor", "1.0"); RefreshPlanTable(-1); $("#floorplanimage").attr("xlink:href", ""); $("#floorplanimagesize").attr("src", ""); } else { oTable.$('tr.row_selected').removeClass('row_selected'); $(param).addClass('row_selected'); var anSelected = fnGetSelected(oTable); if (anSelected.length !== 0) { var data = oTable.fnGetData(anSelected[0]); var idx = data["DT_RowId"]; $.devIdx = idx; $("#updelclr #floorplanedit").attr("href", "javascript:EditFloorplan(" + idx + ")"); $("#updelclr #floorplandelete").attr("href", "javascript:DeleteFloorplan(" + idx + ")"); $("#dialog-add-edit-floorplan #floorplanname").val(data["Name"]); $("#dialog-add-edit-floorplan #imagename").val(data["Image"]); $("#dialog-add-edit-floorplan #scalefactor").val(data["ScaleFactor"]); $("#floorplangroup").attr("scalefactor", data["ScaleFactor"]); RefreshPlanTable(idx); $("#floorplanimage").attr("xlink:href", data["Image"]); $("#floorplanimagesize").attr("src", data["Image"]); $scope.SVGContainerResize(); } } SetButtonStates(); }); }); } } }); SetButtonStates(); $('#modal').hide(); } RefreshUnusedDevicesComboArray = function () { $.UnusedDevices = []; $("#floorplaneditcontent #comboactiveplan").empty(); $.ajax({ url: "json.htm?type=command&param=getunusedfloorplanplans&unique=false", async: false, dataType: 'json', success: function (data) { if (typeof data.result != 'undefined') { $.each(data.result, function (i, item) { $.UnusedDevices.push({ idx: item.idx, name: item.Name }); }); $.each($.UnusedDevices, function (i, item) { var option = $('<option />'); option.attr('value', item.idx).text(item.name); $("#floorplaneditcontent #comboactiveplan").append(option); }); } } }); } ShowFloorplans = function () { var oTable; $('#modal').show(); Device.useSVGtags = true; Device.backFunction = 'ShowFloorplans'; Device.switchFunction = 'RefreshDevices'; Device.contentTag = 'floorplaneditcontent'; var htmlcontent = ""; htmlcontent += $('#floorplaneditmain').html(); $('#floorplaneditcontent').html(htmlcontent); $('#floorplaneditcontent').i18n(); oTable = $('#floorplantable').dataTable({ "sDom": '<"H"lfrC>t<"F"ip>', "oTableTools": { "sRowSelect": "single", }, "bSort": false, "bProcessing": true, "bStateSave": true, "bJQueryUI": true, "aLengthMenu": [[5, 10, 25, 100, -1], [5, 10, 25, 100, "All"]], "iDisplayLength": 5, "sPaginationType": "full_numbers", language: $.DataTableLanguage }); oTable = $('#plantable2').dataTable({ "sDom": '<"H"lfrC>t<"F"ip>', "oTableTools": { "sRowSelect": "single", }, "bSort": false, "bProcessing": true, "bStateSave": false, "bJQueryUI": true, "aLengthMenu": [[5, 10, 25, 100, -1], [5, 10, 25, 100, "All"]], "iDisplayLength": 10, }); oTable = $('#imagetable').dataTable({ "sDom": '<"H"lfrC>t<"F"ip>', "oTableTools": { "sRowSelect": "single", }, "bSort": true, "bProcessing": true, "bStateSave": false, "bJQueryUI": true, "bFilter": false, "bLengthChange": false, language: $.DataTableLanguage, "iDisplayLength": 5 }); RefreshUnusedDevicesComboArray(); RefreshFloorPlanTable(); SetButtonStates(); $('#modal').hide(); } RefreshPlanTable = function (idx) { $.LastPlan = idx; $('#modal').show(); // if we are zoomed in, zoom out before changing rooms by faking a click in the polygon if ($("#floorplangroup")[0].getAttribute("zoomed") == "true") { PolyClick(); } $("#roomplangroup").empty(); $("#roompolyarea").attr("title", ""); $("#roompolyarea").attr("points", ""); $("#firstclick").remove(); if (typeof $scope.mytimer != 'undefined') { $interval.cancel($scope.mytimer); $scope.mytimer = undefined; } var oTable = $('#floorplaneditcontent #plantable2').dataTable(); oTable.fnClearTable(); Device.initialise(); $.ajax({ url: "json.htm?type=command&param=getfloorplanplans&idx=" + idx, async: false, dataType: 'json', success: function (data) { if (typeof data.result != 'undefined') { var totalItems = data.result.length; var planGroup = $("#roomplangroup")[0]; $.each(data.result, function (i, item) { var addId = oTable.fnAddData({ "DT_RowId": item.idx, "Area": item.Area, "0": item.Name, "1": ((item.Area.length == 0) ? '<img src="images/failed.png"/>' : '<img src="images/ok.png"/>'), "2": item.Area }); var el = makeSVGnode('polygon', { id: item.Name + "_Room", 'class': "nothoverable", points: item.Area }, ''); el.appendChild(makeSVGnode('title', null, item.Name)); planGroup.appendChild(el); }); if ((typeof $.myglobals.RoomColour != 'undefined') && (typeof $.myglobals.InactiveRoomOpacity != 'undefined')) { $(".nothoverable").css({ 'fill': $.myglobals.RoomColour, 'fill-opacity': $.myglobals.InactiveRoomOpacity / 100, 'stroke': $.myglobals.RoomColour, 'stroke-opacity': 90 }); } /* Add a click handler to the rows - this could be used as a callback */ $("#plantable2 tbody").off() .on('click', 'tr', function () { ConfirmNoUpdate(this, function (param) { // if we are zoomed in, zoom out before changing rooms by faking a click in the polygon if ($("#floorplangroup")[0].getAttribute("zoomed") == "true") { PolyClick(); } if ($(param).hasClass('row_selected')) { $(param).removeClass('row_selected'); Device.initialise(); $("#roompolyarea").attr("title", ""); $("#roompolyarea").attr("points", ""); $("#firstclick").remove(); $("#floorplangroup").attr("planidx", ""); $('#floorplanimage').css('cursor', 'auto'); } else { oTable.$('tr.row_selected').removeClass('row_selected'); $(param).addClass('row_selected'); Device.initialise(); var anSelected = fnGetSelected(oTable); if (anSelected.length !== 0) { var data = oTable.fnGetData(anSelected[0]); var idx = data["DT_RowId"]; $("#floorplaneditcontent #delclractive #activeplandelete").attr("href", "javascript:DeleteFloorplanPlan(" + idx + ")"); $("#floorplaneditcontent #delclractive #activeplanupdate").attr("href", "javascript:UpdateFloorplanPlan(" + idx + ",false)"); $("#floorplaneditcontent #delclractive #activeplanclear").attr("href", "javascript:UpdateFloorplanPlan(" + idx + ",true)"); $("#roompolyarea").attr("title", data["0"]); $("#roompolyarea").attr("points", data["2"]); $("#floorplangroup").attr("planidx", idx); $('#floorplanimage').css('cursor', 'crosshair'); ShowDevices(idx); } } SetButtonStates(); }); }); } } }); SetButtonStates(); $('#modal').hide(); } AddUnusedPlan = function () { if ($.devIdx == -1) { return; } var PlanIdx = $("#floorplaneditcontent #comboactiveplan option:selected").val(); if (typeof PlanIdx == 'undefined') { return; } $.ajax({ url: "json.htm?type=command&param=addfloorplanplan&idx=" + $.devIdx + "&planidx=" + PlanIdx, async: false, dataType: 'json', success: function (data) { if (data.status == 'OK') { RefreshPlanTable($.devIdx); RefreshUnusedDevicesComboArray(); } else { ShowNotify('Problem adding Plan!', 2500, true); } }, error: function () { HideNotify(); ShowNotify('Problem adding Plan!', 2500, true); } }); SetButtonStates(); } UpdateFloorplanPlan = function (planidx, clear) { var PlanArea = ''; if (clear != true) { PlanArea = $("#roompolyarea").attr("points"); } $.ajax({ url: "json.htm?type=command&param=updatefloorplanplan&planidx=" + planidx + "&area=" + PlanArea, async: false, dataType: 'json', success: function (data) { if (data.status == 'OK') { // RefreshPlanTable($.devIdx); } else { ShowNotify('Problem updating Plan!', 2500, true); } }, error: function () { HideNotify(); ShowNotify('Problem updating Plan!', 2500, true); } }); var deviceParent = $("#DeviceIcons")[0]; for (var i = 0; i < deviceParent.childNodes.length; i++) { if (deviceParent.childNodes[i].getAttribute('onfloorplan') != 'false') { $.ajax({ url: "json.htm?type=command&param=setplandevicecoords" + "&idx=" + deviceParent.childNodes[i].getAttribute('idx') + "&planidx=" + planidx + "&xoffset=" + deviceParent.childNodes[i].getAttribute('xoffset') + "&yoffset=" + deviceParent.childNodes[i].getAttribute('yoffset') + "&DevSceneType=" + deviceParent.childNodes[i].getAttribute('devscenetype'), async: false, dataType: 'json', success: function (data) { if (data.status == 'OK') { // RefreshPlanTable($.devIdx); } else { ShowNotify('Problem udating Device Coordinates!', 2500, true); } }, error: function () { HideNotify(); ShowNotify('Problem updating Device Coordinates!', 2500, true); } }); } } RefreshPlanTable($.devIdx); } ConfirmNoUpdate = function (param, yesFunc) { if ($('#floorplaneditcontent #delclractive #activeplanupdate').attr("class") == "btnstyle3") { bootbox.confirm($.t("You have unsaved changes, do you want to continue?"), function (result) { if (result == true) { yesFunc(param); } }); } else { yesFunc(param); } } DeleteFloorplanPlan = function (planidx) { bootbox.confirm($.t("Are you sure to delete this Plan from the Floorplan?"), function (result) { if (result == true) { $.ajax({ url: "json.htm?type=command&param=deletefloorplanplan&idx=" + planidx, async: false, dataType: 'json', success: function (data) { RefreshUnusedDevicesComboArray(); RefreshPlanTable($.devIdx); }, error: function () { HideNotify(); ShowNotify('Problem deleting Plan!', 2500, true); } }); } }); } RefreshDevices = function () { if ((typeof $("#floorplangroup") != 'undefined') && (typeof $("#floorplangroup")[0] != 'undefined')) { if (typeof $scope.mytimer != 'undefined') { $interval.cancel($scope.mytimer); $scope.mytimer = undefined; } if ($("#floorplangroup")[0].getAttribute("planidx") != "") { Device.useSVGtags = true; $http({ url: "json.htm?type=devices&filter=all&used=true&order=Name&plan=" + $("#floorplangroup")[0].getAttribute("planidx") + "&lastupdate=" + window.myglobals.LastUpdate }).success(function (data) { if (typeof data.ActTime != 'undefined') { window.myglobals.LastUpdate = data.ActTime; } // insert devices into the document if (typeof data.result != 'undefined') { $.each(data.result, function (i, item) { item.Scale = $("#floorplangroup")[0].getAttribute("scalefactor"); var dev = Device.create(item); dev.setDraggable($("#floorplangroup")[0].getAttribute("zoomed") == "false"); dev.htmlMinimum($("#roomplandevices")[0]); }); } // Add Drag and Drop handler $('.DeviceIcon').draggable() .bind('drag', function (event, ui) { // update coordinates manually, since top/left style props don't work on SVG var parent = event.target.parentNode; if (parent) { if (parent.getAttribute("onfloorplan") == 'false') { parent.setAttribute("onfloorplan", 'true'); parent.setAttribute("opacity", ''); } var Scale = Device.xImageSize / $("#floorplaneditor").width(); var offset = $("#floorplanimage").offset(); var xoffset = Math.round((event.pageX - offset.left - (Device.iconSize / 2)) * Scale); var yoffset = Math.round((event.pageY - offset.top - (Device.iconSize / 2)) * Scale); if (xoffset < 0) xoffset = 0; if (yoffset < 0) yoffset = 0; if (xoffset > (Device.xImageSize - Device.iconSize)) xoffset = Device.xImageSize - Device.iconSize; if (yoffset > (Device.yImageSize - Device.iconSize)) yoffset = Device.yImageSize - Device.iconSize; parent.setAttribute("xoffset", xoffset); parent.setAttribute("yoffset", yoffset); parent.setAttribute("transform", 'translate(' + xoffset + ',' + yoffset + ') scale(' + $("#floorplangroup").attr("scalefactor") + ')'); var objData = $('#DeviceDetails #' + event.target.parentNode.id)[0]; if (objData != undefined) { objData.setAttribute("xoffset", xoffset); objData.setAttribute("yoffset", yoffset); objData.setAttribute("transform", 'translate(' + xoffset + ',' + yoffset + ') scale(' + $("#floorplangroup").attr("scalefactor") + ')'); } $('#floorplaneditcontent #delclractive #activeplanupdate').attr("class", "btnstyle3"); if ($.browser.mozilla) // nasty hack for FireFox. FireFox forgets to display the icon once you start dragging so we need to remind it { (event.target.style.display == "inline") ? event.target.style.display = "none" : event.target.style.display = "inline"; } } }) .bind('dragstop', function (event, ui) { event.target.style.display = "inline"; }); $scope.mytimer = $interval(function () { RefreshDevices(); }, 10000); }).error(function (data) { $scope.mytimer = $interval(function () { RefreshDevices(); }, 10000); }); } } } ShowDevices = function (idx) { if (typeof $("#floorplangroup") != 'undefined') { Device.useSVGtags = true; Device.initialise(); $("#roomplandevices").empty(); $("#floorplangroup")[0].setAttribute("planidx", idx); window.myglobals.LastUpdate = 0; RefreshDevices(); } } init(); function init() { Device.initialise(); $scope.MakeGlobalConfig(); ShowFloorplans(); $("#floorplanimage").on("click", function (event) { FloorplanClick(event); }); $("#guidelines").on("click", function (event) { FloorplanClick(event); }); $("#roompolyarea").on("click", function (event) { PolyClick(event); }); $("#svgcontainer").on("mouseleave", function (event) { MouseOut(event); }); $("#svgcontainer").on("mousemove", function (event) { MouseXY(event); }); $("#svgcontainer").resize(function () { $scope.SVGContainerResize(); }); }; $scope.$on('$destroy', function () { if (typeof $scope.mytimer != 'undefined') { $interval.cancel($scope.mytimer); $scope.mytimer = undefined; } $("#floorplanimage").off(); $("#roompolyarea").off(); $("#svgcontainer").off(); }); }]); });
feiltom/domoticz
www/app/FloorplanEditController.js
JavaScript
gpl-3.0
29,911
/* * Stat.cpp * * Created on: Apr 8, 2012 * Author: lion */ #include "Stat.h" #include "ifs/path.h" #include "utf8.h" namespace fibjs { #ifdef _WIN32 inline double FileTimeToJSTime(FILETIME &ft) { return (double)(*(int64_t *)&ft - 116444736000000000) / 10000; } void Stat::fill(WIN32_FIND_DATAW &fd) { name = utf16to8String(fd.cFileName); size = ((int64_t)fd.nFileSizeHigh << 32 | fd.nFileSizeLow); mode = 0666; mtime = FileTimeToJSTime(fd.ftLastWriteTime); atime = FileTimeToJSTime(fd.ftLastAccessTime); ctime = FileTimeToJSTime(fd.ftCreationTime); m_isDirectory = (FILE_ATTRIBUTE_DIRECTORY & fd.dwFileAttributes) != 0; m_isFile = (FILE_ATTRIBUTE_DIRECTORY & fd.dwFileAttributes) == 0; m_isReadable = true; m_isWritable = (FILE_ATTRIBUTE_READONLY & fd.dwFileAttributes) == 0; m_isExecutable = true; m_isSymbolicLink = false; m_isMemory = false; m_isSocket = false; } #endif result_t Stat::getStat(const char *path) { struct stat64 st; if (::stat64(path, &st)) return CHECK_ERROR(LastError()); fill(path, st); return 0; } void Stat::fill(const char *path, struct stat64 &st) { path_base::basename(path, "", name); size = st.st_size; mode = st.st_mode; mtime = (double)st.st_mtime * 1000ll; atime = (double)st.st_atime * 1000ll; ctime = (double)st.st_ctime * 1000ll; m_isReadable = (st.st_mode | S_IRUSR) != 0; m_isWritable = (st.st_mode | S_IWUSR) != 0; m_isExecutable = (st.st_mode | S_IXUSR) != 0; m_isDirectory = (S_IFDIR & st.st_mode) != 0; m_isFile = (S_IFREG & st.st_mode) != 0; m_isSymbolicLink = S_ISLNK(st.st_mode); m_isMemory = false; m_isSocket = false; } void Stat::init() { name.resize(0); size = 0; mode = 0; mtime = 0; atime = 0; ctime = 0; m_isReadable = false; m_isWritable = false; m_isExecutable = false; m_isDirectory = false; m_isFile = false; m_isSymbolicLink = false; m_isMemory = false; m_isSocket = false; } result_t Stat::get_name(std::string &retVal) { retVal = name; return 0; } result_t Stat::get_size(int64_t &retVal) { retVal = size; return 0; } result_t Stat::get_mode(int32_t &retVal) { retVal = mode; return 0; } result_t Stat::get_mtime(date_t &retVal) { retVal = mtime; return 0; } result_t Stat::get_atime(date_t &retVal) { retVal = atime; return 0; } result_t Stat::get_ctime(date_t &retVal) { retVal = ctime; return 0; } result_t Stat::isWritable(bool &retVal) { retVal = m_isWritable; return 0; } result_t Stat::isReadable(bool &retVal) { retVal = m_isReadable; return 0; } result_t Stat::isExecutable(bool &retVal) { retVal = m_isExecutable; return 0; } result_t Stat::isHidden(bool &retVal) { retVal = m_isHidden; return 0; } result_t Stat::isDirectory(bool &retVal) { retVal = m_isDirectory; return 0; } result_t Stat::isFile(bool &retVal) { retVal = m_isFile; return 0; } result_t Stat::isSymbolicLink(bool &retVal) { retVal = m_isSymbolicLink; return 0; } result_t Stat::isMemory(bool &retVal) { retVal = m_isMemory; return 0; } result_t Stat::isSocket(bool &retVal) { retVal = m_isSocket; return 0; } }
verdantyang/fibjs
fibjs/src/fs/Stat.cpp
C++
gpl-3.0
3,319
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright 2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Nicola Baldo <[email protected]> */ #include "lte-hex-grid-enb-topology-helper.h" #include <ns3/double.h> #include <ns3/log.h> #include <ns3/abort.h> #include <ns3/pointer.h> #include <ns3/epc-helper.h> #include <iostream> NS_LOG_COMPONENT_DEFINE ("LteHexGridEnbTopologyHelper"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (LteHexGridEnbTopologyHelper); LteHexGridEnbTopologyHelper::LteHexGridEnbTopologyHelper () { NS_LOG_FUNCTION (this); } LteHexGridEnbTopologyHelper::~LteHexGridEnbTopologyHelper (void) { NS_LOG_FUNCTION (this); } TypeId LteHexGridEnbTopologyHelper::GetTypeId (void) { static TypeId tid = TypeId ("ns3::LteHexGridEnbTopologyHelper") .SetParent<Object> () .AddConstructor<LteHexGridEnbTopologyHelper> () .AddAttribute ("InterSiteDistance", "The distance [m] between nearby sites", DoubleValue (500), MakeDoubleAccessor (&LteHexGridEnbTopologyHelper::m_d), MakeDoubleChecker<double> ()) .AddAttribute ("SectorOffset", "The offset [m] in the position for the node of each sector with respect " "to the center of the three-sector site", DoubleValue (0.5), MakeDoubleAccessor (&LteHexGridEnbTopologyHelper::m_offset), MakeDoubleChecker<double> ()) .AddAttribute ("SiteHeight", "The height [m] of each site", DoubleValue (30), MakeDoubleAccessor (&LteHexGridEnbTopologyHelper::m_siteHeight), MakeDoubleChecker<double> ()) .AddAttribute ("MinX", "The x coordinate where the hex grid starts.", DoubleValue (0.0), MakeDoubleAccessor (&LteHexGridEnbTopologyHelper::m_xMin), MakeDoubleChecker<double> ()) .AddAttribute ("MinY", "The y coordinate where the hex grid starts.", DoubleValue (0.0), MakeDoubleAccessor (&LteHexGridEnbTopologyHelper::m_yMin), MakeDoubleChecker<double> ()) .AddAttribute ("GridWidth", "The number of sites in even rows (odd rows will have one additional site).", UintegerValue (1), MakeUintegerAccessor (&LteHexGridEnbTopologyHelper::m_gridWidth), MakeUintegerChecker<uint32_t> ()) ; return tid; } void LteHexGridEnbTopologyHelper::DoDispose () { NS_LOG_FUNCTION (this); Object::DoDispose (); } void LteHexGridEnbTopologyHelper::SetLteHelper (Ptr<LteHelper> h) { NS_LOG_FUNCTION (this << h); m_lteHelper = h; } NetDeviceContainer LteHexGridEnbTopologyHelper::SetPositionAndInstallEnbDevice (NodeContainer c) { NS_LOG_FUNCTION (this); NetDeviceContainer enbDevs; const double xydfactor = sqrt (0.75); double yd = xydfactor*m_d; for (uint32_t n = 0; n < c.GetN (); ++n) { uint32_t currentSite = n / 3; uint32_t biRowIndex = (currentSite / (m_gridWidth + m_gridWidth + 1)); uint32_t biRowRemainder = currentSite % (m_gridWidth + m_gridWidth + 1); uint32_t rowIndex = biRowIndex*2; uint32_t colIndex = biRowRemainder; if (biRowRemainder >= m_gridWidth) { ++rowIndex; colIndex -= m_gridWidth; } NS_LOG_LOGIC ("node " << n << " site " << currentSite << " rowIndex " << rowIndex << " colIndex " << colIndex << " biRowIndex " << biRowIndex << " biRowRemainder " << biRowRemainder); double y = m_yMin + yd * rowIndex; double x; double antennaOrientation; if ((rowIndex % 2) == 0) { x = m_xMin + m_d * colIndex; } else // row is odd { x = m_xMin -(0.5*m_d) + m_d * colIndex; } switch (n%3) { case 0: antennaOrientation = 0; x += m_offset; break; case 1: antennaOrientation = 120; x -= m_offset/2.0; y += m_offset*xydfactor; break; case 2: antennaOrientation = -120; x -= m_offset/2.0; y -= m_offset*xydfactor; break; default: break; } Ptr<Node> node = c.Get (n); Ptr<MobilityModel> mm = node->GetObject<MobilityModel> (); Vector pos (x, y, m_siteHeight); NS_LOG_LOGIC ("node " << n << " at " << pos << " antennaOrientation " << antennaOrientation); mm->SetPosition (Vector (x, y, m_siteHeight)); m_lteHelper->SetEnbAntennaModelAttribute ("Orientation", DoubleValue (antennaOrientation)); enbDevs.Add (m_lteHelper->InstallEnbDevice (node)); } return enbDevs; } } // namespace ns3
JBonsink/GSOC-2013
tools/ns-allinone-3.14.1/ns-3.14.1/src/lte/helper/lte-hex-grid-enb-topology-helper.cc
C++
gpl-3.0
5,345
/* nsdsel_gtls.c * * An implementation of the nsd select() interface for GnuTLS. * * Copyright (C) 2008-2012 Adiscon GmbH. * * This file is part of the rsyslog runtime library. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * -or- * see COPYING.ASL20 in the source distribution * * 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. */ #include "config.h" #include <stdlib.h> #include <assert.h> #include <errno.h> #include <string.h> #include <sys/select.h> #include <gnutls/gnutls.h> #include "rsyslog.h" #include "module-template.h" #include "obj.h" #include "errmsg.h" #include "nsd.h" #include "nsd_gtls.h" #include "nsd_ptcp.h" #include "nsdsel_ptcp.h" #include "nsdsel_gtls.h" /* static data */ DEFobjStaticHelpers DEFobjCurrIf(errmsg) DEFobjCurrIf(glbl) DEFobjCurrIf(nsdsel_ptcp) /* Standard-Constructor */ BEGINobjConstruct(nsdsel_gtls) /* be sure to specify the object type also in END macro! */ iRet = nsdsel_ptcp.Construct(&pThis->pTcp); ENDobjConstruct(nsdsel_gtls) /* destructor for the nsdsel_gtls object */ BEGINobjDestruct(nsdsel_gtls) /* be sure to specify the object type also in END and CODESTART macros! */ CODESTARTobjDestruct(nsdsel_gtls) if(pThis->pTcp != NULL) nsdsel_ptcp.Destruct(&pThis->pTcp); ENDobjDestruct(nsdsel_gtls) /* Add a socket to the select set */ static rsRetVal Add(nsdsel_t *pNsdsel, nsd_t *pNsd, nsdsel_waitOp_t waitOp) { DEFiRet; nsdsel_gtls_t *pThis = (nsdsel_gtls_t*) pNsdsel; nsd_gtls_t *pNsdGTLS = (nsd_gtls_t*) pNsd; ISOBJ_TYPE_assert(pThis, nsdsel_gtls); ISOBJ_TYPE_assert(pNsdGTLS, nsd_gtls); if(pNsdGTLS->iMode == 1) { if(waitOp == NSDSEL_RD && gtlsHasRcvInBuffer(pNsdGTLS)) { ++pThis->iBufferRcvReady; dbgprintf("nsdsel_gtls: data already present in buffer, initiating " "dummy select %p->iBufferRcvReady=%d\n", pThis, pThis->iBufferRcvReady); FINALIZE; } if(pNsdGTLS->rtryCall != gtlsRtry_None) { if(gnutls_record_get_direction(pNsdGTLS->sess) == 0) { CHKiRet(nsdsel_ptcp.Add(pThis->pTcp, pNsdGTLS->pTcp, NSDSEL_RD)); } else { CHKiRet(nsdsel_ptcp.Add(pThis->pTcp, pNsdGTLS->pTcp, NSDSEL_WR)); } FINALIZE; } } /* if we reach this point, we need no special handling */ CHKiRet(nsdsel_ptcp.Add(pThis->pTcp, pNsdGTLS->pTcp, waitOp)); finalize_it: RETiRet; } /* perform the select() piNumReady returns how many descriptors are ready for IO * TODO: add timeout! */ static rsRetVal Select(nsdsel_t *pNsdsel, int *piNumReady) { DEFiRet; nsdsel_gtls_t *pThis = (nsdsel_gtls_t*) pNsdsel; ISOBJ_TYPE_assert(pThis, nsdsel_gtls); if(pThis->iBufferRcvReady > 0) { /* we still have data ready! */ *piNumReady = pThis->iBufferRcvReady; dbgprintf("nsdsel_gtls: doing dummy select, data present\n"); } else { iRet = nsdsel_ptcp.Select(pThis->pTcp, piNumReady); } RETiRet; } /* retry an interrupted GTLS operation * rgerhards, 2008-04-30 */ static rsRetVal doRetry(nsd_gtls_t *pNsd) { DEFiRet; int gnuRet; dbgprintf("GnuTLS requested retry of %d operation - executing\n", pNsd->rtryCall); /* We follow a common scheme here: first, we do the systen call and * then we check the result. So far, the result is checked after the * switch, because the result check is the same for all calls. Note that * this may change once we deal with the read and write calls (but * probably this becomes an issue only when we begin to work on TLS * for relp). -- rgerhards, 2008-04-30 */ switch(pNsd->rtryCall) { case gtlsRtry_handshake: gnuRet = gnutls_handshake(pNsd->sess); if(gnuRet == 0) { pNsd->rtryCall = gtlsRtry_None; /* we are done */ /* we got a handshake, now check authorization */ CHKiRet(gtlsChkPeerAuth(pNsd)); } break; case gtlsRtry_recv: dbgprintf("retrying gtls recv, nsd: %p\n", pNsd); CHKiRet(gtlsRecordRecv(pNsd)); pNsd->rtryCall = gtlsRtry_None; /* we are done */ gnuRet = 0; break; default: assert(0); /* this shall not happen! */ dbgprintf("ERROR: pNsd->rtryCall invalid in nsdsel_gtls.c:%d\n", __LINE__); gnuRet = 0; /* if it happens, we have at least a defined behaviour... ;) */ break; } if(gnuRet == 0) { pNsd->rtryCall = gtlsRtry_None; /* we are done */ } else if(gnuRet != GNUTLS_E_AGAIN && gnuRet != GNUTLS_E_INTERRUPTED) { uchar *pErr = gtlsStrerror(gnuRet); dbgprintf("unexpected GnuTLS error %d in %s:%d: %s\n", gnuRet, __FILE__, __LINE__, pErr); free(pErr); pNsd->rtryCall = gtlsRtry_None; /* we are also done... ;) */ ABORT_FINALIZE(RS_RET_GNUTLS_ERR); } /* if we are interrupted once again (else case), we do not need to * change our status because we are already setup for retries. */ finalize_it: if(iRet != RS_RET_OK && iRet != RS_RET_CLOSED && iRet != RS_RET_RETRY) pNsd->bAbortConn = 1; /* request abort */ dbgprintf("XXXXXX: doRetry: iRet %d, pNsd->bAbortConn %d\n", iRet, pNsd->bAbortConn); RETiRet; } /* check if a socket is ready for IO */ static rsRetVal IsReady(nsdsel_t *pNsdsel, nsd_t *pNsd, nsdsel_waitOp_t waitOp, int *pbIsReady) { DEFiRet; nsdsel_gtls_t *pThis = (nsdsel_gtls_t*) pNsdsel; nsd_gtls_t *pNsdGTLS = (nsd_gtls_t*) pNsd; ISOBJ_TYPE_assert(pThis, nsdsel_gtls); ISOBJ_TYPE_assert(pNsdGTLS, nsd_gtls); if(pNsdGTLS->iMode == 1) { if(waitOp == NSDSEL_RD && gtlsHasRcvInBuffer(pNsdGTLS)) { *pbIsReady = 1; --pThis->iBufferRcvReady; /* one "pseudo-read" less */ dbgprintf("nsdl_gtls: dummy read, decermenting %p->iBufRcvReady, now %d\n", pThis, pThis->iBufferRcvReady); FINALIZE; } if(pNsdGTLS->rtryCall != gtlsRtry_None) { CHKiRet(doRetry(pNsdGTLS)); /* we used this up for our own internal processing, so the socket * is not ready from the upper layer point of view. */ *pbIsReady = 0; FINALIZE; } /* now we must ensure that we do not fall back to PTCP if we have * done a "dummy" select. In that case, we know when the predicate * is not matched here, we do not have data available for this * socket. -- rgerhards, 2010-11-20 */ if(pThis->iBufferRcvReady) { dbgprintf("nsd_gtls: dummy read, buffer not available for this FD\n"); *pbIsReady = 0; FINALIZE; } } CHKiRet(nsdsel_ptcp.IsReady(pThis->pTcp, pNsdGTLS->pTcp, waitOp, pbIsReady)); finalize_it: RETiRet; } /* ------------------------------ end support for the select() interface ------------------------------ */ /* queryInterface function */ BEGINobjQueryInterface(nsdsel_gtls) CODESTARTobjQueryInterface(nsdsel_gtls) if(pIf->ifVersion != nsdCURR_IF_VERSION) {/* check for current version, increment on each change */ ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED); } /* ok, we have the right interface, so let's fill it * Please note that we may also do some backwards-compatibility * work here (if we can support an older interface version - that, * of course, also affects the "if" above). */ pIf->Construct = (rsRetVal(*)(nsdsel_t**)) nsdsel_gtlsConstruct; pIf->Destruct = (rsRetVal(*)(nsdsel_t**)) nsdsel_gtlsDestruct; pIf->Add = Add; pIf->Select = Select; pIf->IsReady = IsReady; finalize_it: ENDobjQueryInterface(nsdsel_gtls) /* exit our class */ BEGINObjClassExit(nsdsel_gtls, OBJ_IS_CORE_MODULE) /* CHANGE class also in END MACRO! */ CODESTARTObjClassExit(nsdsel_gtls) /* release objects we no longer need */ objRelease(glbl, CORE_COMPONENT); objRelease(errmsg, CORE_COMPONENT); objRelease(nsdsel_ptcp, LM_NSD_PTCP_FILENAME); ENDObjClassExit(nsdsel_gtls) /* Initialize the nsdsel_gtls class. Must be called as the very first method * before anything else is called inside this class. * rgerhards, 2008-02-19 */ BEGINObjClassInit(nsdsel_gtls, 1, OBJ_IS_CORE_MODULE) /* class, version */ /* request objects we use */ CHKiRet(objUse(errmsg, CORE_COMPONENT)); CHKiRet(objUse(glbl, CORE_COMPONENT)); CHKiRet(objUse(nsdsel_ptcp, LM_NSD_PTCP_FILENAME)); /* set our own handlers */ ENDObjClassInit(nsdsel_gtls) /* vi:set ai: */
rngadam/rsyslog
runtime/nsdsel_gtls.c
C
gpl-3.0
8,384
/*************************************************************************** * Copyright (C) 2010 by H-Store Project * * Brown University * * Massachusetts Institute of Technology * * Yale University * * * * Written by: * * Andy Pavlo ([email protected]) * * http://www.cs.brown.edu/~pavlo/ * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be * * included in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * * OTHER DEALINGS IN THE SOFTWARE. * ***************************************************************************/ package edu.brown.benchmark.mapreduce; import java.io.*; import java.util.*; import org.json.*; import org.voltdb.utils.Pair; import edu.brown.rand.AbstractRandomGenerator; import edu.brown.rand.RandomDistribution; import edu.brown.statistics.ObjectHistogram; import edu.brown.utils.*; /** * * @author pavlo * */ public class RandomGenerator extends AbstractRandomGenerator implements JSONString { public enum AffinityRecordMembers { MINIMUM, MAXIMUM, MAP, SIGMA, } /** * Table Name -> Affinity Record */ protected final SortedMap<Pair<String, String>, AffinityRecord> affinity_map = new TreeMap<Pair<String, String>, AffinityRecord>(); protected final transient SortedMap<String, Set<Pair<String, String>>> table_pair_xref = new TreeMap<String, Set<Pair<String,String>>>(); /** * */ protected class AffinityRecord { private final SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); private final transient SortedMap<Integer, RandomDistribution.Zipf> distributions = new TreeMap<Integer, RandomDistribution.Zipf>(); private double zipf_sigma = 1.01d; private int minimum; private int maximum; private transient int range; private final transient SortedMap<Integer, ObjectHistogram> histograms = new TreeMap<Integer, ObjectHistogram>(); public AffinityRecord() { // For serialization... } public AffinityRecord(int minimum, int maximum) { this.minimum = minimum; this.maximum = maximum; this.range = this.maximum - this.minimum; } public double getZipfSigma() { return (this.zipf_sigma); } public void setZipfSigma(double zipf_sigma) { // We have to regenerate all the random number generators if (this.zipf_sigma != zipf_sigma) { this.zipf_sigma = zipf_sigma; for (int source : this.map.keySet()) { int target = this.map.get(source); this.distributions.put(source, new RandomDistribution.Zipf(RandomGenerator.this, target, target + this.range, this.zipf_sigma)); } // FOR } } public int getMinimum() { return (this.minimum); } public int getMaximum() { return (this.maximum); } public Set<Integer> getSources() { return (this.map.keySet()); } public int getTarget(int source) { return (this.map.get(source)); } public RandomDistribution.Zipf getDistribution(int source) { return (this.distributions.get(source)); } public ObjectHistogram getHistogram(int source) { return (this.histograms.get(source)); } public void add(int source, int target) { this.map.put(source, target); this.distributions.put(source, new RandomDistribution.Zipf(RandomGenerator.this, target, target + this.range, this.zipf_sigma)); this.histograms.put(source, new ObjectHistogram()); } public void toJSONString(JSONStringer stringer) throws JSONException { stringer.key(AffinityRecordMembers.SIGMA.name()).value(this.zipf_sigma); stringer.key(AffinityRecordMembers.MINIMUM.name()).value(this.minimum); stringer.key(AffinityRecordMembers.MAXIMUM.name()).value(this.maximum); stringer.key(AffinityRecordMembers.MAP.name()).object(); for (Integer source_id : this.map.keySet()) { stringer.key(source_id.toString()).value(this.map.get(source_id)); } // FOR stringer.endObject(); } public void fromJSONObject(JSONObject object) throws JSONException { this.zipf_sigma = object.getDouble(AffinityRecordMembers.SIGMA.name()); this.minimum = object.getInt(AffinityRecordMembers.MINIMUM.name()); this.maximum = object.getInt(AffinityRecordMembers.MAXIMUM.name()); this.range = this.maximum - this.minimum; JSONObject jsonMap = object.getJSONObject(AffinityRecordMembers.MAP.name()); Iterator<String> i = jsonMap.keys(); while (i.hasNext()) { String key = i.next(); Integer source = Integer.parseInt(key); Integer target = jsonMap.getInt(key); assert(source != null); assert(target != null); this.add(source, target); } // WHILE } @Override public String toString() { StringBuilder buffer = new StringBuilder(); for (int source : this.map.keySet()) { int target = this.map.get(source); buffer.append(source).append(" => ").append(target).append("\n"); buffer.append(this.histograms.get(source)).append("\n-------------\n"); } // FOR return (buffer.toString()); } } // END CLASS /** * Seeds the random number generator using the default Random() constructor. */ public RandomGenerator() { super(0); } /** * Seeds the random number generator with seed. * @param seed */ public RandomGenerator(Integer seed) { super(seed); } /** * Set the Zipfian distribution sigma factor * @param zipf_sigma */ public void setZipfSigma(String table, double zipf_sigma) { assert(this.affinity_map.containsKey(table)); this.affinity_map.get(table).setZipfSigma(zipf_sigma); } private void addAffinityRecord(Pair<String, String> pair, AffinityRecord record) { this.affinity_map.put(pair, record); if (!this.table_pair_xref.containsKey(pair.getFirst())) { this.table_pair_xref.put(pair.getFirst(), new HashSet<Pair<String, String>>()); } this.table_pair_xref.get(pair.getFirst()).add(pair); } /** * Sets the affinity preference of a source value to a target * @param source_id * @param target_id */ public void addAffinity(String source_table, int source_id, String target_table, int target_id, int minimum, int maximum) { assert(minimum <= target_id) : "Min check failed (" + minimum + " <= " + target_id + ")"; assert(maximum >= target_id); Pair<String, String> pair = Pair.of(source_table, target_table); AffinityRecord record = this.affinity_map.get(pair); if (record == null) { record = new AffinityRecord(minimum, maximum); } else { assert(this.affinity_map.get(pair).getMinimum() == minimum); assert(this.affinity_map.get(pair).getMaximum() == maximum); } record.add(source_id, target_id); this.addAffinityRecord(pair, record); } /** * Return all the tables that we have a record for * @return */ public Set<String> getTables() { return (this.table_pair_xref.keySet()); } public Set<Pair<String, String>> getTables(String source_table) { return (this.table_pair_xref.get(source_table)); } public Integer getTarget(String source_table, int source_id, String target_table) { Pair<String, String> pair = Pair.of(source_table, target_table); AffinityRecord record = this.affinity_map.get(pair); return (record != null ? record.getTarget(source_id) : null); } /** * * @param record * @param source_id * @param exclude_base * @return */ private int nextInt(AffinityRecord record, int source_id, boolean exclude_base) { RandomDistribution.Zipf zipf = record.getDistribution(source_id); assert(zipf != null); int value = zipf.nextInt(); int max = record.getMaximum(); if (exclude_base) { long range_start = record.getTarget((int)zipf.getMin()); if (value >= range_start) value++; if (value > max) { value = (value % max) + 1; if (value == max) value--; } } else if (value > max) { value = (value % max) + 1; } record.getHistogram(source_id).put(value); return (value); } @Override public int numberAffinity(int minimum, int maximum, int base, String source_table, String target_table) { Pair<String, String> pair = Pair.of(source_table, target_table); AffinityRecord record = this.affinity_map.get(pair); int value; /* System.out.println("min=" + minimum); System.out.println("max=" + maximum); System.out.println("base=" + base); System.out.println("table=" + table); System.out.println("record=" + (record != null)); System.exit(1); */ // Use an AffinityRecord to generate next number if (record != null && record.getDistribution(base) != null) { value = this.nextInt(record, base, false); // Otherwise, just use the default random number generator } else { value = super.number(minimum, maximum); } return (value); } /** * Generate an affinity-skewed random number that excludes the number given */ @Override public int numberExcluding(int minimum, int maximum, int excluding, String source_table, String target_table) { Pair<String, String> pair = Pair.of(source_table, target_table); AffinityRecord record = this.affinity_map.get(pair); int value; // Use an AffinityRecord to generate next number if (record != null && record.getDistribution(excluding) != null) { value = this.nextInt(record, excluding, true); // Otherwise, just use the default random number generator } else { value = super.numberExcluding(minimum, maximum, excluding); } return (value); } /** * */ @Override public void loadProfile(String input_path) throws Exception { String contents = FileUtil.readFile(input_path); if (contents.isEmpty()) { throw new Exception("The partition plan file '" + input_path + "' is empty"); } JSONObject jsonObject = new JSONObject(contents); System.out.println(jsonObject.toString(2)); this.fromJSONObject(jsonObject); } /** * * @param output_path * @throws Exception */ @Override public void saveProfile(String output_path) throws Exception { String json = this.toJSONString(); JSONObject jsonObject = new JSONObject(json); FileOutputStream out = new FileOutputStream(output_path); out.write(jsonObject.toString(2).getBytes()); out.close(); } @Override public String toJSONString() { JSONStringer stringer = new JSONStringer(); try { stringer.object(); this.toJSONString(stringer); stringer.endObject(); } catch (JSONException e) { e.printStackTrace(); System.exit(-1); } return stringer.toString(); } public void toJSONString(JSONStringer stringer) throws JSONException { for (String source_table : this.getTables()) { stringer.key(source_table).object(); for (Pair<String, String> pair : this.getTables(source_table)) { stringer.key(pair.getSecond()).object(); this.affinity_map.get(pair).toJSONString(stringer); stringer.endObject(); } // FOR stringer.endObject(); } // FOR } public void fromJSONObject(JSONObject object) throws JSONException { Iterator<String> i = object.keys(); while (i.hasNext()) { String source_table = i.next(); JSONObject innerObject = object.getJSONObject(source_table); Iterator<String> j = innerObject.keys(); while (j.hasNext()) { String target_table = j.next(); Pair<String, String> pair = Pair.of(source_table, target_table); AffinityRecord record = new AffinityRecord(); record.fromJSONObject(innerObject.getJSONObject(target_table)); this.addAffinityRecord(pair, record); } // WHILE } // WHILE } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(this.getClass().getSimpleName()).append("\n"); for (String source_table : this.getTables()) { for (Pair<String, String> pair : this.getTables(source_table)) { buffer.append("TABLES: ").append(pair).append("\n"); buffer.append(this.affinity_map.get(pair)); } // FOR } // FOR return (buffer.toString()); } /** * Construct profile for TPC-C warehouses. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int minimum = 1; int num_warehouses = Integer.parseInt(args[0]); String output_path = args[1]; RandomGenerator rand = new RandomGenerator(); /** int half = (int)Math.ceil(num_warehouses / 2.0d); String table_name = Constants.TABLENAME_ORDERLINE; for (int ctr = minimum; ctr < half; ctr++) { int source = ctr; int target = ctr + half; rand.addAffinity(table_name, source, target, minimum, num_warehouses); rand.addAffinity(table_name, target, source, minimum, num_warehouses); } // FOR if ((half - minimum) % 2 == 1) { rand.addAffinity(table_name, half, half, minimum, num_warehouses); } */ System.out.println(rand.toJSONString()); rand.saveProfile(output_path); System.out.println("Saved RandomGenerator profile to '" + output_path + "'"); } }
apavlo/h-store
src/benchmarks/edu/brown/benchmark/mapreduce/RandomGenerator.java
Java
gpl-3.0
16,682
<?php /***************************************************************************************** * EduSec Open Source Edition is a School / College management system developed by * RUDRA SOFTECH. Copyright (C) 2010-2015 RUDRA SOFTECH. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * You can contact RUDRA SOFTECH, 1st floor Geeta Ceramics, * Opp. Thakkarnagar BRTS station, Ahmedbad - 382350, India or * at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * RUDRA SOFTECH" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by RUDRA SOFTECH". *****************************************************************************************/ /** * StuInfoController implements the CRUD actions for StuInfo model. * * @package EduSec.modules.student.controllers */ namespace app\modules\student\controllers; use Yii; use app\modules\student\models\StuInfo; use app\modules\student\models\StuInfoSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; class StuInfoController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all StuInfo models. * @return mixed */ public function actionIndex() { $searchModel = new StuInfoSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single StuInfo model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new StuInfo model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new StuInfo(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->stu_info_id]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing StuInfo model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->stu_info_id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing StuInfo model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the StuInfo model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return StuInfo the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = StuInfo::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
EduSec/EduSec
modules/student/controllers/StuInfoController.php
PHP
gpl-3.0
4,922
using System; namespace Server.Items { public class MetallicLeatherDyeTub : LeatherDyeTub { public override CustomHuePicker CustomHuePicker{ get{ return null; } } public override int LabelNumber { get { return 1153495; } } // Metallic Leather ... public override bool MetallicHues { get { return true; } } [Constructable] public MetallicLeatherDyeTub() { LootType = LootType.Blessed; } public MetallicLeatherDyeTub( Serial serial ) : base( serial ) { } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( Core.ML && IsRewardItem ) list.Add( 1076221 ); // 5th Year Veteran Reward } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
GenerationOfWorlds/GOW
Scripts/Systems/Items/Management/Special/Veteran Rewards/Dyetubs/MetallicLeatherDyeTub.cs
C#
gpl-3.0
952
namespace GMap.NET { using System.Globalization; /// <summary> /// the point ;} /// </summary> public struct GPoint { public static readonly GPoint Empty = new GPoint(); private int x; private int y; public GPoint(int x, int y) { this.x = x; this.y = y; } public GPoint(GSize sz) { this.x = sz.Width; this.y = sz.Height; } public GPoint(int dw) { this.x = (short) LOWORD(dw); this.y = (short) HIWORD(dw); } public bool IsEmpty { get { return x == 0 && y == 0; } } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public static explicit operator GSize(GPoint p) { return new GSize(p.X, p.Y); } public static GPoint operator+(GPoint pt, GSize sz) { return Add(pt, sz); } public static GPoint operator-(GPoint pt, GSize sz) { return Subtract(pt, sz); } public static bool operator==(GPoint left, GPoint right) { return left.X == right.X && left.Y == right.Y; } public static bool operator!=(GPoint left, GPoint right) { return !(left == right); } public static GPoint Add(GPoint pt, GSize sz) { return new GPoint(pt.X + sz.Width, pt.Y + sz.Height); } public static GPoint Subtract(GPoint pt, GSize sz) { return new GPoint(pt.X - sz.Width, pt.Y - sz.Height); } public override bool Equals(object obj) { if(!(obj is GPoint)) return false; GPoint comp = (GPoint) obj; return comp.X == this.X && comp.Y == this.Y; } public override int GetHashCode() { return x ^ y; } public void Offset(int dx, int dy) { X += dx; Y += dy; } public void Offset(GPoint p) { Offset(p.X, p.Y); } public override string ToString() { return "{X=" + X.ToString(CultureInfo.CurrentCulture) + ",Y=" + Y.ToString(CultureInfo.CurrentCulture) + "}"; } private static int HIWORD(int n) { return (n >> 16) & 0xffff; } private static int LOWORD(int n) { return n & 0xffff; } } }
jlnaudin/x-drone
MissionPlanner-master/ExtLibs/GMap.NET.Core/GMap.NET/GPoint.cs
C#
gpl-3.0
2,636
# -*- coding: utf-8 -*- { 'name': "Partner Autocomplete", 'summary': """ Auto-complete partner companies' data""", 'description': """ Auto-complete partner companies' data """, 'author': "Odoo SA", 'category': 'Tools', 'version': '1.0', 'depends': ['web', 'mail', 'iap'], 'data': [ 'security/ir.model.access.csv', 'views/partner_autocomplete_assets.xml', 'views/additional_info_template.xml', 'views/res_partner_views.xml', 'views/res_company_views.xml', 'views/res_config_settings_views.xml', 'data/cron.xml', ], 'qweb': [ 'static/src/xml/partner_autocomplete.xml', ], 'auto_install': True, }
t3dev/odoo
addons/partner_autocomplete/__manifest__.py
Python
gpl-3.0
726
// Copyright (c) Hercules Dev Team, licensed under GNU GPL. // See the LICENSE file // Portions Copyright (c) Athena Dev Teams #define HERCULES_CORE #include "config/core.h" // SHOW_SERVER_STATS #include "socket.h" #include "common/HPM.h" #include "common/cbasetypes.h" #include "common/db.h" #include "common/malloc.h" #include "common/mmo.h" #include "common/nullpo.h" #include "common/showmsg.h" #include "common/strlib.h" #include "common/timer.h" #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #ifdef WIN32 # include "common/winapi.h" #else # include <arpa/inet.h> # include <errno.h> # include <net/if.h> # include <netdb.h> #if defined __linux__ || defined __linux # include <linux/tcp.h> #else # include <netinet/in.h> # include <netinet/tcp.h> #endif # include <sys/ioctl.h> # include <sys/socket.h> # include <sys/time.h> # include <unistd.h> # ifndef SIOCGIFCONF # include <sys/sockio.h> // SIOCGIFCONF on Solaris, maybe others? [Shinomori] # endif # ifndef FIONBIO # include <sys/filio.h> // FIONBIO on Solaris [FlavioJS] # endif # ifdef HAVE_SETRLIMIT # include <sys/resource.h> # endif #endif /** * Socket Interface Source **/ struct socket_interface sockt_s; struct socket_interface *sockt; struct socket_data **session; #ifdef SEND_SHORTLIST // Add a fd to the shortlist so that it'll be recognized as a fd that needs // sending done on it. void send_shortlist_add_fd(int fd); // Do pending network sends (and eof handling) from the shortlist. void send_shortlist_do_sends(); #endif ///////////////////////////////////////////////////////////////////// #if defined(WIN32) ///////////////////////////////////////////////////////////////////// // windows portability layer typedef int socklen_t; #define sErrno WSAGetLastError() #define S_ENOTSOCK WSAENOTSOCK #define S_EWOULDBLOCK WSAEWOULDBLOCK #define S_EINTR WSAEINTR #define S_ECONNABORTED WSAECONNABORTED #define SHUT_RD SD_RECEIVE #define SHUT_WR SD_SEND #define SHUT_RDWR SD_BOTH // global array of sockets (emulating linux) // fd is the position in the array static SOCKET sock_arr[FD_SETSIZE]; static int sock_arr_len = 0; /// Returns the socket associated with the target fd. /// /// @param fd Target fd. /// @return Socket #define fd2sock(fd) sock_arr[fd] /// Returns the first fd associated with the socket. /// Returns -1 if the socket is not found. /// /// @param s Socket /// @return Fd or -1 int sock2fd(SOCKET s) { int fd; // search for the socket for( fd = 1; fd < sock_arr_len; ++fd ) if( sock_arr[fd] == s ) break;// found the socket if( fd == sock_arr_len ) return -1;// not found return fd; } /// Inserts the socket into the global array of sockets. /// Returns a new fd associated with the socket. /// If there are too many sockets it closes the socket, sets an error and // returns -1 instead. /// Since fd 0 is reserved, it returns values in the range [1,FD_SETSIZE[. /// /// @param s Socket /// @return New fd or -1 int sock2newfd(SOCKET s) { int fd; // find an empty position for( fd = 1; fd < sock_arr_len; ++fd ) if( sock_arr[fd] == INVALID_SOCKET ) break;// empty position if( fd == ARRAYLENGTH(sock_arr) ) {// too many sockets closesocket(s); WSASetLastError(WSAEMFILE); return -1; } sock_arr[fd] = s; if( sock_arr_len <= fd ) sock_arr_len = fd+1; return fd; } int sAccept(int fd, struct sockaddr* addr, int* addrlen) { SOCKET s; // accept connection s = accept(fd2sock(fd), addr, addrlen); if( s == INVALID_SOCKET ) return -1;// error return sock2newfd(s); } int sClose(int fd) { int ret = closesocket(fd2sock(fd)); fd2sock(fd) = INVALID_SOCKET; return ret; } int sSocket(int af, int type, int protocol) { SOCKET s; // create socket s = socket(af,type,protocol); if( s == INVALID_SOCKET ) return -1;// error return sock2newfd(s); } char* sErr(int code) { static char sbuf[512]; // strerror does not handle socket codes if( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPTSTR)&sbuf, sizeof(sbuf), NULL) == 0 ) snprintf(sbuf, sizeof(sbuf), "unknown error"); return sbuf; } #define sBind(fd,name,namelen) bind(fd2sock(fd),(name),(namelen)) #define sConnect(fd,name,namelen) connect(fd2sock(fd),(name),(namelen)) #define sIoctl(fd,cmd,argp) ioctlsocket(fd2sock(fd),(cmd),(argp)) #define sListen(fd,backlog) listen(fd2sock(fd),(backlog)) #define sRecv(fd,buf,len,flags) recv(fd2sock(fd),(buf),(len),(flags)) #define sSelect select #define sSend(fd,buf,len,flags) send(fd2sock(fd),(buf),(len),(flags)) #define sSetsockopt(fd,level,optname,optval,optlen) setsockopt(fd2sock(fd),(level),(optname),(optval),(optlen)) #define sShutdown(fd,how) shutdown(fd2sock(fd),(how)) #define sFD_SET(fd,set) FD_SET(fd2sock(fd),(set)) #define sFD_CLR(fd,set) FD_CLR(fd2sock(fd),(set)) #define sFD_ISSET(fd,set) FD_ISSET(fd2sock(fd),(set)) #define sFD_ZERO FD_ZERO ///////////////////////////////////////////////////////////////////// #else ///////////////////////////////////////////////////////////////////// // nix portability layer #define SOCKET_ERROR (-1) #define sErrno errno #define S_ENOTSOCK EBADF #define S_EWOULDBLOCK EAGAIN #define S_EINTR EINTR #define S_ECONNABORTED ECONNABORTED #define sAccept accept #define sClose close #define sSocket socket #define sErr strerror #define sBind bind #define sConnect connect #define sIoctl ioctl #define sListen listen #define sRecv recv #define sSelect select #define sSend send #define sSetsockopt setsockopt #define sShutdown shutdown #define sFD_SET FD_SET #define sFD_CLR FD_CLR #define sFD_ISSET FD_ISSET #define sFD_ZERO FD_ZERO ///////////////////////////////////////////////////////////////////// #endif ///////////////////////////////////////////////////////////////////// #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif fd_set readfds; // Maximum packet size in bytes, which the client is able to handle. // Larger packets cause a buffer overflow and stack corruption. static size_t socket_max_client_packet = 24576; #ifdef SHOW_SERVER_STATS // Data I/O statistics static size_t socket_data_i = 0, socket_data_ci = 0, socket_data_qi = 0; static size_t socket_data_o = 0, socket_data_co = 0, socket_data_qo = 0; static time_t socket_data_last_tick = 0; #endif // initial recv buffer size (this will also be the max. size) // biggest known packet: S 0153 <len>.w <emblem data>.?B -> 24x24 256 color .bmp (0153 + len.w + 1618/1654/1756 bytes) #define RFIFO_SIZE (2*1024) // initial send buffer size (will be resized as needed) #define WFIFO_SIZE (16*1024) // Maximum size of pending data in the write fifo. (for non-server connections) // The connection is closed if it goes over the limit. #define WFIFO_MAX (1*1024*1024) #ifdef SEND_SHORTLIST int send_shortlist_array[FD_SETSIZE];// we only support FD_SETSIZE sockets, limit the array to that int send_shortlist_count = 0;// how many fd's are in the shortlist uint32 send_shortlist_set[(FD_SETSIZE+31)/32];// to know if specific fd's are already in the shortlist #endif static int create_session(int fd, RecvFunc func_recv, SendFunc func_send, ParseFunc func_parse); #ifndef MINICORE int ip_rules = 1; static int connect_check(uint32 ip); #endif const char* error_msg(void) { static char buf[512]; int code = sErrno; snprintf(buf, sizeof(buf), "error %d: %s", code, sErr(code)); return buf; } /*====================================== * CORE : Default processing functions *--------------------------------------*/ int null_recv(int fd) { return 0; } int null_send(int fd) { return 0; } int null_parse(int fd) { return 0; } ParseFunc default_func_parse = null_parse; void set_defaultparse(ParseFunc defaultparse) { default_func_parse = defaultparse; } /*====================================== * CORE : Socket options *--------------------------------------*/ void set_nonblocking(int fd, unsigned long yes) { // FIONBIO Use with a nonzero argp parameter to enable the nonblocking mode of socket s. // The argp parameter is zero if nonblocking is to be disabled. if( sIoctl(fd, FIONBIO, &yes) != 0 ) ShowError("set_nonblocking: Failed to set socket #%d to non-blocking mode (%s) - Please report this!!!\n", fd, error_msg()); } void setsocketopts(int fd, struct hSockOpt *opt) { int yes = 1; // reuse fix struct linger lopt; #if !defined(WIN32) // set SO_REAUSEADDR to true, unix only. on windows this option causes // the previous owner of the socket to give up, which is not desirable // in most cases, neither compatible with unix. if (sSetsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char *)&yes,sizeof(yes))) ShowWarning("setsocketopts: Unable to set SO_REUSEADDR mode for connection #%d!\n", fd); #ifdef SO_REUSEPORT if (sSetsockopt(fd,SOL_SOCKET,SO_REUSEPORT,(char *)&yes,sizeof(yes))) ShowWarning("setsocketopts: Unable to set SO_REUSEPORT mode for connection #%d!\n", fd); #endif // SO_REUSEPORT #endif // WIN32 // Set the socket into no-delay mode; otherwise packets get delayed for up to 200ms, likely creating server-side lag. // The RO protocol is mainly single-packet request/response, plus the FIFO model already does packet grouping anyway. if (sSetsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&yes, sizeof(yes))) ShowWarning("setsocketopts: Unable to set TCP_NODELAY mode for connection #%d!\n", fd); if( opt && opt->setTimeo ) { struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; if (sSetsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(timeout))) ShowWarning("setsocketopts: Unable to set SO_RCVTIMEO for connection #%d!\n", fd); if (sSetsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(timeout))) ShowWarning("setsocketopts: Unable to set SO_SNDTIMEO for connection #%d!\n", fd); } // force the socket into no-wait, graceful-close mode (should be the default, but better make sure) //(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/closesocket_2.asp) lopt.l_onoff = 0; // SO_DONTLINGER lopt.l_linger = 0; // Do not care if( sSetsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&lopt, sizeof(lopt)) ) ShowWarning("setsocketopts: Unable to set SO_LINGER mode for connection #%d!\n", fd); #ifdef TCP_THIN_LINEAR_TIMEOUTS if (sSetsockopt(fd, IPPROTO_TCP, TCP_THIN_LINEAR_TIMEOUTS, (char *)&yes, sizeof(yes))) ShowWarning("setsocketopts: Unable to set TCP_THIN_LINEAR_TIMEOUTS mode for connection #%d!\n", fd); #endif #ifdef TCP_THIN_DUPACK if (sSetsockopt(fd, IPPROTO_TCP, TCP_THIN_DUPACK, (char *)&yes, sizeof(yes))) ShowWarning("setsocketopts: Unable to set TCP_THIN_DUPACK mode for connection #%d!\n", fd); #endif } /*====================================== * CORE : Socket Sub Function *--------------------------------------*/ void set_eof(int fd) { if (sockt->session_is_active(fd)) { #ifdef SEND_SHORTLIST // Add this socket to the shortlist for eof handling. send_shortlist_add_fd(fd); #endif sockt->session[fd]->flag.eof = 1; } } int recv_to_fifo(int fd) { ssize_t len; if (!sockt->session_is_active(fd)) return -1; len = sRecv(fd, (char *) sockt->session[fd]->rdata + sockt->session[fd]->rdata_size, (int)RFIFOSPACE(fd), 0); if( len == SOCKET_ERROR ) {//An exception has occurred if( sErrno != S_EWOULDBLOCK ) { //ShowDebug("recv_to_fifo: %s, closing connection #%d\n", error_msg(), fd); sockt->eof(fd); } return 0; } if( len == 0 ) {//Normal connection end. sockt->eof(fd); return 0; } sockt->session[fd]->rdata_size += len; sockt->session[fd]->rdata_tick = sockt->last_tick; #ifdef SHOW_SERVER_STATS socket_data_i += len; socket_data_qi += len; if (!sockt->session[fd]->flag.server) { socket_data_ci += len; } #endif return 0; } int send_from_fifo(int fd) { ssize_t len; if (!sockt->session_is_valid(fd)) return -1; if( sockt->session[fd]->wdata_size == 0 ) return 0; // nothing to send len = sSend(fd, (const char *) sockt->session[fd]->wdata, (int)sockt->session[fd]->wdata_size, MSG_NOSIGNAL); if( len == SOCKET_ERROR ) {//An exception has occurred if( sErrno != S_EWOULDBLOCK ) { //ShowDebug("send_from_fifo: %s, ending connection #%d\n", error_msg(), fd); #ifdef SHOW_SERVER_STATS socket_data_qo -= sockt->session[fd]->wdata_size; #endif sockt->session[fd]->wdata_size = 0; //Clear the send queue as we can't send anymore. [Skotlex] sockt->eof(fd); } return 0; } if( len > 0 ) { // some data could not be transferred? // shift unsent data to the beginning of the queue if( (size_t)len < sockt->session[fd]->wdata_size ) memmove(sockt->session[fd]->wdata, sockt->session[fd]->wdata + len, sockt->session[fd]->wdata_size - len); sockt->session[fd]->wdata_size -= len; #ifdef SHOW_SERVER_STATS socket_data_o += len; socket_data_qo -= len; if (!sockt->session[fd]->flag.server) { socket_data_co += len; } #endif } return 0; } /// Best effort - there's no warranty that the data will be sent. void flush_fifo(int fd) { if(sockt->session[fd] != NULL) sockt->session[fd]->func_send(fd); } void flush_fifos(void) { int i; for(i = 1; i < sockt->fd_max; i++) sockt->flush(i); } /*====================================== * CORE : Connection functions *--------------------------------------*/ int connect_client(int listen_fd) { int fd; struct sockaddr_in client_address; socklen_t len; len = sizeof(client_address); fd = sAccept(listen_fd, (struct sockaddr*)&client_address, &len); if ( fd == -1 ) { ShowError("connect_client: accept failed (%s)!\n", error_msg()); return -1; } if( fd == 0 ) { // reserved ShowError("connect_client: Socket #0 is reserved - Please report this!!!\n"); sClose(fd); return -1; } if( fd >= FD_SETSIZE ) { // socket number too big ShowError("connect_client: New socket #%d is greater than can we handle! Increase the value of FD_SETSIZE (currently %d) for your OS to fix this!\n", fd, FD_SETSIZE); sClose(fd); return -1; } setsocketopts(fd,NULL); sockt->set_nonblocking(fd, 1); #ifndef MINICORE if( ip_rules && !connect_check(ntohl(client_address.sin_addr.s_addr)) ) { sockt->close(fd); return -1; } #endif if( sockt->fd_max <= fd ) sockt->fd_max = fd + 1; sFD_SET(fd,&readfds); create_session(fd, recv_to_fifo, send_from_fifo, default_func_parse); sockt->session[fd]->client_addr = ntohl(client_address.sin_addr.s_addr); return fd; } int make_listen_bind(uint32 ip, uint16 port) { struct sockaddr_in server_address = { 0 }; int fd; int result; fd = sSocket(AF_INET, SOCK_STREAM, 0); if( fd == -1 ) { ShowError("make_listen_bind: socket creation failed (%s)!\n", error_msg()); exit(EXIT_FAILURE); } if( fd == 0 ) { // reserved ShowError("make_listen_bind: Socket #0 is reserved - Please report this!!!\n"); sClose(fd); return -1; } if( fd >= FD_SETSIZE ) { // socket number too big ShowError("make_listen_bind: New socket #%d is greater than can we handle! Increase the value of FD_SETSIZE (currently %d) for your OS to fix this!\n", fd, FD_SETSIZE); sClose(fd); return -1; } setsocketopts(fd,NULL); sockt->set_nonblocking(fd, 1); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(ip); server_address.sin_port = htons(port); result = sBind(fd, (struct sockaddr*)&server_address, sizeof(server_address)); if( result == SOCKET_ERROR ) { ShowError("make_listen_bind: bind failed (socket #%d, %s)!\n", fd, error_msg()); exit(EXIT_FAILURE); } result = sListen(fd,5); if( result == SOCKET_ERROR ) { ShowError("make_listen_bind: listen failed (socket #%d, %s)!\n", fd, error_msg()); exit(EXIT_FAILURE); } if(sockt->fd_max <= fd) sockt->fd_max = fd + 1; sFD_SET(fd, &readfds); create_session(fd, connect_client, null_send, null_parse); sockt->session[fd]->client_addr = 0; // just listens sockt->session[fd]->rdata_tick = 0; // disable timeouts on this socket return fd; } int make_connection(uint32 ip, uint16 port, struct hSockOpt *opt) { struct sockaddr_in remote_address = { 0 }; int fd; int result; fd = sSocket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { ShowError("make_connection: socket creation failed (%s)!\n", error_msg()); return -1; } if( fd == 0 ) {// reserved ShowError("make_connection: Socket #0 is reserved - Please report this!!!\n"); sClose(fd); return -1; } if( fd >= FD_SETSIZE ) {// socket number too big ShowError("make_connection: New socket #%d is greater than can we handle! Increase the value of FD_SETSIZE (currently %d) for your OS to fix this!\n", fd, FD_SETSIZE); sClose(fd); return -1; } setsocketopts(fd,opt); remote_address.sin_family = AF_INET; remote_address.sin_addr.s_addr = htonl(ip); remote_address.sin_port = htons(port); if( !( opt && opt->silent ) ) ShowStatus("Connecting to %d.%d.%d.%d:%i\n", CONVIP(ip), port); result = sConnect(fd, (struct sockaddr *)(&remote_address), sizeof(struct sockaddr_in)); if( result == SOCKET_ERROR ) { if( !( opt && opt->silent ) ) ShowError("make_connection: connect failed (socket #%d, %s)!\n", fd, error_msg()); sockt->close(fd); return -1; } //Now the socket can be made non-blocking. [Skotlex] sockt->set_nonblocking(fd, 1); if (sockt->fd_max <= fd) sockt->fd_max = fd + 1; sFD_SET(fd,&readfds); create_session(fd, recv_to_fifo, send_from_fifo, default_func_parse); sockt->session[fd]->client_addr = ntohl(remote_address.sin_addr.s_addr); return fd; } static int create_session(int fd, RecvFunc func_recv, SendFunc func_send, ParseFunc func_parse) { CREATE(sockt->session[fd], struct socket_data, 1); CREATE(sockt->session[fd]->rdata, unsigned char, RFIFO_SIZE); CREATE(sockt->session[fd]->wdata, unsigned char, WFIFO_SIZE); sockt->session[fd]->max_rdata = RFIFO_SIZE; sockt->session[fd]->max_wdata = WFIFO_SIZE; sockt->session[fd]->func_recv = func_recv; sockt->session[fd]->func_send = func_send; sockt->session[fd]->func_parse = func_parse; sockt->session[fd]->rdata_tick = sockt->last_tick; sockt->session[fd]->session_data = NULL; sockt->session[fd]->hdata = NULL; sockt->session[fd]->hdatac = 0; return 0; } static void delete_session(int fd) { if (sockt->session_is_valid(fd)) { #ifdef SHOW_SERVER_STATS socket_data_qi -= sockt->session[fd]->rdata_size - sockt->session[fd]->rdata_pos; socket_data_qo -= sockt->session[fd]->wdata_size; #endif aFree(sockt->session[fd]->rdata); aFree(sockt->session[fd]->wdata); if( sockt->session[fd]->session_data ) aFree(sockt->session[fd]->session_data); if (sockt->session[fd]->hdata) { unsigned int i; for(i = 0; i < sockt->session[fd]->hdatac; i++) { if( sockt->session[fd]->hdata[i]->flag.free ) { aFree(sockt->session[fd]->hdata[i]->data); } aFree(sockt->session[fd]->hdata[i]); } aFree(sockt->session[fd]->hdata); } aFree(sockt->session[fd]); sockt->session[fd] = NULL; } } int realloc_fifo(int fd, unsigned int rfifo_size, unsigned int wfifo_size) { if (!sockt->session_is_valid(fd)) return 0; if( sockt->session[fd]->max_rdata != rfifo_size && sockt->session[fd]->rdata_size < rfifo_size) { RECREATE(sockt->session[fd]->rdata, unsigned char, rfifo_size); sockt->session[fd]->max_rdata = rfifo_size; } if( sockt->session[fd]->max_wdata != wfifo_size && sockt->session[fd]->wdata_size < wfifo_size) { RECREATE(sockt->session[fd]->wdata, unsigned char, wfifo_size); sockt->session[fd]->max_wdata = wfifo_size; } return 0; } int realloc_writefifo(int fd, size_t addition) { size_t newsize; if (!sockt->session_is_valid(fd)) // might not happen return 0; if (sockt->session[fd]->wdata_size + addition > sockt->session[fd]->max_wdata) { // grow rule; grow in multiples of WFIFO_SIZE newsize = WFIFO_SIZE; while( sockt->session[fd]->wdata_size + addition > newsize ) newsize += WFIFO_SIZE; } else if (sockt->session[fd]->max_wdata >= (size_t)2*(sockt->session[fd]->flag.server?FIFOSIZE_SERVERLINK:WFIFO_SIZE) && (sockt->session[fd]->wdata_size+addition)*4 < sockt->session[fd]->max_wdata ) { // shrink rule, shrink by 2 when only a quarter of the fifo is used, don't shrink below nominal size. newsize = sockt->session[fd]->max_wdata / 2; } else { // no change return 0; } RECREATE(sockt->session[fd]->wdata, unsigned char, newsize); sockt->session[fd]->max_wdata = newsize; return 0; } /// advance the RFIFO cursor (marking 'len' bytes as processed) int rfifoskip(int fd, size_t len) { struct socket_data *s; if (!sockt->session_is_active(fd)) return 0; s = sockt->session[fd]; if (s->rdata_size < s->rdata_pos + len) { ShowError("RFIFOSKIP: skipped past end of read buffer! Adjusting from %"PRIuS" to %"PRIuS" (session #%d)\n", len, RFIFOREST(fd), fd); len = RFIFOREST(fd); } s->rdata_pos = s->rdata_pos + len; #ifdef SHOW_SERVER_STATS socket_data_qi -= len; #endif return 0; } /// advance the WFIFO cursor (marking 'len' bytes for sending) int wfifoset(int fd, size_t len) { size_t newreserve; struct socket_data* s = sockt->session[fd]; if (!sockt->session_is_valid(fd) || s->wdata == NULL) return 0; // we have written len bytes to the buffer already before calling WFIFOSET if (s->wdata_size+len > s->max_wdata) { // actually there was a buffer overflow already uint32 ip = s->client_addr; ShowFatalError("WFIFOSET: Write Buffer Overflow. Connection %d (%d.%d.%d.%d) has written %u bytes on a %u/%u bytes buffer.\n", fd, CONVIP(ip), (unsigned int)len, (unsigned int)s->wdata_size, (unsigned int)s->max_wdata); ShowDebug("Likely command that caused it: 0x%x\n", (*(uint16*)(s->wdata + s->wdata_size))); // no other chance, make a better fifo model exit(EXIT_FAILURE); } if( len > 0xFFFF ) { // dynamic packets allow up to UINT16_MAX bytes (<packet_id>.W <packet_len>.W ...) // all known fixed-size packets are within this limit, so use the same limit ShowFatalError("WFIFOSET: Packet 0x%x is too big. (len=%u, max=%u)\n", (*(uint16*)(s->wdata + s->wdata_size)), (unsigned int)len, 0xFFFF); exit(EXIT_FAILURE); } else if( len == 0 ) { // abuses the fact, that the code that did WFIFOHEAD(fd,0), already wrote // the packet type into memory, even if it could have overwritten vital data // this can happen when a new packet was added on map-server, but packet len table was not updated ShowWarning("WFIFOSET: Attempted to send zero-length packet, most likely 0x%04x (please report this).\n", WFIFOW(fd,0)); return 0; } if( !s->flag.server ) { if (len > socket_max_client_packet) { // see declaration of socket_max_client_packet for details ShowError("WFIFOSET: Dropped too large client packet 0x%04x (length=%"PRIuS", max=%"PRIuS").\n", WFIFOW(fd,0), len, socket_max_client_packet); return 0; } } s->wdata_size += len; #ifdef SHOW_SERVER_STATS socket_data_qo += len; #endif //If the interserver has 200% of its normal size full, flush the data. if( s->flag.server && s->wdata_size >= 2*FIFOSIZE_SERVERLINK ) sockt->flush(fd); // always keep a WFIFO_SIZE reserve in the buffer // For inter-server connections, let the reserve be 1/4th of the link size. newreserve = s->flag.server ? FIFOSIZE_SERVERLINK / 4 : WFIFO_SIZE; // readjust the buffer to include the chosen reserve sockt->realloc_writefifo(fd, newreserve); #ifdef SEND_SHORTLIST send_shortlist_add_fd(fd); #endif return 0; } int do_sockets(int next) { fd_set rfd; struct timeval timeout; int ret,i; // PRESEND Timers are executed before do_sendrecv and can send packets and/or set sessions to eof. // Send remaining data and process client-side disconnects here. #ifdef SEND_SHORTLIST send_shortlist_do_sends(); #else for (i = 1; i < sockt->fd_max; i++) { if(!sockt->session[fd] continue; if(sockt->session[fd]>wdata_size) sockt->session[fd]>func_send(i); } #endif // can timeout until the next tick timeout.tv_sec = next/1000; timeout.tv_usec = next%1000*1000; memcpy(&rfd, &readfds, sizeof(rfd)); ret = sSelect(sockt->fd_max, &rfd, NULL, NULL, &timeout); if( ret == SOCKET_ERROR ) { if( sErrno != S_EINTR ) { ShowFatalError("do_sockets: select() failed, %s!\n", error_msg()); exit(EXIT_FAILURE); } return 0; // interrupted by a signal, just loop and try again } sockt->last_tick = time(NULL); #if defined(WIN32) // on windows, enumerating all members of the fd_set is way faster if we access the internals for( i = 0; i < (int)rfd.fd_count; ++i ) { int fd = sock2fd(rfd.fd_array[i]); if( sockt->session[fd] ) sockt->session[fd]->func_recv(fd); } #else // otherwise assume that the fd_set is a bit-array and enumerate it in a standard way for( i = 1; ret && i < sockt->fd_max; ++i ) { if(sFD_ISSET(i,&rfd) && sockt->session[i]) { sockt->session[i]->func_recv(i); --ret; } } #endif // POSTSEND Send remaining data and handle eof sessions. #ifdef SEND_SHORTLIST send_shortlist_do_sends(); #else for (i = 1; i < sockt->fd_max; i++) { if(!sockt->session[i]) continue; if(sockt->session[i]->wdata_size) sockt->session[i]->func_send(i); if (sockt->session[i]->flag.eof) { //func_send can't free a session, this is safe. //Finally, even if there is no data to parse, connections signaled eof should be closed, so we call parse_func [Skotlex] sockt->session[i]->func_parse(i); //This should close the session immediately. } } #endif // parse input data on each socket for(i = 1; i < sockt->fd_max; i++) { if(!sockt->session[i]) continue; if (sockt->session[i]->rdata_tick && DIFF_TICK(sockt->last_tick, sockt->session[i]->rdata_tick) > sockt->stall_time) { if( sockt->session[i]->flag.server ) {/* server is special */ if( sockt->session[i]->flag.ping != 2 )/* only update if necessary otherwise it'd resend the ping unnecessarily */ sockt->session[i]->flag.ping = 1; } else { ShowInfo("Session #%d timed out\n", i); sockt->eof(i); } } #ifdef __clang_analyzer__ // Let Clang's static analyzer know this never happens (it thinks it might because of a NULL check in session_is_valid) if (!sockt->session[i]) continue; #endif // __clang_analyzer__ sockt->session[i]->func_parse(i); if(!sockt->session[i]) continue; RFIFOFLUSH(i); // after parse, check client's RFIFO size to know if there is an invalid packet (too big and not parsed) if (sockt->session[i]->rdata_size == sockt->session[i]->max_rdata) { sockt->eof(i); continue; } } #ifdef SHOW_SERVER_STATS if (sockt->last_tick != socket_data_last_tick) { char buf[1024]; sprintf(buf, "In: %.03f kB/s (%.03f kB/s, Q: %.03f kB) | Out: %.03f kB/s (%.03f kB/s, Q: %.03f kB) | RAM: %.03f MB", socket_data_i/1024., socket_data_ci/1024., socket_data_qi/1024., socket_data_o/1024., socket_data_co/1024., socket_data_qo/1024., iMalloc->usage()/1024.); #ifdef _WIN32 SetConsoleTitle(buf); #else ShowMessage("\033[s\033[1;1H\033[2K%s\033[u", buf); #endif socket_data_last_tick = sockt->last_tick; socket_data_i = socket_data_ci = 0; socket_data_o = socket_data_co = 0; } #endif return 0; } ////////////////////////////// #ifndef MINICORE ////////////////////////////// // IP rules and DDoS protection typedef struct connect_history { uint32 ip; int64 tick; int count; unsigned ddos : 1; } ConnectHistory; typedef struct access_control { uint32 ip; uint32 mask; } AccessControl; enum aco { ACO_DENY_ALLOW, ACO_ALLOW_DENY, ACO_MUTUAL_FAILURE }; static AccessControl* access_allow = NULL; static AccessControl* access_deny = NULL; static int access_order = ACO_DENY_ALLOW; static int access_allownum = 0; static int access_denynum = 0; static int access_debug = 0; static int ddos_count = 10; static int ddos_interval = 3*1000; static int ddos_autoreset = 10*60*1000; DBMap *connect_history = NULL; static int connect_check_(uint32 ip); /// Verifies if the IP can connect. (with debug info) /// @see connect_check_() static int connect_check(uint32 ip) { int result = connect_check_(ip); if( access_debug ) { ShowInfo("connect_check: Connection from %d.%d.%d.%d %s\n", CONVIP(ip),result ? "allowed." : "denied!"); } return result; } /// Verifies if the IP can connect. /// 0 : Connection Rejected /// 1 or 2 : Connection Accepted static int connect_check_(uint32 ip) { ConnectHistory* hist = NULL; int i; int is_allowip = 0; int is_denyip = 0; int connect_ok = 0; // Search the allow list for( i=0; i < access_allownum; ++i ){ if( (ip & access_allow[i].mask) == (access_allow[i].ip & access_allow[i].mask) ){ if( access_debug ){ ShowInfo("connect_check: Found match from allow list:%d.%d.%d.%d IP:%d.%d.%d.%d Mask:%d.%d.%d.%d\n", CONVIP(ip), CONVIP(access_allow[i].ip), CONVIP(access_allow[i].mask)); } is_allowip = 1; break; } } // Search the deny list for( i=0; i < access_denynum; ++i ){ if( (ip & access_deny[i].mask) == (access_deny[i].ip & access_deny[i].mask) ){ if( access_debug ){ ShowInfo("connect_check: Found match from deny list:%d.%d.%d.%d IP:%d.%d.%d.%d Mask:%d.%d.%d.%d\n", CONVIP(ip), CONVIP(access_deny[i].ip), CONVIP(access_deny[i].mask)); } is_denyip = 1; break; } } // Decide connection status // 0 : Reject // 1 : Accept // 2 : Unconditional Accept (accepts even if flagged as DDoS) switch(access_order) { case ACO_DENY_ALLOW: default: if( is_denyip ) connect_ok = 0; // Reject else if( is_allowip ) connect_ok = 2; // Unconditional Accept else connect_ok = 1; // Accept break; case ACO_ALLOW_DENY: if( is_allowip ) connect_ok = 2; // Unconditional Accept else if( is_denyip ) connect_ok = 0; // Reject else connect_ok = 1; // Accept break; case ACO_MUTUAL_FAILURE: if( is_allowip && !is_denyip ) connect_ok = 2; // Unconditional Accept else connect_ok = 0; // Reject break; } // Inspect connection history if( ( hist = uidb_get(connect_history, ip)) ) { //IP found if( hist->ddos ) {// flagged as DDoS return (connect_ok == 2 ? 1 : 0); } else if( DIFF_TICK(timer->gettick(),hist->tick) < ddos_interval ) {// connection within ddos_interval hist->tick = timer->gettick(); if( ++hist->count >= ddos_count ) {// DDoS attack detected hist->ddos = 1; ShowWarning("connect_check: DDoS Attack detected from %d.%d.%d.%d!\n", CONVIP(ip)); return (connect_ok == 2 ? 1 : 0); } return connect_ok; } else {// not within ddos_interval, clear data hist->tick = timer->gettick(); hist->count = 0; return connect_ok; } } // IP not found, add to history CREATE(hist, ConnectHistory, 1); hist->ip = ip; hist->tick = timer->gettick(); uidb_put(connect_history, ip, hist); return connect_ok; } /// Timer function. /// Deletes old connection history records. static int connect_check_clear(int tid, int64 tick, int id, intptr_t data) { int clear = 0; int list = 0; ConnectHistory *hist = NULL; DBIterator *iter; if( !db_size(connect_history) ) return 0; iter = db_iterator(connect_history); for( hist = dbi_first(iter); dbi_exists(iter); hist = dbi_next(iter) ){ if( (!hist->ddos && DIFF_TICK(tick,hist->tick) > ddos_interval*3) || (hist->ddos && DIFF_TICK(tick,hist->tick) > ddos_autoreset) ) {// Remove connection history uidb_remove(connect_history, hist->ip); clear++; } list++; } dbi_destroy(iter); if( access_debug ){ ShowInfo("connect_check_clear: Cleared %d of %d from IP list.\n", clear, list); } return list; } /// Parses the ip address and mask and puts it into acc. /// Returns 1 is successful, 0 otherwise. int access_ipmask(const char* str, AccessControl* acc) { uint32 ip; uint32 mask; if( strcmp(str,"all") == 0 ) { ip = 0; mask = 0; } else { unsigned int a[4]; unsigned int m[4]; int n; if( ((n=sscanf(str,"%u.%u.%u.%u/%u.%u.%u.%u",a,a+1,a+2,a+3,m,m+1,m+2,m+3)) != 8 && // not an ip + standard mask (n=sscanf(str,"%u.%u.%u.%u/%u",a,a+1,a+2,a+3,m)) != 5 && // not an ip + bit mask (n=sscanf(str,"%u.%u.%u.%u",a,a+1,a+2,a+3)) != 4 ) || // not an ip a[0] > 255 || a[1] > 255 || a[2] > 255 || a[3] > 255 || // invalid ip (n == 8 && (m[0] > 255 || m[1] > 255 || m[2] > 255 || m[3] > 255)) || // invalid standard mask (n == 5 && m[0] > 32) ){ // invalid bit mask return 0; } ip = MAKEIP(a[0],a[1],a[2],a[3]); if( n == 8 ) {// standard mask mask = MAKEIP(m[0],m[1],m[2],m[3]); } else if( n == 5 ) {// bit mask mask = 0; while( m[0] ){ mask = (mask >> 1) | 0x80000000; --m[0]; } } else {// just this ip mask = 0xFFFFFFFF; } } if( access_debug ){ ShowInfo("access_ipmask: Loaded IP:%d.%d.%d.%d mask:%d.%d.%d.%d\n", CONVIP(ip), CONVIP(mask)); } acc->ip = ip; acc->mask = mask; return 1; } ////////////////////////////// #endif ////////////////////////////// int socket_config_read(const char* cfgName) { char line[1024],w1[1024],w2[1024]; FILE *fp; fp = fopen(cfgName, "r"); if(fp == NULL) { ShowError("File not found: %s\n", cfgName); return 1; } while (fgets(line, sizeof(line), fp)) { if(line[0] == '/' && line[1] == '/') continue; if (sscanf(line, "%1023[^:]: %1023[^\r\n]", w1, w2) != 2) continue; if (!strcmpi(w1, "stall_time")) { sockt->stall_time = atoi(w2); if( sockt->stall_time < 3 ) sockt->stall_time = 3;/* a minimum is required to refrain it from killing itself */ } #ifndef MINICORE else if (!strcmpi(w1, "enable_ip_rules")) { ip_rules = config_switch(w2); } else if (!strcmpi(w1, "order")) { if (!strcmpi(w2, "deny,allow")) access_order = ACO_DENY_ALLOW; else if (!strcmpi(w2, "allow,deny")) access_order = ACO_ALLOW_DENY; else if (!strcmpi(w2, "mutual-failure")) access_order = ACO_MUTUAL_FAILURE; } else if (!strcmpi(w1, "allow")) { RECREATE(access_allow, AccessControl, access_allownum+1); if (access_ipmask(w2, &access_allow[access_allownum])) ++access_allownum; else ShowError("socket_config_read: Invalid ip or ip range '%s'!\n", line); } else if (!strcmpi(w1, "deny")) { RECREATE(access_deny, AccessControl, access_denynum+1); if (access_ipmask(w2, &access_deny[access_denynum])) ++access_denynum; else ShowError("socket_config_read: Invalid ip or ip range '%s'!\n", line); } else if (!strcmpi(w1,"ddos_interval")) ddos_interval = atoi(w2); else if (!strcmpi(w1,"ddos_count")) ddos_count = atoi(w2); else if (!strcmpi(w1,"ddos_autoreset")) ddos_autoreset = atoi(w2); else if (!strcmpi(w1,"debug")) access_debug = config_switch(w2); else if (!strcmpi(w1,"socket_max_client_packet")) socket_max_client_packet = strtoul(w2, NULL, 0); #endif else if (!strcmpi(w1, "import")) socket_config_read(w2); else ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName); } fclose(fp); return 0; } void socket_final(void) { int i; #ifndef MINICORE if( connect_history ) db_destroy(connect_history); if( access_allow ) aFree(access_allow); if( access_deny ) aFree(access_deny); #endif for( i = 1; i < sockt->fd_max; i++ ) if(sockt->session[i]) sockt->close(i); // sockt->session[0] aFree(sockt->session[0]->rdata); aFree(sockt->session[0]->wdata); aFree(sockt->session[0]); aFree(sockt->session); if (sockt->lan_subnet) aFree(sockt->lan_subnet); sockt->lan_subnet = NULL; sockt->lan_subnet_count = 0; if (sockt->allowed_ip) aFree(sockt->allowed_ip); sockt->allowed_ip = NULL; sockt->allowed_ip_count = 0; if (sockt->trusted_ip) aFree(sockt->trusted_ip); sockt->trusted_ip = NULL; sockt->trusted_ip_count = 0; } /// Closes a socket. void socket_close(int fd) { if( fd <= 0 ||fd >= FD_SETSIZE ) return;// invalid sockt->flush(fd); // Try to send what's left (although it might not succeed since it's a nonblocking socket) sFD_CLR(fd, &readfds);// this needs to be done before closing the socket sShutdown(fd, SHUT_RDWR); // Disallow further reads/writes sClose(fd); // We don't really care if these closing functions return an error, we are just shutting down and not reusing this socket. if (sockt->session[fd]) delete_session(fd); } /// Retrieve local ips in host byte order. /// Uses loopback is no address is found. int socket_getips(uint32* ips, int max) { int num = 0; if( ips == NULL || max <= 0 ) return 0; #ifdef WIN32 { char fullhost[255]; // XXX This should look up the local IP addresses in the registry // instead of calling gethostbyname. However, the way IP addresses // are stored in the registry is annoyingly complex, so I'll leave // this as T.B.D. [Meruru] if (gethostname(fullhost, sizeof(fullhost)) == SOCKET_ERROR) { ShowError("socket_getips: No hostname defined!\n"); return 0; } else { u_long** a; struct hostent *hent =gethostbyname(fullhost); if( hent == NULL ){ ShowError("socket_getips: Cannot resolve our own hostname to an IP address\n"); return 0; } a = (u_long**)hent->h_addr_list; for (; num < max && a[num] != NULL; ++num) ips[num] = (uint32)ntohl(*a[num]); } } #else // not WIN32 { int fd; char buf[2*16*sizeof(struct ifreq)]; struct ifconf ic; u_long ad; fd = sSocket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { ShowError("socket_getips: Unable to create a socket!\n"); return 0; } memset(buf, 0x00, sizeof(buf)); // The ioctl call will fail with Invalid Argument if there are more // interfaces than will fit in the buffer ic.ifc_len = sizeof(buf); ic.ifc_buf = buf; if (sIoctl(fd, SIOCGIFCONF, &ic) == -1) { ShowError("socket_getips: SIOCGIFCONF failed!\n"); sClose(fd); return 0; } else { int pos; for (pos = 0; pos < ic.ifc_len && num < max; ) { struct ifreq *ir = (struct ifreq*)(buf+pos); struct sockaddr_in *a = (struct sockaddr_in*) &(ir->ifr_addr); if (a->sin_family == AF_INET) { ad = ntohl(a->sin_addr.s_addr); if (ad != INADDR_LOOPBACK && ad != INADDR_ANY) ips[num++] = (uint32)ad; } #if (defined(BSD) && BSD >= 199103) || defined(_AIX) || defined(__APPLE__) pos += ir->ifr_addr.sa_len + sizeof(ir->ifr_name); #else// not AIX or APPLE pos += sizeof(struct ifreq); #endif//not AIX or APPLE } } sClose(fd); } #endif // not W32 // Use loopback if no ips are found if( num == 0 ) ips[num++] = (uint32)INADDR_LOOPBACK; return num; } void socket_init(void) { char *SOCKET_CONF_FILENAME = "conf/packet.conf"; uint64 rlim_cur = FD_SETSIZE; #ifdef WIN32 {// Start up windows networking WSADATA wsaData; WORD wVersionRequested = MAKEWORD(2, 0); if( WSAStartup(wVersionRequested, &wsaData) != 0 ) { ShowError("socket_init: WinSock not available!\n"); return; } if( LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0 ) { ShowError("socket_init: WinSock version mismatch (2.0 or compatible required)!\n"); return; } } #elif defined(HAVE_SETRLIMIT) && !defined(CYGWIN) // NOTE: getrlimit and setrlimit have bogus behavior in cygwin. // "Number of fds is virtually unlimited in cygwin" (sys/param.h) {// set socket limit to FD_SETSIZE struct rlimit rlp; if( 0 == getrlimit(RLIMIT_NOFILE, &rlp) ) { rlp.rlim_cur = FD_SETSIZE; if( 0 != setrlimit(RLIMIT_NOFILE, &rlp) ) {// failed, try setting the maximum too (permission to change system limits is required) rlp.rlim_max = FD_SETSIZE; if( 0 != setrlimit(RLIMIT_NOFILE, &rlp) ) {// failed const char *errmsg = error_msg(); int rlim_ori; // set to maximum allowed getrlimit(RLIMIT_NOFILE, &rlp); rlim_ori = (int)rlp.rlim_cur; rlp.rlim_cur = rlp.rlim_max; setrlimit(RLIMIT_NOFILE, &rlp); // report limit getrlimit(RLIMIT_NOFILE, &rlp); rlim_cur = rlp.rlim_cur; ShowWarning("socket_init: failed to set socket limit to %d, setting to maximum allowed (original limit=%d, current limit=%d, maximum allowed=%d, %s).\n", FD_SETSIZE, rlim_ori, (int)rlp.rlim_cur, (int)rlp.rlim_max, errmsg); } } } } #endif // Get initial local ips sockt->naddr_ = sockt->getips(sockt->addr_,16); sFD_ZERO(&readfds); #if defined(SEND_SHORTLIST) memset(send_shortlist_set, 0, sizeof(send_shortlist_set)); #endif CREATE(sockt->session, struct socket_data *, FD_SETSIZE); socket_config_read(SOCKET_CONF_FILENAME); // initialize last send-receive tick sockt->last_tick = time(NULL); // sockt->session[0] is now currently used for disconnected sessions of the map server, and as such, // should hold enough buffer (it is a vacuum so to speak) as it is never flushed. [Skotlex] create_session(0, null_recv, null_send, null_parse); #ifndef MINICORE // Delete old connection history every 5 minutes connect_history = uidb_alloc(DB_OPT_RELEASE_DATA); timer->add_func_list(connect_check_clear, "connect_check_clear"); timer->add_interval(timer->gettick()+1000, connect_check_clear, 0, 0, 5*60*1000); #endif ShowInfo("Server supports up to '"CL_WHITE"%"PRId64""CL_RESET"' concurrent connections.\n", rlim_cur); } bool session_is_valid(int fd) { return ( fd > 0 && fd < FD_SETSIZE && sockt->session[fd] != NULL ); } bool session_is_active(int fd) { return ( sockt->session_is_valid(fd) && !sockt->session[fd]->flag.eof ); } // Resolves hostname into a numeric ip. uint32 host2ip(const char* hostname) { struct hostent* h = gethostbyname(hostname); return (h != NULL) ? ntohl(*(uint32*)h->h_addr) : 0; } /** * Converts a numeric ip into a dot-formatted string. * * @param ip Numeric IP to convert. * @param ip_str Output buffer, optional (if provided, must have size greater or equal to 16). * * @return A pointer to the output string. */ const char *ip2str(uint32 ip, char *ip_str) { struct in_addr addr; addr.s_addr = htonl(ip); return (ip_str == NULL) ? inet_ntoa(addr) : strncpy(ip_str, inet_ntoa(addr), 16); } // Converts a dot-formatted ip string into a numeric ip. uint32 str2ip(const char* ip_str) { return ntohl(inet_addr(ip_str)); } // Reorders bytes from network to little endian (Windows). // Necessary for sending port numbers to the RO client until Gravity notices that they forgot ntohs() calls. uint16 ntows(uint16 netshort) { return ((netshort & 0xFF) << 8) | ((netshort & 0xFF00) >> 8); } /* [Ind/Hercules] - socket_datasync */ void socket_datasync(int fd, bool send) { struct { unsigned int length;/* short is not enough for some */ } data_list[] = { { sizeof(struct mmo_charstatus) }, { sizeof(struct quest) }, { sizeof(struct item) }, { sizeof(struct point) }, { sizeof(struct s_skill) }, { sizeof(struct status_change_data) }, { sizeof(struct storage_data) }, { sizeof(struct guild_storage) }, { sizeof(struct s_pet) }, { sizeof(struct s_mercenary) }, { sizeof(struct s_homunculus) }, { sizeof(struct s_elemental) }, { sizeof(struct s_friend) }, { sizeof(struct mail_message) }, { sizeof(struct mail_data) }, { sizeof(struct party_member) }, { sizeof(struct party) }, { sizeof(struct guild_member) }, { sizeof(struct guild_position) }, { sizeof(struct guild_alliance) }, { sizeof(struct guild_expulsion) }, { sizeof(struct guild_skill) }, { sizeof(struct guild) }, { sizeof(struct guild_castle) }, { sizeof(struct fame_list) }, { PACKETVER }, }; unsigned short i; unsigned int alen = ARRAYLENGTH(data_list); if( send ) { unsigned short p_len = ( alen * 4 ) + 4; WFIFOHEAD(fd, p_len); WFIFOW(fd, 0) = 0x2b0a; WFIFOW(fd, 2) = p_len; for( i = 0; i < alen; i++ ) { WFIFOL(fd, 4 + ( i * 4 ) ) = data_list[i].length; } WFIFOSET(fd, p_len); } else { for( i = 0; i < alen; i++ ) { if( RFIFOL(fd, 4 + (i * 4) ) != data_list[i].length ) { /* force the other to go wrong too so both are taken down */ WFIFOHEAD(fd, 8); WFIFOW(fd, 0) = 0x2b0a; WFIFOW(fd, 2) = 8; WFIFOL(fd, 4) = 0; WFIFOSET(fd, 8); sockt->flush(fd); /* shut down */ ShowFatalError("Servers are out of sync! recompile from scratch (%d)\n",i); exit(EXIT_FAILURE); } } } } #ifdef SEND_SHORTLIST // Add a fd to the shortlist so that it'll be recognized as a fd that needs // sending or eof handling. void send_shortlist_add_fd(int fd) { int i; int bit; if (!sockt->session_is_valid(fd)) return;// out of range i = fd/32; bit = fd%32; if( (send_shortlist_set[i]>>bit)&1 ) return;// already in the list if (send_shortlist_count >= ARRAYLENGTH(send_shortlist_array)) { ShowDebug("send_shortlist_add_fd: shortlist is full, ignoring... (fd=%d shortlist.count=%d shortlist.length=%"PRIuS")\n", fd, send_shortlist_count, ARRAYLENGTH(send_shortlist_array)); return; } // set the bit send_shortlist_set[i] |= 1<<bit; // Add to the end of the shortlist array. send_shortlist_array[send_shortlist_count++] = fd; } // Do pending network sends and eof handling from the shortlist. void send_shortlist_do_sends() { int i; for( i = send_shortlist_count-1; i >= 0; --i ) { int fd = send_shortlist_array[i]; int idx = fd/32; int bit = fd%32; // Remove fd from shortlist, move the last fd to the current position --send_shortlist_count; send_shortlist_array[i] = send_shortlist_array[send_shortlist_count]; send_shortlist_array[send_shortlist_count] = 0; if( fd <= 0 || fd >= FD_SETSIZE ) { ShowDebug("send_shortlist_do_sends: fd is out of range, corrupted memory? (fd=%d)\n", fd); continue; } if( ((send_shortlist_set[idx]>>bit)&1) == 0 ) { ShowDebug("send_shortlist_do_sends: fd is not set, why is it in the shortlist? (fd=%d)\n", fd); continue; } send_shortlist_set[idx]&=~(1<<bit);// unset fd // If this session still exists, perform send operations on it and // check for the eof state. if( sockt->session[fd] ) { // Send data if( sockt->session[fd]->wdata_size ) sockt->session[fd]->func_send(fd); // If it's been marked as eof, call the parse func on it so that // the socket will be immediately closed. if( sockt->session[fd]->flag.eof ) sockt->session[fd]->func_parse(fd); // If the session still exists, is not eof and has things left to // be sent from it we'll re-add it to the shortlist. if( sockt->session[fd] && !sockt->session[fd]->flag.eof && sockt->session[fd]->wdata_size ) send_shortlist_add_fd(fd); } } } #endif /** * Checks whether the given IP comes from LAN or WAN. * * @param[in] ip IP address to check. * @param[out] info Verbose output, if requested. Filled with the matching entry. Ignored if NULL. * @retval 0 if it is a WAN IP. * @return the appropriate LAN server address to send, if it is a LAN IP. */ uint32 socket_lan_subnet_check(uint32 ip, struct s_subnet *info) { int i; ARR_FIND(0, sockt->lan_subnet_count, i, (sockt->lan_subnet[i].ip & sockt->lan_subnet[i].mask) == (ip & sockt->lan_subnet[i].mask)); if (i < sockt->lan_subnet_count) { if (info) { info->ip = sockt->lan_subnet[i].ip; info->mask = sockt->lan_subnet[i].mask; } return sockt->lan_subnet[i].ip; } if (info) { info->ip = info->mask = 0; } return 0; } /** * Checks whether the given IP is allowed to connect as a server. * * @param ip IP address to check. * @retval true if we allow server connections from the given IP. * @retval false otherwise. */ bool socket_allowed_ip_check(uint32 ip) { int i; ARR_FIND(0, sockt->allowed_ip_count, i, (sockt->allowed_ip[i].ip & sockt->allowed_ip[i].mask) == (ip & sockt->allowed_ip[i].mask) ); if (i < sockt->allowed_ip_count) return true; return sockt->trusted_ip_check(ip); // If an address is trusted, it's automatically also allowed. } /** * Checks whether the given IP is trusted and can skip ipban checks. * * @param ip IP address to check. * @retval true if we trust the given IP. * @retval false otherwise. */ bool socket_trusted_ip_check(uint32 ip) { int i; ARR_FIND(0, sockt->trusted_ip_count, i, (sockt->trusted_ip[i].ip & sockt->trusted_ip[i].mask) == (ip & sockt->trusted_ip[i].mask)); if (i < sockt->trusted_ip_count) return true; return false; } /** * Helper function to read a list of network.conf values. * * Entries will be appended to the variable-size array pointed to by list/count. * * @param[in] t The list to parse. * @param[in,out] list Pointer to the head of the output array to append to. Must not be NULL (but the array may be empty). * @param[in,out] count Pointer to the counter of the output array to append to. Must not be NULL (but it may contain zero). * @param[in] filename Current filename, for output/logging reasons. * @param[in] groupname Current group name, for output/logging reasons. * @return The amount of entries read, zero in case of errors. */ int socket_net_config_read_sub(config_setting_t *t, struct s_subnet **list, int *count, const char *filename, const char *groupname) { int i, len; char ipbuf[64], maskbuf[64]; nullpo_retr(0, list); nullpo_retr(0, count); if (t == NULL) return 0; len = libconfig->setting_length(t); for (i = 0; i < len; ++i) { const char *subnet = libconfig->setting_get_string_elem(t, i); struct s_subnet *l = NULL; if (sscanf(subnet, "%63[^:]:%63[^:]", ipbuf, maskbuf) != 2) { ShowWarning("Invalid IP:Subnet entry in configuration file %s: '%s' (%s)\n", filename, subnet, groupname); } RECREATE(*list, struct s_subnet, *count + 1); l = *list; l[*count].ip = sockt->str2ip(ipbuf); l[*count].mask = sockt->str2ip(maskbuf); ++*count; } return *count; } /** * Reads the network configuration file. * * @param filename The filename to read from. */ void socket_net_config_read(const char *filename) { config_t network_config; int i; nullpo_retv(filename); if (libconfig->read_file(&network_config, filename)) { ShowError("LAN Support configuration file is not found: '%s'. This server won't be able to accept connections from any servers.\n", filename); return; } if (sockt->lan_subnet) { aFree(sockt->lan_subnet); sockt->lan_subnet = NULL; } sockt->lan_subnet_count = 0; if (sockt->net_config_read_sub(libconfig->lookup(&network_config, "lan_subnets"), &sockt->lan_subnet, &sockt->lan_subnet_count, filename, "lan_subnets") > 0) ShowStatus("Read information about %d LAN subnets.\n", sockt->lan_subnet_count); if (sockt->trusted_ip) { aFree(sockt->trusted_ip); sockt->trusted_ip = NULL; } sockt->trusted_ip_count = 0; if (sockt->net_config_read_sub(libconfig->lookup(&network_config, "trusted"), &sockt->trusted_ip, &sockt->trusted_ip_count, filename, "trusted") > 0) ShowStatus("Read information about %d trusted IP ranges.\n", sockt->trusted_ip_count); for (i = 0; i < sockt->allowed_ip_count; ++i) { if ((sockt->allowed_ip[i].ip & sockt->allowed_ip[i].mask) == 0) { ShowError("Using a wildcard IP range in the trusted server IPs is NOT RECOMMENDED.\n"); ShowNotice("Please edit your '%s' trusted list to fit your network configuration.\n", filename); break; } } if (sockt->allowed_ip) { aFree(sockt->allowed_ip); sockt->allowed_ip = NULL; } sockt->allowed_ip_count = 0; if (sockt->net_config_read_sub(libconfig->lookup(&network_config, "allowed"), &sockt->allowed_ip, &sockt->allowed_ip_count, filename, "allowed") > 0) ShowStatus("Read information about %d allowed server IP ranges.\n", sockt->allowed_ip_count); if (sockt->allowed_ip_count == 0) { ShowError("No allowed server IP ranges configured. This server won't be able to accept connections from any char servers.\n"); } for (i = 0; i < sockt->allowed_ip_count; ++i) { if ((sockt->allowed_ip[i].ip & sockt->allowed_ip[i].mask) == 0) { ShowWarning("Using a wildcard IP range in the allowed server IPs is NOT RECOMMENDED.\n"); ShowNotice("Please edit your '%s' allowed list to fit your network configuration.\n", filename); break; } } libconfig->destroy(&network_config); return; } void socket_defaults(void) { sockt = &sockt_s; sockt->fd_max = 0; /* */ sockt->stall_time = 60; sockt->last_tick = 0; /* */ memset(&sockt->addr_, 0, sizeof(sockt->addr_)); sockt->naddr_ = 0; /* */ sockt->lan_subnet_count = 0; sockt->lan_subnet = NULL; sockt->allowed_ip_count = 0; sockt->allowed_ip = NULL; sockt->trusted_ip_count = 0; sockt->trusted_ip = NULL; sockt->init = socket_init; sockt->final = socket_final; /* */ sockt->perform = do_sockets; /* */ sockt->datasync = socket_datasync; /* */ sockt->make_listen_bind = make_listen_bind; sockt->make_connection = make_connection; sockt->realloc_fifo = realloc_fifo; sockt->realloc_writefifo = realloc_writefifo; sockt->wfifoset = wfifoset; sockt->rfifoskip = rfifoskip; sockt->close = socket_close; /* */ sockt->session_is_valid = session_is_valid; sockt->session_is_active = session_is_active; /* */ sockt->flush = flush_fifo; sockt->flush_fifos = flush_fifos; sockt->set_nonblocking = set_nonblocking; sockt->set_defaultparse = set_defaultparse; sockt->host2ip = host2ip; sockt->ip2str = ip2str; sockt->str2ip = str2ip; sockt->ntows = ntows; sockt->getips = socket_getips; sockt->eof = set_eof; sockt->lan_subnet_check = socket_lan_subnet_check; sockt->allowed_ip_check = socket_allowed_ip_check; sockt->trusted_ip_check = socket_trusted_ip_check; sockt->net_config_read_sub = socket_net_config_read_sub; sockt->net_config_read = socket_net_config_read; }
Jedzkie/EP13.2-Server
src/common/socket.c
C
gpl-3.0
53,607
import { Factory } from "meteor/dburles:factory"; import { Packages } from "/lib/collections"; import { getShopId } from "./shops"; export const getPkgData = (pkgName) => { const pkgData = Packages.findOne({ name: pkgName }); return pkgData; }; export default function () { const examplePaymentMethodPackage = { name: "example-paymentmethod", icon: "fa fa-credit-card-alt", shopId: getShopId(), enabled: true, settings: { "mode": false, "apikey": "", "example": { enabled: false }, "example-paymentmethod": { enabled: true, support: ["Authorize", "Capture", "Refund"] } }, registry: [], layout: null }; Factory.define("examplePaymentPackage", Packages, Object.assign({}, examplePaymentMethodPackage)); }
spestushko/reaction
server/imports/fixtures/packages.js
JavaScript
gpl-3.0
817
// Copyright (C) 2011, 2012 Google Inc. // // This file is part of ycmd. // // ycmd is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ycmd is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ycmd. If not, see <http://www.gnu.org/licenses/>. #ifndef TRANSLATIONUNIT_H_XQ7I6SVA #define TRANSLATIONUNIT_H_XQ7I6SVA #include "Diagnostic.h" #include "Documentation.h" #include "Location.h" #include "UnsavedFile.h" #include <clang-c/Index.h> #include <mutex> #include <string> #include <vector> namespace YouCompleteMe { struct CompletionData; class TranslationUnit { public: // This constructor creates an invalid, sentinel TU. All of it's methods // return empty vectors, and IsCurrentlyUpdating always returns true so that // no callers try to rely on the invalid TU. YCM_EXPORT TranslationUnit(); TranslationUnit( const TranslationUnit& ) = delete; TranslationUnit& operator=( const TranslationUnit& ) = delete; YCM_EXPORT TranslationUnit( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags, CXIndex clang_index ); YCM_EXPORT ~TranslationUnit(); void Destroy(); YCM_EXPORT bool IsCurrentlyUpdating() const; YCM_EXPORT std::vector< Diagnostic > Reparse( const std::vector< UnsavedFile > &unsaved_files ); YCM_EXPORT std::vector< CompletionData > CandidatesForLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files ); YCM_EXPORT Location GetDeclarationLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, bool reparse = true ); YCM_EXPORT Location GetDefinitionLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, bool reparse = true ); YCM_EXPORT Location GetDefinitionOrDeclarationLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, bool reparse = true ); YCM_EXPORT std::string GetTypeAtLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, bool reparse = true ); YCM_EXPORT std::string GetEnclosingFunctionAtLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, bool reparse = true ); std::vector< FixIt > GetFixItsForLocationInFile( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, bool reparse = true ); YCM_EXPORT DocumentationData GetDocsForLocation( const Location &location, const std::vector< UnsavedFile > &unsaved_files, bool reparse = true ); bool LocationIsInSystemHeader( const Location &location ); private: void Reparse( std::vector< CXUnsavedFile > &unsaved_files ); void Reparse( std::vector< CXUnsavedFile > &unsaved_files, size_t parse_options ); void UpdateLatestDiagnostics(); // These four methods must be called under the clang_access_mutex_ lock. CXSourceLocation GetSourceLocation( const std::string& filename, int line, int column ); CXCursor GetCursor( const std::string& filename, int line, int column ); Location GetDeclarationLocationForCursor( CXCursor cursor ); Location GetDefinitionLocationForCursor( CXCursor cursor ); ///////////////////////////// // PRIVATE MEMBER VARIABLES ///////////////////////////// std::mutex diagnostics_mutex_; std::vector< Diagnostic > latest_diagnostics_; mutable std::mutex clang_access_mutex_; CXTranslationUnit clang_translation_unit_; }; } // namespace YouCompleteMe #endif /* end of include guard: TRANSLATIONUNIT_H_XQ7I6SVA */
snakeleon/YouCompleteMe-x64
third_party/ycmd/cpp/ycm/ClangCompleter/TranslationUnit.h
C
gpl-3.0
4,374
#!/bin/sh # untabify.sh # This file is part of the YATE Project http://YATE.null.ro # # Yet Another Telephony Engine - a fully featured software PBX and IVR # Copyright (C) 2005-2014 Null Team # # This software is distributed under multiple licenses; # see the COPYING file in the main directory for licensing # information for this specific distribution. # # This use of this software may be subject to additional restrictions. # See the LEGAL file in the main directory for details. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # Convert tabs at start of line to a number of spaces cmd="" case "$1" in -h|--help) echo "usage: untabify [--size <number>] file [file...]" exit 0 ;; -s|--size) shift while [ ${#cmd} -lt "$1" ]; do cmd=" $cmd"; done shift ;; esac test -z "$cmd" && cmd=" " tmp=".$$.tmp" cmd=": again; s/^\\( *\\) /\\1$cmd/; t again" if [ "$#" = "0" ]; then sed "$cmd" exit 0 fi while [ "$#" != "0" ]; do if [ -f "$1" ]; then sed "$cmd" <"$1" >"$1$tmp" mv "$1$tmp" "$1" else echo "Skipping missing file '$1'" fi shift done
strcpyblog/SubversiveBTS
yate/tools/untabify.sh
Shell
gpl-3.0
1,219
/******************************************************************************* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2012 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package edu.berkeley.boinc.attach; import java.io.InputStream; import java.net.URL; import edu.berkeley.boinc.R; import edu.berkeley.boinc.rpc.ProjectInfo; import edu.berkeley.boinc.utils.*; import android.app.Dialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; public class ProjectInfoFragment extends DialogFragment{ ProjectInfo info; LinearLayout logoWrapper; ProgressBar logoPb; ImageView logoIv; public static ProjectInfoFragment newInstance(ProjectInfo info) { ProjectInfoFragment f = new ProjectInfoFragment(); Bundle args = new Bundle(); args.putParcelable("info", info); f.setArguments(args); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(Logging.DEBUG) Log.d(Logging.TAG, "ProjectInfoFragment onCreateView"); View v = inflater.inflate(R.layout.attach_project_info_layout, container, false); // get data info = this.getArguments().getParcelable("info"); if(info == null) { if(Logging.ERROR) Log.e(Logging.TAG, "ProjectInfoFragment info is null, return."); dismiss(); return v; } if(Logging.DEBUG) Log.d(Logging.TAG, "ProjectInfoFragment project: " + info.name); // set texts ((TextView) v.findViewById(R.id.project_name)).setText(info.name); ((TextView) v.findViewById(R.id.project_summary)).setText(info.summary); ((TextView) v.findViewById(R.id.project_area)).setText(info.generalArea + ": " + info.specificArea); ((TextView) v.findViewById(R.id.project_desc)).setText(info.description); ((TextView) v.findViewById(R.id.project_home)).setText(getResources().getString(R.string.attachproject_login_header_home) + " " + info.home); // find view elements for later use in image download logoWrapper = (LinearLayout) v.findViewById(R.id.project_logo_wrapper); logoPb = (ProgressBar) v.findViewById(R.id.project_logo_loading_pb); logoIv = (ImageView) v.findViewById(R.id.project_logo); // setup return button Button continueB = (Button) v.findViewById(R.id.continue_button); continueB.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if(Logging.DEBUG) Log.d(Logging.TAG, "ProjectInfoFragment continue clicked"); dismiss(); } }); if(Logging.DEBUG) Log.d(Logging.TAG, "ProjectInfoFragment image url: " + info.imageUrl); new DownloadLogoAsync().execute(info.imageUrl); return v; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = super.onCreateDialog(savedInstanceState); // request a window without the title dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); return dialog; } private class DownloadLogoAsync extends AsyncTask<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... params) { String url = params[0]; if(url == null || url.isEmpty()) { if(Logging.ERROR) Log.e(Logging.TAG, "ProjectInfoFragment DownloadLogoAsync url is empty, return."); return null; } if(Logging.DEBUG) Log.d(Logging.TAG, "ProjectInfoFragment DownloadLogoAsync for url: " + url); Bitmap logo = null; try{ InputStream in = new URL(url).openStream(); logo = BitmapFactory.decodeStream(in); // scale logo = Bitmap.createScaledBitmap(logo, logo.getWidth() * 2, logo.getHeight() * 2, false); } catch(Exception e) { if(Logging.ERROR) Log.e(Logging.TAG, "ProjectInfoFragment DownloadLogoAsync image download failed"); return null; } return logo; } protected void onPostExecute(Bitmap logo) { if(logo == null) { // failed. if(Logging.ERROR) Log.e(Logging.TAG, "ProjectInfoFragment DownloadLogoAsync failed."); logoWrapper.setVisibility(View.GONE); } else { // success. if(Logging.DEBUG) Log.d(Logging.TAG, "ProjectInfoFragment DownloadLogoAsync successful."); logoPb.setVisibility(View.GONE); logoIv.setVisibility(View.VISIBLE); logoIv.setImageBitmap(logo); } } } }
maexlich/boinc-igemathome
android/BOINC/src/edu/berkeley/boinc/attach/ProjectInfoFragment.java
Java
gpl-3.0
5,707
package main import ( "encoding/json" "fmt" "github.com/lonelycode/go-uuid/uuid" "github.com/lonelycode/tykcommon" "io/ioutil" "strings" ) var CommandModeOptions = map[string]bool{ "--import-blueprint": true, "--import-swagger": true, "--create-api": true, "--org-id": true, "--upstream-target": true, "--as-mock": true, "--for-api": true, "--as-version": true, } // ./tyk --import-blueprint=blueprint.json --create-api --org-id=<id> --upstream-target="http://widgets.com/api/"` func HandleCommandModeArgs(arguments map[string]interface{}) { if arguments["--import-blueprint"] != nil { handleBluePrintMode(arguments) } if arguments["--import-swagger"] != nil { handleSwaggerMode(arguments) } } func handleBluePrintMode(arguments map[string]interface{}) { doCreate := arguments["--create-api"] inputFile := arguments["--import-blueprint"] if doCreate == true { upstreamVal := arguments["--upstream-target"] orgId := arguments["--org-id"] if upstreamVal != nil && orgId != nil { // Create the API with the blueprint bp, err := bluePrintLoadFile(inputFile.(string)) if err != nil { log.Error("File load error: ", err) return } def, dErr := createDefFromBluePrint(bp, orgId.(string), upstreamVal.(string), arguments["--as-mock"].(bool)) if dErr != nil { log.Error("Failed to create API Defintition from file") return } printDef(def) return } log.Error("No upstream target or org ID defined, these are both required") } else { // Different branch, here we need an API Definition to modify forApiPath := arguments["--for-api"] if forApiPath == nil { log.Error("If ading to an API, the path to the defintiton must be listed") return } versionName := arguments["--as-version"] if versionName == nil { log.Error("No version defined for this import operation, please set an import ID using the --as-version flag") return } thisDefFromFile, fileErr := apiDefLoadFile(forApiPath.(string)) if fileErr != nil { log.Error("failed to load and decode file data for API Definition: ", fileErr) return } bp, err := bluePrintLoadFile(inputFile.(string)) if err != nil { log.Error("File load error: ", err) return } versionData, err := bp.ConvertIntoApiVersion(arguments["--as-mock"].(bool)) if err != nil { log.Error("onversion into API Def failed: ", err) } insertErr := bp.InsertIntoAPIDefinitionAsVersion(versionData, &thisDefFromFile, versionName.(string)) if insertErr != nil { log.Error("Insertion failed: ", insertErr) return } printDef(&thisDefFromFile) } } func printDef(def *tykcommon.APIDefinition) { asJson, err := json.MarshalIndent(def, "", " ") if err != nil { log.Error("Marshalling failed: ", err) } // The id attribute is for BSON only and breaks the parser if it's empty, cull it here. fixed := strings.Replace(string(asJson), " \"id\": \"\",", "", 1) fmt.Printf(fixed) } func createDefFromBluePrint(bp *BluePrintAST, orgId, upstreamURL string, as_mock bool) (*tykcommon.APIDefinition, error) { thisAD := tykcommon.APIDefinition{} thisAD.Name = bp.Name thisAD.Active = true thisAD.UseKeylessAccess = true thisAD.APIID = uuid.NewUUID().String() thisAD.OrgID = orgId thisAD.VersionDefinition.Key = "version" thisAD.VersionDefinition.Location = "header" thisAD.VersionData.Versions = make(map[string]tykcommon.VersionInfo) thisAD.VersionData.NotVersioned = false thisAD.Proxy.ListenPath = "/" + thisAD.APIID + "/" thisAD.Proxy.StripListenPath = true thisAD.Proxy.TargetURL = upstreamURL versionData, err := bp.ConvertIntoApiVersion(as_mock) if err != nil { log.Error("onversion into API Def failed: ", err) } bp.InsertIntoAPIDefinitionAsVersion(versionData, &thisAD, strings.Trim(bp.Name, " ")) return &thisAD, nil } func bluePrintLoadFile(filePath string) (*BluePrintAST, error) { thisBlueprint, astErr := GetImporterForSource(ApiaryBluePrint) if astErr != nil { log.Error("Couldn't get blueprint importer: ", astErr) return thisBlueprint.(*BluePrintAST), astErr } bluePrintFileData, err := ioutil.ReadFile(filePath) if err != nil { log.Error("Couldn't load blueprint file: ", err) return thisBlueprint.(*BluePrintAST), err } readErr := thisBlueprint.ReadString(string(bluePrintFileData)) if readErr != nil { log.Error("Failed to decode object") return thisBlueprint.(*BluePrintAST), readErr } return thisBlueprint.(*BluePrintAST), nil } func apiDefLoadFile(filePath string) (tykcommon.APIDefinition, error) { thisDef := tykcommon.APIDefinition{} defFileData, err := ioutil.ReadFile(filePath) if err != nil { log.Error("Couldn't load API Definition file: ", err) return thisDef, err } jsonErr := json.Unmarshal(defFileData, &thisDef) if jsonErr != nil { log.Error("Failed to unmarshal the JSON definition: ", jsonErr) return thisDef, jsonErr } return thisDef, nil }
trigrass2/tyk
command_mode.go
GO
mpl-2.0
4,966
<?php /** * Will run KAsyncConvertCollection * * @package Scheduler * @subpackage Conversion */ require_once(__DIR__ . "/../../bootstrap.php"); $instance = new KAsyncConvertCollection(); $instance->run(); $instance->done();
ivesbai/server
batch/batches/Convert/KAsyncConvertCollectionExe.php
PHP
agpl-3.0
231
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.gl.report; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.kuali.kfs.gl.businessobject.OriginEntryInformation; import org.kuali.kfs.gl.businessobject.PosterOutputSummaryBalanceTypeFiscalYearAndPeriodTotal; import org.kuali.kfs.gl.businessobject.PosterOutputSummaryBalanceTypeFiscalYearTotal; import org.kuali.kfs.gl.businessobject.PosterOutputSummaryBalanceTypeTotal; import org.kuali.kfs.gl.businessobject.PosterOutputSummaryEntry; import org.kuali.kfs.gl.businessobject.PosterOutputSummaryTotal; import org.kuali.kfs.gl.businessobject.Transaction; import org.kuali.kfs.gl.service.PosterOutputSummaryService; import org.kuali.kfs.sys.KFSKeyConstants; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.service.ReportWriterService; import org.kuali.rice.core.api.config.property.ConfigurationService; /** * A class which builds up the data and then reports the PosterOutputSummary report */ public class PosterOutputSummaryReport { private Map<String, PosterOutputSummaryEntry> posterOutputSummaryEntries; private PosterOutputSummaryTotal posterOutputSummaryTotal; private PosterOutputSummaryService posterOutputSummaryService; /** * Constructs a PosterOutputSummaryReport */ public PosterOutputSummaryReport() { posterOutputSummaryTotal = new PosterOutputSummaryTotal(); posterOutputSummaryEntries = new LinkedHashMap<String, PosterOutputSummaryEntry>(); } /** * Summarizes a transaction for this report * @param transaction the transaction to summarize */ public void summarize(Transaction transaction) { getPosterOutputSummaryService().summarize(transaction, posterOutputSummaryEntries); } /** * Summarizes an origin entry for this report * @param originEntry the origin entry to summarize */ public void summarize(OriginEntryInformation originEntry) { getPosterOutputSummaryService().summarize(originEntry, posterOutputSummaryEntries); } /** * Writes the report to the given reportWriterService * @param reportWriterService the reportWriterService to write the report to */ public void writeReport(ReportWriterService reportWriterService) { List<PosterOutputSummaryEntry> entries = new ArrayList<PosterOutputSummaryEntry>(posterOutputSummaryEntries.values()); if (entries.size() > 0) { Collections.sort(entries, getPosterOutputSummaryService().getEntryComparator()); final ConfigurationService configurationService = SpringContext.getBean(ConfigurationService.class); String currentBalanceTypeCode = entries.get(0).getBalanceTypeCode(); PosterOutputSummaryBalanceTypeTotal balanceTypeTotal = new PosterOutputSummaryBalanceTypeTotal(currentBalanceTypeCode); Integer currentFiscalYear = entries.get(0).getUniversityFiscalYear(); PosterOutputSummaryBalanceTypeFiscalYearTotal balanceTypeFiscalYearTotal = new PosterOutputSummaryBalanceTypeFiscalYearTotal(currentBalanceTypeCode, currentFiscalYear); String currentFiscalPeriod = entries.get(0).getFiscalPeriodCode(); PosterOutputSummaryBalanceTypeFiscalYearAndPeriodTotal balanceTypeFiscalYearAndPeriodTotal = new PosterOutputSummaryBalanceTypeFiscalYearAndPeriodTotal(currentBalanceTypeCode, currentFiscalYear, currentFiscalPeriod); final String titleMessage = configurationService.getPropertyValueAsString(KFSKeyConstants.MESSAGE_REPORT_POSTER_OUTPUT_SUMMARY_TITLE_LINE); String formattedTitle = MessageFormat.format(titleMessage, entries.get(0).getUniversityFiscalYear().toString(), entries.get(0).getBalanceTypeCode()); reportWriterService.writeFormattedMessageLine(formattedTitle); reportWriterService.writeTableHeader(entries.get(0)); for (PosterOutputSummaryEntry entry : entries) { if (!entry.getBalanceTypeCode().equals(currentBalanceTypeCode)) { reportWriterService.writeTableRow(balanceTypeFiscalYearAndPeriodTotal); reportWriterService.writeTableRow(balanceTypeFiscalYearTotal); reportWriterService.writeTableRow(balanceTypeTotal); balanceTypeFiscalYearAndPeriodTotal = new PosterOutputSummaryBalanceTypeFiscalYearAndPeriodTotal(entry.getBalanceTypeCode(), entry.getUniversityFiscalYear(), entry.getFiscalPeriodCode()); balanceTypeFiscalYearTotal = new PosterOutputSummaryBalanceTypeFiscalYearTotal(entry.getBalanceTypeCode(), entry.getUniversityFiscalYear()); balanceTypeTotal = new PosterOutputSummaryBalanceTypeTotal(entry.getBalanceTypeCode()); currentBalanceTypeCode = entry.getBalanceTypeCode(); currentFiscalYear = entry.getUniversityFiscalYear(); currentFiscalPeriod = entry.getFiscalPeriodCode(); // new top-level header for balance types reportWriterService.pageBreak(); formattedTitle = MessageFormat.format(titleMessage, currentFiscalYear.toString(), currentBalanceTypeCode); reportWriterService.writeFormattedMessageLine(formattedTitle); reportWriterService.writeTableHeader(entry); } else if (!entry.getUniversityFiscalYear().equals(currentFiscalYear)) { reportWriterService.writeTableRow(balanceTypeFiscalYearAndPeriodTotal); reportWriterService.writeTableRow(balanceTypeFiscalYearTotal); balanceTypeFiscalYearAndPeriodTotal = new PosterOutputSummaryBalanceTypeFiscalYearAndPeriodTotal(entry.getBalanceTypeCode(), entry.getUniversityFiscalYear(), entry.getFiscalPeriodCode()); balanceTypeFiscalYearTotal = new PosterOutputSummaryBalanceTypeFiscalYearTotal(entry.getBalanceTypeCode(), entry.getUniversityFiscalYear()); currentFiscalYear = entry.getUniversityFiscalYear(); currentFiscalPeriod = entry.getFiscalPeriodCode(); } else if (!entry.getFiscalPeriodCode().equals(currentFiscalPeriod)) { reportWriterService.writeTableRow(balanceTypeFiscalYearAndPeriodTotal); balanceTypeFiscalYearAndPeriodTotal = new PosterOutputSummaryBalanceTypeFiscalYearAndPeriodTotal(entry.getBalanceTypeCode(), entry.getUniversityFiscalYear(), entry.getFiscalPeriodCode()); currentFiscalPeriod = entry.getFiscalPeriodCode(); } reportWriterService.writeTableRow(entry); balanceTypeFiscalYearAndPeriodTotal.addAmount(entry); balanceTypeFiscalYearTotal.addAmount(entry); balanceTypeTotal.addAmount(entry); posterOutputSummaryTotal.addAmount(entry); } reportWriterService.writeTableRow(balanceTypeFiscalYearAndPeriodTotal); reportWriterService.writeTableRow(balanceTypeFiscalYearTotal); reportWriterService.writeTableRow(balanceTypeTotal); reportWriterService.writeNewLines(1); reportWriterService.writeTableRow(posterOutputSummaryTotal); } } /** * @return an implementation of the PosterOutputSummaryService */ public PosterOutputSummaryService getPosterOutputSummaryService() { if (posterOutputSummaryService == null) { posterOutputSummaryService = SpringContext.getBean(PosterOutputSummaryService.class); } return posterOutputSummaryService; } }
ua-eas/ua-kfs-5.3
work/src/org/kuali/kfs/gl/report/PosterOutputSummaryReport.java
Java
agpl-3.0
8,926
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.tem.batch.service; import java.util.List; import org.kuali.kfs.module.tem.businessobject.HistoricalTravelExpense; public interface TravelImportedExpenseNotificationService { /** * send notifications to the travelers of newly imported or unused imported expenses from corporate card, CTS, or pre-trip * payments that need to be reconciled */ public void sendImportedExpenseNotification(); /** * send notifications to the given traveler of newly imported or unused imported expenses from corporate card, CTS, or pre-trip * payments that need to be reconciled * * @param travelerProfileId the profile id of a traveler * @param expensesOfTraveler the expenses of the given traveler */ public void sendImportedExpenseNotification(Integer travelerProfileId, List<HistoricalTravelExpense> expensesOfTraveler); /** * send notifications to the given traveler of newly imported or unused imported expenses from corporate card, CTS, or pre-trip * payments that need to be reconciled * * @param travelerProfileId the profile id of a traveler */ public void sendImportedExpenseNotification(Integer travelerProfileId); }
ua-eas/ua-kfs-5.3
work/src/org/kuali/kfs/module/tem/batch/service/TravelImportedExpenseNotificationService.java
Java
agpl-3.0
2,116
/* * IRremote * Version 0.1 July, 2009 * Copyright 2009 Ken Shirriff * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html * * Modified by Paul Stoffregen <[email protected]> to support other boards and timers * * Interrupt code based on NECIRrcv by Joe Knapp * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ * * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) * Whynter A/C ARC-110WD added by Francesco Meschia */ #ifndef IRremoteint_h #define IRremoteint_h #if defined(ARDUINO) && ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif // define which timer to use // // Uncomment the timer you wish to use on your board. If you // are using another library which uses timer2, you have options // to switch IRremote to use a different timer. // Arduino Mega #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) //#define IR_USE_TIMER1 // tx = pin 11 #define IR_USE_TIMER2 // tx = pin 9 //#define IR_USE_TIMER3 // tx = pin 5 //#define IR_USE_TIMER4 // tx = pin 6 //#define IR_USE_TIMER5 // tx = pin 46 // Teensy 1.0 #elif defined(__AVR_AT90USB162__) #define IR_USE_TIMER1 // tx = pin 17 // Teensy 2.0 #elif defined(__AVR_ATmega32U4__) //#define IR_USE_TIMER1 // tx = pin 14 //#define IR_USE_TIMER3 // tx = pin 9 #define IR_USE_TIMER4_HS // tx = pin 10 // Teensy 3.0 #elif defined(__MK20DX128__) #define IR_USE_TIMER_CMT // tx = pin 5 // Teensy++ 1.0 & 2.0 #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) //#define IR_USE_TIMER1 // tx = pin 25 #define IR_USE_TIMER2 // tx = pin 1 //#define IR_USE_TIMER3 // tx = pin 16 // Sanguino #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) //#define IR_USE_TIMER1 // tx = pin 13 #define IR_USE_TIMER2 // tx = pin 14 // Atmega8 #elif defined(__AVR_ATmega8P__) || defined(__AVR_ATmega8__) #define IR_USE_TIMER1 // tx = pin 9 // Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, etc #else //#define IR_USE_TIMER1 // tx = pin 9 #define IR_USE_TIMER2 // tx = pin 3 #endif #ifdef F_CPU #define SYSCLOCK F_CPU // main Arduino clock #else #define SYSCLOCK 16000000 // main Arduino clock #endif #define ERR 0 #define DECODED 1 // defines for setting and clearing register bits #ifndef cbi #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) #endif #ifndef sbi #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #endif // Pulse parms are *50-100 for the Mark and *50+100 for the space // First MARK is the one after the long gap // pulse parameters in usec #define WHYNTER_HDR_MARK 2850 #define WHYNTER_HDR_SPACE 2850 #define WHYNTER_BIT_MARK 750 #define WHYNTER_ONE_MARK 750 #define WHYNTER_ONE_SPACE 2150 #define WHYNTER_ZERO_MARK 750 #define WHYNTER_ZERO_SPACE 750 #define NEC_HDR_MARK 9000 #define NEC_HDR_SPACE 4500 #define NEC_BIT_MARK 560 #define NEC_ONE_SPACE 1690 #define NEC_ZERO_SPACE 560 #define NEC_RPT_SPACE 2250 #define SONY_HDR_MARK 2400 #define SONY_HDR_SPACE 600 #define SONY_ONE_MARK 1200 #define SONY_ZERO_MARK 600 #define SONY_RPT_LENGTH 45000 #define SONY_DOUBLE_SPACE_USECS 500 // usually ssee 713 - not using ticks as get number wrapround // SA 8650B #define SANYO_HDR_MARK 3500 // seen range 3500 #define SANYO_HDR_SPACE 950 // seen 950 #define SANYO_ONE_MARK 2400 // seen 2400 #define SANYO_ZERO_MARK 700 // seen 700 #define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround #define SANYO_RPT_LENGTH 45000 // Mitsubishi RM 75501 // 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7 // #define MITSUBISHI_HDR_MARK 250 // seen range 3500 #define MITSUBISHI_HDR_SPACE 350 // 7*50+100 #define MITSUBISHI_ONE_MARK 1950 // 41*50-100 #define MITSUBISHI_ZERO_MARK 750 // 17*50-100 // #define MITSUBISHI_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround // #define MITSUBISHI_RPT_LENGTH 45000 #define RC5_T1 889 #define RC5_RPT_LENGTH 46000 #define RC6_HDR_MARK 2666 #define RC6_HDR_SPACE 889 #define RC6_T1 444 #define RC6_RPT_LENGTH 46000 #define SHARP_BIT_MARK 245 #define SHARP_ONE_SPACE 1805 #define SHARP_ZERO_SPACE 795 #define SHARP_GAP 600000 #define SHARP_TOGGLE_MASK 0x3FF #define SHARP_RPT_SPACE 3000 #define DISH_HDR_MARK 400 #define DISH_HDR_SPACE 6100 #define DISH_BIT_MARK 400 #define DISH_ONE_SPACE 1700 #define DISH_ZERO_SPACE 2800 #define DISH_RPT_SPACE 6200 #define DISH_TOP_BIT 0x8000 #define PANASONIC_HDR_MARK 3502 #define PANASONIC_HDR_SPACE 1750 #define PANASONIC_BIT_MARK 502 #define PANASONIC_ONE_SPACE 1244 #define PANASONIC_ZERO_SPACE 400 #define JVC_HDR_MARK 8000 #define JVC_HDR_SPACE 4000 #define JVC_BIT_MARK 600 #define JVC_ONE_SPACE 1600 #define JVC_ZERO_SPACE 550 #define JVC_RPT_LENGTH 60000 #define LG_HDR_MARK 8000 #define LG_HDR_SPACE 4000 #define LG_BIT_MARK 600 #define LG_ONE_SPACE 1600 #define LG_ZERO_SPACE 550 #define LG_RPT_LENGTH 60000 #define SAMSUNG_HDR_MARK 5000 #define SAMSUNG_HDR_SPACE 5000 #define SAMSUNG_BIT_MARK 560 #define SAMSUNG_ONE_SPACE 1600 #define SAMSUNG_ZERO_SPACE 560 #define SAMSUNG_RPT_SPACE 2250 #define SHARP_BITS 15 #define DISH_BITS 16 // AIWA RC T501 // Lirc file http://lirc.sourceforge.net/remotes/aiwa/RC-T501 #define AIWA_RC_T501_HZ 38 #define AIWA_RC_T501_BITS 15 #define AIWA_RC_T501_PRE_BITS 26 #define AIWA_RC_T501_POST_BITS 1 #define AIWA_RC_T501_SUM_BITS AIWA_RC_T501_PRE_BITS+AIWA_RC_T501_BITS+AIWA_RC_T501_POST_BITS #define AIWA_RC_T501_HDR_MARK 8800 #define AIWA_RC_T501_HDR_SPACE 4500 #define AIWA_RC_T501_BIT_MARK 500 #define AIWA_RC_T501_ONE_SPACE 600 #define AIWA_RC_T501_ZERO_SPACE 1700 #define TOLERANCE 25 // percent tolerance in measurements #define LTOL (1.0 - TOLERANCE/100.) #define UTOL (1.0 + TOLERANCE/100.) #define _GAP 5000 // Minimum map between transmissions #define GAP_TICKS (_GAP/USECPERTICK) #define TICKS_LOW(us) (int) (((us)*LTOL/USECPERTICK)) #define TICKS_HIGH(us) (int) (((us)*UTOL/USECPERTICK + 1)) // receiver states #define STATE_IDLE 2 #define STATE_MARK 3 #define STATE_SPACE 4 #define STATE_STOP 5 // information for the interrupt handler typedef struct { uint8_t recvpin; // pin for IR data from detector uint8_t rcvstate; // state machine uint8_t blinkflag; // TRUE to enable blinking of pin 13 on IR processing unsigned int timer; // state timer, counts 50uS ticks. unsigned int rawbuf[RAWBUF]; // raw data uint8_t rawlen; // counter of entries in rawbuf } irparams_t; // Defined in IRremote.cpp extern volatile irparams_t irparams; // IR detector output is active low #define MARK 0 #define SPACE 1 #define TOPBIT 0x80000000 #define NEC_BITS 32 #define SONY_BITS 12 #define SANYO_BITS 12 #define MITSUBISHI_BITS 16 #define MIN_RC5_SAMPLES 11 #define MIN_RC6_SAMPLES 1 #define PANASONIC_BITS 48 #define JVC_BITS 16 #define LG_BITS 28 #define SAMSUNG_BITS 32 #define WHYNTER_BITS 32 // defines for timer2 (8 bits) #if defined(IR_USE_TIMER2) #define TIMER_RESET #define TIMER_ENABLE_PWM (TCCR2A |= _BV(COM2B1)) #define TIMER_DISABLE_PWM (TCCR2A &= ~(_BV(COM2B1))) #define TIMER_ENABLE_INTR (TIMSK2 = _BV(OCIE2A)) #define TIMER_DISABLE_INTR (TIMSK2 = 0) #define TIMER_INTR_NAME TIMER2_COMPA_vect #define TIMER_CONFIG_KHZ(val) ({ \ const uint8_t pwmval = SYSCLOCK / 2000 / (val); \ TCCR2A = _BV(WGM20); \ TCCR2B = _BV(WGM22) | _BV(CS20); \ OCR2A = pwmval; \ OCR2B = pwmval / 3; \ }) #define TIMER_COUNT_TOP (SYSCLOCK * USECPERTICK / 1000000) #if (TIMER_COUNT_TOP < 256) #define TIMER_CONFIG_NORMAL() ({ \ TCCR2A = _BV(WGM21); \ TCCR2B = _BV(CS20); \ OCR2A = TIMER_COUNT_TOP; \ TCNT2 = 0; \ }) #else #define TIMER_CONFIG_NORMAL() ({ \ TCCR2A = _BV(WGM21); \ TCCR2B = _BV(CS21); \ OCR2A = TIMER_COUNT_TOP / 8; \ TCNT2 = 0; \ }) #endif #if defined(CORE_OC2B_PIN) #define TIMER_PWM_PIN CORE_OC2B_PIN /* Teensy */ #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define TIMER_PWM_PIN 9 /* Arduino Mega */ #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) #define TIMER_PWM_PIN 14 /* Sanguino */ #else #define TIMER_PWM_PIN 3 /* Arduino Duemilanove, Diecimila, LilyPad, etc */ #endif // defines for timer1 (16 bits) #elif defined(IR_USE_TIMER1) #define TIMER_RESET #define TIMER_ENABLE_PWM (TCCR1A |= _BV(COM1A1)) #define TIMER_DISABLE_PWM (TCCR1A &= ~(_BV(COM1A1))) #if defined(__AVR_ATmega8P__) || defined(__AVR_ATmega8__) #define TIMER_ENABLE_INTR (TIMSK |= _BV(OCIE1A)) #define TIMER_DISABLE_INTR (TIMSK &= ~_BV(OCIE1A)) #else #define TIMER_ENABLE_INTR (TIMSK1 = _BV(OCIE1A)) #define TIMER_DISABLE_INTR (TIMSK1 = 0) #endif #define TIMER_INTR_NAME TIMER1_COMPA_vect #define TIMER_CONFIG_KHZ(val) ({ \ const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ TCCR1A = _BV(WGM11); \ TCCR1B = _BV(WGM13) | _BV(CS10); \ ICR1 = pwmval; \ OCR1A = pwmval / 3; \ }) #define TIMER_CONFIG_NORMAL() ({ \ TCCR1A = 0; \ TCCR1B = _BV(WGM12) | _BV(CS10); \ OCR1A = SYSCLOCK * USECPERTICK / 1000000; \ TCNT1 = 0; \ }) #if defined(CORE_OC1A_PIN) #define TIMER_PWM_PIN CORE_OC1A_PIN /* Teensy */ #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define TIMER_PWM_PIN 11 /* Arduino Mega */ #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) #define TIMER_PWM_PIN 13 /* Sanguino */ #else #define TIMER_PWM_PIN 9 /* Arduino Duemilanove, Diecimila, LilyPad, etc */ #endif // defines for timer3 (16 bits) #elif defined(IR_USE_TIMER3) #define TIMER_RESET #define TIMER_ENABLE_PWM (TCCR3A |= _BV(COM3A1)) #define TIMER_DISABLE_PWM (TCCR3A &= ~(_BV(COM3A1))) #define TIMER_ENABLE_INTR (TIMSK3 = _BV(OCIE3A)) #define TIMER_DISABLE_INTR (TIMSK3 = 0) #define TIMER_INTR_NAME TIMER3_COMPA_vect #define TIMER_CONFIG_KHZ(val) ({ \ const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ TCCR3A = _BV(WGM31); \ TCCR3B = _BV(WGM33) | _BV(CS30); \ ICR3 = pwmval; \ OCR3A = pwmval / 3; \ }) #define TIMER_CONFIG_NORMAL() ({ \ TCCR3A = 0; \ TCCR3B = _BV(WGM32) | _BV(CS30); \ OCR3A = SYSCLOCK * USECPERTICK / 1000000; \ TCNT3 = 0; \ }) #if defined(CORE_OC3A_PIN) #define TIMER_PWM_PIN CORE_OC3A_PIN /* Teensy */ #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define TIMER_PWM_PIN 5 /* Arduino Mega */ #else #error "Please add OC3A pin number here\n" #endif // defines for timer4 (10 bits, high speed option) #elif defined(IR_USE_TIMER4_HS) #define TIMER_RESET #define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1)) #define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1))) #define TIMER_ENABLE_INTR (TIMSK4 = _BV(TOIE4)) #define TIMER_DISABLE_INTR (TIMSK4 = 0) #define TIMER_INTR_NAME TIMER4_OVF_vect #define TIMER_CONFIG_KHZ(val) ({ \ const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ TCCR4A = (1<<PWM4A); \ TCCR4B = _BV(CS40); \ TCCR4C = 0; \ TCCR4D = (1<<WGM40); \ TCCR4E = 0; \ TC4H = pwmval >> 8; \ OCR4C = pwmval; \ TC4H = (pwmval / 3) >> 8; \ OCR4A = (pwmval / 3) & 255; \ }) #define TIMER_CONFIG_NORMAL() ({ \ TCCR4A = 0; \ TCCR4B = _BV(CS40); \ TCCR4C = 0; \ TCCR4D = 0; \ TCCR4E = 0; \ TC4H = (SYSCLOCK * USECPERTICK / 1000000) >> 8; \ OCR4C = (SYSCLOCK * USECPERTICK / 1000000) & 255; \ TC4H = 0; \ TCNT4 = 0; \ }) #if defined(CORE_OC4A_PIN) #define TIMER_PWM_PIN CORE_OC4A_PIN /* Teensy */ #elif defined(__AVR_ATmega32U4__) #define TIMER_PWM_PIN 13 /* Leonardo */ #else #error "Please add OC4A pin number here\n" #endif // defines for timer4 (16 bits) #elif defined(IR_USE_TIMER4) #define TIMER_RESET #define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1)) #define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1))) #define TIMER_ENABLE_INTR (TIMSK4 = _BV(OCIE4A)) #define TIMER_DISABLE_INTR (TIMSK4 = 0) #define TIMER_INTR_NAME TIMER4_COMPA_vect #define TIMER_CONFIG_KHZ(val) ({ \ const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ TCCR4A = _BV(WGM41); \ TCCR4B = _BV(WGM43) | _BV(CS40); \ ICR4 = pwmval; \ OCR4A = pwmval / 3; \ }) #define TIMER_CONFIG_NORMAL() ({ \ TCCR4A = 0; \ TCCR4B = _BV(WGM42) | _BV(CS40); \ OCR4A = SYSCLOCK * USECPERTICK / 1000000; \ TCNT4 = 0; \ }) #if defined(CORE_OC4A_PIN) #define TIMER_PWM_PIN CORE_OC4A_PIN #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define TIMER_PWM_PIN 6 /* Arduino Mega */ #else #error "Please add OC4A pin number here\n" #endif // defines for timer5 (16 bits) #elif defined(IR_USE_TIMER5) #define TIMER_RESET #define TIMER_ENABLE_PWM (TCCR5A |= _BV(COM5A1)) #define TIMER_DISABLE_PWM (TCCR5A &= ~(_BV(COM5A1))) #define TIMER_ENABLE_INTR (TIMSK5 = _BV(OCIE5A)) #define TIMER_DISABLE_INTR (TIMSK5 = 0) #define TIMER_INTR_NAME TIMER5_COMPA_vect #define TIMER_CONFIG_KHZ(val) ({ \ const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ TCCR5A = _BV(WGM51); \ TCCR5B = _BV(WGM53) | _BV(CS50); \ ICR5 = pwmval; \ OCR5A = pwmval / 3; \ }) #define TIMER_CONFIG_NORMAL() ({ \ TCCR5A = 0; \ TCCR5B = _BV(WGM52) | _BV(CS50); \ OCR5A = SYSCLOCK * USECPERTICK / 1000000; \ TCNT5 = 0; \ }) #if defined(CORE_OC5A_PIN) #define TIMER_PWM_PIN CORE_OC5A_PIN #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define TIMER_PWM_PIN 46 /* Arduino Mega */ #else #error "Please add OC5A pin number here\n" #endif // defines for special carrier modulator timer #elif defined(IR_USE_TIMER_CMT) #define TIMER_RESET ({ \ uint8_t tmp = CMT_MSC; \ CMT_CMD2 = 30; \ }) #define TIMER_ENABLE_PWM CORE_PIN5_CONFIG = PORT_PCR_MUX(2)|PORT_PCR_DSE|PORT_PCR_SRE #define TIMER_DISABLE_PWM CORE_PIN5_CONFIG = PORT_PCR_MUX(1)|PORT_PCR_DSE|PORT_PCR_SRE #define TIMER_ENABLE_INTR NVIC_ENABLE_IRQ(IRQ_CMT) #define TIMER_DISABLE_INTR NVIC_DISABLE_IRQ(IRQ_CMT) #define TIMER_INTR_NAME cmt_isr #ifdef ISR #undef ISR #endif #define ISR(f) void f(void) #if F_BUS == 48000000 #define CMT_PPS_VAL 5 #else #define CMT_PPS_VAL 2 #endif #define TIMER_CONFIG_KHZ(val) ({ \ SIM_SCGC4 |= SIM_SCGC4_CMT; \ SIM_SOPT2 |= SIM_SOPT2_PTD7PAD; \ CMT_PPS = CMT_PPS_VAL; \ CMT_CGH1 = 2667 / val; \ CMT_CGL1 = 5333 / val; \ CMT_CMD1 = 0; \ CMT_CMD2 = 30; \ CMT_CMD3 = 0; \ CMT_CMD4 = 0; \ CMT_OC = 0x60; \ CMT_MSC = 0x01; \ }) #define TIMER_CONFIG_NORMAL() ({ \ SIM_SCGC4 |= SIM_SCGC4_CMT; \ CMT_PPS = CMT_PPS_VAL; \ CMT_CGH1 = 1; \ CMT_CGL1 = 1; \ CMT_CMD1 = 0; \ CMT_CMD2 = 30; \ CMT_CMD3 = 0; \ CMT_CMD4 = 19; \ CMT_OC = 0; \ CMT_MSC = 0x03; \ }) #define TIMER_PWM_PIN 5 #else // unknown timer #error "Internal code configuration error, no known IR_USE_TIMER# defined\n" #endif // defines for blinking the LED #if defined(CORE_LED0_PIN) #define BLINKLED CORE_LED0_PIN #define BLINKLED_ON() (digitalWrite(CORE_LED0_PIN, HIGH)) #define BLINKLED_OFF() (digitalWrite(CORE_LED0_PIN, LOW)) #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define BLINKLED 13 #define BLINKLED_ON() (PORTB |= B10000000) #define BLINKLED_OFF() (PORTB &= B01111111) #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) #define BLINKLED 0 #define BLINKLED_ON() (PORTD |= B00000001) #define BLINKLED_OFF() (PORTD &= B11111110) #else #define BLINKLED 13 #define BLINKLED_ON() (PORTB |= B00100000) #define BLINKLED_OFF() (PORTB &= B11011111) #endif #endif
aldrinleal/irremote-spark
firmware/IRremoteInt.h
C
lgpl-2.1
15,691
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.domain.controller.resources; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ListAttributeDefinition; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReadResourceNameOperationStepHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.as.domain.controller.LocalHostControllerInfo; import org.jboss.as.domain.controller.operations.DomainIncludesValidationWriteAttributeHandler; import org.jboss.as.domain.controller.operations.GenericModelDescribeOperationHandler; import org.jboss.as.domain.controller.operations.ProfileAddHandler; import org.jboss.as.domain.controller.operations.ProfileCloneHandler; import org.jboss.as.domain.controller.operations.ProfileDescribeHandler; import org.jboss.as.domain.controller.operations.ProfileModelDescribeHandler; import org.jboss.as.domain.controller.operations.ProfileRemoveHandler; import org.jboss.as.host.controller.ignored.IgnoredDomainResourceRegistry; import org.jboss.dmr.ModelType; /** * @author <a href="[email protected]">Kabir Khan</a> */ public class ProfileResourceDefinition extends SimpleResourceDefinition { public static final PathElement PATH = PathElement.pathElement(PROFILE); static final String PROFILE_CAPABILITY_NAME = "org.wildfly.domain.profile"; public static final RuntimeCapability<Void> PROFILE_CAPABILITY = RuntimeCapability.Builder.of(PROFILE_CAPABILITY_NAME, true) .build(); private static OperationDefinition DESCRIBE = new SimpleOperationDefinitionBuilder(ModelDescriptionConstants.DESCRIBE, DomainResolver.getResolver(PROFILE, false)) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG) .setReplyType(ModelType.LIST) .setReplyValueType(ModelType.OBJECT) .withFlag(OperationEntry.Flag.HIDDEN) .setReadOnly() .build(); //This attribute exists in 7.1.2 and 7.1.3 but was always nillable public static final SimpleAttributeDefinition NAME = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.NAME, ModelType.STRING) .setValidator(new StringLengthValidator(1, true)) .setRequired(false) .setResourceOnly() .build(); public static final ListAttributeDefinition INCLUDES = new StringListAttributeDefinition.Builder(ModelDescriptionConstants.INCLUDES) .setRequired(false) .setElementValidator(new StringLengthValidator(1, true)) .setCapabilityReference(PROFILE_CAPABILITY_NAME, PROFILE_CAPABILITY_NAME) .build(); public static final AttributeDefinition[] ATTRIBUTES = new AttributeDefinition[] {INCLUDES}; private final LocalHostControllerInfo hostInfo; private final IgnoredDomainResourceRegistry ignoredDomainResourceRegistry; public ProfileResourceDefinition(LocalHostControllerInfo hostInfo, IgnoredDomainResourceRegistry ignoredDomainResourceRegistry) { super(new SimpleResourceDefinition.Parameters(PATH, DomainResolver.getResolver(PROFILE, false)) .setAddHandler(ProfileAddHandler.INSTANCE) .setRemoveHandler(ProfileRemoveHandler.INSTANCE) .addCapabilities(PROFILE_CAPABILITY) ); this.hostInfo = hostInfo; this.ignoredDomainResourceRegistry = ignoredDomainResourceRegistry; } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(DESCRIBE, ProfileDescribeHandler.INSTANCE); resourceRegistration.registerOperationHandler(ProfileCloneHandler.DEFINITION, new ProfileCloneHandler(hostInfo, ignoredDomainResourceRegistry)); resourceRegistration.registerOperationHandler(GenericModelDescribeOperationHandler.DEFINITION, ProfileModelDescribeHandler.INSTANCE); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(NAME, ReadResourceNameOperationStepHandler.INSTANCE); resourceRegistration.registerReadWriteAttribute(INCLUDES, null, createIncludesValidationHandler()); } public static OperationStepHandler createIncludesValidationHandler() { return new DomainIncludesValidationWriteAttributeHandler(INCLUDES); } }
yersan/wildfly-core
host-controller/src/main/java/org/jboss/as/domain/controller/resources/ProfileResourceDefinition.java
Java
lgpl-2.1
6,359
/* * Copyright (c) JForum Team. All rights reserved. * * The software in this package is published under the terms of the LGPL * license a copy of which has been included with this distribution in the * license.txt file. * * The JForum Project * http://www.jforum.net */ package net.jforum.controllers; import java.util.Date; import net.jforum.actions.helpers.Domain; import net.jforum.core.SecurityConstraint; import net.jforum.core.SessionManager; import net.jforum.entities.Forum; import net.jforum.entities.Topic; import net.jforum.entities.UserSession; import net.jforum.entities.util.PaginatedResult; import net.jforum.entities.util.Pagination; import net.jforum.repository.CategoryRepository; import net.jforum.repository.ForumRepository; import net.jforum.repository.UserRepository; import net.jforum.security.AccessForumRule; import net.jforum.security.AuthenticatedRule; import net.jforum.services.MostUsersEverOnlineService; import net.jforum.util.ConfigKeys; import net.jforum.util.GroupInteractionFilter; import net.jforum.util.JForumConfig; import net.jforum.util.SecurityConstants; import br.com.caelum.vraptor.Path; import br.com.caelum.vraptor.Resource; import br.com.caelum.vraptor.Result; /** * @author Rafael Steil */ @Resource @Path(Domain.FORUMS) public class ForumController { private CategoryRepository categoryRepository; private ForumRepository forumRepository; private UserRepository userRepository; private MostUsersEverOnlineService mostUsersEverOnlineService; private JForumConfig config; private GroupInteractionFilter groupInteractionFilter; private final Result result; private final UserSession userSession; private final SessionManager sessionManager; public ForumController(CategoryRepository categoryRepository, ForumRepository forumRepository, UserSession userSession, UserRepository userRepository, MostUsersEverOnlineService mostUsersEverOnlineService, JForumConfig config, GroupInteractionFilter groupInteractionFilter, Result result, SessionManager sessionManager) { this.categoryRepository = categoryRepository; this.userSession = userSession; this.forumRepository = forumRepository; this.userRepository = userRepository; this.mostUsersEverOnlineService = mostUsersEverOnlineService; this.config = config; this.groupInteractionFilter = groupInteractionFilter; this.result = result; this.sessionManager = sessionManager; } /** * Show the new messages since the last time the user did something in the forum */ @SecurityConstraint(value = AuthenticatedRule.class, displayLogin = true) public void newMessages(int page) { UserSession userSession = this.userSession; int recordsPerPage = this.config.getInt(ConfigKeys.TOPICS_PER_PAGE); PaginatedResult<Topic> newMessages = this.forumRepository.getNewMessages(new Date(userSession.getLastVisit()), new Pagination().calculeStart(page, recordsPerPage), recordsPerPage); Pagination pagination = new Pagination(this.config, page).forNewMessages(newMessages.getTotalRecords()); this.result.include("pagination", pagination); this.result.include("results", newMessages.getResults()); this.result.include("categories", this.categoryRepository.getAllCategories()); } /** * Show topics from a forum */ @SecurityConstraint(value = AccessForumRule.class, displayLogin = true) @Path({"/show/{forumId}", "/show/{forumId}/{page}"}) public void show(int forumId, int page) { Forum forum = this.forumRepository.get(forumId); Pagination pagination = new Pagination(this.config, page).forForum(forum); this.result.include("forum", forum); this.result.include("pagination", pagination); this.result.include("isModeratorOnline", this.sessionManager.isModeratorOnline()); this.result.include("categories", this.categoryRepository.getAllCategories()); this.result.include("topics", forum.getTopics(pagination.getStart(), pagination.getRecordsPerPage())); } /** * Listing of all forums */ public void list() { this.result.include("categories", this.categoryRepository.getAllCategories()); this.result.include("onlineUsers", this.sessionManager.getLoggedSessions()); this.result.include("totalRegisteredUsers", this.userRepository.getTotalUsers()); this.result.include("totalMessages", this.forumRepository.getTotalMessages()); this.result.include("totalLoggedUsers", this.sessionManager.getTotalLoggedUsers()); this.result.include("totalAnonymousUsers", this.sessionManager.getTotalAnonymousUsers()); this.result.include("lastRegisteredUser", this.userRepository.getLastRegisteredUser()); this.result.include("postsPerPage", this.config.getInt(ConfigKeys.POSTS_PER_PAGE)); this.result.include("mostUsersEverOnline", mostUsersEverOnlineService .getMostRecentData(this.sessionManager.getTotalUsers())); if (userSession.isLogged() && !userSession.getRoleManager().roleExists(SecurityConstants.INTERACT_OTHER_GROUPS)) { this.groupInteractionFilter.filterForumListing(this.result, userSession); } } }
ippxie/jforum3
src/main/java/net/jforum/controllers/ForumController.java
Java
lgpl-2.1
5,008
using System; namespace NHibernate.Test.NHSpecificTest.NH3332 { public class DataTypeDescription { private Culture _culture; private DataType _dataType; private String _description; // Assigned by reflection #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value private Byte[] _rowVersionId; #pragma warning restore CS0649 // Field is never assigned to, and will always have its default value public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object obj) { return ReferenceEquals(this, obj); } public virtual String Description { get { return _description; } set { _description = value; } } public virtual Byte[] RowVersionId { get { return _rowVersionId; } } public virtual Culture Culture { get { return _culture; } set { _culture = value; } } public virtual DataType DataType { get { return _dataType; } set { _dataType = value; } } } }
RogerKratz/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH3332/DataTypeDescription.cs
C#
lgpl-2.1
1,022
/* pvfileio.h: Copyright (C) 2000 Richard Dobson This file is part of Csound. The Csound Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Csound; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* pvfileio.h: header file for PVOC_EX file format */ /* Initial Version 0.1 RWD 25:5:2000 all rights reserved: work in progress! */ #ifndef __PVFILEIO_H_INCLUDED #define __PVFILEIO_H_INCLUDED #include "sysdep.h" #if defined(WIN32) || defined(_WIN32) || defined(_MSC_VER) #include <windows.h> #else typedef struct { uint32_t Data1; uint16_t Data2; uint16_t Data3; unsigned char Data4[8]; } GUID; typedef struct /* waveformatex */ { uint16_t wFormatTag; uint16_t nChannels; uint32_t nSamplesPerSec; uint32_t nAvgBytesPerSec; uint16_t nBlockAlign; uint16_t wBitsPerSample; uint16_t cbSize; } WAVEFORMATEX; #endif /* NB no support provided for double format (yet) */ typedef enum pvoc_wordformat { PVOC_IEEE_FLOAT, PVOC_IEEE_DOUBLE } pvoc_wordformat; /* include PVOC_COMPLEX for some parity with SDIF */ typedef enum pvoc_frametype { PVOC_AMP_FREQ = 0, PVOC_AMP_PHASE, PVOC_COMPLEX } pvoc_frametype; /* a minimal list */ typedef enum pvoc_windowtype { PVOC_DEFAULT = 0, PVOC_HAMMING = 0, PVOC_HANN, PVOC_KAISER, PVOC_RECT, PVOC_CUSTOM } pv_wtype; /* Renderer information: source is presumed to be of this type */ typedef enum pvoc_sampletype { STYPE_16, STYPE_24, STYPE_32, STYPE_IEEE_FLOAT } pv_stype; typedef struct pvoc_data { /* 32 bytes */ uint16_t wWordFormat; /* pvoc_wordformat */ uint16_t wAnalFormat; /* pvoc_frametype */ uint16_t wSourceFormat; /* WAVE_FORMAT_PCM or WAVE_FORMAT_IEEE_FLOAT */ uint16_t wWindowType; /* pvoc_windowtype */ uint32_t nAnalysisBins; /* implicit FFT size = (nAnalysisBins-1) * 2 */ uint32_t dwWinlen; /* analysis winlen, in samples */ /* NB may be != FFT size */ uint32_t dwOverlap; /* samples */ uint32_t dwFrameAlign; /* usually nAnalysisBins * 2 * sizeof(float) */ float fAnalysisRate; float fWindowParam; /* default 0.0f unless needed */ } PVOCDATA; typedef struct { WAVEFORMATEX Format; /* 18 bytes: info for renderer */ /* as well as for pvoc */ union { /* 2 bytes */ uint16_t wValidBitsPerSample; /* as per standard WAVE_EX: */ /* applies to renderer */ uint16_t wSamplesPerBlock; uint16_t wReserved; } Samples; uint32_t dwChannelMask; /* 4 bytes: can be used as in */ /* standrad WAVE_EX */ GUID SubFormat; /* 16 bytes */ } WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE; typedef struct { WAVEFORMATEXTENSIBLE wxFormat; /* 40 bytes */ uint32_t dwVersion; /* 4 bytes */ uint32_t dwDataSize; /* 4 bytes: sizeof PVOCDATA data block */ PVOCDATA data; /* 32 bytes */ } WAVEFORMATPVOCEX; /* total 80 bytes */ /* at least VC++ will give 84 for sizeof(WAVEFORMATPVOCEX), */ /* so we need our own version */ #define SIZEOF_FMTPVOCEX (80) /* for the same reason: */ #define SIZEOF_WFMTEX (18) #define PVX_VERSION (1) /******* the all-important PVOC GUID {8312B9C2-2E6E-11d4-A824-DE5B96C3AB21} **************/ #ifndef CSOUND_CSDL_H extern const GUID KSDATAFORMAT_SUBTYPE_PVOC; /* pvoc file handling functions */ const char *pvoc_errorstr(CSOUND *); int init_pvsys(CSOUND *); int pvoc_createfile(CSOUND *, const char *, uint32, uint32, uint32, uint32, int32, int, int, float, float *, uint32); int pvoc_openfile(CSOUND *, const char *filename, void *data_, void *fmt_); int pvoc_closefile(CSOUND *, int); int pvoc_putframes(CSOUND *, int ofd, const float *frame, int32 numframes); int pvoc_getframes(CSOUND *, int ifd, float *frames, uint32 nframes); int pvoc_framecount(CSOUND *, int ifd); int pvoc_fseek(CSOUND *, int ifd, int offset); int pvsys_release(CSOUND *); #endif /* CSOUND_CSDL_H */ #endif /* __PVFILEIO_H_INCLUDED */
csound/csound
include/pvfileio.h
C
lgpl-2.1
5,476
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by AsyncGenerator. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System.Linq; using NHibernate.Linq; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3800 { using System.Threading.Tasks; [TestFixture] public class FixtureAsync : BugTestCase { protected override void OnSetUp() { var tagA = new Tag() { Name = "A" }; var tagB = new Tag() { Name = "B" }; var project1 = new Project { Name = "ProjectOne" }; var compP1_x = new Component() { Name = "PONEx", Project = project1 }; var compP1_y = new Component() { Name = "PONEy", Project = project1 }; var project2 = new Project { Name = "ProjectTwo" }; var compP2_x = new Component() { Name = "PTWOx", Project = project2 }; var compP2_y = new Component() { Name = "PTWOy", Project = project2 }; using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { session.Save(tagA); session.Save(tagB); session.Save(project1); session.Save(compP1_x); session.Save(compP1_y); session.Save(project2); session.Save(compP2_x); session.Save(compP2_y); session.Save(new TimeRecord { TimeInHours = 1, Project = null, Components = { }, Tags = { tagA } }); session.Save(new TimeRecord { TimeInHours = 2, Project = null, Components = { }, Tags = { tagB } }); session.Save(new TimeRecord { TimeInHours = 3, Project = project1, Tags = { tagA, tagB } }); session.Save(new TimeRecord { TimeInHours = 4, Project = project1, Components = { compP1_x }, Tags = { tagB } }); session.Save(new TimeRecord { TimeInHours = 5, Project = project1, Components = { compP1_y }, Tags = { tagA } }); session.Save(new TimeRecord { TimeInHours = 6, Project = project1, Components = { compP1_x, compP1_y }, Tags = { } }); session.Save(new TimeRecord { TimeInHours = 7, Project = project2, Components = { }, Tags = { tagA, tagB } }); session.Save(new TimeRecord { TimeInHours = 8, Project = project2, Components = { compP2_x }, Tags = { tagB } }); session.Save(new TimeRecord { TimeInHours = 9, Project = project2, Components = { compP2_y }, Tags = { tagA } }); session.Save(new TimeRecord { TimeInHours = 10, Project = project2, Components = { compP2_x, compP2_y }, Tags = { } }); transaction.Commit(); } } protected override void OnTearDown() { using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { session.Delete("from TimeRecord"); session.Delete("from Component"); session.Delete("from Project"); session.Delete("from Tag"); transaction.Commit(); } } [Test] public async Task ExpectedHqlAsync() { using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { var baseQuery = session.Query<TimeRecord>(); Assert.That(await (baseQuery.SumAsync(x => x.TimeInHours)), Is.EqualTo(55)); var query = session.CreateQuery(@" select c.Id, count(t), sum(cast(t.TimeInHours as big_decimal)) from TimeRecord t left join t.Components as c group by c.Id"); var results = await (query.ListAsync<object[]>()); Assert.That(results.Select(x => x[1]), Is.EquivalentTo(new[] { 4, 2, 2, 2, 2 })); Assert.That(results.Select(x => x[2]), Is.EquivalentTo(new[] { 13, 10, 11, 18, 19 })); Assert.That(results.Sum(x => (decimal?)x[2]), Is.EqualTo(71)); await (transaction.RollbackAsync()); } } [Test] public async Task PureLinqAsync() { using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { var baseQuery = session.Query<TimeRecord>(); var query = from t in baseQuery from c in t.Components.Select(x => (object)x.Id).DefaultIfEmpty() let r = new object[] { c, t } group r by r[0] into g select new[] { g.Key, g.Select(x => x[1]).Count(), g.Select(x => x[1]).Sum(x => (decimal?)((TimeRecord)x).TimeInHours) }; var results = await (query.ToListAsync()); Assert.That(results.Select(x => x[1]), Is.EquivalentTo(new[] { 4, 2, 2, 2, 2 })); Assert.That(results.Select(x => x[2]), Is.EquivalentTo(new[] { 13, 10, 11, 18, 19 })); Assert.That(results.Sum(x => (decimal?)x[2]), Is.EqualTo(71)); await (transaction.RollbackAsync()); } } [Test] public async Task MethodGroupAsync() { using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { var baseQuery = session.Query<TimeRecord>(); var query = baseQuery .SelectMany(t => t.Components.Select(c => c.Id).DefaultIfEmpty().Select(c => new object[] { c, t })) .GroupBy(g => g[0], g => (TimeRecord)g[1]) .Select(g => new[] { g.Key, g.Count(), g.Sum(x => (decimal?)x.TimeInHours) }); var results = await (query.ToListAsync()); Assert.That(results.Select(x => x[1]), Is.EquivalentTo(new[] { 4, 2, 2, 2, 2 })); Assert.That(results.Select(x => x[2]), Is.EquivalentTo(new[] { 13, 10, 11, 18, 19 })); Assert.That(results.Sum(x => (decimal?)x[2]), Is.EqualTo(71)); await (transaction.RollbackAsync()); } } [Test] public async Task ComplexExampleAsync() { using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { var baseQuery = session.Query<TimeRecord>(); Assert.That(await (baseQuery.SumAsync(x => x.TimeInHours)), Is.EqualTo(55)); var query = baseQuery.Select(t => new object[] { t }) .SelectMany(t => ((TimeRecord)t[0]).Components.Select(c => (object)c.Id).DefaultIfEmpty().Select(c => new[] { t[0], c })) .SelectMany(t => ((TimeRecord)t[0]).Tags.Select(x => (object)x.Id).DefaultIfEmpty().Select(x => new[] { t[0], t[1], x })) .GroupBy(j => new[] { ((TimeRecord)j[0]).Project.Id, j[1], j[2] }, j => (TimeRecord)j[0]) .Select(g => new object[] { g.Key, g.Count(), g.Sum(t => (decimal?)t.TimeInHours) }); var results = await (query.ToListAsync()); Assert.That(results.Select(x => x[1]), Is.EquivalentTo(new[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 })); Assert.That(results.Select(x => x[2]), Is.EquivalentTo(new[] { 1, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 9, 10, 10 })); Assert.That(results.Sum(x => (decimal?)x[2]), Is.EqualTo(81)); await (transaction.RollbackAsync()); } } [Test] public async Task OuterJoinGroupingWithSubQueryInProjectionAsync() { if (!Dialect.SupportsScalarSubSelects) Assert.Ignore("Dialect does not support scalar sub-select"); using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { var baseQuery = session.Query<TimeRecord>(); var query = baseQuery .SelectMany(t => t.Components.Select(c => c.Name).DefaultIfEmpty().Select(c => new object[] { c, t })) .GroupBy(g => g[0], g => (TimeRecord)g[1]) .Select(g => new[] { g.Key, g.Count(), session.Query<Component>().Count(c => c.Name == (string)g.Key) }); var results = await (query.ToListAsync()); Assert.That(results.Select(x => x[1]), Is.EquivalentTo(new[] { 4, 2, 2, 2, 2 })); Assert.That(results.Select(x => x[2]), Is.EquivalentTo(new[] { 0, 1, 1, 1, 1 })); await (transaction.RollbackAsync()); } } } }
RogerKratz/nhibernate-core
src/NHibernate.Test/Async/NHSpecificTest/NH3800/Fixture.cs
C#
lgpl-2.1
7,574
package org.molgenis.data.decorator.meta; import org.molgenis.data.AbstractSystemEntityFactory; import org.molgenis.data.populate.EntityPopulator; import org.springframework.stereotype.Component; @Component public class DynamicDecoratorFactory extends AbstractSystemEntityFactory<DynamicDecorator, DynamicDecoratorMetadata, String> { DynamicDecoratorFactory( DynamicDecoratorMetadata dynamicDecoratorMetadata, EntityPopulator entityPopulator) { super(DynamicDecorator.class, dynamicDecoratorMetadata, entityPopulator); } }
dennishendriksen/molgenis
molgenis-data/src/main/java/org/molgenis/data/decorator/meta/DynamicDecoratorFactory.java
Java
lgpl-3.0
543
# # rez_install_doxygen # # Macro for building and installing doxygen files for rez projects. Take special note of the # DOXYPY option if you want to build docs for python source. # # Usage: # rez_install_doxygen( # <label> # FILES <files> # DESTINATION <rel_install_dir> # [DOXYFILE <doxyfile>] # [DOXYDIR <dir>] # [IMAGEPATH <dir>] # [FORCE] # [DOXYPY] # ) # # <label>: This becomes the name of this cmake target. Eg 'doc'. # DESTINATION: Relative path to install resulting docs to. Typically Doxygen will create a # directory (often 'html'), which is installed into <install_path>/<rel_install_dir>/html. # # DOXYFILE: The doxygen config file to use. If unspecified, Rez will use its own default config. # # DOXYDIR: The directory the docs will be generated in, defaults to 'html'. You only need to set # this if you're generating non-html output (for eg, by setting GENERATE_HTML=NO in a custom Doxyfile). # # IMAGEPATH: The directory that images are found in. # # FORCE: Normally docs are not installed unless a central installation is taking place - set this # arg to force doc building and installation always. # # DOXYPY: At the time of writing, Doxygen does not have good python support. A separate, GPL project # called 'doxypy' (http://code.foosel.org/doxypy) can be used to fix this - it lets you write # doxygen-style comments in python docstrings, and extracts them correctly. Doxypy cannot be shipped # with Rez since its license is incompatible - in order to use it, Rez expects you to install it # yourself, and then make it available by binding it to Rez (as you would any 3rd party software) # as a package called 'doxypy', with the doxypy.py file in the package root. Once you've done this, # and you specify the DOXYPY option, you get complete python Doxygen support (don't forget to include # the doxypy package as a build_requires). You can then comment your python code in doxygen style, # like so: # # def myFunc(foo): # """ # @param foo The foo. # @return Something foo-like. # """ # # Note: Consider adding a rez-help entry to your package.yaml like so: # help: firefox file://!ROOT!/<DESTINATION>/<DOXYDIR>/index.html # Then, users can just go "rez-help <pkg>", and the doxygen help will appear. # if(NOT REZ_BUILD_ENV) message(FATAL_ERROR "RezInstallDoxygen requires that RezBuild have been included beforehand.") endif(NOT REZ_BUILD_ENV) INCLUDE(Utils) FIND_PACKAGE(Doxygen) macro (rez_install_doxygen) if(DOXYGEN_EXECUTABLE) parse_arguments(INSTDOX "FILES;DESTINATION;DOXYFILE;DOXYDIR;IMAGEPATH" "FORCE;DOXYPY;USE_TAGFILES;GENERATE_TAGFILE" ${ARGN}) list(GET INSTDOX_DEFAULT_ARGS 0 label) if(NOT label) message(FATAL_ERROR "need to specify a label in call to rez_install_doxygen") endif(NOT label) list(GET INSTDOX_DESTINATION 0 dest_dir) if(NOT dest_dir) message(FATAL_ERROR "need to specify DESTINATION in call to rez_install_doxygen") endif(NOT dest_dir) if(NOT INSTDOX_FILES) message(FATAL_ERROR "no files listed in call to rez_install_doxygen") endif(NOT INSTDOX_FILES) list(GET INSTDOX_DOXYFILE 0 doxyfile) if(NOT doxyfile) set(doxyfile $ENV{REZ_BUILD_DOXYFILE}) endif(NOT doxyfile) list(GET INSTDOX_DOXYDIR 0 doxydir) if(NOT doxydir) set(doxydir html) endif(NOT doxydir) set(_filter_source_files "") set(_input_filter "") set(_opt_output_java "") set(_extract_all "") if(INSTDOX_DOXYPY) find_file(DOXYPY_SRC doxypy.py $ENV{REZ_DOXYPY_ROOT}) if(DOXYPY_SRC) set(_filter_source_files "FILTER_SOURCE_FILES = YES") set(_input_filter "INPUT_FILTER = \"python ${DOXYPY_SRC}\"") set(_opt_output_java "OPTIMIZE_OUTPUT_JAVA = YES") set(_extract_all "EXTRACT_ALL = YES") else(DOXYPY_SRC) message(FATAL_ERROR "Cannot locate doxypy.py - you probably need to supply doxypy as a Rez package, see the documentation in <rez_install>/cmake/RezInstallDoxygen.cmake for more info.") endif(DOXYPY_SRC) endif(INSTDOX_DOXYPY) set(_proj_name $ENV{REZ_BUILD_PROJECT_NAME}) set(_proj_ver $ENV{REZ_BUILD_PROJECT_VERSION}) set(_proj_desc $ENV{REZ_BUILD_PROJECT_DESCRIPTION}) string(REPLACE "\n" " " _proj_desc2 ${_proj_desc}) set(_tagfile "") set(_tagfiles "") if (INSTDOX_GENERATE_TAGFILE) set(_tagfile ${_proj_name}.tag) set(_generate_tagfile "GENERATE_TAGFILE = ${_tagfile}") endif () if (INSTDOX_USE_TAGFILES) set(_tagfiles "TAGFILES += $(DOXYGEN_TAGFILES)") endif () add_custom_command( OUTPUT ${dest_dir}/Doxyfile DEPENDS ${doxyfile} COMMAND ${CMAKE_COMMAND} -E make_directory ${dest_dir} COMMAND ${CMAKE_COMMAND} -E copy ${doxyfile} ${dest_dir}/Doxyfile COMMAND chmod +w ${dest_dir}/Doxyfile COMMAND echo PROJECT_NAME = \"${_proj_name}\" >> ${dest_dir}/Doxyfile COMMAND echo PROJECT_NUMBER = \"${_proj_ver}\" >> ${dest_dir}/Doxyfile COMMAND echo PROJECT_BRIEF = \"${_proj_desc2}\" >> ${dest_dir}/Doxyfile COMMAND echo ${_filter_source_files} >> ${dest_dir}/Doxyfile COMMAND echo ${_input_filter} >> ${dest_dir}/Doxyfile COMMAND echo ${_opt_output_java} >> ${dest_dir}/Doxyfile COMMAND echo ${_extract_all} >> ${dest_dir}/Doxyfile COMMAND echo ${_tagfiles} >> ${dest_dir}/Doxyfile COMMAND echo ${_generate_tagfile} >> ${dest_dir}/Doxyfile COMMAND echo INPUT = ${INSTDOX_FILES} >> ${dest_dir}/Doxyfile COMMAND echo IMAGE_PATH = ${CMAKE_SOURCE_DIR}/${INSTDOX_IMAGEPATH} >> ${dest_dir}/Doxyfile COMMAND echo STRIP_FROM_PATH = ${CMAKE_SOURCE_DIR} >> ${dest_dir}/Doxyfile COMMENT "Generating Doxyfile ${dest_dir}/Doxyfile..." VERBATIM ) add_custom_target(${label} DEPENDS ${dest_dir}/Doxyfile #COMMAND ${DOXYGEN_EXECUTABLE} COMMAND doxygen WORKING_DIRECTORY ${dest_dir} COMMENT "Generating doxygen content in ${dest_dir}/${doxydir}..." ) if(REZ_BUILD_TYPE STREQUAL "central" OR INSTDOX_FORCE) # only install docs when installing centrally add_custom_target(_install_${label} ALL DEPENDS ${label}) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${dest_dir}/${doxydir} DESTINATION ${dest_dir}) if (INSTDOX_GENERATE_TAGFILE) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${dest_dir}/${_tagfile} DESTINATION ${dest_dir}) endif () endif(CENTRAL OR INSTDOX_FORCE) else(DOXYGEN_EXECUTABLE) message(WARNING "RezInstallDoxygen cannot find Doxygen - documentation was not built.") endif(DOXYGEN_EXECUTABLE) endmacro (rez_install_doxygen)
cwmartin/rez
src/rezplugins/build_system/cmake_files/RezInstallDoxygen.cmake
CMake
lgpl-3.0
6,418
package org.molgenis.data.export; import java.nio.file.Path; import java.util.List; import org.molgenis.data.meta.model.EntityType; import org.molgenis.data.meta.model.Package; import org.molgenis.jobs.Progress; public interface EmxExportService { void export(List<EntityType> entityTypes, List<Package> packages, Path path, Progress progress); }
sidohaakma/molgenis
molgenis-data-import/src/main/java/org/molgenis/data/export/EmxExportService.java
Java
lgpl-3.0
351
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of Google Inc. 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. *is % allowed in string */ #include <memory> #include <string> #include <thread> #include <utility> #include <vector> #include <gflags/gflags.h> #include <grpc++/create_channel.h> #include <grpc++/grpc++.h> #include <grpc++/impl/thd.h> #include <grpc/support/time.h> #include "src/proto/grpc/testing/metrics.grpc.pb.h" #include "src/proto/grpc/testing/metrics.pb.h" #include "test/cpp/interop/interop_client.h" #include "test/cpp/interop/stress_interop_client.h" #include "test/cpp/util/metrics_server.h" #include "test/cpp/util/test_config.h" extern "C" { extern void gpr_default_log(gpr_log_func_args* args); } DEFINE_int32(metrics_port, 8081, "The metrics server port."); DEFINE_int32(sleep_duration_ms, 0, "The duration (in millisec) between two" " consecutive test calls (per server) issued by the server."); DEFINE_int32(test_duration_secs, -1, "The length of time (in seconds) to run" " the test. Enter -1 if the test should run continuously until" " forcefully terminated."); DEFINE_string(server_addresses, "localhost:8080", "The list of server" " addresses in the format:\n" " \"<name_1>:<port_1>,<name_2>:<port_1>...<name_N>:<port_N>\"\n" " Note: <name> can be servername or IP address."); DEFINE_int32(num_channels_per_server, 1, "Number of channels for each server"); DEFINE_int32(num_stubs_per_channel, 1, "Number of stubs per each channels to server. This number also " "indicates the max number of parallel RPC calls on each channel " "at any given time."); // TODO(sreek): Add more test cases here in future DEFINE_string(test_cases, "", "List of test cases to call along with the" " relative weights in the following format:\n" " \"<testcase_1:w_1>,<testcase_2:w_2>...<testcase_n:w_n>\"\n" " The following testcases are currently supported:\n" " empty_unary\n" " large_unary\n" " large_compressed_unary\n" " client_streaming\n" " server_streaming\n" " server_compressed_streaming\n" " slow_consumer\n" " half_duplex\n" " ping_pong\n" " cancel_after_begin\n" " cancel_after_first_response\n" " timeout_on_sleeping_server\n" " empty_stream\n" " status_code_and_message\n" " custom_metadata\n" " Example: \"empty_unary:20,large_unary:10,empty_stream:70\"\n" " The above will execute 'empty_unary', 20% of the time," " 'large_unary', 10% of the time and 'empty_stream' the remaining" " 70% of the time"); DEFINE_int32(log_level, GPR_LOG_SEVERITY_INFO, "Severity level of messages that should be logged. Any messages " "greater than or equal to the level set here will be logged. " "The choices are: 0 (GPR_LOG_SEVERITY_DEBUG), 1 " "(GPR_LOG_SEVERITY_INFO) and 2 (GPR_LOG_SEVERITY_ERROR)"); DEFINE_bool(do_not_abort_on_transient_failures, true, "If set to 'true', abort() is not called in case of transient " "failures like temporary connection failures."); using grpc::testing::kTestCaseList; using grpc::testing::MetricsService; using grpc::testing::MetricsServiceImpl; using grpc::testing::StressTestInteropClient; using grpc::testing::TestCaseType; using grpc::testing::UNKNOWN_TEST; using grpc::testing::WeightedRandomTestSelector; static int log_level = GPR_LOG_SEVERITY_DEBUG; // A simple wrapper to grp_default_log() function. This only logs messages at or // above the current log level (set in 'log_level' variable) void TestLogFunction(gpr_log_func_args* args) { if (args->severity >= log_level) { gpr_default_log(args); } } TestCaseType GetTestTypeFromName(const grpc::string& test_name) { TestCaseType test_case = UNKNOWN_TEST; for (auto it = kTestCaseList.begin(); it != kTestCaseList.end(); it++) { if (test_name == it->second) { test_case = it->first; break; } } return test_case; } // Converts a string of comma delimited tokens to a vector of tokens bool ParseCommaDelimitedString(const grpc::string& comma_delimited_str, std::vector<grpc::string>& tokens) { size_t bpos = 0; size_t epos = grpc::string::npos; while ((epos = comma_delimited_str.find(',', bpos)) != grpc::string::npos) { tokens.emplace_back(comma_delimited_str.substr(bpos, epos - bpos)); bpos = epos + 1; } tokens.emplace_back(comma_delimited_str.substr(bpos)); // Last token return true; } // Input: Test case string "<testcase_name:weight>,<testcase_name:weight>...." // Output: // - Whether parsing was successful (return value) // - Vector of (test_type_enum, weight) pairs returned via 'tests' parameter bool ParseTestCasesString(const grpc::string& test_cases, std::vector<std::pair<TestCaseType, int>>& tests) { bool is_success = true; std::vector<grpc::string> tokens; ParseCommaDelimitedString(test_cases, tokens); for (auto it = tokens.begin(); it != tokens.end(); it++) { // Token is in the form <test_name>:<test_weight> size_t colon_pos = it->find(':'); if (colon_pos == grpc::string::npos) { gpr_log(GPR_ERROR, "Error in parsing test case string: %s", it->c_str()); is_success = false; break; } grpc::string test_name = it->substr(0, colon_pos); int weight = std::stoi(it->substr(colon_pos + 1)); TestCaseType test_case = GetTestTypeFromName(test_name); if (test_case == UNKNOWN_TEST) { gpr_log(GPR_ERROR, "Unknown test case: %s", test_name.c_str()); is_success = false; break; } tests.emplace_back(std::make_pair(test_case, weight)); } return is_success; } // For debugging purposes void LogParameterInfo(const std::vector<grpc::string>& addresses, const std::vector<std::pair<TestCaseType, int>>& tests) { gpr_log(GPR_INFO, "server_addresses: %s", FLAGS_server_addresses.c_str()); gpr_log(GPR_INFO, "test_cases : %s", FLAGS_test_cases.c_str()); gpr_log(GPR_INFO, "sleep_duration_ms: %d", FLAGS_sleep_duration_ms); gpr_log(GPR_INFO, "test_duration_secs: %d", FLAGS_test_duration_secs); gpr_log(GPR_INFO, "num_channels_per_server: %d", FLAGS_num_channels_per_server); gpr_log(GPR_INFO, "num_stubs_per_channel: %d", FLAGS_num_stubs_per_channel); gpr_log(GPR_INFO, "log_level: %d", FLAGS_log_level); gpr_log(GPR_INFO, "do_not_abort_on_transient_failures: %s", FLAGS_do_not_abort_on_transient_failures ? "true" : "false"); int num = 0; for (auto it = addresses.begin(); it != addresses.end(); it++) { gpr_log(GPR_INFO, "%d:%s", ++num, it->c_str()); } num = 0; for (auto it = tests.begin(); it != tests.end(); it++) { TestCaseType test_case = it->first; int weight = it->second; gpr_log(GPR_INFO, "%d. TestCaseType: %d, Weight: %d", ++num, test_case, weight); } } int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); if (FLAGS_log_level > GPR_LOG_SEVERITY_ERROR || FLAGS_log_level < GPR_LOG_SEVERITY_DEBUG) { gpr_log(GPR_ERROR, "log_level should be an integer between %d and %d", GPR_LOG_SEVERITY_DEBUG, GPR_LOG_SEVERITY_ERROR); return 1; } // Change the default log function to TestLogFunction which respects the // log_level setting. log_level = FLAGS_log_level; gpr_set_log_function(TestLogFunction); srand(time(NULL)); // Parse the server addresses std::vector<grpc::string> server_addresses; ParseCommaDelimitedString(FLAGS_server_addresses, server_addresses); // Parse test cases and weights if (FLAGS_test_cases.length() == 0) { gpr_log(GPR_ERROR, "Not running tests. The 'test_cases' string is empty"); return 1; } std::vector<std::pair<TestCaseType, int>> tests; if (!ParseTestCasesString(FLAGS_test_cases, tests)) { gpr_log(GPR_ERROR, "Error in parsing test cases string %s ", FLAGS_test_cases.c_str()); return 1; } LogParameterInfo(server_addresses, tests); WeightedRandomTestSelector test_selector(tests); MetricsServiceImpl metrics_service; gpr_log(GPR_INFO, "Starting test(s).."); std::vector<grpc::thread> test_threads; // Create and start the test threads. // Note that: // - Each server can have multiple channels (as configured by // FLAGS_num_channels_per_server). // // - Each channel can have multiple stubs (as configured by // FLAGS_num_stubs_per_channel). This is to test calling multiple RPCs in // parallel on the same channel. int thread_idx = 0; int server_idx = -1; char buffer[256]; for (auto it = server_addresses.begin(); it != server_addresses.end(); it++) { ++server_idx; // Create channel(s) for each server for (int channel_idx = 0; channel_idx < FLAGS_num_channels_per_server; channel_idx++) { // TODO (sreek). This won't work for tests that require Authentication std::shared_ptr<grpc::Channel> channel( grpc::CreateChannel(*it, grpc::InsecureChannelCredentials())); // Create stub(s) for each channel for (int stub_idx = 0; stub_idx < FLAGS_num_stubs_per_channel; stub_idx++) { StressTestInteropClient* client = new StressTestInteropClient( ++thread_idx, *it, channel, test_selector, FLAGS_test_duration_secs, FLAGS_sleep_duration_ms, FLAGS_do_not_abort_on_transient_failures); bool is_already_created = false; // QpsGauge name std::snprintf(buffer, sizeof(buffer), "/stress_test/server_%d/channel_%d/stub_%d/qps", server_idx, channel_idx, stub_idx); test_threads.emplace_back(grpc::thread( &StressTestInteropClient::MainLoop, client, metrics_service.CreateQpsGauge(buffer, &is_already_created))); // The QpsGauge should not have been already created GPR_ASSERT(!is_already_created); } } } // Start metrics server before waiting for the stress test threads std::unique_ptr<grpc::Server> metrics_server = metrics_service.StartServer(FLAGS_metrics_port); // Wait for the stress test threads to complete for (auto it = test_threads.begin(); it != test_threads.end(); it++) { it->join(); } return 0; }
shishaochen/TensorFlow-0.8-Win
third_party/grpc/test/cpp/interop/stress_test.cc
C++
apache-2.0
12,147
--- layout: default title: "Puppet Server: Tuning Guide" canonical: "/puppetserver/latest/tuning_guide.html" --- Puppet Server provides many configuration options that can be used to tune the server for maximum performance and hardware resource utilization. In this guide, we'll highlight some of the most important settings that you can use to get the best performance in your environment. ## Puppet Server and JRuby Before you begin tuning your configuration, it's helpful to have a little bit of context on how Puppet Server uses JRuby to handle incoming HTTP requests from your Puppet agents. When Puppet Server starts up, it creates a pool of JRuby interpreters to use as workers when it needs need to execute some of the Puppet Ruby code. You can think of these almost as individual Ruby "virtual machines" that are controlled by Puppet Server; it's not entirely dissimilar to the way that Passenger spawns several Ruby processes to hand off work to. Puppet Server isolates these JRuby instances so that they will only be allowed to handle one request at a time. This ensures that we don't encounter any concurrency issues, since the Ruby code is not thread-safe. When an HTTP request comes in to Puppet Server, and it determines that some Ruby code will need to be executed in order to handle the request, Puppet Server "borrows" a JRuby instance from the pool, uses it to do the work, and then "returns" it to the pool. If there are no JRuby instances available in the pool at the time a request comes in (presumably because all of the JRuby instances are already in use handling other requests), Puppet Server will block the request until one becomes available. (In the future, this approach will allow us to do some really powerful things such as creating multiple pools of JRubies and isolating each of your Puppet environments to a single pool, to ensure that there is no pollution from one Puppet environment to the next.) This brings us to the two most important settings that you can use to tune your Puppet Server. ### Number of JRubies The most important setting that you can use to improve the throughput of your Puppet Server installation is the [`max-active-instances`](./configuration.html#puppetserver_conf) setting. The value of this setting is used by Puppet Server to determine how many JRuby instances to create when the server starts up. From a practical perspective, this setting basically controls how many Puppet agent runs Puppet Server can handle concurrently. The minimum value you can get away with here is `1`, and if your installation is small enough that you're unlikely to ever have more than one Puppet agent checking in with the server at exactly the same time, this is totally sufficient. However, if you specify a value of `1` for this setting, and then you have two Puppet agent runs hitting the server at the same time, the requests being made by the second agent will be effectively blocked until the server has finished handling all of the requests from the first agent. In other words, one of Puppet Server's threads will have "borrowed" the single JRuby instance from the pool to handle the requests from the first agent, and only when those requests are completed will it return the JRuby instance to the pool. At that point, the next thread can "borrow" the JRuby instance to use to handle the requests from the second agent. Assuming you have more than one CPU core in your machine, this situation means that you won't be getting the maximum possible throughput from your Puppet Server installation. Increasing the value from `1` to `2` would mean that Puppet Server could now use a second CPU core to handle the requests from a second Puppet agent simultaneously. It follows, then, that the maximum sensible value to use for this setting will be roughly the number of CPU cores you have in your server. Setting the value to something much higher than that won't improve performance, because even if there are extra JRuby instances available in the pool to do work, they won't be able to actually do any work if all of the CPU cores are already busy using JRuby instances to handle incoming agent requests. (There are some exceptions to this rule. For example, if you have report processors that make a network connection as part of the processing of a report, and if there is a chance that the network operation is slow and will block on I/O for some period of time, then it might make sense to have more JRuby instances than the number of cores. The JVM is smart enough to suspend the thread that is handling those kinds of requests and use the CPUs for other work, assuming there are still JRuby instances available in the pool. In a case like this you might want to set `max-active-instances` to a value higher than the number of CPUs.) At this point you may be wondering, "What's the downside to just setting `max-active-instances` to a really high value?" The answer to this question, in a nutshell, is "memory usage". This brings us to the other extremely important setting to consider for Puppet Server. ### JVM Heap Size The JVM's "max heap size" controls the maximum amount of (heap*[[1]](#footnotes) memory that the JVM process is allowed to request from the operating system. You can set this value via the `-Xmx` command-line argument at JVM startup. (In the case of Puppet Server, you'll find this setting in the "defaults" file for Puppet Server for your operating system; this will generally be something like `/etc/sysconfig/puppetserver` or `/etc/defaults/puppetserver`.) If your application's memory usage approaches this value, the JVM will try to get more aggressive with garbage collection to free up memory. In certain situations, you may see increased CPU activity related to this garbage collection. If the JVM is unable to recover enough memory to keep the application running smoothly, you will eventually encounter an `OutOfMemoryError`, and the process will shut down. For Puppet Server, we also use a JVM argument, `-XX:HeapDumpOnOutOfMemoryError`, to cause the JVM to dump an `.hprof` file to disk. This is basically a memory snapshot at the point in time where the error occurred; it can be loaded into various profiling tools to get a better understanding of where the memory was being used. (Note that there is another setting, "min heap size", that is controlled via the -Xms setting; [Oracle recommends](http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html#0.0.0.%20Total%20Heap|outline) setting this value to the same value that you use for -Xmx.) The most important factor when determining the max heap size for Puppet Server is the value of `max-active-instances`. Each JRuby instance needs to load up a copy of the Puppet Ruby code, and then needs some amount of memory overhead for all of the garbage that gets generated during a Puppet catalog compilation. Also, the memory requirements will vary based on how many Puppet modules you have in your module path, how much Hiera data you have, etc. At this time we estimate that a reasonable ballpark figure is about 512MB of RAM per JRuby instance, but that can vary depending on some characteristics of your Puppet codebase. For example, if you have a really high number of modules or a great deal of Hiera data, you might find that you need more than 512MB per JRuby instance. You'll also want to allocate a little extra heap to be used by the rest of the things going on in Puppet Server: the web server, etc. So, a good rule of thumb might be 512MB + (max-active-instances * 512MB). We're working on some optimizations for really small installations (for testing, demos, etc.). Puppet Server should run fine with a value of 1 for `max-active-instances` and a heap size of 512MB, and we might be able to improve that further in the future. ### Tying Together `max-active-instances` and Heap Size We're still gathering data on what the best default settings are, to try to provide an out-of-the-box configuration that works well in most environments. In versions prior to 1.0.8 in the 1.x series (compatible with Puppet 3.x), and prior to 2.1.0 in the 2.x series (compatible with Puppet 4.x), the default value is `num-cpus + 2`. This value will be far too high if you're running on a system with a large number of CPU cores. As of Puppet Server 1.0.8 and 2.1.0, if you don't provide an explicit value for this setting, we'll default to `num-cpus - 1`, with a minimum value of `1` and a maximum value of `4`. The maximum value of `4` is probably too low for production environments with beefy hardware and a high number of Puppet agents checking in, but our current thinking is that it's better to ship with a default setting that is too low and allow you to tune up, than to ship with a default setting that is too high and causes you to run into `OutOfMemory` errors. In general, it's recommended that you explicitly set this value to something that you think is reasonable in your environment. To encourage this, we log a warning message at startup if you haven't provided an explicit value. ## Footnotes [1] The vast majority of the memory footprint of a JVM process can usually be accounted for by the heap size. However, there is some amount of non-heap memory that will always be used, and for programs that call out to native code at all, there may be a bit more. Generally speaking, the resident memory usage of a JVM process shouldn't exceed the max heap size by more than 256MB or so, but exceeding the max heap size by some amount is normal.
stahnma/puppet-server
documentation/tuning_guide.markdown
Markdown
apache-2.0
9,559
/* * 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. */ package org.apache.druid.query.aggregation.cardinality.types; import com.google.common.hash.Hasher; import org.apache.druid.common.config.NullHandling; import org.apache.druid.hll.HyperLogLogCollector; import org.apache.druid.query.aggregation.cardinality.CardinalityAggregator; import org.apache.druid.segment.DimensionSelector; import org.apache.druid.segment.data.IndexedInts; import java.util.Arrays; public class StringCardinalityAggregatorColumnSelectorStrategy implements CardinalityAggregatorColumnSelectorStrategy<DimensionSelector> { public static final String CARDINALITY_AGG_NULL_STRING = "\u0000"; public static final char CARDINALITY_AGG_SEPARATOR = '\u0001'; @Override public void hashRow(DimensionSelector dimSelector, Hasher hasher) { final IndexedInts row = dimSelector.getRow(); final int size = row.size(); // nothing to add to hasher if size == 0, only handle size == 1 and size != 0 cases. if (size == 1) { final String value = dimSelector.lookupName(row.get(0)); if (NullHandling.replaceWithDefault() || value != null) { hasher.putUnencodedChars(nullToSpecial(value)); } } else if (size != 0) { boolean hasNonNullValue = false; final String[] values = new String[size]; for (int i = 0; i < size; ++i) { final String value = dimSelector.lookupName(row.get(i)); // SQL standard spec does not count null values, // Skip counting null values when we are not replacing null with default value. // A special value for null in case null handling is configured to use empty string for null. if (NullHandling.sqlCompatible() && !hasNonNullValue && value != null) { hasNonNullValue = true; } values[i] = nullToSpecial(value); } // SQL standard spec does not count null values, // Skip counting null values when we are not replacing null with default value. // A special value for null in case null handling is configured to use empty string for null. if (NullHandling.replaceWithDefault() || hasNonNullValue) { // Values need to be sorted to ensure consistent multi-value ordering across different segments Arrays.sort(values); for (int i = 0; i < size; ++i) { if (i != 0) { hasher.putChar(CARDINALITY_AGG_SEPARATOR); } hasher.putUnencodedChars(values[i]); } } } } @Override public void hashValues(DimensionSelector dimSelector, HyperLogLogCollector collector) { IndexedInts row = dimSelector.getRow(); for (int i = 0, rowSize = row.size(); i < rowSize; i++) { int index = row.get(i); final String value = dimSelector.lookupName(index); // SQL standard spec does not count null values, // Skip counting null values when we are not replacing null with default value. // A special value for null in case null handling is configured to use empty string for null. if (NullHandling.replaceWithDefault() || value != null) { collector.add(CardinalityAggregator.HASH_FUNCTION.hashUnencodedChars(nullToSpecial(value)).asBytes()); } } } private String nullToSpecial(String value) { return value == null ? CARDINALITY_AGG_NULL_STRING : value; } }
pjain1/druid
processing/src/main/java/org/apache/druid/query/aggregation/cardinality/types/StringCardinalityAggregatorColumnSelectorStrategy.java
Java
apache-2.0
4,100
/* * 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. */ package org.apache.spark.sql.catalyst.rules import org.apache.spark.internal.Logging import org.apache.spark.sql.catalyst.QueryPlanningTracker import org.apache.spark.sql.catalyst.errors.TreeNodeException import org.apache.spark.sql.catalyst.trees.TreeNode import org.apache.spark.sql.catalyst.util.sideBySide import org.apache.spark.sql.internal.SQLConf import org.apache.spark.util.Utils object RuleExecutor { protected val queryExecutionMeter = QueryExecutionMetering() /** Dump statistics about time spent running specific rules. */ def dumpTimeSpent(): String = { queryExecutionMeter.dumpTimeSpent() } /** Resets statistics about time spent running specific rules */ def resetMetrics(): Unit = { queryExecutionMeter.resetMetrics() } } abstract class RuleExecutor[TreeType <: TreeNode[_]] extends Logging { /** * An execution strategy for rules that indicates the maximum number of executions. If the * execution reaches fix point (i.e. converge) before maxIterations, it will stop. */ abstract class Strategy { def maxIterations: Int } /** A strategy that is run once and idempotent. */ case object Once extends Strategy { val maxIterations = 1 } /** * A strategy that runs until fix point or maxIterations times, whichever comes first. * Especially, a FixedPoint(1) batch is supposed to run only once. */ case class FixedPoint(maxIterations: Int) extends Strategy /** A batch of rules. */ protected case class Batch(name: String, strategy: Strategy, rules: Rule[TreeType]*) /** Defines a sequence of rule batches, to be overridden by the implementation. */ protected def batches: Seq[Batch] /** Once batches that are blacklisted in the idempotence checker */ protected val blacklistedOnceBatches: Set[String] = Set.empty /** * Defines a check function that checks for structural integrity of the plan after the execution * of each rule. For example, we can check whether a plan is still resolved after each rule in * `Optimizer`, so we can catch rules that return invalid plans. The check function returns * `false` if the given plan doesn't pass the structural integrity check. */ protected def isPlanIntegral(plan: TreeType): Boolean = true /** * Util method for checking whether a plan remains the same if re-optimized. */ private def checkBatchIdempotence(batch: Batch, plan: TreeType): Unit = { val reOptimized = batch.rules.foldLeft(plan) { case (p, rule) => rule(p) } if (!plan.fastEquals(reOptimized)) { val message = s""" |Once strategy's idempotence is broken for batch ${batch.name} |${sideBySide(plan.treeString, reOptimized.treeString).mkString("\n")} """.stripMargin throw new TreeNodeException(reOptimized, message, null) } } /** * Executes the batches of rules defined by the subclass, and also tracks timing info for each * rule using the provided tracker. * @see [[execute]] */ def executeAndTrack(plan: TreeType, tracker: QueryPlanningTracker): TreeType = { QueryPlanningTracker.withTracker(tracker) { execute(plan) } } /** * Executes the batches of rules defined by the subclass. The batches are executed serially * using the defined execution strategy. Within each batch, rules are also executed serially. */ def execute(plan: TreeType): TreeType = { var curPlan = plan val queryExecutionMetrics = RuleExecutor.queryExecutionMeter val planChangeLogger = new PlanChangeLogger() val tracker: Option[QueryPlanningTracker] = QueryPlanningTracker.get // Run the structural integrity checker against the initial input if (!isPlanIntegral(plan)) { val message = "The structural integrity of the input plan is broken in " + s"${this.getClass.getName.stripSuffix("$")}." throw new TreeNodeException(plan, message, null) } batches.foreach { batch => val batchStartPlan = curPlan var iteration = 1 var lastPlan = curPlan var continue = true // Run until fix point (or the max number of iterations as specified in the strategy. while (continue) { curPlan = batch.rules.foldLeft(curPlan) { case (plan, rule) => val startTime = System.nanoTime() val result = rule(plan) val runTime = System.nanoTime() - startTime val effective = !result.fastEquals(plan) if (effective) { queryExecutionMetrics.incNumEffectiveExecution(rule.ruleName) queryExecutionMetrics.incTimeEffectiveExecutionBy(rule.ruleName, runTime) planChangeLogger.logRule(rule.ruleName, plan, result) } queryExecutionMetrics.incExecutionTimeBy(rule.ruleName, runTime) queryExecutionMetrics.incNumExecution(rule.ruleName) // Record timing information using QueryPlanningTracker tracker.foreach(_.recordRuleInvocation(rule.ruleName, runTime, effective)) // Run the structural integrity checker against the plan after each rule. if (!isPlanIntegral(result)) { val message = s"After applying rule ${rule.ruleName} in batch ${batch.name}, " + "the structural integrity of the plan is broken." throw new TreeNodeException(result, message, null) } result } iteration += 1 if (iteration > batch.strategy.maxIterations) { // Only log if this is a rule that is supposed to run more than once. if (iteration != 2) { val message = s"Max iterations (${iteration - 1}) reached for batch ${batch.name}" if (Utils.isTesting) { throw new TreeNodeException(curPlan, message, null) } else { logWarning(message) } } // Check idempotence for Once batches. if (batch.strategy == Once && Utils.isTesting && !blacklistedOnceBatches.contains(batch.name)) { checkBatchIdempotence(batch, curPlan) } continue = false } if (curPlan.fastEquals(lastPlan)) { logTrace( s"Fixed point reached for batch ${batch.name} after ${iteration - 1} iterations.") continue = false } lastPlan = curPlan } planChangeLogger.logBatch(batch.name, batchStartPlan, curPlan) } curPlan } private class PlanChangeLogger { private val logLevel = SQLConf.get.optimizerPlanChangeLogLevel private val logRules = SQLConf.get.optimizerPlanChangeRules.map(Utils.stringToSeq) private val logBatches = SQLConf.get.optimizerPlanChangeBatches.map(Utils.stringToSeq) def logRule(ruleName: String, oldPlan: TreeType, newPlan: TreeType): Unit = { if (logRules.isEmpty || logRules.get.contains(ruleName)) { def message(): String = { s""" |=== Applying Rule ${ruleName} === |${sideBySide(oldPlan.treeString, newPlan.treeString).mkString("\n")} """.stripMargin } logBasedOnLevel(message) } } def logBatch(batchName: String, oldPlan: TreeType, newPlan: TreeType): Unit = { if (logBatches.isEmpty || logBatches.get.contains(batchName)) { def message(): String = { if (!oldPlan.fastEquals(newPlan)) { s""" |=== Result of Batch ${batchName} === |${sideBySide(oldPlan.treeString, newPlan.treeString).mkString("\n")} """.stripMargin } else { s"Batch ${batchName} has no effect." } } logBasedOnLevel(message) } } private def logBasedOnLevel(f: => String): Unit = { logLevel match { case "TRACE" => logTrace(f) case "DEBUG" => logDebug(f) case "INFO" => logInfo(f) case "WARN" => logWarning(f) case "ERROR" => logError(f) case _ => logTrace(f) } } } }
pgandhi999/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/rules/RuleExecutor.scala
Scala
apache-2.0
8,840
// Mixing +bundle and +whole-archive is not allowed // compile-flags: -l static:+bundle,+whole-archive=mylib -Zunstable-options --crate-type rlib // build-fail // error-pattern: the linking modifiers `+bundle` and `+whole-archive` are not compatible with each other when generating rlibs fn main() { }
graydon/rust
src/test/ui/native-library-link-flags/mix-bundle-and-whole-archive.rs
Rust
apache-2.0
304
<!DOCTYPE html> <html lang="en"> <head> <title>How do I create a text document?</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta content="sakai.resources" name="description"> <meta content="" name="search"> <link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/sakai-help-tool/css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <script src="/library/webjars/jquery/1.11.3/jquery.min.js" type="text/javascript" charset="utf-8"></script><script src="/library/js/jquery/featherlight/0.4.0/featherlight.min.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='featherlight']").featherlight({ type: { image:true }, closeOnClick: 'anywhere' }); }); </script> </head> <body> <div id="wrapper"> <div id="article-content"> <div id="article-header"> <h1 class="article-title">How do I create a text document?</h1> </div> <div id="steps-container"> <div id="step-7023" class="step-container"> <h2 class="step-title">Go to Resources.</h2> <div class="step-instructions"><p>Select the <strong>Resources</strong> tool from the Tool Menu of your site.</p></div> </div> <div class="clear"></div> <div id="step-7024" class="step-container"> <h2 class="step-title">Click Add, then Create Text Document.</h2> <div class="step-image-container"> <img src="/library/image/help/en/How-do-I-create-a-text-document-/Click-Add--then-Create-Text-Document.png" width="601" height="435" class="step-image" alt="Click Add, then Create Text Document."> </div> <div class="step-instructions"> <p>To the right of the folder where you want to create the text document, from the <strong>Add</strong> drop-down menu, select <strong>Create Text Document</strong>.</p> <p>This displays the Create Text Document page.</p> </div> </div> <div class="clear"></div> <div id="step-7025" class="step-container"> <h2 class="step-title">Enter text, then click Continue.</h2> <div class="step-image-container"> <img src="/library/image/help/en/How-do-I-create-a-text-document-/Enter-text--then-click-Continue.png" width="554" height="342" class="step-image" alt="Enter text, then click Continue."> </div> <div class="step-instructions"> <p>Enter (or paste) the text into the text box, then click <strong>Continue</strong>.</p> <p>This displays The details page for the text document.</p> </div> </div> <div class="clear"></div> <div id="step-7026" class="step-container"> <h2 class="step-title">Enter document information.</h2> <div class="step-image-container step-image-fullsize"> <img src="/library/image/help/en/How-do-I-create-a-text-document-/Enter-document-information-sm.png" width="640" height="622" class="step-image" alt="Enter document information."><div class="step-image-caption"> <a href="/library/image/help/en/How-do-I-create-a-text-document-/Enter-document-information.png" rel="featherlight" target="_blank">Zoom</a> </div> </div> <div class="step-instructions"><p>Enter a <strong>Name</strong> for the text document, add additional data if needed, then click <strong>Finish</strong>.</p></div> </div> <div class="clear"></div> <div id="step-7027" class="step-container"> <h2 class="step-title">View text document in Resources.</h2> <div class="step-image-container"> <img src="/library/image/help/en/How-do-I-create-a-text-document-/View-text-document-in-Resources.png" width="599" height="356" class="step-image" alt="View text document in Resources."> </div> <div class="step-instructions"> <p>The text document has been placed in the selected folder. </p> <p><em>Note: You may click on the blue Information icon to the right of the file to see the item description.</em></p> </div> </div> <div class="clear"></div> </div> </div> </div> </body> </html>
rodriguezdevera/sakai
help/help/src/sakai_screensteps_resourcesInstructorGuide/How-do-I-create-a-text-document-.html
HTML
apache-2.0
4,619
/** * 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. */ package kafka.producer import kafka.utils.Utils import java.util.Properties class SyncProducerConfig(val props: Properties) extends SyncProducerConfigShared { /** the broker to which the producer sends events */ val host = Utils.getString(props, "host") /** the port on which the broker is running */ val port = Utils.getInt(props, "port") } trait SyncProducerConfigShared { val props: Properties val bufferSize = Utils.getInt(props, "buffer.size", 100*1024) val connectTimeoutMs = Utils.getInt(props, "connect.timeout.ms", 5000) /** the socket timeout for network requests */ val socketTimeoutMs = Utils.getInt(props, "socket.timeout.ms", 30000) val reconnectInterval = Utils.getInt(props, "reconnect.interval", 30000) /** negative reconnect time interval means disabling this time-based reconnect feature */ var reconnectTimeInterval = Utils.getInt(props, "reconnect.time.interval.ms", 1000*1000*10) val maxMessageSize = Utils.getInt(props, "max.message.size", 1000000) }
piavlo/operations-debs-kafka
core/src/main/scala/kafka/producer/SyncProducerConfig.scala
Scala
apache-2.0
1,816
package common import ( "io/ioutil" "os" "regexp" "testing" "github.com/mitchellh/packer/helper/communicator" ) func init() { // Clear out the AWS access key env vars so they don't // affect our tests. os.Setenv("AWS_ACCESS_KEY_ID", "") os.Setenv("AWS_ACCESS_KEY", "") os.Setenv("AWS_SECRET_ACCESS_KEY", "") os.Setenv("AWS_SECRET_KEY", "") } func testConfig() *RunConfig { return &RunConfig{ SourceAmi: "abcd", InstanceType: "m1.small", Comm: communicator.Config{ SSHUsername: "foo", }, } } func testConfigFilter() *RunConfig { config := testConfig() config.SourceAmi = "" config.SourceAmiFilter = AmiFilterOptions{} return config } func TestRunConfigPrepare(t *testing.T) { c := testConfig() err := c.Prepare(nil) if len(err) > 0 { t.Fatalf("err: %s", err) } } func TestRunConfigPrepare_InstanceType(t *testing.T) { c := testConfig() c.InstanceType = "" if err := c.Prepare(nil); len(err) != 1 { t.Fatalf("err: %s", err) } } func TestRunConfigPrepare_SourceAmi(t *testing.T) { c := testConfig() c.SourceAmi = "" if err := c.Prepare(nil); len(err) != 1 { t.Fatalf("err: %s", err) } } func TestRunConfigPrepare_SourceAmiFilterBlank(t *testing.T) { c := testConfigFilter() if err := c.Prepare(nil); len(err) != 1 { t.Fatalf("err: %s", err) } } func TestRunConfigPrepare_SourceAmiFilterGood(t *testing.T) { c := testConfigFilter() owner := "123" filter_key := "name" filter_value := "foo" goodFilter := AmiFilterOptions{Owners: []*string{&owner}, Filters: map[*string]*string{&filter_key: &filter_value}} c.SourceAmiFilter = goodFilter if err := c.Prepare(nil); len(err) != 0 { t.Fatalf("err: %s", err) } } func TestRunConfigPrepare_SpotAuto(t *testing.T) { c := testConfig() c.SpotPrice = "auto" if err := c.Prepare(nil); len(err) != 1 { t.Fatalf("err: %s", err) } c.SpotPriceAutoProduct = "foo" if err := c.Prepare(nil); len(err) != 0 { t.Fatalf("err: %s", err) } } func TestRunConfigPrepare_SSHPort(t *testing.T) { c := testConfig() c.Comm.SSHPort = 0 if err := c.Prepare(nil); len(err) != 0 { t.Fatalf("err: %s", err) } if c.Comm.SSHPort != 22 { t.Fatalf("invalid value: %d", c.Comm.SSHPort) } c.Comm.SSHPort = 44 if err := c.Prepare(nil); len(err) != 0 { t.Fatalf("err: %s", err) } if c.Comm.SSHPort != 44 { t.Fatalf("invalid value: %d", c.Comm.SSHPort) } } func TestRunConfigPrepare_UserData(t *testing.T) { c := testConfig() tf, err := ioutil.TempFile("", "packer") if err != nil { t.Fatalf("err: %s", err) } defer tf.Close() c.UserData = "foo" c.UserDataFile = tf.Name() if err := c.Prepare(nil); len(err) != 1 { t.Fatalf("err: %s", err) } } func TestRunConfigPrepare_UserDataFile(t *testing.T) { c := testConfig() if err := c.Prepare(nil); len(err) != 0 { t.Fatalf("err: %s", err) } c.UserDataFile = "idontexistidontthink" if err := c.Prepare(nil); len(err) != 1 { t.Fatalf("err: %s", err) } tf, err := ioutil.TempFile("", "packer") if err != nil { t.Fatalf("err: %s", err) } defer tf.Close() c.UserDataFile = tf.Name() if err := c.Prepare(nil); len(err) != 0 { t.Fatalf("err: %s", err) } } func TestRunConfigPrepare_TemporaryKeyPairName(t *testing.T) { c := testConfig() c.TemporaryKeyPairName = "" if err := c.Prepare(nil); len(err) != 0 { t.Fatalf("err: %s", err) } if c.TemporaryKeyPairName == "" { t.Fatal("keypair name is empty") } // Match prefix and UUID, e.g. "packer_5790d491-a0b8-c84c-c9d2-2aea55086550". r := regexp.MustCompile(`\Apacker_(?:(?i)[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}?)\z`) if !r.MatchString(c.TemporaryKeyPairName) { t.Fatal("keypair name is not valid") } c.TemporaryKeyPairName = "ssh-key-123" if err := c.Prepare(nil); len(err) != 0 { t.Fatalf("err: %s", err) } if c.TemporaryKeyPairName != "ssh-key-123" { t.Fatal("keypair name does not match") } }
stardog-union/stardog-graviton
vendor/github.com/mitchellh/packer/builder/amazon/common/run_config_test.go
GO
apache-2.0
3,870