code
stringlengths
4
1.01M
language
stringclasses
2 values
//---------------------------------------------------------------------------------------------- // <copyright file="AppDeployment.cs" company="Microsoft Corporation"> // Licensed under the MIT License. See LICENSE.TXT in the project root license information. // </copyright> //---------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; #if !WINDOWS_UWP using System.Net; using System.Net.Http; #endif // !WINDOWS_UWP using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; #if WINDOWS_UWP using Windows.Foundation; using Windows.Security.Credentials; using Windows.Storage.Streams; using Windows.Web.Http; using Windows.Web.Http.Filters; using Windows.Web.Http.Headers; #endif namespace Microsoft.Tools.WindowsDevicePortal { /// <content> /// Wrappers for App Deployment methods. /// </content> public partial class DevicePortal { /// <summary> /// API to retrieve list of installed packages. /// </summary> public static readonly string InstalledPackagesApi = "api/app/packagemanager/packages"; /// <summary> /// Install state API. /// </summary> public static readonly string InstallStateApi = "api/app/packagemanager/state"; /// <summary> /// API for package management. /// </summary> public static readonly string PackageManagerApi = "api/app/packagemanager/package"; /// <summary> /// App Install Status handler. /// </summary> public event ApplicationInstallStatusEventHandler AppInstallStatus; /// <summary> /// Gets the collection of applications installed on the device. /// </summary> /// <returns>AppPackages object containing the list of installed application packages.</returns> public async Task<AppPackages> GetInstalledAppPackagesAsync() { return await this.GetAsync<AppPackages>(InstalledPackagesApi); } /// <summary> /// Installs an application /// </summary> /// <param name="appName">Friendly name (ex: Hello World) of the application. If this parameter is not provided, the name of the package is assumed to be the app name.</param> /// <param name="packageFileName">Full name of the application package file.</param> /// <param name="dependencyFileNames">List containing the full names of any required dependency files.</param> /// <param name="certificateFileName">Full name of the optional certificate file.</param> /// <param name="stateCheckIntervalMs">How frequently we should check the installation state.</param> /// <param name="timeoutInMinutes">Operation timeout.</param> /// <param name="uninstallPreviousVersion">Indicate whether or not the previous app version should be uninstalled prior to installing.</param> /// <remarks>InstallApplication sends ApplicationInstallStatus events to indicate the current progress in the installation process. /// Some applications may opt to not register for the AppInstallStatus event and await on InstallApplication.</remarks> /// <returns>Task for tracking completion of install initialization.</returns> public async Task InstallApplicationAsync( string appName, string packageFileName, List<string> dependencyFileNames, string certificateFileName = null, short stateCheckIntervalMs = 500, short timeoutInMinutes = 15, bool uninstallPreviousVersion = true) { string installPhaseDescription = string.Empty; try { FileInfo packageFile = new FileInfo(packageFileName); // If appName was not provided, use the package file name if (string.IsNullOrEmpty(appName)) { appName = packageFile.Name; } // Uninstall the application's previous version, if one exists. if (uninstallPreviousVersion) { installPhaseDescription = string.Format("Uninstalling any previous version of {0}", appName); this.SendAppInstallStatus( ApplicationInstallStatus.InProgress, ApplicationInstallPhase.UninstallingPreviousVersion, installPhaseDescription); AppPackages installedApps = await this.GetInstalledAppPackagesAsync(); foreach (PackageInfo package in installedApps.Packages) { if (package.Name == appName) { await this.UninstallApplicationAsync(package.FullName); break; } } } // Create the API endpoint and generate a unique boundary string. Uri uri; string boundaryString; this.CreateAppInstallEndpointAndBoundaryString( packageFile.Name, out uri, out boundaryString); installPhaseDescription = string.Format("Copying: {0}", packageFile.Name); this.SendAppInstallStatus( ApplicationInstallStatus.InProgress, ApplicationInstallPhase.CopyingFile, installPhaseDescription); var content = new HttpMultipartFileContent(); content.Add(packageFile.FullName); content.AddRange(dependencyFileNames); content.Add(certificateFileName); await this.PostAsync(uri, content); // Poll the status until complete. ApplicationInstallStatus status = ApplicationInstallStatus.InProgress; do { installPhaseDescription = string.Format("Installing {0}", appName); this.SendAppInstallStatus( ApplicationInstallStatus.InProgress, ApplicationInstallPhase.Installing, installPhaseDescription); await Task.Delay(TimeSpan.FromMilliseconds(stateCheckIntervalMs)); status = await this.GetInstallStatusAsync().ConfigureAwait(false); } while (status == ApplicationInstallStatus.InProgress); installPhaseDescription = string.Format("{0} installed successfully", appName); this.SendAppInstallStatus( ApplicationInstallStatus.Completed, ApplicationInstallPhase.Idle, installPhaseDescription); } catch (Exception e) { DevicePortalException dpe = e as DevicePortalException; if (dpe != null) { this.SendAppInstallStatus( ApplicationInstallStatus.Failed, ApplicationInstallPhase.Idle, string.Format("Failed to install {0}: {1}", appName, dpe.Reason)); } else { this.SendAppInstallStatus( ApplicationInstallStatus.Failed, ApplicationInstallPhase.Idle, string.Format("Failed to install {0}: {1}", appName, installPhaseDescription)); } } } /// <summary> /// Uninstalls the specified application. /// </summary> /// <param name="packageName">The name of the application package to uninstall.</param> /// <returns>Task tracking the uninstall operation.</returns> public async Task UninstallApplicationAsync(string packageName) { await this.DeleteAsync( PackageManagerApi, //// NOTE: When uninstalling an app package, the package name is not Hex64 encoded. string.Format("package={0}", packageName)); } /// <summary> /// Builds the application installation Uri and generates a unique boundary string for the multipart form data. /// </summary> /// <param name="packageName">The name of the application package.</param> /// <param name="uri">The endpoint for the install request.</param> /// <param name="boundaryString">Unique string used to separate the parts of the multipart form data.</param> private void CreateAppInstallEndpointAndBoundaryString( string packageName, out Uri uri, out string boundaryString) { uri = Utilities.BuildEndpoint( this.deviceConnection.Connection, PackageManagerApi, string.Format("package={0}", packageName)); boundaryString = Guid.NewGuid().ToString(); } /// <summary> /// Sends application install status. /// </summary> /// <param name="status">Status of the installation.</param> /// <param name="phase">Current installation phase (ex: Uninstalling previous version)</param> /// <param name="message">Optional error message describing the install status.</param> private void SendAppInstallStatus( ApplicationInstallStatus status, ApplicationInstallPhase phase, string message = "") { this.AppInstallStatus?.Invoke( this, new ApplicationInstallStatusEventArgs(status, phase, message)); } #region Data contract /// <summary> /// Object representing a list of Application Packages /// </summary> [DataContract] public class AppPackages { /// <summary> /// Gets a list of the packages /// </summary> [DataMember(Name = "InstalledPackages")] public List<PackageInfo> Packages { get; private set; } /// <summary> /// Presents a user readable representation of a list of AppPackages /// </summary> /// <returns>User readable list of AppPackages.</returns> public override string ToString() { string output = "Packages:\n"; foreach (PackageInfo package in this.Packages) { output += package; } return output; } } /// <summary> /// Object representing the install state /// </summary> [DataContract] public class InstallState { /// <summary> /// Gets install state code /// </summary> [DataMember(Name = "Code")] public int Code { get; private set; } /// <summary> /// Gets message text /// </summary> [DataMember(Name = "CodeText")] public string CodeText { get; private set; } /// <summary> /// Gets reason for state /// </summary> [DataMember(Name = "Reason")] public string Reason { get; private set; } /// <summary> /// Gets a value indicating whether this was successful /// </summary> [DataMember(Name = "Success")] public bool WasSuccessful { get; private set; } } /// <summary> /// object representing the package information /// </summary> [DataContract] public class PackageInfo { /// <summary> /// Gets package name /// </summary> [DataMember(Name = "Name")] public string Name { get; private set; } /// <summary> /// Gets package family name /// </summary> [DataMember(Name = "PackageFamilyName")] public string FamilyName { get; private set; } /// <summary> /// Gets package full name /// </summary> [DataMember(Name = "PackageFullName")] public string FullName { get; private set; } /// <summary> /// Gets package relative Id /// </summary> [DataMember(Name = "PackageRelativeId")] public string AppId { get; private set; } /// <summary> /// Gets package publisher /// </summary> [DataMember(Name = "Publisher")] public string Publisher { get; private set; } /// <summary> /// Gets package version /// </summary> [DataMember(Name = "Version")] public PackageVersion Version { get; private set; } /// <summary> /// Gets package origin, a measure of how the app was installed. /// PackageOrigin_Unknown            = 0, /// PackageOrigin_Unsigned           = 1, /// PackageOrigin_Inbox              = 2, /// PackageOrigin_Store              = 3, /// PackageOrigin_DeveloperUnsigned  = 4, /// PackageOrigin_DeveloperSigned    = 5, /// PackageOrigin_LineOfBusiness     = 6 /// </summary> [DataMember(Name = "PackageOrigin")] public int PackageOrigin { get; private set; } /// <summary> /// Helper method to determine if the app was sideloaded and therefore can be used with e.g. GetFolderContentsAsync /// </summary> /// <returns> True if the package is sideloaded. </returns> public bool IsSideloaded() { return this.PackageOrigin == 4 || this.PackageOrigin == 5; } /// <summary> /// Get a string representation of the package /// </summary> /// <returns>String representation</returns> public override string ToString() { return string.Format("\t{0}\n\t\t{1}\n", this.FullName, this.AppId); } } /// <summary> /// Object representing a package version /// </summary> [DataContract] public class PackageVersion { /// <summary> /// Gets version build /// </summary> [DataMember(Name = "Build")] public int Build { get; private set; } /// <summary> /// Gets package Major number /// </summary> [DataMember(Name = "Major")] public int Major { get; private set; } /// <summary> /// Gets package minor number /// </summary> [DataMember(Name = "Minor")] public int Minor { get; private set; } /// <summary> /// Gets package revision /// </summary> [DataMember(Name = "Revision")] public int Revision { get; private set; } /// <summary> /// Gets package version /// </summary> public Version Version { get { return new Version(this.Major, this.Minor, this.Build, this.Revision); } } /// <summary> /// Get a string representation of a version /// </summary> /// <returns>String representation</returns> public override string ToString() { return Version.ToString(); } } #endregion // Data contract } }
Java
'use strict'; module.exports = function generate_format(it, $keyword) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); if (it.opts.format === false) { if ($breakOnError) { out += ' if (true) { '; } return out; } var $isData = it.opts.v5 && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats); if ($isData) { var $format = 'format' + $lvl; out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var isObject' + ($lvl) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; if (isObject' + ($lvl) + ') { '; if (it.async) { out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; } out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; } out += ' ('; if ($unknownFormats === true || $allowUnknown) { out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; if ($allowUnknown) { out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; } out += ') || '; } out += ' (' + ($format) + ' && !(typeof ' + ($format) + ' == \'function\' ? '; if (it.async) { out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; } else { out += ' ' + ($format) + '(' + ($data) + ') '; } out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; } else { var $format = it.formats[$schema]; if (!$format) { if ($unknownFormats === true || ($allowUnknown && $unknownFormats.indexOf($schema) == -1)) { throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); } else { if (!$allowUnknown) { console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); if ($unknownFormats !== 'ignore') console.warn('In the next major version it will throw exception. See option unknownFormats for more information'); } if ($breakOnError) { out += ' if (true) { '; } return out; } } var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; if ($isObject) { var $async = $format.async === true; $format = $format.validate; } if ($async) { if (!it.async) throw new Error('async format in sync schema'); var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { '; } else { out += ' if (! '; var $formatRef = 'formats' + it.util.getProperty($schema); if ($isObject) $formatRef += '.validate'; if (typeof $format == 'function') { out += ' ' + ($formatRef) + '(' + ($data) + ') '; } else { out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; } out += ') { '; } } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; if ($isData) { out += '' + ($schemaValue); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match format "'; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + (it.util.escapeQuotes($schema)); } out += '"\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } return out; }
Java
package org.luban.common.plugin; import org.luban.common.network.URL; /** * 服务插件接口 * * @author hexiaofeng * @version 1.0.0 * @since 12-12-12 下午8:47 */ public interface ServicePlugin { /** * 返回类型 * * @return */ String getType(); /** * 设置URL * * @param url */ void setUrl(URL url); }
Java
#!/usr/bin/env python2 """Example of server-side computations used in global forest change analysis. In this example we will focus on server side computation using NDVI and EVI data. This both metrics are computed bands created by third party companies or directly taken by the satellites. NDVI and EVI are two metrics used in global forest change analysis. They represent the forest concentration in a specific area. We will use the MOD13A1 vegetation indice provided by the NASA [1]. The goal is to generate an RGB image, where reds stands for deforestation, gree for reforestation and blue for masked data (e.g. rivers, oceans...). [1] https://code.earthengine.google.com/dataset/MODIS/MOD13A1 """ import ee # Initialize the Earth Engine ee.Initialize() # Small rectangle used to generate the image, over the Amazonian forest. # The location is above the Rondonia (West of Bresil). rectangle = ee.Geometry.Rectangle(-68, -7, -65, -8) # Get the MODIS dataset. collection = ee.ImageCollection('MODIS/MOD13A1') # Select the EVI, since it is more accurate on this dataset. You can also # use the NDVI band here. collection = collection.select(['EVI']) # Get two dataset, one over the year 2000 and the other one over 2015 ndvi2000 = collection.filterDate('2000-01-01', '2000-12-31').median() ndvi2015 = collection.filterDate('2015-01-01', '2015-12-31').median() # Substract the two datasets to see the evolution between both of them. difference = ndvi2015.subtract(ndvi2000) # Use a mask to avoid showing data on rivers. # TODO(funkysayu) move this mask to blue color. classifiedImage = ee.Image('MODIS/051/MCD12Q1/2001_01_01') mask = classifiedImage.select(['Land_Cover_Type_1']) maskedDifference = difference.updateMask(mask) # Convert it to RGB image. visualized = maskedDifference.visualize( min=-2000, max=2000, palette='FF0000, 000000, 00FF00', ) # Finally generate the PNG. print visualized.getDownloadUrl({ 'region': rectangle.toGeoJSONString(), 'scale': 500, 'format': 'png', })
Java
require File.expand_path("../../../test_helper", __FILE__) describe Flipflop::Strategies::DefaultStrategy do before do Flipflop::FeatureSet.current.replace do Flipflop.configure do feature :one, default: true feature :two end end end describe "with defaults" do subject do Flipflop::Strategies::DefaultStrategy.new.freeze end it "should have default name" do assert_equal "default", subject.name end it "should have title derived from name" do assert_equal "Default", subject.title end it "should have no default description" do assert_equal "Uses feature default status.", subject.description end it "should not be switchable" do assert_equal false, subject.switchable? end it "should have unique key" do assert_match /^\w+$/, subject.key end describe "with explicitly defaulted feature" do it "should have feature enabled" do assert_equal true, subject.enabled?(:one) end end describe "with implicitly defaulted feature" do it "should not have feature enabled" do assert_equal false, subject.enabled?(:two) end end end end
Java
require 'forwardable' require 'puppet/node' require 'puppet/resource/catalog' require 'puppet/util/errors' require 'puppet/resource/type_collection_helper' # Maintain a graph of scopes, along with a bunch of data # about the individual catalog we're compiling. class Puppet::Parser::Compiler extend Forwardable include Puppet::Util include Puppet::Util::Errors include Puppet::Util::MethodHelper include Puppet::Resource::TypeCollectionHelper def self.compile(node) $env_module_directories = nil node.environment.check_for_reparse if node.environment.conflicting_manifest_settings? errmsg = [ "The 'disable_per_environment_manifest' setting is true, and this '#{node.environment}'", "has an environment.conf manifest that conflicts with the 'default_manifest' setting.", "Compilation has been halted in order to avoid running a catalog which may be using", "unexpected manifests. For more information, see", "http://docs.puppetlabs.com/puppet/latest/reference/environments.html", ] raise(Puppet::Error, errmsg.join(' ')) end new(node).compile {|resulting_catalog| resulting_catalog.to_resource } rescue Puppet::ParseErrorWithIssue => detail detail.node = node.name Puppet.log_exception(detail) raise rescue => detail message = "#{detail} on node #{node.name}" Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end attr_reader :node, :facts, :collections, :catalog, :resources, :relationships, :topscope # The injector that provides lookup services, or nil if accessed before the compiler has started compiling and # bootstrapped. The injector is initialized and available before any manifests are evaluated. # # @return [Puppet::Pops::Binder::Injector, nil] The injector that provides lookup services for this compiler/environment # @api public # attr_accessor :injector # Access to the configured loaders for 4x # @return [Puppet::Pops::Loader::Loaders] the configured loaders # @api private attr_reader :loaders # The injector that provides lookup services during the creation of the {#injector}. # @return [Puppet::Pops::Binder::Injector, nil] The injector that provides lookup services during injector creation # for this compiler/environment # # @api private # attr_accessor :boot_injector # Add a collection to the global list. def_delegator :@collections, :<<, :add_collection def_delegator :@relationships, :<<, :add_relationship # Store a resource override. def add_override(override) # If possible, merge the override in immediately. if resource = @catalog.resource(override.ref) resource.merge(override) else # Otherwise, store the override for later; these # get evaluated in Resource#finish. @resource_overrides[override.ref] << override end end def add_resource(scope, resource) @resources << resource # Note that this will fail if the resource is not unique. @catalog.add_resource(resource) if not resource.class? and resource[:stage] raise ArgumentError, "Only classes can set 'stage'; normal resources like #{resource} cannot change run stage" end # Stages should not be inside of classes. They are always a # top-level container, regardless of where they appear in the # manifest. return if resource.stage? # This adds a resource to the class it lexically appears in in the # manifest. unless resource.class? return @catalog.add_edge(scope.resource, resource) end end # Do we use nodes found in the code, vs. the external node sources? def_delegator :known_resource_types, :nodes?, :ast_nodes? # Store the fact that we've evaluated a class def add_class(name) @catalog.add_class(name) unless name == "" end # Return a list of all of the defined classes. def_delegator :@catalog, :classes, :classlist # Compiler our catalog. This mostly revolves around finding and evaluating classes. # This is the main entry into our catalog. def compile Puppet.override( @context_overrides , "For compiling #{node.name}") do @catalog.environment_instance = environment # Set the client's parameters into the top scope. Puppet::Util::Profiler.profile("Compile: Set node parameters", [:compiler, :set_node_params]) { set_node_parameters } Puppet::Util::Profiler.profile("Compile: Created settings scope", [:compiler, :create_settings_scope]) { create_settings_scope } if is_binder_active? # create injector, if not already created - this is for 3x that does not trigger # lazy loading of injector via context Puppet::Util::Profiler.profile("Compile: Created injector", [:compiler, :create_injector]) { injector } end Puppet::Util::Profiler.profile("Compile: Evaluated main", [:compiler, :evaluate_main]) { evaluate_main } Puppet::Util::Profiler.profile("Compile: Evaluated AST node", [:compiler, :evaluate_ast_node]) { evaluate_ast_node } Puppet::Util::Profiler.profile("Compile: Evaluated node classes", [:compiler, :evaluate_node_classes]) { evaluate_node_classes } Puppet::Util::Profiler.profile("Compile: Evaluated generators", [:compiler, :evaluate_generators]) { evaluate_generators } Puppet::Util::Profiler.profile("Compile: Finished catalog", [:compiler, :finish_catalog]) { finish } fail_on_unevaluated if block_given? yield @catalog else @catalog end end end # Constructs the overrides for the context def context_overrides() if Puppet.future_parser?(environment) { :current_environment => environment, :global_scope => @topscope, # 4x placeholder for new global scope :loaders => lambda {|| loaders() }, # 4x loaders :injector => lambda {|| injector() } # 4x API - via context instead of via compiler } else { :current_environment => environment, } end end def_delegator :@collections, :delete, :delete_collection # Return the node's environment. def environment node.environment end # Evaluate all of the classes specified by the node. # Classes with parameters are evaluated as if they were declared. # Classes without parameters or with an empty set of parameters are evaluated # as if they were included. This means classes with an empty set of # parameters won't conflict even if the class has already been included. def evaluate_node_classes if @node.classes.is_a? Hash classes_with_params, classes_without_params = @node.classes.partition {|name,params| params and !params.empty?} # The results from Hash#partition are arrays of pairs rather than hashes, # so we have to convert to the forms evaluate_classes expects (Hash, and # Array of class names) classes_with_params = Hash[classes_with_params] classes_without_params.map!(&:first) else classes_with_params = {} classes_without_params = @node.classes end evaluate_classes(classes_with_params, @node_scope || topscope) evaluate_classes(classes_without_params, @node_scope || topscope) end # Evaluate each specified class in turn. If there are any classes we can't # find, raise an error. This method really just creates resource objects # that point back to the classes, and then the resources are themselves # evaluated later in the process. # # Sometimes we evaluate classes with a fully qualified name already, in which # case, we tell scope.find_hostclass we've pre-qualified the name so it # doesn't need to search its namespaces again. This gets around a weird # edge case of duplicate class names, one at top scope and one nested in our # namespace and the wrong one (or both!) getting selected. See ticket #13349 # for more detail. --jeffweiss 26 apr 2012 def evaluate_classes(classes, scope, lazy_evaluate = true, fqname = false) raise Puppet::DevError, "No source for scope passed to evaluate_classes" unless scope.source class_parameters = nil # if we are a param class, save the classes hash # and transform classes to be the keys if classes.class == Hash class_parameters = classes classes = classes.keys end hostclasses = classes.collect do |name| scope.find_hostclass(name, :assume_fqname => fqname) or raise Puppet::Error, "Could not find class #{name} for #{node.name}" end if class_parameters resources = ensure_classes_with_parameters(scope, hostclasses, class_parameters) if !lazy_evaluate resources.each(&:evaluate) end resources else already_included, newly_included = ensure_classes_without_parameters(scope, hostclasses) if !lazy_evaluate newly_included.each(&:evaluate) end already_included + newly_included end end def evaluate_relationships @relationships.each { |rel| rel.evaluate(catalog) } end # Return a resource by either its ref or its type and title. def_delegator :@catalog, :resource, :findresource def initialize(node, options = {}) @node = node set_options(options) initvars end # Create a new scope, with either a specified parent scope or # using the top scope. def newscope(parent, options = {}) parent ||= topscope scope = Puppet::Parser::Scope.new(self, options) scope.parent = parent scope end # Return any overrides for the given resource. def resource_overrides(resource) @resource_overrides[resource.ref] end def injector create_injector if @injector.nil? @injector end def loaders @loaders ||= Puppet::Pops::Loaders.new(environment) end def boot_injector create_boot_injector(nil) if @boot_injector.nil? @boot_injector end # Creates the boot injector from registered system, default, and injector config. # @return [Puppet::Pops::Binder::Injector] the created boot injector # @api private Cannot be 'private' since it is called from the BindingsComposer. # def create_boot_injector(env_boot_bindings) assert_binder_active() pb = Puppet::Pops::Binder boot_contribution = pb::SystemBindings.injector_boot_contribution(env_boot_bindings) final_contribution = pb::SystemBindings.final_contribution binder = pb::Binder.new(pb::BindingsFactory.layered_bindings(final_contribution, boot_contribution)) @boot_injector = pb::Injector.new(binder) end # Answers if Puppet Binder should be active or not, and if it should and is not active, then it is activated. # @return [Boolean] true if the Puppet Binder should be activated def is_binder_active? should_be_active = Puppet[:binder] || Puppet.future_parser? if should_be_active # TODO: this should be in a central place, not just for ParserFactory anymore... Puppet::Parser::ParserFactory.assert_rgen_installed() @@binder_loaded ||= false unless @@binder_loaded require 'puppet/pops' require 'puppetx' @@binder_loaded = true end end should_be_active end private def ensure_classes_with_parameters(scope, hostclasses, parameters) hostclasses.collect do |klass| klass.ensure_in_catalog(scope, parameters[klass.name] || {}) end end def ensure_classes_without_parameters(scope, hostclasses) already_included = [] newly_included = [] hostclasses.each do |klass| class_scope = scope.class_scope(klass) if class_scope already_included << class_scope.resource else newly_included << klass.ensure_in_catalog(scope) end end [already_included, newly_included] end # If ast nodes are enabled, then see if we can find and evaluate one. def evaluate_ast_node return unless ast_nodes? # Now see if we can find the node. astnode = nil @node.names.each do |name| break if astnode = known_resource_types.node(name.to_s.downcase) end unless (astnode ||= known_resource_types.node("default")) raise Puppet::ParseError, "Could not find default node or by name with '#{node.names.join(", ")}'" end # Create a resource to model this node, and then add it to the list # of resources. resource = astnode.ensure_in_catalog(topscope) resource.evaluate @node_scope = topscope.class_scope(astnode) end # Evaluate our collections and return true if anything returned an object. # The 'true' is used to continue a loop, so it's important. def evaluate_collections return false if @collections.empty? exceptwrap do # We have to iterate over a dup of the array because # collections can delete themselves from the list, which # changes its length and causes some collections to get missed. Puppet::Util::Profiler.profile("Evaluated collections", [:compiler, :evaluate_collections]) do found_something = false @collections.dup.each do |collection| found_something = true if collection.evaluate end found_something end end end # Make sure all of our resources have been evaluated into native resources. # We return true if any resources have, so that we know to continue the # evaluate_generators loop. def evaluate_definitions exceptwrap do Puppet::Util::Profiler.profile("Evaluated definitions", [:compiler, :evaluate_definitions]) do !unevaluated_resources.each do |resource| resource.evaluate end.empty? end end end # Iterate over collections and resources until we're sure that the whole # compile is evaluated. This is necessary because both collections # and defined resources can generate new resources, which themselves could # be defined resources. def evaluate_generators count = 0 loop do done = true Puppet::Util::Profiler.profile("Iterated (#{count + 1}) on generators", [:compiler, :iterate_on_generators]) do # Call collections first, then definitions. done = false if evaluate_collections done = false if evaluate_definitions end break if done count += 1 if count > 1000 raise Puppet::ParseError, "Somehow looped more than 1000 times while evaluating host catalog" end end end # Find and evaluate our main object, if possible. def evaluate_main @main = known_resource_types.find_hostclass([""], "") || known_resource_types.add(Puppet::Resource::Type.new(:hostclass, "")) @topscope.source = @main @main_resource = Puppet::Parser::Resource.new("class", :main, :scope => @topscope, :source => @main) @topscope.resource = @main_resource add_resource(@topscope, @main_resource) @main_resource.evaluate end # Make sure the entire catalog is evaluated. def fail_on_unevaluated fail_on_unevaluated_overrides fail_on_unevaluated_resource_collections end # If there are any resource overrides remaining, then we could # not find the resource they were supposed to override, so we # want to throw an exception. def fail_on_unevaluated_overrides remaining = @resource_overrides.values.flatten.collect(&:ref) if !remaining.empty? fail Puppet::ParseError, "Could not find resource(s) #{remaining.join(', ')} for overriding" end end # Make sure we don't have any remaining collections that specifically # look for resources, because we want to consider those to be # parse errors. def fail_on_unevaluated_resource_collections if Puppet.future_parser? remaining = @collections.collect(&:unresolved_resources).flatten.compact else remaining = @collections.collect(&:resources).flatten.compact end if !remaining.empty? raise Puppet::ParseError, "Failed to realize virtual resources #{remaining.join(', ')}" end end # Make sure all of our resources and such have done any last work # necessary. def finish evaluate_relationships resources.each do |resource| # Add in any resource overrides. if overrides = resource_overrides(resource) overrides.each do |over| resource.merge(over) end # Remove the overrides, so that the configuration knows there # are none left. overrides.clear end resource.finish if resource.respond_to?(:finish) end add_resource_metaparams end def add_resource_metaparams unless main = catalog.resource(:class, :main) raise "Couldn't find main" end names = Puppet::Type.metaparams.select do |name| !Puppet::Parser::Resource.relationship_parameter?(name) end data = {} catalog.walk(main, :out) do |source, target| if source_data = data[source] || metaparams_as_data(source, names) # only store anything in the data hash if we've actually got # data data[source] ||= source_data source_data.each do |param, value| target[param] = value if target[param].nil? end data[target] = source_data.merge(metaparams_as_data(target, names)) end target.tag(*(source.tags)) end end def metaparams_as_data(resource, params) data = nil params.each do |param| unless resource[param].nil? # Because we could be creating a hash for every resource, # and we actually probably don't often have any data here at all, # we're optimizing a bit by only creating a hash if there's # any data to put in it. data ||= {} data[param] = resource[param] end end data end # Set up all of our internal variables. def initvars # The list of overrides. This is used to cache overrides on objects # that don't exist yet. We store an array of each override. @resource_overrides = Hash.new do |overs, ref| overs[ref] = [] end # The list of collections that have been created. This is a global list, # but they each refer back to the scope that created them. @collections = [] # The list of relationships to evaluate. @relationships = [] # For maintaining the relationship between scopes and their resources. @catalog = Puppet::Resource::Catalog.new(@node.name, @node.environment) # MOVED HERE - SCOPE IS NEEDED (MOVE-SCOPE) # Create the initial scope, it is needed early @topscope = Puppet::Parser::Scope.new(self) # Need to compute overrides here, and remember them, because we are about to # enter the magic zone of known_resource_types and intial import. # Expensive entries in the context are bound lazily. @context_overrides = context_overrides() # This construct ensures that initial import (triggered by instantiating # the structure 'known_resource_types') has a configured context # It cannot survive the initvars method, and is later reinstated # as part of compiling... # Puppet.override( @context_overrides , "For initializing compiler") do # THE MAGIC STARTS HERE ! This triggers parsing, loading etc. @catalog.version = known_resource_types.version end @catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => @topscope)) # local resource array to maintain resource ordering @resources = [] # Make sure any external node classes are in our class list if @node.classes.class == Hash @catalog.add_class(*@node.classes.keys) else @catalog.add_class(*@node.classes) end end # Set the node's parameters into the top-scope as variables. def set_node_parameters node.parameters.each do |param, value| @topscope[param.to_s] = value end # These might be nil. catalog.client_version = node.parameters["clientversion"] catalog.server_version = node.parameters["serverversion"] if Puppet[:trusted_node_data] @topscope.set_trusted(node.trusted_data) end if(Puppet[:immutable_node_data]) facts_hash = node.facts.nil? ? {} : node.facts.values @topscope.set_facts(facts_hash) end end def create_settings_scope settings_type = Puppet::Resource::Type.new :hostclass, "settings" environment.known_resource_types.add(settings_type) settings_resource = Puppet::Parser::Resource.new("class", "settings", :scope => @topscope) @catalog.add_resource(settings_resource) settings_type.evaluate_code(settings_resource) scope = @topscope.class_scope(settings_type) env = environment Puppet.settings.each do |name, setting| next if name == :name scope[name.to_s] = env[name] end end # Return an array of all of the unevaluated resources. These will be definitions, # which need to get evaluated into native resources. def unevaluated_resources # The order of these is significant for speed due to short-circuting resources.reject { |resource| resource.evaluated? or resource.virtual? or resource.builtin_type? } end # Creates the injector from bindings found in the current environment. # @return [void] # @api private # def create_injector assert_binder_active() composer = Puppet::Pops::Binder::BindingsComposer.new() layered_bindings = composer.compose(topscope) @injector = Puppet::Pops::Binder::Injector.new(Puppet::Pops::Binder::Binder.new(layered_bindings)) end def assert_binder_active unless is_binder_active? raise ArgumentError, "The Puppet Binder is only available when either '--binder true' or '--parser future' is used" end end end
Java
package nxt.http; import nxt.Nxt; import nxt.Transaction; import nxt.util.Convert; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware; import javax.servlet.http.HttpServletRequest; import static nxt.http.JSONResponses.INCORRECT_TRANSACTION; import static nxt.http.JSONResponses.MISSING_TRANSACTION; import static nxt.http.JSONResponses.UNKNOWN_TRANSACTION; public final class GetTransaction extends APIServlet.APIRequestHandler { static final GetTransaction instance = new GetTransaction(); private GetTransaction() { super("transaction", "hash"); } @Override JSONStreamAware processRequest(HttpServletRequest req) { String transactionIdString = Convert.emptyToNull(req.getParameter("transaction")); String transactionHash = Convert.emptyToNull(req.getParameter("hash")); if (transactionIdString == null && transactionHash == null) { return MISSING_TRANSACTION; } Long transactionId = null; Transaction transaction; try { if (transactionIdString != null) { transactionId = Convert.parseUnsignedLong(transactionIdString); transaction = Nxt.getBlockchain().getTransaction(transactionId); } else { transaction = Nxt.getBlockchain().getTransaction(transactionHash); if (transaction == null) { return UNKNOWN_TRANSACTION; } } } catch (RuntimeException e) { return INCORRECT_TRANSACTION; } JSONObject response; if (transaction == null) { transaction = Nxt.getTransactionProcessor().getUnconfirmedTransaction(transactionId); if (transaction == null) { return UNKNOWN_TRANSACTION; } response = transaction.getJSONObject(); } else { response = transaction.getJSONObject(); response.put("block", Convert.toUnsignedLong(transaction.getBlockId())); response.put("confirmations", Nxt.getBlockchain().getLastBlock().getHeight() - transaction.getHeight()); response.put("blockTimestamp", transaction.getBlockTimestamp()); } response.put("sender", Convert.toUnsignedLong(transaction.getSenderId())); response.put("hash", transaction.getHash()); return response; } }
Java
# =================================================================== # # Copyright (c) 2015, Legrandin <helderijs@gmail.com> # 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. # # 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 HOLDER 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. # =================================================================== """Keccak family of cryptographic hash algorithms. `Keccak`_ is the winning algorithm of the SHA-3 competition organized by NIST. What eventually became SHA-3 is a variant incompatible to Keccak, even though the security principles and margins remain the same. If you are interested in writing SHA-3 compliant code, you must use the modules ``SHA3_224``, ``SHA3_256``, ``SHA3_384`` or ``SHA3_512``. This module implements the Keccak hash functions for the 64 bit word length (b=1600) and the fixed digest sizes of 224, 256, 384 and 512 bits. >>> from Cryptodome.Hash import keccak >>> >>> keccak_hash = keccak.new(digest_bits=512) >>> keccak_hash.update(b'Some data') >>> print keccak_hash.hexdigest() .. _Keccak: http://www.keccak.noekeon.org/Keccak-specifications.pdf """ from Cryptodome.Util.py3compat import bord from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer, SmartPointer, create_string_buffer, get_raw_buffer, c_size_t, expect_byte_string) _raw_keccak_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._keccak", """ int keccak_init(void **state, size_t capacity_bytes, uint8_t padding_byte); int keccak_destroy(void *state); int keccak_absorb(void *state, const uint8_t *in, size_t len); int keccak_squeeze(const void *state, uint8_t *out, size_t len); int keccak_digest(void *state, uint8_t *digest, size_t len); """) class Keccak_Hash(object): """Class that implements a Keccak hash """ def __init__(self, data, digest_bytes, update_after_digest): #: The size of the resulting hash in bytes. self.digest_size = digest_bytes self._update_after_digest = update_after_digest self._digest_done = False state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(self.digest_size * 2), 0x01) if result: raise ValueError("Error %d while instantiating keccak" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError("You can only call 'digest' or 'hexdigest' on this object") expect_byte_string(data) result = _raw_keccak_lib.keccak_absorb(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while updating keccak" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. You cannot update the hash anymore after the first call to ``digest`` (or ``hexdigest``). :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ self._digest_done = True bfr = create_string_buffer(self.digest_size) result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while squeezing keccak" % result) return get_raw_buffer(bfr) def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. This method does not change the state of the hash object. :Return: A string of 2* `digest_size` characters. It contains only hexadecimal ASCII digits. """ return "".join(["%02x" % bord(x) for x in self.digest()]) def new(self, **kwargs): if "digest_bytes" not in kwargs and "digest_bits" not in kwargs: kwargs["digest_bytes"] = self.digest_size return new(**kwargs) def new(**kwargs): """Return a fresh instance of the hash object. :Keywords: data : byte string Optional. The very first chunk of the message to hash. It is equivalent to an early call to ``update()``. digest_bytes : integer The size of the digest, in bytes (28, 32, 48, 64). digest_bits : integer The size of the digest, in bits (224, 256, 384, 512). update_after_digest : boolean Optional. By default, a hash object cannot be updated anymore after the digest is computed. When this flag is ``True``, such check is no longer enforced. :Return: A `Keccak_Hash` object """ data = kwargs.pop("data", None) update_after_digest = kwargs.pop("update_after_digest", False) digest_bytes = kwargs.pop("digest_bytes", None) digest_bits = kwargs.pop("digest_bits", None) if None not in (digest_bytes, digest_bits): raise TypeError("Only one digest parameter must be provided") if (None, None) == (digest_bytes, digest_bits): raise TypeError("Digest size (bits, bytes) not provided") if digest_bytes is not None: if digest_bytes not in (28, 32, 48, 64): raise ValueError("'digest_bytes' must be: 28, 32, 48 or 64") else: if digest_bits not in (224, 256, 384, 512): raise ValueError("'digest_bytes' must be: 224, 256, 384 or 512") digest_bytes = digest_bits // 8 if kwargs: raise TypeError("Unknown parameters: " + str(kwargs)) return Keccak_Hash(data, digest_bytes, update_after_digest)
Java
--- title: Kathryn Borel summary: Writer and editor (The Believer, American Dad!) categories: - editor - mac - writer --- ### Who are you, and what do you do? I am [Kathryn Borel, Jr](http://www.kathrynborel.com/ "Kathryn's website."). I am a former Canadian radio journalist (Canadian Broadcasting Corporation) and currently an LA-based television writer (American Dad! on TBS.) I'm also the interviews editor at [The Believer](http://www.believermag.com/ "A literary magazine."), the nice pithy literary magazine founded by Dave Eggers a bunch of years ago. And I wrote a book called [Corked](http://www.amazon.com/Corked-Memoir-Kathryn-Borel/dp/0446409502/ "Kathryn's book."). I've done other writerly garbage but those are the top headlines. ### What hardware do you use? Everything I do is done on a 13-inch [MacBook Air][macbook-air], and I just received a [Das Keyboard Model S mechanical keyboard][model-s-professional] that makes a very satisfying clickety-clack sound of the desktop computers of yesteryear. I like to think the reward of the clack makes me a more decisive writer and thinker. Counterintuitively I'll plug in a pair of [Bose QuietComfort headphones][quietcomfort-15] while I write. When I'm being an analog guy I use a red Moleskine (yearly Xmas present from my parents) and the Lamy fountain pen my best friend gave me as a maid of honor gift, which I love despite me being left-handed and constantly dragging my hand through the ink and making smears. ### And what software? [Final Draft 9 Pro Edition][final-draft] for screenwriting; [TextEdit][] for all other stuff. TextEdit has an appealing unfussiness -- fewer options and no margins and the small screen all make the act of writing feel less precious and therefore less daunting. ### What would be your dream setup? I really really REALLY wish there were a reliable transcription program for when I have to transcribe the interviews I do for The Believer. I also would like a disgusting, fart-trapping leather club chair and someone to pour me small glasses of wine when I work at night. [final-draft]: http://store.finaldraft.com/final-draft-10.html "Popular screenwriting software." [macbook-air]: https://www.apple.com/macbook-air/ "A very thin laptop." [model-s-professional]: https://www.daskeyboard.com/model-s-professional/ "A keyboard." [quietcomfort-15]: http://www.bose.com/controller?url=/shop_online/headphones/noise_cancelling_headphones/quietcomfort_15/index.jsp "Noise-cancelling headphones." [textedit]: https://support.apple.com/en-us/HT2523 "A text editor included with Mac OS X."
Java
module Octokit class Client module Gists # List gists for a user or all public gists # # @param username [String] An optional user to filter listing # @return [Array<Hashie::Mash>] A list of gists # @example Fetch all gists for defunkt # Octokit.gists('defunkt') # @example Fetch all public gists # Octokit.gists # @see http://developer.github.com/v3/gists/#list-gists def gists(username=nil, options={}) if username.nil? get 'gists', options else get "users/#{username}/gists", options end end alias :list_gists :gists # List public gists # # @return [Array<Hashie::Mash>] A list of gists # @example Fetch all public gists # Octokit.public_gists # @see http://developer.github.com/v3/gists/#list-gists def public_gists(options={}) get 'gists/public', options end # List the authenticated user’s starred gists # # @return [Array<Hashie::Mash>] A list of gists def starred_gists(options={}) get 'gists/starred', options end # Get a single gist # # @param gist [String] ID of gist to fetch # @return [Hash::Mash] Gist information # @see http://developer.github.com/v3/gists/#get-a-single-gist def gist(gist, options={}) get "gists/#{Gist.new gist}", options end # Create a gist # # @param options [Hash] Gist information. # @option options [String] :description # @option options [Boolean] :public Sets gist visibility # @option options [Array<Hash>] :files Files that make up this gist. Keys # should be the filename, the value a Hash with a :content key with text # content of the Gist. # @return [Hashie::Mash] Newly created gist info # @see http://developer.github.com/v3/gists/#create-a-gist def create_gist(options={}) post 'gists', options end # Edit a gist # # @param options [Hash] Gist information. # @option options [String] :description # @option options [Boolean] :public Sets gist visibility # @option options [Array<Hash>] :files Files that make up this gist. Keys # should be the filename, the value a Hash with a :content key with text # content of the Gist. # # NOTE: All files from the previous version of the # gist are carried over by default if not included in the hash. Deletes # can be performed by including the filename with a null hash. # @return # [Hashie::Mash] Newly created gist info # @see http://developer.github.com/v3/gists/#edit-a-gist def edit_gist(gist, options={}) patch "gists/#{Gist.new gist}", options end # # Star a gist # # @param gist [String] Gist ID # @return [Boolean] Indicates if gist is starred successfully # @see http://developer.github.com/v3/gists/#star-a-gist def star_gist(gist, options={}) boolean_from_response(:put, "gists/#{Gist.new gist}/star", options) end # Unstar a gist # # @param gist [String] Gist ID # @return [Boolean] Indicates if gist is unstarred successfully # @see http://developer.github.com/v3/gists/#unstar-a-gist def unstar_gist(gist, options={}) boolean_from_response(:delete, "gists/#{Gist.new gist}/star", options) end # Check if a gist is starred # # @param gist [String] Gist ID # @return [Boolean] Indicates if gist is starred # @see http://developer.github.com/v3/gists/#check-if-a-gist-is-starred def gist_starred?(gist, options={}) boolean_from_response(:get, "gists/#{Gist.new gist}/star", options) end # Fork a gist # # @param gist [String] Gist ID # @return [Hashie::Mash] Data for the new gist # @see http://developer.github.com/v3/gists/#fork-a-gist def fork_gist(gist, options={}) post "gists/#{Gist.new gist}/forks", options end # Delete a gist # # @param gist [String] Gist ID # @return [Boolean] Indicating success of deletion # @see http://developer.github.com/v3/gists/#delete-a-gist def delete_gist(gist, options={}) boolean_from_response(:delete, "gists/#{Gist.new gist}", options) end # List gist comments # # @param gist_id [String] Gist Id. # @return [Array<Hashie::Mash>] Array of hashes representing comments. # @see http://developer.github.com/v3/gists/comments/#list-comments-on-a-gist # @example # Octokit.gist_comments('3528ae645') def gist_comments(gist_id, options={}) get "gists/#{gist_id}/comments", options end # Get gist comment # # @param gist_id [String] Id of the gist. # @param gist_comment_id [Integer] Id of the gist comment. # @return [Hashie::Mash] Hash representing gist comment. # @see http://developer.github.com/v3/gists/comments/#get-a-single-comment # @example # Octokit.gist_comment('208sdaz3', 1451398) def gist_comment(gist_id, gist_comment_id, options={}) get "gists/#{gist_id}/comments/#{gist_comment_id}", options end # Create gist comment # # Requires authenticated client. # # @param gist_id [String] Id of the gist. # @param comment [String] Comment contents. # @return [Hashie::Mash] Hash representing the new comment. # @see Octokit::Client # @see http://developer.github.com/v3/gists/comments/#create-a-comment # @example # @client.create_gist_comment('3528645', 'This is very helpful.') def create_gist_comment(gist_id, comment, options={}) options.merge!({:body => comment}) post "gists/#{gist_id}/comments", options end # Update gist comment # # Requires authenticated client # # @param gist_id [String] Id of the gist. # @param gist_comment_id [Integer] Id of the gist comment to update. # @param comment [String] Updated comment contents. # @return [Hashie::Mash] Hash representing the updated comment. # @see Octokit::Client # @see http://developer.github.com/v3/gists/comments/#edit-a-comment # @example # @client.update_gist_comment('208sdaz3', '3528645', ':heart:') def update_gist_comment(gist_id, gist_comment_id, comment, options={}) options.merge!({:body => comment}) patch "gists/#{gist_id}/comments/#{gist_comment_id}", options end # Delete gist comment # # Requires authenticated client. # # @param gist_id [String] Id of the gist. # @param gist_comment_id [Integer] Id of the gist comment to delete. # @return [Boolean] True if comment deleted, false otherwise. # @see Octokit::Client # @see http://developer.github.com/v3/gists/comments/#delete-a-comment # @example # @client.delete_gist_comment('208sdaz3', '586399') def delete_gist_comment(gist_id, gist_comment_id, options={}) boolean_from_response(:delete, "gists/#{gist_id}/comments/#{gist_comment_id}", options) end end end end
Java
/** \file * \brief GTK Driver * * See Copyright Notice in "iup.h" */ #ifndef __IUPGTK_DRV_H #define __IUPGTK_DRV_H #ifdef __cplusplus extern "C" { #endif #define iupCOLORDoubleTO8(_x) ((unsigned char)(_x*255)) /* 1.0*255 = 255 */ #define iupCOLOR8ToDouble(_x) ((double)_x/255.0) /* common */ gboolean iupgtkEnterLeaveEvent(GtkWidget *widget, GdkEventCrossing *evt, Ihandle* ih); gboolean iupgtkMotionNotifyEvent(GtkWidget *widget, GdkEventMotion *evt, Ihandle *ih); gboolean iupgtkButtonEvent(GtkWidget *widget, GdkEventButton *evt, Ihandle *ih); gboolean iupgtkShowHelp(GtkWidget *widget, GtkWidgetHelpType *arg1, Ihandle* ih); int iupgtkSetMnemonicTitle(Ihandle* ih, GtkLabel* label, const char* value); void iupgtkUpdateMnemonic(Ihandle* ih); void iupgdkColorSet(GdkColor* color, unsigned char r, unsigned char g, unsigned char b); void iupgtkSetBgColor(InativeHandle* handle, unsigned char r, unsigned char g, unsigned char b); void iupgtkSetFgColor(InativeHandle* handle, unsigned char r, unsigned char g, unsigned char b); void iupgtkAddToParent(Ihandle* ih); const char* iupgtkGetWidgetClassName(GtkWidget* widget); void iupgtkSetPosSize(GtkContainer* parent, GtkWidget* widget, int x, int y, int width, int height); GdkWindow* iupgtkGetWindow(GtkWidget *widget); void iupgtkWindowGetPointer(GdkWindow *window, int *x, int *y, GdkModifierType *mask); int iupgtkIsVisible(GtkWidget* widget); GtkWidget* iupgtkNativeContainerNew(int has_window); void iupgtkNativeContainerAdd(GtkWidget* container, GtkWidget* widget); void iupgtkNativeContainerMove(GtkWidget* container, GtkWidget* widget, int x, int y); /* str */ void iupgtkStrRelease(void); char* iupgtkStrConvertToSystem(const char* str); char* iupgtkStrConvertToSystemLen(const char* str, int *len); char* iupgtkStrConvertFromSystem(const char* str); char* iupgtkStrConvertFromFilename(const char* str); char* iupgtkStrConvertToFilename(const char* str); void iupgtkStrSetUTF8Mode(int utf8mode); int iupgtkStrGetUTF8Mode(void); /* focus */ gboolean iupgtkFocusInOutEvent(GtkWidget *widget, GdkEventFocus *evt, Ihandle* ih); void iupgtkSetCanFocus(GtkWidget *widget, int can); /* key */ gboolean iupgtkKeyPressEvent(GtkWidget *widget, GdkEventKey *evt, Ihandle* ih); gboolean iupgtkKeyReleaseEvent(GtkWidget *widget, GdkEventKey *evt, Ihandle* ih); void iupgtkButtonKeySetStatus(guint state, unsigned int but, char* status, int doubleclick); int iupgtkKeyDecode(GdkEventKey *evt); /* font */ PangoFontDescription* iupgtkGetPangoFontDesc(const char* value); char* iupgtkGetPangoFontDescAttrib(Ihandle *ih); char* iupgtkGetPangoLayoutAttrib(Ihandle *ih); char* iupgtkGetFontIdAttrib(Ihandle *ih); void iupgtkUpdateObjectFont(Ihandle* ih, gpointer object); void iupgtkUpdateWidgetFont(Ihandle *ih, GtkWidget* widget); PangoLayout* iupgtkGetPangoLayout(const char* value); /* There are PANGO_SCALE Pango units in one device unit. For an output backend where a device unit is a pixel, a size value of 10 * PANGO_SCALE gives 10 pixels. */ #define iupGTK_PANGOUNITS2PIXELS(_x) (((_x) + PANGO_SCALE/2) / PANGO_SCALE) #define iupGTK_PIXELS2PANGOUNITS(_x) ((_x) * PANGO_SCALE) /* open */ char* iupgtkGetNativeWindowHandle(Ihandle* ih); void iupgtkPushVisualAndColormap(void* visual, void* colormap); void* iupgtkGetNativeGraphicsContext(GtkWidget* widget); void iupgtkReleaseNativeGraphicsContext(GtkWidget* widget, void* gc); /* dialog */ gboolean iupgtkDialogDeleteEvent(GtkWidget *widget, GdkEvent *evt, Ihandle *ih); #ifdef __cplusplus } #endif #endif
Java
/*body > section > section > section > div > section > div > div.row > div > div*/ fieldset.contact { position: relative; left: 6%; } .input { position: relative; z-index: 1; display: inline-block; margin: 1em; max-width: 350px; width: calc(100% - 2em); vertical-align: top; } .input .title { width: 85%; } .input .title, .input.input-secondary.title { max-width: 100%; width: 92%; } .input.input-secondary.title.input-filled { left: 5%; } .input_field { position: relative; display: block; float: right; padding: 0.8em; width: 60%; border: none; border-radius: 0; background: #f0f0f0; color: #aaa; font-weight: bold; -webkit-appearance: none; /* for box shadows to show on iOS */ } .input_field:focus { outline: none; } .submit-project { left: 13%; position: relative; } .input_label { display: inline-block; float: right; padding: 0 1em; width: 40%; color: #6a7989; font-weight: bold; font-size: 70.25%; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .input_label-content { position: relative; display: block; padding: 1.6em 0; width: 100%; } .graphic { position: absolute; top: 0; left: 0; fill: none; } .icon { color: #ddd; font-size: 150%; } .input-secondary { margin: 0.75rem 0 0 1.4rem; } .input_field-secondary { width: 100%; background: transparent; padding: 1.3rem 0 0 0; margin-bottom: 2em; color: #006400; font-size: 1.5em; } textarea.input_field-secondary { left: 2%; height: 50px; background: transparent; padding: 0.3em 0 0 0.3rem; margin-bottom: 2em; border: #023A31 solid 3px; } textarea.input_field-secondary::before { content: 'Talk to us!'; position: absolute; } textarea.input_field-secondary::after { width: 100%; height: 7px; content: 'Talk to us!'; position: absolute; left: 0; top: 100%; } textarea.input_field-secondary:active { } .contact-form textarea { width: 96%; height: 120px; padding: 1.5%; background-color: transparent; margin: 1% 0 0 1.4rem; border: 0.1rem solid #023A31; border-bottom: 1rem solid #023A31; color: darkgreen; font-size: 1.75rem; font-weight: 600; /*line-height: ;*/ -webkit-transition: -webkit-transform 0.3s, all 1s; transition: transform 0.3s, all 1s; } .contact-form textarea.ng-valid.ng-dirty:active, .contact-form textarea.ng-valid.ng-dirty:focus { border-top: #78FA89; border-right: #78FA89; border-left: #78FA89; border-bottom: 0.25rem solid #023A31; } .contact-form textarea:focus, .contact-form textarea:active { border-bottom: none; -webkit-transform-origin: 0 0; transform-origin: 0 0; -webkit-transition: -webkit-transform 0.3s, all 1s; transition: transform 0.3s, all 1s; } .input_label-secondary { width: 100%; position: absolute; text-align: left; font-size: 1em; padding: 10px 0 5px; pointer-events: none; } .input_label-secondary::after { content: ''; position: absolute; width: 100%; height: 7px; background: #023A31; left: 0; top: 100%; -webkit-transform-origin: 50% 100%; transform-origin: 50% 100%; -webkit-transition: -webkit-transform 0.3s, background-color 0.3s; transition: transform 0.3s, background-color 0.3s; } .input_label-content-secondary { padding: 0; -webkit-transform-origin: 0 0; transform-origin: 0 0; -webkit-transition: -webkit-transform 0.3s, color 0.3s; transition: transform 0.3s, color 0.3s; } .input_field-secondary:focus + .input_label-secondary::after, .input-filled .input_label-secondary::after { background: #006400; -webkit-transform: scale3d(1.25, 0.25, 1); transform: scale3d(1.25, 0.25, 1); } .input_field-secondary:focus + .input_label-secondary .input_label-content-secondary, .input-filled .input_label-secondary .input_label-content-secondary { color: #006400; -webkit-transform: translateY(3.0em) scale3d(0.955, 0.955, 1.5); transform: translateY(3.0em) scale3d(0.955, 0.955, 1.5); } span.input.input-secondary .title { max-width: 100%; } .input_label.input_label-secondary .title { /*left: 10%;*/ } .grow.btn-contact { position: relative; left: 2%; margin-top: 3%; } .grow.btn-contact:hover { background: rgba(240, 240, 240, 0.8); border-color: #023a31; color: #023a31; -webkit-transition: -webkit-transform 0.3s, all 0.5s; transition: transform 0.3s, all 0.5s; } .tab-pane { padding: 4%; }
Java
require( [ 'gui/Button' ], function (Button) { return; var button = new Button({ main: $('#ui-button') }); button.render(); } );
Java
source $setup tar -xf $src mkdir build cd build ../libsigsegv-$version/configure \ --host=$host \ --prefix=$out \ --enable-static=yes \ --enable-shared=no make make install
Java
--- title: Open source + periodismo&#58 vía rápida a la innovación (1) categories: [ Analisis, Innovación ] layout: post cover_image: srcc.png excerpt: Asistimos a una eclosión de proyectos periodísticos que se han beneficiado de lenguajes de programación, librerías y aplicaciones de software desarrolladas con esa filosofía. Como contraprestación, los medios más innovadores de todo el mundo liberan el código de sus proyectos, arquitecturas y aplicaciones web. Este es un repaso seriado a las principales aportaciones del binomio open source y periodismo. author: name: Miguel Carvajal twitter: mcarvajal_ gplus: '105651624538664882557' bio: Director del Máster image: yo.png link: https://twitter.com/mcarvajal_ --- El open source ha encontrado en el periodismo un terreno propicio para expandirse y generar proyectos muy atractivos. En estos tiempos de declive del modelo de prensa industrial, casi **a diario se abre un nuevo reto tecnológico que zarandea los viejos presupuestos económicos** y empresariales que han permitido financiar el periodismo. ¿Qué puede aportar el open source? Mucho. Asistimos a una **eclosión de proyectos periodísticos que se han beneficiado de lenguajes de programación, librerías y aplicaciones de software desarrolladas con esa filosofía**. Como contraprestación, **los medios más innovadores liberan el código de algunos proyectos, arquitecturas y aplicaciones web**. Este es un repaso seriado de las principales frutos del binomio open source y periodismo. ![](https://dl.dropboxusercontent.com/u/3578704/shots/shot_2015-06-25_00-12-11.png) El open source (_código abierto_ en español) es un fenómeno complejo con múltiples aristas, con sus propios filósofos y su frente de activistas en universidades, instituciones y, por supuesto, internets paralelos. **El open source es una cultura participativa, una filosofía de trabajo abierto y documentado**, que tiene como epicentro el propio código fuente. También es una **defensa del conocimiento gratuito y universal**, una espoleta **contra las grandes industrias del software privativo** y **es la constatación de que muchos trabajan más y mejor que unos pocos**. Y todo eso sin consultar qué dice Wikipedia, precisamente, un símbolo de esta cultura. Hay cientos de proyectos de software nacidos [bajo el paraguas del open source](https://es.wikipedia.org/wiki/C%C3%B3digo_abierto) de los que nos estamos beneficiando ahora. Ese virus se inoculó en el sistema del periodismo a través de la tribu de programadores y desarrolladores web. En 2009, un grupo de periodistas (hacks) y escritores de código (hackers) decidió fundar **una red para intercambiar experiencias y conocimientos sobre el futuro del periodismo**. Bajo el lema "reiniciando el periodismo", la cultura [Hacks&Hackers](http://hackshackers.com/) se expandió por las principales ciudadades de todo el mundo, como Madrid (2011) que contó con un gran aliado en el entorno creativo del [Medialab Prado](http://medialab-prado.es/). El fenómeno Hacks&Hackers **contagió a los más innovadores de las principales redacciones**, como el **New York Times**, el **Guardian** o la radio pública **NPR**. La cultura open source entró de forma definitiva en el periodismo cuando [Mozilla y la Fundación Knight crearon Open News](http://opennews.org/) con el fin de "apoyar la creciente comunidad de programadores, desarrolladores, diseñadores y periodistas de datos **que ayudan al periodismo a prosperar en internet**". Precisamente, [estos días se celebra en Minneapolis la segunda edición de la Source Conference (SRCCON)](http://srccon.org/), que congrega a programadores de los proyectos periodísticos más punteros del mundo. En la intersección entre la tecnología y el periodismo han surgido algunas de las principales startups periodísticas y la mayor parte de los grandes proyectos de periodismo de datos. [ProPublica](https://www.propublica.org/) (Pulitzer en 2010), [Buzzfeed](https://www.buzzfeed.com) (en camino de convertirse el modelo de organización mediática del siglo XXI), [Vox Media](https://voxmedia.com), [Gawker](http://gawker.com/), **Hufftington Post**, [FiveThirtyEight](http://fivethirtyeight.com/)... El mix periodismo y _tech world_ ha impulsado también el nacimiento de laboratorios de innovación en medios de todo el mundo: **New York Times**, **Guardian**, **Chicago Tribune**, **Bloomberg**, **Finantial Times**. En España, esta cultura ha encontrado un buen caldo de cultivo en la [Fundación Civio](http://www.civio.es/), un genial mix de programadores y periodistas, y ahora en [El Confidencial](http://www.elconfidencial.com/), [eldiario.es](http://www.eldiario.es/), [DNLab](http://laboratorio.diariodenavarra.es/hsf/) y, por lo que apuntan, [El Español](http://espanaencifras.elespanol.com/). Sin duda, la aparición de _hackatones_ en diarios tradicionales es la punta del iceberg de este movimiento. El _adn_ del open source está en los programadores (defensores o simples usuarios) de las organizaciones periodísticas más innovadores de todo el mundo. **Ellos crean y diseñan aplicaciones y sitios web** con lenguajes como _ruby on rails_ o _php_. Los **periodistas trabajan con herramientas gratuitas para extraer y filtrar datos o para presentarlos en mapas**. Hay _coders_ que escriben programas en _python_ que se ejecutan desde su terminal para _scrapear_ la web (navegarla y obtener datos útiles y relevantes). A diario **los desarrolladores emplean librerías de _javascript_, _html_ y _css_ gratuitas para diseñar las webs o las aplicaciones o de sus medios**. El open source no solo debe aportar al periodismo herramientas gratuitas (lenguajes y aplicaciones), puede ayudar a transmitir una cultura _pirata_, [como plantea Pau Llop](http://www.eldiario.es/colaboratorio/Periodismo-pirata_6_109249075.html), y "conquistar nuevos territorios para la democracia y una organización social más justa". [Seth Lewis y Nikki Usher señalan que el periodismo](http://mcs.sagepub.com/content/35/5/602.abstract) podría beneficiarse del ethos del open source de cuatro modos: * La **transparencia** para abrir el proceso de trabajo desde el inicio y estar dispuestos a someterse al control, mediante cambios documentados y con la voluntad de resolver vicios y errores de la producción periodística. * La **repetición** o estado beta constante que anima a trabajar desde la necesidad permanente de mejora, abierta a la comunidad, y que también garantiza la libertad de equivocarse. * La **experimentación** constante para abrir, desmenuzar e innovar con cada parte o elemento del proceso periodístico. La capacidad de construir de forma colaborativa para buscar la virtud en el proceso, más que en un resultado final. * La **participación** de diversos colaboradores, actores implicados en el proceso, tanto fuentes como audiencia, expertos y programadores, para facilitar un control efectivo del proceso periodístico. La tribu open source también tiene publicaciones, licencias abiertas, redes sociales. Una gran mayoría de estos proyectos están alojados en [Github](https://github.com/), una plataforma de servicios para programadores y desarrolladores web que **permite almacenar gratuitamente repositorios de código y facilita el trabajo colaborativo** porque funciona con el sistema de control de versiones [_git_](https://git-scm.com/). Esto que escribo quizá está ya en _la frontera de matrix_ para un periodista medio. Solo como detalle: [el blog está alojado en Github](https://github.com/mipumh/blog) y se sostiene por el módulo (gema) _jekyll_ escrito en el lenguaje _ruby_. Lo que ves ahora no tiene detrás el popular CMS (_content management system_) de **Wordpress** (otro proyecto open source, por cierto). En Github se encuentran los principales frutos del binomio open source y periodismo: aplicaciones, herramientas y programas gratuitos que pueden servir para mejorar la producción o el aspecto de cualquier proyecto periodístico. Todos ellos se desgranarán próximamente en [este blog](http://mip.umh.es/blog/ "Web inicial de este proyecto").
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Future</title> <link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../thread.html" title="Chapter 40. Thread 4.8.0"> <link rel="prev" href="changes.html" title="History"> <link rel="next" href="thread_management.html" title="Thread Management"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td> <td align="center"><a href="../../../index.html">Home</a></td> <td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="changes.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../thread.html"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="thread_management.html"><img src="../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h2 class="title" style="clear: both"> <a name="thread.future"></a><a class="link" href="future.html" title="Future">Future</a> </h2></div></div></div> <p> The following features will be included in next releases. </p> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"> Add some minor features, in particular <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"> <a href="http://svn.boost.org/trac/boost/ticket/7589" target="_top">#7589</a> Synchro: Add polymorphic lockables. </li></ul></div> </li> <li class="listitem"> Add some features based on C++ proposals, in particular <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> <a href="http://svn.boost.org/trac/boost/ticket/8273" target="_top">#8273</a> Synchro: Add externally locked streams. </li> <li class="listitem"> <a href="http://svn.boost.org/trac/boost/ticket/8514" target="_top">#8514</a> Async: Add a thread_pool executor with work stealing. </li> </ul></div> </li> <li class="listitem"> And some additional extensions related to futures as: <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"> <a href="http://svn.boost.org/trac/boost/ticket/8517" target="_top">#8517</a> Async: Add a variadic shared_future::then. </li></ul></div> </li> </ol></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2007 -11 Anthony Williams<br>Copyright © 2011 -17 Vicente J. Botet Escriba<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="changes.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../thread.html"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="thread_management.html"><img src="../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AsanaNet { [Serializable] public class AsanaTeam : AsanaObject, IAsanaData { [AsanaDataAttribute("name")] public string Name { get; private set; } // ------------------------------------------------------ public bool IsObjectLocal { get { return true; } } public void Complete() { throw new NotImplementedException(); } static public implicit operator AsanaTeam(Int64 ID) { return Create(typeof(AsanaTeam), ID) as AsanaTeam; } } }
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MultiplicationSign")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MultiplicationSign")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("16b9c3ba-c518-4e36-93c4-969cc63ec2bc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sr" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Fuguecoin</source> <translation>О Fuguecoin-у</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Fuguecoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Fuguecoin&lt;/b&gt; верзија</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Fuguecoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Адресар</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Кликните два пута да промените адресу и/или етикету</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Прави нову адресу</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копира изабрану адресу на системски клипборд</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Нова адреса</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Fuguecoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ово су Ваше Fuguecoin адресе за примање уплата. Можете да сваком пошиљаоцу дате другачију адресу да би пратили ко је вршио уплате.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Prikaži &amp;QR kod</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Fuguecoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Fuguecoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Избриши</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Fuguecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Извоз података из адресара</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Зарезом одвојене вредности (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Грешка током извоза</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Није могуће писати у фајл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Етикета</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(без етикете)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Унесите лозинку</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Нова лозинка</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Поновите нову лозинку</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Унесите нову лозинку за приступ новчанику.&lt;br/&gt;Молимо Вас да лозинка буде &lt;b&gt;10 или више насумице одабраних знакова&lt;/b&gt;, или &lt;b&gt;осам или више речи&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Шифровање новчаника</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ова акција захтева лозинку Вашег новчаника да би га откључала.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Откључавање новчаника</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ова акција захтева да унесете лозинку да би дешифловала новчаник.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Дешифровање новчаника</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Промена лозинке</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Унесите стару и нову лозинку за шифровање новчаника.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Одобрите шифровање новчаника</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>Упозорење: Ако се ваш новчаник шифрује а потом изгубите лозинкзу, ви ћете &lt;b&gt;ИЗГУБИТИ СВЕ BITCOIN-Е&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Да ли сте сигурни да желите да се новчаник шифује?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Новчаник је шифрован</translation> </message> <message> <location line="-56"/> <source>Fuguecoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation>Fuguecoin će se sad zatvoriti da bi završio proces enkripcije. Zapamti da enkripcija tvog novčanika ne može u potpunosti da zaštiti tvoje bitcoine da ne budu ukradeni od malawarea koji bi inficirao tvoj kompjuter.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Неуспело шифровање новчаника</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Настала је унутрашња грешка током шифровања новчаника. Ваш новчаник није шифрован.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Лозинке које сте унели се не подударају.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Неуспело откључавање новчаника</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Лозинка коју сте унели за откључавање новчаника је нетачна.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Неуспело дешифровање новчаника</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Лозинка за приступ новчанику је успешно промењена.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронизација са мрежом у току...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Општи преглед</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Погледајте општи преглед новчаника</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Трансакције</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Претражите историјат трансакција</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Уредите запамћене адресе и њихове етикете</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Прегледајте листу адреса на којима прихватате уплате</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>I&amp;zlaz</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Напустите програм</translation> </message> <message> <location line="+4"/> <source>Show information about Fuguecoin</source> <translation>Прегледајте информације о Fuguecoin-у</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>О &amp;Qt-у</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Прегледајте информације о Qt-у</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>П&amp;оставке...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Шифровање новчаника...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup новчаника</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Промени &amp;лозинку...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Fuguecoin address</source> <translation>Пошаљите новац на bitcoin адресу</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Fuguecoin</source> <translation>Изаберите могућности bitcoin-а</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Мењање лозинке којом се шифрује новчаник</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>Fuguecoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>новчаник</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Fuguecoin</source> <translation>&amp;О Fuguecoin-у</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Fuguecoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Fuguecoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Фајл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Подешавања</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>П&amp;омоћ</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Трака са картицама</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Fuguecoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Fuguecoin network</source> <translation><numerusform>%n активна веза са Fuguecoin мрежом</numerusform><numerusform>%n активне везе са Fuguecoin мрежом</numerusform><numerusform>%n активних веза са Fuguecoin мрежом</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ажурно</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Ажурирање у току...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Послана трансакција</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Придошла трансакција</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1⏎ Iznos: %2⏎ Tip: %3⏎ Adresa: %4⏎</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Fuguecoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Новчаник јс &lt;b&gt;шифрован&lt;/b&gt; и тренутно &lt;b&gt;откључан&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Новчаник јс &lt;b&gt;шифрован&lt;/b&gt; и тренутно &lt;b&gt;закључан&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Fuguecoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Измени адресу</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адреса</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Унешена адреса &quot;%1&quot; се већ налази у адресару.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Fuguecoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Немогуће откључати новчаник.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Fuguecoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation>верзија</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Korišćenje:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Поставке</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Fuguecoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Fuguecoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Fuguecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Fuguecoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Fuguecoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Јединица за приказивање износа:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Fuguecoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Fuguecoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Fuguecoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Непотврђено:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>новчаник</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Недавне трансакције&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start bitcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Zatraži isplatu</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Poruka:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Snimi kao...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Fuguecoin-Qt help message to get a list with possible Fuguecoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Fuguecoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Fuguecoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Fuguecoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Fuguecoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Слање новца</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Ukloni sva polja sa transakcijama</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Потврди акцију слања</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Пошаљи</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Да ли сте сигурни да желите да пошаљете %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>и</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Izaberite adresu iz adresara</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Fuguecoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Unesite Fuguecoin adresu (n.pr. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Fuguecoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Fuguecoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Fuguecoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Unesite Fuguecoin adresu (n.pr. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Fuguecoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Fuguecoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otvorite do %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrdjeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrde</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>етикета</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>iznos</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, nije još uvek uspešno emitovan</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nepoznato</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>detalji transakcije</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ovaj odeljak pokazuje detaljan opis transakcije</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>tip</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>iznos</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otvoreno do %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline * van mreže (%1 potvrdjenih)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrdjeno (%1 of %2 potvrdjenih)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrdjena (%1 potvrdjenih)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ovaj blok nije primljen od ostalih čvorova (nodova) i verovatno neće biti prihvaćen!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generisan ali nije prihvaćen</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Primljen sa</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primljeno od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Poslat ka</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Isplata samom sebi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minirano</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status vaše transakcije. Predjite mišem preko ovog polja da bi ste videli broj konfirmacija</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum i vreme primljene transakcije.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tip transakcije</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Destinacija i adresa transakcije</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Iznos odbijen ili dodat balansu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>ove nedelje</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovog meseca</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošlog meseca</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Opseg...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Primljen sa</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Poslat ka</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Vama - samom sebi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minirano</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Drugi</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Navedite adresu ili naziv koji bi ste potražili</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min iznos</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>kopiraj adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>kopiraj naziv</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>kopiraj iznos</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>promeni naziv</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Izvezi podatke o transakcijama</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Зарезом одвојене вредности (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrdjen</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>tip</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Етикета</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>iznos</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Грешка током извоза</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Није могуће писати у фајл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Opseg:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>do</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Слање новца</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Fuguecoin version</source> <translation>Fuguecoin верзија</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Korišćenje:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or bitcoind</source> <translation>Pošalji naredbu na -server ili bitcoinid </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listaj komande</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Zatraži pomoć za komande</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opcije</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>Potvrdi željeni konfiguracioni fajl (podrazumevani:bitcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>Konkretizuj pid fajl (podrazumevani: bitcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Gde je konkretni data direktorijum </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Slušaj konekcije na &lt;port&gt; (default: 8333 or testnet: 18333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Održavaj najviše &lt;n&gt; konekcija po priključku (default: 125) </translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Prihvati komandnu liniju i JSON-RPC komande</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Radi u pozadini kao daemon servis i prihvati komande</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Koristi testnu mrežu</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Fuguecoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Fuguecoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Fuguecoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the Fuguecoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Korisničko ime za JSON-RPC konekcije</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Lozinka za JSON-RPC konekcije</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Dozvoli JSON-RPC konekcije sa posebne IP adrese</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Pošalji komande to nodu koji radi na &lt;ip&gt; (default: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Odredi veličinu zaštićenih ključeva na &lt;n&gt; (default: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ponovo skeniraj lanac blokova za nedostajuće transakcije iz novčanika</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Koristi OpenSSL (https) za JSON-RPC konekcije</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>privatni ključ za Server (podrazumevan: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Prihvatljive cifre (podrazumevano: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Ova poruka Pomoći</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>učitavam adrese....</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Fuguecoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Fuguecoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Učitavam blok indeksa...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Fuguecoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Новчаник се учитава...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Ponovo skeniram...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Završeno učitavanje</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
Java
load File.dirname(__FILE__) + '/production.rb' if File.exists? File.dirname(__FILE__) + '/../application.local.rb' require File.dirname(__FILE__) + '/../application.local.rb' end
Java
from typing import Dict import tempfile from dxlclient.client_config import DxlClientConfig from dxlclient.client import DxlClient from dxlclient.broker import Broker from dxlclient.message import Event import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * INTEGRATION_NAME = "McAfee DXL" CONNECT_RETRIES = 1 RECONNECT_DELAY = 1 RECONNECT_DELAY_MAX = 10 class EventSender: TRUST_LEVEL = { 'NOT_SET': '0', 'KNOWN_MALICIOUS': '1', 'MOST_LIKELY_MALICIOUS': '15', 'MIGHT_BE_MALICIOUS': '30', 'UNKNOWN': '50', 'MIGHT_BE_TRUSTED': '70', 'MOST_LIKELY_TRUSTED': '85', 'KNOWN_TRUSTED': '99', 'KNOWN_TRUSTED_INSTALLER': '100' } broker_ca_bundle = tempfile.NamedTemporaryFile().name cert_file = tempfile.NamedTemporaryFile().name private_key = tempfile.NamedTemporaryFile().name def __init__(self, params: Dict): with open(self.broker_ca_bundle, "w") as text_file: text_file.write(params['broker_ca_bundle']) with open(self.cert_file, "w") as text_file: text_file.write(params['cert_file']) with open(self.private_key, "w") as text_file: text_file.write(params['private_key']) if 'broker_urls' in params: self.broker_urls = params['broker_urls'].split(',') self.push_ip_topic = params.get('push_ip_topic') self.push_url_topic = params.get('push_url_topic') self.push_domain_topic = params.get('push_domain_topic') self.push_hash_topic = params.get('push_hash_topic') self.client = DxlClient(self.get_client_config()) self.client.connect() def __del__(self): self.client.disconnect() def push_ip(self, ip, trust_level, topic): if not is_ip_valid(ip): raise ValueError(f'argument ip {ip} is not a valid IP') trust_level_key = self.TRUST_LEVEL[trust_level] if topic: self.push_ip_topic = topic self.send_event(self.push_ip_topic, f'ip:{ip};trust_level:{trust_level_key}') return f'Successfully pushed ip {ip} with trust level {trust_level}' def push_url(self, url, trust_level, topic): trust_level_key = self.TRUST_LEVEL[trust_level] if topic: self.push_url_topic = topic self.send_event(self.push_url_topic, f'url:{url};trust_level:{trust_level_key}') return f'Successfully pushed url {url} with trust level {trust_level}' def push_domain(self, domain, trust_level, topic): trust_level_key = self.TRUST_LEVEL[trust_level] if topic: self.push_domain_topic = topic self.send_event(self.push_domain_topic, f'domain:{domain};trust_level:{trust_level_key}') return f'Successfully pushed domain {domain} with trust level {trust_level}' def push_hash(self, hash_obj, trust_level, topic): trust_level_key = self.TRUST_LEVEL[trust_level] if topic: self.push_ip_topic = topic self.send_event(self.push_hash_topic, f'hash:{hash_obj};trust_level:{trust_level_key}') return f'Successfully pushed hash {hash_obj} with trust level {trust_level}' def get_client_config(self): config = DxlClientConfig( broker_ca_bundle=self.broker_ca_bundle, cert_file=self.cert_file, private_key=self.private_key, brokers=[Broker.parse(url) for url in self.broker_urls] ) config.connect_retries = CONNECT_RETRIES config.reconnect_delay = RECONNECT_DELAY config.reconnect_delay_max = RECONNECT_DELAY_MAX return config def send_event(self, topic, payload): if not topic: raise Exception(f'Error in {demisto.command()} topic field is required') event = Event(topic) event.payload = str(payload).encode() self.client.send_event(event) def send_event_wrapper(self, topic, payload): self.send_event(topic, payload) return 'Successfully sent event' def validate_certificates_format(): if '-----BEGIN PRIVATE KEY-----' not in demisto.params()['private_key']: return_error( "The private key content seems to be incorrect as it doesn't start with -----BEGIN PRIVATE KEY-----") if '-----END PRIVATE KEY-----' not in demisto.params()['private_key']: return_error( "The private key content seems to be incorrect as it doesn't end with -----END PRIVATE KEY-----") if '-----BEGIN CERTIFICATE-----' not in demisto.params()['cert_file']: return_error("The client certificates content seem to be " "incorrect as they don't start with '-----BEGIN CERTIFICATE-----'") if '-----END CERTIFICATE-----' not in demisto.params()['cert_file']: return_error( "The client certificates content seem to be incorrect as it doesn't end with -----END CERTIFICATE-----") if not demisto.params()['broker_ca_bundle'].lstrip(" ").startswith('-----BEGIN CERTIFICATE-----'): return_error( "The broker certificate seem to be incorrect as they don't start with '-----BEGIN CERTIFICATE-----'") if not demisto.params()['broker_ca_bundle'].rstrip(" ").endswith('-----END CERTIFICATE-----'): return_error( "The broker certificate seem to be incorrect as they don't end with '-----END CERTIFICATE-----'") def main(): args = demisto.args() command = demisto.command() try: event_sender = EventSender(demisto.params()) result = '' if command == 'test-module': event_sender.send_event('TEST', 'test') result = 'ok' elif command == 'dxl-send-event': result = event_sender.send_event_wrapper(args.get('topic'), args.get('payload')) elif command == 'dxl-push-ip': result = event_sender.push_ip(args.get('ip'), args.get('trust_level'), args.get('topic')) elif command == 'dxl-push-url': result = event_sender.push_url(args.get('url'), args.get('trust_level'), args.get('topic')) elif command == 'dxl-push-domain': result = event_sender.push_domain(args.get('domain'), args.get('trust_level'), args.get('topic')) elif command == 'dxl-push-hash': result = event_sender.push_hash(args.get('hash'), args.get('trust_level'), args.get('topic')) else: raise Exception(f'{demisto.command()} is not a command') return_outputs(result) except Exception as error: validate_certificates_format() return_error(f'error in {INTEGRATION_NAME} {str(error)}.', error) if __name__ in ('__builtin__', 'builtins'): main()
Java
using System; using System.Collections; using System.Collections.Generic; using System.Web.Http; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using UtilJsonApiSerializer.Serialization; namespace UtilJsonApiSerializer { public class Configuration { private readonly Dictionary<string, IResourceMapping> resourcesMappingsByResourceType = new Dictionary<string, IResourceMapping>(); private readonly Dictionary<Type, IResourceMapping> resourcesMappingsByType = new Dictionary<Type, IResourceMapping>(); private readonly Dictionary<Type, IPreSerializerPipelineModule> _preSerializerPipelineModules = new Dictionary<Type, IPreSerializerPipelineModule>(); public void AddMapping(IResourceMapping resourceMapping) { resourcesMappingsByResourceType[resourceMapping.ResourceType] = resourceMapping; resourcesMappingsByType[resourceMapping.ResourceRepresentationType] = resourceMapping; } public bool IsMappingRegistered(Type type) { if (typeof(IEnumerable).IsAssignableFrom(type) && type.IsGenericType) { return resourcesMappingsByType.ContainsKey(type.GetGenericArguments()[0]); } return resourcesMappingsByType.ContainsKey(type); } public IResourceMapping GetMapping(Type type) { IResourceMapping mapping; resourcesMappingsByType.TryGetValue(type, out mapping); return mapping; } public IPreSerializerPipelineModule GetPreSerializerPipelineModule(Type type) { _preSerializerPipelineModules.TryGetValue(type, out var preSerializerPipelineModule); return preSerializerPipelineModule; } public void Apply(HttpConfiguration configuration) { var serializer = GetJsonSerializer(); var helper = new TransformationHelper(); var transformer = new JsonApiTransformer { Serializer = serializer, TransformationHelper = helper }; var filter = new JsonApiActionFilter(transformer, this); configuration.Filters.Add(filter); var formatter = new JsonApiFormatter(this, serializer); configuration.Formatters.Add(formatter); } private static JsonSerializer GetJsonSerializer() { var serializerSettings = new JsonSerializerSettings(); serializerSettings.ContractResolver= new CamelCasePropertyNamesContractResolver(); serializerSettings.Converters.Add(new IsoDateTimeConverter()); serializerSettings.Converters.Add(new StringEnumConverter() { CamelCaseText = true}); #if DEBUG serializerSettings.Formatting = Formatting.Indented; #endif var jsonSerializer = JsonSerializer.Create(serializerSettings); return jsonSerializer; } public void AddPreSerializationModule(Type type, IPreSerializerPipelineModule preSerializerPipelineModule) { _preSerializerPipelineModules.Add(type, preSerializerPipelineModule); } } }
Java
module SlotMachine # A Slot defines a slot in a slotted. A bit like a variable name but for objects. # # PS: for the interested: A "development" of Smalltalk was the # prototype based language (read: JavaScript equivalent) # called Self https://en.wikipedia.org/wiki/Self_(programming_language) # # Slots are the instance names of objects. But since the language is dynamic # what is it that we can say about instance names at runtime? # Start with a Slotted, like the Message (in register one), we know all it's # variables. But there is a Message in there, and for that we know the instances # too. And off course for _all_ objects we know where the type is. # # The definiion is an array of symbols that we can resolve to SlotLoad # Instructions. Or in the case of constants to ConstantLoad # class Slot attr_reader :name , :next_slot # initialize with just the name of the slot. Add more to the chain with set_next def initialize( name ) raise "No name" unless name @name = name end #set the next_slot , but always at the end of the chain def set_next(slot) if(@next_slot) @next_slot.set_next(slot) else @next_slot = slot end end # return the length of chain, ie 1 plus however many more next_slots there are def length return 1 unless @next_slot 1 + @next_slot.length end # name of all the slots, with dot syntax def to_s names = name.to_s names += ".#{@next_slot}" if @next_slot names end end end
Java
--- order: 0 title: 基本用法 --- 简单的步骤条。 ````jsx import { Steps } from 'antd'; const Step = Steps.Step; ReactDOM.render( <Steps current={1}> <Step title="已完成" description="这里是多信息的描述" /> <Step title="进行中" description="这里是多信息的描述" /> <Step title="待运行" description="这里是多信息的描述" /> <Step title="待运行" description="这里是多信息的描述" /> </Steps> , mountNode); ````
Java
var GUID = (function () { function _GUID() { return UUIDcreatePart(4) + UUIDcreatePart(2) + UUIDcreatePart(2) + UUIDcreatePart(2) + UUIDcreatePart(6); }; function UUIDcreatePart(length) { var uuidpart = ""; for (var i = 0; i < length; i++) { var uuidchar = parseInt((Math.random() * 256), 10).toString(16); if (uuidchar.length == 1) { uuidchar = "0" + uuidchar; } uuidpart += uuidchar; } return uuidpart; } return { newGuid: _GUID }; })(); var dataSource = (function () { var tablesStorageKey = "60AE0285-40EE-4A2D-BA5F-F75D601593DD"; var globalData = []; var tables = [ { Id: 5, Name: "Contact", Schema: [ { k: "name", t: 1 }, { k: "companyname", t: 1 }, { k: "position", t: 1 } ], Created: "2016-08-12T07:32:46.69" }, { Id: 6, Name: "Profile", Schema: [ { k: "Name", t: 1 }, { k: "Age", t: 2 }, { k: "Gender", t: 4 }, { k: "Rating", t: 3 }, { k: "Created", t: 5 } ], Created: "2016-09-28T21:53:40.19" } ]; function _loadData(){ globalData = JSON.parse(localStorage[tablesStorageKey] || "[]"); } function _save() { localStorage[tablesStorageKey] = JSON.stringify(globalData); } function _getSchema(tableId) { for (var t = 0; t < tables.length; t++) if (tableId === tables[t].Id) return tables[t].Schema; } function _find(data) { var skip = data.start; var take = data.length; return { draw: data.draw, recordsTotal: globalData.length, recordsFiltered: globalData.length, data: globalData.slice(skip, take + skip) }; } function _insert(data) { var id = GUID.newGuid(); globalData.push([id, data.Name, data.Age, data.Gender, data.Rating, data.Created]); _save() return { IsOk: true, id: id }; } function _update(data) { for (var t = 0; t < globalData.length; t++) if (data._id === globalData[t][0]) { globalData[t] = [data._id, data.Name, data.Age, data.Gender, data.Rating, data.Created]; _save() return { IsOk: true }; } return { IsOk: false }; } function _delete(id) { for (var t = 0; t < globalData.length; t++) if (id === globalData[t][0]) { globalData = globalData.filter(item => item !== globalData[t]); _save(); return { IsOk: true }; } return { IsOk: false }; } _loadData(); return { getSchema: _getSchema, find: _find, insert: _insert, update: _update, delete: _delete }; })();
Java
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\log; use Yii; use yii\base\Component; /** * Logger records logged messages in memory and sends them to different targets if [[dispatcher]] is set. * * A Logger instance can be accessed via `Yii::getLogger()`. You can call the method [[log()]] to record a single log message. * For convenience, a set of shortcut methods are provided for logging messages of various severity levels * via the [[Yii]] class: * * - [[Yii::trace()]] * - [[Yii::error()]] * - [[Yii::warning()]] * - [[Yii::info()]] * - [[Yii::beginProfile()]] * - [[Yii::endProfile()]] * * For more details and usage information on Logger, see the [guide article on logging](guide:runtime-logging). * * When the application ends or [[flushInterval]] is reached, Logger will call [[flush()]] * to send logged messages to different log targets, such as [[FileTarget|file]], [[EmailTarget|email]], * or [[DbTarget|database]], with the help of the [[dispatcher]]. * * @property-read array $dbProfiling The first element indicates the number of SQL statements executed, and * the second element the total time spent in SQL execution. This property is read-only. * @property-read float $elapsedTime The total elapsed time in seconds for current request. This property is * read-only. * @property-read array $profiling The profiling results. Each element is an array consisting of these * elements: `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`. The `memory` * and `memoryDiff` values are available since version 2.0.11. This property is read-only. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class Logger extends Component { /** * Error message level. An error message is one that indicates the abnormal termination of the * application and may require developer's handling. */ const LEVEL_ERROR = 0x01; /** * Warning message level. A warning message is one that indicates some abnormal happens but * the application is able to continue to run. Developers should pay attention to this message. */ const LEVEL_WARNING = 0x02; /** * Informational message level. An informational message is one that includes certain information * for developers to review. */ const LEVEL_INFO = 0x04; /** * Tracing message level. An tracing message is one that reveals the code execution flow. */ const LEVEL_TRACE = 0x08; /** * Profiling message level. This indicates the message is for profiling purpose. */ const LEVEL_PROFILE = 0x40; /** * Profiling message level. This indicates the message is for profiling purpose. It marks the * beginning of a profiling block. */ const LEVEL_PROFILE_BEGIN = 0x50; /** * Profiling message level. This indicates the message is for profiling purpose. It marks the * end of a profiling block. */ const LEVEL_PROFILE_END = 0x60; /** * @var array logged messages. This property is managed by [[log()]] and [[flush()]]. * Each log message is of the following structure: * * ``` * [ * [0] => message (mixed, can be a string or some complex data, such as an exception object) * [1] => level (integer) * [2] => category (string) * [3] => timestamp (float, obtained by microtime(true)) * [4] => traces (array, debug backtrace, contains the application code call stacks) * [5] => memory usage in bytes (int, obtained by memory_get_usage()), available since version 2.0.11. * ] * ``` */ public $messages = []; /** * @var int how many messages should be logged before they are flushed from memory and sent to targets. * Defaults to 1000, meaning the [[flush]] method will be invoked once every 1000 messages logged. * Set this property to be 0 if you don't want to flush messages until the application terminates. * This property mainly affects how much memory will be taken by the logged messages. * A smaller value means less memory, but will increase the execution time due to the overhead of [[flush()]]. */ public $flushInterval = 1000; /** * @var int how much call stack information (file name and line number) should be logged for each message. * If it is greater than 0, at most that number of call stacks will be logged. Note that only application * call stacks are counted. */ public $traceLevel = 0; /** * @var Dispatcher the message dispatcher */ public $dispatcher; /** * Initializes the logger by registering [[flush()]] as a shutdown function. */ public function init() { parent::init(); register_shutdown_function(function () { // make regular flush before other shutdown functions, which allows session data collection and so on $this->flush(); // make sure log entries written by shutdown functions are also flushed // ensure "flush()" is called last when there are multiple shutdown functions register_shutdown_function([$this, 'flush'], true); }); } /** * Logs a message with the given type and category. * If [[traceLevel]] is greater than 0, additional call stack information about * the application code will be logged as well. * @param string|array $message the message to be logged. This can be a simple string or a more * complex data structure that will be handled by a [[Target|log target]]. * @param int $level the level of the message. This must be one of the following: * `Logger::LEVEL_ERROR`, `Logger::LEVEL_WARNING`, `Logger::LEVEL_INFO`, `Logger::LEVEL_TRACE`, * `Logger::LEVEL_PROFILE_BEGIN`, `Logger::LEVEL_PROFILE_END`. * @param string $category the category of the message. */ public function log($message, $level, $category = 'application') { $time = microtime(true); $traces = []; if ($this->traceLevel > 0) { $count = 0; $ts = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); array_pop($ts); // remove the last trace since it would be the entry script, not very useful foreach ($ts as $trace) { if (isset($trace['file'], $trace['line']) && strpos($trace['file'], YII2_PATH) !== 0) { unset($trace['object'], $trace['args']); $traces[] = $trace; if (++$count >= $this->traceLevel) { break; } } } } $this->messages[] = [$message, $level, $category, $time, $traces, memory_get_usage()]; if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) { $this->flush(); } } /** * Flushes log messages from memory to targets. * @param bool $final whether this is a final call during a request. */ public function flush($final = false) { $messages = $this->messages; // https://github.com/yiisoft/yii2/issues/5619 // new messages could be logged while the existing ones are being handled by targets $this->messages = []; if ($this->dispatcher instanceof Dispatcher) { $this->dispatcher->dispatch($messages, $final); } } /** * Returns the total elapsed time since the start of the current request. * This method calculates the difference between now and the timestamp * defined by constant `YII_BEGIN_TIME` which is evaluated at the beginning * of [[\yii\BaseYii]] class file. * @return float the total elapsed time in seconds for current request. */ public function getElapsedTime() { return microtime(true) - YII_BEGIN_TIME; } /** * Returns the profiling results. * * By default, all profiling results will be returned. You may provide * `$categories` and `$excludeCategories` as parameters to retrieve the * results that you are interested in. * * @param array $categories list of categories that you are interested in. * You can use an asterisk at the end of a category to do a prefix match. * For example, 'yii\db\*' will match categories starting with 'yii\db\', * such as 'yii\db\Connection'. * @param array $excludeCategories list of categories that you want to exclude * @return array the profiling results. Each element is an array consisting of these elements: * `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`. * The `memory` and `memoryDiff` values are available since version 2.0.11. */ public function getProfiling($categories = [], $excludeCategories = []) { $timings = $this->calculateTimings($this->messages); if (empty($categories) && empty($excludeCategories)) { return $timings; } foreach ($timings as $i => $timing) { $matched = empty($categories); foreach ($categories as $category) { $prefix = rtrim($category, '*'); if (($timing['category'] === $category || $prefix !== $category) && strpos($timing['category'], $prefix) === 0) { $matched = true; break; } } if ($matched) { foreach ($excludeCategories as $category) { $prefix = rtrim($category, '*'); foreach ($timings as $i => $timing) { if (($timing['category'] === $category || $prefix !== $category) && strpos($timing['category'], $prefix) === 0) { $matched = false; break; } } } } if (!$matched) { unset($timings[$i]); } } return array_values($timings); } /** * Returns the statistical results of DB queries. * The results returned include the number of SQL statements executed and * the total time spent. * @return array the first element indicates the number of SQL statements executed, * and the second element the total time spent in SQL execution. */ public function getDbProfiling() { $timings = $this->getProfiling(['yii\db\Command::query', 'yii\db\Command::execute']); $count = count($timings); $time = 0; foreach ($timings as $timing) { $time += $timing['duration']; } return [$count, $time]; } /** * Calculates the elapsed time for the given log messages. * @param array $messages the log messages obtained from profiling * @return array timings. Each element is an array consisting of these elements: * `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`. * The `memory` and `memoryDiff` values are available since version 2.0.11. */ public function calculateTimings($messages) { $timings = []; $stack = []; foreach ($messages as $i => $log) { list($token, $level, $category, $timestamp, $traces) = $log; $memory = isset($log[5]) ? $log[5] : 0; $log[6] = $i; $hash = md5(json_encode($token)); if ($level == self::LEVEL_PROFILE_BEGIN) { $stack[$hash] = $log; } elseif ($level == self::LEVEL_PROFILE_END) { if (isset($stack[$hash])) { $timings[$stack[$hash][6]] = [ 'info' => $stack[$hash][0], 'category' => $stack[$hash][2], 'timestamp' => $stack[$hash][3], 'trace' => $stack[$hash][4], 'level' => count($stack) - 1, 'duration' => $timestamp - $stack[$hash][3], 'memory' => $memory, 'memoryDiff' => $memory - (isset($stack[$hash][5]) ? $stack[$hash][5] : 0), ]; unset($stack[$hash]); } } } ksort($timings); return array_values($timings); } /** * Returns the text display of the specified level. * @param int $level the message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]]. * @return string the text display of the level */ public static function getLevelName($level) { static $levels = [ self::LEVEL_ERROR => 'error', self::LEVEL_WARNING => 'warning', self::LEVEL_INFO => 'info', self::LEVEL_TRACE => 'trace', self::LEVEL_PROFILE_BEGIN => 'profile begin', self::LEVEL_PROFILE_END => 'profile end', self::LEVEL_PROFILE => 'profile', ]; return isset($levels[$level]) ? $levels[$level] : 'unknown'; } }
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <title>Introduction to OpenFL | HaxeFlixel 2D Game Framework</title> <meta name="description" content="HaxeFlixel is a 2D Game framework that lets you create cross-platform games easier with free, open source technology!"/> <meta name="keywords" content="gamedev, game development, cross-platform, haxe, flixel"/> <meta name="author" content=""/> <meta name="viewport" content="width=device-width"/> <link rel="shortcut icon" href="/images/favicon.ico"> <!--[if lt IE 9]> <script async src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link rel="stylesheet" href="/styles/style.css" /> </head> <body> <header> <nav> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/" class="navbar-brand"><img src="/images/haxeflixel-header.png" alt="HaxeFlixel" /></a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li > <a href="/demos">Demos</a> </li> <li class="dropdown" > <a href="/showcase" class="dropdown-toggle" data-toggle="dropdown">Showcase <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li> <a href="/showcase/games">Games</a> </li> <li> <a href="/showcase/jams">Jams</a> </li> </ul> </li> <li > <a href="/blog">Blog</a> </li> <li class='active'> <a href="/documentation">Docs</a> </li> <li> <a href="http://api.haxeflixel.com">API</a> </li> <li > <a href="/forum">Forum</a> </li> </ul> <form class="navbar-form search-form" role="search" action="http://google.com/search" method="get"> <div class="form-group"> <input type="search" name="q" class="form-control" placeholder="Search"> <input type="hidden" name="q" value="site:http://haxeflixel.com"> </div> </form> </div> </div> </div> </nav> </header> <div class="container container-main"> <div class="row"> <div class="col-md-3"> <div class="doc-nav affix"> <ul class="nav"> <li> <h4><a href="/documentation/getting-started">Getting Started</a><h4> </li> <li> <h4><a href="/documentation/community">Community</a><h4> </li> <li class= about="/documentation/community"> <a href="/documentation/community"> Community </a> </li> <li class= about="/documentation/about"> <a href="/documentation/about"> About </a> </li> <li class= about="/documentation/why-haxe"> <a href="/documentation/why-haxe"> Why a Haxe Version </a> </li> <li class= about="/documentation/introduction-to-haxe"> <a href="/documentation/introduction-to-haxe"> Introduction to Haxe </a> </li> <li class=active about="/documentation/introduction-to-openfl"> <a href="/documentation/introduction-to-openfl"> Introduction to OpenFL </a> </li> <li class= about="/documentation/contributing"> <a href="/documentation/contributing"> Contributing </a> </li> <li class= about="/documentation/code-contributions"> <a href="/documentation/code-contributions"> Code Contributions </a> </li> <li class= about="/documentation/code-style"> <a href="/documentation/code-style"> Code Style </a> </li> <li class= about="/documentation/website-docs"> <a href="/documentation/website-docs"> HaxeFlixel Website </a> </li> <li class= about="/documentation/haxeflixel-3-x"> <a href="/documentation/haxeflixel-3-x"> HaxeFlixel 3.x </a> </li> <li class= about="/documentation/upgrade-guide"> <a href="/documentation/upgrade-guide"> Upgrade Guide </a> </li> <li class= about="/documentation/flixel-addons"> <a href="/documentation/flixel-addons"> Flixel Addons </a> </li> <li class= about="/documentation/flixel-tools"> <a href="/documentation/flixel-tools"> Flixel Tools </a> </li> <li class= about="/documentation/install-development-flixel"> <a href="/documentation/install-development-flixel"> Install development Flixel </a> </li> <li> <h4><a href="/documentation/haxeflixel-handbook">HaxeFlixel Handbook</a><h4> </li> <li> <h4><a href="/documentation/resources">Resources</a><h4> </li> <li> <h4><a href="/documentation/tutorials">Tutorials</a><h4> </li> </ul> </div> </div> <div class="col-md-9 doc-content" role="main"> <h1 class="title">Introduction to OpenFL</h1> <a href="https://github.com/HaxeFlixel/flixel-docs/blob/master/documentation/01_community/04-introduction-to-openfl.html.md" class="btn btn-sm btn-edit" target="_blank"><span class="glyphicon glyphicon-pencil"></span> Edit </a> <p><img src="/images/openfl.jpg" width="100%" /></p> <p>The <a href="http://www.openfl.org">Open Flash Library</a> ( OpenFL ) previously known as NME, is an innovative framework designed to provide fast, productive development for Windows, Mac, Linux, iOS, Android, BlackBerry, Tizen, Mozilla OS, Flash and HTML5 – all using the same source code.</p> <p>OpenFL has a history of providing the Flash API wherever possible however it is also used to extend upon that API. OpenFL is powered with the Haxe Toolkit&#39;s cross-compiler that lets it produce native code such as C++ for its target platforms.</p> <p>OpenFL has a an active community of developers building games for the web, consoles, desktop and mobile devices. OpenFL is free to use and modify and it is currently being developed <a href="http://www.github.com/openfl">openly on GitHub</a>. The project made from the combined work of talented and passionate developers over many years has resulted in a mature and advanced platform.</p> <p>OpenFL targets include native cross-compiled C++ for Desktop and Mobile targets as well as web targets such as Flash, Html5 and experimental Emscripten. OpenFL is written primarily in the Haxe language as well as platform specific code integrating with SDKs and native APIs.</p> <p>OpenFL provides HaxeFlixel with a familiar Flash API as well as an extended set of features for Native targets. This includes the use of GPU accelerated texture batching through drawTiles, multi-threading and more.</p> <br> <hr> <ul class="pager"> <li class="previous"> <a href="/documentation/introduction-to-haxe">< Introduction to Haxe</a> </li> <li class="next"> <a href="/documentation/contributing">Contributing ></a> </li> </ul> </div> </div> </div> <footer> <div class="footer-main"> <div class=" container"> <div class="footer-social"> <iframe width="120px" scrolling="0" height="20px" frameborder="0" allowtransparency="true" src="http://ghbtns.com/github-btn.html?user=HaxeFlixel&amp;repo=flixel&amp;type=watch&amp;count=true&amp;size=small"></iframe> <a href="https://twitter.com/haxeflixel" class="twitter-follow-button" data-show-count="true" data-lang="en" data-size="small">Follow @haxeflixel</a> <script>!function (d, s, id) { var js, fjs = d.getElementsByTagName (s)[0]; if (!d.getElementById (id)) { js = d.createElement (s); js.id = id; js.src = "//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore (js, fjs); } } (document, "script", "twitter-wjs");</script> </div> <div class="footer-powered-by"> <p>HaxeFlixel is powered by</p> <a href="http://haxe.org"><img src="/images/haxe.svg" alt="Haxe" title="Haxe"></a> + <a href="http://openfl.org"><img class="openfl-footer-logo" src="/images/openfl.svg" alt="OpenFL" title="OpenFL"></a> + <a href="http://flixel.org"><img class="flixel-footer-logo" src="/images/flixel.svg" alt="Flixel" title="Flixel"></a> </div> </div> </div> </footer> <script >(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-35511281-1'); ga('send', 'pageview');</script><script defer="defer" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script defer="defer" src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script><script defer="defer" src="/vendor/twitter-bootstrap-3/js/dropdown.js"></script><script defer="defer" src="/vendor/twitter-bootstrap-3/js/transition.js"></script><script defer="defer" src="/vendor/twitter-bootstrap-3/js/collapse.js"></script> </body> </html>
Java
package com.github.scribejava.apis.examples; import com.github.scribejava.apis.EtsyApi; import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.model.OAuth1AccessToken; import com.github.scribejava.core.model.OAuth1RequestToken; import com.github.scribejava.core.model.OAuthRequest; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.model.Verb; import com.github.scribejava.core.oauth.OAuth10aService; import java.io.IOException; import java.util.Scanner; import java.util.concurrent.ExecutionException; public class EtsyExample { private static final String PROTECTED_RESOURCE_URL = "https://openapi.etsy.com/v2/users/__SELF__"; private EtsyExample() { } @SuppressWarnings("PMD.SystemPrintln") public static void main(String[] args) throws InterruptedException, ExecutionException, IOException { // Replace with your api and secret key final OAuth10aService service = new ServiceBuilder("your api key") .apiSecret("your secret key") .build(EtsyApi.instance()); final Scanner in = new Scanner(System.in); System.out.println("=== Etsy's OAuth Workflow ==="); System.out.println(); // Obtain the Request Token System.out.println("Fetching the Request Token..."); final OAuth1RequestToken requestToken = service.getRequestToken(); System.out.println("Got the Request Token!"); System.out.println(); System.out.println("Now go and authorize ScribeJava here:"); System.out.println(service.getAuthorizationUrl(requestToken)); System.out.println("And paste the verifier here"); System.out.print(">>"); final String oauthVerifier = in.nextLine(); System.out.println(); // Trade the Request Token and Verifier for the Access Token System.out.println("Trading the Request Token for an Access Token..."); final OAuth1AccessToken accessToken = service.getAccessToken(requestToken, oauthVerifier); System.out.println("Got the Access Token!"); System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to access a protected resource..."); final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); service.signRequest(accessToken, request); final Response response = service.execute(request); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getBody()); System.out.println(); System.out.println("That's it man! Go and build something awesome with ScribeJava! :)"); } }
Java
<?php namespace Tapestry\Providers; use Exception; use Tapestry\Tapestry; use Tapestry\Entities\Configuration; use Tapestry\Modules\Kernel\DefaultKernel; use Tapestry\Modules\Kernel\KernelInterface; use League\Container\ServiceProvider\AbstractServiceProvider; use League\Container\ServiceProvider\BootableServiceProviderInterface; class ProjectKernelServiceProvider extends AbstractServiceProvider implements BootableServiceProviderInterface { /** * @var array */ protected $provides = [ KernelInterface::class, ]; /** * Use the register method to register items with the container via the * protected $this->container property or the `getContainer` method * from the ContainerAwareTrait. * * @return void */ public function register() { } /** * Method will be invoked on registration of a service provider implementing * this interface. Provides ability for eager loading of Service Providers. * @return void * @throws Exception */ public function boot() { $container = $this->getContainer(); /** @var Tapestry $tapestry */ $tapestry = $container->get(Tapestry::class); $configuration = $container->get(Configuration::class); $kernelPath = $tapestry['currentWorkingDirectory'].DIRECTORY_SEPARATOR.'kernel.php'; if (! file_exists($kernelPath)) { $kernelPath = $tapestry['currentWorkingDirectory'].DIRECTORY_SEPARATOR.'Kernel.php'; } if (file_exists($kernelPath)) { $kernelClassName = $configuration->get('kernel', DefaultKernel::class); if (! class_exists($kernelClassName)) { include $kernelPath; } if (! class_exists($kernelClassName)) { throw new Exception('['.$kernelClassName.'] kernel file not found.'); } $container->share(KernelInterface::class, $kernelClassName)->withArgument( $container->get(Tapestry::class) ); } else { $container->share(KernelInterface::class, DefaultKernel::class)->withArgument( $container->get(Tapestry::class) ); } /** @var KernelInterface $kernel */ $kernel = $container->get(KernelInterface::class); $kernel->register(); } }
Java
<?php namespace App; use Illuminate\Support\Facades\Route; /* * Clearboard Routes */ Route::group(['middleware' => ['web']], function () { Route::get('/', function() { return view('clearboard.index.viewindex', ['forums' => Forum::all()]); }); Route::get('/forum/{fid}-{_}', 'ForumController@view'); Route::get('/thread/{tid}-{_}', 'ThreadController@view'); Route::get('/profile/{uid}-{_}', 'ProfileController@view'); Route::get('/forum', function() { return redirect('/'); }); // Route for processing markdown to HTML. Route::post('/ajax/markdown', 'MarkdownController@postParse'); Route::post('/ajax/markdown_inline', 'MarkdownController@postInlineParse'); // for parsing inline markdown // Posting routes Route::post('/ajax/new_post', 'PostController@createApi')->middleware('auth'); Route::post('/ajax/new_thread', 'ThreadController@createApi')->middleware('auth'); Route::get('/newthread/{forumid}', 'ThreadController@create')->middleware('auth'); // Account Settings Route::get('/settings/{userid}', 'SettingsController@view'); Route::get('/settings', 'SettingsController@view')->middleware('auth'); // Registration Route::get('/register', function(){ return view('clearboard.register.register'); }); Route::post('/ajax/register', 'RegisterController@postRegister'); // Authentication routes Route::group(array('prefix' => '/auth'), function() { Route::post('/login', 'Auth\AuthController@postAjaxLogin'); Route::get('/logout', 'Auth\AuthController@getLogout')->middleware('get_csrf'); Route::post('/sudo', 'Auth\AuthController@postSudo'); Route::get('/ping', function () { return ''; }); // a simple request that returns nothing to update the existence of a user. }); // Introduction route. Probably will be a way to disable at some point. Route::get('/clearboard/welcome', function () { return view('clearboard.welcome'); }); });
Java
(function() { 'use strict'; angular .module('app.core') .constant('STATIC_URL', '/static/js/'); })();
Java
<gd-annotation-app></gd-annotation-app>
Java
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get; set; } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException(nameof(textView)); var pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (var r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { var halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.X - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Y - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); } else { AddRectangle(r.X, r.Y, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException(nameof(textView)); if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { var segmentStart = segment.Offset; var segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment sel) { start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (var vl in textView.VisualLines) { var vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; var vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; segmentStartVc = segmentStart < vlStartOffset ? 0 : vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException(nameof(textView)); if (line == null) throw new ArgumentNullException(nameof(line)); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { var lastTextLine = visualLine.TextLines.Last(); var scrollOffset = textView.ScrollOffset; for (var i = 0; i < visualLine.TextLines.Count; i++) { var line = visualLine.TextLines[i]; var y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); var visualStartCol = visualLine.GetTextLineVisualStartColumn(line); var visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph // TODO: ? //else // visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; var segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); var segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; var lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible var pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { var b = line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine); var left = b.X - scrollOffset.X; var right = b.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width; } // TODO: !!!!!!!!!!!!!!!!!! SCROLL !!!!!!!!!!!!!!!!!! //if (line != lastTextLine || segmentEndVC == int.MaxValue) { // // If word-wrap is enabled and the segment continues into the next line, // // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // // we select the full width of the viewport. // right = Math.Max(((IScrollInfo)textView).ExtentWidth, ((IScrollInfo)textView).ViewportWidth); //} else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); //} var extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure { StartPoint = new Point(left, top + CornerRadius) }; if (Math.Abs(left - right) > CornerRadius) { _figure.Segments.Add(MakeArc(left + CornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - CornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + CornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - CornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { var cr = right < _lastRight ? -CornerRadius : CornerRadius; var dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; var dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + CornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - CornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + CornerRadius)); if (!_lastLeft.IsClose(left)) { var cr = left < _lastLeft ? CornerRadius : -CornerRadius; var dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; var dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - CornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } _lastTop = top; _lastBottom = bottom; _lastLeft = left; _lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + CornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > CornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - CornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + CornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - CornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } }
Java
@font-face { font-family: 'icomoon'; src:url('fonts/icomoon.eot?-ru2f3j'); src:url('fonts/icomoon.eot?#iefix-ru2f3j') format('embedded-opentype'), url('fonts/icomoon.woff?-ru2f3j') format('woff'), url('fonts/icomoon.ttf?-ru2f3j') format('truetype'), url('fonts/icomoon.svg?-ru2f3j#icomoon') format('svg'); font-weight: normal; font-style: normal; } [class^="icon-"], [class*=" icon-"] { font-family: 'icomoon'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; /* Better Font Rendering =========== */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .icon-twitter:before { content: "\21"; } .icon-facebook:before { content: "\22"; }
Java
namespace Nancy.Swagger.Tests { public class TestModel { public int SomeInt { get; set; } public long SomeLong { get; set; } public long? SomeNullableLong { get; set; } } }
Java
class Fitbit::Activity < Fitbit::Data attr_accessor :activityId, :activityParentId, :activityParentName, :calories, :description, :distance, :duration, :hasStartTime, :isFavorite, :logId, :name, :startTime, :steps def initialize(activity_data, unit_measurement_mappings) @activityId = activity_data['activityId'] @activityParentId = activity_data['activityParentId'] @activityParentName = activity_data['activityParentName'] @calories = activity_data['calories'] @description = activity_data['description'] @distance = "#{activity_data['distance']} #{unit_measurement_mappings[:distance]}" if activity_data['distance'] @duration = Time.at(activity_data['duration']/1000).utc.strftime("%H:%M:%S") if activity_data['duration'] @hasStartTime = activity_data['hasStartTime'] @logId = activity_data['logId'] @name = activity_data['name'] @startTime = activity_data['startTime'] @steps = activity_data['steps'] # Uncomment to view the data that is returned by the Fitbit service # ActiveRecord::Base.logger.info activity_data end def self.fetch_all_on_date(user, date) activity_objects = [] if user.present? && user.linked? activities = user.fitbit_data.activities_on_date(date)['activities'] activity_objects = activities.map {|a| Fitbit::Activity.new(a, user.unit_measurement_mappings) } end activity_objects end def self.log_activity(user, activity) if user.present? && user.linked? user.fitbit_data.log_activity(activity) end end end # Sample response from fitbit.com api #{"activityId"=>17151, # "activityParentId"=>90013, # "activityParentName"=>"Walking", # "calories"=>54, # "description"=>"less than 2 mph, strolling very slowly", # "distance"=>0.5, # "duration"=>1200000, # "hasStartTime"=>true, # "isFavorite"=>true, # "logId"=>21537078, # "name"=>"Walking", # "startTime"=>"11:45", # "steps"=>1107}
Java
$(document).ready(function(){ //Grabs url path var url = window.location.pathname; //Grabs current file name from URL var url = url.substring(url.lastIndexOf('/')+1); // now grab every link from the navigation $('#navigation a').each(function(){ //Grab the current elements href tag value var link = $(this).attr("href"); //Test if the url value and element value matches if(url === link){ //Adds class to the current item $(this).parent('li').addClass('active'); } }); });
Java
支持修改民法! 不要workaround!
Java
.urank-docviewer-container-default { background: -webkit-linear-gradient(top, rgba(175, 175, 175, 1), rgba(170, 170, 170, 1)); box-shadow: inset .1em .1em .5em #aaa, inset -.1em -.1em .5em #aaa; }
Java
<!-- begin:navbar --> <div class="maintainEvent"> <nav id="top" class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-top"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/"> <img src="img/mini_logo.png"> <h4>{{userName}}'s page!</h4> </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-top"> <ul class="nav navbar-nav navbar-right"> <li><a href="/">Home</a></li> <li><a ng-href="/maintainUser{{userId}}">Maintain info</a></li> <li class="dropdown active"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">My events <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="/createEvent">Create new</a></li> <li><a href="/maintainEvents">Maintain created</a></li><!-- <li><a href="category.html">Category (Grid View)</a></li> <li><a href="category_list.html">Category (List View)</a></li> <li><a href="single.html">Single page</a></li>--> </ul> </li> <li><a ng-if="userId" ng-href="/myMessages{{userId}}">Messages<small class="alert alert-warning">{{countMsgs}}</small></a></li> <!--<li class="dropdown">--> <!--<a href="#" class="dropdown-toggle" data-toggle="dropdown">Pages <b class="caret"></b></a>--> <!--<ul class="dropdown-menu">--> <!--<li><a href="blog.html">Blog Archive</a></li>--> <!--<li><a href="blog_single.html">Blog Single</a></li>--> <!--<li><a href="about.html">About</a></li>--> <!--<li><a href="contact.html">Contact</a></li>--> <!--</ul>--> <!--</li>--> <li> <button type="button" class="signin btn btn-warning" ng-click="signOut()">Sign out</button> </li> <!--<li><a href="/registerUser" class="signup" data-toggle="modal" data-target="#modal-signup">Sign up</a></li>--> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav> <!-- end:navbar --> <!--<h3 class="text-center">The list of created by you events:</h3>--> <!--<div class="list-group">--> <!--<div data-ng-repeat="event in info" class="dropdown">--> <!--<a href="" class="list-group-item list-group-item-success dropdown-toggle" data-toggle="dropdown" aria-expanded="true">--> <!--<span class="badge">{{event.party.length}}</span>--> <!--{{event.title}}--> <!--<span class="caret"></span>--> <!--</a>--> <!--<div class="dropdown-menu">--> <!--{{event}}--> <!--</div>--> <!--</div>--> <!--</div>--> <h2 class="text-center">You created events:</h2> <div id="MainMenu"> <div class="list-group panel"> <ui-gmap-google-map options="optionsForMap" center="{latitude:40.866667,longitude:34.566667}" zoom="1" ng-cloak> <div data-ng-repeat="event in info"> <ui-gmap-marker options="optionsMarker" coords="event.coords[0]" idkey="event._id" ng-cloak> <ui-gmap-window coords='event.coords[0]' show='true' > <h5>Link: <a ng-href="/makeChangesEvent{{event._id}}">{{event.title}}</a></h5> </ui-gmap-window> </ui-gmap-marker> </div> </ui-gmap-google-map> </div> <!-- begin:footer --> <div id="footer"> <div class="container"> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <div class="widget"> <h3>Support</h3> <ul class="list-unstyled"> <li><span class="fa fa-skype"></span> Skype : <span><a ng-href="skype:{{mySkype}}?chat">{{mySkype}}</a></span></li> <li><span class="fa fa-envelope-o"></span> Email : <span><a href="mailto:{{myEmail}}">{{myEmail}}</a></span></li> </ul> </div> </div> <!-- break --> <div class="col-md-3 col-sm-6 col-xs-12 col-md-offset-3"> <div class="widget"> <h2>Enveti</h2> <address> {{myAddress}} </address> </div> </div> <!-- break --> </div> <!-- break --> <!-- begin:copyright --> <div class="row"> <div class="col-md-12 copyright"> <p>Copyright &copy; 2014 UncoJet Ltd, All Right Reserved.</p> <a ng-click="scrollTo('top')" class="btn btn-warning scroltop"><i class="fa fa-angle-up"></i></a> <ul class="list-inline social-links"> <li><a href="https://vk.com/public70183674" class="icon-twitter" rel="tooltip" title="" data-placement="bottom" data-original-title="VK"><i class="fa fa-vk"></i></a></li> <li><a href="#" class="icon-facebook" rel="tooltip" title="" data-placement="bottom" data-original-title="Facebook"><i class="fa fa-facebook"></i></a></li> <li><a href="#" class="icon-gplus" rel="tooltip" title="" data-placement="bottom" data-original-title="Gplus"><i class="fa fa-google-plus"></i></a></li> </ul> </div> </div> <!-- end:copyright --> </div> </div> <!-- end:footer --> </div>
Java
.timbr_highlight { border-radius: 4px 4px 4px 4px; -moz-border-radius: 4px 4px 4px 4px; -webkit-border-radius: 4px 4px 4px 4px; } .timbr_border1 { border: 3px dashed #ff0000; } .timbr_border2 { border: 3px dashed #ff0099; } .timbr_border3 { border: 3px dashed #a900b8; } .timbr_border4 { border: 3px dashed #3c00ff; } .timbr_border5 { border: 3px dashed #040080; } .timbr_border6 { border: 3px dashed #3595fc; } .timbr_border7 { border: 3px dashed #00fff2; } .timbr_border8 { border: 3px dashed #00e388; } .timbr_border9 { border: 3px dashed #00bd1c; } .timbr_border10 { border: 3px dashed #f5d11b; } .timbr_border11 { border: 3px dashed #d17e02; } .timbr_border12 { border: 3px dashed #59362a } .dis{ display: none; }
Java
var fixDate = function(date) { return date.Format('2006-01-02 15:04:05'); }; var entries = executeCommand('getEntries', {}); dbotCommands = []; userCommands = []; for (var i = 0; i < entries.length; i++) { if (typeof entries[i].Contents == 'string' && entries[i].Contents.indexOf('!') === 0 && entries[i].Contents.indexOf('!listExecutedCommands') !== 0) { if (entries[i].Metadata.User) { if (args.source === 'All' || args.source === 'Manual') { userCommands.push({ 'Time': fixDate(entries[i].Metadata.Created), 'Entry ID': entries[i].ID, 'User': entries[i].Metadata.User, 'Command': entries[i].Contents }); } } else { if (args.source === 'All' || args.source === 'Playbook') { dbotCommands.push({ 'Time': fixDate(entries[i].Metadata.Created), 'Entry ID': entries[i].ID, 'Playbook (Task)': entries[i].Metadata.EntryTask.PlaybookName + " (" + entries[i].Metadata.EntryTask.TaskName + ")", 'Command': entries[i].Contents }); } } } } var md = ''; if (dbotCommands.length > 0) { md += tableToMarkdown('DBot Executed Commands', dbotCommands, ['Time', 'Entry ID', 'Playbook (Task)', 'Command']) + '\n'; } if (userCommands.length > 0) { md += tableToMarkdown('User Executed Commands', userCommands, ['Time', 'Entry ID', 'User', 'Command']) + '\n'; } if (md === '') { md = 'No commands found\n'; } return {ContentsFormat: formats.markdown, Type: entryTypes.note, Contents: md};
Java
public class A extends B { public A() {} }
Java
<?php // AdminBundle:Inquiry:inquiry.html.twig return array ( );
Java
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> {% include _head.html %} </head> <body class="post"> {% include _browser-upgrade.html %} {% include _navigation.html %} {% if page.image.feature %} <div class="image-wrap"> <img src= {% if page.image.feature contains 'http' %} "{{ page.image.feature }}" {% else %} "{{ site.url }}/images/{{ page.image.feature }}" {% endif %} alt="{{ page.title }} feature image"> {% if page.image.credit %} <span class="image-credit">Photo Credit: <a href="{{ page.image.creditlink }}">{{ page.image.credit }}</a></span> {% endif %} </div><!-- /.image-wrap --> {% endif %} <div id="main" role="main"> <div class="article-author-side"> {% include _author-bio.html %} </div> <article class="post" dir="rtl"> <div class="headline-wrap"> {% if page.link %} <h1><a href="{{ page.link }}">{{ page.title }}</a></h1> {% else %} <h1><a href="{{ site.url }}{{ page.url }}" rel="bookmark" title="{{ page.title }}">{{ page.title }}</a></h1> {% endif %} </div><!--/ .headline-wrap --> <div class="article-wrap"> {{ content }} <hr /> <footer role="contentinfo" dir="ltr"> {% if page.share != false %}{% include _social-share.html %}{% endif %} <p class="byline"><strong>{{ page.title }}</strong> was published on <time datetime="{{ page.date | date_to_xmlschema }}">{{ page.date | date: "%B %d, %Y" }}</time>{% if page.modified %} and last modified on <time datetime="{{ page.modified | date: "%Y-%m-%d" }}">{{ page.modified | date: "%B %d, %Y" }}</time>{% endif %}.</p> </footer> </div><!-- /.article-wrap --> {% if site.owner.disqus-shortname and page.comments == true %} <section id="disqus_thread"></section><!-- /#disqus_thread --> {% endif %} </article> </div><!-- /#main --> <div class="footer-wrap"> {% if site.related_posts.size > 0 %} <div class="related-articles"> <h4>You might also enjoy <small class="pull-right">(<a href="{{ site.url }}/posts/">View all posts</a>)</small></h4> <ul> {% for post in site.related_posts limit:3 %} <li><a href="{{ site.url }}{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a></li> {% endfor %} </ul> <hr /> </div><!-- /.related-articles --> {% endif %} <footer> {% include _footer.html %} </footer> </div><!-- /.footer-wrap --> {% include _scripts.html %} </body> </html>
Java
package easyupload.entity; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; @Entity public class FileUpload { public FileUpload(String filename, byte[] file, String mimeType) { this.file = file; this.filename = filename; this.mimeType = mimeType; } public FileUpload() { // Default Constructor } @Id private String filename; @Lob private byte[] file; private String mimeType; public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public byte[] getFile() { return file; } public void setFile(byte[] file) { this.file = file; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } }
Java
# guh Changes ## 2.0.1 - Updated typings to match Typings 1.0 ## 2.0.0 - Renamed from Basis to guh - Rewrite from the ground-up - Moved build system core to `guh-core` package - Switched from LiveReload to BrowserSync - Switched from Ruby Sass to libsass - Now requires Node ^5.0 - More flexible configuration format - Local configuration support - Added CLI - `guh new` to generate - `guh build` to build ## 1.2.1 - Fixed version number in `package.json` - Fixed server script build references ## 1.2.0 - Added extra optional arguments to `gulp build` to build only specific modules ## 1.1.1 - Updated dependencies ## 1.1.0 - Cleaned up typings folder - Updated dependencies ## 1.0.1 - Fix TS glob pattern in default config ## 1.0.0 - Initial release
Java
"""Tests for wheel binary packages and .dist-info.""" import os import pytest from mock import patch, Mock from pip._vendor import pkg_resources from pip import pep425tags, wheel from pip.exceptions import InvalidWheelFilename, UnsupportedWheel from pip.utils import unpack_file def test_get_entrypoints(tmpdir): with open(str(tmpdir.join("entry_points.txt")), "w") as fp: fp.write(""" [console_scripts] pip = pip.main:pip """) assert wheel.get_entrypoints(str(tmpdir.join("entry_points.txt"))) == ( {"pip": "pip.main:pip"}, {}, ) def test_uninstallation_paths(): class dist(object): def get_metadata_lines(self, record): return ['file.py,,', 'file.pyc,,', 'file.so,,', 'nopyc.py'] location = '' d = dist() paths = list(wheel.uninstallation_paths(d)) expected = ['file.py', 'file.pyc', 'file.so', 'nopyc.py', 'nopyc.pyc'] assert paths == expected # Avoid an easy 'unique generator' bug paths2 = list(wheel.uninstallation_paths(d)) assert paths2 == paths def test_wheel_version(tmpdir, data): future_wheel = 'futurewheel-1.9-py2.py3-none-any.whl' broken_wheel = 'brokenwheel-1.0-py2.py3-none-any.whl' future_version = (1, 9) unpack_file(data.packages.join(future_wheel), tmpdir + 'future', None, None) unpack_file(data.packages.join(broken_wheel), tmpdir + 'broken', None, None) assert wheel.wheel_version(tmpdir + 'future') == future_version assert not wheel.wheel_version(tmpdir + 'broken') def test_check_compatibility(): name = 'test' vc = wheel.VERSION_COMPATIBLE # Major version is higher - should be incompatible higher_v = (vc[0] + 1, vc[1]) # test raises with correct error with pytest.raises(UnsupportedWheel) as e: wheel.check_compatibility(higher_v, name) assert 'is not compatible' in str(e) # Should only log.warn - minor version is greator higher_v = (vc[0], vc[1] + 1) wheel.check_compatibility(higher_v, name) # These should work fine wheel.check_compatibility(wheel.VERSION_COMPATIBLE, name) # E.g if wheel to install is 1.0 and we support up to 1.2 lower_v = (vc[0], max(0, vc[1] - 1)) wheel.check_compatibility(lower_v, name) class TestWheelFile(object): def test_std_wheel_pattern(self): w = wheel.Wheel('simple-1.1.1-py2-none-any.whl') assert w.name == 'simple' assert w.version == '1.1.1' assert w.pyversions == ['py2'] assert w.abis == ['none'] assert w.plats == ['any'] def test_wheel_pattern_multi_values(self): w = wheel.Wheel('simple-1.1-py2.py3-abi1.abi2-any.whl') assert w.name == 'simple' assert w.version == '1.1' assert w.pyversions == ['py2', 'py3'] assert w.abis == ['abi1', 'abi2'] assert w.plats == ['any'] def test_wheel_with_build_tag(self): # pip doesn't do anything with build tags, but theoretically, we might # see one, in this case the build tag = '4' w = wheel.Wheel('simple-1.1-4-py2-none-any.whl') assert w.name == 'simple' assert w.version == '1.1' assert w.pyversions == ['py2'] assert w.abis == ['none'] assert w.plats == ['any'] def test_single_digit_version(self): w = wheel.Wheel('simple-1-py2-none-any.whl') assert w.version == '1' def test_missing_version_raises(self): with pytest.raises(InvalidWheelFilename): wheel.Wheel('Cython-cp27-none-linux_x86_64.whl') def test_invalid_filename_raises(self): with pytest.raises(InvalidWheelFilename): wheel.Wheel('invalid.whl') def test_supported_single_version(self): """ Test single-version wheel is known to be supported """ w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.supported(tags=[('py2', 'none', 'any')]) def test_supported_multi_version(self): """ Test multi-version wheel is known to be supported """ w = wheel.Wheel('simple-0.1-py2.py3-none-any.whl') assert w.supported(tags=[('py3', 'none', 'any')]) def test_not_supported_version(self): """ Test unsupported wheel is known to be unsupported """ w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert not w.supported(tags=[('py1', 'none', 'any')]) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') @patch('pip.pep425tags.get_platform', lambda: 'macosx_10_9_intel') def test_supported_osx_version(self): """ Wheels built for OS X 10.6 are supported on 10.9 """ tags = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_6_intel.whl') assert w.supported(tags=tags) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_9_intel.whl') assert w.supported(tags=tags) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') @patch('pip.pep425tags.get_platform', lambda: 'macosx_10_6_intel') def test_not_supported_osx_version(self): """ Wheels built for OS X 10.9 are not supported on 10.6 """ tags = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_9_intel.whl') assert not w.supported(tags=tags) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') def test_supported_multiarch_darwin(self): """ Multi-arch wheels (intel) are supported on components (i386, x86_64) """ with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_universal'): universal = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_intel'): intel = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_x86_64'): x64 = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_i386'): i386 = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_ppc'): ppc = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_ppc64'): ppc64 = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_intel.whl') assert w.supported(tags=intel) assert w.supported(tags=x64) assert w.supported(tags=i386) assert not w.supported(tags=universal) assert not w.supported(tags=ppc) assert not w.supported(tags=ppc64) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_universal.whl') assert w.supported(tags=universal) assert w.supported(tags=intel) assert w.supported(tags=x64) assert w.supported(tags=i386) assert w.supported(tags=ppc) assert w.supported(tags=ppc64) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') def test_not_supported_multiarch_darwin(self): """ Single-arch wheels (x86_64) are not supported on multi-arch (intel) """ with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_universal'): universal = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_intel'): intel = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_i386.whl') assert not w.supported(tags=intel) assert not w.supported(tags=universal) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_x86_64.whl') assert not w.supported(tags=intel) assert not w.supported(tags=universal) def test_support_index_min(self): """ Test results from `support_index_min` """ tags = [ ('py2', 'none', 'TEST'), ('py2', 'TEST', 'any'), ('py2', 'none', 'any'), ] w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.support_index_min(tags=tags) == 2 w = wheel.Wheel('simple-0.1-py2-none-TEST.whl') assert w.support_index_min(tags=tags) == 0 def test_support_index_min_none(self): """ Test `support_index_min` returns None, when wheel not supported """ w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.support_index_min(tags=[]) is None def test_unpack_wheel_no_flatten(self): from pip import utils from tempfile import mkdtemp from shutil import rmtree filepath = '../data/packages/meta-1.0-py2.py3-none-any.whl' if not os.path.exists(filepath): pytest.skip("%s does not exist" % filepath) try: tmpdir = mkdtemp() utils.unpack_file(filepath, tmpdir, 'application/zip', None) assert os.path.isdir(os.path.join(tmpdir, 'meta-1.0.dist-info')) finally: rmtree(tmpdir) pass def test_purelib_platlib(self, data): """ Test the "wheel is purelib/platlib" code. """ packages = [ ("pure_wheel", data.packages.join("pure_wheel-1.7"), True), ("plat_wheel", data.packages.join("plat_wheel-1.7"), False), ] for name, path, expected in packages: assert wheel.root_is_purelib(name, path) == expected def test_version_underscore_conversion(self): """ Test that we convert '_' to '-' for versions parsed out of wheel filenames """ w = wheel.Wheel('simple-0.1_1-py2-none-any.whl') assert w.version == '0.1-1' class TestPEP425Tags(object): def test_broken_sysconfig(self): """ Test that pep425tags still works when sysconfig is broken. Can be a problem on Python 2.7 Issue #1074. """ import pip.pep425tags def raises_ioerror(var): raise IOError("I have the wrong path!") with patch('pip.pep425tags.sysconfig.get_config_var', raises_ioerror): assert len(pip.pep425tags.get_supported()) class TestMoveWheelFiles(object): """ Tests for moving files from wheel src to scheme paths """ def prep(self, data, tmpdir): self.name = 'sample' self.wheelpath = data.packages.join( 'sample-1.2.0-py2.py3-none-any.whl') self.req = pkg_resources.Requirement.parse('sample') self.src = os.path.join(tmpdir, 'src') self.dest = os.path.join(tmpdir, 'dest') unpack_file(self.wheelpath, self.src, None, None) self.scheme = { 'scripts': os.path.join(self.dest, 'bin'), 'purelib': os.path.join(self.dest, 'lib'), 'data': os.path.join(self.dest, 'data'), } self.src_dist_info = os.path.join( self.src, 'sample-1.2.0.dist-info') self.dest_dist_info = os.path.join( self.scheme['purelib'], 'sample-1.2.0.dist-info') def assert_installed(self): # lib assert os.path.isdir( os.path.join(self.scheme['purelib'], 'sample')) # dist-info metadata = os.path.join(self.dest_dist_info, 'METADATA') assert os.path.isfile(metadata) # data files data_file = os.path.join(self.scheme['data'], 'my_data', 'data_file') assert os.path.isfile(data_file) # package data pkg_data = os.path.join( self.scheme['purelib'], 'sample', 'package_data.dat') assert os.path.isfile(pkg_data) def test_std_install(self, data, tmpdir): self.prep(data, tmpdir) wheel.move_wheel_files( self.name, self.req, self.src, scheme=self.scheme) self.assert_installed() def test_dist_info_contains_empty_dir(self, data, tmpdir): """ Test that empty dirs are not installed """ # e.g. https://github.com/pypa/pip/issues/1632#issuecomment-38027275 self.prep(data, tmpdir) src_empty_dir = os.path.join( self.src_dist_info, 'empty_dir', 'empty_dir') os.makedirs(src_empty_dir) assert os.path.isdir(src_empty_dir) wheel.move_wheel_files( self.name, self.req, self.src, scheme=self.scheme) self.assert_installed() assert not os.path.isdir( os.path.join(self.dest_dist_info, 'empty_dir')) class TestWheelBuilder(object): def test_skip_building_wheels(self, caplog): with patch('pip.wheel.WheelBuilder._build_one') as mock_build_one: wheel_req = Mock(is_wheel=True, editable=False) reqset = Mock(requirements=Mock(values=lambda: [wheel_req]), wheel_download_dir='/wheel/dir') wb = wheel.WheelBuilder(reqset, Mock()) wb.build() assert "due to already being wheel" in caplog.text() assert mock_build_one.mock_calls == [] def test_skip_building_editables(self, caplog): with patch('pip.wheel.WheelBuilder._build_one') as mock_build_one: editable_req = Mock(editable=True, is_wheel=False) reqset = Mock(requirements=Mock(values=lambda: [editable_req]), wheel_download_dir='/wheel/dir') wb = wheel.WheelBuilder(reqset, Mock()) wb.build() assert "due to being editable" in caplog.text() assert mock_build_one.mock_calls == []
Java
# Camera ```sh user@server:~$ nano ~/.homeassistant/configuration.yaml ``` ``` camera: - platform: generic name: HikvisionCamImage still_image_url: http://10.0.74.78/Streaming/channels/1/picture username: admin password: 12345 - platform: generic name: DlinkImage still_image_url: http://admin:@10.0.72.82/image/jpeg.cgi - platform: mjpeg name: DlinkVideo mjpeg_url: http://admin:@10.0.72.82/video/mjpg.cgi ```
Java
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\MIEGeo; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Country extends AbstractTag { protected $Id = 'Country'; protected $Name = 'Country'; protected $FullName = 'MIE::Geo'; protected $GroupName = 'MIE-Geo'; protected $g0 = 'MIE'; protected $g1 = 'MIE-Geo'; protected $g2 = 'Location'; protected $Type = 'string'; protected $Writable = true; protected $Description = 'Country'; }
Java
'use strict'; var canUseDOM = require('./canUseDOM'); var one = function() { }; var on = function() { }; var off = function() { }; if (canUseDOM) { var bind = window.addEventListener ? 'addEventListener' : 'attachEvent'; var unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent'; var prefix = bind !== 'addEventListener' ? 'on' : ''; one = function(node, eventNames, eventListener) { var typeArray = eventNames.split(' '); var recursiveFunction = function(e) { e.target.removeEventListener(e.type, recursiveFunction); return eventListener(e); }; for (var i = typeArray.length - 1; i >= 0; i--) { this.on(node, typeArray[i], recursiveFunction); } }; /** * Bind `node` event `eventName` to `eventListener`. * * @param {Element} node * @param {String} eventName * @param {Function} eventListener * @param {Boolean} capture * @return {Obejct} * @api public */ on = function(node, eventName, eventListener, capture) { node[bind](prefix + eventName, eventListener, capture || false); return { off: function() { node[unbind](prefix + eventName, eventListener, capture || false); } }; } /** * Unbind `node` event `eventName`'s callback `eventListener`. * * @param {Element} node * @param {String} eventName * @param {Function} eventListener * @param {Boolean} capture * @return {Function} * @api public */ off = function(node, eventName, eventListener, capture) { node[unbind](prefix + eventName, eventListener, capture || false); return eventListener; }; } module.exports = { one: one, on: on, off: off };
Java
'use strict'; describe('angular', function() { var element; afterEach(function(){ dealoc(element); }); describe('case', function() { it('should change case', function() { expect(lowercase('ABC90')).toEqual('abc90'); expect(manualLowercase('ABC90')).toEqual('abc90'); expect(uppercase('abc90')).toEqual('ABC90'); expect(manualUppercase('abc90')).toEqual('ABC90'); }); }); describe("copy", function() { it("should return same object", function () { var obj = {}; var arr = []; expect(copy({}, obj)).toBe(obj); expect(copy([], arr)).toBe(arr); }); it("should copy Date", function() { var date = new Date(123); expect(copy(date) instanceof Date).toBeTruthy(); expect(copy(date).getTime()).toEqual(123); expect(copy(date) === date).toBeFalsy(); }); it("should deeply copy an array into an existing array", function() { var src = [1, {name:"value"}]; var dst = [{key:"v"}]; expect(copy(src, dst)).toBe(dst); expect(dst).toEqual([1, {name:"value"}]); expect(dst[1]).toEqual({name:"value"}); expect(dst[1]).not.toBe(src[1]); }); it("should deeply copy an array into a new array", function() { var src = [1, {name:"value"}]; var dst = copy(src); expect(src).toEqual([1, {name:"value"}]); expect(dst).toEqual(src); expect(dst).not.toBe(src); expect(dst[1]).not.toBe(src[1]); }); it('should copy empty array', function() { var src = []; var dst = [{key: "v"}]; expect(copy(src, dst)).toEqual([]); expect(dst).toEqual([]); }); it("should deeply copy an object into an existing object", function() { var src = {a:{name:"value"}}; var dst = {b:{key:"v"}}; expect(copy(src, dst)).toBe(dst); expect(dst).toEqual({a:{name:"value"}}); expect(dst.a).toEqual(src.a); expect(dst.a).not.toBe(src.a); }); it("should deeply copy an object into an existing object", function() { var src = {a:{name:"value"}}; var dst = copy(src, dst); expect(src).toEqual({a:{name:"value"}}); expect(dst).toEqual(src); expect(dst).not.toBe(src); expect(dst.a).toEqual(src.a); expect(dst.a).not.toBe(src.a); }); it("should copy primitives", function() { expect(copy(null)).toEqual(null); expect(copy('')).toBe(''); expect(copy('lala')).toBe('lala'); expect(copy(123)).toEqual(123); expect(copy([{key:null}])).toEqual([{key:null}]); }); it('should throw an exception if a Scope is being copied', inject(function($rootScope) { expect(function() { copy($rootScope.$new()); }). toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported."); })); it('should throw an exception if a Window is being copied', function() { expect(function() { copy(window); }). toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported."); }); it('should throw an exception when source and destination are equivalent', function() { var src, dst; src = dst = {key: 'value'}; expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical."); src = dst = [2, 4]; expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical."); }); it('should not copy the private $$hashKey', function() { var src,dst; src = {}; hashKey(src); dst = copy(src); expect(hashKey(dst)).not.toEqual(hashKey(src)); }); it('should retain the previous $$hashKey', function() { var src,dst,h; src = {}; dst = {}; // force creation of a hashkey h = hashKey(dst); hashKey(src); dst = copy(src,dst); // make sure we don't copy the key expect(hashKey(dst)).not.toEqual(hashKey(src)); // make sure we retain the old key expect(hashKey(dst)).toEqual(h); }); }); describe("extend", function() { it('should not copy the private $$hashKey', function() { var src,dst; src = {}; dst = {}; hashKey(src); dst = extend(dst,src); expect(hashKey(dst)).not.toEqual(hashKey(src)); }); it('should retain the previous $$hashKey', function() { var src,dst,h; src = {}; dst = {}; h = hashKey(dst); hashKey(src); dst = extend(dst,src); // make sure we don't copy the key expect(hashKey(dst)).not.toEqual(hashKey(src)); // make sure we retain the old key expect(hashKey(dst)).toEqual(h); }); it('should work when extending with itself', function() { var src,dst,h; dst = src = {}; h = hashKey(dst); dst = extend(dst,src); // make sure we retain the old key expect(hashKey(dst)).toEqual(h); }); }); describe('shallow copy', function() { it('should make a copy', function() { var original = {key:{}}; var copy = shallowCopy(original); expect(copy).toEqual(original); expect(copy.key).toBe(original.key); }); it('should not copy $$ properties nor prototype properties', function() { var original = {$$some: true, $$: true}; var clone = {}; expect(shallowCopy(original, clone)).toBe(clone); expect(clone.$$some).toBeUndefined(); expect(clone.$$).toBeUndefined(); }); }); describe('elementHTML', function() { it('should dump element', function() { expect(startingTag('<div attr="123">something<span></span></div>')). toEqual('<div attr="123">'); }); }); describe('equals', function() { it('should return true if same object', function() { var o = {}; expect(equals(o, o)).toEqual(true); expect(equals(o, {})).toEqual(true); expect(equals(1, '1')).toEqual(false); expect(equals(1, '2')).toEqual(false); }); it('should recurse into object', function() { expect(equals({}, {})).toEqual(true); expect(equals({name:'misko'}, {name:'misko'})).toEqual(true); expect(equals({name:'misko', age:1}, {name:'misko'})).toEqual(false); expect(equals({name:'misko'}, {name:'misko', age:1})).toEqual(false); expect(equals({name:'misko'}, {name:'adam'})).toEqual(false); expect(equals(['misko'], ['misko'])).toEqual(true); expect(equals(['misko'], ['adam'])).toEqual(false); expect(equals(['misko'], ['misko', 'adam'])).toEqual(false); }); it('should ignore undefined member variables during comparison', function() { var obj1 = {name: 'misko'}, obj2 = {name: 'misko', undefinedvar: undefined}; expect(equals(obj1, obj2)).toBe(true); expect(equals(obj2, obj1)).toBe(true); }); it('should ignore $ member variables', function() { expect(equals({name:'misko', $id:1}, {name:'misko', $id:2})).toEqual(true); expect(equals({name:'misko'}, {name:'misko', $id:2})).toEqual(true); expect(equals({name:'misko', $id:1}, {name:'misko'})).toEqual(true); }); it('should ignore functions', function() { expect(equals({func: function() {}}, {bar: function() {}})).toEqual(true); }); it('should work well with nulls', function() { expect(equals(null, '123')).toBe(false); expect(equals('123', null)).toBe(false); var obj = {foo:'bar'}; expect(equals(null, obj)).toBe(false); expect(equals(obj, null)).toBe(false); expect(equals(null, null)).toBe(true); }); it('should work well with undefined', function() { expect(equals(undefined, '123')).toBe(false); expect(equals('123', undefined)).toBe(false); var obj = {foo:'bar'}; expect(equals(undefined, obj)).toBe(false); expect(equals(obj, undefined)).toBe(false); expect(equals(undefined, undefined)).toBe(true); }); it('should treat two NaNs as equal', function() { expect(equals(NaN, NaN)).toBe(true); }); it('should compare Scope instances only by identity', inject(function($rootScope) { var scope1 = $rootScope.$new(), scope2 = $rootScope.$new(); expect(equals(scope1, scope1)).toBe(true); expect(equals(scope1, scope2)).toBe(false); expect(equals($rootScope, scope1)).toBe(false); expect(equals(undefined, scope1)).toBe(false); })); it('should compare Window instances only by identity', function() { expect(equals(window, window)).toBe(true); expect(equals(window, window.parent)).toBe(false); expect(equals(window, undefined)).toBe(false); }); it('should compare dates', function() { expect(equals(new Date(0), new Date(0))).toBe(true); expect(equals(new Date(0), new Date(1))).toBe(false); expect(equals(new Date(0), 0)).toBe(false); expect(equals(0, new Date(0))).toBe(false); }); it('should correctly test for keys that are present on Object.prototype', function() { // MS IE8 just doesn't work for this kind of thing, since "for ... in" doesn't return // things like hasOwnProperty even if it is explicitly defined on the actual object! if (msie<=8) return; expect(equals({}, {hasOwnProperty: 1})).toBe(false); expect(equals({}, {toString: null})).toBe(false); }); }); describe('size', function() { it('should return the number of items in an array', function() { expect(size([])).toBe(0); expect(size(['a', 'b', 'c'])).toBe(3); }); it('should return the number of properties of an object', function() { expect(size({})).toBe(0); expect(size({a:1, b:'a', c:noop})).toBe(3); }); it('should return the number of own properties of an object', function() { var obj = inherit({protoProp: 'c', protoFn: noop}, {a:1, b:'a', c:noop}); expect(size(obj)).toBe(5); expect(size(obj, true)).toBe(3); }); it('should return the string length', function() { expect(size('')).toBe(0); expect(size('abc')).toBe(3); }); it('should not rely on length property of an object to determine its size', function() { expect(size({length:99})).toBe(1); }); }); describe('parseKeyValue', function() { it('should parse a string into key-value pairs', function() { expect(parseKeyValue('')).toEqual({}); expect(parseKeyValue('simple=pair')).toEqual({simple: 'pair'}); expect(parseKeyValue('first=1&second=2')).toEqual({first: '1', second: '2'}); expect(parseKeyValue('escaped%20key=escaped%20value')). toEqual({'escaped key': 'escaped value'}); expect(parseKeyValue('emptyKey=')).toEqual({emptyKey: ''}); expect(parseKeyValue('flag1&key=value&flag2')). toEqual({flag1: true, key: 'value', flag2: true}); }); it('should ignore key values that are not valid URI components', function() { expect(function() { parseKeyValue('%'); }).not.toThrow(); expect(parseKeyValue('%')).toEqual({}); expect(parseKeyValue('invalid=%')).toEqual({ invalid: undefined }); expect(parseKeyValue('invalid=%&valid=good')).toEqual({ invalid: undefined, valid: 'good' }); }); it('should parse a string into key-value pairs with duplicates grouped in an array', function() { expect(parseKeyValue('')).toEqual({}); expect(parseKeyValue('duplicate=pair')).toEqual({duplicate: 'pair'}); expect(parseKeyValue('first=1&first=2')).toEqual({first: ['1','2']}); expect(parseKeyValue('escaped%20key=escaped%20value&&escaped%20key=escaped%20value2')). toEqual({'escaped key': ['escaped value','escaped value2']}); expect(parseKeyValue('flag1&key=value&flag1')). toEqual({flag1: [true,true], key: 'value'}); expect(parseKeyValue('flag1&flag1=value&flag1=value2&flag1')). toEqual({flag1: [true,'value','value2',true]}); }); }); describe('toKeyValue', function() { it('should serialize key-value pairs into string', function() { expect(toKeyValue({})).toEqual(''); expect(toKeyValue({simple: 'pair'})).toEqual('simple=pair'); expect(toKeyValue({first: '1', second: '2'})).toEqual('first=1&second=2'); expect(toKeyValue({'escaped key': 'escaped value'})). toEqual('escaped%20key=escaped%20value'); expect(toKeyValue({emptyKey: ''})).toEqual('emptyKey='); }); it('should serialize true values into flags', function() { expect(toKeyValue({flag1: true, key: 'value', flag2: true})).toEqual('flag1&key=value&flag2'); }); it('should serialize duplicates into duplicate param strings', function() { expect(toKeyValue({key: [323,'value',true]})).toEqual('key=323&key=value&key'); expect(toKeyValue({key: [323,'value',true, 1234]})). toEqual('key=323&key=value&key&key=1234'); }); }); describe('forEach', function() { it('should iterate over *own* object properties', function() { function MyObj() { this.bar = 'barVal'; this.baz = 'bazVal'; } MyObj.prototype.foo = 'fooVal'; var obj = new MyObj(), log = []; forEach(obj, function(value, key) { log.push(key + ':' + value)}); expect(log).toEqual(['bar:barVal', 'baz:bazVal']); }); it('should handle JQLite and jQuery objects like arrays', function() { var jqObject = jqLite("<p><span>s1</span><span>s2</span></p>").find("span"), log = []; forEach(jqObject, function(value, key) { log.push(key + ':' + value.innerHTML)}); expect(log).toEqual(['0:s1', '1:s2']); }); it('should handle NodeList objects like arrays', function() { var nodeList = jqLite("<p><span>a</span><span>b</span><span>c</span></p>")[0].childNodes, log = []; forEach(nodeList, function(value, key) { log.push(key + ':' + value.innerHTML)}); expect(log).toEqual(['0:a', '1:b', '2:c']); }); it('should handle HTMLCollection objects like arrays', function() { document.body.innerHTML = "<p>" + "<a name='x'>a</a>" + "<a name='y'>b</a>" + "<a name='x'>c</a>" + "</p>"; var htmlCollection = document.getElementsByName('x'), log = []; forEach(htmlCollection, function(value, key) { log.push(key + ':' + value.innerHTML)}); expect(log).toEqual(['0:a', '1:c']); }); it('should handle arguments objects like arrays', function() { var args, log = []; (function(){ args = arguments}('a', 'b', 'c')); forEach(args, function(value, key) { log.push(key + ':' + value)}); expect(log).toEqual(['0:a', '1:b', '2:c']); }); it('should handle objects with length property as objects', function() { var obj = { 'foo' : 'bar', 'length': 2 }, log = []; forEach(obj, function(value, key) { log.push(key + ':' + value)}); expect(log).toEqual(['foo:bar', 'length:2']); }); it('should handle objects of custom types with length property as objects', function() { function CustomType() { this.length = 2; this.foo = 'bar' } var obj = new CustomType(), log = []; forEach(obj, function(value, key) { log.push(key + ':' + value)}); expect(log).toEqual(['length:2', 'foo:bar']); }); }); describe('sortedKeys', function() { it('should collect keys from object', function() { expect(sortedKeys({c:0, b:0, a:0})).toEqual(['a', 'b', 'c']); }); }); describe('encodeUriSegment', function() { it('should correctly encode uri segment and not encode chars defined as pchar set in rfc3986', function() { //don't encode alphanum expect(encodeUriSegment('asdf1234asdf')). toEqual('asdf1234asdf'); //don't encode unreserved' expect(encodeUriSegment("-_.!~*'() -_.!~*'()")). toEqual("-_.!~*'()%20-_.!~*'()"); //don't encode the rest of pchar' expect(encodeUriSegment(':@&=+$, :@&=+$,')). toEqual(':@&=+$,%20:@&=+$,'); //encode '/', ';' and ' '' expect(encodeUriSegment('/; /;')). toEqual('%2F%3B%20%2F%3B'); }); }); describe('encodeUriQuery', function() { it('should correctly encode uri query and not encode chars defined as pchar set in rfc3986', function() { //don't encode alphanum expect(encodeUriQuery('asdf1234asdf')). toEqual('asdf1234asdf'); //don't encode unreserved expect(encodeUriQuery("-_.!~*'() -_.!~*'()")). toEqual("-_.!~*'()+-_.!~*'()"); //don't encode the rest of pchar expect(encodeUriQuery(':@$, :@$,')). toEqual(':@$,+:@$,'); //encode '&', ';', '=', '+', and '#' expect(encodeUriQuery('&;=+# &;=+#')). toEqual('%26%3B%3D%2B%23+%26%3B%3D%2B%23'); //encode ' ' as '+' expect(encodeUriQuery(' ')). toEqual('++'); //encode ' ' as '%20' when a flag is used expect(encodeUriQuery(' ', true)). toEqual('%20%20'); //do not encode `null` as '+' when flag is used expect(encodeUriQuery('null', true)). toEqual('null'); //do not encode `null` with no flag expect(encodeUriQuery('null')). toEqual('null'); }); }); describe('angularInit', function() { var bootstrapSpy; var element; beforeEach(function() { element = { getElementById: function (id) { return element.getElementById[id] || []; }, querySelectorAll: function(arg) { return element.querySelectorAll[arg] || []; }, getAttribute: function(name) { return element[name]; } }; bootstrapSpy = jasmine.createSpy('bootstrapSpy'); }); it('should do nothing when not found', function() { angularInit(element, bootstrapSpy); expect(bootstrapSpy).not.toHaveBeenCalled(); }); it('should look for ngApp directive as attr', function() { var appElement = jqLite('<div ng-app="ABC"></div>')[0]; element.querySelectorAll['[ng-app]'] = [appElement]; angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should look for ngApp directive in id', function() { var appElement = jqLite('<div id="ng-app" data-ng-app="ABC"></div>')[0]; jqLite(document.body).append(appElement); angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should look for ngApp directive in className', function() { var appElement = jqLite('<div data-ng-app="ABC"></div>')[0]; element.querySelectorAll['.ng\\:app'] = [appElement]; angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should look for ngApp directive using querySelectorAll', function() { var appElement = jqLite('<div x-ng-app="ABC"></div>')[0]; element.querySelectorAll['[ng\\:app]'] = [ appElement ]; angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should bootstrap using class name', function() { var appElement = jqLite('<div class="ng-app: ABC;"></div>')[0]; angularInit(jqLite('<div></div>').append(appElement)[0], bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should bootstrap anonymously', function() { var appElement = jqLite('<div x-ng-app></div>')[0]; element.querySelectorAll['[x-ng-app]'] = [ appElement ]; angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []); }); it('should bootstrap anonymously using class only', function() { var appElement = jqLite('<div class="ng-app"></div>')[0]; angularInit(jqLite('<div></div>').append(appElement)[0], bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []); }); it('should bootstrap if the annotation is on the root element', function() { var appElement = jqLite('<div class="ng-app"></div>')[0]; angularInit(appElement, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []); }); it('should complain if app module cannot be found', function() { var appElement = jqLite('<div ng-app="doesntexist"></div>')[0]; expect(function() { angularInit(appElement, bootstrap); }).toThrowMatching( /\[\$injector:modulerr] Failed to instantiate module doesntexist due to:\n.*\[\$injector:nomod] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it\./ ); }); }); describe('angular service', function() { it('should override services', function() { module(function($provide){ $provide.value('fake', 'old'); $provide.value('fake', 'new'); }); inject(function(fake) { expect(fake).toEqual('new'); }); }); it('should inject dependencies specified by $inject and ignore function argument name', function() { expect(angular.injector([function($provide){ $provide.factory('svc1', function() { return 'svc1'; }); $provide.factory('svc2', ['svc1', function(s) { return 'svc2-' + s; }]); }]).get('svc2')).toEqual('svc2-svc1'); }); }); describe('isDate', function() { it('should return true for Date object', function() { expect(isDate(new Date())).toBe(true); }); it('should return false for non Date objects', function() { expect(isDate([])).toBe(false); expect(isDate('')).toBe(false); expect(isDate(23)).toBe(false); expect(isDate({})).toBe(false); }); }); describe('compile', function() { it('should link to existing node and create scope', inject(function($rootScope, $compile) { var template = angular.element('<div>{{greeting = "hello world"}}</div>'); element = $compile(template)($rootScope); $rootScope.$digest(); expect(template.text()).toEqual('hello world'); expect($rootScope.greeting).toEqual('hello world'); })); it('should link to existing node and given scope', inject(function($rootScope, $compile) { var template = angular.element('<div>{{greeting = "hello world"}}</div>'); element = $compile(template)($rootScope); $rootScope.$digest(); expect(template.text()).toEqual('hello world'); })); it('should link to new node and given scope', inject(function($rootScope, $compile) { var template = jqLite('<div>{{greeting = "hello world"}}</div>'); var compile = $compile(template); var templateClone = template.clone(); element = compile($rootScope, function(clone){ templateClone = clone; }); $rootScope.$digest(); expect(template.text()).toEqual('{{greeting = "hello world"}}'); expect(element.text()).toEqual('hello world'); expect(element).toEqual(templateClone); expect($rootScope.greeting).toEqual('hello world'); })); it('should link to cloned node and create scope', inject(function($rootScope, $compile) { var template = jqLite('<div>{{greeting = "hello world"}}</div>'); element = $compile(template)($rootScope, noop); $rootScope.$digest(); expect(template.text()).toEqual('{{greeting = "hello world"}}'); expect(element.text()).toEqual('hello world'); expect($rootScope.greeting).toEqual('hello world'); })); }); describe('nodeName_', function() { it('should correctly detect node name with "namespace" when xmlns is defined', function() { var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' + '<ngtest:foo ngtest:attr="bar"></ngtest:foo>' + '</div>')[0]; expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO'); expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar'); }); if (!msie || msie >= 9) { it('should correctly detect node name with "namespace" when xmlns is NOT defined', function() { var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' + '<ngtest:foo ngtest:attr="bar"></ng-test>' + '</div>')[0]; expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO'); expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar'); }); } }); describe('nextUid()', function() { it('should return new id per call', function() { var seen = {}; var count = 100; while(count--) { var current = nextUid(); expect(current.match(/[\d\w]+/)).toBeTruthy(); expect(seen[current]).toBeFalsy(); seen[current] = true; } }); }); describe('version', function() { it('version should have full/major/minor/dot/codeName properties', function() { expect(version).toBeDefined(); expect(version.full).toBe('"NG_VERSION_FULL"'); expect(version.major).toBe("NG_VERSION_MAJOR"); expect(version.minor).toBe("NG_VERSION_MINOR"); expect(version.dot).toBe("NG_VERSION_DOT"); expect(version.codeName).toBe('"NG_VERSION_CODENAME"'); }); }); describe('bootstrap', function() { it('should bootstrap app', function(){ var element = jqLite('<div>{{1+2}}</div>'); var injector = angular.bootstrap(element); expect(injector).toBeDefined(); expect(element.injector()).toBe(injector); dealoc(element); }); it("should complain if app module can't be found", function() { var element = jqLite('<div>{{1+2}}</div>'); expect(function() { angular.bootstrap(element, ['doesntexist']); }).toThrowMatching( /\[\$injector:modulerr\] Failed to instantiate module doesntexist due to:\n.*\[\$injector:nomod\] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it\./); expect(element.html()).toBe('{{1+2}}'); dealoc(element); }); describe('deferred bootstrap', function() { var originalName = window.name, element; beforeEach(function() { window.name = ''; element = jqLite('<div>{{1+2}}</div>'); }); afterEach(function() { dealoc(element); window.name = originalName; }); it('should wait for extra modules', function() { window.name = 'NG_DEFER_BOOTSTRAP!'; angular.bootstrap(element); expect(element.html()).toBe('{{1+2}}'); angular.resumeBootstrap(); expect(element.html()).toBe('3'); expect(window.name).toEqual(''); }); it('should load extra modules', function() { element = jqLite('<div>{{1+2}}</div>'); window.name = 'NG_DEFER_BOOTSTRAP!'; var bootstrapping = jasmine.createSpy('bootstrapping'); angular.bootstrap(element, [bootstrapping]); expect(bootstrapping).not.toHaveBeenCalled(); expect(element.injector()).toBeUndefined(); angular.module('addedModule', []).value('foo', 'bar'); angular.resumeBootstrap(['addedModule']); expect(bootstrapping).toHaveBeenCalledOnce(); expect(element.injector().get('foo')).toEqual('bar'); }); it('should not defer bootstrap without window.name cue', function() { angular.bootstrap(element, []); angular.module('addedModule', []).value('foo', 'bar'); expect(function() { element.injector().get('foo'); }).toThrow('[$injector:unpr] Unknown provider: fooProvider <- foo'); expect(element.injector().get('$http')).toBeDefined(); }); it('should restore the original window.name after bootstrap', function() { window.name = 'NG_DEFER_BOOTSTRAP!my custom name'; angular.bootstrap(element); expect(element.html()).toBe('{{1+2}}'); angular.resumeBootstrap(); expect(element.html()).toBe('3'); expect(window.name).toEqual('my custom name'); }); }); }); describe('startingElementHtml', function(){ it('should show starting element tag only', function(){ expect(startingTag('<ng-abc x="2A"><div>text</div></ng-abc>')). toBe('<ng-abc x="2A">'); }); }); describe('startingTag', function() { it('should allow passing in Nodes instead of Elements', function() { var txtNode = document.createTextNode('some text'); expect(startingTag(txtNode)).toBe('some text'); }); }); describe('snake_case', function(){ it('should convert to snake_case', function() { expect(snake_case('ABC')).toEqual('a_b_c'); expect(snake_case('alanBobCharles')).toEqual('alan_bob_charles'); }); }); describe('fromJson', function() { it('should delegate to JSON.parse', function() { var spy = spyOn(JSON, 'parse').andCallThrough(); expect(fromJson('{}')).toEqual({}); expect(spy).toHaveBeenCalled(); }); }); describe('toJson', function() { it('should delegate to JSON.stringify', function() { var spy = spyOn(JSON, 'stringify').andCallThrough(); expect(toJson({})).toEqual('{}'); expect(spy).toHaveBeenCalled(); }); it('should format objects pretty', function() { expect(toJson({a: 1, b: 2}, true)). toBeOneOf('{\n "a": 1,\n "b": 2\n}', '{\n "a":1,\n "b":2\n}'); expect(toJson({a: {b: 2}}, true)). toBeOneOf('{\n "a": {\n "b": 2\n }\n}', '{\n "a":{\n "b":2\n }\n}'); }); it('should not serialize properties starting with $', function() { expect(toJson({$few: 'v', $$some:'value'}, false)).toEqual('{}'); }); it('should not serialize $window object', function() { expect(toJson(window)).toEqual('"$WINDOW"'); }); it('should not serialize $document object', function() { expect(toJson(document)).toEqual('"$DOCUMENT"'); }); it('should not serialize scope instances', inject(function($rootScope) { expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}'); })); }); });
Java
<!-- @license Copyright (c) 2016 The Jviz Project Authors. All rights reserved. The Jviz Project is under the MIT License. See https://github.com/jviz/jviz/blob/dev/LICENSE --> <!-- Import components --> <link rel="import" href="../../../polymer/polymer.html"> <link rel="import" href="../../../jviz-styles/jviz-styles.html"> <!-- Import jviz elements --> <link rel="import" href="../../jviz.html"> <link rel="import" href="../jviz-btn/jviz-btn.html"> <link rel="import" href="../jviz-input/jviz-input.html"> <link rel="import" href="../jviz-select/jviz-select.html"> <!-- Import table components --> <link rel="import" href="./jviz-table-column.html"> <!-- Table component --> <dom-module id="jviz-table"> <template> <style> /* Main element */ :host { display: block; margin-top: 0px; margin-bottom: 10px; } /* Table header */ :host .header { display: block; } :host .header .title { @apply --jviz-heading-3; } /* Main table container */ :host .main { display: block; width: 100%; overflow-x: auto; overflow-y: auto; } /* Table element */ :host .table { display: table; min-width: 100%; table-layout: auto; @apply(--jviz-font); color: var(--jviz-navy); border-collapse: collapse; border-width: 0px; } /* Table head */ :host .head { display: table-header-group; width: 100%; position: relative; height: 40px; background-color: var(--jviz-grey-2); } /* Table head row */ :host .head .row { display: table-row; transition: all 0.3s; } /* Table head cell */ :host .head .cell { display: table-cell; transition: all 0.3s; vertical-align: top; user-select: none; -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; font-weight: bold; line-height: 24px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; cursor: pointer; padding: 10px; } :host .head .cell:first-of-type { border-top-left-radius: 5px !important; } :host .head .cell:last-of-type { border-top-right-radius: 5px !important; } :host .head .sortable { background-size: 15px 30px; background-position: right center; background-repeat: no-repeat; } :host .head .order-none { background-image: url('./img/tab_order_none.svg'); } :host .head .order-asc { background-image: url('./img/tab_order_asc.svg'); } :host .head .order-desc { background-image: url('./img/tab_order_desc.svg'); } :host .head .checkbox { width: 26px; padding-right: 10px; padding-left: 10px; padding-top: 12px; padding-bottom: 12px; } /* Table body */ :host .body { display: table-row-group; } /* Table body row */ :host .body .row { display: table-row; transition: all 0.3s; } :host .body .row:nth-child(even) { background-color: var(--jviz-grey-4); } :host .body .row:nth-child(odd) { background-color: var(--jviz-grey-3); } /* Table body cell */ :host .body .row .cell { display: table-cell; transition: all 0.3s; padding: 10px; } :host .body .row:last-of-type .cell:first-of-type { border-bottom-left-radius: 5px !important; } :host .body .row:last-of-type .cell:last-of-type { border-bottom-right-radius: 5px !important; } /* Page control */ :host .page { display: block; width: 100%; height: 30px; margin-top: 10px; margin-bottom: 10px; } :host .page .content-left { display: inline-block; float: left; } :host .page .content-right { display: inline-block; float: right; } :host .page .text { display: inline-block; height: 30px; line-height: 30px; vertical-align: top; } :host .page .text-rows { padding-right: 5px; } :host .page .text-page { padding-left: 6px; padding-right: 6px; } :host .page .space { display: inline-block; width: 15px; } </style> <!-- Columns --> <content select="jviz-table-column"></content> <div class="header"> <div class="title">{{ header }}</div> </div> <div id="main" class="main"> <!-- Table container --> <div id="table" class="table"> <!-- Table head --> <div id="head" class="head"> <div class="row"> <template is="dom-if" if="{{ selectable }}"> <div class="cell checkbox"></div> </template> <template id="headerRow" is="dom-repeat" items="{{ _columns }}"> <template is="dom-if" if="{{ item.sortable }}"> <div class="cell sortable order-none" data-key$="{{ item.key }}" data-index$="{{ item.index }}" on-tap="_tap_head_cell"> {{ item.header }} </div> </template> <template is="dom-if" if="{{ !item.sortable }}"> <div class="cell" data-key$="{{ item.key }}" data-index$="{{ item.index }}" on-tap="_tap_head_cell"> {{ item.header }} </div> </template> </template> </div> </div> <!-- Table body --> <div id="body" class="body"> <template id="bodyRow" is="dom-repeat" items="{{ _keys_displayed }}" as="row"> <div class="row"> <template is="dom-if" if="{{ selectable }}"> <div class="cell checkbox"></div> </template> <template is="dom-repeat" items="{{ _columns }}" index-as="column"> <div class="cell" data-row$="{{ row }}" data-column$="{{ column }}" on-tap="_tap_body_cell"> {{ value(row, column) }} </div> </template> </div> </template> </div> </div> </div> <!-- Page control --> <div class="page"> <div class="content-left"> <div class="text text-rows"> Showing <b>{{ _get_range_start(page, pageSize, rows) }}</b> to <b>{{ _get_range_end(page, pageSize, rows) }}</b> of <b>{{ rows }}</b> rows. </div> </div> <div class="content-right"> <div class="text text-rows">Rows per page:</div> <jviz-select id="entries" width="60px"> <option value="10">10</option> </jviz-select> <div class="space"></div> <jviz-btn color="grey" icon="chevron-left" text="Prev" on-tap="prev_page" icon-align="left"></jviz-btn> <div class="text text-page">Page <b>{{ page }}</b> of <b>{{ _page_end }}</b></div> <jviz-btn color="grey" icon="chevron-right" text="Next" on-tap="next_page" icon-align="right"></jviz-btn> </div> </div> </template> </dom-module> <!-- Table logic --> <script> //Initialize the table element var jviz_table = { is: 'jviz-table' }; //Properties jviz_table.properties = {}; //Table private properties jviz_table.properties._sort_keys = { type: Array, value: [] }; jviz_table.properties._sort_order = { type: Array, value: [] }; jviz_table.properties._columns = { type: Array, value: [] }; jviz_table.properties._keys_displayed = { type: Array, value: [] }; jviz_table.properties._keys_selected = { type: Array, value: [] }; jviz_table.properties._keys_filtered = { type: Array, value: [] }; jviz_table.properties._keys_sorted = { type: Array, value: [] }; jviz_table.properties._page_start = { type: Number, value: 1 }; jviz_table.properties._page_end = { type: Number, value: 1 }; //Table public api jviz_table.properties.selectable = { type: Boolean, reflectToAttribute: true, value: false }; jviz_table.properties.header = { type: String, reflectToAttribute: true }; jviz_table.properties.default = { type: String, reflectToAttribute: true, value: '' }; jviz_table.properties.rows = { type: Number, value: 0 }; jviz_table.properties.pageSize = { type: Number, reflectToAttribute: true, value: 10, observer: '_update_page_size' }; jviz_table.properties.page = { type: Number, reflectToAttribute: true, value: 1, observer: '_update_page' }; jviz_table.properties.pageEntries = { type: String, reflectToAttribute: true, value: '10', observer: '_update_page_entries' }; //Table public lists jviz_table.properties.columns = { type: Array, value: [], observer: '_update_columns' }; jviz_table.properties.data = { type: Array, value: [], observer: '_update_data' }; //Observers jviz_table.observers = [ '_get_pages(rows, pageSize)' ]; //Table is attached jviz_table.attached = function() { //Save this var self = this; //Save the actual columns this.columns = this.queryAllEffectiveChildren('jviz-table-column'); //Add the entries event listener this.$.entries.addEventListener('change:value', function() { //Update the page size self.pageSize = parseInt(self.$.entries.value); }); }; //Update the columns jviz_table._update_columns = function() { //Save this var self = this; //Display in console console.debug('Update columns information'); //Initialize the columns list var list = []; //Read all the columns this.columns.forEach(function(col, index) { //Check if column is visible if(col.visible === false){ return; } //Save the column information list.push({ header: col.header, key: col.key, sortable: col.sortable, index: index }); }); //Reset the columns list this._columns = list; //Update the columns images jviz.time_out(50, function() { //Update the columns images return self._images_sort(); }); }; //Update the data jviz_table._update_data = function() { //Display in console console.debug('Update data information'); //Clear the filter this._clear_filter(); //Fire the update data event var event = this.fire('update-data', { data: this.data }); //Check if the prevent default has been set if(event.defaultPrevented === false) { //Display all the data //this.display(0, this.data.length - 1); this.page = 1; } }; //Update the entries number jviz_table._update_page_entries = function(value) { //Initialize the entries list var entries = []; //Split the entries by comma value.split(',').forEach(function(el) { //Initialize the option object var obj = { value: el, text: el, selected: false }; //Save the option to the entries list entries.push(obj); }); //Update the entries values this.$.entries.options = entries; //Check the number of entries if(entries.length > 0) { //Set the page size as the first entry value this.pageSize = parseInt(entries[0].value); } }; //Update the page size jviz_table._update_page_size = function() { //Save the actual value this.$.entries.value = this.pageSize.toString(); }; //Calculate the number of pages jviz_table._get_pages = function() { //Calculate the number of pages this._page_end = this.rows / this.pageSize; //Parse the number of pages this._page_end = (Math.floor(this._page_end) === this._page_end) ? this._page_end : Math.floor(this._page_end) + 1; //Check for empty page if(this._page_end === 0){ this._page_end = 1; } //Check the actual page if(this.page === 1) { //Update the actual page this._update_page(); } else { //Reset the actual page this.page = 1; } }; //Update the actual page jviz_table._update_page = function() { //Get the start position //var start = (this.page - 1) * this.pageSize; //Get the end position //var end = (this.page) * this.pageSize - 1; //Display the data //this.display(start, end); //Draw the table this.reload(); }; //Get the start range value jviz_table._get_range_start = function() { //Return the start range value return (this.page - 1) * this.pageSize + 1; }; //Get the end range jviz_table._get_range_end = function() { //Return the end range value return Math.min(this.rows, this.page * this.pageSize); }; //Get a data value jviz_table.value = function(row_index, column_index) { //Get the column key var column_key = this.columns[column_index].key; //Get the column parse method var column_parse = this.columns[column_index].parse; //Get the real index //var index = this._keys_displayed[row_index]; //Get the data value var value = (typeof this.data[row_index][column_key] === 'undefined') ? this.default : this.data[row_index][column_key]; //Check if the parse method is defined if(column_parse) { //Parse the column data var new_value = jviz.exec(column_parse, window, value, column_key, this.data[row_index], row_index); //Check the new value if(typeof new_value !== 'undefined') { //Save the new value value = new_value; } } //Return the data value return value; }; //Display a subset of data jviz_table.display = function(start, end) { /* //Check for no start position if(typeof start !== 'number'){ var start = 0; } //Check for no end position if(typeof end !== 'number'){ var end = this.rows - 1; } //Check the start value if(start < 0){ start = 0; } //Check the end value if(end < 0){ end = 0; } //Save the start value this._row_start = Math.min(start, end); //Save the end value this._row_end = Math.max(start, end); */ //Display the data //this._display(); this.reload(); }; //Reload the table jviz_table.reload = function() { //Check if data exists if(typeof this.data !== 'object'){ return; } //Reset the displayed keys this._keys_displayed = []; //Check for no data to show if(this.data.length > 0) { //Get the computed start position //var start = Math.max(0, this._row_start); var start = this._get_range_start() - 1; //Get the computed end position //var end = Math.min(this.rows - 1, this._row_end); var end = this._get_range_end() - 1; //Display in console (debug) console.log('Draw ' + start + ' - ' + end); //Build the displayed keys array //this._keys_displayed = jviz.array.range(start, end, 1); this._keys_displayed = this._keys_sorted.slice(start, end + 1); } //Render the table //this.$.bodyRow.render(); //this._display_data(); }; //Reset all jviz_table.reset = function() { //Clear the data this.data = []; }; //Select a row jviz_table.select = function(index, notify) { }; //Select all rows jviz_table.select_all = function(notify) { }; //Deselect a row jviz_table.deselect = function(index, notify) { }; //Deselect all rows jviz_table.deselect_all = function(notify) { }; //Toggle the selection jviz_table.toggle = function() { }; //Sort the data jviz_table.sort = function(conditions) { //Save this var self = this; //Check for undefined conditions if(typeof conditions !== 'object'){ var conditions = []; } //Check if the conditions is an array if(jviz.is.array(conditions) === false){ conditions = [ conditions ]; } //Clear the sort this._clear_sort(); //Reset the sort keys //this._reset_sort(); //Read all the conditions conditions.forEach(function(el) { //Check if the key and the order is defined if(typeof el.key !== 'string' || typeof el.order !== 'string'){ return; } //Save the key value self._sort_keys.push(el.key); //Save the order value self._sort_order.push(el.order); }); //Apply the sort conditions this._apply_sort(); }; //Sort the data jviz_table._apply_sort = function() { //Save this var self = this; //Reset the keys order this._reset_sort(); //Check the sort keys if(this._sort_keys.length !== 0) { //Sort the order array this._keys_sorted.sort(function(a, b) { //Compare all keys for(var i = 0; i < self._sort_keys.length; i++) { //Get the column key var key = self._sort_keys[i]; //Get the order var order = self._sort_order[i]; //Check if que difference is numeric var numeric = !isNaN(+self.data[a][key] - +self.data[b][key]); //Get the values var value1 = (numeric === true) ? +self.data[a][key] : self.data[a][key].toLowerCase(); var value2 = (numeric === true) ? +self.data[b][key] : self.data[b][key].toLowerCase(); //Check the values if(value1 < value2) { //Check the order return (order === 'desc') ? 1 : -1; } else if(value1 > value2) { //Check the order return (order === 'desc') ? -1 : 1; } } //Default, return 0 return 0; }); } //Display the sort images this._images_sort(); //Display again the data //this._display(); this.reload(); }; //Display the sort images jviz_table._images_sort = function() { //Save this var self = this; //Iterate over all sortable and visible columns this.$.head.querySelectorAll('.sortable').forEach(function(col) { //Remove the asc order col.classList.remove('order-asc'); //Remove the desc order col.classList.remove('order-desc'); //Get the column key var key = col.dataset.key; //Get the key index in the sort array var index = self._sort_keys.indexOf(key); //Check if key exists if(index === -1) { //Add the none order col.classList.add('order-none'); } else { //Remove the order none col.classList.remove('order-none'); //Add the order col.classList.add('order-' + self._sort_order[index]); } }); }; //Reset the sort jviz_table._reset_sort = function() { //Reset the sorted keys this._keys_sorted = this._keys_filtered.concat([]); }; //Clear the sort jviz_table._clear_sort = function() { //Reset the sorted keys //this._reset_sort(); //Clear the sort keys this._sort_keys = []; //Clear the sort order this._sort_order = []; }; //Add a new sort key jviz_table._add_sort = function(key) { //Save the key this._sort_keys.push(key); //Add the order value this._sort_order.push('asc'); }; //Change the sort order for a key jviz_table._change_sort = function(key) { //Get the key index var index = this._sort_keys.indexOf(key); //Check for not found if(index === -1){ return false; } //Change the order if(this._sort_order[index] === 'asc') { //Change the order to desc this._sort_order[index] = 'desc'; } else { //Remove the item this._remove_sort(key); } }; //Remove a sort key jviz_table._remove_sort = function(key) { //Get the index var index = this._sort_keys.indexOf(key); //Check for not found if(index === -1){ return; } //Remove from the keys array this._sort_keys.splice(index, 1); //Remove from the order array this._sort_order.splice(index, 1); }; //Filter the data jviz_table.filter = function(condition) { //Save this var self = this; //Check the condition if(typeof condition !== 'function'){ return this._clear_filter(); } //Reset the filtered array this._keys_filtered = []; //Read all the data this.data.forEach(function(el, index) { //Call the condition function var valid = condition(el, index); //Check for no valid if(typeof valid === 'boolean' && valid === false){ return; } //Save the index self._keys_filtered.push(index); }); //Save the number of rows this.rows = this._keys_filtered.length; //Reset the sorted keys //this._reset_sort(); //Order again the data this._apply_sort(); }; //Clear the filters jviz_table._clear_filter = function() { //Clear the filter keys //this._keys_filtered = Array.apply(null, Array(this.data.length)).map(function(v, i){ return i; }); this._keys_filtered = jviz.array.range(0, this.data.length - 1, 1); //Save the number of rows this.rows = this._keys_filtered.length; //Reset the sorted keys this._reset_sort(); //Apply the sort conditions this._apply_sort(); }; //Clicked on a header cell jviz_table._tap_head_cell = function(e) { //Display the column index in console console.debug(e.target.dataset.key); //Get the column key value var column_key = e.target.dataset.key; //Get the column index var column_index = e.target.dataset.index; //Check if this column is sortable if(this.columns[column_index].sortable === false){ return; } //Check if exists var column_exists = this._sort_keys.indexOf(column_key) !== -1; //Check for shift key pressed if(e.detail.sourceEvent.shiftKey === true) { //Display in console console.debug('Shift pressed'); //Check if column exists if(column_exists === true) { //Display in console console.debug('Key ' + column_key + ' exists, change the order'); //Change the order this._change_sort(column_key); } else { //Display in console console.debug('Key ' + column_key + ' does not exists, adding'); //Add the new key this._add_sort(column_key); } } else { //Display in console console.debug('Shift not pressed'); //Check the number of keys sorted if(this._sort_keys.length === 0) { //Display in console console.debug('Sort is empty. Adding ' + column_key); //Add the new sort key this._add_sort(column_key); } else if(this._sort_keys.length === 1 && column_exists === true) { //Display in console console.debug('Sort key ' + column_key + ' exists, change the key order...'); //Change the key order this._change_sort(column_key); } else { //Display in console console.debug('Remove all sort keys'); //Reset the sort arrays this._clear_sort(); //Add the new sort key this._add_sort(column_key); } } //Sort the data this._apply_sort(); }; //Clicked on a body cell jviz_table._tap_body_cell = function(e) { //Get the cell div var cell = e.path[0]; //Check for undefined dataset row and column if(typeof cell.dataset.row === 'undefined' || typeof cell.dataset.column === 'undefined'){ return; } //Get the row index var row_index = parseInt(cell.dataset.row); //Get the row data var row_data = this.data[row_index]; //Get the column index var column_index = parseInt(cell.dataset.column); //Get the column key var column_key = this.columns[column_index].key; //Get the value var value = row_data[column_key]; //Emit the tap cell this.fire('tap:body:cell', { value: value, row: row_data, column: column_key, row_index: row_index, column_index: column_index }); }; //Next page jviz_table.next_page = function() { //Check the page this.page = (this._page_end <= this.page) ? this._page_end : this.page + 1; }; //Prev page jviz_table.prev_page = function() { //Check the page this.page = (this.page <= this._page_start) ? this._page_start : this.page - 1; }; //Go to the first page jviz_table.first_page = function() { //Open the first page this.page = this._page_start; }; //Go to the last page jviz_table.last_page = function() { //Open the last page this.page = this._page_end; }; //Register the table element Polymer(jviz_table); </script>
Java
/** * \file * * \brief Autogenerated API include file for the Atmel Software Framework (ASF) * * Copyright (c) 2012 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * 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. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ #ifndef ASF_H #define ASF_H /* * This file includes all API header files for the selected drivers from ASF. * Note: There might be duplicate includes required by more than one driver. * * The file is automatically generated and will be re-written when * running the ASF driver selector tool. Any changes will be discarded. */ // From module: Common SAM compiler driver #include <compiler.h> #include <status_codes.h> // From module: Generic board support #include <board.h> // From module: Generic components of unit test framework #include <unit_test/suite.h> // From module: IOPORT - General purpose I/O service #include <ioport.h> // From module: Interrupt management - SAM implementation #include <interrupt.h> // From module: PMC - Power Management Controller #include <pmc.h> #include <sleep.h> // From module: Part identification macros #include <parts.h> // From module: SAM FPU driver #include <fpu.h> // From module: SAM4E EK LED support enabled #include <led.h> // From module: SAM4E startup code #include <exceptions.h> // From module: Standard serial I/O (stdio) - SAM implementation #include <stdio_serial.h> // From module: System Clock Control - SAM4E implementation #include <sysclk.h> // From module: UART - Univ. Async Rec/Trans #include <uart.h> // From module: USART - Serial interface - SAM implementation for devices with both UART and USART #include <serial.h> // From module: USART - Univ. Syn Async Rec/Trans #include <usart.h> #endif // ASF_H
Java
package corehttp // TODO: move to IPNS const WebUIPath = "/ipfs/QmXc9raDM1M5G5fpBnVyQ71vR4gbnskwnB9iMEzBuLgvoZ" // this is a list of all past webUI paths. var WebUIPaths = []string{ WebUIPath, "/ipfs/QmenEBWcAk3tN94fSKpKFtUMwty1qNwSYw3DMDFV6cPBXA", "/ipfs/QmUnXcWZC5Ve21gUseouJsH5mLAyz5JPp8aHsg8qVUUK8e", "/ipfs/QmSDgpiHco5yXdyVTfhKxr3aiJ82ynz8V14QcGKicM3rVh", "/ipfs/QmRuvWJz1Fc8B9cTsAYANHTXqGmKR9DVfY5nvMD1uA2WQ8", "/ipfs/QmQLXHs7K98JNQdWrBB2cQLJahPhmupbDjRuH1b9ibmwVa", "/ipfs/QmXX7YRpU7nNBKfw75VG7Y1c3GwpSAGHRev67XVPgZFv9R", "/ipfs/QmXdu7HWdV6CUaUabd9q2ZeA4iHZLVyDRj3Gi4dsJsWjbr", "/ipfs/QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w", "/ipfs/QmSHDxWsMPuJQKWmVA1rB5a3NX2Eme5fPqNb63qwaqiqSp", "/ipfs/QmctngrQAt9fjpQUZr7Bx3BsXUcif52eZGTizWhvcShsjz", "/ipfs/QmS2HL9v5YeKgQkkWMvs1EMnFtUowTEdFfSSeMT4pos1e6", "/ipfs/QmR9MzChjp1MdFWik7NjEjqKQMzVmBkdK3dz14A6B5Cupm", "/ipfs/QmRyWyKWmphamkMRnJVjUTzSFSAAZowYP4rnbgnfMXC9Mr", "/ipfs/QmU3o9bvfenhTKhxUakbYrLDnZU7HezAVxPM6Ehjw9Xjqy", "/ipfs/QmPhnvn747LqwPYMJmQVorMaGbMSgA7mRRoyyZYz3DoZRQ", } var WebUIOption = RedirectOption("webui", WebUIPath)
Java
<?php /* SonataAdminBundle:CRUD:base_acl_macro.html.twig */ class __TwigTemplate_f7bb38229ed8df4e133506255cce57f53a109aac1f79d839de0cea8756a1aaf0 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 11 echo " "; } // line 12 public function getrender_form($__form__ = null, $__permissions__ = null, $__td_type__ = null, $__admin__ = null, $__admin_pool__ = null, $__object__ = null) { $context = $this->env->mergeGlobals(array( "form" => $__form__, "permissions" => $__permissions__, "td_type" => $__td_type__, "admin" => $__admin__, "admin_pool" => $__admin_pool__, "object" => $__object__, )); $blocks = array(); ob_start(); try { // line 13 echo " <form class=\"form-horizontal\" action=\""; // line 14 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "generateUrl", array(0 => "acl", 1 => array("id" => $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "id", array(0 => (isset($context["object"]) ? $context["object"] : $this->getContext($context, "object"))), "method"), "uniqid" => $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "uniqid", array()), "subclass" => $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "request", array()), "get", array(0 => "subclass"), "method"))), "method"), "html", null, true); echo "\" "; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype'); echo " method=\"POST\" "; // line 16 if ( !$this->getAttribute((isset($context["admin_pool"]) ? $context["admin_pool"] : $this->getContext($context, "admin_pool")), "getOption", array(0 => "html5_validate"), "method")) { echo "novalidate=\"novalidate\""; } // line 17 echo " > "; // line 18 if ((twig_length_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "vars", array()), "errors", array())) > 0)) { // line 19 echo " <div class=\"sonata-ba-form-error\"> "; // line 20 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors'); echo " </div> "; } // line 23 echo " <div class=\"box box-success\"> <div class=\"body table-responsive no-padding\"> <table class=\"table\"> <colgroup> <col style=\"width: 100%;\"/> "; // line 29 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions"))); foreach ($context['_seq'] as $context["_key"] => $context["permission"]) { // line 30 echo " <col/> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 32 echo " </colgroup> "; // line 34 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "children", array())); $context['loop'] = array( 'parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true, ); foreach ($context['_seq'] as $context["_key"] => $context["child"]) { if (($this->getAttribute($this->getAttribute($context["child"], "vars", array()), "name", array()) != "_token")) { // line 35 echo " "; if ((($this->getAttribute($context["loop"], "index0", array()) == 0) || (($this->getAttribute($context["loop"], "index0", array()) % 10) == 0))) { // line 36 echo " <tr> <th>"; // line 37 echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["td_type"]) ? $context["td_type"] : $this->getContext($context, "td_type")), array(), "SonataAdminBundle"), "html", null, true); echo "</th> "; // line 38 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions"))); foreach ($context['_seq'] as $context["_key"] => $context["permission"]) { // line 39 echo " <th class=\"text-right\">"; echo twig_escape_filter($this->env, $context["permission"], "html", null, true); echo "</th> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 41 echo " </tr> "; } // line 43 echo " <tr> <td> "; // line 46 $context["typeChild"] = (($this->getAttribute($context["child"], "role", array(), "array", true, true)) ? ($this->getAttribute($context["child"], "role", array(), "array")) : ($this->getAttribute($context["child"], "user", array(), "array"))); // line 47 echo " "; echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["typeChild"]) ? $context["typeChild"] : $this->getContext($context, "typeChild")), "vars", array()), "value", array()), "html", null, true); echo " "; // line 48 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["typeChild"]) ? $context["typeChild"] : $this->getContext($context, "typeChild")), 'widget'); echo " </td> "; // line 50 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions"))); foreach ($context['_seq'] as $context["_key"] => $context["permission"]) { // line 51 echo " <td class=\"text-right\">"; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($context["child"], $context["permission"], array(), "array"), 'widget', array("label" => false)); echo "</td> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 53 echo " </tr> "; ++$context['loop']['index0']; ++$context['loop']['index']; $context['loop']['first'] = false; } } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['child'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 55 echo " </table> </div> </div> "; // line 59 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "_token", array()), 'row'); echo " <div class=\"well well-small form-actions\"> <input class=\"btn btn-primary\" type=\"submit\" name=\"btn_create_and_edit\" value=\""; // line 62 echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("btn_update_acl", array(), "SonataAdminBundle"), "html", null, true); echo "\"> </div> </form> "; } catch (Exception $e) { ob_end_clean(); throw $e; } return ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset()); } public function getTemplateName() { return "SonataAdminBundle:CRUD:base_acl_macro.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 182 => 62, 176 => 59, 170 => 55, 159 => 53, 150 => 51, 146 => 50, 141 => 48, 136 => 47, 134 => 46, 129 => 43, 125 => 41, 116 => 39, 112 => 38, 108 => 37, 105 => 36, 102 => 35, 91 => 34, 87 => 32, 80 => 30, 76 => 29, 68 => 23, 62 => 20, 59 => 19, 57 => 18, 54 => 17, 50 => 16, 43 => 14, 40 => 13, 24 => 12, 19 => 11,); } }
Java
class X where foo :: Int -- | Y -- Y is something -- nice. class Y where bar :: Int
Java
/** * Logger configuration * * Configure the log level for your app, as well as the transport * (Underneath the covers, Sails uses Winston for logging, which * allows for some pretty neat custom transports/adapters for log messages) * * For more information on the Sails logger, check out: * http://sailsjs.org/#documentation */ module.exports = { // Valid `level` configs: // i.e. the minimum log level to capture with sails.log.*() // // 'error' : Display calls to `.error()` // 'warn' : Display calls from `.error()` to `.warn()` // 'debug' : Display calls from `.error()`, `.warn()` to `.debug()` // 'info' : Display calls from `.error()`, `.warn()`, `.debug()` to `.info()` // 'verbose': Display calls from `.error()`, `.warn()`, `.debug()`, `.info()` to `.verbose()` // log: { level: 'info' } };
Java
/***************************************************************************** * This file is part of the Prolog Development Tool (PDT) * * Author: Lukas Degener (among others) * WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start * Mail: pdt@lists.iai.uni-bonn.de * Copyright (C): 2004-2012, CS Dept. III, University of Bonn * * All rights reserved. This program is 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 * ****************************************************************************/ package org.cs3.prolog.connector.cterm; import org.cs3.prolog.connector.internal.cterm.parser.ASTNode; /** * Represents a Prolog string. */ public class CString extends CTerm { public CString(ASTNode node) { super(node); } }
Java
// // Created by eran on 01/04/2015. // #include <unordered_set> #include "fakeit/Invocation.hpp" namespace fakeit { struct ActualInvocationsContainer { virtual void clear() = 0; virtual ~ActualInvocationsContainer() NO_THROWS { } }; struct ActualInvocationsSource { virtual void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const = 0; virtual ~ActualInvocationsSource() NO_THROWS { } }; struct InvocationsSourceProxy : public ActualInvocationsSource { InvocationsSourceProxy(ActualInvocationsSource *inner) : _inner(inner) { } void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override { _inner->getActualInvocations(into); } private: std::shared_ptr<ActualInvocationsSource> _inner; }; struct UnverifiedInvocationsSource : public ActualInvocationsSource { UnverifiedInvocationsSource(InvocationsSourceProxy decorated) : _decorated(decorated) { } void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override { std::unordered_set<fakeit::Invocation *> all; _decorated.getActualInvocations(all); for (fakeit::Invocation *i : all) { if (!i->isVerified()) { into.insert(i); } } } private: InvocationsSourceProxy _decorated; }; struct AggregateInvocationsSource : public ActualInvocationsSource { AggregateInvocationsSource(std::vector<ActualInvocationsSource *> &sources) : _sources(sources) { } void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override { std::unordered_set<fakeit::Invocation *> tmp; for (ActualInvocationsSource *source : _sources) { source->getActualInvocations(tmp); } filter(tmp, into); } protected: bool shouldInclude(fakeit::Invocation *) const { return true; } private: std::vector<ActualInvocationsSource *> _sources; void filter(std::unordered_set<Invocation *> &source, std::unordered_set<Invocation *> &target) const { for (Invocation *i:source) { if (shouldInclude(i)) { target.insert(i); } } } }; }
Java
#!/usr/bin/python # Copyright 2014 Steven Watanabe # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE.txt or https://www.bfgroup.xyz/b2/LICENSE.txt) # Test the handling of toolset.add-requirements import BoostBuild t = BoostBuild.Tester(pass_toolset=0, ignore_toolset_requirements=False) t.write('jamroot.jam', ''' import toolset ; import errors ; rule test-rule ( properties * ) { return <define>TEST_INDIRECT_CONDITIONAL ; } toolset.add-requirements <define>TEST_MACRO <conditional>@test-rule <link>shared:<define>TEST_CONDITIONAL ; rule check-requirements ( target : sources * : properties * ) { local macros = TEST_MACRO TEST_CONDITIONAL TEST_INDIRECT_CONDITIONAL ; for local m in $(macros) { if ! <define>$(m) in $(properties) { errors.error $(m) not defined ; } } } make test : : @check-requirements ; ''') t.run_build_system() t.cleanup()
Java
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" /> <title>CellIdentityWcdma - Android SDK | Android Developers</title> <!-- STYLESHEETS --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto"> <link href="../../../assets/css/default.css" rel="stylesheet" type="text/css"> <!-- FULLSCREEN STYLESHEET --> <link href="../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen" type="text/css"> <!-- JAVASCRIPT --> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script src="../../../assets/js/android_3p-bundle.js" type="text/javascript"></script> <script type="text/javascript"> var toRoot = "../../../"; var devsite = false; </script> <script src="../../../assets/js/docs.js" type="text/javascript"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-5831155-1']); _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> </head> <body class="gc-documentation develop" itemscope itemtype="http://schema.org/Article"> <div id="doc-api-level" class="18" style="display:none"></div> <a name="top"></a> <a name="top"></a> <!-- Header --> <div id="header"> <div class="wrap" id="header-wrap"> <div class="col-3 logo"> <a href="../../../index.html"> <img src="../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" /> </a> <div class="btn-quicknav" id="btn-quicknav"> <a href="#" class="arrow-inactive">Quicknav</a> <a href="#" class="arrow-active">Quicknav</a> </div> </div> <ul class="nav-x col-9"> <li class="design"> <a href="../../../design/index.html" zh-tw-lang="設計" zh-cn-lang="设计" ru-lang="Проектирование" ko-lang="디자인" ja-lang="設計" es-lang="Diseñar" >Design</a></li> <li class="develop"><a href="../../../develop/index.html" zh-tw-lang="開發" zh-cn-lang="开发" ru-lang="Разработка" ko-lang="개발" ja-lang="開発" es-lang="Desarrollar" >Develop</a></li> <li class="distribute last"><a href="../../../distribute/index.html" zh-tw-lang="發佈" zh-cn-lang="分发" ru-lang="Распространение" ko-lang="배포" ja-lang="配布" es-lang="Distribuir" >Distribute</a></li> </ul> <!-- New Search --> <div class="menu-container"> <div class="moremenu"> <div id="more-btn"></div> </div> <div class="morehover" id="moremenu"> <div class="top"></div> <div class="mid"> <div class="header">Links</div> <ul> <li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li> <li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li> <li><a href="../../../about/index.html">About Android</a></li> </ul> <div class="header">Android Sites</div> <ul> <li><a href="http://www.android.com">Android.com</a></li> <li class="active"><a>Android Developers</a></li> <li><a href="http://source.android.com">Android Open Source Project</a></li> </ul> <br class="clearfix" /> </div> <div class="bottom"></div> </div> <div class="search" id="search-container"> <div class="search-inner"> <div id="search-btn"></div> <div class="left"></div> <form onsubmit="return submit_search()"> <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q" onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../')" onkeyup="return search_changed(event, false, '../../../')" /> </form> <div class="right"></div> <a class="close hide">close</a> <div class="left"></div> <div class="right"></div> </div> </div> <div class="search_filtered_wrapper reference"> <div class="suggest-card reference no-display"> <ul class="search_filtered"> </ul> </div> </div> <div class="search_filtered_wrapper docs"> <div class="suggest-card dummy no-display">&nbsp;</div> <div class="suggest-card develop no-display"> <ul class="search_filtered"> </ul> <div class="child-card guides no-display"> </div> <div class="child-card training no-display"> </div> </div> <div class="suggest-card design no-display"> <ul class="search_filtered"> </ul> </div> <div class="suggest-card distribute no-display"> <ul class="search_filtered"> </ul> </div> </div> </div> <!-- /New Search> <!-- Expanded quicknav --> <div id="quicknav" class="col-9"> <ul> <li class="design"> <ul> <li><a href="../../../design/index.html">Get Started</a></li> <li><a href="../../../design/style/index.html">Style</a></li> <li><a href="../../../design/patterns/index.html">Patterns</a></li> <li><a href="../../../design/building-blocks/index.html">Building Blocks</a></li> <li><a href="../../../design/downloads/index.html">Downloads</a></li> <li><a href="../../../design/videos/index.html">Videos</a></li> </ul> </li> <li class="develop"> <ul> <li><a href="../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li><a href="../../../guide/components/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li><a href="../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li><a href="../../../tools/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a> <ul><li><a href="../../../sdk/index.html">Get the SDK</a></li></ul> </li> <li><a href="../../../google/index.html">Google Services</a> </li> </ul> </li> <li class="distribute last"> <ul> <li><a href="../../../distribute/index.html">Google Play</a></li> <li><a href="../../../distribute/googleplay/publish/index.html">Publishing</a></li> <li><a href="../../../distribute/googleplay/promote/index.html">Promoting</a></li> <li><a href="../../../distribute/googleplay/quality/index.html">App Quality</a></li> <li><a href="../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li> <li><a href="../../../distribute/open.html">Open Distribution</a></li> </ul> </li> </ul> </div> <!-- /Expanded quicknav --> </div> </div> <!-- /Header --> <div id="searchResults" class="wrap" style="display:none;"> <h2 id="searchTitle">Results</h2> <div id="leftSearchControl" class="search-control">Loading...</div> </div> <!-- Secondary x-nav --> <div id="nav-x"> <div class="wrap"> <ul class="nav-x col-9 develop" style="width:100%"> <li class="training"><a href="../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li class="guide"><a href="../../../guide/components/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li class="reference"><a href="../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li class="tools"><a href="../../../tools/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a></li> <li class="google"><a href="../../../google/index.html" >Google Services</a> </li> </ul> </div> </div> <!-- /Sendondary x-nav --> <div class="wrap clearfix" id="body-content"> <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div id="devdoc-nav"> <a class="totop" href="#top" data-g-event="left-nav-top">to top</a> <div id="api-nav-header"> <div id="api-level-toggle"> <label for="apiLevelCheckbox" class="disabled">API level: </label> <div class="select-wrapper"> <select id="apiLevelSelector"> <!-- option elements added by buildApiLevelSelector() --> </select> </div> </div><!-- end toggle --> <div id="api-nav-title">Android APIs</div> </div><!-- end nav header --> <script> var SINCE_DATA = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19' ]; buildApiLevelSelector(); </script> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav" class="scroll-pane"> <ul> <li class="api apilevel-1"> <a href="../../../reference/android/package-summary.html">android</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/accessibilityservice/package-summary.html">android.accessibilityservice</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/accounts/package-summary.html">android.accounts</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/animation/package-summary.html">android.animation</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/app/package-summary.html">android.app</a></li> <li class="api apilevel-8"> <a href="../../../reference/android/app/admin/package-summary.html">android.app.admin</a></li> <li class="api apilevel-8"> <a href="../../../reference/android/app/backup/package-summary.html">android.app.backup</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/appwidget/package-summary.html">android.appwidget</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/bluetooth/package-summary.html">android.bluetooth</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/package-summary.html">android.content</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/pm/package-summary.html">android.content.pm</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/res/package-summary.html">android.content.res</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/database/package-summary.html">android.database</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/database/sqlite/package-summary.html">android.database.sqlite</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/drm/package-summary.html">android.drm</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/gesture/package-summary.html">android.gesture</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/package-summary.html">android.graphics</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/drawable/package-summary.html">android.graphics.drawable</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/drawable/shapes/package-summary.html">android.graphics.drawable.shapes</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/graphics/pdf/package-summary.html">android.graphics.pdf</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/hardware/package-summary.html">android.hardware</a></li> <li class="api apilevel-17"> <a href="../../../reference/android/hardware/display/package-summary.html">android.hardware.display</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/hardware/input/package-summary.html">android.hardware.input</a></li> <li class="api apilevel-18"> <a href="../../../reference/android/hardware/location/package-summary.html">android.hardware.location</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/hardware/usb/package-summary.html">android.hardware.usb</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/inputmethodservice/package-summary.html">android.inputmethodservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/location/package-summary.html">android.location</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/media/package-summary.html">android.media</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/media/audiofx/package-summary.html">android.media.audiofx</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/media/effect/package-summary.html">android.media.effect</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/mtp/package-summary.html">android.mtp</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/package-summary.html">android.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/http/package-summary.html">android.net.http</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/net/nsd/package-summary.html">android.net.nsd</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/net/rtp/package-summary.html">android.net.rtp</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/net/sip/package-summary.html">android.net.sip</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/wifi/package-summary.html">android.net.wifi</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/net/wifi/p2p/package-summary.html">android.net.wifi.p2p</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/net/wifi/p2p/nsd/package-summary.html">android.net.wifi.p2p.nsd</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/nfc/package-summary.html">android.nfc</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/nfc/cardemulation/package-summary.html">android.nfc.cardemulation</a></li> <li class="api apilevel-10"> <a href="../../../reference/android/nfc/tech/package-summary.html">android.nfc.tech</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/opengl/package-summary.html">android.opengl</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/os/package-summary.html">android.os</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/os/storage/package-summary.html">android.os.storage</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/preference/package-summary.html">android.preference</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/print/package-summary.html">android.print</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/print/pdf/package-summary.html">android.print.pdf</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/printservice/package-summary.html">android.printservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/provider/package-summary.html">android.provider</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/renderscript/package-summary.html">android.renderscript</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/sax/package-summary.html">android.sax</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/security/package-summary.html">android.security</a></li> <li class="api apilevel-17"> <a href="../../../reference/android/service/dreams/package-summary.html">android.service.dreams</a></li> <li class="api apilevel-18"> <a href="../../../reference/android/service/notification/package-summary.html">android.service.notification</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/service/textservice/package-summary.html">android.service.textservice</a></li> <li class="api apilevel-7"> <a href="../../../reference/android/service/wallpaper/package-summary.html">android.service.wallpaper</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/speech/package-summary.html">android.speech</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/speech/tts/package-summary.html">android.speech.tts</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v13/app/package-summary.html">android.support.v13.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/accessibilityservice/package-summary.html">android.support.v4.accessibilityservice</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/app/package-summary.html">android.support.v4.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/content/package-summary.html">android.support.v4.content</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/content/pm/package-summary.html">android.support.v4.content.pm</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/database/package-summary.html">android.support.v4.database</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/graphics/drawable/package-summary.html">android.support.v4.graphics.drawable</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/hardware/display/package-summary.html">android.support.v4.hardware.display</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/media/package-summary.html">android.support.v4.media</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/net/package-summary.html">android.support.v4.net</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/os/package-summary.html">android.support.v4.os</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/print/package-summary.html">android.support.v4.print</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/text/package-summary.html">android.support.v4.text</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/util/package-summary.html">android.support.v4.util</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/view/package-summary.html">android.support.v4.view</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/view/accessibility/package-summary.html">android.support.v4.view.accessibility</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/widget/package-summary.html">android.support.v4.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/app/package-summary.html">android.support.v7.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/appcompat/package-summary.html">android.support.v7.appcompat</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/gridlayout/package-summary.html">android.support.v7.gridlayout</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/media/package-summary.html">android.support.v7.media</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/mediarouter/package-summary.html">android.support.v7.mediarouter</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/view/package-summary.html">android.support.v7.view</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/widget/package-summary.html">android.support.v7.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v8/renderscript/package-summary.html">android.support.v8.renderscript</a></li> <li class="selected api apilevel-1"> <a href="../../../reference/android/telephony/package-summary.html">android.telephony</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/telephony/cdma/package-summary.html">android.telephony.cdma</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/telephony/gsm/package-summary.html">android.telephony.gsm</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/package-summary.html">android.test</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/mock/package-summary.html">android.test.mock</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/suitebuilder/package-summary.html">android.test.suitebuilder</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/package-summary.html">android.text</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/text/format/package-summary.html">android.text.format</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/method/package-summary.html">android.text.method</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/style/package-summary.html">android.text.style</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/util/package-summary.html">android.text.util</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/transition/package-summary.html">android.transition</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/util/package-summary.html">android.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/view/package-summary.html">android.view</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/view/accessibility/package-summary.html">android.view.accessibility</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/view/animation/package-summary.html">android.view.animation</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/view/inputmethod/package-summary.html">android.view.inputmethod</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/view/textservice/package-summary.html">android.view.textservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/webkit/package-summary.html">android.webkit</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/widget/package-summary.html">android.widget</a></li> <li class="api apilevel-1"> <a href="../../../reference/dalvik/bytecode/package-summary.html">dalvik.bytecode</a></li> <li class="api apilevel-1"> <a href="../../../reference/dalvik/system/package-summary.html">dalvik.system</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/awt/font/package-summary.html">java.awt.font</a></li> <li class="api apilevel-3"> <a href="../../../reference/java/beans/package-summary.html">java.beans</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/io/package-summary.html">java.io</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/package-summary.html">java.lang</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/annotation/package-summary.html">java.lang.annotation</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/ref/package-summary.html">java.lang.ref</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/reflect/package-summary.html">java.lang.reflect</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/math/package-summary.html">java.math</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/net/package-summary.html">java.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/package-summary.html">java.nio</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/channels/package-summary.html">java.nio.channels</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/channels/spi/package-summary.html">java.nio.channels.spi</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/charset/package-summary.html">java.nio.charset</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/charset/spi/package-summary.html">java.nio.charset.spi</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/package-summary.html">java.security</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/acl/package-summary.html">java.security.acl</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/cert/package-summary.html">java.security.cert</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/interfaces/package-summary.html">java.security.interfaces</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/spec/package-summary.html">java.security.spec</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/sql/package-summary.html">java.sql</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/text/package-summary.html">java.text</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/package-summary.html">java.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/package-summary.html">java.util.concurrent</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/atomic/package-summary.html">java.util.concurrent.atomic</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/locks/package-summary.html">java.util.concurrent.locks</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/jar/package-summary.html">java.util.jar</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/logging/package-summary.html">java.util.logging</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/prefs/package-summary.html">java.util.prefs</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/regex/package-summary.html">java.util.regex</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/zip/package-summary.html">java.util.zip</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/package-summary.html">javax.crypto</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/interfaces/package-summary.html">javax.crypto.interfaces</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/spec/package-summary.html">javax.crypto.spec</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/microedition/khronos/egl/package-summary.html">javax.microedition.khronos.egl</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/microedition/khronos/opengles/package-summary.html">javax.microedition.khronos.opengles</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/net/package-summary.html">javax.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/net/ssl/package-summary.html">javax.net.ssl</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/package-summary.html">javax.security.auth</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/callback/package-summary.html">javax.security.auth.callback</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/login/package-summary.html">javax.security.auth.login</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/x500/package-summary.html">javax.security.auth.x500</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/cert/package-summary.html">javax.security.cert</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/sql/package-summary.html">javax.sql</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/xml/package-summary.html">javax.xml</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/datatype/package-summary.html">javax.xml.datatype</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/namespace/package-summary.html">javax.xml.namespace</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/xml/parsers/package-summary.html">javax.xml.parsers</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/package-summary.html">javax.xml.transform</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/dom/package-summary.html">javax.xml.transform.dom</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/sax/package-summary.html">javax.xml.transform.sax</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/stream/package-summary.html">javax.xml.transform.stream</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/validation/package-summary.html">javax.xml.validation</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/xpath/package-summary.html">javax.xml.xpath</a></li> <li class="api apilevel-1"> <a href="../../../reference/junit/framework/package-summary.html">junit.framework</a></li> <li class="api apilevel-1"> <a href="../../../reference/junit/runner/package-summary.html">junit.runner</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/package-summary.html">org.apache.http</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/auth/package-summary.html">org.apache.http.auth</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/auth/params/package-summary.html">org.apache.http.auth.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/package-summary.html">org.apache.http.client</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/entity/package-summary.html">org.apache.http.client.entity</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/methods/package-summary.html">org.apache.http.client.methods</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/params/package-summary.html">org.apache.http.client.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/protocol/package-summary.html">org.apache.http.client.protocol</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/utils/package-summary.html">org.apache.http.client.utils</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/package-summary.html">org.apache.http.conn</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/params/package-summary.html">org.apache.http.conn.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/routing/package-summary.html">org.apache.http.conn.routing</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/scheme/package-summary.html">org.apache.http.conn.scheme</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/ssl/package-summary.html">org.apache.http.conn.ssl</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/util/package-summary.html">org.apache.http.conn.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/cookie/package-summary.html">org.apache.http.cookie</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/cookie/params/package-summary.html">org.apache.http.cookie.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/entity/package-summary.html">org.apache.http.entity</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/package-summary.html">org.apache.http.impl</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/auth/package-summary.html">org.apache.http.impl.auth</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/client/package-summary.html">org.apache.http.impl.client</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/conn/package-summary.html">org.apache.http.impl.conn</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/conn/tsccm/package-summary.html">org.apache.http.impl.conn.tsccm</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/cookie/package-summary.html">org.apache.http.impl.cookie</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/entity/package-summary.html">org.apache.http.impl.entity</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/io/package-summary.html">org.apache.http.impl.io</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/io/package-summary.html">org.apache.http.io</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/message/package-summary.html">org.apache.http.message</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/params/package-summary.html">org.apache.http.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/protocol/package-summary.html">org.apache.http.protocol</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/util/package-summary.html">org.apache.http.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/json/package-summary.html">org.json</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/w3c/dom/package-summary.html">org.w3c.dom</a></li> <li class="api apilevel-8"> <a href="../../../reference/org/w3c/dom/ls/package-summary.html">org.w3c.dom.ls</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/package-summary.html">org.xml.sax</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/ext/package-summary.html">org.xml.sax.ext</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/helpers/package-summary.html">org.xml.sax.helpers</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xmlpull/v1/package-summary.html">org.xmlpull.v1</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xmlpull/v1/sax2/package-summary.html">org.xmlpull.v1.sax2</a></li> </ul><br/> </div> <!-- end packages-nav --> </div> <!-- end resize-packages --> <div id="classes-nav" class="scroll-pane"> <ul> <li><h2>Classes</h2> <ul> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellIdentityCdma.html">CellIdentityCdma</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellIdentityGsm.html">CellIdentityGsm</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellIdentityLte.html">CellIdentityLte</a></li> <li class="selected api apilevel-18"><a href="../../../reference/android/telephony/CellIdentityWcdma.html">CellIdentityWcdma</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellInfo.html">CellInfo</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellInfoCdma.html">CellInfoCdma</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellInfoGsm.html">CellInfoGsm</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellInfoLte.html">CellInfoLte</a></li> <li class="api apilevel-18"><a href="../../../reference/android/telephony/CellInfoWcdma.html">CellInfoWcdma</a></li> <li class="api apilevel-1"><a href="../../../reference/android/telephony/CellLocation.html">CellLocation</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellSignalStrength.html">CellSignalStrength</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellSignalStrengthCdma.html">CellSignalStrengthCdma</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellSignalStrengthGsm.html">CellSignalStrengthGsm</a></li> <li class="api apilevel-17"><a href="../../../reference/android/telephony/CellSignalStrengthLte.html">CellSignalStrengthLte</a></li> <li class="api apilevel-18"><a href="../../../reference/android/telephony/CellSignalStrengthWcdma.html">CellSignalStrengthWcdma</a></li> <li class="api apilevel-3"><a href="../../../reference/android/telephony/NeighboringCellInfo.html">NeighboringCellInfo</a></li> <li class="api apilevel-1"><a href="../../../reference/android/telephony/PhoneNumberFormattingTextWatcher.html">PhoneNumberFormattingTextWatcher</a></li> <li class="api apilevel-1"><a href="../../../reference/android/telephony/PhoneNumberUtils.html">PhoneNumberUtils</a></li> <li class="api apilevel-1"><a href="../../../reference/android/telephony/PhoneStateListener.html">PhoneStateListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/telephony/ServiceState.html">ServiceState</a></li> <li class="api apilevel-7"><a href="../../../reference/android/telephony/SignalStrength.html">SignalStrength</a></li> <li class="api apilevel-4"><a href="../../../reference/android/telephony/SmsManager.html">SmsManager</a></li> <li class="api apilevel-4"><a href="../../../reference/android/telephony/SmsMessage.html">SmsMessage</a></li> <li class="api apilevel-4"><a href="../../../reference/android/telephony/SmsMessage.SubmitPdu.html">SmsMessage.SubmitPdu</a></li> <li class="api apilevel-1"><a href="../../../reference/android/telephony/TelephonyManager.html">TelephonyManager</a></li> </ul> </li> <li><h2>Enums</h2> <ul> <li class="api apilevel-4"><a href="../../../reference/android/telephony/SmsMessage.MessageClass.html">SmsMessage.MessageClass</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none" class="scroll-pane"> <div id="tree-list"></div> </div><!-- end nav-tree --> </div><!-- end swapper --> <div id="nav-swap"> <a class="fullscreen">fullscreen</a> <a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a> </div> </div> <!-- end devdoc-nav --> </div> <!-- end side-nav --> <script type="text/javascript"> // init fullscreen based on user pref var fullscreen = readCookie("fullscreen"); if (fullscreen != 0) { if (fullscreen == "false") { toggleFullscreen(false); } else { toggleFullscreen(true); } } // init nav version for mobile if (isMobile) { swapNav(); // tree view should be used on mobile $('#nav-swap').hide(); } else { chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../"); } } // scroll the selected page into view $(document).ready(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); </script> <div class="col-12" id="doc-col"> <div id="api-info-block"> <div class="sum-details-links"> Summary: <a href="#inhconstants">Inherited Constants</a> &#124; <a href="#lfields">Fields</a> &#124; <a href="#pubmethods">Methods</a> &#124; <a href="#inhmethods">Inherited Methods</a> &#124; <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a> </div><!-- end sum-details-links --> <div class="api-level"> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a> </div> </div><!-- end api-info-block --> <!-- ======== START OF CLASS DATA ======== --> <div id="jd-header"> public final class <h1 itemprop="name">CellIdentityWcdma</h1> extends <a href="../../../reference/java/lang/Object.html">Object</a><br/> implements <a href="../../../reference/android/os/Parcelable.html">Parcelable</a> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-18"> <table class="jd-inheritance-table"> <tr> <td colspan="2" class="jd-inheritance-class-cell"><a href="../../../reference/java/lang/Object.html">java.lang.Object</a></td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="1" class="jd-inheritance-class-cell">android.telephony.CellIdentityWcdma</td> </tr> </table> <div class="jd-descr"> <h2>Class Overview</h2> <p itemprop="articleBody">CellIdentity to represent a unique UMTS cell </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <table id="inhconstants" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Constants</div></th></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-constants-android.os.Parcelable" class="jd-expando-trigger closed" ><img id="inherited-constants-android.os.Parcelable-trigger" src="../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a>From interface <a href="../../../reference/android/os/Parcelable.html">android.os.Parcelable</a> <div id="inherited-constants-android.os.Parcelable"> <div id="inherited-constants-android.os.Parcelable-list" class="jd-inheritedlinks"> </div> <div id="inherited-constants-android.os.Parcelable-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-1" > <td class="jd-typecol">int</td> <td class="jd-linkcol"><a href="../../../reference/android/os/Parcelable.html#CONTENTS_FILE_DESCRIPTOR">CONTENTS_FILE_DESCRIPTOR</a></td> <td class="jd-descrcol" width="100%">Bit masks for use with <code><a href="../../../reference/android/os/Parcelable.html#describeContents()">describeContents()</a></code>: each bit represents a kind of object considered to have potential special significance when marshalled.</td> </tr> <tr class=" api apilevel-1" > <td class="jd-typecol">int</td> <td class="jd-linkcol"><a href="../../../reference/android/os/Parcelable.html#PARCELABLE_WRITE_RETURN_VALUE">PARCELABLE_WRITE_RETURN_VALUE</a></td> <td class="jd-descrcol" width="100%">Flag for use with <code><a href="../../../reference/android/os/Parcelable.html#writeToParcel(android.os.Parcel, int)">writeToParcel(Parcel, int)</a></code>: the object being written is a return value, that is the result of a function such as "<code>Parcelable someFunction()</code>", "<code>void someFunction(out Parcelable)</code>", or "<code>void someFunction(inout Parcelable)</code>".</td> </tr> </table> </div> </div> </td></tr> </table> <!-- =========== FIELD SUMMARY =========== --> <table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr> <tr class="alt-color api apilevel-18" > <td class="jd-typecol"><nobr> public static final <a href="../../../reference/android/os/Parcelable.Creator.html">Creator</a>&lt;<a href="../../../reference/android/telephony/CellIdentityWcdma.html">CellIdentityWcdma</a>&gt;</nobr></td> <td class="jd-linkcol"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#CREATOR">CREATOR</a></td> <td class="jd-descrcol" width="100%">Implement the Parcelable interface </td> </tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr> <tr class="alt-color api apilevel-18" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#describeContents()">describeContents</a></span>()</nobr> <div class="jd-descrdiv">Implement the Parcelable interface </div> </td></tr> <tr class=" api apilevel-18" > <td class="jd-typecol"><nobr> boolean</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#equals(java.lang.Object)">equals</a></span>(<a href="../../../reference/java/lang/Object.html">Object</a> other)</nobr> <div class="jd-descrdiv">Compares this instance with the specified object and indicates if they are equal.</div> </td></tr> <tr class="alt-color api apilevel-18" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getCid()">getCid</a></span>()</nobr> </td></tr> <tr class=" api apilevel-18" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getLac()">getLac</a></span>()</nobr> </td></tr> <tr class="alt-color api apilevel-18" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getMcc()">getMcc</a></span>()</nobr> </td></tr> <tr class=" api apilevel-18" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getMnc()">getMnc</a></span>()</nobr> </td></tr> <tr class="alt-color api apilevel-18" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getPsc()">getPsc</a></span>()</nobr> </td></tr> <tr class=" api apilevel-18" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#hashCode()">hashCode</a></span>()</nobr> <div class="jd-descrdiv">Returns an integer hash code for this object.</div> </td></tr> <tr class="alt-color api apilevel-18" > <td class="jd-typecol"><nobr> <a href="../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#toString()">toString</a></span>()</nobr> <div class="jd-descrdiv">Returns a string containing a concise, human-readable description of this object.</div> </td></tr> <tr class=" api apilevel-18" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#writeToParcel(android.os.Parcel, int)">writeToParcel</a></span>(<a href="../../../reference/android/os/Parcel.html">Parcel</a> dest, int flags)</nobr> <div class="jd-descrdiv">Implement the Parcelable interface </div> </td></tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="inhmethods" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Methods</div></th></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed" ><img id="inherited-methods-java.lang.Object-trigger" src="../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From class <a href="../../../reference/java/lang/Object.html">java.lang.Object</a> <div id="inherited-methods-java.lang.Object"> <div id="inherited-methods-java.lang.Object-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-java.lang.Object-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../reference/java/lang/Object.html">Object</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#clone()">clone</a></span>()</nobr> <div class="jd-descrdiv">Creates and returns a copy of this <code>Object</code>.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> boolean</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#equals(java.lang.Object)">equals</a></span>(<a href="../../../reference/java/lang/Object.html">Object</a> o)</nobr> <div class="jd-descrdiv">Compares this instance with the specified object and indicates if they are equal.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#finalize()">finalize</a></span>()</nobr> <div class="jd-descrdiv">Invoked when the garbage collector has detected that this instance is no longer reachable.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final <a href="../../../reference/java/lang/Class.html">Class</a>&lt;?&gt;</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#getClass()">getClass</a></span>()</nobr> <div class="jd-descrdiv">Returns the unique instance of <code><a href="../../../reference/java/lang/Class.html">Class</a></code> that represents this object's class.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#hashCode()">hashCode</a></span>()</nobr> <div class="jd-descrdiv">Returns an integer hash code for this object.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#notify()">notify</a></span>()</nobr> <div class="jd-descrdiv">Causes a thread which is waiting on this object's monitor (by means of calling one of the <code>wait()</code> methods) to be woken up.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#notifyAll()">notifyAll</a></span>()</nobr> <div class="jd-descrdiv">Causes all threads which are waiting on this object's monitor (by means of calling one of the <code>wait()</code> methods) to be woken up.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#toString()">toString</a></span>()</nobr> <div class="jd-descrdiv">Returns a string containing a concise, human-readable description of this object.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait()">wait</a></span>()</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait(long, int)">wait</a></span>(long millis, int nanos)</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the specified timeout expires.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait(long)">wait</a></span>(long millis)</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the specified timeout expires.</div> </td></tr> </table> </div> </div> </td></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-android.os.Parcelable" class="jd-expando-trigger closed" ><img id="inherited-methods-android.os.Parcelable-trigger" src="../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From interface <a href="../../../reference/android/os/Parcelable.html">android.os.Parcelable</a> <div id="inherited-methods-android.os.Parcelable"> <div id="inherited-methods-android.os.Parcelable-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-android.os.Parcelable-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> abstract int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/os/Parcelable.html#describeContents()">describeContents</a></span>()</nobr> <div class="jd-descrdiv">Describe the kinds of special objects contained in this Parcelable's marshalled representation.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> abstract void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/os/Parcelable.html#writeToParcel(android.os.Parcel, int)">writeToParcel</a></span>(<a href="../../../reference/android/os/Parcel.html">Parcel</a> dest, int flags)</nobr> <div class="jd-descrdiv">Flatten this object in to a Parcel.</div> </td></tr> </table> </div> </div> </td></tr> </table> </div><!-- jd-descr (summary) --> <!-- Details --> <!-- XML Attributes --> <!-- Enum Values --> <!-- Constants --> <!-- Fields --> <!-- ========= FIELD DETAIL ======== --> <h2>Fields</h2> <A NAME="CREATOR"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public static final <a href="../../../reference/android/os/Parcelable.Creator.html">Creator</a>&lt;<a href="../../../reference/android/telephony/CellIdentityWcdma.html">CellIdentityWcdma</a>&gt; </span> CREATOR </h4> <div class="api-level"> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Implement the Parcelable interface </p></div> </div> </div> <!-- Public ctors --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- Protected ctors --> <!-- ========= METHOD DETAIL ======== --> <!-- Public methdos --> <h2>Public Methods</h2> <A NAME="describeContents()"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public int </span> <span class="sympad">describeContents</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Implement the Parcelable interface </p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>a bitmask indicating the set of special object types marshalled by the Parcelable. </li></ul> </div> </div> </div> <A NAME="equals(java.lang.Object)"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public boolean </span> <span class="sympad">equals</span> <span class="normal">(<a href="../../../reference/java/lang/Object.html">Object</a> other)</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Compares this instance with the specified object and indicates if they are equal. In order to be equal, <code>o</code> must represent the same object as this instance using a class-specific comparison. The general contract is that this comparison should be reflexive, symmetric, and transitive. Also, no object reference other than null is equal to null. <p>The default implementation returns <code>true</code> only if <code>this == o</code>. See <a href="../../../reference/java/lang/Object.html#writing_equals">Writing a correct <code>equals</code> method</a> if you intend implementing your own <code>equals</code> method. <p>The general contract for the <code>equals</code> and <code><a href="../../../reference/java/lang/Object.html#hashCode()">hashCode()</a></code> methods is that if <code>equals</code> returns <code>true</code> for any two objects, then <code>hashCode()</code> must return the same value for these objects. This means that subclasses of <code>Object</code> usually override either both methods or neither of them.</p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Parameters</h5> <table class="jd-tagtable"> <tr> <th>other</td> <td>the object to compare this instance with.</td> </tr> </table> </div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li><code>true</code> if the specified object is equal to this <code>Object</code>; <code>false</code> otherwise.</li></ul> </div> </div> </div> <A NAME="getCid()"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public int </span> <span class="sympad">getCid</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>CID 28-bit UMTS Cell Identity described in TS 25.331, 0..268435455, Integer.MAX_VALUE if unknown </li></ul> </div> </div> </div> <A NAME="getLac()"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public int </span> <span class="sympad">getLac</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>16-bit Location Area Code, 0..65535, Integer.MAX_VALUE if unknown </li></ul> </div> </div> </div> <A NAME="getMcc()"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public int </span> <span class="sympad">getMcc</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>3-digit Mobile Country Code, 0..999, Integer.MAX_VALUE if unknown </li></ul> </div> </div> </div> <A NAME="getMnc()"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public int </span> <span class="sympad">getMnc</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>2 or 3-digit Mobile Network Code, 0..999, Integer.MAX_VALUE if unknown </li></ul> </div> </div> </div> <A NAME="getPsc()"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public int </span> <span class="sympad">getPsc</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>9-bit UMTS Primary Scrambling Code described in TS 25.331, 0..511, Integer.MAX_VALUE if unknown </li></ul> </div> </div> </div> <A NAME="hashCode()"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public int </span> <span class="sympad">hashCode</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Returns an integer hash code for this object. By contract, any two objects for which <code><a href="../../../reference/java/lang/Object.html#equals(java.lang.Object)">equals(Object)</a></code> returns <code>true</code> must return the same hash code value. This means that subclasses of <code>Object</code> usually override both methods or neither method. <p>Note that hash values must not change over time unless information used in equals comparisons also changes. <p>See <a href="../../../reference/java/lang/Object.html#writing_hashCode">Writing a correct <code>hashCode</code> method</a> if you intend implementing your own <code>hashCode</code> method.</p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>this object's hash code.</li></ul> </div> </div> </div> <A NAME="toString()"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public <a href="../../../reference/java/lang/String.html">String</a> </span> <span class="sympad">toString</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression: <pre> getClass().getName() + '@' + Integer.toHexString(hashCode())</pre> <p>See <a href="../../../reference/java/lang/Object.html#writing_toString">Writing a useful <code>toString</code> method</a> if you intend implementing your own <code>toString</code> method.</p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>a printable representation of this object. </li></ul> </div> </div> </div> <A NAME="writeToParcel(android.os.Parcel, int)"></A> <div class="jd-details api apilevel-18"> <h4 class="jd-details-title"> <span class="normal"> public void </span> <span class="sympad">writeToParcel</span> <span class="normal">(<a href="../../../reference/android/os/Parcel.html">Parcel</a> dest, int flags)</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Implement the Parcelable interface </p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Parameters</h5> <table class="jd-tagtable"> <tr> <th>dest</td> <td>The Parcel in which the object should be written.</td> </tr> <tr> <th>flags</td> <td>Additional flags about how the object should be written. May be 0 or <code><a href="../../../reference/android/os/Parcelable.html#PARCELABLE_WRITE_RETURN_VALUE">PARCELABLE_WRITE_RETURN_VALUE</a></code>. </td> </tr> </table> </div> </div> </div> <!-- ========= METHOD DETAIL ======== --> <!-- ========= END OF CLASS DATA ========= --> <A NAME="navbar_top"></A> <div id="footer" class="wrap" > <div id="copyright"> Except as noted, this content is licensed under <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. For details and restrictions, see the <a href="../../../license.html"> Content License</a>. </div> <div id="build_info"> Android 4.4&nbsp;r1 &mdash; <script src="../../../timestamp.js" type="text/javascript"></script> <script>document.write(BUILD_TIMESTAMP)</script> </div> <div id="footerlinks"> <p> <a href="../../../about/index.html">About Android</a>&nbsp;&nbsp;|&nbsp; <a href="../../../legal.html">Legal</a>&nbsp;&nbsp;|&nbsp; <a href="../../../support.html">Support</a> </p> </div> </div> <!-- end footer --> </div> <!-- jd-content --> </div><!-- end doc-content --> </div> <!-- end body-content --> </body> </html>
Java
/* Copyright (c) 2018 lib4j * * 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. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.lib4j.test; import java.util.HashMap; import java.util.Map; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.junit.Assert; import org.junit.ComparisonFailure; import org.lib4j.xml.dom.DOMStyle; import org.lib4j.xml.dom.DOMs; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xmlunit.builder.Input; import org.xmlunit.diff.Comparison; import org.xmlunit.diff.ComparisonListener; import org.xmlunit.diff.ComparisonResult; import org.xmlunit.diff.DOMDifferenceEngine; import org.xmlunit.diff.DifferenceEngine; public class AssertXml { private XPath newXPath() { final XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(new SimpleNamespaceContext(prefixToNamespaceURI)); return xPath; } public static AssertXml compare(final Element controlElement, final Element testElement) { final Map<String,String> prefixToNamespaceURI = new HashMap<>(); prefixToNamespaceURI.put("xsi", "http://www.w3.org/2001/XMLSchema-instance"); final NamedNodeMap attributes = controlElement.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { final Attr attribute = (Attr)attributes.item(i); if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI()) && "xmlns".equals(attribute.getPrefix())) prefixToNamespaceURI.put(attribute.getLocalName(), attribute.getNodeValue()); } return new AssertXml(prefixToNamespaceURI, controlElement, testElement); } private final Map<String,String> prefixToNamespaceURI; private final Element controlElement; private final Element testElement; private AssertXml(final Map<String,String> prefixToNamespaceURI, final Element controlElement, final Element testElement) { if (!controlElement.getPrefix().equals(testElement.getPrefix())) throw new IllegalArgumentException("Prefixes of control and test elements must be the same: " + controlElement.getPrefix() + " != " + testElement.getPrefix()); this.prefixToNamespaceURI = prefixToNamespaceURI; this.controlElement = controlElement; this.testElement = testElement; } public void addAttribute(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException { final XPathExpression expression = newXPath().compile(xpath); final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); ++i) { final Node node = nodes.item(i); if (!(node instanceof Element)) throw new UnsupportedOperationException("Only support addition of attributes to elements"); final Element target = (Element)node; final int colon = name.indexOf(':'); final String namespaceURI = colon == -1 ? node.getNamespaceURI() : node.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon)); target.setAttributeNS(namespaceURI, name, value); } } public void remove(final Element element, final String ... xpaths) throws XPathExpressionException { for (final String xpath : xpaths) { final XPathExpression expression = newXPath().compile(xpath); final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); ++i) { final Node node = nodes.item(i); if (node instanceof Attr) { final Attr attribute = (Attr)node; attribute.getOwnerElement().removeAttributeNode(attribute); } else { node.getParentNode().removeChild(node); } } } } public void replace(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException { final XPathExpression expression = newXPath().compile(xpath); final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); ++i) { final Node node = nodes.item(i); if (node instanceof Attr) { final Attr attribute = (Attr)node; if (name == null) { attribute.setValue(value); } else { final int colon = name.indexOf(':'); final String namespaceURI = colon == -1 ? attribute.getNamespaceURI() : attribute.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon)); final Element owner = attribute.getOwnerElement(); owner.removeAttributeNode(attribute); owner.setAttributeNS(namespaceURI, name, value); } } else { throw new UnsupportedOperationException("Only support replacement of attribute values"); } } } public void replace(final Element element, final String xpath, final String value) throws XPathExpressionException { replace(element, xpath, null, value); } public void assertEqual() { final String prefix = controlElement.getPrefix(); final String controlXml = DOMs.domToString(controlElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS); final String testXml = DOMs.domToString(testElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS); final Source controlSource = Input.fromString(controlXml).build(); final Source testSource = Input.fromString(testXml).build(); final DifferenceEngine diffEngine = new DOMDifferenceEngine(); diffEngine.addDifferenceListener(new ComparisonListener() { @Override public void comparisonPerformed(final Comparison comparison, final ComparisonResult result) { final String controlXPath = comparison.getControlDetails().getXPath() == null ? null : comparison.getControlDetails().getXPath().replaceAll("/([^@])", "/" + prefix + ":$1"); if (controlXPath == null || controlXPath.matches("^.*\\/@[:a-z]+$") || controlXPath.contains("text()")) return; try { Assert.assertEquals(controlXml, testXml); } catch (final ComparisonFailure e) { final StackTraceElement[] stackTrace = e.getStackTrace(); int i; for (i = 3; i < stackTrace.length; i++) if (!stackTrace[i].getClassName().startsWith("org.xmlunit.diff")) break; final StackTraceElement[] filtered = new StackTraceElement[stackTrace.length - ++i]; System.arraycopy(stackTrace, i, filtered, 0, stackTrace.length - i); e.setStackTrace(filtered); throw e; } Assert.fail(comparison.toString()); } }); diffEngine.compare(controlSource, testSource); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_66-internal) on Tue Dec 08 09:28:01 GMT 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.jena.sparql.expr.E_Lang (Apache Jena ARQ)</title> <meta name="date" content="2015-12-08"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.jena.sparql.expr.E_Lang (Apache Jena ARQ)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/jena/sparql/expr/E_Lang.html" title="class in org.apache.jena.sparql.expr">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/jena/sparql/expr/class-use/E_Lang.html" target="_top">Frames</a></li> <li><a href="E_Lang.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.jena.sparql.expr.E_Lang" class="title">Uses of Class<br>org.apache.jena.sparql.expr.E_Lang</h2> </div> <div class="classUseContainer">No usage of org.apache.jena.sparql.expr.E_Lang</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/jena/sparql/expr/E_Lang.html" title="class in org.apache.jena.sparql.expr">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/jena/sparql/expr/class-use/E_Lang.html" target="_top">Frames</a></li> <li><a href="E_Lang.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p> </body> </html>
Java
#include "src/OgreExternalTextureSourceManager.cpp" #include "src/OgreFileSystem.cpp" #include "src/OgreFont.cpp" #include "src/OgreFontManager.cpp" #include "src/OgreFrustum.cpp" #include "src/OgreGpuProgram.cpp" #include "src/OgreGpuProgramManager.cpp" #include "src/OgreGpuProgramParams.cpp" #include "src/OgreGpuProgramUsage.cpp" #include "src/OgreHardwareBufferManager.cpp" #include "src/OgreHardwareIndexBuffer.cpp" #include "src/OgreHardwareOcclusionQuery.cpp" #include "src/OgreHardwarePixelBuffer.cpp" #include "src/OgreHardwareVertexBuffer.cpp" #include "src/OgreHighLevelGpuProgram.cpp" #include "src/OgreHighLevelGpuProgramManager.cpp" #include "src/OgreImage.cpp" #include "src/OgreInstanceBatch.cpp" #include "src/OgreInstanceBatchHW.cpp" #include "src/OgreInstanceBatchHW_VTF.cpp" #include "src/OgreInstanceBatchShader.cpp" #include "src/OgreInstanceBatchVTF.cpp" #include "src/OgreInstancedGeometry.cpp" #include "src/OgreInstancedEntity.cpp" #include "src/OgreInstanceManager.cpp" #include "src/OgreKeyFrame.cpp" #include "src/OgreLight.cpp" #include "src/OgreLodStrategy.cpp" #include "src/OgreLodStrategyManager.cpp" #include "src/OgreLog.cpp" #include "src/OgreLogManager.cpp" #include "src/OgreManualObject.cpp" #include "src/OgreMaterial.cpp" #include "src/OgreMaterialManager.cpp" #include "src/OgreMaterialSerializer.cpp" #include "src/OgreMath.cpp" #include "src/OgreMatrix3.cpp" #include "src/OgreMatrix4.cpp" #include "src/OgreMemoryAllocatedObject.cpp" #include "src/OgreMemoryNedAlloc.cpp"
Java
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfWebDebugPanelPropel adds a panel to the web debug toolbar with Propel information. * * @package symfony * @subpackage debug * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id: sfWebDebugPanelPropel.class.php 27284 2010-01-28 18:34:57Z Kris.Wallsmith $ */ class sfWebDebugPanelPropel extends sfWebDebugPanel { /** * Get the title/icon for the panel * * @return string $html */ public function getTitle() { if ($sqlLogs = $this->getSqlLogs()) { return '<img src="'.$this->webDebug->getOption('image_root_path').'/database.png" alt="SQL queries" /> '.count($sqlLogs); } } /** * Get the verbal title of the panel * * @return string $title */ public function getPanelTitle() { return 'SQL queries'; } /** * Get the html content of the panel * * @return string $html */ public function getPanelContent() { return ' <div id="sfWebDebugDatabaseLogs"> <h3>Propel Version: '.Propel::VERSION.'</h3> <ol>'.implode("\n", $this->getSqlLogs()).'</ol> </div> '; } /** * Listens to debug.web.load_panels and adds this panel. */ static public function listenToAddPanelEvent(sfEvent $event) { $event->getSubject()->setPanel('db', new self($event->getSubject())); } /** * Builds the sql logs and returns them as an array. * * @return array */ protected function getSqlLogs() { $config = $this->getPropelConfiguration(); $outerGlue = $config->getParameter('debugpdo.logging.outerglue', ' | '); $innerGlue = $config->getParameter('debugpdo.logging.innerglue', ': '); $flagSlow = $config->getParameter('debugpdo.logging.details.slow.enabled', false); $threshold = $config->getParameter('debugpdo.logging.details.slow.threshold', DebugPDO::DEFAULT_SLOW_THRESHOLD); $html = array(); foreach ($this->webDebug->getLogger()->getLogs() as $log) { if ('sfPropelLogger' != $log['type']) { continue; } $details = array(); $slowQuery = false; $parts = explode($outerGlue, $log['message']); foreach ($parts as $i => $part) { // is this a key-glue-value fragment ? if (preg_match('/^(\w+)'.preg_quote($innerGlue, '/').'(.*)/', $part, $match)) { $details[] = $part; unset($parts[$i]); // check for slow query if ('time' == $match[1]) { if ($flagSlow && (float) $match[2] > $threshold) { $slowQuery = true; if ($this->getStatus() > sfLogger::NOTICE) { $this->setStatus(sfLogger::NOTICE); } } } } } // all stuff that has not been eaten by the loop should be the query string $query = join($outerGlue, $parts); $query = $this->formatSql(htmlspecialchars($query, ENT_QUOTES, sfConfig::get('sf_charset'))); $backtrace = isset($log['debug_backtrace']) && count($log['debug_backtrace']) ? '&nbsp;'.$this->getToggleableDebugStack($log['debug_backtrace']) : ''; $html[] = sprintf(' <li%s> <p class="sfWebDebugDatabaseQuery">%s</p> <div class="sfWebDebugDatabaseLogInfo">%s%s</div> </li>', $slowQuery ? ' class="sfWebDebugWarning"' : '', $query, implode(', ', $details), $backtrace ); } return $html; } /** * Returns the current PropelConfiguration. * * @return PropelConfiguration */ protected function getPropelConfiguration() { return Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT); } }
Java
# frozen_string_literal: true require_relative 'helper' describe 'Digest class' do it 'raises error with invalid digest_class' do assert_raises ArgumentError do Dalli::Client.new('foo', { expires_in: 10, digest_class: Object }) end end end
Java
using UnityEngine; using System.Collections; using System.Runtime.Serialization; namespace StrumpyShaderEditor { [DataContract(Namespace = "http://strumpy.net/ShaderEditor/")] public abstract class ChannelReference { [DataMember] private string nodeIdentifier; [DataMember] private uint channelId; public ChannelReference( string nodeIdentifier, uint channelId ) { this.nodeIdentifier = nodeIdentifier; this.channelId = channelId; } public string NodeIdentifier { get{ return nodeIdentifier; } set{ nodeIdentifier = value; } } public uint ChannelId { get{ return channelId; } } } }
Java
var partialsTemp = [ "login", "profile" ]; exports.partialRender = function (req, res) { var pageIndex = req.params[0]; if (partialsTemp.indexOf("" + pageIndex) > -1) { res.render("partials/" + pageIndex, {}); } else { res.render("common/404", {}); } };
Java
/* * The MIT License * * Copyright 2015 Eduardo Weiland. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ define(['knockout', 'grammar', 'productionrule', 'utils'], function(ko, Grammar, ProductionRule, utils) { 'use strict'; /** * Encontra todos os símbolos não-terminais inalcançáveis dentro de uma gramática. * * @param {Grammar} grammar Gramática para ser verificada. * @return {string[]} Lista de símbolos inalcançáveis. */ function findUnreachableSymbols(grammar) { var unreachable = [], nt = grammar.nonTerminalSymbols(), s = grammar.productionStartSymbol(); for (var i = 0, l = nt.length; i < l; ++i) { // Ignora símbolo de início de produção if (nt[i] === s) { continue; } var found = false; for (var j = 0, k = nt.length; j < k && !found; ++j) { if (i === j) { // Ignora produções do próprio símbolo continue; } var prods = grammar.getProductions(nt[j]); for (var x = 0, y = prods.length; x < y; ++x) { if (prods[x].indexOf(nt[i]) !== -1) { found = true; break; } } } if (!found) { unreachable.push(nt[i]); } } return unreachable; } function findSterileSymbols(grammar) { var steriles = [], rules = grammar.productionRules(); for (var i = 0, l = rules.length; i < l; ++i) { var found = false, left = rules[i].leftSide(), right = rules[i].rightSide(); for (var j = 0, k = right.length; j < k && !found; ++j) { if (right[j].indexOf(left) === -1) { found = true; break; } } if (!found) { steriles.push(left); } } return steriles; } /** * Substitui símbolos não terminais no começo de todas as produções pelas suas produções. * * @param {Grammar} grammar Gramática para ser modificada. * @return {ProductionRule[]} Regras de produção modificadas. */ function replaceStartingSymbols(grammar) { var rules = grammar.productionRules(); var nt = grammar.nonTerminalSymbols(); var s = grammar.productionStartSymbol(); for (var i = 0, l = rules.length; i < l; ++i) { var left = rules[i].leftSide(); if (left === s) { // Ignora produção inicial continue; } var prods = rules[i].rightSide(); // Não usa cache do length porque o array é modificado internamente for (var j = 0; j < prods.length; ++j) { if ( (prods[j][0] === left) || (nt.indexOf(prods[j][0]) === -1) ) { // Produção começa com o próprio símbolo não-terminal (recursivo) ou // não começa com nenhum símbolo não-terminal, ignora as substituições continue; } var otherProds = grammar.getProductions(prods[j][0]); var rest = prods[j].substr(1); for (var k = 0, m = otherProds.length; k < m; ++k) { otherProds[k] = otherProds[k] + rest; } // Remove a produção que começa com não-terminal e adiciona as novas produções no lugar prods.splice.apply(prods, [j--, 1].concat(otherProds)); } } return rules; } return { /** * Remove símbolos inúteis de uma gramática. * * @param {Grammar} grammar Gramática de entrada. * @return {Grammar} Uma nova gramática sem os simbolos inúteis. */ removeUselessSymbols: function(grammar) { var newGrammar = new Grammar(ko.toJS(grammar)); var sterile = findSterileSymbols(newGrammar), unreachable = findUnreachableSymbols(newGrammar), useless = utils.arrayUnion(sterile, unreachable), nt = newGrammar.nonTerminalSymbols(); // Remove os símbolos inalcançáveis... newGrammar.nonTerminalSymbols(utils.arrayRemove(nt, utils.arrayUnion(sterile, unreachable))); newGrammar.removeSymbolRules(useless); // .. e as produções em que eles aparecem var rules = newGrammar.productionRules(); for (var i = 0, l = rules.length; i < l; ++i) { var right = rules[i].rightSide(); for (var j = 0, m = useless.length; j < m; ++j) { for (var k = 0; k < right.length; ++k) { if (right[k].indexOf(useless[j]) !== -1) { right.splice(k--, 1); } } } rules[i].rightSide(utils.arrayUnique(right)); } newGrammar.productionRules(rules); return newGrammar; }, /** * Remove produções vazias de uma gramática. * * @param {Grammar} grammar Gramática de entrada. * @return {Grammar} Uma nova gramática sem as produções vazias. */ removeEmptyProductions: function(grammar) { var newGrammar = new Grammar(ko.toJS(grammar)); var newStart; var rules = newGrammar.productionRules(); for (var i = 0, l = rules.length; i < l; ++i) { var left = rules[i].leftSide(); var right = rules[i].rightSide(); var emptyIndex = right.indexOf(ProductionRule.EPSILON); if (emptyIndex === -1) { // Essa regra não possui produção vazia, ignora e testa a próxima continue; } if (left === newGrammar.productionStartSymbol()) { // Início de produção pode gerar sentença vazia, então trata o caso especial newStart = new ProductionRule(newGrammar, { leftSide: left + "'", rightSide: [left, ProductionRule.EPSILON] }); } // Encontra todas as outras regras que produzem esse símbolo e adiciona uma nova // produção sem esse símbolo for (var j = 0; j < l; ++j) { var rightOther = rules[j].rightSide(); for (var k = 0, m = rightOther.length; k < m; ++k) { if (rightOther[k].indexOf(left) !== -1) { rightOther.push(rightOther[k].replace(new RegExp(left, 'g'), '')); } } rules[j].rightSide(utils.arrayUnique(rightOther)); } right.splice(emptyIndex, 1); rules[i].rightSide(utils.arrayUnique(right)); } if (newStart) { rules.unshift(newStart); newGrammar.productionStartSymbol(newStart.leftSide()); newGrammar.nonTerminalSymbols([newStart.leftSide()].concat(newGrammar.nonTerminalSymbols())); } newGrammar.productionRules(rules); return newGrammar; }, /** * Fatora uma gramática. * * @param {Grammar} grammar Gramática de entrada. * @return {Grammar} Uma nova gramática fatorada. */ factor: function(grammar) { var newGrammar = new Grammar(ko.toJS(grammar)); var rules = replaceStartingSymbols(newGrammar); var newRules = []; for (var i = 0; i < rules.length; ++i) { var left = rules[i].leftSide(); var right = rules[i].rightSide(); var newRight = []; var firstSymbolGrouped = {}; // Percorre todos as produções verificando quais precisam ser fatoradas for (var j = 0, l = right.length; j < l; ++j) { if (right[j].length === 1) { // Produções com apenas um símbolo são deixadas como estão newRight.push(right[j]); } else { // Agrupa todas as produções que começam com o mesmo símbolo terminal var firstSymbol = right[j][0]; if (!firstSymbolGrouped[firstSymbol]) { firstSymbolGrouped[firstSymbol] = []; } firstSymbolGrouped[firstSymbol].push(right[j].substr(1)); } } // Adiciona a produção na mesma ordem que estava antes, antes das novas produções serem adicionadas newRules.push(rules[i]); for (var j in firstSymbolGrouped) { if (firstSymbolGrouped[j].length > 1) { // Mais de uma produção começando com o mesmo símbolo terminal var newSymbol = newGrammar.createNonTerminalSymbol(left); newRight.push(j + newSymbol); newRules.push(new ProductionRule(newGrammar, { leftSide: newSymbol, rightSide: firstSymbolGrouped[j] })); } else { // Senão, é apenas uma produção (índice 0), mantém ela no mesmo lugar newRight.push(j + firstSymbolGrouped[j][0]); } } // Atualiza as produções para o símbolo existente rules[i].rightSide(utils.arrayUnique(newRight)); } newGrammar.productionRules(newRules); return newGrammar; }, /** * Remove recursão à esquerda de uma gramática. * * @param {Grammar} grammar Gramática de entrada. * @return {Grammar} Uma nova gramática sem recursão à esquerda. */ removeLeftRecursion: function(grammar) { var newGrammar = new Grammar(ko.toJS(grammar)); var rules = newGrammar.productionRules(); var newRules = []; for (var i = 0, l = rules.length; i < l; ++i) { var left = rules[i].leftSide(); var prods = rules[i].rightSide(); var recursives = []; // Adiciona a produção na mesma ordem que estava antes, antes das nova produção ser adicionada newRules.push(rules[i]); // Não usa cache do length porque o array é modificado internamente for (var j = 0; j < prods.length; ++j) { if (prods[j][0] === left && prods[j].length > 1) { // Encontrou produção recursiva, cria uma nova regra var newSymbol = newGrammar.createNonTerminalSymbol(left); recursives.push(newSymbol); newRules.push(new ProductionRule(newGrammar, { leftSide: newSymbol, rightSide: [prods[j].substr(1) + newSymbol, ProductionRule.EPSILON] })); // Remove essa produção prods.splice(j--, 1); } } var newProds = []; if (recursives.length === 0) { newProds = prods.slice(); } else { for (var j = 0; j < prods.length; ++j) { for (var k = 0; k < recursives.length; ++k) { newProds.push(prods[j] + recursives[k]); } } } rules[i].rightSide(newProds); } newGrammar.productionRules(newRules); return newGrammar; } }; });
Java
/** * Uploader implementation - with the Connection object in ExtJS 4 * */ Ext.define('MyApp.ux.panel.upload.uploader.ExtJsUploader', { extend : 'MyApp.ux.panel.upload.uploader.AbstractXhrUploader', requires : [ 'MyApp.ux.panel.upload.data.Connection' ], config : { /** * @cfg {String} [method='PUT'] * * The HTTP method to be used. */ method : 'PUT', /** * @cfg {Ext.data.Connection} * * If set, this connection object will be used when uploading files. */ connection : null }, /** * @property * @private * * The connection object. */ conn : null, /** * @private * * Initializes and returns the connection object. * * @return {MyApp.ux.panel.upload.data.Connection} */ initConnection : function() { var conn, url = this.url; console.log('[ExtJsUploader initConnection params', this.params); if (this.connection instanceof Ext.data.Connection) { console.log('[ExtJsUploader] instanceof Connection'); conn = this.connection; } else { console.log('[ExtJsUploader] !! instanceof Connection'); if (this.params) { url = Ext.urlAppend(url, Ext.urlEncode(this.params)); } conn = Ext.create('MyApp.ux.panel.upload.data.Connection', { disableCaching : true, method : this.method, url : url, timeout : this.timeout, defaultHeaders : { 'Content-Type' : this.contentType, 'X-Requested-With' : 'XMLHttpRequest' } }); } return conn; }, /** * @protected */ initHeaders : function(item) { console.log('[ExtJsUploader] initHeaders', item); var headers = this.callParent(arguments); headers['Content-Type'] = item.getType(); return headers; }, /** * Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#uploadItem} * * @param {MyApp.ux.panel.upload.Item} * item */ uploadItem : function(item) { console.log('ExtJsUploader uploadItem', item); var file = item.getFileApiObject(); if (!file) { return; } item.setUploading(); // tony this.params = { folder : item.getRemoteFolder() }; this.conn = this.initConnection(); /* * Passing the File object directly as the "rawData" option. Specs: https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-send()-method * http://dev.w3.org/2006/webapi/FileAPI/#blob */ console.log('ExtJsUploader conn', this.conn); this.conn.request({ scope : this, headers : this.initHeaders(item), rawData : file, timeout : MyApp.Const.JAVASCRIPT_MAX_NUMBER, // tony success : Ext.Function.bind(this.onUploadSuccess, this, [ item ], true), failure : Ext.Function.bind(this.onUploadFailure, this, [ item ], true), progress : Ext.Function.bind(this.onUploadProgress, this, [ item ], true) }); }, /** * Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#abortUpload} */ abortUpload : function() { if (this.conn) { /* * If we don't suspend the events, the connection abortion will cause a failure event. */ this.suspendEvents(); console.log('abort conn', conn); this.conn.abort(); this.resumeEvents(); } } });
Java
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using NSubstitute; using Nancy; using Nancy.Routing; using PactNet.Logging; using PactNet.Mocks.MockHttpService; using PactNet.Mocks.MockHttpService.Nancy; using Xunit; namespace PactNet.Tests.Mocks.MockHttpService.Nancy { public class MockProviderNancyRequestDispatcherTests { private IMockProviderRequestHandler _mockRequestHandler; private IMockProviderAdminRequestHandler _mockAdminRequestHandler; private ILog _log; private IRequestDispatcher GetSubject() { _mockRequestHandler = Substitute.For<IMockProviderRequestHandler>(); _mockAdminRequestHandler = Substitute.For<IMockProviderAdminRequestHandler>(); _log = Substitute.For<ILog>(); return new MockProviderNancyRequestDispatcher(_mockRequestHandler, _mockAdminRequestHandler, _log, new PactConfig()); } [Fact] public void Dispatch_WithNancyContext_CallsRequestHandlerWithContext() { var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var requestDispatcher = GetSubject(); _mockRequestHandler.Handle(nancyContext).Returns(new Response()); requestDispatcher.Dispatch(nancyContext, CancellationToken.None); _mockRequestHandler.Received(1).Handle(nancyContext); } [Fact] public void Dispatch_WithNancyContextThatContainsAdminHeader_CallsAdminRequestHandlerWithContext() { var headers = new Dictionary<string, IEnumerable<string>> { { Constants.AdministrativeRequestHeaderKey, new List<string> { "true" } } }; var nancyContext = new NancyContext { Request = new Request("GET", new Url { Path = "/Test", Scheme = "HTTP" }, null, headers) }; var requestDispatcher = GetSubject(); _mockAdminRequestHandler.Handle(nancyContext).Returns(new Response()); requestDispatcher.Dispatch(nancyContext, CancellationToken.None); _mockAdminRequestHandler.Received(1).Handle(nancyContext); } [Fact] public void Dispatch_WithNullNancyContext_ArgumentExceptionIsSetOnTask() { var requestDispatcher = GetSubject(); var response = requestDispatcher.Dispatch(null, CancellationToken.None); Assert.Equal(typeof(ArgumentException), response.Exception.InnerExceptions.First().GetType()); } [Fact] public void Dispatch_WithNancyContext_SetsContextResponse() { var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var nancyResponse = new Response { StatusCode = HttpStatusCode.OK }; var requestDispatcher = GetSubject(); _mockRequestHandler.Handle(nancyContext).Returns(nancyResponse); requestDispatcher.Dispatch(nancyContext, CancellationToken.None); Assert.Equal(nancyResponse, nancyContext.Response); } [Fact] public void Dispatch_WithNancyContext_ReturnsResponse() { var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var nancyResponse = new Response { StatusCode = HttpStatusCode.OK }; var requestDispatcher = GetSubject(); _mockRequestHandler.Handle(nancyContext).Returns(nancyResponse); var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None); Assert.Equal(nancyResponse, response.Result); } [Fact] public void Dispatch_WithNancyContext_NoExceptionIsSetOnTask() { var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var nancyResponse = new Response { StatusCode = HttpStatusCode.OK }; var requestDispatcher = GetSubject(); _mockRequestHandler.Handle(nancyContext).Returns(nancyResponse); var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None); Assert.Null(response.Exception); } [Fact] public void Dispatch_WithCanceledCancellationToken_OperationCanceledExceptionIsSetOnTask() { var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var nancyResponse = new Response { StatusCode = HttpStatusCode.OK }; var cancellationToken = new CancellationToken(true); var requestDispatcher = GetSubject(); _mockRequestHandler.Handle(nancyContext).Returns(nancyResponse); var response = requestDispatcher.Dispatch(nancyContext, cancellationToken); Assert.Equal(typeof(OperationCanceledException), response.Exception.InnerExceptions.First().GetType()); } [Fact] public void Dispatch_WhenRequestHandlerThrows_InternalServerErrorResponseIsReturned() { var exception = new InvalidOperationException("Something failed."); const string expectedMessage = "Something failed. See logs for details."; var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var requestDispatcher = GetSubject(); _mockRequestHandler .When(x => x.Handle(Arg.Any<NancyContext>())) .Do(x => { throw exception; }); var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result; Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Equal(expectedMessage, response.ReasonPhrase); Assert.Equal(expectedMessage, ReadResponseContent(response)); } [Fact] public void Dispatch_WhenRequestHandlerThrowsWithMessageThatContainsSlashes_ResponseContentAndReasonPhrasesIsReturnedWithoutSlashes() { var exception = new InvalidOperationException("Something\r\n \t \\ failed."); const string expectedMessage = @"Something\r\n \t \\ failed. See logs for details."; var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var requestDispatcher = GetSubject(); _mockRequestHandler .When(x => x.Handle(Arg.Any<NancyContext>())) .Do(x => { throw exception; }); var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result; Assert.Equal(expectedMessage, response.ReasonPhrase); Assert.Equal(expectedMessage, ReadResponseContent(response)); } [Fact] public void Dispatch_WhenRequestHandlerThrows_TheExceptionIsLogged() { var exception = new InvalidOperationException("Something failed."); var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var requestDispatcher = GetSubject(); _mockRequestHandler .When(x => x.Handle(Arg.Any<NancyContext>())) .Do(x => { throw exception; }); var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result; _log.Received(1).ErrorException(Arg.Any<string>(), exception); } [Fact] public void Dispatch_WhenRequestHandlerThrowsAPactFailureException_TheExceptionIsNotLogged() { var exception = new PactFailureException("Something failed"); var nancyContext = new NancyContext { Request = new Request("GET", "/Test", "HTTP") }; var requestDispatcher = GetSubject(); _mockRequestHandler .When(x => x.Handle(Arg.Any<NancyContext>())) .Do(x => { throw exception; }); var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result; _log.DidNotReceive().ErrorException(Arg.Any<string>(), Arg.Any<Exception>()); } private string ReadResponseContent(Response response) { string content; using (var stream = new MemoryStream()) { response.Contents(stream); stream.Position = 0; using (var reader = new StreamReader(stream)) { content = reader.ReadToEnd(); } } return content; } } }
Java
class Revista<ReferenciaBase attr_reader :m_nombre_revista, :m_volumen, :m_paginas def initialize(a_autores,a_titulo,a_anio,a_nombre_revista, a_volumen, a_paginas) super(a_autores,a_titulo,a_anio) @m_nombre_revista,@m_volumen, @m_paginas = a_nombre_revista, a_volumen, a_paginas end end
Java
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M9 10v4c0 .55.45 1 1 1s1-.45 1-1V4h2v10c0 .55.45 1 1 1s1-.45 1-1V4h1c.55 0 1-.45 1-1s-.45-1-1-1H9.17C7.08 2 5.22 3.53 5.02 5.61 4.79 7.99 6.66 10 9 10zm11.65 7.65-2.79-2.79c-.32-.32-.86-.1-.86.35V17H6c-.55 0-1 .45-1 1s.45 1 1 1h11v1.79c0 .45.54.67.85.35l2.79-2.79c.2-.19.2-.51.01-.7z" }), 'FormatTextdirectionLToRRounded'); exports.default = _default;
Java
var jazz = require("../lib/jazz"); var fs = require("fs"); var data = fs.readFileSync(__dirname + "/foreach_object.jazz", "utf8"); var template = jazz.compile(data); template.eval({"doc": { "title": "First", "content": "Some content" }}, function(data) { console.log(data); });
Java
/********************************************************************** map_GoogleV2.js $Comment: provides JavaScript for Google Api V2 calls $Source :map_GoogleV2.js,v $ $InitialAuthor: guenter richter $ $InitialDate: 2011/01/03 $ $Author: guenter richter $ $Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $ Copyright (c) Guenter Richter $Log:map_GoogleV2.js,v $ **********************************************************************/ /** * @fileoverview This is the interface to the Google maps API v2 * * @author Guenter Richter guenter.richter@maptune.com * @version 0.9 */ /* ...................................................................* * global vars * * ...................................................................*/ /* ...................................................................* * Google directions * * ...................................................................*/ function __directions_handleErrors(){ var result = $("#directions-result")[0]; if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_BAD_KEY) result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code); else result.innerHTML = ("Errore sconosciuto!"); } function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) { var result = $("#directions-result")[0]; result.innerHTML = ""; gdir.loadFromWaypoints([fromAddress,toHidden], { "locale": locale, "preserveViewport":true }); } function _map_setDestinationWaypoint(marker){ if ( marker ){ var form = $("#directionsform")[0]; if ( form ){ form.to.value = marker.data.name; if ( marker.getLatLng ){ form.toHidden.value = marker.getLatLng(); } else if( marker.getVertex ){ form.toHidden.value = marker.getVertex(0); } } } } /** * Is called 'onload' to start creating the map */ function _map_loadMap(target){ var __map = null; // if google maps API v2 is loaded if ( GMap2 ){ // check if browser can handle Google Maps if ( !GBrowserIsCompatible()) { alert("sorry - your browser cannot handle Google Maps !"); return null; } __map = new GMap2(target); if ( __map ){ // configure user map interface __map.addControl(new GMapTypeControl()); // map.addControl(new GMenuMapTypeControl()); __map.addControl(new GLargeMapControl3D()); __map.addControl(new GScaleControl()); __map.addMapType(G_PHYSICAL_MAP); __map.addMapType(G_SATELLITE_3D_MAP); __map.enableDoubleClickZoom(); __map.enableScrollWheelZoom(); } } return __map; } /** * Is called to set up directions query */ function _map_addDirections(map,target){ if (map){ gdir = new GDirections(map,target); GEvent.addListener(gdir, "error", __directions_handleErrors); } } /** * Is called to set up traffic information layer */ function _map_addTrafficLayer(map,target){ /* tbd */ } /** * Is called to set event handler */ function _map_addEventListner(map,szEvent,callback,mapUp){ if (map){ GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) ); } } /** * Is called 'onunload' to clear objects */ function _map_unloadMap(map){ if (map){ GUnload(); } } // set map center and zoom // function _map_setMapExtension(map,bBox){ if (map){ var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) }; var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]), new GLatLng(bBox[3],bBox[1]) ) ); map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom); } } // get map zoom // function _map_getZoom(map){ if (map){ return map.getZoom(); } return 0; } // get map center // function _map_getCenter(map){ if (map){ return map.getCenter(); } return null; } // set map zoom // function _map_setZoom(map,nZoom){ if (map){ map.setZoom(nZoom); } } // set map center // function _map_setCenter(map,center){ if (map){ map.setCenter(center); } } // set map center and zoom // function _map_setCenterAndZoom(map,center,nZoom){ if (map){ map.setCenter(center,nZoom); } } // create custom tooltip // function _map_createMyTooltip(marker, text, padding){ var tooltip = new Tooltip(marker, text, padding); marker.tooltip = tooltip; map.addOverlay(tooltip); } function _map_createMyTooltipListener(element, tooltip){ GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip, Tooltip.prototype.show)); GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip, Tooltip.prototype.hide)); } // ----------------------------- // EOF // -----------------------------
Java
import InputValidator from "../../common/js/InputValidator.js"; import ObjectUtilities from "../../common/js/ObjectUtilities.js"; import Action from "./Action.js"; import DefaultFilters from "./DefaultFilters.js"; import InitialState from "./InitialState.js"; var Reducer = {}; Reducer.root = function(state, action) { LOGGER.debug("root() type = " + action.type); if (typeof state === 'undefined') { return new InitialState(); } var newFilters, newFilteredTableRow; switch (action.type) { case Action.REMOVE_FILTERS: newFilteredTableRow = []; newFilteredTableRow = newFilteredTableRow.concat(state.tableRows); return Object.assign( {}, state, { filteredTableRows: newFilteredTableRow, }); case Action.SET_DEFAULT_FILTERS: newFilters = DefaultFilters.create(); return Object.assign( {}, state, { filters: newFilters, }); case Action.SET_FILTERS: LOGGER.debug("Reducer filters = "); Object.getOwnPropertyNames(action.filters).forEach(function(propertyName) { LOGGER.debug(propertyName + ": " + action.filters[propertyName]); }); newFilters = Object.assign( {}, state.filters); newFilters = ObjectUtilities.merge(newFilters, action.filters); newFilteredTableRow = Reducer.filterTableRow(state.tableRows, newFilters); Reducer.saveToLocalStorage(newFilters); return Object.assign( {}, state, { filters: newFilters, filteredTableRows: newFilteredTableRow, }); case Action.TOGGLE_FILTER_SHOWN: return Object.assign( {}, state, { isFilterShown: !state.isFilterShown, }); default: LOGGER.warn("Reducer.root: Unhandled action type: " + action.type); return state; } }; Reducer.filterTableRow = function(tableRows, filters) { InputValidator.validateNotNull("tableRows", tableRows); InputValidator.validateNotNull("filters", filters); var answer = []; tableRows.forEach(function(data) { if (Reducer.passes(data, filters)) { answer.push(data); } }); return answer; }; Reducer.passes = function(data, filters) { InputValidator.validateNotNull("data", data); InputValidator.validateNotNull("filters", filters); var answer = true; var propertyNames = Object.getOwnPropertyNames(filters); for (var i = 0; i < propertyNames.length; i++) { var propertyName = propertyNames[i]; var filter = filters[propertyName]; if (!filter.passes(data)) { answer = false; break; } } return answer; }; Reducer.saveToLocalStorage = function(filters) { InputValidator.validateNotNull("filters", filters); var filterObjects = []; Object.getOwnPropertyNames(filters).forEach(function(columnKey) { var filter = filters[columnKey]; filterObjects.push(filter.toObject()); }); localStorage.filters = JSON.stringify(filterObjects); }; export default Reducer;
Java
{% extends 'layout.html' %} {% block heading %}Coming soon{% endblock %} {% block body %} {{ message }} {% endblock %} {% block footer_nav %} <li> <a href="{{ root }}">Back home</a> </li> {% endblock %}
Java
package com.github.mlk.queue.codex; import com.github.mlk.queue.Queuify; import com.github.mlk.queue.implementation.Module; public class Utf8StringModule implements Module { public static Utf8StringModule utfStrings() { return new Utf8StringModule(); } @Override public void bind(Queuify.Builder builder) { builder.encoder(new StringEncoder()) .decoder(new StringDecoder()); } }
Java
ig.module( 'plusplus.config-user' ) .defines(function() { /** * User configuration of Impact++. * <span class="alert alert-info"><strong>Tip:</strong> it is recommended to modify this configuration file!</span> * @example * // in order to add your own custom configuration to Impact++ * // edit the file defining ig.CONFIG_USER, 'plusplus/config-user.js' * // ig.CONFIG_USER is never modified by Impact++ (it is strictly for your use) * // ig.CONFIG_USER is automatically merged over Impact++'s config * @static * @readonly * @memberof ig * @namespace ig.CONFIG_USER * @author Collin Hover - collinhover.com **/ ig.CONFIG_USER = { // no need to do force entity extended checks, we won't mess it up // because we know to have our entities extend ig.EntityExtended FORCE_ENTITY_EXTENDED: false, // auto sort AUTO_SORT_LAYERS: true, // fullscreen! GAME_WIDTH_PCT: 1, GAME_HEIGHT_PCT: 1, // dynamic scaling based on dimensions in view (resolution independence) GAME_WIDTH_VIEW: 352, GAME_HEIGHT_VIEW: 208, // clamped scaling is still dynamic, but within a range // so we can't get too big or too small SCALE_MIN: 1, SCALE_MAX: 4, // camera flexibility and smoothness CAMERA: { // keep the camera within the level // (whenever possible) //KEEP_INSIDE_LEVEL: true, KEEP_CENTERED: false, LERP: 0.025, // trap helps with motion sickness BOUNDS_TRAP_AS_PCT: true, BOUNDS_TRAP_PCT_MINX: -0.2, BOUNDS_TRAP_PCT_MINY: -0.3, BOUNDS_TRAP_PCT_MAXX: 0.2, BOUNDS_TRAP_PCT_MAXY: 0.3 }, // font and text settings FONT: { MAIN_NAME: "font_helloplusplus_white_16.png", ALT_NAME: "font_helloplusplus_white_8.png", CHAT_NAME: "font_helloplusplus_black_8.png", // we can have the font be scaled relative to system SCALE_OF_SYSTEM_SCALE: 0.5, // and force a min / max SCALE_MIN: 1, SCALE_MAX: 2 }, // text bubble settings TEXT_BUBBLE: { // match the visual style PIXEL_PERFECT: true }, UI: { // sometimes, we want to keep things at a static scale // for example, UI is a possible target SCALE: 3, IGNORE_SYSTEM_SCALE: true }, /* // to try dynamic clamped UI scaling // uncomment below and delete the UI settings above UI: { SCALE_MIN: 2, SCALE_MAX: 4 } */ // UI should persist across all levels UI_LAYER_CLEAR_ON_LOAD: false, CHARACTER: { // add some depth using offset SIZE_OFFSET_X: 8, SIZE_OFFSET_Y: 4 } }; });
Java
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Jean-Baptiste Quenot, id:cactusman * 2015 Kanstantsin Shautsou * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.triggers; import antlr.ANTLRException; import com.google.common.base.Preconditions; import hudson.Extension; import hudson.Util; import hudson.console.AnnotatedLargeText; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.AdministrativeMonitor; import hudson.model.Cause; import hudson.model.CauseAction; import hudson.model.Item; import hudson.model.Run; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.util.FlushProofOutputStream; import hudson.util.FormValidation; import hudson.util.IOUtils; import hudson.util.NamingThreadFactory; import hudson.util.SequentialExecutionQueue; import hudson.util.StreamTaskListener; import hudson.util.TimeUnit2; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.charset.Charset; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.model.Jenkins; import jenkins.model.RunAction2; import jenkins.scm.SCMDecisionHandler; import jenkins.triggers.SCMTriggerItem; import jenkins.util.SystemProperties; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.apache.commons.jelly.XMLOutput; import org.jenkinsci.Symbol; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.DoNotUse; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import static java.util.logging.Level.WARNING; /** * {@link Trigger} that checks for SCM updates periodically. * * You can add UI elements under the SCM section by creating a * config.jelly or config.groovy in the resources area for * your class that inherits from SCMTrigger and has the * @{@link hudson.model.Extension} annotation. The UI should * be wrapped in an f:section element to denote it. * * @author Kohsuke Kawaguchi */ public class SCMTrigger extends Trigger<Item> { private boolean ignorePostCommitHooks; public SCMTrigger(String scmpoll_spec) throws ANTLRException { this(scmpoll_spec, false); } @DataBoundConstructor public SCMTrigger(String scmpoll_spec, boolean ignorePostCommitHooks) throws ANTLRException { super(scmpoll_spec); this.ignorePostCommitHooks = ignorePostCommitHooks; } /** * This trigger wants to ignore post-commit hooks. * <p> * SCM plugins must respect this and not run this trigger for post-commit notifications. * * @since 1.493 */ public boolean isIgnorePostCommitHooks() { return this.ignorePostCommitHooks; } @Override public void run() { if (job == null) { return; } run(null); } /** * Run the SCM trigger with additional build actions. Used by SubversionRepositoryStatus * to trigger a build at a specific revisionn number. * * @param additionalActions * @since 1.375 */ public void run(Action[] additionalActions) { if (job == null) { return; } DescriptorImpl d = getDescriptor(); LOGGER.fine("Scheduling a polling for "+job); if (d.synchronousPolling) { LOGGER.fine("Running the trigger directly without threading, " + "as it's already taken care of by Trigger.Cron"); new Runner(additionalActions).run(); } else { // schedule the polling. // even if we end up submitting this too many times, that's OK. // the real exclusion control happens inside Runner. LOGGER.fine("scheduling the trigger to (asynchronously) run"); d.queue.execute(new Runner(additionalActions)); d.clogCheck(); } } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } @Override public Collection<? extends Action> getProjectActions() { if (job == null) { return Collections.emptyList(); } return Collections.singleton(new SCMAction()); } /** * Returns the file that records the last/current polling activity. */ public File getLogFile() { return new File(job.getRootDir(),"scm-polling.log"); } @Extension @Symbol("scm") public static class DescriptorImpl extends TriggerDescriptor { private static ThreadFactory threadFactory() { return new NamingThreadFactory(Executors.defaultThreadFactory(), "SCMTrigger"); } /** * Used to control the execution of the polling tasks. * <p> * This executor implementation has a semantics suitable for polling. Namely, no two threads will try to poll the same project * at once, and multiple polling requests to the same job will be combined into one. Note that because executor isn't aware * of a potential workspace lock between a build and a polling, we may end up using executor threads unwisely --- they * may block. */ private transient final SequentialExecutionQueue queue = new SequentialExecutionQueue(Executors.newSingleThreadExecutor(threadFactory())); /** * Whether the projects should be polled all in one go in the order of dependencies. The default behavior is * that each project polls for changes independently. */ public boolean synchronousPolling = false; /** * Max number of threads for SCM polling. * 0 for unbounded. */ private int maximumThreads; public DescriptorImpl() { load(); resizeThreadPool(); } public boolean isApplicable(Item item) { return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item) != null; } public ExecutorService getExecutor() { return queue.getExecutors(); } /** * Returns true if the SCM polling thread queue has too many jobs * than it can handle. */ public boolean isClogged() { return queue.isStarving(STARVATION_THRESHOLD); } /** * Checks if the queue is clogged, and if so, * activate {@link AdministrativeMonitorImpl}. */ public void clogCheck() { AdministrativeMonitor.all().get(AdministrativeMonitorImpl.class).on = isClogged(); } /** * Gets the snapshot of {@link Runner}s that are performing polling. */ public List<Runner> getRunners() { return Util.filter(queue.getInProgress(),Runner.class); } // originally List<SCMedItem> but known to be used only for logging, in which case the instances are not actually cast to SCMedItem anyway public List<SCMTriggerItem> getItemsBeingPolled() { List<SCMTriggerItem> r = new ArrayList<SCMTriggerItem>(); for (Runner i : getRunners()) r.add(i.getTarget()); return r; } public String getDisplayName() { return Messages.SCMTrigger_DisplayName(); } /** * Gets the number of concurrent threads used for polling. * * @return * 0 if unlimited. */ public int getPollingThreadCount() { return maximumThreads; } /** * Sets the number of concurrent threads used for SCM polling and resizes the thread pool accordingly * @param n number of concurrent threads, zero or less means unlimited, maximum is 100 */ public void setPollingThreadCount(int n) { // fool proof if(n<0) n=0; if(n>100) n=100; maximumThreads = n; resizeThreadPool(); } @Restricted(NoExternalUse.class) public boolean isPollingThreadCountOptionVisible() { // unless you have a fair number of projects, this option is likely pointless. // so let's hide this option for new users to avoid confusing them // unless it was already changed // TODO switch to check for SCMTriggerItem return Jenkins.getInstance().getAllItems(AbstractProject.class).size() > 10 || getPollingThreadCount() != 0; } /** * Update the {@link ExecutorService} instance. */ /*package*/ synchronized void resizeThreadPool() { queue.setExecutors( (maximumThreads==0 ? Executors.newCachedThreadPool(threadFactory()) : Executors.newFixedThreadPool(maximumThreads, threadFactory()))); } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { String t = json.optString("pollingThreadCount",null); if(t==null || t.length()==0) setPollingThreadCount(0); else setPollingThreadCount(Integer.parseInt(t)); // Save configuration save(); return true; } public FormValidation doCheckPollingThreadCount(@QueryParameter String value) { if (value != null && "".equals(value.trim())) return FormValidation.ok(); return FormValidation.validateNonNegativeInteger(value); } } @Extension public static final class AdministrativeMonitorImpl extends AdministrativeMonitor { private boolean on; public boolean isActivated() { return on; } } /** * Associated with {@link Run} to show the polling log * that triggered that build. * * @since 1.376 */ public static class BuildAction implements RunAction2 { private transient /*final*/ Run<?,?> run; @Deprecated public transient /*final*/ AbstractBuild build; /** * @since 1.568 */ public BuildAction(Run<?,?> run) { this.run = run; build = run instanceof AbstractBuild ? (AbstractBuild) run : null; } @Deprecated public BuildAction(AbstractBuild build) { this((Run) build); } /** * @since 1.568 */ public Run<?,?> getRun() { return run; } /** * Polling log that triggered the build. */ public File getPollingLogFile() { return new File(run.getRootDir(),"polling.log"); } public String getIconFileName() { return "clipboard.png"; } public String getDisplayName() { return Messages.SCMTrigger_BuildAction_DisplayName(); } public String getUrlName() { return "pollingLog"; } /** * Sends out the raw polling log output. */ public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException { rsp.setContentType("text/plain;charset=UTF-8"); // Prevent jelly from flushing stream so Content-Length header can be added afterwards FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req)); try { getPollingLogText().writeLogTo(0, out); } finally { IOUtils.closeQuietly(out); } } public AnnotatedLargeText getPollingLogText() { return new AnnotatedLargeText<BuildAction>(getPollingLogFile(), Charset.defaultCharset(), true, this); } /** * Used from <tt>polling.jelly</tt> to write annotated polling log to the given output. */ public void writePollingLogTo(long offset, XMLOutput out) throws IOException { // TODO: resurrect compressed log file support getPollingLogText().writeHtmlTo(offset, out.asWriter()); } @Override public void onAttached(Run<?, ?> r) { // unnecessary, existing constructor does this } @Override public void onLoad(Run<?, ?> r) { run = r; build = run instanceof AbstractBuild ? (AbstractBuild) run : null; } } /** * Action object for job. Used to display the last polling log. */ public final class SCMAction implements Action { public AbstractProject<?,?> getOwner() { Item item = getItem(); return item instanceof AbstractProject ? ((AbstractProject) item) : null; } /** * @since 1.568 */ public Item getItem() { return job().asItem(); } public String getIconFileName() { return "clipboard.png"; } public String getDisplayName() { Set<SCMDescriptor<?>> descriptors = new HashSet<SCMDescriptor<?>>(); for (SCM scm : job().getSCMs()) { descriptors.add(scm.getDescriptor()); } return descriptors.size() == 1 ? Messages.SCMTrigger_getDisplayName(descriptors.iterator().next().getDisplayName()) : Messages.SCMTrigger_BuildAction_DisplayName(); } public String getUrlName() { return "scmPollLog"; } public String getLog() throws IOException { return Util.loadFile(getLogFile()); } /** * Writes the annotated log to the given output. * @since 1.350 */ public void writeLogTo(XMLOutput out) throws IOException { new AnnotatedLargeText<SCMAction>(getLogFile(),Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter()); } } private static final Logger LOGGER = Logger.getLogger(SCMTrigger.class.getName()); /** * {@link Runnable} that actually performs polling. */ public class Runner implements Runnable { /** * When did the polling start? */ private volatile long startTime; private Action[] additionalActions; public Runner() { this(null); } public Runner(Action[] actions) { Preconditions.checkNotNull(job, "Runner can't be instantiated when job is null"); if (actions == null) { additionalActions = new Action[0]; } else { additionalActions = actions; } } /** * Where the log file is written. */ public File getLogFile() { return SCMTrigger.this.getLogFile(); } /** * For which {@link Item} are we polling? * @since 1.568 */ public SCMTriggerItem getTarget() { return job(); } /** * When was this polling started? */ public long getStartTime() { return startTime; } /** * Human readable string of when this polling is started. */ public String getDuration() { return Util.getTimeSpanString(System.currentTimeMillis()-startTime); } private boolean runPolling() { try { // to make sure that the log file contains up-to-date text, // don't do buffering. StreamTaskListener listener = new StreamTaskListener(getLogFile()); try { PrintStream logger = listener.getLogger(); long start = System.currentTimeMillis(); logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date())); boolean result = job().poll(listener).hasChanges(); logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start)); if(result) logger.println("Changes found"); else logger.println("No changes"); return result; } catch (Error | RuntimeException e) { e.printStackTrace(listener.error("Failed to record SCM polling for "+job)); LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e); throw e; } finally { listener.close(); } } catch (IOException e) { LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e); return false; } } public void run() { if (job == null) { return; } // we can pre-emtively check the SCMDecisionHandler instances here // note that job().poll(listener) should also check this SCMDecisionHandler veto = SCMDecisionHandler.firstShouldPollVeto(job); if (veto != null) { try (StreamTaskListener listener = new StreamTaskListener(getLogFile())) { listener.getLogger().println( "Skipping polling on " + DateFormat.getDateTimeInstance().format(new Date()) + " due to veto from " + veto); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Failed to record SCM polling for " + job, e); } LOGGER.log(Level.FINE, "Skipping polling for {0} due to veto from {1}", new Object[]{job.getFullDisplayName(), veto} ); return; } String threadName = Thread.currentThread().getName(); Thread.currentThread().setName("SCM polling for "+job); try { startTime = System.currentTimeMillis(); if(runPolling()) { SCMTriggerItem p = job(); String name = " #"+p.getNextBuildNumber(); SCMTriggerCause cause; try { cause = new SCMTriggerCause(getLogFile()); } catch (IOException e) { LOGGER.log(WARNING, "Failed to parse the polling log",e); cause = new SCMTriggerCause(); } Action[] queueActions = new Action[additionalActions.length + 1]; queueActions[0] = new CauseAction(cause); System.arraycopy(additionalActions, 0, queueActions, 1, additionalActions.length); if (p.scheduleBuild2(p.getQuietPeriod(), queueActions) != null) { LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Triggering "+name); } else { LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Job is already in the queue"); } } } finally { Thread.currentThread().setName(threadName); } } // as per the requirement of SequentialExecutionQueue, value equality is necessary @Override public boolean equals(Object that) { return that instanceof Runner && job == ((Runner) that)._job(); } private Item _job() {return job;} @Override public int hashCode() { return job.hashCode(); } } @SuppressWarnings("deprecation") private SCMTriggerItem job() { return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job); } public static class SCMTriggerCause extends Cause { /** * Only used while ths cause is in the queue. * Once attached to the build, we'll move this into a file to reduce the memory footprint. */ private String pollingLog; private transient Run run; public SCMTriggerCause(File logFile) throws IOException { // TODO: charset of this log file? this(FileUtils.readFileToString(logFile)); } public SCMTriggerCause(String pollingLog) { this.pollingLog = pollingLog; } /** * @deprecated * Use {@link SCMTrigger.SCMTriggerCause#SCMTriggerCause(String)}. */ @Deprecated public SCMTriggerCause() { this(""); } @Override public void onLoad(Run run) { this.run = run; } @Override public void onAddedTo(Run build) { this.run = build; try { BuildAction a = new BuildAction(build); FileUtils.writeStringToFile(a.getPollingLogFile(),pollingLog); build.replaceAction(a); } catch (IOException e) { LOGGER.log(WARNING,"Failed to persist the polling log",e); } pollingLog = null; } @Override public String getShortDescription() { return Messages.SCMTrigger_SCMTriggerCause_ShortDescription(); } @Restricted(DoNotUse.class) public Run getRun() { return this.run; } @Override public boolean equals(Object o) { return o instanceof SCMTriggerCause; } @Override public int hashCode() { return 3; } } /** * How long is too long for a polling activity to be in the queue? */ public static long STARVATION_THRESHOLD = SystemProperties.getLong(SCMTrigger.class.getName()+".starvationThreshold", TimeUnit2.HOURS.toMillis(1)); }
Java
/* * The MIT License * * Copyright 2019 Karus Labs. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.karuslabs.commons.command.synchronization; import java.util.List; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerCommandSendEvent; import org.bukkit.scheduler.BukkitScheduler; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class SynchronizationTest { Synchronizer synchronizer = mock(Synchronizer.class); BukkitScheduler scheduler = mock(BukkitScheduler.class); Synchronization synchronization = new Synchronization(synchronizer, scheduler, null); PlayerCommandSendEvent event = mock(PlayerCommandSendEvent.class); @Test void add() { synchronization.add(event); assertTrue(synchronization.events.contains(event)); assertTrue(synchronization.running); verify(scheduler).scheduleSyncDelayedTask(null, synchronization); } @Test void add_duplicate() { synchronization.events.add(event); synchronization.add(event); assertTrue(synchronization.events.contains(event)); assertFalse(synchronization.running); verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization); } @Test void add_running() { synchronization.running = true; synchronization.add(event); assertTrue(synchronization.events.contains(event)); assertTrue(synchronization.running); verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization); } @Test void run() { when(event.getPlayer()).thenReturn(mock(Player.class)); when(event.getCommands()).thenReturn(List.of("a")); synchronization.add(event); synchronization.run(); verify(synchronizer).synchronize(any(Player.class), any(List.class)); assertTrue(synchronization.events.isEmpty()); assertFalse(synchronization.running); } }
Java
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>DebugAppender Constructor ()</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">DebugAppender Constructor ()</h1> </div> </div> <div id="nstext"> <p> Initializes a new instance of the <a href="log4net.Appender.DebugAppender.html">DebugAppender</a>. </p> <div class="syntax"> <span class="lang">[Visual Basic]</span> <br />Overloads Public Sub New()</div> <div class="syntax"> <span class="lang">[C#]</span> <br />public DebugAppender();</div> <h4 class="dtH4">Remarks</h4> <p> Default constructor. </p> <h4 class="dtH4">See Also</h4><p><a href="log4net.Appender.DebugAppender.html">DebugAppender Class</a> | <a href="log4net.Appender.html">log4net.Appender Namespace</a> | <a href="log4net.Appender.DebugAppenderConstructor.html">DebugAppender Constructor Overload List</a></p><hr /><div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div></div> </body> </html>
Java
--- title: Jesus är grunden för vårt vittnesbörd date: 06/09/2020 --- Som kristna har vi alla en personlig berättelse att återge, en berättelse om hur Jesus förvandlat vårt liv och vad han gjort för oss. **Läs Ef. 2:1–10. Hurdana var vi innan vi lärde känna Kristus? Vad äger vi sedan vi har tagit emot honom?** `A. Innan vi kände Kristus (Ef. 2:1–3).` `B. Efter att vi lärt känna Kristus (Ef. 2:4–10).` Vilken förunderlig förvandling! Innan vi kände Kristus var vi ”döda” genom våra överträdelser, ”levde i dem på denna tidens och världens vis”, ”följde våra mänskliga begär och handlade som kroppen och våra egna tankar ville, och av födseln var vi vredens barn”. Enkelt uttryckt: innan vi kände Kristus vandrade vi mållöst genom livet i ett förlorat tillstånd. Vi kan ha upplevt något som verkade vara lycka, men där fanns en själens ångest och en ofullbordad mening med våra liv. Att komma till Kristus och uppleva hans kärlek gjorde hela skillnaden. Nu är vi i Kristus verkligen ”levande”. ”Men Gud, som är rik på barmhärtighet, har älskat oss med så stor kärlek att fast vi var döda genom våra överträdelser har han gjort oss levande tillsammans med Kristus – av nåd är ni frälsta – och uppväckt oss med honom och gett oss en plats i himlen genom Kristus Jesus. Därmed ville han för kommande tider visa den överväldigande rika nåden i sin godhet mot oss genom Kristus Jesus” (Ef. 2:4–7). I Kristus har livet fått en ny mening och ett nytt mål. Som Johannes säger: ”I honom fanns livet, och livet var människornas ljus” (Joh. 1:4, nuB). `Läs Ef. 2:10. Vad säger det oss om hur centrala goda gärningar är för den kristna tron? Hur förstår vi den tanken i samband med frälsning genom tro ”oberoende av laggärningar” (Rom. 3:28)?` `Hur har ditt liv förändrats tack vare Jesus, en förvandling som kanske kan hjälpa någon annan att lära känna Jesus?`
Java
<?php /* * This file is part of the Omnipay package. * * (c) Adrian Macneil <adrian@adrianmacneil.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Omnipay\Common\Message; use Mockery as m; use Omnipay\TestCase; class AbstractResponseTest extends TestCase { public function testDefaultMethods() { $response = m::mock('\Omnipay\Common\Message\AbstractResponse[isSuccessful]'); $this->assertFalse($response->isRedirect()); $this->assertNull($response->getData()); $this->assertNull($response->getTransactionReference()); $this->assertNull($response->getMessage()); } }
Java
# encoding: utf-8 require 'spec_helper' describe Github::Authorization do let(:client_id) { '234jl23j4l23j4l' } let(:client_secret) { 'asasd79sdf9a7asfd7sfd97s' } let(:code) { 'c9798sdf97df98ds'} let(:site) { 'http://github-ent.example.com/' } let(:options) { {:site => site} } subject(:github) { Github.new(options) } after do reset_authentication_for(github) end context '.client' do it { is_expected.to respond_to :client } it "should return OAuth2::Client instance" do expect(github.client).to be_a OAuth2::Client end it "should assign site from the options hash" do expect(github.client.site).to eq site end it "should assign 'authorize_url" do expect(github.client.authorize_url).to eq "#{site}login/oauth/authorize" end it "should assign 'token_url" do expect(github.client.token_url).to eq "#{site}login/oauth/access_token" end end context '.auth_code' do let(:oauth) { OAuth2::Client.new(client_id, client_secret) } it "should throw an error if no client_id" do expect { github.auth_code }.to raise_error(ArgumentError) end it "should throw an error if no client_secret" do expect { github.auth_code }.to raise_error(ArgumentError) end it "should return authentication token code" do github.client_id = client_id github.client_secret = client_secret allow(github.client).to receive(:auth_code).and_return code expect(github.auth_code).to eq code end end context "authorize_url" do let(:options) { {:client_id => client_id, :client_secret => client_secret} } it { is_expected.to respond_to(:authorize_url) } it "should return address containing client_id" do expect(github.authorize_url).to match /client_id=#{client_id}/ end it "should return address containing scopes" do expect(github.authorize_url(:scope => 'user')).to match /scope=user/ end it "should return address containing redirect_uri" do expect(github.authorize_url(:redirect_uri => 'http://localhost')).to match /redirect_uri/ end end context "get_token" do let(:options) { {:client_id => client_id, :client_secret => client_secret} } before do stub_request(:post, 'https://github.com/login/oauth/access_token'). to_return(:body => '', :status => 200, :headers => {}) end it { is_expected.to respond_to(:get_token) } it "should make the authorization request" do expect { github.get_token code a_request(:post, expect("https://github.com/login/oauth/access_token")).to have_been_made }.to raise_error(OAuth2::Error) end it "should fail to get_token without authorization code" do expect { github.get_token }.to raise_error(ArgumentError) end end context ".authenticated?" do it { is_expected.to respond_to(:authenticated?) } it "should return false if falied on basic authentication" do allow(github).to receive(:basic_authed?).and_return false expect(github.authenticated?).to be false end it "should return true if basic authentication performed" do allow(github).to receive(:basic_authed?).and_return true expect(github.authenticated?).to be true end it "should return true if basic authentication performed" do allow(github).to receive(:oauth_token?).and_return true expect(github.authenticated?).to be true end end context ".basic_authed?" do before do allow(github).to receive(:basic_auth?).and_return false end it { is_expected.to respond_to(:basic_authed?) } it "should return false if login is missing" do allow(github).to receive(:login?).and_return false expect(github.basic_authed?).to be false end it "should return true if login && password provided" do allow(github).to receive(:login?).and_return true allow(github).to receive(:password?).and_return true expect(github.basic_authed?).to be true end end context "authentication" do it { is_expected.to respond_to(:authentication) } it "should return empty hash if no basic authentication params available" do allow(github).to receive(:login?).and_return false allow(github).to receive(:basic_auth?).and_return false expect(github.authentication).to be_empty end context 'basic_auth' do let(:options) { { :basic_auth => 'github:pass' } } it "should return hash with basic auth params" do expect(github.authentication).to include({login: 'github'}) expect(github.authentication).to include({password: 'pass'}) end end context 'login & password' do it "should return hash with login & password params" do options = {login: 'github', password: 'pass'} github = Github.new(options) expect(github.authentication).to be_a(Hash) expect(github.authentication).to include({login: 'github'}) expect(github.authentication).to include({password: 'pass'}) reset_authentication_for(github) end end end # authentication end # Github::Authorization
Java
require File.expand_path('../spec_helper', __FILE__) module Danger describe DangerProse do it 'is a plugin' do expect(Danger::DangerProse < Danger::Plugin).to be_truthy end describe 'with Dangerfile' do before do @dangerfile = testing_dangerfile @prose = testing_dangerfile.prose end describe 'linter' do it 'handles proselint not being installed' do allow(@prose).to receive(:`).with('which proselint').and_return('') expect(@prose.proselint_installed?).to be_falsy end it 'handles proselint being installed' do allow(@prose).to receive(:`).with('which proselint').and_return('/bin/thing/proselint') expect(@prose.proselint_installed?).to be_truthy end describe :lint_files do before do # So it doesn't try to install on your computer allow(@prose).to receive(:`).with('which proselint').and_return('/bin/thing/proselint') # Proselint returns JSON data, which is nice 👍 errors = '[{"start": 1441, "replacements": null, "end": 1445, "severity": "warning", "extent": 4, "column": 1, "message": "!!! is hyperbolic.", "line": 46, "check": "hyperbolic.misc"}]' proselint_response = '{"status" : "success", "data" : { "errors" : ' + errors + '}}' # This is where we generate our JSON allow(@prose).to receive(:`).with('proselint "spec/fixtures/blog_post.md" --json').and_return(proselint_response) # it's worth noting - you can call anything on your plugin that a Dangerfile responds to # The request source's PR JSON typically looks like # https://raw.githubusercontent.com/danger/danger/bffc246a11dac883d76fc6636319bd6c2acd58a3/spec/fixtures/pr_response.json @prose.env.request_source.pr_json = { "head" => { "ref" => 'my_fake_branch' } } end it 'handles a known JSON report from proselint' do @prose.lint_files('spec/fixtures/*.md') output = @prose.status_report[:markdowns].first # A title expect(output.message).to include('Proselint found issues') # A warning expect(output.message).to include('!!! is hyperbolic. | warning') # A link to the file inside the fixtures dir expect(output.message).to include('[spec/fixtures/blog_post.md](/artsy/eigen/tree/my_fake_branch/spec/fixtures/blog_post.md)') end end end describe 'spell checking' do it 'handles proselint not being installed' do allow(@prose).to receive(:`).with('which mdspell').and_return('') expect(@prose.mdspell_installed?).to be_falsy end it 'handles proselint being installed' do allow(@prose).to receive(:`).with('which mdspell').and_return('/bin/thing/mdspell') expect(@prose.mdspell_installed?).to be_truthy end describe 'full command' do before do # So it doesn't try to install on your computer allow(@prose).to receive(:`).with('which mdspell').and_return('/bin/thing/mdspell') # mdspell returns JSON data, which is nice 👍 proselint_response = " spec/fixtures/blog_post.md\n 1:27 | This post intentional left blank-ish.\n 4:84 | Here's a tpyo - it should registor.\n 4:101 | Here's a tpyo - it should registor.\n\n >> 3 spelling errors found in 1 file" # This is where we generate our JSON allow(@prose).to receive(:`).with('mdspell spec/fixtures/blog_post.md -r --en-gb').and_return(proselint_response) # it's worth noting - you can call anything on your plugin that a Dangerfile responds to # The request source's PR JSON typically looks like # https://raw.githubusercontent.com/danger/danger/bffc246a11dac883d76fc6636319bd6c2acd58a3/spec/fixtures/pr_response.json @prose.env.request_source.pr_json = { "head" => { "ref" => 'my_fake_branch' } } end it 'handles a known JSON report from mdspell' do @prose.check_spelling('spec/fixtures/*.md') output = @prose.status_report[:markdowns].first # A title expect(output.message).to include('Spell Checker found issues') # A typo, in bold expect(output.message).to include('**tpyo**') # A link to the file inside the fixtures dir expect(output.message).to include('[spec/fixtures/blog_post.md](/artsy/eigen/tree/my_fake_branch/spec/fixtures/blog_post.md)') end end end end end end
Java
'use strict' const path = require('path') const hbs = require('express-hbs') module.exports = function (app, express) { hbs.registerHelper('asset', require('./helpers/asset')) app.engine('hbs', hbs.express4({ partialsDir: path.resolve('app/client/views/partials'), layoutsDir: path.resolve('app/client/views/layouts'), beautify: app.locals.isProduction })) app.set('view engine', 'hbs') app.set('views', path.resolve('app/client/views')) app.use(express.static(path.resolve('app/public'))) return app }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>LCOV - result.info - c++/7.1.0/bits/stl_pair.h - functions</title> <link rel="stylesheet" type="text/css" href="../../../gcov.css"> </head> <body> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="title">LCOV - code coverage report</td></tr> <tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr> <tr> <td width="100%"> <table cellpadding=1 border=0 width="100%"> <tr> <td width="10%" class="headerItem">Current view:</td> <td width="35%" class="headerValue"><a href="../../../index.html">top level</a> - <a href="index.html">c++/7.1.0/bits</a> - stl_pair.h<span style="font-size: 80%;"> (<a href="stl_pair.h.gcov.html">source</a> / functions)</span></td> <td width="5%"></td> <td width="15%"></td> <td width="10%" class="headerCovTableHead">Hit</td> <td width="10%" class="headerCovTableHead">Total</td> <td width="15%" class="headerCovTableHead">Coverage</td> </tr> <tr> <td class="headerItem">Test:</td> <td class="headerValue">result.info</td> <td></td> <td class="headerItem">Lines:</td> <td class="headerCovTableEntry">7</td> <td class="headerCovTableEntry">7</td> <td class="headerCovTableEntryHi">100.0 %</td> </tr> <tr> <td class="headerItem">Date:</td> <td class="headerValue">2017-07-07 11:26:11</td> <td></td> <td class="headerItem">Functions:</td> <td class="headerCovTableEntry">0</td> <td class="headerCovTableEntry">0</td> <td class="headerCovTableEntryHi">-</td> </tr> <tr><td><img src="../../../glass.png" width=3 height=3 alt=""></td></tr> </table> </td> </tr> <tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr> </table> <center> <table width="60%" cellpadding=1 cellspacing=1 border=0> <tr><td><br></td></tr> <tr> <td width="80%" class="tableHead">Function Name <span class="tableHeadSort"><a href="stl_pair.h.func.html"><img src="../../../updown.png" width=10 height=14 alt="Sort by function name" title="Sort by function name" border=0></a></span></td> <td width="20%" class="tableHead">Hit count <span class="tableHeadSort"><img src="../../../glass.png" width=10 height=14 alt="Sort by hit count" title="Sort by hit count" border=0></span></td> </tr> </table> <br> </center> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr> <tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.13</a></td></tr> </table> <br> </body> </html>
Java
///////////////////////////////////////////////////////////////////////////// // Name: wx/msw/notebook.h // Purpose: MSW/GTK compatible notebook (a.k.a. property sheet) // Author: Robert Roebling // Modified by: Vadim Zeitlin for Windows version // RCS-ID: $Id$ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _NOTEBOOK_H #define _NOTEBOOK_H #if wxUSE_NOTEBOOK // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #include "wx/control.h" // ---------------------------------------------------------------------------- // wxNotebook // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxNotebookPageInfo : public wxObject { public : wxNotebookPageInfo() { m_page = NULL; m_imageId = -1; m_selected = false; } virtual ~wxNotebookPageInfo() { } void Create(wxNotebookPage *page, const wxString& text, bool selected, int imageId) { m_page = page; m_text = text; m_selected = selected; m_imageId = imageId; } wxNotebookPage* GetPage() const { return m_page; } wxString GetText() const { return m_text; } bool GetSelected() const { return m_selected; } int GetImageId() const { return m_imageId; } private: wxNotebookPage *m_page; wxString m_text; bool m_selected; int m_imageId; DECLARE_DYNAMIC_CLASS(wxNotebookPageInfo) }; WX_DECLARE_EXPORTED_LIST(wxNotebookPageInfo, wxNotebookPageInfoList ); class WXDLLIMPEXP_CORE wxNotebook : public wxNotebookBase { public: // ctors // ----- // default for dynamic class wxNotebook(); // the same arguments as for wxControl (@@@ any special styles?) wxNotebook(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxNotebookNameStr); // Create() function bool Create(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxNotebookNameStr); virtual ~wxNotebook(); // accessors // --------- // get number of pages in the dialog virtual size_t GetPageCount() const; // set the currently selected page, return the index of the previously // selected one (or -1 on error) // NB: this function will _not_ generate wxEVT_NOTEBOOK_PAGE_xxx events int SetSelection(size_t nPage); // get the currently selected page int GetSelection() const { return m_nSelection; } // changes selected page without sending events int ChangeSelection(size_t nPage); // set/get the title of a page bool SetPageText(size_t nPage, const wxString& strText); wxString GetPageText(size_t nPage) const; // image list stuff: each page may have an image associated with it. All // the images belong to an image list, so you have to // 1) create an image list // 2) associate it with the notebook // 3) set for each page it's image // associate image list with a control void SetImageList(wxImageList* imageList); // sets/returns item's image index in the current image list int GetPageImage(size_t nPage) const; bool SetPageImage(size_t nPage, int nImage); // currently it's always 1 because wxGTK doesn't support multi-row // tab controls int GetRowCount() const; // control the appearance of the notebook pages // set the size (the same for all pages) void SetPageSize(const wxSize& size); // set the padding between tabs (in pixels) void SetPadding(const wxSize& padding); // operations // ---------- // remove all pages bool DeleteAllPages(); // inserts a new page to the notebook (it will be deleted ny the notebook, // don't delete it yourself). If bSelect, this page becomes active. bool InsertPage(size_t nPage, wxNotebookPage *pPage, const wxString& strText, bool bSelect = false, int imageId = -1); void AddPageInfo( wxNotebookPageInfo* info ) { AddPage( info->GetPage() , info->GetText() , info->GetSelected() , info->GetImageId() ); } const wxNotebookPageInfoList& GetPageInfos() const; // Windows-only at present. Also, you must use the wxNB_FIXEDWIDTH // style. void SetTabSize(const wxSize& sz); // hit test virtual int HitTest(const wxPoint& pt, long *flags = NULL) const; // calculate the size of the notebook from the size of its page virtual wxSize CalcSizeFromPage(const wxSize& sizePage) const; // callbacks // --------- void OnSize(wxSizeEvent& event); void OnSelChange(wxBookCtrlEvent& event); void OnNavigationKey(wxNavigationKeyEvent& event); // base class virtuals // ------------------- virtual bool MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result); virtual bool MSWOnScroll(int orientation, WXWORD nSBCode, WXWORD pos, WXHWND control); #if wxUSE_CONSTRAINTS virtual void SetConstraintSizes(bool recurse = true); virtual bool DoPhase(int nPhase); #endif // wxUSE_CONSTRAINTS // Attempts to get colour for UX theme page background wxColour GetThemeBackgroundColour() const; // implementation only // ------------------- #if wxUSE_UXTHEME virtual bool SetBackgroundColour(const wxColour& colour) { if ( !wxNotebookBase::SetBackgroundColour(colour) ) return false; UpdateBgBrush(); return true; } // return the themed brush for painting our children virtual WXHBRUSH MSWGetBgBrushForChild(WXHDC hDC, wxWindow *child); // draw child background virtual bool MSWPrintChild(WXHDC hDC, wxWindow *win); #endif // wxUSE_UXTHEME // translate wxWin styles to the Windows ones virtual WXDWORD MSWGetStyle(long flags, WXDWORD *exstyle = NULL) const; protected: // common part of all ctors void Init(); // hides the currently shown page and shows the given one (if not -1) and // updates m_nSelection accordingly void UpdateSelection(int selNew); // remove one page from the notebook, without deleting virtual wxNotebookPage *DoRemovePage(size_t nPage); // get the page rectangle for the current notebook size // // returns empty rectangle if an error occurs, do test for it wxRect GetPageSize() const; // set the size of the given page to fit in the notebook void AdjustPageSize(wxNotebookPage *page); #if wxUSE_UXTHEME // gets the bitmap of notebook background and returns a brush from it WXHBRUSH QueryBgBitmap(); // creates the brush to be used for drawing the tab control background void UpdateBgBrush(); // common part of QueryBgBitmap() and MSWPrintChild() // // if child == NULL, draw background for the entire notebook itself bool DoDrawBackground(WXHDC hDC, wxWindow *child = NULL); #endif // wxUSE_UXTHEME // these function are only used for reducing flicker on notebook resize and // we don't need to do this for WinCE #ifndef __WXWINCE__ void OnEraseBackground(wxEraseEvent& event); void OnPaint(wxPaintEvent& event); // true if we have already subclassed our updown control bool m_hasSubclassedUpdown; #endif // __WXWINCE__ // the current selection (-1 if none) int m_nSelection; wxNotebookPageInfoList m_pageInfos; #if wxUSE_UXTHEME // background brush used to paint the tab control WXHBRUSH m_hbrBackground; #endif // wxUSE_UXTHEME DECLARE_DYNAMIC_CLASS_NO_COPY(wxNotebook) DECLARE_EVENT_TABLE() }; #endif // wxUSE_NOTEBOOK #endif // _NOTEBOOK_H
Java
// Polyfills if ( Number.EPSILON === undefined ) { Number.EPSILON = Math.pow( 2, - 52 ); } if ( Number.isInteger === undefined ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger Number.isInteger = function ( value ) { return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value; }; } // if ( Math.sign === undefined ) { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign Math.sign = function ( x ) { return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; }; } if ( 'name' in Function.prototype === false ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name Object.defineProperty( Function.prototype, 'name', { get: function () { return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ]; } } ); } if ( Object.assign === undefined ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign Object.assign = function ( target ) { 'use strict'; if ( target === undefined || target === null ) { throw new TypeError( 'Cannot convert undefined or null to object' ); } const output = Object( target ); for ( let index = 1; index < arguments.length; index ++ ) { const source = arguments[ index ]; if ( source !== undefined && source !== null ) { for ( const nextKey in source ) { if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { output[ nextKey ] = source[ nextKey ]; } } } } return output; }; }
Java
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\FlashPix; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class LockedPropertyList extends AbstractTag { protected $Id = 65538; protected $Name = 'LockedPropertyList'; protected $FullName = 'mixed'; protected $GroupName = 'FlashPix'; protected $g0 = 'FlashPix'; protected $g1 = 'FlashPix'; protected $g2 = 'Other'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Locked Property List'; }
Java
import supertest from 'supertest'; import { publicChannelName, privateChannelName } from './channel.js'; import { roleNameUsers, roleNameSubscriptions, roleScopeUsers, roleScopeSubscriptions, roleDescription } from './role.js'; import { username, email, adminUsername, adminPassword } from './user.js'; export const request = supertest('http://localhost:3000'); const prefix = '/api/v1/'; export function wait(cb, time) { return () => setTimeout(cb, time); } export const apiUsername = `api${ username }`; export const apiEmail = `api${ email }`; export const apiPublicChannelName = `api${ publicChannelName }`; export const apiPrivateChannelName = `api${ privateChannelName }`; export const apiRoleNameUsers = `api${ roleNameUsers }`; export const apiRoleNameSubscriptions = `api${ roleNameSubscriptions }`; export const apiRoleScopeUsers = `${ roleScopeUsers }`; export const apiRoleScopeSubscriptions = `${ roleScopeSubscriptions }`; export const apiRoleDescription = `api${ roleDescription }`; export const reservedWords = [ 'admin', 'administrator', 'system', 'user', ]; export const targetUser = {}; export const channel = {}; export const group = {}; export const message = {}; export const directMessage = {}; export const integration = {}; export const credentials = { 'X-Auth-Token': undefined, 'X-User-Id': undefined, }; export const login = { user: adminUsername, password: adminPassword, }; export function api(path) { return prefix + path; } export function methodCall(methodName) { return api(`method.call/${ methodName }`); } export function log(res) { console.log(res.req.path); console.log({ body: res.body, headers: res.headers, }); } export function getCredentials(done = function() {}) { request.post(api('login')) .send(login) .expect('Content-Type', 'application/json') .expect(200) .expect((res) => { credentials['X-Auth-Token'] = res.body.data.authToken; credentials['X-User-Id'] = res.body.data.userId; }) .end(done); }
Java
<?php defined('BX_DOL') or die('hack attempt'); /** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup UnaStudio UNA Studio * @{ */ define("BX_DOL_STUDIO_INSTALLER_SUCCESS", 0); define("BX_DOL_STUDIO_INSTALLER_FAILED", 1); /** * Base class for Installer classes in modules engine. * * The class contains different check functions which are used during the installation process. * An object of the class is created automatically with modules installer. * Installation/Uninstallation process can be controlled with config.php file located in [module]/install/ folder. * * * Example of usage: * refer to the BoonEx modules * * * Memberships/ACL: * Doesn't depend on user's membership. * * * Alerts: * no alerts available * */ class BxDolStudioInstaller extends BxDolInstallerUtils { protected $oDb; protected $_aConfig; protected $_sBasePath; protected $_sHomePath; protected $_sModulePath; protected $_bUseFtp; protected $_aActions; protected $_bShowOnSuccess = false; public function __construct($aConfig) { parent::__construct(); $this->oDb = bx_instance('BxDolStudioInstallerQuery'); $this->_aConfig = $aConfig; $this->_sBasePath = BX_DIRECTORY_PATH_MODULES; $this->_sHomePath = $this->_sBasePath . $aConfig['home_dir']; $this->_sModulePath = $this->_sBasePath . $aConfig['home_dir']; $this->_bUseFtp = BX_FORCE_USE_FTP_FILE_TRANSFER; $this->_aActions = array( 'perform_install' => array( 'title' => '', 'success' => _t('_adm_msg_modules_success_install'), 'failed' => '' ), 'perform_uninstall' => array( 'title' => '', 'success' => _t('_adm_msg_modules_success_uninstall'), 'failed' => '' ), 'perform_enable' => array( 'title' => '', 'success' => _t('_adm_msg_modules_success_enable'), 'failed' => '' ), 'perform_disable' => array( 'title' => '', 'success' => _t('_adm_msg_modules_success_disable'), 'failed' => '' ), 'check_script_version' => array( 'title' => _t('_adm_txt_modules_check_script_version'), ), 'check_dependencies' => array( 'title' => _t('_adm_txt_modules_check_dependencies'), ), 'show_introduction' => array( 'title' => _t('_adm_txt_modules_show_introduction'), ), 'move_sources' => array( 'title' => _t('_adm_txt_modules_move_sources'), ), 'execute_sql' => array( 'title' => _t('_adm_txt_modules_execute_sql'), ), 'install_language' => array( 'title' => _t('_adm_txt_modules_install_language'), ), 'update_languages' => array( 'title' => _t('_adm_txt_modules_update_languages'), ), 'update_relations' => array( 'title' => _t('_adm_txt_modules_update_relations'), ), 'update_relations_for_all' => array( 'title' => _t('_adm_txt_modules_update_relations_for_all'), ), 'process_connections' => array( 'title' => _t('_adm_txt_modules_process_connections'), ), 'process_deleted_profiles' => array( 'title' => _t('_adm_txt_modules_process_deleted_profiles'), ), 'process_menu_triggers' => array( 'title' => _t('_adm_txt_modules_process_menu_triggers'), ), 'process_page_triggers' => array( 'title' => _t('_adm_txt_modules_process_page_triggers'), ), 'process_storages' => array( 'title' => _t('_adm_txt_modules_process_storages'), ), 'process_esearches' => array( 'title' => _t('_adm_txt_modules_process_esearches'), ), 'register_transcoders' => array( 'title' => _t('_adm_txt_modules_register_transcoders'), ), 'unregister_transcoders' => array( 'title' => _t('_adm_txt_modules_unregister_transcoders'), ), 'clear_db_cache' => array( 'title' => _t('_adm_txt_modules_clear_db_cache'), ), 'clear_template_cache' => array( 'title' => _t('_adm_txt_modules_clear_template_cache'), ), 'show_conclusion' => array( 'title' => _t('_adm_txt_modules_show_conclusion'), ), ); $this->_aNonHashableFiles = array( 'install', 'updates' ); } public function install($aParams, $bAutoEnable = false) { //--- Auto uninstall before install ---// $this->disable($aParams); $this->uninstall($aParams); $bAutoEnable = $bAutoEnable || (isset($aParams['auto_enable']) && (bool)$aParams['auto_enable']); $bHtmlResponce = isset($aParams['html_response']) && (bool)$aParams['html_response']; //--- Check whether the module was already installed ---// if($this->oDb->isModule($this->_aConfig['home_uri'])) return array( 'message' => _t('_adm_err_modules_already_installed'), 'result' => false ); $aResult = array(); bx_alert('system', 'before_install', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult)); if ($aResult && !$aResult['result']) return $aResult; //--- Check mandatory settings ---// if($this->oDb->isModuleParamsUsed($this->_aConfig['home_uri'], $this->_aConfig['home_dir'], $this->_aConfig['db_prefix'], $this->_aConfig['class_prefix'])) return array( 'message' => _t('_adm_txt_modules_params_used'), 'result' => false ); //--- Check version compatibility ---// if(!$this->_isCompatibleWith()) return array( 'message' => $this->_displayResult('check_script_version', false, '_adm_err_modules_wrong_version_script', $bHtmlResponce), 'result' => false ); //--- Check for available translations ---// $oFile = $this->_getFileManager(); $sModuleUri = $this->_aConfig['home_uri']; $aLanguages = $this->oDb->getModulesBy(array('type' => 'languages')); foreach($aLanguages as $aLanguage) { if($aLanguage['uri'] == 'en') continue; $aLanguageConfig = self::getModuleConfig(BX_DIRECTORY_PATH_MODULES . $aLanguage['path'] . '/install/config.php'); if(empty($aLanguageConfig)) continue; if(!isset($aLanguageConfig['includes'][$sModuleUri]) || empty($aLanguageConfig['includes'][$sModuleUri])) continue; $sSrcPath = 'modules/' . $aLanguage['path'] . 'install/data/' . $aLanguageConfig['includes'][$sModuleUri]; $sDstPath = $aLanguageConfig['includes'][$sModuleUri]; $oFile->copy($sSrcPath, $sDstPath); } $aResultBefore = $this->_onInstallBefore(); if($aResultBefore !== BX_DOL_STUDIO_INSTALLER_SUCCESS) return array( 'message' => $aResultBefore['content'], 'result' => false ); //--- Check actions ---// $aResult = $this->_perform('install', $aParams); if($aResult['result']) { $iModuleId = $this->oDb->insertModule($this->_aConfig); $sTitleKey = BxDolModule::getTitleKey($this->_aConfig['home_uri']); $oLanguages = BxDolStudioLanguagesUtils::getInstance(); $oLanguages->addLanguageString($sTitleKey, $this->_aConfig['title']); $oLanguages->compileLanguage(); BxDolStudioInstallerUtils::getInstance()->checkModules(); $aFiles = array(); $this->hashFiles($this->_sModulePath, $aFiles); foreach($aFiles as $aFile) $this->oDb->insertModuleTrack($iModuleId, $aFile); $this->cleanupMemoryAfterAction($this->_aConfig['home_uri'], $iModuleId); $this->_onInstallAfter(); if(!empty($this->_aConfig['install_success'])) $this->_perform('install_success', $aParams); } else { if(!empty($this->_aConfig['install_failed'])) $this->_perform('install_failed', $aParams); } bx_alert('system', 'install', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult)); if($aResult['result'] && $bAutoEnable) { $aResultEnable = $this->enable($aParams); $aResult['result'] = $aResult['result'] & $aResultEnable['result']; $aResult['message'] = $aResult['message'] . $aResultEnable['message']; } return $aResult; } public function uninstall($aParams, $bAutoDisable = false) { $bAutoDisable = $bAutoDisable || (isset($aParams['auto_disable']) && (bool)$aParams['auto_disable']); $bHtmlResponce = isset($aParams['html_response']) && (bool)$aParams['html_response']; //--- Check whether the module was already uninstalled ---// if(!$this->oDb->isModule($this->_aConfig['home_uri'])) return array( 'message' => _t('_adm_err_modules_already_uninstalled'), 'result' => false ); if($bAutoDisable) { $aResultDisable = $this->disable($aParams); if(!$aResultDisable['result']) return $aResultDisable; } $aResult = array(); bx_alert('system', 'before_uninstall', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult)); if ($aResult && !$aResult['result']) return $aResult; //--- Check for dependent modules ---// $bDependent = false; $aDependents = $this->oDb->getDependent($this->_aConfig['name'], $this->_aConfig['home_uri']); if(is_array($aDependents) && !empty($aDependents)) { $bDependent = true; $sMessage = '<br />' . _t('_adm_err_modules_wrong_dependency_uninstall') . '<br />'; foreach($aDependents as $aDependent) $sMessage .= $aDependent['title'] . '<br />'; } if($bDependent) return array( 'message' => $this->_displayResult('check_dependencies', false, $sMessage, $bHtmlResponce), 'result' => false ); //--- Process storages and comments ---// $aResultBefore = $this->_onUninstallBefore(); if($aResultBefore !== BX_DOL_STUDIO_INSTALLER_SUCCESS) return array( 'message' => $aResultBefore['content'], 'result' => false ); $aResult = $this->_perform('uninstall', $aParams); if($aResult['result']) { $iModuleId = $this->oDb->deleteModule($this->_aConfig); $sTitleKey = BxDolModule::getTitleKey($this->_aConfig['home_uri']); $oLanguages = BxDolStudioLanguagesUtils::getInstance(); $oLanguages->deleteLanguageString($sTitleKey); $oLanguages->compileLanguage(); $this->cleanupMemoryAfterAction($this->_aConfig['home_uri'], $iModuleId); $this->_onUninstallAfter(); if(!empty($this->_aConfig['uninstall_success'])) $this->_perform('uninstall_success', $aParams); } else { if(!empty($this->_aConfig['uninstall_failed'])) $this->_perform('uninstall_failed', $aParams); } if($bAutoDisable) { $aResult['result'] = $aResultDisable['result'] & $aResult['result']; $aResult['message'] = $aResultDisable['message'] . $aResult['message']; } bx_alert('system', 'uninstall', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult)); return $aResult; } public function delete($aParams) { $aError = array( 'message' => _t('_adm_err_modules_cannot_remove_package'), 'result' => false ); $oFile = $this->_getFileManager(); if(empty($oFile)) return $aError; if(!$oFile->delete('modules/' . $this->_aConfig['home_dir'])) return $aError; return array( 'message' => '', //_t('_adm_msg_modules_success_delete'), 'result' => true ); } public function recompile($aParams) { $oLanguages = BxDolStudioLanguagesUtils::getInstance(); $aResult = array('message' => '', 'result' => false); $aLanguages = $this->oDb->getLanguages(); if (isAdmin() && !empty($aLanguages)) { $this->_updateLanguage(false, current($aLanguages)); $bResult = false; foreach($aLanguages as $aLanguage) { $bResult = $this->_updateLanguage(true, $aLanguage) && $oLanguages->compileLanguage($aLanguage['id']); $aResult['message'] .= $aLanguage['title'] . ': <span style="color:' . ($bResult ? 'green' : 'red') . '">' . _t($bResult ? '_adm_txt_modules_process_action_success' : '_adm_txt_modules_process_action_failed') . '</span><br />'; $aResult['result'] |= $bResult; } } return $aResult; } public function enable($aParams) { //--- Auto disable before enable ---// $this->disable($aParams); $aModule = $this->oDb->getModuleByUri($this->_aConfig['home_uri']); //--- Check whether the module is installed ---// if(empty($aModule) || !is_array($aModule)) return array( 'message' => _t('_adm_err_modules_module_not_installed'), 'result' => false ); //--- Check whether the module is already enabled ---// if((int)$aModule['enabled'] != 0) return array( 'message' => _t('_adm_err_modules_already_enabled'), 'result' => false ); $aResult = array(); if(!empty($this->_aConfig['before_enable'])) { $aResult = $this->_perform('before_enable', $aParams); if($aResult && !$aResult['result']) return $aResult; } $aResult = array(); bx_alert('system', 'before_enable', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult)); if ($aResult && !$aResult['result']) return $aResult; $aResultBefore = $this->_onEnableBefore(); if($aResultBefore !== BX_DOL_STUDIO_INSTALLER_SUCCESS) return array( 'message' => $aResultBefore['content'], 'result' => false ); $aResult = $this->_perform('enable', $aParams); if($aResult['result']) { $this->oDb->enableModuleByUri($aModule['uri']); $this->cleanupMemoryAfterAction($aModule['uri'], $aModule['id']); $this->_onEnableAfter(); if(!empty($this->_aConfig['enable_success'])) $this->_perform('enable_success', $aParams); } else { if(!empty($this->_aConfig['enable_failed'])) $this->_perform('enable_failed', $aParams); } setParam('sys_revision', 1 + getParam('sys_revision')); bx_alert('system', 'enable', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult)); return $aResult; } public function disable($aParams) { $bHtmlResponce = isset($aParams['html_response']) && (bool)$aParams['html_response']; $aModule = $this->oDb->getModuleByUri($this->_aConfig['home_uri']); //--- Check whether the module is installed ---// if(empty($aModule) || !is_array($aModule)) return array( 'message' => _t('_adm_err_modules_module_not_installed'), 'result' => false ); //--- Check whether the module is already disabled ---// if((int)$aModule['enabled'] == 0) return array( 'message' => _t('_adm_err_modules_already_disabled'), 'result' => false ); $aResult = array(); if(!empty($this->_aConfig['before_disable'])) { $aResult = $this->_perform('before_disable', $aParams); if($aResult && !$aResult['result']) return $aResult; } $aResult = array(); bx_alert('system', 'before_disable', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult)); if ($aResult && !$aResult['result']) return $aResult; //--- Check for dependent modules ---// $bDependent = false; $aDependents = $this->oDb->getDependent($this->_aConfig['name'], $this->_aConfig['home_uri']); if(is_array($aDependents) && !empty($aDependents)) { $bDependent = true; $sMessage = '<br />' . _t('_adm_err_modules_wrong_dependency_disable') . '<br />'; foreach($aDependents as $aDependent) $sMessage .= $aDependent['title'] . '<br />'; } if($bDependent) return array( 'message' => $this->_displayResult('check_dependencies', false, $sMessage, $bHtmlResponce), 'result' => false ); $aResultBefore = $this->_onDisableBefore(); if($aResultBefore !== BX_DOL_STUDIO_INSTALLER_SUCCESS) return array( 'message' => $aResultBefore['content'], 'result' => false ); $aResult = $this->_perform('disable', $aParams); if($aResult['result']) { $this->oDb->disableModuleByUri($aModule['uri']); $this->cleanupMemoryAfterAction($aModule['uri'], $aModule['id']); $this->_onDisableAfter(); if(!empty($this->_aConfig['disable_success'])) $this->_perform('disable_success', $aParams); } else { if(!empty($this->_aConfig['disable_failed'])) $this->_perform('disable_failed', $aParams); } bx_alert('system', 'disable', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult)); return $aResult; } //--- Get/Set Methods ---// public function getVendor() { return $this->_aConfig['vendor']; } public function getName() { return $this->_aConfig['name']; } public function getTitle() { return $this->_aConfig['title']; } public function getHomeDir() { return $this->_aConfig['home_dir']; } //--- Action Methods ---// protected function actionOperationFailed($mixedResult) { return _t('_adm_err_modules_process_action_failed'); } protected function actionCheckDependencies($sOperation) { $sContent = ''; if(in_array($sOperation, array('install', 'enable', 'update'))) { if(!isset($this->_aConfig['dependencies']) || !is_array($this->_aConfig['dependencies'])) return BX_DOL_STUDIO_INSTALLER_SUCCESS; foreach($this->_aConfig['dependencies'] as $sModule => $sModuleTitle) { if($this->oDb->isModule($sModule) && $this->oDb->isEnabled($sModule)) continue; if($this->oDb->isModuleByName($sModule) && $this->oDb->isEnabledByName($sModule)) continue; $sContent .= $sModuleTitle . '<br />'; } if(!empty($sContent)) $sContent = '<br />' . _t('_adm_err_modules_wrong_dependency_install') . '<br />' . $sContent; } return empty($sContent) ? BX_DOL_STUDIO_INSTALLER_SUCCESS : array('code' => BX_DOL_STUDIO_INSTALLER_FAILED, 'content' => $sContent); } protected function actionCheckDependenciesFailed($mixedResult) { return $mixedResult['content']; } protected function actionShowIntroduction($sOperation) { if(!isset($this->_aConfig[$sOperation . '_info']['introduction'])) return BX_DOL_STUDIO_INSTALLER_FAILED; $sPath = $this->_sHomePath . 'install/info/' . $this->_aConfig[$sOperation . '_info']['introduction']; return file_exists($sPath) ? array("code" => BX_DOL_STUDIO_INSTALLER_SUCCESS, "content" => file_get_contents($sPath)) : BX_DOL_STUDIO_INSTALLER_FAILED; } protected function actionShowConclusion($sOperation) { if(!isset($this->_aConfig[$sOperation . '_info']['conclusion'])) return BX_DOL_STUDIO_INSTALLER_FAILED; $sPath = $this->_sHomePath . 'install/info/' . $this->_aConfig[$sOperation . '_info']['conclusion']; return file_exists($sPath) ? array("code" => BX_DOL_STUDIO_INSTALLER_SUCCESS, "content" => file_get_contents($sPath)) : BX_DOL_STUDIO_INSTALLER_FAILED; } protected function actionMoveSources($sOperation) { $oFile = $this->_getFileManager(); $aInstalled = array_merge(array('system'), $this->oDb->getModulesUri()); $bResult = true; foreach($this->_aConfig['includes'] as $sUri => $sPath) { if(!in_array($sUri, $aInstalled) || empty($sPath)) continue; if($sOperation == 'install') { $sSrcPath = 'modules/' . $this->_aConfig['home_dir'] . 'install/data/' . $sPath; $sDstPath = $sPath; $bResult &= $oFile->copy($sSrcPath, $sDstPath); } else if($sOperation == 'uninstall') $bResult &= $oFile->delete($sPath); } return $bResult ? BX_DOL_STUDIO_INSTALLER_SUCCESS : BX_DOL_STUDIO_INSTALLER_FAILED; } protected function actionExecuteSql($sOperation) { switch($sOperation) { case 'install': $this->actionExecuteSql('disable'); $this->actionExecuteSql('uninstall'); break; case 'enable': $this->actionExecuteSql('disable'); break; } $mixedResult = $this->oDb->executeSQL($this->_sHomePath . 'install/sql/' . $sOperation . '.sql', $this->getMarkersForDb()); return $mixedResult === true ? BX_DOL_STUDIO_INSTALLER_SUCCESS : array('code' => BX_DOL_STUDIO_INSTALLER_FAILED, 'content' => $mixedResult); } protected function actionExecuteSqlFailed($mixedResult) { if(is_int($mixedResult)) return $this->actionOperationFailed($mixedResult); $sResult = _t('_adm_err_modules_wrong_mysql_query') . '<br />'; foreach($mixedResult['content'] as $aQuery) { $sResult .= _t('_adm_err_modules_wrong_mysql_query_msg', $aQuery['error']) . '<br />'; $sResult .= '<pre>' . $aQuery['query'] . '</pre>'; } return $sResult; } protected function actionInstallLanguage($sOperation) { $oLanguages = BxDolStudioLanguagesUtils::getInstance(); $sLanguage = isset($this->_aConfig['home_uri']) ? $this->_aConfig['home_uri'] : ''; $bResult = true; if($sOperation == 'install') $bResult = $oLanguages->installLanguage(array('name' => $this->_aConfig['name'], 'path' => $this->_aConfig['home_dir'], 'uri' => $this->_aConfig['home_uri'], 'lang_category' => $this->_aConfig['language_category']), false); return $bResult && $oLanguages->compileLanguage(0, true) ? BX_DOL_STUDIO_INSTALLER_SUCCESS : BX_DOL_STUDIO_INSTALLER_FAILED; } protected function actionUpdateLanguages($sOperation) { if(!isset($this->_aConfig['language_category']) || empty($this->_aConfig['language_category'])) return BX_DOL_STUDIO_INSTALLER_FAILED; $oLanguages = BxDolStudioLanguagesUtils::getInstance(); $bResult = true; $aResult = array(); //--- Process Language Category ---// if($sOperation == 'install') $iCategoryId = $oLanguages->addLanguageCategory($this->_aConfig['language_category']); //--- Process languages' key=>value pears ---// $aModule = array( 'name' => $this->_aConfig['name'], 'path' => $this->_aConfig['home_dir'], 'uri' => $this->_aConfig['home_uri'], 'lang_category' => $this->_aConfig['language_category'] ); if($sOperation == 'install') $bResult = $oLanguages->restoreLanguage(0, $aModule, false); else if($sOperation == 'uninstall') $bResult = $oLanguages->removeLanguageByModule($aModule, false); if($sOperation == 'uninstall' && $bResult) $oLanguages->deleteLanguageCategory($this->_aConfig['language_category']); return $bResult && $oLanguages->compileLanguage(0, true) ? BX_DOL_STUDIO_INSTALLER_SUCCESS : BX_DOL_STUDIO_INSTALLER_FAILED; } /** * NOTE. The action is ONLY needed for dependent module to let * Notifications based module(s) know that he(they) should * update (request and save) handlers from this dependent module. */ protected function actionUpdateRelations($sOperation) { if(!in_array($sOperation, array('install', 'uninstall', 'enable', 'disable'))) return BX_DOL_STUDIO_INSTALLER_FAILED; if(empty($this->_aConfig['relations']) || !is_array($this->_aConfig['relations'])) return BX_DOL_STUDIO_INSTALLER_SUCCESS; foreach($this->_aConfig['relations'] as $sModule) { if(!$this->oDb->isModuleByName($sModule)) continue; $aRelation = $this->oDb->getRelationsBy(array('type' => 'module', 'value' => $sModule)); if(empty($aRelation) || empty($aRelation['on_' . $sOperation]) || !BxDolRequest::serviceExists($aRelation['module'], $aRelation['on_' . $sOperation])) continue; BxDolService::call($aRelation['module'], $aRelation['on_' . $sOperation], array($this->_aConfig['home_uri'])); } return BX_DOL_STUDIO_INSTALLER_SUCCESS; } /** * NOTE. The action is ONLY needed for Notifications based modules * to update (request and save) handlers from all dependent modules. */ protected function actionUpdateRelationsForAll($sOperation) { if(!in_array($sOperation, array('enable', 'disable'))) return BX_DOL_STUDIO_INSTALLER_FAILED; if($sOperation == 'enable') $this->oDb->insertRelation($this->_aConfig['name'], $this->_aConfig['relation_handlers']); $aRelation = $this->oDb->getRelationsBy(array('type' => 'module', 'value' => $this->_aConfig['name'])); if(empty($aRelation) || empty($aRelation['on_' . $sOperation])) return BX_DOL_STUDIO_INSTALLER_SUCCESS; $aModules = $this->oDb->getModulesBy(array('type' => 'all', 'active' => 1)); foreach($aModules as $aModule) { $aConfig = self::getModuleConfig($aModule); if(!empty($aConfig['relations']) && is_array($aConfig['relations']) && in_array($this->_aConfig['name'], $aConfig['relations'])) BxDolService::call($this->_aConfig['name'], $aRelation['on_' . $sOperation], array($aModule['uri'])); } if($sOperation == 'disable') $this->oDb->deleteRelation($this->_aConfig['name']); return BX_DOL_STUDIO_INSTALLER_SUCCESS; } /** * * Connections objects associated with module data. It must be defined which content is associated with the connection. * The key is connection object name and value is array (possible array values: type, conn, table, field_id). * If 'type' == 'profiles', then it is considered profiles connection and other possible param is 'conn' ('initiator', 'content' or 'both') * If 'type' == 'custom' (or ommited), then other possible params are 'conn', 'table' and 'field_id' * @param string $sOperation - operation type. */ protected function actionProcessConnections($sOperation) { if(!in_array($sOperation, array('uninstall')) || empty($this->_aConfig['connections'])) return BX_DOL_STUDIO_INSTALLER_FAILED; foreach($this->_aConfig['connections'] as $sObjectConnections => $a) { $o = BxDolConnection::getObjectInstance($sObjectConnections); if(!$o) continue; $sFuncSuffix = 'DeleteInitiatorAndContent'; if (isset($a['conn']) && 'initiator' == $a['conn']) $sFuncSuffix = 'DeleteInitiator'; elseif (isset($a['conn']) && 'content' == $a['conn']) $sFuncSuffix = 'DeleteContent'; if (isset($a['type']) && 'profiles' == $a['type']) { $sFunc = 'onModuleProfile' . $sFuncSuffix; $o->$sFunc($this->_aConfig['name']); } else { $sFunc = 'onModule' . $sFuncSuffix; $o->$sFunc($a['table'], $a['field_id']); } } return BX_DOL_STUDIO_INSTALLER_SUCCESS; } /** * * Process the list of menu triggers provided in config array. * It must be specified in the module which adds menu item and in modules where menu items are added, @see BxDolMenu::processMenuTrigger * @param string $sOperation - operation type. */ protected function actionProcessMenuTriggers($sOperation) { if(empty($this->_aConfig['menu_triggers'])) return BX_DOL_STUDIO_INSTALLER_FAILED; foreach($this->_aConfig['menu_triggers'] as $sMenuTriggerName) BxDolMenu::processMenuTrigger($sMenuTriggerName); return BX_DOL_STUDIO_INSTALLER_SUCCESS; } /** * * Process the list of page triggers provided in config array. * It must be specified in the module which adds page block and in modules where page blocks are added, @see BxDolPage::processPageTrigger * @param string $sOperation - operation type. */ protected function actionProcessPageTriggers($sOperation) { if(empty($this->_aConfig['page_triggers'])) return BX_DOL_STUDIO_INSTALLER_FAILED; foreach($this->_aConfig['page_triggers'] as $sPageTriggerName) BxDolPage::processPageTrigger($sPageTriggerName); return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function actionProcessDeletedProfiles($sOperation) { if(!in_array($sOperation, array('install', 'uninstall', 'enable', 'disable'))) return BX_DOL_STUDIO_INSTALLER_FAILED; $o = BxDolProfileQuery::getInstance(); $o->processDeletedProfiles(); return BX_DOL_STUDIO_INSTALLER_SUCCESS; } /** * * Process the list of extended search forms provided in config array. * @param string $sOperation - operation type. */ protected function actionProcessEsearches($sOperation) { if(empty($this->_aConfig['esearches'])) return BX_DOL_STUDIO_INSTALLER_FAILED; foreach($this->_aConfig['esearches'] as $sObject) { if(in_array($sOperation, array('install', 'enable', 'enable_success'))) BxDolSearchExtended::getObjectInstance($sObject); else if(in_array($sOperation, array('uninstall', 'disable'))) BxDolSearchExtended::getObjectInstance($sObject)->clean(); } return BX_DOL_STUDIO_INSTALLER_SUCCESS; } /** * * Process the list of transcoders provided in config array. * Transcoder objects to automatically register/unregister necessary alerts for. * @param string $sOperation - operation type. */ protected function actionRegisterTranscoders($sOperation) { if(empty($this->_aConfig['transcoders'])) return BX_DOL_STUDIO_INSTALLER_FAILED; BxDolTranscoderImage::registerHandlersArray($this->_aConfig['transcoders']); return BX_DOL_STUDIO_INSTALLER_SUCCESS; } /** * * Process the list of transcoders provided in config array. * Transcoder objects to automatically register/unregister necessary alerts for. * @param string $sOperation - operation type. */ protected function actionUnregisterTranscoders($sOperation) { if(empty($this->_aConfig['transcoders'])) return BX_DOL_STUDIO_INSTALLER_FAILED; BxDolTranscoderImage::unregisterHandlersArray($this->_aConfig['transcoders']); BxDolTranscoderImage::cleanupObjectsArray($this->_aConfig['transcoders']); return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function actionClearDbCache($sOperation) { $oCache = $this->oDb->getDbCacheObject(); $bResult = $oCache->removeAllByPrefix('db_'); $bResult &= $this->oDb->cleanMemoryAll(); $aKeys = array_keys($GLOBALS); $aKeysPrefixes = array('bx_dol_cache_memory_'); foreach($aKeysPrefixes as $sKeyPrefix) foreach($aKeys as $sKey) if(substr($sKey, 0, strlen($sKeyPrefix)) == $sKeyPrefix) unset($GLOBALS[$sKey]); return $bResult ? BX_DOL_STUDIO_INSTALLER_SUCCESS : BX_DOL_STUDIO_INSTALLER_FAILED; } protected function actionClearTemplateCache($sOperation) { $aCaches = array('template', 'css', 'js'); $oCacheUtilities = BxDolCacheUtilities::getInstance(); foreach($aCaches as $sCache) { $aResult = $oCacheUtilities->clear($sCache); if($aResult === false) continue; if(isset($aResult['code']) && $aResult['code'] != 0) return BX_DOL_STUDIO_INSTALLER_FAILED; } return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _onInstallBefore() { return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _onInstallAfter() { return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _onEnableBefore() { return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _onEnableAfter() { BxDolCmts::onModuleEnable($this->_aConfig['name']); return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _onDisableBefore() { BxDolCmts::onModuleDisable($this->_aConfig['name']); return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _onDisableAfter() { return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _onUninstallBefore() { // check if module is already waiting while files are deleting if(self::isModulePendingUninstall($this->_aConfig['home_uri'])) return array( 'code' => BX_DOL_STUDIO_INSTALLER_FAILED, 'content' => _t('_adm_err_modules_pending_uninstall_already'), ); $bSetModulePendingUninstall = false; // delete comments and queue for deletion comments attachments $iFiles = 0; BxDolCmts::onModuleUninstall($this->_aConfig['name'], $iFiles); if($iFiles) $bSetModulePendingUninstall = true; // queue for deletion storage files if(!empty($this->_aConfig['storages']) && is_array($this->_aConfig['storages'])) foreach($this->_aConfig['storages'] as $s) if(($o = BxDolStorage::getObjectInstance($s)) && $o->queueFilesForDeletionFromObject()) $bSetModulePendingUninstall = true; // if some files were added to the queue, set module as pending uninstall if ($bSetModulePendingUninstall) { self::setModulePendingUninstall($this->_aConfig['home_uri']); return array( 'code' => BX_DOL_STUDIO_INSTALLER_FAILED, 'content' => _t('_adm_err_modules_pending_uninstall'), ); } return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _onUninstallAfter() { return BX_DOL_STUDIO_INSTALLER_SUCCESS; } protected function _perform($sOperationName, $aParams = array()) { $bHtmlResponce = isset($aParams['html_response']) && (bool)$aParams['html_response']; if(!defined('BX_SKIP_INSTALL_CHECK') && !defined('BX_DOL_CRON_EXECUTE') && !$GLOBALS['logged']['admin']) return array('message' => '_adm_mod_err_only_admin_can_perform_operations_with_modules', 'result' => false); $sMessage = ''; foreach($this->_aConfig[$sOperationName] as $sAction => $iEnabled) { $sMethod = 'action' . bx_gen_method_name($sAction); if($iEnabled == 0 || !method_exists($this, $sMethod)) continue; $mixedResult = $this->$sMethod($sOperationName); //--- On Success ---// if((is_int($mixedResult) && (int)$mixedResult == BX_DOL_STUDIO_INSTALLER_SUCCESS) || (isset($mixedResult['code']) && (int)$mixedResult['code'] == BX_DOL_STUDIO_INSTALLER_SUCCESS)) { $sMessage .= $this->_displayResult($sAction, true, isset($mixedResult['content']) ? $mixedResult['content'] : '', $bHtmlResponce); continue; } //--- On Failed ---// $sMethodFailed = $sMethod . 'Failed'; return array('message' => $this->_displayResult($sAction, false, method_exists($this, $sMethodFailed) ? $this->$sMethodFailed($mixedResult) : $this->actionOperationFailed($mixedResult), $bHtmlResponce), 'result' => false); } if($this->_bShowOnSuccess) $sMessage = $this->_aActions['perform_' . $sOperationName]['success'] . $sMessage; return array('message' => $sMessage, 'result' => true); } protected function _displayResult($sAction, $bResult, $sResult = '', $bHtmlResponse = true) { if($bResult && !in_array($sAction, array('show_introduction', 'show_conclusion')) && !$this->_bShowOnSuccess) return ''; $sTitle = $this->_aActions[$sAction]['title'] . ' '; if(!empty($sResult)) $sResult = (substr($sResult, 0, 1) == '_' ? _t($sResult) : $sResult); $sContent = !empty($sResult) ? $sResult : _t($bResult ? '_adm_txt_modules_process_action_success' : '_adm_err_modules_process_action_failed'); if(!$bHtmlResponse) return $sTitle . $sContent; return BxDolStudioTemplate::getInstance()->parseHtmlByName('mod_action_result_step.html', array( 'color' => $bResult ? 'green' : 'red', 'title' => $sTitle, 'content' => $sContent )); } protected function _getFileManager() { $oFile = null; if($this->_bUseFtp) { $oFile = new BxDolFtp(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost', getParam('sys_ftp_login'), getParam('sys_ftp_password'), getParam('sys_ftp_dir')); if(!$oFile->connect()) return null; if(!$oFile->isUna()) return null; } else $oFile = BxDolFile::getInstance(); return $oFile; } protected function _isCompatibleWith() { $sVersionCur = bx_get_ver(); $bCompatible = false; if(isset($this->_aConfig['compatible_with']) && is_array($this->_aConfig['compatible_with'])) foreach($this->_aConfig['compatible_with'] as $iKey => $sVersionReq) $bCompatible = $bCompatible || (version_compare($sVersionCur, $sVersionReq, '>=') == 1); return $bCompatible; } protected function filePathWithoutBase($sPath) { return bx_ltrim_str($sPath, $this->_sModulePath); } protected function getMarkersForDb() { return array( 'from' => array('{db_name}'), 'to' => array(defined('BX_DATABASE_NAME') ? BX_DATABASE_NAME : ''), ); } protected function cleanupMemoryAfterAction($sModuleUri, $iModuleId) { $this->oDb->cleanMemory('sys_modules_' . $sModuleUri); $this->oDb->cleanMemory('sys_modules_' . $iModuleId); $this->oDb->cleanMemory('sys_modules'); $this->oDb->cleanMemory('sys_modules_modules'); $this->oDb->cleanMemory('sys_modules_modules_active'); } } /** @} */
Java
<?php namespace Illuminate\Database\Eloquent; use Exception; use ArrayAccess; use JsonSerializable; use Illuminate\Support\Arr; use Illuminate\Support\Str; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Routing\UrlRoutable; use Illuminate\Contracts\Queue\QueueableEntity; use Illuminate\Database\Eloquent\Relations\Pivot; use Illuminate\Contracts\Queue\QueueableCollection; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\ConnectionResolverInterface as Resolver; abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable { use Concerns\HasAttributes, Concerns\HasEvents, Concerns\HasGlobalScopes, Concerns\HasRelationships, Concerns\HasTimestamps, Concerns\HidesAttributes, Concerns\GuardsAttributes; /** * The connection name for the model. * * @var string */ protected $connection; /** * The table associated with the model. * * @var string */ protected $table; /** * The primary key for the model. * * @var string */ protected $primaryKey = 'id'; /** * The "type" of the auto-incrementing ID. * * @var string */ protected $keyType = 'int'; /** * Indicates if the IDs are auto-incrementing. * * @var bool */ public $incrementing = true; /** * The relations to eager load on every query. * * @var array */ protected $with = []; /** * The relationship counts that should be eager loaded on every query. * * @var array */ protected $withCount = []; /** * The number of models to return for pagination. * * @var int */ protected $perPage = 15; /** * Indicates if the model exists. * * @var bool */ public $exists = false; /** * Indicates if the model was inserted during the current request lifecycle. * * @var bool */ public $wasRecentlyCreated = false; /** * The connection resolver instance. * * @var \Illuminate\Database\ConnectionResolverInterface */ protected static $resolver; /** * The event dispatcher instance. * * @var \Illuminate\Contracts\Events\Dispatcher */ protected static $dispatcher; /** * The array of booted models. * * @var array */ protected static $booted = []; /** * The array of global scopes on the model. * * @var array */ protected static $globalScopes = []; /** * The name of the "created at" column. * * @var string */ const CREATED_AT = 'created_at'; /** * The name of the "updated at" column. * * @var string */ const UPDATED_AT = 'updated_at'; /** * Create a new Eloquent model instance. * * @param array $attributes * @return void */ public function __construct(array $attributes = []) { $this->bootIfNotBooted(); $this->syncOriginal(); $this->fill($attributes); } /** * Check if the model needs to be booted and if so, do it. * * @return void */ protected function bootIfNotBooted() { if (! isset(static::$booted[static::class])) { static::$booted[static::class] = true; $this->fireModelEvent('booting', false); static::boot(); $this->fireModelEvent('booted', false); } } /** * The "booting" method of the model. * * @return void */ protected static function boot() { static::bootTraits(); } /** * Boot all of the bootable traits on the model. * * @return void */ protected static function bootTraits() { $class = static::class; foreach (class_uses_recursive($class) as $trait) { if (method_exists($class, $method = 'boot'.class_basename($trait))) { forward_static_call([$class, $method]); } } } /** * Clear the list of booted models so they will be re-booted. * * @return void */ public static function clearBootedModels() { static::$booted = []; static::$globalScopes = []; } /** * Fill the model with an array of attributes. * * @param array $attributes * @return $this * * @throws \Illuminate\Database\Eloquent\MassAssignmentException */ public function fill(array $attributes) { $totallyGuarded = $this->totallyGuarded(); foreach ($this->fillableFromArray($attributes) as $key => $value) { $key = $this->removeTableFromKey($key); // The developers may choose to place some attributes in the "fillable" array // which means only those attributes may be set through mass assignment to // the model, and all others will just get ignored for security reasons. if ($this->isFillable($key)) { $this->setAttribute($key, $value); } elseif ($totallyGuarded) { throw new MassAssignmentException(sprintf( 'Add [%s] to fillable property to allow mass assignment on [%s].', $key, get_class($this) )); } } return $this; } /** * Fill the model with an array of attributes. Force mass assignment. * * @param array $attributes * @return $this */ public function forceFill(array $attributes) { return static::unguarded(function () use ($attributes) { return $this->fill($attributes); }); } /** * Qualify the given column name by the model's table. * * @param string $column * @return string */ public function qualifyColumn($column) { if (Str::contains($column, '.')) { return $column; } return $this->getTable().'.'.$column; } /** * Remove the table name from a given key. * * @param string $key * @return string */ protected function removeTableFromKey($key) { return Str::contains($key, '.') ? last(explode('.', $key)) : $key; } /** * Create a new instance of the given model. * * @param array $attributes * @param bool $exists * @return static */ public function newInstance($attributes = [], $exists = false) { // This method just provides a convenient way for us to generate fresh model // instances of this current model. It is particularly useful during the // hydration of new objects via the Eloquent query builder instances. $model = new static((array) $attributes); $model->exists = $exists; $model->setConnection( $this->getConnectionName() ); return $model; } /** * Create a new model instance that is existing. * * @param array $attributes * @param string|null $connection * @return static */ public function newFromBuilder($attributes = [], $connection = null) { $model = $this->newInstance([], true); $model->setRawAttributes((array) $attributes, true); $model->setConnection($connection ?: $this->getConnectionName()); $model->fireModelEvent('retrieved', false); return $model; } /** * Begin querying the model on a given connection. * * @param string|null $connection * @return \Illuminate\Database\Eloquent\Builder */ public static function on($connection = null) { // First we will just create a fresh instance of this model, and then we can // set the connection on the model so that it is be used for the queries // we execute, as well as being set on each relationship we retrieve. $instance = new static; $instance->setConnection($connection); return $instance->newQuery(); } /** * Begin querying the model on the write connection. * * @return \Illuminate\Database\Query\Builder */ public static function onWriteConnection() { $instance = new static; return $instance->newQuery()->useWritePdo(); } /** * Get all of the models from the database. * * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Collection|static[] */ public static function all($columns = ['*']) { return (new static)->newQuery()->get( is_array($columns) ? $columns : func_get_args() ); } /** * Begin querying a model with eager loading. * * @param array|string $relations * @return \Illuminate\Database\Eloquent\Builder|static */ public static function with($relations) { return (new static)->newQuery()->with( is_string($relations) ? func_get_args() : $relations ); } /** * Eager load relations on the model. * * @param array|string $relations * @return $this */ public function load($relations) { $query = $this->newQueryWithoutRelationships()->with( is_string($relations) ? func_get_args() : $relations ); $query->eagerLoadRelations([$this]); return $this; } /** * Eager load relations on the model if they are not already eager loaded. * * @param array|string $relations * @return $this */ public function loadMissing($relations) { $relations = is_string($relations) ? func_get_args() : $relations; return $this->load(array_filter($relations, function ($relation) { return ! $this->relationLoaded($relation); })); } /** * Increment a column's value by a given amount. * * @param string $column * @param int $amount * @param array $extra * @return int */ protected function increment($column, $amount = 1, array $extra = []) { return $this->incrementOrDecrement($column, $amount, $extra, 'increment'); } /** * Decrement a column's value by a given amount. * * @param string $column * @param int $amount * @param array $extra * @return int */ protected function decrement($column, $amount = 1, array $extra = []) { return $this->incrementOrDecrement($column, $amount, $extra, 'decrement'); } /** * Run the increment or decrement method on the model. * * @param string $column * @param int $amount * @param array $extra * @param string $method * @return int */ protected function incrementOrDecrement($column, $amount, $extra, $method) { $query = $this->newQuery(); if (! $this->exists) { return $query->{$method}($column, $amount, $extra); } $this->incrementOrDecrementAttributeValue($column, $amount, $extra, $method); return $query->where( $this->getKeyName(), $this->getKey() )->{$method}($column, $amount, $extra); } /** * Increment the underlying attribute value and sync with original. * * @param string $column * @param int $amount * @param array $extra * @param string $method * @return void */ protected function incrementOrDecrementAttributeValue($column, $amount, $extra, $method) { $this->{$column} = $this->{$column} + ($method == 'increment' ? $amount : $amount * -1); $this->forceFill($extra); $this->syncOriginalAttribute($column); } /** * Update the model in the database. * * @param array $attributes * @param array $options * @return bool */ public function update(array $attributes = [], array $options = []) { if (! $this->exists) { return false; } return $this->fill($attributes)->save($options); } /** * Save the model and all of its relationships. * * @return bool */ public function push() { if (! $this->save()) { return false; } // To sync all of the relationships to the database, we will simply spin through // the relationships and save each model via this "push" method, which allows // us to recurse into all of these nested relations for the model instance. foreach ($this->relations as $models) { $models = $models instanceof Collection ? $models->all() : [$models]; foreach (array_filter($models) as $model) { if (! $model->push()) { return false; } } } return true; } /** * Save the model to the database. * * @param array $options * @return bool */ public function save(array $options = []) { $query = $this->newQueryWithoutScopes(); // If the "saving" event returns false we'll bail out of the save and return // false, indicating that the save failed. This provides a chance for any // listeners to cancel save operations if validations fail or whatever. if ($this->fireModelEvent('saving') === false) { return false; } // If the model already exists in the database we can just update our record // that is already in this database using the current IDs in this "where" // clause to only update this model. Otherwise, we'll just insert them. if ($this->exists) { $saved = $this->isDirty() ? $this->performUpdate($query) : true; } // If the model is brand new, we'll insert it into our database and set the // ID attribute on the model to the value of the newly inserted row's ID // which is typically an auto-increment value managed by the database. else { $saved = $this->performInsert($query); if (! $this->getConnectionName() && $connection = $query->getConnection()) { $this->setConnection($connection->getName()); } } // If the model is successfully saved, we need to do a few more things once // that is done. We will call the "saved" method here to run any actions // we need to happen after a model gets successfully saved right here. if ($saved) { $this->finishSave($options); } return $saved; } /** * Save the model to the database using transaction. * * @param array $options * @return bool * * @throws \Throwable */ public function saveOrFail(array $options = []) { return $this->getConnection()->transaction(function () use ($options) { return $this->save($options); }); } /** * Perform any actions that are necessary after the model is saved. * * @param array $options * @return void */ protected function finishSave(array $options) { $this->fireModelEvent('saved', false); if ($this->isDirty() && ($options['touch'] ?? true)) { $this->touchOwners(); } $this->syncOriginal(); } /** * Perform a model update operation. * * @param \Illuminate\Database\Eloquent\Builder $query * @return bool */ protected function performUpdate(Builder $query) { // If the updating event returns false, we will cancel the update operation so // developers can hook Validation systems into their models and cancel this // operation if the model does not pass validation. Otherwise, we update. if ($this->fireModelEvent('updating') === false) { return false; } // First we need to create a fresh query instance and touch the creation and // update timestamp on the model which are maintained by us for developer // convenience. Then we will just continue saving the model instances. if ($this->usesTimestamps()) { $this->updateTimestamps(); } // Once we have run the update operation, we will fire the "updated" event for // this model instance. This will allow developers to hook into these after // models are updated, giving them a chance to do any special processing. $dirty = $this->getDirty(); if (count($dirty) > 0) { $this->setKeysForSaveQuery($query)->update($dirty); $this->fireModelEvent('updated', false); $this->syncChanges(); } return true; } /** * Set the keys for a save update query. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function setKeysForSaveQuery(Builder $query) { $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery()); return $query; } /** * Get the primary key value for a save query. * * @return mixed */ protected function getKeyForSaveQuery() { return $this->original[$this->getKeyName()] ?? $this->getKey(); } /** * Perform a model insert operation. * * @param \Illuminate\Database\Eloquent\Builder $query * @return bool */ protected function performInsert(Builder $query) { if ($this->fireModelEvent('creating') === false) { return false; } // First we'll need to create a fresh query instance and touch the creation and // update timestamps on this model, which are maintained by us for developer // convenience. After, we will just continue saving these model instances. if ($this->usesTimestamps()) { $this->updateTimestamps(); } // If the model has an incrementing key, we can use the "insertGetId" method on // the query builder, which will give us back the final inserted ID for this // table from the database. Not all tables have to be incrementing though. $attributes = $this->attributes; if ($this->getIncrementing()) { $this->insertAndSetId($query, $attributes); } // If the table isn't incrementing we'll simply insert these attributes as they // are. These attribute arrays must contain an "id" column previously placed // there by the developer as the manually determined key for these models. else { if (empty($attributes)) { return true; } $query->insert($attributes); } // We will go ahead and set the exists property to true, so that it is set when // the created event is fired, just in case the developer tries to update it // during the event. This will allow them to do so and run an update here. $this->exists = true; $this->wasRecentlyCreated = true; $this->fireModelEvent('created', false); return true; } /** * Insert the given attributes and set the ID on the model. * * @param \Illuminate\Database\Eloquent\Builder $query * @param array $attributes * @return void */ protected function insertAndSetId(Builder $query, $attributes) { $id = $query->insertGetId($attributes, $keyName = $this->getKeyName()); $this->setAttribute($keyName, $id); } /** * Destroy the models for the given IDs. * * @param array|int $ids * @return int */ public static function destroy($ids) { // We'll initialize a count here so we will return the total number of deletes // for the operation. The developers can then check this number as a boolean // type value or get this total count of records deleted for logging, etc. $count = 0; $ids = is_array($ids) ? $ids : func_get_args(); // We will actually pull the models from the database table and call delete on // each of them individually so that their events get fired properly with a // correct set of attributes in case the developers wants to check these. $key = ($instance = new static)->getKeyName(); foreach ($instance->whereIn($key, $ids)->get() as $model) { if ($model->delete()) { $count++; } } return $count; } /** * Delete the model from the database. * * @return bool|null * * @throws \Exception */ public function delete() { if (is_null($this->getKeyName())) { throw new Exception('No primary key defined on model.'); } // If the model doesn't exist, there is nothing to delete so we'll just return // immediately and not do anything else. Otherwise, we will continue with a // deletion process on the model, firing the proper events, and so forth. if (! $this->exists) { return; } if ($this->fireModelEvent('deleting') === false) { return false; } // Here, we'll touch the owning models, verifying these timestamps get updated // for the models. This will allow any caching to get broken on the parents // by the timestamp. Then we will go ahead and delete the model instance. $this->touchOwners(); $this->performDeleteOnModel(); // Once the model has been deleted, we will fire off the deleted event so that // the developers may hook into post-delete operations. We will then return // a boolean true as the delete is presumably successful on the database. $this->fireModelEvent('deleted', false); return true; } /** * Force a hard delete on a soft deleted model. * * This method protects developers from running forceDelete when trait is missing. * * @return bool|null */ public function forceDelete() { return $this->delete(); } /** * Perform the actual delete query on this model instance. * * @return void */ protected function performDeleteOnModel() { $this->setKeysForSaveQuery($this->newQueryWithoutScopes())->delete(); $this->exists = false; } /** * Begin querying the model. * * @return \Illuminate\Database\Eloquent\Builder */ public static function query() { return (new static)->newQuery(); } /** * Get a new query builder for the model's table. * * @return \Illuminate\Database\Eloquent\Builder */ public function newQuery() { return $this->registerGlobalScopes($this->newQueryWithoutScopes()); } /** * Get a new query builder with no relationships loaded. * * @return \Illuminate\Database\Eloquent\Builder */ public function newQueryWithoutRelationships() { return $this->registerGlobalScopes( $this->newEloquentBuilder($this->newBaseQueryBuilder())->setModel($this) ); } /** * Register the global scopes for this builder instance. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return \Illuminate\Database\Eloquent\Builder */ public function registerGlobalScopes($builder) { foreach ($this->getGlobalScopes() as $identifier => $scope) { $builder->withGlobalScope($identifier, $scope); } return $builder; } /** * Get a new query builder that doesn't have any global scopes. * * @return \Illuminate\Database\Eloquent\Builder|static */ public function newQueryWithoutScopes() { $builder = $this->newEloquentBuilder($this->newBaseQueryBuilder()); // Once we have the query builders, we will set the model instances so the // builder can easily access any information it may need from the model // while it is constructing and executing various queries against it. return $builder->setModel($this) ->with($this->with) ->withCount($this->withCount); } /** * Get a new query instance without a given scope. * * @param \Illuminate\Database\Eloquent\Scope|string $scope * @return \Illuminate\Database\Eloquent\Builder */ public function newQueryWithoutScope($scope) { $builder = $this->newQuery(); return $builder->withoutGlobalScope($scope); } /** * Get a new query to restore one or more models by their queueable IDs. * * @param array|int $ids * @return \Illuminate\Database\Eloquent\Builder */ public function newQueryForRestoration($ids) { return is_array($ids) ? $this->newQueryWithoutScopes()->whereIn($this->getQualifiedKeyName(), $ids) : $this->newQueryWithoutScopes()->whereKey($ids); } /** * Create a new Eloquent query builder for the model. * * @param \Illuminate\Database\Query\Builder $query * @return \Illuminate\Database\Eloquent\Builder|static */ public function newEloquentBuilder($query) { return new Builder($query); } /** * Get a new query builder instance for the connection. * * @return \Illuminate\Database\Query\Builder */ protected function newBaseQueryBuilder() { $connection = $this->getConnection(); return new QueryBuilder( $connection, $connection->getQueryGrammar(), $connection->getPostProcessor() ); } /** * Create a new Eloquent Collection instance. * * @param array $models * @return \Illuminate\Database\Eloquent\Collection */ public function newCollection(array $models = []) { return new Collection($models); } /** * Create a new pivot model instance. * * @param \Illuminate\Database\Eloquent\Model $parent * @param array $attributes * @param string $table * @param bool $exists * @param string|null $using * @return \Illuminate\Database\Eloquent\Relations\Pivot */ public function newPivot(self $parent, array $attributes, $table, $exists, $using = null) { return $using ? $using::fromRawAttributes($parent, $attributes, $table, $exists) : Pivot::fromAttributes($parent, $attributes, $table, $exists); } /** * Convert the model instance to an array. * * @return array */ public function toArray() { return array_merge($this->attributesToArray(), $this->relationsToArray()); } /** * Convert the model instance to JSON. * * @param int $options * @return string * * @throws \Illuminate\Database\Eloquent\JsonEncodingException */ public function toJson($options = 0) { $json = json_encode($this->jsonSerialize(), $options); if (JSON_ERROR_NONE !== json_last_error()) { throw JsonEncodingException::forModel($this, json_last_error_msg()); } return $json; } /** * Convert the object into something JSON serializable. * * @return array */ public function jsonSerialize() { return $this->toArray(); } /** * Reload a fresh model instance from the database. * * @param array|string $with * @return static|null */ public function fresh($with = []) { if (! $this->exists) { return; } return static::newQueryWithoutScopes() ->with(is_string($with) ? func_get_args() : $with) ->where($this->getKeyName(), $this->getKey()) ->first(); } /** * Reload the current model instance with fresh attributes from the database. * * @return $this */ public function refresh() { if (! $this->exists) { return $this; } $this->setRawAttributes( static::newQueryWithoutScopes()->findOrFail($this->getKey())->attributes ); $this->load(collect($this->relations)->except('pivot')->keys()->toArray()); $this->syncOriginal(); return $this; } /** * Clone the model into a new, non-existing instance. * * @param array|null $except * @return \Illuminate\Database\Eloquent\Model */ public function replicate(array $except = null) { $defaults = [ $this->getKeyName(), $this->getCreatedAtColumn(), $this->getUpdatedAtColumn(), ]; $attributes = Arr::except( $this->attributes, $except ? array_unique(array_merge($except, $defaults)) : $defaults ); return tap(new static, function ($instance) use ($attributes) { $instance->setRawAttributes($attributes); $instance->setRelations($this->relations); }); } /** * Determine if two models have the same ID and belong to the same table. * * @param \Illuminate\Database\Eloquent\Model|null $model * @return bool */ public function is($model) { return ! is_null($model) && $this->getKey() === $model->getKey() && $this->getTable() === $model->getTable() && $this->getConnectionName() === $model->getConnectionName(); } /** * Determine if two models are not the same. * * @param \Illuminate\Database\Eloquent\Model|null $model * @return bool */ public function isNot($model) { return ! $this->is($model); } /** * Get the database connection for the model. * * @return \Illuminate\Database\Connection */ public function getConnection() { return static::resolveConnection($this->getConnectionName()); } /** * Get the current connection name for the model. * * @return string */ public function getConnectionName() { return $this->connection; } /** * Set the connection associated with the model. * * @param string $name * @return $this */ public function setConnection($name) { $this->connection = $name; return $this; } /** * Resolve a connection instance. * * @param string|null $connection * @return \Illuminate\Database\Connection */ public static function resolveConnection($connection = null) { return static::$resolver->connection($connection); } /** * Get the connection resolver instance. * * @return \Illuminate\Database\ConnectionResolverInterface */ public static function getConnectionResolver() { return static::$resolver; } /** * Set the connection resolver instance. * * @param \Illuminate\Database\ConnectionResolverInterface $resolver * @return void */ public static function setConnectionResolver(Resolver $resolver) { static::$resolver = $resolver; } /** * Unset the connection resolver for models. * * @return void */ public static function unsetConnectionResolver() { static::$resolver = null; } /** * Get the table associated with the model. * * @return string */ public function getTable() { if (! isset($this->table)) { return str_replace( '\\', '', Str::snake(Str::plural(class_basename($this))) ); } return $this->table; } /** * Set the table associated with the model. * * @param string $table * @return $this */ public function setTable($table) { $this->table = $table; return $this; } /** * Get the primary key for the model. * * @return string */ public function getKeyName() { return $this->primaryKey; } /** * Set the primary key for the model. * * @param string $key * @return $this */ public function setKeyName($key) { $this->primaryKey = $key; return $this; } /** * Get the table qualified key name. * * @return string */ public function getQualifiedKeyName() { return $this->qualifyColumn($this->getKeyName()); } /** * Get the auto-incrementing key type. * * @return string */ public function getKeyType() { return $this->keyType; } /** * Set the data type for the primary key. * * @param string $type * @return $this */ public function setKeyType($type) { $this->keyType = $type; return $this; } /** * Get the value indicating whether the IDs are incrementing. * * @return bool */ public function getIncrementing() { return $this->incrementing; } /** * Set whether IDs are incrementing. * * @param bool $value * @return $this */ public function setIncrementing($value) { $this->incrementing = $value; return $this; } /** * Get the value of the model's primary key. * * @return mixed */ public function getKey() { return $this->getAttribute($this->getKeyName()); } /** * Get the queueable identity for the entity. * * @return mixed */ public function getQueueableId() { return $this->getKey(); } /** * Get the queueable relationships for the entity. * * @return array */ public function getQueueableRelations() { $relations = []; foreach ($this->getRelations() as $key => $relation) { if (method_exists($this, $key)) { $relations[] = $key; } if ($relation instanceof QueueableCollection) { foreach ($relation->getQueueableRelations() as $collectionValue) { $relations[] = $key.'.'.$collectionValue; } } if ($relation instanceof QueueableEntity) { foreach ($relation->getQueueableRelations() as $entityKey => $entityValue) { $relations[] = $key.'.'.$entityValue; } } } return array_unique($relations); } /** * Get the queueable connection for the entity. * * @return mixed */ public function getQueueableConnection() { return $this->getConnectionName(); } /** * Get the value of the model's route key. * * @return mixed */ public function getRouteKey() { return $this->getAttribute($this->getRouteKeyName()); } /** * Get the route key for the model. * * @return string */ public function getRouteKeyName() { return $this->getKeyName(); } /** * Retrieve the model for a bound value. * * @param mixed $value * @return \Illuminate\Database\Eloquent\Model|null */ public function resolveRouteBinding($value) { return $this->where($this->getRouteKeyName(), $value)->first(); } /** * Get the default foreign key name for the model. * * @return string */ public function getForeignKey() { return Str::snake(class_basename($this)).'_'.$this->getKeyName(); } /** * Get the number of models to return per page. * * @return int */ public function getPerPage() { return $this->perPage; } /** * Set the number of models to return per page. * * @param int $perPage * @return $this */ public function setPerPage($perPage) { $this->perPage = $perPage; return $this; } /** * Dynamically retrieve attributes on the model. * * @param string $key * @return mixed */ public function __get($key) { return $this->getAttribute($key); } /** * Dynamically set attributes on the model. * * @param string $key * @param mixed $value * @return void */ public function __set($key, $value) { $this->setAttribute($key, $value); } /** * Determine if the given attribute exists. * * @param mixed $offset * @return bool */ public function offsetExists($offset) { return ! is_null($this->getAttribute($offset)); } /** * Get the value for a given offset. * * @param mixed $offset * @return mixed */ public function offsetGet($offset) { return $this->getAttribute($offset); } /** * Set the value for a given offset. * * @param mixed $offset * @param mixed $value * @return void */ public function offsetSet($offset, $value) { $this->setAttribute($offset, $value); } /** * Unset the value for a given offset. * * @param mixed $offset * @return void */ public function offsetUnset($offset) { unset($this->attributes[$offset], $this->relations[$offset]); } /** * Determine if an attribute or relation exists on the model. * * @param string $key * @return bool */ public function __isset($key) { return $this->offsetExists($key); } /** * Unset an attribute on the model. * * @param string $key * @return void */ public function __unset($key) { $this->offsetUnset($key); } /** * Handle dynamic method calls into the model. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { if (in_array($method, ['increment', 'decrement'])) { return $this->$method(...$parameters); } return $this->newQuery()->$method(...$parameters); } /** * Handle dynamic static method calls into the method. * * @param string $method * @param array $parameters * @return mixed */ public static function __callStatic($method, $parameters) { return (new static)->$method(...$parameters); } /** * Convert the model to its string representation. * * @return string */ public function __toString() { return $this->toJson(); } /** * When a model is being unserialized, check if it needs to be booted. * * @return void */ public function __wakeup() { $this->bootIfNotBooted(); } }
Java
using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using ECommon.Components; using ECommon.Scheduling; using ECommon.Socketing; using EQueue.Protocols; namespace EQueue.Broker.Client { public class ConsumerManager { private readonly ConcurrentDictionary<string, ConsumerGroup> _consumerGroupDict = new ConcurrentDictionary<string, ConsumerGroup>(); private readonly IScheduleService _scheduleService; public ConsumerManager() { _scheduleService = ObjectContainer.Resolve<IScheduleService>(); } public void Start() { _consumerGroupDict.Clear(); _scheduleService.StartTask("ScanNotActiveConsumer", ScanNotActiveConsumer, 1000, 1000); } public void Shutdown() { _consumerGroupDict.Clear(); _scheduleService.StopTask("ScanNotActiveConsumer"); } public void RegisterConsumer(string groupName, string consumerId, IEnumerable<string> subscriptionTopics, IEnumerable<MessageQueueEx> consumingQueues, ITcpConnection connection) { var consumerGroup = _consumerGroupDict.GetOrAdd(groupName, key => new ConsumerGroup(key)); consumerGroup.RegisterConsumer(connection, consumerId, subscriptionTopics.ToList(), consumingQueues.ToList()); } public void RemoveConsumer(string connectionId) { foreach (var consumerGroup in _consumerGroupDict.Values) { consumerGroup.RemoveConsumer(connectionId); } } public int GetConsumerGroupCount() { return _consumerGroupDict.Count; } public IEnumerable<ConsumerGroup> GetAllConsumerGroups() { return _consumerGroupDict.Values.ToList(); } public int GetAllConsumerCount() { return GetAllConsumerGroups().Sum(x => x.GetConsumerCount()); } public ConsumerGroup GetConsumerGroup(string groupName) { ConsumerGroup consumerGroup; if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup)) { return consumerGroup; } return null; } public int GetConsumerCount(string groupName) { ConsumerGroup consumerGroup; if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup)) { return consumerGroup.GetConsumerCount(); } return 0; } public int GetClientCacheMessageCount(string groupName, string topic, int queueId) { ConsumerGroup consumerGroup; if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup)) { return consumerGroup.GetClientCacheMessageCount(topic, queueId); } return 0; } public bool IsConsumerActive(string consumerGroup, string consumerId) { var group = GetConsumerGroup(consumerGroup); return group != null && group.IsConsumerActive(consumerId); } public bool IsConsumerExistForQueue(string topic, int queueId) { var groups = GetAllConsumerGroups(); foreach (var group in groups) { if (group.IsConsumerExistForQueue(topic, queueId)) { return true; } } return false; } private void ScanNotActiveConsumer() { foreach (var consumerGroup in _consumerGroupDict.Values) { consumerGroup.RemoveNotActiveConsumers(); } } } }
Java
<?php namespace Phrest\Skeleton\v1\Requests\Users; use Phrest\SDK\Request\AbstractRequest; use Phrest\SDK\Request\RequestOptions; use Phrest\SDK\PhrestSDK; class CreateUserRequest extends AbstractRequest { /** * @var string */ private $path = '/v1/users/'; /** * @var string */ public $name = null; /** * @var string */ public $email = null; /** * @var string */ public $password = null; /** * @param string $name * @param string $email * @param string $password */ public function __construct($name = null, $email = null, $password = null) { $this->name = $name; $this->email = $email; $this->password = $password; } /** * */ public function create() { $requestOptions = new RequestOptions(); $requestOptions->addPostParams( [ 'name' => $this->name, 'email' => $this->email, 'password' => $this->password, ] ); return PhrestSDK::getResponse( self::METHOD_POST, $this->path, $requestOptions ); } /** * @param string $name * * @return static */ public function setName($name) { $this->name = $name; return $this; } /** * @param string $email * * @return static */ public function setEmail($email) { $this->email = $email; return $this; } /** * @param string $password * * @return static */ public function setPassword($password) { $this->password = $password; return $this; } }
Java
'use strict'; // https://github.com/betsol/gulp-require-tasks // Require the module. const gulpRequireTasks = require('gulp-require-tasks'); const gulp = require('gulp'); const env = require('../index'); // Call it when necessary. gulpRequireTasks({ // Pass any options to it. Please see below. path: env.inConfigs('gulp', 'tasks')// This is default }); gulp.task('default', ['scripts:build', 'json-copy:build']);
Java
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData // package to your project. ////#define Handle_PageResultOfT using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Web; using System.Web.Http; #if Handle_PageResultOfT using System.Web.Http.OData; #endif namespace MusicStore.Services.Areas.HelpPage { /// <summary> /// Use this class to customize the Help Page. /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation /// or you can provide the samples for the requests/responses. /// </summary> public static class HelpPageConfig { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "MusicStore.Services.Areas.HelpPage.TextSample.#ctor(System.String)", Justification = "End users may choose to merge this string with existing localized resources.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "bsonspec", Justification = "Part of a URI.")] public static void Register(HttpConfiguration config) { //// Uncomment the following to use the documentation from XML documentation file. //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type //// formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> //{ // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} //}); // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if Handle_PageResultOfT config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. config.SetSampleForMediaType( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new MediaTypeHeaderValue("application/bson")); //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" //// and action named "Put". //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" //// on the controller named "Values" and action named "Get" with parameter "id". //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.SetActualRequestType(typeof(string), "Values", "Get"); //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.SetActualResponseType(typeof(string), "Values", "Post"); } #if Handle_PageResultOfT private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) { if (type.IsGenericType) { Type openGenericType = type.GetGenericTypeDefinition(); if (openGenericType == typeof(PageResult<>)) { // Get the T in PageResult<T> Type[] typeParameters = type.GetGenericArguments(); Debug.Assert(typeParameters.Length == 1); // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor Type itemsType = typeof(List<>).MakeGenericType(typeParameters); object items = sampleGenerator.GetSampleObject(itemsType); // Fill in the other information needed to invoke the PageResult<T> constuctor Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor ConstructorInfo constructor = type.GetConstructor(parameterTypes); return constructor.Invoke(parameters); } } return null; } #endif } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CacheCow.Server.EntityTagStore.SqlServer { internal class ColumnNames { public static string CacheKeyHash = "CacheKeyHash"; public static string RoutePattern = "RoutePattern"; public static string ResourceUri = "ResourceUri"; public static string ETag = "ETag"; public static string LastModified = "LastModified"; } }
Java