code
stringlengths
4
1.01M
language
stringclasses
2 values
// // NSDictionary+Enumerable.h // MRCEnumerable // // Created by Marcus Crafter on 17/11/10. // Copyright 2010 Red Artisan. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDictionary (Enumerable) - (void)each:(void (^)(id key, id obj))block; - (id)inject:(id)m :(id (^)(id m, id key, id obj))block; - (NSDictionary *)select:(BOOL (^)(id key, id obj))block; - (NSDictionary *)reject:(BOOL (^)(id key, id obj))block; - (id)detect:(BOOL (^)(id key, id obj))block; @end
Java
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Properties of an artifact source. * * @extends models['Resource'] */ class ArtifactSource extends models['Resource'] { /** * Create a ArtifactSource. * @member {string} [displayName] The artifact source's display name. * @member {string} [uri] The artifact source's URI. * @member {string} [sourceType] The artifact source's type. Possible values * include: 'VsoGit', 'GitHub' * @member {string} [folderPath] The folder containing artifacts. * @member {string} [armTemplateFolderPath] The folder containing Azure * Resource Manager templates. * @member {string} [branchRef] The artifact source's branch reference. * @member {string} [securityToken] The security token to authenticate to the * artifact source. * @member {string} [status] Indicates if the artifact source is enabled * (values: Enabled, Disabled). Possible values include: 'Enabled', * 'Disabled' * @member {date} [createdDate] The artifact source's creation date. * @member {string} [provisioningState] The provisioning status of the * resource. * @member {string} [uniqueIdentifier] The unique immutable identifier of a * resource (Guid). */ constructor() { super(); } /** * Defines the metadata of ArtifactSource * * @returns {object} metadata of ArtifactSource * */ mapper() { return { required: false, serializedName: 'ArtifactSource', type: { name: 'Composite', className: 'ArtifactSource', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, location: { required: false, serializedName: 'location', type: { name: 'String' } }, tags: { required: false, serializedName: 'tags', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, displayName: { required: false, serializedName: 'properties.displayName', type: { name: 'String' } }, uri: { required: false, serializedName: 'properties.uri', type: { name: 'String' } }, sourceType: { required: false, serializedName: 'properties.sourceType', type: { name: 'String' } }, folderPath: { required: false, serializedName: 'properties.folderPath', type: { name: 'String' } }, armTemplateFolderPath: { required: false, serializedName: 'properties.armTemplateFolderPath', type: { name: 'String' } }, branchRef: { required: false, serializedName: 'properties.branchRef', type: { name: 'String' } }, securityToken: { required: false, serializedName: 'properties.securityToken', type: { name: 'String' } }, status: { required: false, serializedName: 'properties.status', type: { name: 'String' } }, createdDate: { required: false, readOnly: true, serializedName: 'properties.createdDate', type: { name: 'DateTime' } }, provisioningState: { required: false, serializedName: 'properties.provisioningState', type: { name: 'String' } }, uniqueIdentifier: { required: false, serializedName: 'properties.uniqueIdentifier', type: { name: 'String' } } } } }; } } module.exports = ArtifactSource;
Java
// implementation for cube_support.h #include <utils/multiindex.h> #include <utils/fixed_array1d.h> using MathTL::multi_degree; using MathTL::FixedArray1D; namespace WaveletTL { template <class IBASIS, unsigned int DIM> inline void support(const CubeBasis<IBASIS,DIM>& basis, const typename CubeBasis<IBASIS,DIM>::Index& lambda, typename CubeBasis<IBASIS,DIM>::Support& supp) { basis.support(lambda, supp); } template <class IBASIS, unsigned int DIM> bool intersect_supports(const CubeBasis<IBASIS,DIM>& basis, const typename CubeBasis<IBASIS,DIM>::Index& lambda, const typename CubeBasis<IBASIS,DIM>::Index& mu, typename CubeBasis<IBASIS,DIM>::Support& supp) { typename CubeBasis<IBASIS,DIM>::Support supp_lambda; WaveletTL::support<IBASIS,DIM>(basis, lambda, supp_lambda); typename CubeBasis<IBASIS,DIM>::Support supp_mu; WaveletTL::support<IBASIS,DIM>(basis, mu, supp_mu); // determine support intersection granularity, // adjust single support granularities if necessary supp.j = std::max(supp_lambda.j, supp_mu.j); if (supp_lambda.j > supp_mu.j) { const int adjust = 1<<(supp_lambda.j-supp_mu.j); for (unsigned int i = 0; i < DIM; i++) { supp_mu.a[i] *= adjust; supp_mu.b[i] *= adjust; } } else { const int adjust = 1<<(supp_mu.j-supp_lambda.j); for (unsigned int i = 0; i < DIM; i++) { supp_lambda.a[i] *= adjust; supp_lambda.b[i] *= adjust; } } for (unsigned int i = 0; i < DIM; i++) { supp.a[i] = std::max(supp_lambda.a[i],supp_mu.a[i]); supp.b[i] = std::min(supp_lambda.b[i],supp_mu.b[i]); if (supp.a[i] >= supp.b[i]) { return false; } } return true; } template <class IBASIS, unsigned int DIM> void intersecting_wavelets(const CubeBasis<IBASIS,DIM>& basis, const typename CubeBasis<IBASIS,DIM>::Index& lambda, const int j, const bool generators, std::list<typename CubeBasis<IBASIS,DIM>::Index>& intersecting) { typedef typename CubeBasis<IBASIS,DIM>::Index Index; intersecting.clear(); #if 1 // the set of intersecting wavelets is a cartesian product from d sets from the 1D case, // so we only have to compute the relevant 1D indices typedef typename IBASIS::Index Index1D; FixedArray1D<std::list<Index1D>,DIM> intersecting_1d_generators, intersecting_1d_wavelets; // prepare all intersecting wavelets and generators in the i-th coordinate direction for (unsigned int i = 0; i < DIM; i++) { intersecting_wavelets(*basis.bases()[i], Index1D(lambda.j(), lambda.e()[i], lambda.k()[i], basis.bases()[i]), j, true, intersecting_1d_generators[i]); if (!(generators)) { intersecting_wavelets(*basis.bases()[i], Index1D(lambda.j(), lambda.e()[i], lambda.k()[i], basis.bases()[i]), j, false, intersecting_1d_wavelets[i]); } } // generate all relevant tensor product indices with either e=(0,...,0) or e!=(0,...,0) typedef std::list<FixedArray1D<Index1D,DIM> > list_type; list_type indices; FixedArray1D<Index1D,DIM> helpindex; if (DIM > 1 || (DIM == 1 && generators)) { for (typename std::list<Index1D>::const_iterator it(intersecting_1d_generators[0].begin()), itend(intersecting_1d_generators[0].end()); it != itend; ++it) { helpindex[0] = *it; indices.push_back(helpindex); } } if (!(generators)) { for (typename std::list<Index1D>::const_iterator it(intersecting_1d_wavelets[0].begin()), itend(intersecting_1d_wavelets[0].end()); it != itend; ++it) { helpindex[0] = *it; indices.push_back(helpindex); } } for (unsigned int i = 1; i < DIM; i++) { list_type sofar; sofar.swap(indices); for (typename list_type::const_iterator itready(sofar.begin()), itreadyend(sofar.end()); itready != itreadyend; ++itready) { helpindex = *itready; unsigned int esum = 0; for (unsigned int k = 0; k < i; k++) { esum += helpindex[k].e(); } if (generators || (i < DIM-1 || (i == (DIM-1) && esum > 0))) { for (typename std::list<Index1D>::const_iterator it(intersecting_1d_generators[i].begin()), itend(intersecting_1d_generators[i].end()); it != itend; ++it) { helpindex[i] = *it; indices.push_back(helpindex); } } if (!(generators)) { for (typename std::list<Index1D>::const_iterator it(intersecting_1d_wavelets[i].begin()), itend(intersecting_1d_wavelets[i].end()); it != itend; ++it) { helpindex[i] = *it; indices.push_back(helpindex); } } } } // compose the results typename Index::type_type help_e; typename Index::translation_type help_k; for (typename list_type::const_iterator it(indices.begin()), itend(indices.end()); it != itend; ++it) { for (unsigned int i = 0; i < DIM; i++) { help_e[i] = (*it)[i].e(); help_k[i] = (*it)[i].k(); } intersecting.push_back(Index(j, help_e, help_k, &basis)); } #else typedef typename CubeBasis<IBASIS,DIM>::Index Index; int k = -1; if ( generators ) { k=0; } else { k=j-basis.j0()+1; } //std::list<typename Frame::Index> intersect_diff; //! generators if (true) { FixedArray1D<int,DIM> minkwavelet, maxkwavelet, minkgen, maxkgen; typedef typename IBASIS::Index Index1D; int minkkkk; int maxkkkk; // prepare all intersecting wavelets and generators in the i-th coordinate direction for (unsigned int i = 0; i < DIM; i++) { get_intersecting_wavelets_on_level(*basis.bases()[i], Index1D(lambda.j(), lambda.e()[i], lambda.k()[i], basis.bases()[i]), j, true, minkkkk,maxkkkk); minkgen[i]=minkkkk; maxkgen[i] = maxkkkk; if (!(generators)) get_intersecting_wavelets_on_level(*basis.bases()[i], Index1D(lambda.j(), lambda.e()[i], lambda.k()[i], basis.bases()[i]), j, false, minkkkk,maxkkkk); minkwavelet[i] = minkkkk; maxkwavelet[i] = maxkkkk; } // end for unsigned int result = 0; int deltaresult = 0; int genfstlvl = 0; bool gen = 0; //const Array1D<Index>* full_collection = &basis.full_collection; MultiIndex<int,DIM> type; type[DIM-1] = 1; unsigned int tmp = 1; bool exit = 0; // determine how many wavelets there are on all the levels // below the level of this index if (! gen) { result = 0; genfstlvl =1; //generators on level j0 for (unsigned int i = 0; i< DIM; i++) genfstlvl *= (basis.bases()[i])->Deltasize((basis.bases()[i])->j0()); //additional wavelets on level j // =(#Gen[1]+#Wav[1])*...*(#Gen[Dim-1]+#Wav[Dim-1]) // -#Gen[1]*...*#Gen[Dim-1] for (int lvl= 0 ; lvl < (j -basis.j0()); lvl++){ int genCurLvl = 1; int addWav = 1; for (unsigned int i = 0; i< DIM; i++) { unsigned int curJ = basis.bases()[i]->j0()+lvl; int genCurDim = (basis.bases()[i])->Deltasize(curJ); genCurLvl *= genCurDim; addWav *= genCurDim+ (basis.bases()[i])->Nablasize(curJ); } result += addWav-genCurLvl; } result += genfstlvl; } while(!exit){ FixedArray1D<int,DIM> help1, help2; for(unsigned int i = 0; i<DIM; i++) help1[i]=0; // berechnet wie viele indices mit einem zu kleinem translationstyp es gibt, so dass sich die Wavelets nicht schneiden unsigned int result2 = 0; for (unsigned int i = 0; i < DIM; i++) { // begin for1 int tmp = 1; for (unsigned int l = i+1; l < DIM; l++) { if (type[l] == 0) tmp *= (basis.bases())[l]->Deltasize(j); else tmp *= (basis.bases())[l]->Nablasize(j); } help2[i] = tmp; if (type[i] == 0) { if (minkgen[i] == (basis.bases())[i]->DeltaLmin()) continue; } else if (minkwavelet[i] == (basis.bases())[i]->Nablamin()) continue; if (type[i] == 0) { tmp *= minkgen[i]-(basis.bases())[i]->DeltaLmin(); } else tmp *= minkwavelet[i]-(basis.bases())[i]->Nablamin(); result2 += tmp; } // end for1 int tmp = 0; if (type[DIM-1] == 0) { tmp = maxkgen[DIM-1] - minkgen[DIM-1]+1; } else{ tmp = maxkwavelet[DIM-1] - minkwavelet[DIM-1]+1; } bool exit2 = 0; while(!exit2){ // fügt die Indizes ein die sich überlappen for (unsigned int i = result + result2; i < result + result2 + tmp; i++) { const Index* ind = basis.get_wavelet(i); //&((*full_collection)[i]); intersecting.push_back(*ind); } for (unsigned int i = DIM-2; i >= 0; i--) { if(type[i]==0){ if ( help1[i] < maxkgen[i]-minkgen[i]) { help1[i]++; result2 = result2 + help2[i]; for (unsigned int j = i+1; j<=DIM-2;j++){ if(type[i] == 0){ result2 = result2 - help2[j]*(maxkgen[j] - minkgen[j]+1); } else result2 = result2 - help2[j]*(maxkwavelet[j] - minkwavelet[j]+1); } break; } else { help1[i]=0; exit2 = (i==0); break; } } else { if ( help1[i] < maxkwavelet[i] - minkwavelet[i]) { help1[i]++; result2 = result2 + help2[i]; for (unsigned int j = i+1; j<=DIM-2;j++){ if(type[i] == 0){ result2 = result2 - help2[j]*(maxkgen[j] - minkgen[j]+1); } else result2 = result2 - help2[j]*(maxkwavelet[j] - minkwavelet[j]+1); } break; } else { help1[i]=0; exit2 = (i==0); break; } } } //end for } //end while 2 // berechnet wie viele Indizes von dem jeweiligen Typ in Patches p liegen tmp = 1; for (unsigned int i = 0; i < DIM; i++) { if (type[i] == 0) tmp *= (basis.bases())[i]->Deltasize(j); else tmp *= (basis.bases())[i]->Nablasize(j); } result += tmp; // berechnet den nächsten Typ for (unsigned int i = DIM-1; i >= 0; i--) { if ( type[i] == 1 ) { type[i] = 0; exit = (i == 0); if(exit) break; } else { type[i]++; break; } } //end for } // end while 1 } // end if // } // end if else { // if generators // a brute force solution typedef typename CubeBasis<IBASIS,DIM>::Support Support; Support supp; if (generators) { for (Index mu = basis.first_generator (j);; ++mu) { if (intersect_supports(basis, lambda, mu, supp)) intersecting.push_back(mu); if (mu == basis.last_generator(j)) break; } } } //*/ #endif //#else #if 0 // a brute force solution typedef typename CubeBasis<IBASIS,DIM>::Support Support; Support supp; if (generators) { for (Index mu = first_generator<IBASIS,DIM>(&basis, j);; ++mu) { if (intersect_supports(basis, lambda, mu, supp)) intersecting.push_back(mu); if (mu == last_generator<IBASIS,DIM>(&basis, j)) break; } } else { for (Index mu = first_wavelet<IBASIS,DIM>(&basis, j);; ++mu) { if (intersect_supports(basis, lambda, mu, supp)) intersecting.push_back(mu); if (mu == last_wavelet<IBASIS,DIM>(&basis, j)) break; } } #endif } template <class IBASIS, unsigned int DIM> bool intersect_singular_support(const CubeBasis<IBASIS,DIM>& basis, const typename CubeBasis<IBASIS,DIM>::Index& lambda, const typename CubeBasis<IBASIS,DIM>::Index& mu) { // we have intersection of the singular supports if and only if // one of the components have this property in one dimension typedef typename IBASIS::Index Index1D; for (unsigned int i = 0; i < DIM; i++) { if (intersect_singular_support (*basis.bases()[i], Index1D(lambda.j(), lambda.e()[i], lambda.k()[i], basis.bases()[i]), Index1D(mu.j(), mu.e()[i], mu.k()[i], basis.bases()[i]))) return true; } return false; } }
Java
<?php /** * Config class **/ class Config extends Application { private $config; function __construct($param = array()) { if (!empty($param['file'])) { $this -> load($param['file']); } } public function reset() { $this -> config = array(); } public function load($filename = '') { $file = APP . DIRECTORY_SEPARATOR . 'Configs' . DIRECTORY_SEPARATOR . $filename . '.ini'; if (file_exists($file)) { $this -> config = parse_ini_file($file); } } function __get($value) { return $this -> config[$value]; } }
Java
# frozen_string_literal: true class AddFieldsToCourseMaterialFolders < ActiveRecord::Migration[4.2] def change remove_column :course_material_folders, :parent_folder_id, :integer, foreign_key: { references: :course_material_folders } add_column :course_material_folders, :parent_id, :integer add_column :course_material_folders, :course_id, :integer, null: false add_column :course_material_folders, :can_student_upload, :boolean, null: false, default: false add_index :course_material_folders, [:parent_id, :name], unique: true, case_sensitive: false end end
Java
MoeDownloader ====== 基于python的福利图嗅探器,目前可以嗅探草榴、煎蛋和二次萌エロ画像ブログ这三个网站的图片,如果需要加入其他网站也比较容易。 基本用法: ====== "` python catch.py [topic] `" 其中,[topic]可以是caoliu、moeimg、jandan三个选项之一 更多的用法请输入 "` python catch.py -h `" 来查看
Java
module Emulation export run_cpu const EMULATED_INTRINSICS = [ :get_global_id, :get_global_size ] type EmulationContext global_id global_size function EmulationContext() new( [0,0,0], [0,0,0] ) end end # Emulated version of intrinsic functions # mainly for testing and execution on the CPU function get_global_id(ctx::EmulationContext, dim::Int32) return ctx.global_id[dim + 1] end function get_global_size(ctx::EmulationContext, dim::Int32) return ctx.global_size[dim + 1] end # Helpers for adding an emulation overload for a kernel const CTX = gensym("ctx") function visit_ast(f :: Function, ast) f(ast) if isa(ast, Expr) for a in ast.args visit_ast(f, a) end end end function add_intrinsics_ctx_arg(ex) if isa(ex, Expr) && ex.head == :call fname = ex.args[1] if in(fname, EMULATED_INTRINSICS) # add context as first argument (after the function name) insert!(ex.args, 2, CTX) # qualify the call to the Emulation module ex.args[1] = :(Emulation.$fname) end end end function add_emulation(fun::Expr) sig = fun.args[1] # insert ctx as first argument (after the function name) insert!(sig.args, 2, :($CTX :: HSA.Emulation.EmulationContext)) visit_ast(add_intrinsics_ctx_arg, fun) end function run_cpu(rng::Tuple{Int,Int,Int}, kernel::Function, args...) ctx = Emulation.EmulationContext() ctx.global_size = [rng...] for x = 0:rng[1]-1 for y = 0:rng[2]-1 for z = 0:rng[3]-1 ctx.global_id[1:3] = [x,y,z] kernel(ctx, args...) end end end end end # module Emulation export @hsa_kernel """ Marks a function as implementing an HSA kernel That means that it needs to be handled differently from a host function during code generation. Also, this macro enables emulation support for the kernel by adding a method that takes an EmulationContext as an additional argument. """ macro hsa_kernel(fun::Expr) if(fun.head != :function) error("@hsa_kernel must be applied to a function definition") end emu_fun = copy(fun) Emulation.add_emulation(emu_fun) if has_hsa_codegen() device_fun = HSA.Execution.hsa_kernel(fun) else device_fun = quote end end return quote $(esc(device_fun)) $(esc(emu_fun)) end end # if codegen is not available, we need to emulate @hsa if !has_hsa_codegen() include("execution.jl") end
Java
package bf.io.openshop.entities; public class Page { private long id; private String title; private String text; public Page() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Page page = (Page) o; if (id != page.id) return false; if (title != null ? !title.equals(page.title) : page.title != null) return false; return !(text != null ? !text.equals(page.text) : page.text != null); } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (text != null ? text.hashCode() : 0); return result; } @Override public String toString() { return "Page{" + "id=" + id + ", title='" + title + '\'' + ", text='" + text + '\'' + '}'; } }
Java
require 'abstract_unit' require 'controller/fake_models' class CustomersController < ActionController::Base end module Fun class GamesController < ActionController::Base def hello_world end end end module NewRenderTestHelper def rjs_helper_method_from_module page.visual_effect :highlight end end class LabellingFormBuilder < ActionView::Helpers::FormBuilder end class NewRenderTestController < ActionController::Base layout :determine_layout def self.controller_name; "test"; end def self.controller_path; "test"; end def hello_world end def render_hello_world render :template => "test/hello_world" end def render_hello_world_from_variable @person = "david" render :text => "hello #{@person}" end def render_action_hello_world render :action => "hello_world" end def render_action_hello_world_as_symbol render :action => :hello_world end def render_text_hello_world render :text => "hello world" end def render_text_hello_world_with_layout @variable_for_layout = ", I'm here!" render :text => "hello world", :layout => true end def hello_world_with_layout_false render :layout => false end def render_custom_code render :text => "hello world", :status => "404 Moved" end def render_file_with_instance_variables @secret = 'in the sauce' path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb') render :file => path end def render_file_with_locals path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb') render :file => path, :locals => {:secret => 'in the sauce'} end def render_file_not_using_full_path @secret = 'in the sauce' render :file => 'test/render_file_with_ivar', :use_full_path => true end def render_file_not_using_full_path_with_dot_in_path @secret = 'in the sauce' render :file => 'test/dot.directory/render_file_with_ivar', :use_full_path => true end def render_xml_hello @name = "David" render :template => "test/hello" end def greeting # let's just rely on the template end def layout_test render :action => "hello_world" end def layout_test_with_different_layout render :action => "hello_world", :layout => "standard" end def rendering_without_layout render :action => "hello_world", :layout => false end def layout_overriding_layout render :action => "hello_world", :layout => "standard" end def rendering_nothing_on_layout render :nothing => true end def builder_layout_test render :action => "hello" end def partials_list @test_unchanged = 'hello' @customers = [ Customer.new("david"), Customer.new("mary") ] render :action => "list" end def partial_only render :partial => true end def partial_only_with_layout render :partial => "partial_only", :layout => true end def partial_with_locals render :partial => "customer", :locals => { :customer => Customer.new("david") } end def partial_with_form_builder render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, @template, {}, Proc.new {}) end def partial_with_form_builder_subclass render :partial => LabellingFormBuilder.new(:post, nil, @template, {}, Proc.new {}) end def partial_collection render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_with_spacer render :partial => "customer", :spacer_template => "partial_only", :collection => [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_with_counter render :partial => "customer_counter", :collection => [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_with_locals render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } end def partial_collection_shorthand_with_locals render :partial => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } end def partial_collection_shorthand_with_different_types_of_records render :partial => [ BadCustomer.new("mark"), GoodCustomer.new("craig"), BadCustomer.new("john"), GoodCustomer.new("zach"), GoodCustomer.new("brandon"), BadCustomer.new("dan") ], :locals => { :greeting => "Bonjour" } end def partial_collection_shorthand_with_different_types_of_records_with_counter partial_collection_shorthand_with_different_types_of_records end def empty_partial_collection render :partial => "customer", :collection => [] end def partial_with_hash_object render :partial => "hash_object", :object => {:first_name => "Sam"} end def partial_hash_collection render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ] end def partial_hash_collection_with_locals render :partial => "hash_greeting", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ], :locals => { :greeting => "Hola" } end def partial_with_implicit_local_assignment @customer = Customer.new("Marcel") render :partial => "customer" end def missing_partial render :partial => 'thisFileIsntHere' end def hello_in_a_string @customers = [ Customer.new("david"), Customer.new("mary") ] render :text => "How's there? " << render_to_string(:template => "test/list") end def render_to_string_with_assigns @before = "i'm before the render" render_to_string :text => "foo" @after = "i'm after the render" render :action => "test/hello_world" end def render_to_string_with_partial @partial_only = render_to_string :partial => "partial_only" @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") } render :action => "test/hello_world" end def render_to_string_with_exception render_to_string :file => "exception that will not be caught - this will certainly not work", :use_full_path => true end def render_to_string_with_caught_exception @before = "i'm before the render" begin render_to_string :file => "exception that will be caught- hope my future instance vars still work!", :use_full_path => true rescue end @after = "i'm after the render" render :action => "test/hello_world" end def accessing_params_in_template render :inline => "Hello: <%= params[:name] %>" end def accessing_params_in_template_with_layout render :layout => nil, :inline => "Hello: <%= params[:name] %>" end def render_with_explicit_template render :template => "test/hello_world" end def double_render render :text => "hello" render :text => "world" end def double_redirect redirect_to :action => "double_render" redirect_to :action => "double_render" end def render_and_redirect render :text => "hello" redirect_to :action => "double_render" end def render_to_string_and_render @stuff = render_to_string :text => "here is some cached stuff" render :text => "Hi web users! #{@stuff}" end def rendering_with_conflicting_local_vars @name = "David" def @template.name() nil end render :action => "potential_conflicts" end def hello_world_from_rxml_using_action render :action => "hello_world_from_rxml.builder" end def hello_world_from_rxml_using_template render :template => "test/hello_world_from_rxml.builder" end def head_with_location_header head :location => "/foo" end def head_with_symbolic_status head :status => params[:status].intern end def head_with_integer_status head :status => params[:status].to_i end def head_with_string_status head :status => params[:status] end def head_with_custom_header head :x_custom_header => "something" end def head_with_status_code_first head :forbidden, :x_custom_header => "something" end def render_with_location render :xml => "<hello/>", :location => "http://example.com", :status => 201 end def render_with_object_location customer = Customer.new("Some guy", 1) render :xml => "<customer/>", :location => customer_url(customer), :status => :created end def render_with_to_xml to_xmlable = Class.new do def to_xml "<i-am-xml/>" end end.new render :xml => to_xmlable end helper NewRenderTestHelper helper do def rjs_helper_method(value) page.visual_effect :highlight, value end end def enum_rjs_test render :update do |page| page.select('.product').each do |value| page.rjs_helper_method_from_module page.rjs_helper_method(value) page.sortable(value, :url => { :action => "order" }) page.draggable(value) end end end def delete_with_js @project_id = 4 end def render_js_with_explicit_template @project_id = 4 render :template => 'test/delete_with_js' end def render_js_with_explicit_action_template @project_id = 4 render :action => 'delete_with_js' end def update_page render :update do |page| page.replace_html 'balance', '$37,000,000.00' page.visual_effect :highlight, 'balance' end end def update_page_with_instance_variables @money = '$37,000,000.00' @div_id = 'balance' render :update do |page| page.replace_html @div_id, @money page.visual_effect :highlight, @div_id end end def action_talk_to_layout # Action template sets variable that's picked up by layout end def render_text_with_assigns @hello = "world" render :text => "foo" end def yield_content_for render :action => "content_for", :layout => "yield" end def render_content_type_from_body response.content_type = Mime::RSS render :text => "hello world!" end def render_call_to_partial_with_layout render :action => "calling_partial_with_layout" end def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout render :action => "calling_partial_with_layout" end def render_using_layout_around_block render :action => "using_layout_around_block" end def render_using_layout_around_block_in_main_layout_and_within_content_for_layout render :action => "using_layout_around_block" end def rescue_action(e) raise end private def determine_layout case action_name when "hello_world", "layout_test", "rendering_without_layout", "rendering_nothing_on_layout", "render_text_hello_world", "render_text_hello_world_with_layout", "hello_world_with_layout_false", "partial_only", "partial_only_with_layout", "accessing_params_in_template", "accessing_params_in_template_with_layout", "render_with_explicit_template", "render_js_with_explicit_template", "render_js_with_explicit_action_template", "delete_with_js", "update_page", "update_page_with_instance_variables" "layouts/standard" when "builder_layout_test" "layouts/builder" when "action_talk_to_layout", "layout_overriding_layout" "layouts/talk_from_action" when "render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout" "layouts/partial_with_layout" when "render_using_layout_around_block_in_main_layout_and_within_content_for_layout" "layouts/block_with_layout" end end end NewRenderTestController.view_paths = [ File.dirname(__FILE__) + "/../fixtures/" ] Fun::GamesController.view_paths = [ File.dirname(__FILE__) + "/../fixtures/" ] class NewRenderTest < Test::Unit::TestCase def setup @controller = NewRenderTestController.new # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.host = "www.nextangle.com" end def test_simple_show get :hello_world assert_response :success assert_template "test/hello_world" assert_equal "<html>Hello world!</html>", @response.body end def test_do_with_render get :render_hello_world assert_template "test/hello_world" end def test_do_with_render_from_variable get :render_hello_world_from_variable assert_equal "hello david", @response.body end def test_do_with_render_action get :render_action_hello_world assert_template "test/hello_world" end def test_do_with_render_action_as_symbol get :render_action_hello_world_as_symbol assert_template "test/hello_world" end def test_do_with_render_text get :render_text_hello_world assert_equal "hello world", @response.body end def test_do_with_render_text_and_layout get :render_text_hello_world_with_layout assert_equal "<html>hello world, I'm here!</html>", @response.body end def test_do_with_render_action_and_layout_false get :hello_world_with_layout_false assert_equal 'Hello world!', @response.body end def test_do_with_render_custom_code get :render_custom_code assert_response :missing end def test_render_file_with_instance_variables get :render_file_with_instance_variables assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_not_using_full_path get :render_file_not_using_full_path assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_not_using_full_path_with_dot_in_path get :render_file_not_using_full_path_with_dot_in_path assert_equal "The secret is in the sauce\n", @response.body end def test_render_file_with_locals get :render_file_with_locals assert_equal "The secret is in the sauce\n", @response.body end def test_attempt_to_access_object_method assert_raises(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } end def test_private_methods assert_raises(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout } end def test_access_to_request_in_view view_internals_old_value = ActionController::Base.view_controller_internals ActionController::Base.view_controller_internals = false ActionController::Base.protected_variables_cache = nil get :hello_world assert !assigns.include?('_request'), '_request should not be in assigns' assert !assigns.include?('request'), 'request should not be in assigns' ActionController::Base.view_controller_internals = true ActionController::Base.protected_variables_cache = nil get :hello_world assert !assigns.include?('request'), 'request should not be in assigns' assert_kind_of ActionController::AbstractRequest, assigns['_request'] assert_kind_of ActionController::AbstractRequest, @response.template.request ensure ActionController::Base.view_controller_internals = view_internals_old_value ActionController::Base.protected_variables_cache = nil end def test_render_xml get :render_xml_hello assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body end def test_enum_rjs_test get :enum_rjs_test assert_equal <<-EOS.strip, @response.body $$(".product").each(function(value, index) { new Effect.Highlight(element,{}); new Effect.Highlight(value,{}); Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value)})}}); new Draggable(value, {}); }); EOS end def test_render_xml_with_default get :greeting assert_equal "<p>This is grand!</p>\n", @response.body end def test_render_with_default_from_accept_header @request.env["HTTP_ACCEPT"] = "text/javascript" get :greeting assert_equal "$(\"body\").visualEffect(\"highlight\");", @response.body end def test_render_rjs_with_default get :delete_with_js assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body end def test_render_rjs_template_explicitly get :render_js_with_explicit_template assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body end def test_rendering_rjs_action_explicitly get :render_js_with_explicit_action_template assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body end def test_layout_rendering get :layout_test assert_equal "<html>Hello world!</html>", @response.body end def test_layout_test_with_different_layout get :layout_test_with_different_layout assert_equal "<html>Hello world!</html>", @response.body end def test_rendering_without_layout get :rendering_without_layout assert_equal "Hello world!", @response.body end def test_layout_overriding_layout get :layout_overriding_layout assert_no_match %r{<title>}, @response.body end def test_rendering_nothing_on_layout get :rendering_nothing_on_layout assert_equal " ", @response.body end def test_render_xml_with_layouts get :builder_layout_test assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body end def test_partial_only get :partial_only assert_equal "only partial", @response.body end def test_partial_only_with_layout get :partial_only_with_layout assert_equal "<html>only partial</html>", @response.body end def test_render_to_string assert_not_deprecated { get :hello_in_a_string } assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body end def test_render_to_string_doesnt_break_assigns get :render_to_string_with_assigns assert_equal "i'm before the render", assigns(:before) assert_equal "i'm after the render", assigns(:after) end def test_render_to_string_partial get :render_to_string_with_partial assert_equal "only partial", assigns(:partial_only) assert_equal "Hello: david", assigns(:partial_with_locals) end def test_bad_render_to_string_still_throws_exception assert_raises(ActionController::MissingTemplate) { get :render_to_string_with_exception } end def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns assert_nothing_raised { get :render_to_string_with_caught_exception } assert_equal "i'm before the render", assigns(:before) assert_equal "i'm after the render", assigns(:after) end def test_nested_rendering get :hello_world assert_equal "Living in a nested world", Fun::GamesController.process(@request, @response).body end def test_accessing_params_in_template get :accessing_params_in_template, :name => "David" assert_equal "Hello: David", @response.body end def test_accessing_params_in_template_with_layout get :accessing_params_in_template_with_layout, :name => "David" assert_equal "<html>Hello: David</html>", @response.body end def test_render_with_explicit_template get :render_with_explicit_template assert_response :success end def test_double_render assert_raises(ActionController::DoubleRenderError) { get :double_render } end def test_double_redirect assert_raises(ActionController::DoubleRenderError) { get :double_redirect } end def test_render_and_redirect assert_raises(ActionController::DoubleRenderError) { get :render_and_redirect } end # specify the one exception to double render rule - render_to_string followed by render def test_render_to_string_and_render get :render_to_string_and_render assert_equal("Hi web users! here is some cached stuff", @response.body) end def test_rendering_with_conflicting_local_vars get :rendering_with_conflicting_local_vars assert_equal("First: David\nSecond: Stephan\nThird: David\nFourth: David\nFifth: ", @response.body) end def test_action_talk_to_layout get :action_talk_to_layout assert_equal "<title>Talking to the layout</title>\nAction was here!", @response.body end def test_partials_list get :partials_list assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body end def test_partial_with_locals get :partial_with_locals assert_equal "Hello: david", @response.body end def test_partial_with_form_builder get :partial_with_form_builder assert_match(/<label/, @response.body) assert_template('test/_form') end def test_partial_with_form_builder_subclass get :partial_with_form_builder_subclass assert_match(/<label/, @response.body) assert_template('test/_labelling_form') end def test_partial_collection get :partial_collection assert_equal "Hello: davidHello: mary", @response.body end def test_partial_collection_with_counter get :partial_collection_with_counter assert_equal "david1mary2", @response.body end def test_partial_collection_with_locals get :partial_collection_with_locals assert_equal "Bonjour: davidBonjour: mary", @response.body end def test_partial_collection_with_spacer get :partial_collection_with_spacer assert_equal "Hello: davidonly partialHello: mary", @response.body end def test_partial_collection_shorthand_with_locals get :partial_collection_shorthand_with_locals assert_equal "Bonjour: davidBonjour: mary", @response.body end def test_partial_collection_shorthand_with_different_types_of_records get :partial_collection_shorthand_with_different_types_of_records assert_equal "Bonjour bad customer: mark1Bonjour good customer: craig2Bonjour bad customer: john3Bonjour good customer: zach4Bonjour good customer: brandon5Bonjour bad customer: dan6", @response.body end def test_empty_partial_collection get :empty_partial_collection assert_equal " ", @response.body end def test_partial_with_hash_object get :partial_with_hash_object assert_equal "Sam\nmaS\n", @response.body end def test_hash_partial_collection get :partial_hash_collection assert_equal "Pratik\nkitarP\nAmy\nymA\n", @response.body end def test_partial_hash_collection_with_locals get :partial_hash_collection_with_locals assert_equal "Hola: PratikHola: Amy", @response.body end def test_partial_with_implicit_local_assignment get :partial_with_implicit_local_assignment assert_equal "Hello: Marcel", @response.body end def test_render_missing_partial_template assert_raises(ActionView::ActionViewError) do get :missing_partial end end def test_render_text_with_assigns get :render_text_with_assigns assert_equal "world", assigns["hello"] end def test_update_page get :update_page assert_template nil assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] assert_equal 2, @response.body.split($/).length end def test_update_page_with_instance_variables get :update_page_with_instance_variables assert_template nil assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] assert_match /balance/, @response.body assert_match /\$37/, @response.body end def test_yield_content_for assert_not_deprecated { get :yield_content_for } assert_equal "<title>Putting stuff in the title!</title>\n\nGreat stuff!\n", @response.body end def test_overwritting_rendering_relative_file_with_extension get :hello_world_from_rxml_using_template assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body get :hello_world_from_rxml_using_action assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body end def test_head_with_location_header get :head_with_location_header assert @response.body.blank? assert_equal "/foo", @response.headers["Location"] assert_response :ok end def test_head_with_custom_header get :head_with_custom_header assert @response.body.blank? assert_equal "something", @response.headers["X-Custom-Header"] assert_response :ok end def test_head_with_symbolic_status get :head_with_symbolic_status, :status => "ok" assert_equal "200 OK", @response.headers["Status"] assert_response :ok get :head_with_symbolic_status, :status => "not_found" assert_equal "404 Not Found", @response.headers["Status"] assert_response :not_found ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE.each do |status, code| get :head_with_symbolic_status, :status => status.to_s assert_equal code, @response.response_code assert_response status end end def test_head_with_integer_status ActionController::StatusCodes::STATUS_CODES.each do |code, message| get :head_with_integer_status, :status => code.to_s assert_equal message, @response.message end end def test_head_with_string_status get :head_with_string_status, :status => "404 Eat Dirt" assert_equal 404, @response.response_code assert_equal "Eat Dirt", @response.message assert_response :not_found end def test_head_with_status_code_first get :head_with_status_code_first assert_equal 403, @response.response_code assert_equal "Forbidden", @response.message assert_equal "something", @response.headers["X-Custom-Header"] assert_response :forbidden end def test_rendering_with_location_should_set_header get :render_with_location assert_equal "http://example.com", @response.headers["Location"] end def test_rendering_xml_should_call_to_xml_if_possible get :render_with_to_xml assert_equal "<i-am-xml/>", @response.body end def test_rendering_with_object_location_should_set_header_with_url_for ActionController::Routing::Routes.draw do |map| map.resources :customers map.connect ':controller/:action/:id' end get :render_with_object_location assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] end def test_render_call_to_partial_with_layout get :render_call_to_partial_with_layout assert_equal "Before (David)\nInside from partial (David)\nAfter", @response.body end def test_render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout get :render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout assert_equal "Before (Anthony)\nInside from partial (Anthony)\nAfter\nBefore (David)\nInside from partial (David)\nAfter\nBefore (Ramm)\nInside from partial (Ramm)\nAfter", @response.body end def test_using_layout_around_block get :render_using_layout_around_block assert_equal "Before (David)\nInside from block\nAfter", @response.body end def test_using_layout_around_block_in_main_layout_and_within_content_for_layout get :render_using_layout_around_block_in_main_layout_and_within_content_for_layout assert_equal "Before (Anthony)\nInside from first block in layout\nAfter\nBefore (David)\nInside from block\nAfter\nBefore (Ramm)\nInside from second block in layout\nAfter\n", @response.body end end
Java
/** * Bootstrap * (sails.config.bootstrap) * * An asynchronous bootstrap function that runs before your Sails app gets lifted. * This gives you an opportunity to set up your data model, run jobs, or perform some special logic. * * For more information on bootstrapping your app, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html */ module.exports.bootstrap = function(cb) { // It's very important to trigger this callback method when you are finished // with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap) sails.services.passport.loadStrategies(); // CRON JOBS FOR INFLUENCERS, HASHTAGS, MENTIONS // Runs every 15 minutes const TIMEZONE = 'America/Los_Angeles'; var CronJob = require('cron').CronJob; var cronJobs = Object.keys(sails.config.cron); cronJobs.forEach(function(key) { var value = sails.config.cron[key]; new CronJob(key, value, null, true, TIMEZONE); }) sails.config.twitterstream(); // new CronJob('00 * * * * *', function() { // console.log(new Date(), 'You will see this message every minute.'); // }, null, true, TIMEZONE); cb(); };
Java
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; /// <summary> /// Represents the response to a folder search operation. /// </summary> internal sealed class FindFolderResponse : ServiceResponse { private FindFoldersResults results = new FindFoldersResults(); private PropertySet propertySet; /// <summary> /// Reads response elements from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void ReadElementsFromXml(EwsServiceXmlReader reader) { reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.RootFolder); this.results.TotalCount = reader.ReadAttributeValue<int>(XmlAttributeNames.TotalItemsInView); this.results.MoreAvailable = !reader.ReadAttributeValue<bool>(XmlAttributeNames.IncludesLastItemInRange); // Ignore IndexedPagingOffset attribute if MoreAvailable is false. this.results.NextPageOffset = results.MoreAvailable ? reader.ReadNullableAttributeValue<int>(XmlAttributeNames.IndexedPagingOffset) : null; reader.ReadStartElement(XmlNamespace.Types, XmlElementNames.Folders); if (!reader.IsEmptyElement) { do { reader.Read(); if (reader.NodeType == XmlNodeType.Element) { Folder folder = EwsUtilities.CreateEwsObjectFromXmlElementName<Folder>(reader.Service, reader.LocalName); if (folder == null) { reader.SkipCurrentElement(); } else { folder.LoadFromXml( reader, true, /* clearPropertyBag */ this.propertySet, true /* summaryPropertiesOnly */); this.results.Folders.Add(folder); } } } while (!reader.IsEndElement(XmlNamespace.Types, XmlElementNames.Folders)); } reader.ReadEndElement(XmlNamespace.Messages, XmlElementNames.RootFolder); } /// <summary> /// Creates a folder instance. /// </summary> /// <param name="service">The service.</param> /// <param name="xmlElementName">Name of the XML element.</param> /// <returns>Folder</returns> private Folder CreateFolderInstance(ExchangeService service, string xmlElementName) { return EwsUtilities.CreateEwsObjectFromXmlElementName<Folder>(service, xmlElementName); } /// <summary> /// Initializes a new instance of the <see cref="FindFolderResponse"/> class. /// </summary> /// <param name="propertySet">The property set from, the request.</param> internal FindFolderResponse(PropertySet propertySet) : base() { this.propertySet = propertySet; EwsUtilities.Assert( this.propertySet != null, "FindFolderResponse.ctor", "PropertySet should not be null"); } /// <summary> /// Gets the results of the search operation. /// </summary> public FindFoldersResults Results { get { return this.results; } } } }
Java
#define MICROPY_HW_BOARD_NAME "CustomPCB" #define MICROPY_HW_MCU_NAME "STM32F439" #define MICROPY_HW_HAS_FLASH (1) #define MICROPY_HW_ENABLE_RNG (1) #define MICROPY_HW_ENABLE_RTC (1) #define MICROPY_HW_ENABLE_DAC (1) #define MICROPY_HW_ENABLE_USB (1) #define MICROPY_HW_ENABLE_SDCARD (1) // works with no SD card too // SD card detect switch #if MICROPY_HW_ENABLE_SDCARD #define MICROPY_HW_SDCARD_DETECT_PIN (pin_A8) #define MICROPY_HW_SDCARD_DETECT_PULL (GPIO_PULLUP) #define MICROPY_HW_SDCARD_DETECT_PRESENT (1) #endif // HSE is 8MHz #define MICROPY_HW_CLK_PLLM (8) //divide external clock by this to get 1MHz #define MICROPY_HW_CLK_PLLN (384) //this number is the PLL clock in MHz #define MICROPY_HW_CLK_PLLP (RCC_PLLP_DIV2) //divide PLL clock by this to get core clock #define MICROPY_HW_CLK_PLLQ (8) //divide core clock by this to get 48MHz // USB config #define MICROPY_HW_USB_FS (1) // UART config #define MICROPY_HW_UART1_TX (pin_A9) #define MICROPY_HW_UART1_RX (pin_A10) #define MICROPY_HW_UART2_TX (pin_D5) #define MICROPY_HW_UART2_RX (pin_D6) #define MICROPY_HW_UART2_RTS (pin_D1) #define MICROPY_HW_UART2_CTS (pin_D0) #define MICROPY_HW_UART3_TX (pin_D8) #define MICROPY_HW_UART3_RX (pin_D9) #define MICROPY_HW_UART3_RTS (pin_D12) #define MICROPY_HW_UART3_CTS (pin_D11) #define MICROPY_HW_UART4_TX (pin_A0) #define MICROPY_HW_UART4_RX (pin_A1) #define MICROPY_HW_UART6_TX (pin_C6) #define MICROPY_HW_UART6_RX (pin_C7) // I2C buses #define MICROPY_HW_I2C1_SCL (pin_A8) #define MICROPY_HW_I2C1_SDA (pin_C9) // SPI buses #define MICROPY_HW_SPI1_NSS (pin_A4) #define MICROPY_HW_SPI1_SCK (pin_A5) #define MICROPY_HW_SPI1_MISO (pin_A6) #define MICROPY_HW_SPI1_MOSI (pin_A7) #if MICROPY_HW_USB_HS_IN_FS // The HS USB uses B14 & B15 for D- and D+ #else #define MICROPY_HW_SPI2_NSS (pin_B12) #define MICROPY_HW_SPI2_SCK (pin_B13) #define MICROPY_HW_SPI2_MISO (pin_B14) #define MICROPY_HW_SPI2_MOSI (pin_B15) #endif #define MICROPY_HW_SPI3_NSS (pin_E11) #define MICROPY_HW_SPI3_SCK (pin_E12) #define MICROPY_HW_SPI3_MISO (pin_E13) #define MICROPY_HW_SPI3_MOSI (pin_E14) //#define MICROPY_HW_SPI4_NSS (pin_E11) //#define MICROPY_HW_SPI4_SCK (pin_E12) //#define MICROPY_HW_SPI4_MISO (pin_E13) //#define MICROPY_HW_SPI4_MOSI (pin_E14) //#define MICROPY_HW_SPI5_NSS (pin_F6) //#define MICROPY_HW_SPI5_SCK (pin_F7) //#define MICROPY_HW_SPI5_MISO (pin_F8) //#define MICROPY_HW_SPI5_MOSI (pin_F9) //#define MICROPY_HW_SPI6_NSS (pin_G8) //#define MICROPY_HW_SPI6_SCK (pin_G13) //#define MICROPY_HW_SPI6_MISO (pin_G12) //#define MICROPY_HW_SPI6_MOSI (pin_G14) // CAN buses #define MICROPY_HW_CAN1_TX (pin_B9) #define MICROPY_HW_CAN1_RX (pin_B8) #define MICROPY_HW_CAN2_TX (pin_B13) #define MICROPY_HW_CAN2_RX (pin_B12) // USRSW is pulled low. Pressing the button makes the input go high. #define MICROPY_HW_USRSW_PIN (pin_A0) #define MICROPY_HW_USRSW_PULL (GPIO_NOPULL) #define MICROPY_HW_USRSW_EXTI_MODE (GPIO_MODE_IT_RISING) #define MICROPY_HW_USRSW_PRESSED (1)
Java
const latestIncome = require('./latestIncome') const latestSpending = require('./latestSpending') function aggFinances(search) { return { latestIncome: () => latestIncome(search), latestSpending: () => latestSpending(search), } } module.exports = aggFinances
Java
#ifndef LEON_RTEMS_CONFIG_H_ #define LEON_RTEMS_CONFIG_H_ #ifndef _RTEMS_CONFIG_H_ #define _RTEMS_CONFIG_H_ #include <OsDrvCpr.h> #if defined(__RTEMS__) #if !defined (__CONFIG__) #define __CONFIG__ /* ask the system to generate a configuration table */ #define CONFIGURE_INIT #ifndef RTEMS_POSIX_API #define RTEMS_POSIX_API #endif #define CONFIGURE_MICROSECONDS_PER_TICK 1000 /* 1 millisecond */ #define CONFIGURE_TICKS_PER_TIMESLICE 50 /* 50 milliseconds */ #define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER #define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER #define CONFIGURE_POSIX_INIT_THREAD_TABLE #define CONFIGURE_MINIMUM_TASK_STACK_SIZE (8192) #define CONFIGURE_MAXIMUM_TASKS 20 #define CONFIGURE_MAXIMUM_POSIX_THREADS 5 #define CONFIGURE_MAXIMUM_POSIX_MUTEXES 8 #define CONFIGURE_MAXIMUM_POSIX_KEYS 8 #define CONFIGURE_MAXIMUM_POSIX_SEMAPHORES 8 #define CONFIGURE_MAXIMUM_POSIX_MESSAGE_QUEUES 8 #define CONFIGURE_MAXIMUM_POSIX_TIMERS 4 #define CONFIGURE_MAXIMUM_TIMERS 4 void POSIX_Init( void *args ); static void Fatal_extension( Internal_errors_Source the_source, bool is_internal, uint32_t the_error ); #define CONFIGURE_MAXIMUM_USER_EXTENSIONS 1 #define CONFIGURE_INITIAL_EXTENSIONS { .fatal = Fatal_extension } #include <SDCardIORTEMSConfig.h> #include <rtems/confdefs.h> #endif // __CONFIG__ #endif // __RTEMS__ // Set the system clocks BSP_SET_CLOCK( DEFAULT_REFCLOCK, 200000, 1, 1, DEFAULT_RTEMS_CSS_LOS_CLOCKS, DEFAULT_RTEMS_MSS_LRT_CLOCKS, 0, 0, 0 ); // Set L2 cache behaviour BSP_SET_L2C_CONFIG( 1, DEFAULT_RTEMS_L2C_REPLACEMENT_POLICY, DEFAULT_RTEMS_L2C_WAYS, DEFAULT_RTEMS_L2C_MODE, 0, 0 ); #endif // _RTEMS_CONFIG_H_ #endif // LEON_RTEMS_CONFIG_H_
Java
require 'spec_helper' require 'generator_spec/test_case' require 'generators/refinery/engine/engine_generator' module Refinery describe EngineGenerator do include GeneratorSpec::TestCase destination File.expand_path("../../../../../../tmp", __FILE__) before do prepare_destination run_generator %w{ rspec_product_test title:string description:text image:image brochure:resource } end context "when generating a resource inside existing extensions dir" do before do run_generator %w{ rspec_item_test title:string --extension rspec_product_tests --namespace rspec_product_tests --skip } end it "creates a new migration with the new resource" do destination_root.should have_structure { directory "vendor" do directory "extensions" do directory "rspec_product_tests" do directory "db" do directory "migrate" do file "2_create_rspec_product_tests_rspec_item_tests.rb" end end end end end } end it "appends routes to the routes file" do File.open("#{destination_root}/vendor/extensions/rspec_product_tests/config/routes.rb") do |file| file.grep(%r{rspec_item_tests}).count.should eq(2) end end end end end
Java
--- title: The Title of the Book date: 30/12/2018 --- According to Rev. 1:1 the title of the book is "The Revelation of Jesus Christ". It is a self-revelation of Him to His people and an expression of His care for them. The book is the unveiling of Jesus Christ and it is both from Jesus and about Him. He is the focus of its content and its central figure. It begins where the four Gospels end, with Jesus's resurrection and ascension into heaven and the continuation of his work of salvation. Together with the Epistle to the Hebrews, Revelation emphasizes Jesus' heavenly ministry. Without Revelation or Hebrews, our knowledge of Christ's high-priestly ministry in heaven in behalf of His people would be very limited.
Java
package inputs import ( "fmt" ) // DiskIO is based on telegraf DiskIO. type DiskIO struct { baseInput } // PluginName is based on telegraf plugin name. func (d *DiskIO) PluginName() string { return "diskio" } // UnmarshalTOML decodes the parsed data to the object func (d *DiskIO) UnmarshalTOML(data interface{}) error { return nil } // TOML encodes to toml string. func (d *DiskIO) TOML() string { return fmt.Sprintf(`[[inputs.%s]] ## By default, telegraf will gather stats for all devices including ## disk partitions. ## Setting devices will restrict the stats to the specified devices. # devices = ["sda", "sdb", "vd*"] ## Uncomment the following line if you need disk serial numbers. # skip_serial_number = false # ## On systems which support it, device metadata can be added in the form of ## tags. ## Currently only Linux is supported via udev properties. You can view ## available properties for a device by running: ## 'udevadm info -q property -n /dev/sda' ## Note: Most, but not all, udev properties can be accessed this way. Properties ## that are currently inaccessible include DEVTYPE, DEVNAME, and DEVPATH. # device_tags = ["ID_FS_TYPE", "ID_FS_USAGE"] # ## Using the same metadata source as device_tags, you can also customize the ## name of the device via templates. ## The 'name_templates' parameter is a list of templates to try and apply to ## the device. The template may contain variables in the form of '$PROPERTY' or ## '${PROPERTY}'. The first template which does not contain any variables not ## present for the device is used as the device name tag. ## The typical use case is for LVM volumes, to get the VG/LV name instead of ## the near-meaningless DM-0 name. # name_templates = ["$ID_FS_LABEL","$DM_VG_NAME/$DM_LV_NAME"] `, d.PluginName()) }
Java
// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.19.6\Source\Uno\UX\Attributes\$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Attribute.h> namespace g{namespace Uno{namespace UX{struct UXSourceFileNameAttribute;}}} namespace g{ namespace Uno{ namespace UX{ // public sealed class UXSourceFileNameAttribute :234 // { uType* UXSourceFileNameAttribute_typeof(); void UXSourceFileNameAttribute__ctor_1_fn(UXSourceFileNameAttribute* __this); void UXSourceFileNameAttribute__New1_fn(UXSourceFileNameAttribute** __retval); struct UXSourceFileNameAttribute : ::g::Uno::Attribute { void ctor_1(); static UXSourceFileNameAttribute* New1(); }; // } }}} // ::g::Uno::UX
Java
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Task extends Model { // }
Java
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_("News '{title}' has been posted").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage'))
Java
package swarm import ( "testing" "time" ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr" context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context" inet "github.com/ipfs/go-ipfs/p2p/net" ) func TestNotifications(t *testing.T) { ctx := context.Background() swarms := makeSwarms(ctx, t, 5) defer func() { for _, s := range swarms { s.Close() } }() timeout := 5 * time.Second // signup notifs notifiees := make([]*netNotifiee, len(swarms)) for i, swarm := range swarms { n := newNetNotifiee() swarm.Notify(n) notifiees[i] = n } connectSwarms(t, ctx, swarms) <-time.After(time.Millisecond) // should've gotten 5 by now. // test everyone got the correct connection opened calls for i, s := range swarms { n := notifiees[i] for _, s2 := range swarms { if s == s2 { continue } var actual []inet.Conn for len(s.ConnectionsToPeer(s2.LocalPeer())) != len(actual) { select { case c := <-n.connected: actual = append(actual, c) case <-time.After(timeout): t.Fatal("timeout") } } expect := s.ConnectionsToPeer(s2.LocalPeer()) for _, c1 := range actual { found := false for _, c2 := range expect { if c1 == c2 { found = true break } } if !found { t.Error("connection not found") } } } } complement := func(c inet.Conn) (*Swarm, *netNotifiee, *Conn) { for i, s := range swarms { for _, c2 := range s.Connections() { if c.LocalMultiaddr().Equal(c2.RemoteMultiaddr()) && c2.LocalMultiaddr().Equal(c.RemoteMultiaddr()) { return s, notifiees[i], c2 } } } t.Fatal("complementary conn not found", c) return nil, nil, nil } testOCStream := func(n *netNotifiee, s inet.Stream) { var s2 inet.Stream select { case s2 = <-n.openedStream: t.Log("got notif for opened stream") case <-time.After(timeout): t.Fatal("timeout") } if s != s2 { t.Fatal("got incorrect stream", s.Conn(), s2.Conn()) } select { case s2 = <-n.closedStream: t.Log("got notif for closed stream") case <-time.After(timeout): t.Fatal("timeout") } if s != s2 { t.Fatal("got incorrect stream", s.Conn(), s2.Conn()) } } streams := make(chan inet.Stream) for _, s := range swarms { s.SetStreamHandler(func(s inet.Stream) { streams <- s s.Close() }) } // open a streams in each conn for i, s := range swarms { for _, c := range s.Connections() { _, n2, _ := complement(c) st1, err := c.NewStream() if err != nil { t.Error(err) } else { st1.Write([]byte("hello")) st1.Close() testOCStream(notifiees[i], st1) st2 := <-streams testOCStream(n2, st2) } } } // close conns for i, s := range swarms { n := notifiees[i] for _, c := range s.Connections() { _, n2, c2 := complement(c) c.Close() c2.Close() var c3, c4 inet.Conn select { case c3 = <-n.disconnected: case <-time.After(timeout): t.Fatal("timeout") } if c != c3 { t.Fatal("got incorrect conn", c, c3) } select { case c4 = <-n2.disconnected: case <-time.After(timeout): t.Fatal("timeout") } if c2 != c4 { t.Fatal("got incorrect conn", c, c2) } } } } type netNotifiee struct { listen chan ma.Multiaddr listenClose chan ma.Multiaddr connected chan inet.Conn disconnected chan inet.Conn openedStream chan inet.Stream closedStream chan inet.Stream } func newNetNotifiee() *netNotifiee { return &netNotifiee{ listen: make(chan ma.Multiaddr), listenClose: make(chan ma.Multiaddr), connected: make(chan inet.Conn), disconnected: make(chan inet.Conn), openedStream: make(chan inet.Stream), closedStream: make(chan inet.Stream), } } func (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr) { nn.listen <- a } func (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) { nn.listenClose <- a } func (nn *netNotifiee) Connected(n inet.Network, v inet.Conn) { nn.connected <- v } func (nn *netNotifiee) Disconnected(n inet.Network, v inet.Conn) { nn.disconnected <- v } func (nn *netNotifiee) OpenedStream(n inet.Network, v inet.Stream) { nn.openedStream <- v } func (nn *netNotifiee) ClosedStream(n inet.Network, v inet.Stream) { nn.closedStream <- v }
Java
## Infiniti Samples This repository contains examples for [Intelledox Infiniti](http://intelledox.com). Directory | Description --------- | ----------- [Extension Examples](ExtensionExamples) | A collection of sample code that helps you learn and explore Infiniti extensions. [API Examples](ApiExamples) | A collection of sample API client code that helps demonstrate calling Infiniti REST services. ## Resources + **Website:** [intelledox.com](http://intelledox.com) + **Documentation:** [Infiniti Knowledge Base](http://ixsupport.intelledox.com/kb) + **Blog:** [Intelledox Blog](http://intelledox.com/ix-connect/blog)
Java
// -------------------------------------------------------------------------------------------- // <copyright file="TransformVisitor.UnionAll.cs" company="Effort Team"> // Copyright (C) 2011-2014 Effort 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. // </copyright> // -------------------------------------------------------------------------------------------- namespace Effort.Internal.DbCommandTreeTransformation { using System; using System.Collections.Generic; #if !EFOLD using System.Data.Entity.Core.Common.CommandTrees; #else using System.Data.Common.CommandTrees; #endif using System.Linq; using System.Linq.Expressions; using System.Reflection; using Effort.Internal.Common; internal partial class TransformVisitor { public override Expression Visit(DbUnionAllExpression expression) { Type resultType = edmTypeConverter.Convert(expression.ResultType); Expression left = this.Visit(expression.Left); Expression right = this.Visit(expression.Right); var resultElemType = TypeHelper.GetElementType(resultType); this.UnifyCollections(resultElemType, ref left, ref right); return queryMethodExpressionBuilder.Concat(left, right); } } }
Java
<?php namespace Kunstmaan\NodeSearchBundle\Helper\FormWidgets; use Doctrine\ORM\EntityManager; use Kunstmaan\AdminBundle\Helper\FormWidgets\FormWidget; use Kunstmaan\NodeBundle\Entity\Node; use Kunstmaan\NodeSearchBundle\Entity\NodeSearch; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\HttpFoundation\Request; class SearchFormWidget extends FormWidget { /** @var Node */ private $node; /** @var NodeSearch */ private $nodeSearch; /** * @param Node $node * @param EntityManager $em */ public function __construct(Node $node, EntityManager $em) { $this->node = $node; $this->nodeSearch = $em->getRepository('KunstmaanNodeSearchBundle:NodeSearch')->findOneByNode($this->node); } /** * @param FormBuilderInterface $builder The form builder */ public function buildForm(FormBuilderInterface $builder) { parent::buildForm($builder); $data = $builder->getData(); $data['node_search'] = $this->nodeSearch; $builder->setData($data); } /** * @param Request $request */ public function bindRequest(Request $request) { $form = $request->request->get('form'); $this->data['node_search'] = $form['node_search']['boost']; } /** * @param EntityManager $em */ public function persist(EntityManager $em) { $nodeSearch = $em->getRepository('KunstmaanNodeSearchBundle:NodeSearch')->findOneByNode($this->node); if ($this->data['node_search'] !== null) { if ($nodeSearch === null) { $nodeSearch = new NodeSearch(); $nodeSearch->setNode($this->node); } $nodeSearch->setBoost($this->data['node_search']); $em->persist($nodeSearch); } } }
Java
using System.Reflection; [assembly: AssemblyTitle("Rainbow")] [assembly: AssemblyDescription("Rainbow serialization library")]
Java
main: main.cc g++ -O2 -Wall -Wextra -o main main.cc run: main ./main debug: main valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./main clean: rm -fv main
Java
define(function(require, exports, module) { var Notify = require('common/bootstrap-notify'); var FileChooser = require('../widget/file/file-chooser3'); exports.run = function() { var $form = $("#course-material-form"); var materialChooser = new FileChooser({ element: '#material-file-chooser' }); materialChooser.on('change', function(item) { $form.find('[name="fileId"]').val(item.id); }); $form.on('click', '.delete-btn', function(){ var $btn = $(this); if (!confirm(Translator.trans('真的要删除该资料吗?'))) { return ; } $.post($btn.data('url'), function(){ $btn.parents('.list-group-item').remove(); Notify.success(Translator.trans('资料已删除')); }); }); $form.on('submit', function(){ if ($form.find('[name="fileId"]').val().length == 0) { Notify.danger(Translator.trans('请先上传文件或添加资料网络链接!')); return false; } $.post($form.attr('action'), $form.serialize(), function(html){ Notify.success(Translator.trans('资料添加成功!')); $("#material-list").append(html).show(); $form.find('.text-warning').hide(); $form.find('[name="fileId"]').val(''); $form.find('[name="link"]').val(''); $form.find('[name="description"]').val(''); materialChooser.open(); }).fail(function(){ Notify.success(Translator.trans('资料添加失败,请重试!')); }); return false; }); $('.modal').on('hidden.bs.modal', function(){ window.location.reload(); }); }; });
Java
#!/bin/sh set -e set -u set -o pipefail function on_error { echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" } trap 'on_error $LINENO' ERR if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" elif [ -L "${binary}" ]; then echo "Destination binary is symlinked..." dirname="$(dirname "${binary}")" binary="${dirname}/$(readlink "${binary}")" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Copies the bcsymbolmap files of a vendored framework install_bcsymbolmap() { local bcsymbolmap_path="$1" local destination="${BUILT_PRODUCTS_DIR}" echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identity echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/ForecastIO-iOS/ForecastIO.framework" install_framework "${BUILT_PRODUCTS_DIR}/OHHTTPStubs-iOS/OHHTTPStubs.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/ForecastIO-iOS/ForecastIO.framework" install_framework "${BUILT_PRODUCTS_DIR}/OHHTTPStubs-iOS/OHHTTPStubs.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
Java
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2013 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #ifndef _RTShaderSRSSegmentedLights_ #define _RTShaderSRSSegmentedLights_ #include "OgreShaderPrerequisites.h" #include "OgreShaderParameter.h" #include "OgreShaderSubRenderState.h" #include "OgreVector4.h" #include "OgreLight.h" #include "OgreCommon.h" /** Segmented lighting sub render state * The following is sub render state handles lighting in the scene. * This sub render state is heavily based on PerPixelLighting */ class RTShaderSRSSegmentedLights : public Ogre::RTShader::SubRenderState { // Interface. public: /** Class default constructor */ RTShaderSRSSegmentedLights(); /** @see SubRenderState::getType. */ virtual const Ogre::String& getType() const; /** @see SubRenderState::getType. */ virtual int getExecutionOrder() const; /** @see SubRenderState::updateGpuProgramsParams. */ virtual void updateGpuProgramsParams(Ogre::Renderable* rend, Ogre::Pass* pass, const Ogre::AutoParamDataSource* source, const Ogre::LightList* pLightList); /** @see SubRenderState::copyFrom. */ virtual void copyFrom(const Ogre::RTShader::SubRenderState& rhs); /** @see SubRenderState::preAddToRenderState. */ virtual bool preAddToRenderState(const Ogre::RTShader::RenderState* renderState, Ogre::Pass* srcPass, Ogre::Pass* dstPass); static Ogre::String Type; // Protected types: protected: // Per light parameters. struct LightParams { Ogre::Light::LightTypes mType; // Light type. Ogre::RTShader::UniformParameterPtr mPosition; // Light position. Ogre::RTShader::UniformParameterPtr mDirection; // Light direction. Ogre::RTShader::UniformParameterPtr mSpotParams; // Spot light parameters. Ogre::RTShader::UniformParameterPtr mDiffuseColour; // Diffuse colour. Ogre::RTShader::UniformParameterPtr mSpecularColour; // Specular colour. }; typedef Ogre::vector<LightParams>::type LightParamsList; typedef LightParamsList::iterator LightParamsIterator; typedef LightParamsList::const_iterator LightParamsConstIterator; // Protected methods protected: /** Set the track per vertex colour type. Ambient, Diffuse, Specular and Emissive lighting components source can be the vertex colour component. To establish such a link one should provide the matching flags to this sub render state. */ void setTrackVertexColourType(Ogre::TrackVertexColourType type) { mTrackVertexColourType = type; } /** Return the current track per vertex type. */ Ogre::TrackVertexColourType getTrackVertexColourType() const { return mTrackVertexColourType; } /** Set the light count per light type that this sub render state will generate. @see ShaderGenerator::setLightCount. */ void setLightCount(const int lightCount[3]); /** Get the light count per light type that this sub render state will generate. @see ShaderGenerator::getLightCount. */ void getLightCount(int lightCount[3]) const; /** Set the specular component state. If set to true this sub render state will compute a specular lighting component in addition to the diffuse component. @param enable Pass true to enable specular component computation. */ void setSpecularEnable(bool enable) { mSpecularEnable = enable; } /** Get the specular component state. */ bool getSpecularEnable() const { return mSpecularEnable; } /** @see SubRenderState::resolveParameters. */ virtual bool resolveParameters(Ogre::RTShader::ProgramSet* programSet); /** Resolve global lighting parameters */ bool resolveGlobalParameters(Ogre::RTShader::ProgramSet* programSet); /** Resolve per light parameters */ bool resolvePerLightParameters(Ogre::RTShader::ProgramSet* programSet); /** @see SubRenderState::resolveDependencies. */ virtual bool resolveDependencies(Ogre::RTShader::ProgramSet* programSet); /** @see SubRenderState::addFunctionInvocations. */ virtual bool addFunctionInvocations(Ogre::RTShader::ProgramSet* programSet); /** Internal method that adds related vertex shader functions invocations. */ bool addVSInvocation(Ogre::RTShader::Function* vsMain, const int groupOrder, int& internalCounter); /** Internal method that adds global illumination component functions invocations. */ bool addPSGlobalIlluminationInvocationBegin(Ogre::RTShader::Function* psMain, const int groupOrder, int& internalCounter); bool addPSGlobalIlluminationInvocationEnd(Ogre::RTShader::Function* psMain, const int groupOrder, int& internalCounter); /** Internal method that adds per light illumination component functions invocations. */ bool addPSIlluminationInvocation(LightParams* curLightParams, Ogre::RTShader::Function* psMain, const int groupOrder, int& internalCounter); /** Internal method that adds light illumination component calculated from the segmented texture. */ bool addPSSegmentedTextureLightInvocation(Ogre::RTShader::Function* psMain, const int groupOrder, int& internalCounter); /** Internal method that adds the final colour assignments. */ bool addPSFinalAssignmentInvocation(Ogre::RTShader::Function* psMain, const int groupOrder, int& internalCounter); // Attributes. protected: Ogre::TrackVertexColourType mTrackVertexColourType; // Track per vertex colour type. bool mSpecularEnable; // Specular component enabled/disabled. LightParamsList mLightParamsList; // Light list. Ogre::RTShader::UniformParameterPtr mWorldMatrix; // World view matrix parameter. Ogre::RTShader::UniformParameterPtr mWorldITMatrix; // World view matrix inverse transpose parameter. Ogre::RTShader::ParameterPtr mVSInPosition; // Vertex shader input position parameter. Ogre::RTShader::ParameterPtr mVSOutWorldPos; // Vertex shader output view position (position in camera space) parameter. Ogre::RTShader::ParameterPtr mPSInWorldPos; // Pixel shader input view position (position in camera space) parameter. Ogre::RTShader::ParameterPtr mVSInNormal; // Vertex shader input normal. Ogre::RTShader::ParameterPtr mVSOutNormal; // Vertex shader output normal. Ogre::RTShader::ParameterPtr mPSInNormal; // Pixel shader input normal. Ogre::RTShader::ParameterPtr mPSLocalNormal; Ogre::RTShader::ParameterPtr mPSTempDiffuseColour; // Pixel shader temporary diffuse calculation parameter. Ogre::RTShader::ParameterPtr mPSTempSpecularColour; // Pixel shader temporary specular calculation parameter. Ogre::RTShader::ParameterPtr mPSDiffuse; // Pixel shader input/local diffuse parameter. Ogre::RTShader::ParameterPtr mPSSpecular; // Pixel shader input/local specular parameter. Ogre::RTShader::ParameterPtr mPSOutDiffuse; // Pixel shader output diffuse parameter. Ogre::RTShader::ParameterPtr mPSOutSpecular; // Pixel shader output specular parameter. Ogre::RTShader::UniformParameterPtr mDerivedSceneColour; // Derived scene colour parameter. Ogre::RTShader::UniformParameterPtr mLightAmbientColour; // Ambient light colour parameter. Ogre::RTShader::UniformParameterPtr mDerivedAmbientLightColour; // Derived ambient light colour parameter. Ogre::RTShader::UniformParameterPtr mSurfaceAmbientColour; // Surface ambient colour parameter. Ogre::RTShader::UniformParameterPtr mSurfaceDiffuseColour; // Surface diffuse colour parameter. Ogre::RTShader::UniformParameterPtr mSurfaceSpecularColour; // Surface specular colour parameter. Ogre::RTShader::UniformParameterPtr mSurfaceEmissiveColour; // Surface emissive colour parameter. Ogre::RTShader::UniformParameterPtr mSurfaceShininess; // Surface shininess parameter. //Segmented texture bool mUseSegmentedLightTexture; bool mIsDebugMode; unsigned short m_LightSamplerIndex; Ogre::RTShader::UniformParameterPtr mPSLightTextureIndexLimit; Ogre::RTShader::UniformParameterPtr mPSLightTextureLightBounds; Ogre::RTShader::UniformParameterPtr mPSSegmentedLightTexture; //Ogre::RTShader::UniformParameterPtr mPSLightAreaBounds; static Ogre::Light msBlankLight; // Shared blank light. }; /** A factory that enables creation of PerPixelLighting instances. @remarks Sub class of SubRenderStateFactory */ class RTShaderSRSSegmentedLightsFactory : public Ogre::RTShader::SubRenderStateFactory { public: /** @see SubRenderStateFactory::getType. */ virtual const Ogre::String& getType() const; /** @see SubRenderStateFactory::createInstance. */ virtual Ogre::RTShader::SubRenderState* createInstance(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop, Ogre::Pass* pass, Ogre::RTShader::SGScriptTranslator* translator); /** @see SubRenderStateFactory::writeInstance. */ virtual void writeInstance(Ogre::MaterialSerializer* ser, Ogre::RTShader::SubRenderState* subRenderState, Ogre::Pass* srcPass, Ogre::Pass* dstPass); protected: /** @see SubRenderStateFactory::createInstanceImpl. */ virtual Ogre::RTShader::SubRenderState* createInstanceImpl(); }; #endif
Java
module.exports={A:{A:{"2":"H D G E A B FB"},B:{"1":"p z J L N I","2":"C"},C:{"1":"0 2 3 5 6 8 9 P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y CB AB","2":"4 aB F K H D G E A B C p z J L N I O YB SB"},D:{"1":"0 2 3 5 6 8 9 z J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y CB AB MB cB GB b HB IB JB KB","2":"F K H D G E A B C p"},E:{"1":"1 B C RB TB","2":"F K H D G E A LB DB NB OB PB QB"},F:{"1":"2 J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y","2":"1 E B C UB VB WB XB BB ZB EB"},G:{"2":"7 G C DB bB dB eB fB gB hB iB jB kB lB mB"},H:{"2":"nB"},I:{"1":"b sB tB","2":"4 7 F oB pB qB rB"},J:{"1":"A","2":"D"},K:{"1":"M","2":"1 A B C BB EB"},L:{"1":"b"},M:{"1":"0"},N:{"2":"A B"},O:{"1":"uB"},P:{"1":"F K vB wB"},Q:{"1":"xB"},R:{"1":"yB"}},B:1,C:"Download attribute"};
Java
<?php /** * This makes our life easier when dealing with paths. Everything is relative * to the application root now. */ chdir(dirname(__DIR__)); // Decline static file requests back to the PHP built-in webserver if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) { return false; } // Setup autoloading include 'vendor/autoload.php'; if (!defined('APPLICATION_PATH')) { define('APPLICATION_PATH', realpath(__DIR__ . '/../')); } $appConfig = include APPLICATION_PATH . '/config/application.config.php'; if (file_exists(APPLICATION_PATH . '/config/development.config.php')) { $appConfig = Zend\Stdlib\ArrayUtils::merge($appConfig, include APPLICATION_PATH . '/config/development.config.php'); } // Run the application! Zend\Mvc\Application::init($appConfig)->run();
Java
// --------------------------------------------------------------------------------------------- #region // Copyright (c) 2014, SIL International. All Rights Reserved. // <copyright from='2008' to='2014' company='SIL International'> // Copyright (c) 2014, SIL International. All Rights Reserved. // // Distributable under the terms of the MIT License (http://sil.mit-license.org/) // </copyright> #endregion // // This class originated in FieldWorks (under the GNU Lesser General Public License), but we // have decided to make it avaialble in SIL.ScriptureUtils as part of Palaso so it will be more // readily available to other projects. // --------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace SIL.Scripture { /// <summary> /// Manipulate information for standard chatper/verse schemes /// </summary> public class VersificationTable { private readonly ScrVers scrVers; private List<int[]> bookList; private Dictionary<string, string> toStandard; private Dictionary<string, string> fromStandard; private static string baseDir; private static VersificationTable[] versifications = null; // Names of the versificaiton files. These are in "\My Paratext Projects" private static string[] versificationFiles = new string[] { "", "org.vrs", "lxx.vrs", "vul.vrs", "eng.vrs", "rsc.vrs", "rso.vrs", "oth.vrs", "oth2.vrs", "oth3.vrs", "oth4.vrs", "oth5.vrs", "oth6.vrs", "oth7.vrs", "oth8.vrs", "oth9.vrs", "oth10.vrs", "oth11.vrs", "oth12.vrs", "oth13.vrs", "oth14.vrs", "oth15.vrs", "oth16.vrs", "oth17.vrs", "oth18.vrs", "oth19.vrs", "oth20.vrs", "oth21.vrs", "oth22.vrs", "oth23.vrs", "oth24.vrs" }; /// ------------------------------------------------------------------------------------ /// <summary> /// This method should be called once before an application accesses anything that /// requires versification info. /// TODO: Paratext needs to call this with ScrTextCollection.SettingsDirectory. /// </summary> /// <param name="vrsFolder">Path to the folder containing the .vrs files</param> /// ------------------------------------------------------------------------------------ public static void Initialize(string vrsFolder) { baseDir = vrsFolder; } /// ------------------------------------------------------------------------------------ /// <summary> /// Get the versification table for this versification /// </summary> /// <param name="vers"></param> /// <returns></returns> /// ------------------------------------------------------------------------------------ public static VersificationTable Get(ScrVers vers) { Debug.Assert(vers != ScrVers.Unknown); if (versifications == null) versifications = new VersificationTable[versificationFiles.GetUpperBound(0)]; // Read versification table if not already read if (versifications[(int)vers] == null) { versifications[(int)vers] = new VersificationTable(vers); ReadVersificationFile(FileName(vers), versifications[(int)vers]); } return versifications[(int)vers]; } /// ------------------------------------------------------------------------------------ /// <summary> /// Read versification file and "add" its entries. /// At the moment we only do this once. Eventually we will call this twice. /// Once for the standard versification, once for custom entries in versification.vrs /// file for this project. /// </summary> /// <param name="fileName"></param> /// <param name="versification"></param> /// ------------------------------------------------------------------------------------ private static void ReadVersificationFile(string fileName, VersificationTable versification) { using (TextReader reader = new StreamReader(fileName)) { for (string line = reader.ReadLine(); line != null; line = reader.ReadLine()) { line = line.Trim(); if (line == "" || line[0] == '#') continue; if (line.Contains("=")) ParseMappingLine(fileName, versification, line); else ParseChapterVerseLine(fileName, versification, line); } } } // Parse lines mapping from this versification to standard versification // GEN 1:10 = GEN 2:11 // GEN 1:10-13 = GEN 2:11-14 private static void ParseChapterVerseLine(string fileName, VersificationTable versification, string line) { string[] parts = line.Split(' '); int bookNum = BCVRef.BookToNumber(parts[0]); if (bookNum == -1) return; // Deuterocanonical books not supported if (bookNum == 0) throw new Exception("Invalid [" + parts[0] + "] " + fileName); while (versification.bookList.Count < bookNum) versification.bookList.Add(new int[1] { 1 }); List<int> verses = new List<int>(); for (int i = 1; i <= parts.GetUpperBound(0); ++i) { string[] pieces = parts[i].Split(':'); int verseCount; if (pieces.GetUpperBound(0) != 1 || !int.TryParse(pieces[1], out verseCount) || verseCount <= 0) { throw new Exception("Invalid [" + line + "] " + fileName); } verses.Add(verseCount); } versification.bookList[bookNum - 1] = verses.ToArray(); } // Parse lines giving number of verses for each chapter like // GEN 1:10 2:23 ... private static void ParseMappingLine(string fileName, VersificationTable versification, string line) { try { string[] parts = line.Split('='); string[] leftPieces = parts[0].Trim().Split('-'); string[] rightPieces = parts[1].Trim().Split('-'); BCVRef left = new BCVRef(leftPieces[0]); int leftLimit = leftPieces.GetUpperBound(0) == 0 ? 0 : int.Parse(leftPieces[1]); BCVRef right = new BCVRef(rightPieces[0]); while (true) { versification.toStandard[left.ToString()] = right.ToString(); versification.fromStandard[right.ToString()] = left.ToString(); if (left.Verse >= leftLimit) break; left.Verse = left.Verse + 1; right.Verse = right.Verse + 1; } } catch { // ENHANCE: Make it so the TE version of Localizer can have its own resources for stuff // like this. throw new Exception("Invalid [" + line + "] " + fileName); } } /// <summary> /// Gets the name of this requested versification file. /// </summary> /// <param name="vers">Versification scheme</param> public static string GetFileNameForVersification(ScrVers vers) { return versificationFiles[(int)vers]; } // Get path of this versification file. // Fall back to eng.vrs if not present. private static string FileName(ScrVers vers) { if (baseDir == null) throw new InvalidOperationException("VersificationTable.Initialize must be called first"); string fileName = Path.Combine(baseDir, GetFileNameForVersification(vers)); if (!File.Exists(fileName)) fileName = Path.Combine(baseDir, GetFileNameForVersification(ScrVers.English)); return fileName; } // Create empty versification table private VersificationTable(ScrVers vers) { this.scrVers = vers; bookList = new List<int[]>(); toStandard = new Dictionary<string, string>(); fromStandard = new Dictionary<string, string>(); } public int LastBook() { return bookList.Count; } /// <summary> /// Last chapter number in this book. /// </summary> /// <param name="bookNum"></param> /// <returns></returns> public int LastChapter(int bookNum) { if (bookNum <= 0) return 0; if (bookNum - 1 >= bookList.Count) return 1; int[] chapters = bookList[bookNum - 1]; return chapters.GetUpperBound(0) + 1; } /// <summary> /// Last verse number in this book/chapter. /// </summary> /// <param name="bookNum"></param> /// <param name="chapterNum"></param> /// <returns></returns> public int LastVerse(int bookNum, int chapterNum) { if (bookNum <= 0) return 0; if (bookNum - 1 >= bookList.Count) return 1; int[] chapters = bookList[bookNum - 1]; // Chapter "0" is the intro material. Pretend that it has 1 verse. if (chapterNum - 1 > chapters.GetUpperBound(0) || chapterNum < 1) return 1; return chapters[chapterNum - 1]; } /// <summary> /// Change the passed VerseRef to be this versification. /// </summary> /// <param name="vref"></param> public void ChangeVersification(IVerseReference vref) { if (vref.Versification == scrVers) return; // Map from existing to standard versification string verse = vref.ToString(); string verse2; Get(vref.Versification).toStandard.TryGetValue(verse, out verse2); if (verse2 == null) verse2 = verse; // Map from standard versification to this versification string verse3; fromStandard.TryGetValue(verse2, out verse3); if (verse3 == null) verse3 = verse2; // If verse has changed, parse new value if (verse != verse3) vref.Parse(verse3); vref.Versification = scrVers; } } }
Java
{{< layout}} {{$pageTitle}}Upload your photo{{/pageTitle}} {{$header}} <h1>Take your photo</h1> {{/header}} {{$content}} <p>If you need to, <a href="/priority_service_170215/photoguide-short/">read the photo guide again</a>.</p> <p> We’ll store all photos for up to 30 days in line with our <a href="" rel="external">privacy policy</a>. </p> <!-- browse button <div id="photo-group" class="form-group"> <label for="photo" class="button photo-upload-label" role="button"> <span id="photo-label-text" class="">Upload your photo</span> </label> <input type="file" accept="image/jpeg" id="photo" class="photo-choose-file" name="photo" aria-controls="progress-container" aria-required="true" style="display:none"> </div> --> <a href="/prototype_170123/uploadphoto/processing-image" class="button">Upload your photo</a><br/><br/> <details> <summary><span class="summary">I have a printed photo</span></summary> <div class="panel panel-border-narrow"> <p> You can’t use a printed photo with this service. You’ll either need to <a href="">get a digital photo</a>, or <a href="">use a different service</a> to renew your passport. </p> </div> </details> <h3>How to take a good passport photo</h3> <div class="column-half"> <ol class="list-number"> <li>Get a friend to take your photo.</li> <li>Use a plain background.</li> <li>Don’t crop your photo — include your face, shoulders and upper body.</li> <li>Keep your hair away from your face and brushed down.</li> <li>Make sure there are no shadows on your face or behind you.</li> </ol> </div> <object type="image/jpg" data="/public/images/[email protected]"type="image/svg+xml" class="svg" tabindex="-1" style="width:100%;padding-left:0px;padding-top:30px"> <img src="/public/images/[email protected]" width="206" height= alt=""> </object> {{/content}} {{/ layout}}
Java
require 'sprockets/autoload' require 'sprockets/path_utils' module Sprockets class BabelProcessor VERSION = '1' def self.instance @instance ||= new end def self.call(input) instance.call(input) end def initialize(options = {}) @options = options.merge({ 'blacklist' => (options['blacklist'] || []) + ['useStrict'], 'sourceMap' => false }).freeze @cache_key = [ self.class.name, Autoload::Babel::Transpiler::VERSION, Autoload::Babel::Source::VERSION, VERSION, @options ].freeze end def call(input) data = input[:data] result = input[:cache].fetch(@cache_key + [data]) do Autoload::Babel::Transpiler.transform(data, @options.merge( 'sourceRoot' => input[:load_path], 'moduleRoot' => '', 'filename' => input[:filename], 'filenameRelative' => PathUtils.split_subpath(input[:load_path], input[:filename]) )) end result['code'] end end end
Java
'use strict'; const EventEmitter = require('events'); const uuid = require('node-uuid'); const ItemType = require('./ItemType'); const { Inventory, InventoryFullError } = require('./Inventory'); const Logger = require('./Logger'); const Player = require('./Player'); /** * @property {Area} area Area the item belongs to (warning: this is not the area is currently in but the * area it belongs to on a fresh load) * @property {object} properties Essentially a blob of whatever attrs the item designer wanted to add * @property {array|string} behaviors Single or list of behaviors this object uses * @property {string} description Long description seen when looking at it * @property {number} id vnum * @property {boolean} isEquipped Whether or not item is currently equipped * @property {Map} inventory Current items this item contains * @property {string} name Name shown in inventory and when equipped * @property {Room} room Room the item is currently in * @property {string} roomDesc Description shown when item is seen in a room * @property {string} script A custom script for this item * @property {ItemType|string} type * @property {string} uuid UUID differentiating all instances of this item */ class Item extends EventEmitter { constructor (area, item) { super(); const validate = ['keywords', 'name', 'id']; for (const prop of validate) { if (!(prop in item)) { throw new ReferenceError(`Item in area [${area.name}] missing required property [${prop}]`); } } this.area = area; this.properties = item.properties || {}; this.behaviors = item.behaviors || {}; this.defaultItems = item.items || []; this.description = item.description || 'Nothing special.'; this.entityReference = item.entityReference; // EntityFactory key this.id = item.id; this.maxItems = item.maxItems || Infinity; this.inventory = item.inventory ? new Inventory(item.inventory) : null; if (this.inventory) { this.inventory.setMax(this.maxItems); } this.isEquipped = item.isEquipped || false; this.keywords = item.keywords; this.level = item.level || 1; this.itemLevel = item.itemLevel || this.level; this.name = item.name; this.quality = item.quality || 'common'; this.room = item.room || null; this.roomDesc = item.roomDesc || ''; this.script = item.script || null; this.slot = item.slot || null; this.type = typeof item.type === 'string' ? ItemType[item.type] : (item.type || ItemType.OBJECT); this.uuid = item.uuid || uuid.v4(); } hasKeyword(keyword) { return this.keywords.indexOf(keyword) !== -1; } /** * @param {string} name * @return {boolean} */ hasBehavior(name) { if (!(this.behaviors instanceof Map)) { throw new Error("Item has not been hydrated. Cannot access behaviors."); } return this.behaviors.has(name); } /** * @param {string} name * @return {*} */ getBehavior(name) { if (!(this.behaviors instanceof Map)) { throw new Error("Item has not been hydrated. Cannot access behaviors."); } return this.behaviors.get(name); } addItem(item) { this._setupInventory(); this.inventory.addItem(item); item.belongsTo = this; } removeItem(item) { this.inventory.removeItem(item); // if we removed the last item unset the inventory // This ensures that when it's reloaded it won't try to set // its default inventory. Instead it will persist the fact // that all the items were removed from it if (!this.inventory.size) { this.inventory = null; } item.belongsTo = null; } isInventoryFull() { this._setupInventory(); return this.inventory.isFull; } _setupInventory() { if (!this.inventory) { this.inventory = new Inventory({ items: [], max: this.maxItems }); } } get qualityColors() { return ({ poor: ['bold', 'black'], common: ['bold', 'white'], uncommon: ['bold', 'green'], rare: ['bold', 'blue'], epic: ['bold', 'magenta'], legendary: ['bold', 'red'], artifact: ['yellow'], })[this.quality]; } /** * Friendly display colorized by quality */ get display() { return this.qualityColorize(`[${this.name}]`); } /** * Colorize the given string according to this item's quality * @param {string} string * @return string */ qualityColorize(string) { const colors = this.qualityColors; const open = '<' + colors.join('><') + '>'; const close = '</' + colors.reverse().join('></') + '>'; return open + string + close; } /** * For finding the player who has the item in their possession. * @return {Player|null} owner */ findOwner() { let found = null; let owner = this.belongsTo; while (owner) { if (owner instanceof Player) { found = owner; break; } owner = owner.belongsTo; } return found; } hydrate(state, serialized = {}) { if (typeof this.area === 'string') { this.area = state.AreaManager.getArea(this.area); } // if the item was saved with a custom inventory hydrate it if (this.inventory) { this.inventory.hydrate(state); } else { // otherwise load its default inv this.defaultItems.forEach(defaultItemId => { Logger.verbose(`\tDIST: Adding item [${defaultItemId}] to item [${this.name}]`); const newItem = state.ItemFactory.create(this.area, defaultItemId); newItem.hydrate(state); state.ItemManager.add(newItem); this.addItem(newItem); }); } // perform deep copy if behaviors is set to prevent sharing of the object between // item instances const behaviors = JSON.parse(JSON.stringify(serialized.behaviors || this.behaviors)); this.behaviors = new Map(Object.entries(behaviors)); for (let [behaviorName, config] of this.behaviors) { let behavior = state.ItemBehaviorManager.get(behaviorName); if (!behavior) { return; } // behavior may be a boolean in which case it will be `behaviorName: true` config = config === true ? {} : config; behavior.attach(this, config); } } serialize() { let behaviors = {}; for (const [key, val] of this.behaviors) { behaviors[key] = val; } return { entityReference: this.entityReference, inventory: this.inventory && this.inventory.serialize(), // behaviors are serialized in case their config was modified during gameplay // and that state needs to persist (charges of a scroll remaining, etc) behaviors, }; } } module.exports = Item;
Java
using System; using System.Collections.Generic; using Foundation.ObjectHydrator.Interfaces; namespace Foundation.ObjectHydrator.Generators { public class UnitedKingdomCityGenerator : IGenerator<string> { private readonly Random _random; private IList<string> _citynames = new List<string>(); public UnitedKingdomCityGenerator() { _random = RandomSingleton.Instance.Random; LoadCityNames(); } private void LoadCityNames() { _citynames = new List<string>() { "Aberaeron", "Aberdare", "Aberdeen", "Aberfeldy", "Abergavenny", "Abergele", "Abertillery", "Aberystwyth", "Abingdon", "Accrington", "Adlington", "Airdrie", "Alcester", "Aldeburgh", "Aldershot", "Aldridge", "Alford", "Alfreton", "Alloa", "Alnwick", "Alsager", "Alston", "Amesbury", "Amlwch", "Ammanford", "Ampthill", "Andover", "Annan", "Antrim", "Appleby in Westmorland", "Arbroath", "Armagh", "Arundel", "Ashbourne", "Ashburton", "Ashby de la Zouch", "Ashford", "Ashington", "Ashton in Makerfield", "Atherstone", "Auchtermuchty", "Axminster", "Aylesbury", "Aylsham", "Ayr", "Bacup", "Bakewell", "Bala", "Ballater", "Ballycastle", "Ballyclare", "Ballymena", "Ballymoney", "Ballynahinch", "Banbridge", "Banbury", "Banchory", "Banff", "Bangor", "Barmouth", "Barnard Castle", "Barnet", "Barnoldswick", "Barnsley", "Barnstaple", "Barrhead", "Barrow in Furness", "Barry", "Barton upon Humber", "Basildon", "Basingstoke", "Bath", "Bathgate", "Batley", "Battle", "Bawtry", "Beaconsfield", "Bearsden", "Beaumaris", "Bebington", "Beccles", "Bedale", "Bedford", "Bedlington", "Bedworth", "Beeston", "Bellshill", "Belper", "Berkhamsted", "Berwick upon Tweed", "Betws y Coed", "Beverley", "Bewdley", "Bexhill on Sea", "Bicester", "Biddulph", "Bideford", "Biggar", "Biggleswade", "Billericay", "Bilston", "Bingham", "Birkenhead", "Birmingham", "Bishop Auckland", "Blackburn", "Blackheath", "Blackpool", "Blaenau Ffestiniog", "Blandford Forum", "Bletchley", "Bloxwich", "Blyth", "Bodmin", "Bognor Regis", "Bollington", "Bolsover", "Bolton", "Bootle", "Borehamwood", "Boston", "Bourne", "Bournemouth", "Brackley", "Bracknell", "Bradford", "Bradford on Avon", "Brading", "Bradley Stoke", "Bradninch", "Braintree", "Brechin", "Brecon", "Brentwood", "Bridge of Allan", "Bridgend", "Bridgnorth", "Bridgwater", "Bridlington", "Bridport", "Brigg", "Brighouse", "Brightlingsea", "Brighton", "Bristol", "Brixham", "Broadstairs", "Bromsgrove", "Bromyard", "Brynmawr", "Buckfastleigh", "Buckie", "Buckingham", "Buckley", "Bude", "Budleigh Salterton", "Builth Wells", "Bungay", "Buntingford", "Burford", "Burgess Hill", "Burnham on Crouch", "Burnham on Sea", "Burnley", "Burntisland", "Burntwood", "Burry Port", "Burton Latimer", "Bury", "Bushmills", "Buxton", "Caernarfon", "Caerphilly", "Caistor", "Caldicot", "Callander", "Calne", "Camberley", "Camborne", "Cambridge", "Camelford", "Campbeltown", "Cannock", "Canterbury", "Cardiff", "Cardigan", "Carlisle", "Carluke", "Carmarthen", "Carnforth", "Carnoustie", "Carrickfergus", "Carterton", "Castle Douglas", "Castlederg", "Castleford", "Castlewellan", "Chard", "Charlbury", "Chatham", "Chatteris", "Chelmsford", "Cheltenham", "Chepstow", "Chesham", "Cheshunt", "Chester", "Chester le Street", "Chesterfield", "Chichester", "Chippenham", "Chipping Campden", "Chipping Norton", "Chipping Sodbury", "Chorley", "Christchurch", "Church Stretton", "Cinderford", "Cirencester", "Clacton on Sea", "Cleckheaton", "Cleethorpes", "Clevedon", "Clitheroe", "Clogher", "Clydebank", "Coalisland", "Coalville", "Coatbridge", "Cockermouth", "Coggeshall", "Colchester", "Coldstream", "Coleraine", "Coleshill", "Colne", "Colwyn Bay", "Comber", "Congleton", "Conwy", "Cookstown", "Corbridge", "Corby", "Coventry", "Cowbridge", "Cowdenbeath", "Cowes", "Craigavon", "Cramlington", "Crawley", "Crayford", "Crediton", "Crewe", "Crewkerne", "Criccieth", "Crickhowell", "Crieff", "Cromarty", "Cromer", "Crowborough", "Crowthorne", "Crumlin", "Cuckfield", "Cullen", "Cullompton", "Cumbernauld", "Cupar", "Cwmbran", "Dalbeattie", "Dalkeith", "Darlington", "Dartford", "Dartmouth", "Darwen", "Daventry", "Dawlish", "Deal", "Denbigh", "Denton", "Derby", "Dereham", "Devizes", "Dewsbury", "Didcot", "Dingwall", "Dinnington", "Diss", "Dolgellau", "Donaghadee", "Doncaster", "Dorchester", "Dorking", "Dornoch", "Dover", "Downham Market", "Downpatrick", "Driffield", "Dronfield", "Droylsden", "Dudley", "Dufftown", "Dukinfield", "Dumbarton", "Dumfries", "Dunbar", "Dunblane", "Dundee", "Dunfermline", "Dungannon", "Dunoon", "Duns", "Dunstable", "Durham", "Dursley", "Easingwold", "East Grinstead", "East Kilbride", "Eastbourne", "Eastleigh", "Eastwood", "Ebbw Vale", "Edenbridge", "Edinburgh", "Egham", "Elgin", "Ellesmere", "Ellesmere Port", "Ely", "Enniskillen", "Epping", "Epsom", "Erith", "Esher", "Evesham", "Exeter", "Exmouth", "Eye", "Eyemouth", "Failsworth", "Fairford", "Fakenham", "Falkirk", "Falkland", "Falmouth", "Fareham", "Faringdon", "Farnborough", "Farnham", "Farnworth", "Faversham", "Felixstowe", "Ferndown", "Filey", "Fintona", "Fishguard", "Fivemiletown", "Fleet", "Fleetwood", "Flint", "Flitwick", "Folkestone", "Fordingbridge", "Forfar", "Forres", "Fort William", "Fowey", "Framlingham", "Fraserburgh", "Frodsham", "Frome", "Gainsborough", "Galashiels", "Gateshead", "Gillingham", "Glasgow", "Glastonbury", "Glossop", "Gloucester", "Godalming", "Godmanchester", "Goole", "Gorseinon", "Gosport", "Gourock", "Grange over Sands", "Grangemouth", "Grantham", "Grantown on Spey", "Gravesend", "Grays", "Great Yarmouth", "Greenock", "Grimsby", "Guildford", "Haddington", "Hadleigh", "Hailsham", "Halesowen", "Halesworth", "Halifax", "Halstead", "Haltwhistle", "Hamilton", "Harlow", "Harpenden", "Harrogate", "Hartlepool", "Harwich", "Haslemere", "Hastings", "Hatfield", "Havant", "Haverfordwest", "Haverhill", "Hawarden", "Hawick", "Hay on Wye", "Hayle", "Haywards Heath", "Heanor", "Heathfield", "Hebden Bridge", "Helensburgh", "Helston", "Hemel Hempstead", "Henley on Thames", "Hereford", "Herne Bay", "Hertford", "Hessle", "Heswall", "Hexham", "High Wycombe", "Higham Ferrers", "Highworth", "Hinckley", "Hitchin", "Hoddesdon", "Holmfirth", "Holsworthy", "Holyhead", "Holywell", "Honiton", "Horley", "Horncastle", "Hornsea", "Horsham", "Horwich", "Houghton le Spring", "Hove", "Howden", "Hoylake", "Hucknall", "Huddersfield", "Hungerford", "Hunstanton", "Huntingdon", "Huntly", "Hyde", "Hythe", "Ilford", "Ilfracombe", "Ilkeston", "Ilkley", "Ilminster", "Innerleithen", "Inveraray", "Inverkeithing", "Inverness", "Inverurie", "Ipswich", "Irthlingborough", "Irvine", "Ivybridge", "Jarrow", "Jedburgh", "Johnstone", "Keighley", "Keith", "Kelso", "Kempston", "Kendal", "Kenilworth", "Kesgrave", "Keswick", "Kettering", "Keynsham", "Kidderminster", "Kilbarchan", "Kilkeel", "Killyleagh", "Kilmarnock", "Kilwinning", "Kinghorn", "Kingsbridge", "Kington", "Kingussie", "Kinross", "Kintore", "Kirkby", "Kirkby Lonsdale", "Kirkcaldy", "Kirkcudbright", "Kirkham", "Kirkwall", "Kirriemuir", "Knaresborough", "Knighton", "Knutsford", "Ladybank", "Lampeter", "Lanark", "Lancaster", "Langholm", "Largs", "Larne", "Laugharne", "Launceston", "Laurencekirk", "Leamington Spa", "Leatherhead", "Ledbury", "Leeds", "Leek", "Leicester", "Leighton Buzzard", "Leiston", "Leominster", "Lerwick", "Letchworth", "Leven", "Lewes", "Leyland", "Lichfield", "Limavady", "Lincoln", "Linlithgow", "Lisburn", "Liskeard", "Lisnaskea", "Littlehampton", "Liverpool", "Llandeilo", "Llandovery", "Llandrindod Wells", "Llandudno", "Llanelli", "Llanfyllin", "Llangollen", "Llanidloes", "Llanrwst", "Llantrisant", "Llantwit Major", "Llanwrtyd Wells", "Loanhead", "Lochgilphead", "Lockerbie", "Londonderry", "Long Eaton", "Longridge", "Looe", "Lossiemouth", "Lostwithiel", "Loughborough", "Loughton", "Louth", "Lowestoft", "Ludlow", "Lurgan", "Luton", "Lutterworth", "Lydd", "Lydney", "Lyme Regis", "Lymington", "Lynton", "Mablethorpe", "Macclesfield", "Machynlleth", "Maesteg", "Magherafelt", "Maidenhead", "Maidstone", "Maldon", "Malmesbury", "Malton", "Malvern", "Manchester", "Manningtree", "Mansfield", "March", "Margate", "Market Deeping", "Market Drayton", "Market Harborough", "Market Rasen", "Market Weighton", "Markethill", "Markinch", "Marlborough", "Marlow", "Maryport", "Matlock", "Maybole", "Melksham", "Melrose", "Melton Mowbray", "Merthyr Tydfil", "Mexborough", "Middleham", "Middlesbrough", "Middlewich", "Midhurst", "Midsomer Norton", "Milford Haven", "Milngavie", "Milton Keynes", "Minehead", "Moffat", "Mold", "Monifieth", "Monmouth", "Montgomery", "Montrose", "Morecambe", "Moreton in Marsh", "Moretonhampstead", "Morley", "Morpeth", "Motherwell", "Musselburgh", "Nailsea", "Nailsworth", "Nairn", "Nantwich", "Narberth", "Neath", "Needham Market", "Neston", "New Mills", "New Milton", "Newbury", "Newcastle", "Newcastle Emlyn", "Newcastle upon Tyne", "Newent", "Newhaven", "Newmarket", "Newport", "Newport Pagnell", "Newport on Tay", "Newquay", "Newry", "Newton Abbot", "Newton Aycliffe", "Newton Stewart", "Newton le Willows", "Newtown", "Newtownabbey", "Newtownards", "Normanton", "North Berwick", "North Walsham", "Northallerton", "Northampton", "Northwich", "Norwich", "Nottingham", "Nuneaton", "Oakham", "Oban", "Okehampton", "Oldbury", "Oldham", "Oldmeldrum", "Olney", "Omagh", "Ormskirk", "Orpington", "Ossett", "Oswestry", "Otley", "Oundle", "Oxford", "Padstow", "Paignton", "Painswick", "Paisley", "Peebles", "Pembroke", "Penarth", "Penicuik", "Penistone", "Penmaenmawr", "Penrith", "Penryn", "Penzance", "Pershore", "Perth", "Peterborough", "Peterhead", "Peterlee", "Petersfield", "Petworth", "Pickering", "Pitlochry", "Pittenweem", "Plymouth", "Pocklington", "Polegate", "Pontefract", "Pontypridd", "Poole", "Port Talbot", "Portadown", "Portaferry", "Porth", "Porthcawl", "Porthmadog", "Portishead", "Portrush", "Portsmouth", "Portstewart", "Potters Bar", "Potton", "Poulton le Fylde", "Prescot", "Prestatyn", "Presteigne", "Preston", "Prestwick", "Princes Risborough", "Prudhoe", "Pudsey", "Pwllheli", "Ramsgate", "Randalstown", "Rayleigh", "Reading", "Redcar", "Redditch", "Redhill", "Redruth", "Reigate", "Retford", "Rhayader", "Rhuddlan", "Rhyl", "Richmond", "Rickmansworth", "Ringwood", "Ripley", "Ripon", "Rochdale", "Rochester", "Rochford", "Romford", "Romsey", "Ross on Wye", "Rostrevor", "Rothbury", "Rotherham", "Rothesay", "Rowley Regis", "Royston", "Rugby", "Rugeley", "Runcorn", "Rushden", "Rutherglen", "Ruthin", "Ryde", "Rye", "Saffron Walden", "Saintfield", "Salcombe", "Sale", "Salford", "Salisbury", "Saltash", "Saltcoats", "Sandbach", "Sandhurst", "Sandown", "Sandwich", "Sandy", "Sawbridgeworth", "Saxmundham", "Scarborough", "Scunthorpe", "Seaford", "Seaton", "Sedgefield", "Selby", "Selkirk", "Selsey", "Settle", "Sevenoaks", "Shaftesbury", "Shanklin", "Sheerness", "Sheffield", "Shepshed", "Shepton Mallet", "Sherborne", "Sheringham", "Shildon", "Shipston on Stour", "Shoreham by Sea", "Shrewsbury", "Sidmouth", "Sittingbourne", "Skegness", "Skelmersdale", "Skipton", "Sleaford", "Slough", "Smethwick", "Soham", "Solihull", "Somerton", "South Molton", "South Shields", "South Woodham Ferrers", "Southam", "Southampton", "Southborough", "Southend on Sea", "Southport", "Southsea", "Southwell", "Southwold", "Spalding", "Spennymoor", "Spilsby", "Stafford", "Staines", "Stamford", "Stanley", "Staveley", "Stevenage", "Stirling", "Stockport", "Stockton on Tees", "Stoke on Trent", "Stone", "Stowmarket", "Strabane", "Stranraer", "Stratford upon Avon", "Strood", "Stroud", "Sudbury", "Sunderland", "Sutton Coldfield", "Sutton in Ashfield", "Swadlincote", "Swanage", "Swanley", "Swansea", "Swindon", "Tadcaster", "Tadley", "Tain", "Talgarth", "Tamworth", "Taunton", "Tavistock", "Teignmouth", "Telford", "Tenby", "Tenterden", "Tetbury", "Tewkesbury", "Thame", "Thatcham", "Thaxted", "Thetford", "Thirsk", "Thornbury", "Thrapston", "Thurso", "Tilbury", "Tillicoultry", "Tipton", "Tiverton", "Tobermory", "Todmorden", "Tonbridge", "Torpoint", "Torquay", "Totnes", "Totton", "Towcester", "Tredegar", "Tregaron", "Tring", "Troon", "Trowbridge", "Truro", "Tunbridge Wells", "Tywyn", "Uckfield", "Ulverston", "Uppingham", "Usk", "Uttoxeter", "Ventnor", "Verwood", "Wadebridge", "Wadhurst", "Wakefield", "Wallasey", "Wallingford", "Walsall", "Waltham Abbey", "Waltham Cross", "Walton on Thames", "Walton on the Naze", "Wantage", "Ware", "Wareham", "Warminster", "Warrenpoint", "Warrington", "Warwick", "Washington", "Watford", "Wednesbury", "Wednesfield", "Wellingborough", "Wellington", "Wells", "Wells next the Sea", "Welshpool", "Welwyn Garden City", "Wem", "Wendover", "West Bromwich", "Westbury", "Westerham", "Westhoughton", "Weston super Mare", "Wetherby", "Weybridge", "Weymouth", "Whaley Bridge", "Whitby", "Whitchurch", "Whitehaven", "Whitley Bay", "Whitnash", "Whitstable", "Whitworth", "Wick", "Wickford", "Widnes", "Wigan", "Wigston", "Wigtown", "Willenhall", "Wincanton", "Winchester", "Windermere", "Winsford", "Winslow", "Wisbech", "Witham", "Withernsea", "Witney", "Woburn", "Woking", "Wokingham", "Wolverhampton", "Wombwell", "Woodbridge", "Woodstock", "Wootton Bassett", "Worcester", "Workington", "Worksop", "Worthing", "Wotton under Edge", "Wrexham", "Wymondham", "Yarm", "Yarmouth", "Yate", "Yateley", "Yeadon", "Yeovil", "York" }; } public string Generate() { return _citynames[_random.Next(0, _citynames.Count)]; } } }
Java
<fieldset class="col-sm-12 bordure"> <legend class="legende">{{ 'Verifyrecord' | translate }}</legend> <div ng-include src="'partials/message-include.html'"></div> <form class="well form-horizontal"> <div class="form-group"> <label for="verifyrecord_uid" class="col-sm-2 control-label">{{ 'verifyrecord.uid' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_uid" name="uid" ng-model="verifyrecord.uid" class="form-control" maxLength="20" ng-disabled="mode != 'create'"/> </div> </div> <div class="form-group"> <label for="verifyrecord_verifytype" class="col-sm-2 control-label">{{ 'verifyrecord.verifytype' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_verifytype" name="verifytype" ng-model="verifyrecord.verifytype" class="form-control" maxLength="4" /> </div> </div> <div class="form-group"> <label for="verifyrecord_userid" class="col-sm-2 control-label">{{ 'verifyrecord.userid' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_userid" name="userid" ng-model="verifyrecord.userid" class="form-control" maxLength="20" /> </div> </div> <div class="form-group"> <label for="verifyrecord_username" class="col-sm-2 control-label">{{ 'verifyrecord.username' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_username" name="username" ng-model="verifyrecord.username" class="form-control" maxLength="50" /> </div> </div> <div class="form-group"> <label for="verifyrecord_email" class="col-sm-2 control-label">{{ 'verifyrecord.email' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_email" name="email" ng-model="verifyrecord.email" class="form-control" maxLength="100" /> </div> </div> <div class="form-group"> <label for="verifyrecord_randomcode" class="col-sm-2 control-label">{{ 'verifyrecord.randomcode' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_randomcode" name="randomcode" ng-model="verifyrecord.randomcode" class="form-control" maxLength="30" /> </div> </div> <div class="form-group"> <label for="verifyrecord_expiretime" class="col-sm-2 control-label">{{ 'verifyrecord.expiretime' | translate }}</label> <div class="col-sm-10"> <input id="verifyrecord_expiretime" bs-datepicker data-autoclose="1" ng-model="verifyrecord.expiretime" name="expiretime" class="form-control" /> </div> </div> <div class="form-group"> <label for="verifyrecord_resetflg" class="col-sm-2 control-label">{{ 'verifyrecord.resetflg' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_resetflg" name="resetflg" ng-model="verifyrecord.resetflg" class="form-control" maxLength="4" /> </div> </div> <div class="form-group"> <label for="verifyrecord_createdate" class="col-sm-2 control-label">{{ 'verifyrecord.createdate' | translate }}</label> <div class="col-sm-10"> <input id="verifyrecord_createdate" bs-datepicker data-autoclose="1" ng-model="verifyrecord.createdate" name="createdate" class="form-control" /> </div> </div> <div class="form-group"> <label for="verifyrecord_modifydate" class="col-sm-2 control-label">{{ 'verifyrecord.modifydate' | translate }}</label> <div class="col-sm-10"> <input id="verifyrecord_modifydate" bs-datepicker data-autoclose="1" ng-model="verifyrecord.modifydate" name="modifydate" class="form-control" /> </div> </div> <div class="form-group"> <label for="verifyrecord_createuser" class="col-sm-2 control-label">{{ 'verifyrecord.createuser' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_createuser" name="createuser" ng-model="verifyrecord.createuser" class="form-control" maxLength="50" /> </div> </div> <div class="form-group"> <label for="verifyrecord_modifyuser" class="col-sm-2 control-label">{{ 'verifyrecord.modifyuser' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_modifyuser" name="modifyuser" ng-model="verifyrecord.modifyuser" class="form-control" maxLength="50" /> </div> </div> <div class="form-group"> <label for="verifyrecord_delflg" class="col-sm-2 control-label">{{ 'verifyrecord.delflg' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_delflg" name="delflg" ng-model="verifyrecord.delflg" class="form-control" maxLength="4" /> </div> </div> <div class="form-group"> <label for="verifyrecord_platform" class="col-sm-2 control-label">{{ 'verifyrecord.platform' | translate }}</label> <div class="col-sm-10"> <input type="text" id="verifyrecord_platform" name="platform" ng-model="verifyrecord.platform" class="form-control" maxLength="50" /> </div> </div> <!-- ACTION BUTTONS --> <div class="form-group"> <div class="col-sm-offset-2 col-sm-2"> <a role="button" class="btn btn-danger btn-block" ng-click="delete(verifyrecord.uid)" ng-show="mode != 'create'">{{ 'delete' | translate }}</a> </div> <div class="col-sm-offset-4 col-sm-2"> <a role="button" class="btn btn-default btn-block" href="#/verifyrecord">{{ 'cancel' | translate }}</a> </div> <div class="col-sm-2"> <button type="submit" class="btn btn-primary btn-lg btn-block" ng-click="save()">{{ 'save' | translate }}</button> </div> </div> </form> </fieldset>
Java
// This file was generated based on 'C:\ProgramData\Uno\Packages\Fuse.Controls\0.18.8\$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Controls.TextBlock.h> #include <Fuse.IActualPlacement.h> #include <Fuse.Navigation.INavigationPanel.h> #include <Fuse.Node.h> #include <Fuse.Scripting.INameScope.h> #include <Fuse.Triggers.Actions.ICollapse.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Fuse.Triggers.IAddRemove-1.h> #include <Fuse.Triggers.IValue-1.h> #include <Uno.String.h> namespace g{namespace Fuse{namespace Controls{struct Text;}}} namespace g{ namespace Fuse{ namespace Controls{ // public sealed class Text :4254 // { ::g::Fuse::Controls::TextControl_type* Text_typeof(); void Text__ctor_6_fn(Text* __this); void Text__New2_fn(Text** __retval); void Text__OnRooted_fn(Text* __this); void Text__OnUnrooted_fn(Text* __this); struct Text : ::g::Fuse::Controls::TextBlock { void ctor_6(); static Text* New2(); }; // } }}} // ::g::Fuse::Controls
Java
var JobsList = React.createClass({displayName: "JobsList", render: function() { return ( React.createElement(JobItem, {title: "Trabalho Python", desc: "Descricao aqui"}) ); } }); var JobItem = React.createClass({displayName: "JobItem", render: function() { React.createElement("div", {className: "panel panel-default"}, React.createElement("div", {className: "panel-heading"}, this.params.job.title), React.createElement("div", {className: "panel-body"}, this.params.job.desc ) ) } })
Java
/*************************************************************************/ /* skeleton_modification_stack_3d.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #ifndef SKELETONMODIFICATIONSTACK3D_H #define SKELETONMODIFICATIONSTACK3D_H #include "core/templates/local_vector.h" #include "scene/3d/skeleton_3d.h" class Skeleton3D; class SkeletonModification3D; class SkeletonModificationStack3D : public Resource { GDCLASS(SkeletonModificationStack3D, Resource); friend class Skeleton3D; friend class SkeletonModification3D; protected: static void _bind_methods(); virtual void _get_property_list(List<PropertyInfo> *p_list) const; virtual bool _set(const StringName &p_path, const Variant &p_value); virtual bool _get(const StringName &p_path, Variant &r_ret) const; public: Skeleton3D *skeleton = nullptr; bool is_setup = false; bool enabled = false; real_t strength = 1.0; enum EXECUTION_MODE { execution_mode_process, execution_mode_physics_process, }; LocalVector<Ref<SkeletonModification3D>> modifications = LocalVector<Ref<SkeletonModification3D>>(); int modifications_count = 0; virtual void setup(); virtual void execute(real_t p_delta, int p_execution_mode); void enable_all_modifications(bool p_enable); Ref<SkeletonModification3D> get_modification(int p_mod_idx) const; void add_modification(Ref<SkeletonModification3D> p_mod); void delete_modification(int p_mod_idx); void set_modification(int p_mod_idx, Ref<SkeletonModification3D> p_mod); void set_modification_count(int p_count); int get_modification_count() const; void set_skeleton(Skeleton3D *p_skeleton); Skeleton3D *get_skeleton() const; bool get_is_setup() const; void set_enabled(bool p_enabled); bool get_enabled() const; void set_strength(real_t p_strength); real_t get_strength() const; SkeletonModificationStack3D(); }; #endif // SKELETONMODIFICATIONSTACK3D_H
Java
Merge Search Result Templates ================ With these templates you are able to merge search results from multiple search web parts into one view. ![Here is an example where a global query is merged with results from ICT](http://www.eliostruyf.com/wp-content/uploads/2015/08/081715_1551_Mergesearch3.png) File | Desciption --- | --- __Control_Combine.html__ | This is the control display template that enables you to merge search results. __Item_Combine.html__ | This is the item display template that pushes the item HTML to the control template. Related blog post ------- Check the following post to get more information about how you need to configure this on your environment: [Merge search results from multiple search web parts together](http://www.eliostruyf.com/merge-search-results-from-multiple-search-web-parts-together/)
Java
/* Copyright (c) 2007-2016, The Tor Project, Inc. */ /* See LICENSE for licensing information */ /** * \file geoip.c * \brief Functions related to maintaining an IP-to-country database; * to summarizing client connections by country to entry guards, bridges, * and directory servers; and for statistics on answering network status * requests. * * There are two main kinds of functions in this module: geoip functions, * which map groups of IPv4 and IPv6 addresses to country codes, and * statistical functions, which collect statistics about different kinds of * per-country usage. * * The geoip lookup tables are implemented as sorted lists of disjoint address * ranges, each mapping to a singleton geoip_country_t. These country objects * are also indexed by their names in a hashtable. * * The tables are populated from disk at startup by the geoip_load_file() * function. For more information on the file format they read, see that * function. See the scripts and the README file in src/config for more * information about how those files are generated. * * Tor uses GeoIP information in order to implement user requests (such as * ExcludeNodes {cc}), and to keep track of how much usage relays are getting * for each country. */ #define GEOIP_PRIVATE #include "or.h" #include "ht.h" #include "config.h" #include "control.h" #include "dnsserv.h" #include "geoip.h" #include "routerlist.h" static void init_geoip_countries(void); /** An entry from the GeoIP IPv4 file: maps an IPv4 range to a country. */ typedef struct geoip_ipv4_entry_t { uint32_t ip_low; /**< The lowest IP in the range, in host order */ uint32_t ip_high; /**< The highest IP in the range, in host order */ intptr_t country; /**< An index into geoip_countries */ } geoip_ipv4_entry_t; /** An entry from the GeoIP IPv6 file: maps an IPv6 range to a country. */ typedef struct geoip_ipv6_entry_t { struct in6_addr ip_low; /**< The lowest IP in the range, in host order */ struct in6_addr ip_high; /**< The highest IP in the range, in host order */ intptr_t country; /**< An index into geoip_countries */ } geoip_ipv6_entry_t; /** A per-country record for GeoIP request history. */ typedef struct geoip_country_t { char countrycode[3]; uint32_t n_v3_ns_requests; } geoip_country_t; /** A list of geoip_country_t */ static smartlist_t *geoip_countries = NULL; /** A map from lowercased country codes to their position in geoip_countries. * The index is encoded in the pointer, and 1 is added so that NULL can mean * not found. */ static strmap_t *country_idxplus1_by_lc_code = NULL; /** Lists of all known geoip_ipv4_entry_t and geoip_ipv6_entry_t, sorted * by their respective ip_low. */ static smartlist_t *geoip_ipv4_entries = NULL, *geoip_ipv6_entries = NULL; /** SHA1 digest of the GeoIP files to include in extra-info descriptors. */ static char geoip_digest[DIGEST_LEN]; static char geoip6_digest[DIGEST_LEN]; /** Return the index of the <b>country</b>'s entry in the GeoIP * country list if it is a valid 2-letter country code, otherwise * return -1. */ MOCK_IMPL(country_t, geoip_get_country,(const char *country)) { void *idxplus1_; intptr_t idx; idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country); if (!idxplus1_) return -1; idx = ((uintptr_t)idxplus1_)-1; return (country_t)idx; } /** Add an entry to a GeoIP table, mapping all IP addresses between <b>low</b> * and <b>high</b>, inclusive, to the 2-letter country code <b>country</b>. */ static void geoip_add_entry(const tor_addr_t *low, const tor_addr_t *high, const char *country) { intptr_t idx; void *idxplus1_; IF_BUG_ONCE(tor_addr_family(low) != tor_addr_family(high)) return; IF_BUG_ONCE(tor_addr_compare(high, low, CMP_EXACT) < 0) return; idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country); if (!idxplus1_) { geoip_country_t *c = tor_malloc_zero(sizeof(geoip_country_t)); strlcpy(c->countrycode, country, sizeof(c->countrycode)); tor_strlower(c->countrycode); smartlist_add(geoip_countries, c); idx = smartlist_len(geoip_countries) - 1; strmap_set_lc(country_idxplus1_by_lc_code, country, (void*)(idx+1)); } else { idx = ((uintptr_t)idxplus1_)-1; } { geoip_country_t *c = smartlist_get(geoip_countries, idx); tor_assert(!strcasecmp(c->countrycode, country)); } if (tor_addr_family(low) == AF_INET) { geoip_ipv4_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv4_entry_t)); ent->ip_low = tor_addr_to_ipv4h(low); ent->ip_high = tor_addr_to_ipv4h(high); ent->country = idx; smartlist_add(geoip_ipv4_entries, ent); } else if (tor_addr_family(low) == AF_INET6) { geoip_ipv6_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv6_entry_t)); ent->ip_low = *tor_addr_to_in6_assert(low); ent->ip_high = *tor_addr_to_in6_assert(high); ent->country = idx; smartlist_add(geoip_ipv6_entries, ent); } } /** Add an entry to the GeoIP table indicated by <b>family</b>, * parsing it from <b>line</b>. The format is as for geoip_load_file(). */ STATIC int geoip_parse_entry(const char *line, sa_family_t family) { tor_addr_t low_addr, high_addr; char c[3]; char *country = NULL; if (!geoip_countries) init_geoip_countries(); if (family == AF_INET) { if (!geoip_ipv4_entries) geoip_ipv4_entries = smartlist_new(); } else if (family == AF_INET6) { if (!geoip_ipv6_entries) geoip_ipv6_entries = smartlist_new(); } else { log_warn(LD_GENERAL, "Unsupported family: %d", family); return -1; } while (TOR_ISSPACE(*line)) ++line; if (*line == '#') return 0; char buf[512]; if (family == AF_INET) { unsigned int low, high; if (tor_sscanf(line,"%u,%u,%2s", &low, &high, c) == 3 || tor_sscanf(line,"\"%u\",\"%u\",\"%2s\",", &low, &high, c) == 3) { tor_addr_from_ipv4h(&low_addr, low); tor_addr_from_ipv4h(&high_addr, high); } else goto fail; country = c; } else { /* AF_INET6 */ char *low_str, *high_str; struct in6_addr low, high; char *strtok_state; strlcpy(buf, line, sizeof(buf)); low_str = tor_strtok_r(buf, ",", &strtok_state); if (!low_str) goto fail; high_str = tor_strtok_r(NULL, ",", &strtok_state); if (!high_str) goto fail; country = tor_strtok_r(NULL, "\n", &strtok_state); if (!country) goto fail; if (strlen(country) != 2) goto fail; if (tor_inet_pton(AF_INET6, low_str, &low) <= 0) goto fail; tor_addr_from_in6(&low_addr, &low); if (tor_inet_pton(AF_INET6, high_str, &high) <= 0) goto fail; tor_addr_from_in6(&high_addr, &high); } geoip_add_entry(&low_addr, &high_addr, country); return 0; fail: log_warn(LD_GENERAL, "Unable to parse line from GEOIP %s file: %s", family == AF_INET ? "IPv4" : "IPv6", escaped(line)); return -1; } /** Sorting helper: return -1, 1, or 0 based on comparison of two * geoip_ipv4_entry_t */ static int geoip_ipv4_compare_entries_(const void **_a, const void **_b) { const geoip_ipv4_entry_t *a = *_a, *b = *_b; if (a->ip_low < b->ip_low) return -1; else if (a->ip_low > b->ip_low) return 1; else return 0; } /** bsearch helper: return -1, 1, or 0 based on comparison of an IP (a pointer * to a uint32_t in host order) to a geoip_ipv4_entry_t */ static int geoip_ipv4_compare_key_to_entry_(const void *_key, const void **_member) { /* No alignment issue here, since _key really is a pointer to uint32_t */ const uint32_t addr = *(uint32_t *)_key; const geoip_ipv4_entry_t *entry = *_member; if (addr < entry->ip_low) return -1; else if (addr > entry->ip_high) return 1; else return 0; } /** Sorting helper: return -1, 1, or 0 based on comparison of two * geoip_ipv6_entry_t */ static int geoip_ipv6_compare_entries_(const void **_a, const void **_b) { const geoip_ipv6_entry_t *a = *_a, *b = *_b; return fast_memcmp(a->ip_low.s6_addr, b->ip_low.s6_addr, sizeof(struct in6_addr)); } /** bsearch helper: return -1, 1, or 0 based on comparison of an IPv6 * (a pointer to a in6_addr) to a geoip_ipv6_entry_t */ static int geoip_ipv6_compare_key_to_entry_(const void *_key, const void **_member) { const struct in6_addr *addr = (struct in6_addr *)_key; const geoip_ipv6_entry_t *entry = *_member; if (fast_memcmp(addr->s6_addr, entry->ip_low.s6_addr, sizeof(struct in6_addr)) < 0) return -1; else if (fast_memcmp(addr->s6_addr, entry->ip_high.s6_addr, sizeof(struct in6_addr)) > 0) return 1; else return 0; } /** Return 1 if we should collect geoip stats on bridge users, and * include them in our extrainfo descriptor. Else return 0. */ int should_record_bridge_info(const or_options_t *options) { return options->BridgeRelay && options->BridgeRecordUsageByCountry; } /** Set up a new list of geoip countries with no countries (yet) set in it, * except for the unknown country. */ static void init_geoip_countries(void) { geoip_country_t *geoip_unresolved; geoip_countries = smartlist_new(); /* Add a geoip_country_t for requests that could not be resolved to a * country as first element (index 0) to geoip_countries. */ geoip_unresolved = tor_malloc_zero(sizeof(geoip_country_t)); strlcpy(geoip_unresolved->countrycode, "??", sizeof(geoip_unresolved->countrycode)); smartlist_add(geoip_countries, geoip_unresolved); country_idxplus1_by_lc_code = strmap_new(); strmap_set_lc(country_idxplus1_by_lc_code, "??", (void*)(1)); } /** Clear appropriate GeoIP database, based on <b>family</b>, and * reload it from the file <b>filename</b>. Return 0 on success, -1 on * failure. * * Recognized line formats for IPv4 are: * INTIPLOW,INTIPHIGH,CC * and * "INTIPLOW","INTIPHIGH","CC","CC3","COUNTRY NAME" * where INTIPLOW and INTIPHIGH are IPv4 addresses encoded as 4-byte unsigned * integers, and CC is a country code. * * Recognized line format for IPv6 is: * IPV6LOW,IPV6HIGH,CC * where IPV6LOW and IPV6HIGH are IPv6 addresses and CC is a country code. * * It also recognizes, and skips over, blank lines and lines that start * with '#' (comments). */ int geoip_load_file(sa_family_t family, const char *filename) { FILE *f; const char *msg = ""; const or_options_t *options = get_options(); int severity = options_need_geoip_info(options, &msg) ? LOG_WARN : LOG_INFO; crypto_digest_t *geoip_digest_env = NULL; tor_assert(family == AF_INET || family == AF_INET6); if (!(f = tor_fopen_cloexec(filename, "r"))) { log_fn(severity, LD_GENERAL, "Failed to open GEOIP file %s. %s", filename, msg); return -1; } if (!geoip_countries) init_geoip_countries(); if (family == AF_INET) { if (geoip_ipv4_entries) { SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, e, tor_free(e)); smartlist_free(geoip_ipv4_entries); } geoip_ipv4_entries = smartlist_new(); } else { /* AF_INET6 */ if (geoip_ipv6_entries) { SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, e, tor_free(e)); smartlist_free(geoip_ipv6_entries); } geoip_ipv6_entries = smartlist_new(); } geoip_digest_env = crypto_digest_new(); log_notice(LD_GENERAL, "Parsing GEOIP %s file %s.", (family == AF_INET) ? "IPv4" : "IPv6", filename); while (!feof(f)) { char buf[512]; if (fgets(buf, (int)sizeof(buf), f) == NULL) break; crypto_digest_add_bytes(geoip_digest_env, buf, strlen(buf)); /* FFFF track full country name. */ geoip_parse_entry(buf, family); } /*XXXX abort and return -1 if no entries/illformed?*/ fclose(f); /* Sort list and remember file digests so that we can include it in * our extra-info descriptors. */ if (family == AF_INET) { smartlist_sort(geoip_ipv4_entries, geoip_ipv4_compare_entries_); /* Okay, now we need to maybe change our mind about what is in * which country. We do this for IPv4 only since that's what we * store in node->country. */ refresh_all_country_info(); crypto_digest_get_digest(geoip_digest_env, geoip_digest, DIGEST_LEN); } else { /* AF_INET6 */ smartlist_sort(geoip_ipv6_entries, geoip_ipv6_compare_entries_); crypto_digest_get_digest(geoip_digest_env, geoip6_digest, DIGEST_LEN); } crypto_digest_free(geoip_digest_env); return 0; } /** Given an IP address in host order, return a number representing the * country to which that address belongs, -1 for "No geoip information * available", or 0 for the 'unknown country'. The return value will always * be less than geoip_get_n_countries(). To decode it, call * geoip_get_country_name(). */ STATIC int geoip_get_country_by_ipv4(uint32_t ipaddr) { geoip_ipv4_entry_t *ent; if (!geoip_ipv4_entries) return -1; ent = smartlist_bsearch(geoip_ipv4_entries, &ipaddr, geoip_ipv4_compare_key_to_entry_); return ent ? (int)ent->country : 0; } /** Given an IPv6 address, return a number representing the country to * which that address belongs, -1 for "No geoip information available", or * 0 for the 'unknown country'. The return value will always be less than * geoip_get_n_countries(). To decode it, call geoip_get_country_name(). */ STATIC int geoip_get_country_by_ipv6(const struct in6_addr *addr) { geoip_ipv6_entry_t *ent; if (!geoip_ipv6_entries) return -1; ent = smartlist_bsearch(geoip_ipv6_entries, addr, geoip_ipv6_compare_key_to_entry_); return ent ? (int)ent->country : 0; } /** Given an IP address, return a number representing the country to which * that address belongs, -1 for "No geoip information available", or 0 for * the 'unknown country'. The return value will always be less than * geoip_get_n_countries(). To decode it, call geoip_get_country_name(). */ MOCK_IMPL(int, geoip_get_country_by_addr,(const tor_addr_t *addr)) { if (tor_addr_family(addr) == AF_INET) { return geoip_get_country_by_ipv4(tor_addr_to_ipv4h(addr)); } else if (tor_addr_family(addr) == AF_INET6) { return geoip_get_country_by_ipv6(tor_addr_to_in6(addr)); } else { return -1; } } /** Return the number of countries recognized by the GeoIP country list. */ MOCK_IMPL(int, geoip_get_n_countries,(void)) { if (!geoip_countries) init_geoip_countries(); return (int) smartlist_len(geoip_countries); } /** Return the two-letter country code associated with the number <b>num</b>, * or "??" for an unknown value. */ const char * geoip_get_country_name(country_t num) { if (geoip_countries && num >= 0 && num < smartlist_len(geoip_countries)) { geoip_country_t *c = smartlist_get(geoip_countries, num); return c->countrycode; } else return "??"; } /** Return true iff we have loaded a GeoIP database.*/ MOCK_IMPL(int, geoip_is_loaded,(sa_family_t family)) { tor_assert(family == AF_INET || family == AF_INET6); if (geoip_countries == NULL) return 0; if (family == AF_INET) return geoip_ipv4_entries != NULL; else /* AF_INET6 */ return geoip_ipv6_entries != NULL; } /** Return the hex-encoded SHA1 digest of the loaded GeoIP file. The * result does not need to be deallocated, but will be overwritten by the * next call of hex_str(). */ const char * geoip_db_digest(sa_family_t family) { tor_assert(family == AF_INET || family == AF_INET6); if (family == AF_INET) return hex_str(geoip_digest, DIGEST_LEN); else /* AF_INET6 */ return hex_str(geoip6_digest, DIGEST_LEN); } /** Entry in a map from IP address to the last time we've seen an incoming * connection from that IP address. Used by bridges only, to track which * countries have them blocked. */ typedef struct clientmap_entry_t { HT_ENTRY(clientmap_entry_t) node; tor_addr_t addr; /* Name of pluggable transport used by this client. NULL if no pluggable transport was used. */ char *transport_name; /** Time when we last saw this IP address, in MINUTES since the epoch. * * (This will run out of space around 4011 CE. If Tor is still in use around * 4000 CE, please remember to add more bits to last_seen_in_minutes.) */ unsigned int last_seen_in_minutes:30; unsigned int action:2; } clientmap_entry_t; /** Largest allowable value for last_seen_in_minutes. (It's a 30-bit field, * so it can hold up to (1u<<30)-1, or 0x3fffffffu. */ #define MAX_LAST_SEEN_IN_MINUTES 0X3FFFFFFFu /** Map from client IP address to last time seen. */ static HT_HEAD(clientmap, clientmap_entry_t) client_history = HT_INITIALIZER(); /** Hashtable helper: compute a hash of a clientmap_entry_t. */ static inline unsigned clientmap_entry_hash(const clientmap_entry_t *a) { unsigned h = (unsigned) tor_addr_hash(&a->addr); if (a->transport_name) h += (unsigned) siphash24g(a->transport_name, strlen(a->transport_name)); return h; } /** Hashtable helper: compare two clientmap_entry_t values for equality. */ static inline int clientmap_entries_eq(const clientmap_entry_t *a, const clientmap_entry_t *b) { if (strcmp_opt(a->transport_name, b->transport_name)) return 0; return !tor_addr_compare(&a->addr, &b->addr, CMP_EXACT) && a->action == b->action; } HT_PROTOTYPE(clientmap, clientmap_entry_t, node, clientmap_entry_hash, clientmap_entries_eq) HT_GENERATE2(clientmap, clientmap_entry_t, node, clientmap_entry_hash, clientmap_entries_eq, 0.6, tor_reallocarray_, tor_free_) /** Free all storage held by <b>ent</b>. */ static void clientmap_entry_free(clientmap_entry_t *ent) { if (!ent) return; tor_free(ent->transport_name); tor_free(ent); } /** Clear history of connecting clients used by entry and bridge stats. */ static void client_history_clear(void) { clientmap_entry_t **ent, **next, *this; for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) { if ((*ent)->action == GEOIP_CLIENT_CONNECT) { this = *ent; next = HT_NEXT_RMV(clientmap, &client_history, ent); clientmap_entry_free(this); } else { next = HT_NEXT(clientmap, &client_history, ent); } } } /** Note that we've seen a client connect from the IP <b>addr</b> * at time <b>now</b>. Ignored by all but bridges and directories if * configured accordingly. */ void geoip_note_client_seen(geoip_client_action_t action, const tor_addr_t *addr, const char *transport_name, time_t now) { const or_options_t *options = get_options(); clientmap_entry_t lookup, *ent; memset(&lookup, 0, sizeof(clientmap_entry_t)); if (action == GEOIP_CLIENT_CONNECT) { /* Only remember statistics as entry guard or as bridge. */ if (!options->EntryStatistics && (!(options->BridgeRelay && options->BridgeRecordUsageByCountry))) return; } else { /* Only gather directory-request statistics if configured, and * forcibly disable them on bridge authorities. */ if (!options->DirReqStatistics || options->BridgeAuthoritativeDir) return; } log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.", safe_str_client(fmt_addr((addr))), transport_name ? transport_name : "<no transport>"); tor_addr_copy(&lookup.addr, addr); lookup.action = (int)action; lookup.transport_name = (char*) transport_name; ent = HT_FIND(clientmap, &client_history, &lookup); if (! ent) { ent = tor_malloc_zero(sizeof(clientmap_entry_t)); tor_addr_copy(&ent->addr, addr); if (transport_name) ent->transport_name = tor_strdup(transport_name); ent->action = (int)action; HT_INSERT(clientmap, &client_history, ent); } if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0) ent->last_seen_in_minutes = (unsigned)(now/60); else ent->last_seen_in_minutes = 0; if (action == GEOIP_CLIENT_NETWORKSTATUS) { int country_idx = geoip_get_country_by_addr(addr); if (country_idx < 0) country_idx = 0; /** unresolved requests are stored at index 0. */ if (country_idx >= 0 && country_idx < smartlist_len(geoip_countries)) { geoip_country_t *country = smartlist_get(geoip_countries, country_idx); ++country->n_v3_ns_requests; } } } /** HT_FOREACH helper: remove a clientmap_entry_t from the hashtable if it's * older than a certain time. */ static int remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff) { time_t cutoff = *(time_t*)_cutoff / 60; if (ent->last_seen_in_minutes < cutoff) { clientmap_entry_free(ent); return 1; } else { return 0; } } /** Forget about all clients that haven't connected since <b>cutoff</b>. */ void geoip_remove_old_clients(time_t cutoff) { clientmap_HT_FOREACH_FN(&client_history, remove_old_client_helper_, &cutoff); } /** How many responses are we giving to clients requesting v3 network * statuses? */ static uint32_t ns_v3_responses[GEOIP_NS_RESPONSE_NUM]; /** Note that we've rejected a client's request for a v3 network status * for reason <b>reason</b> at time <b>now</b>. */ void geoip_note_ns_response(geoip_ns_response_t response) { static int arrays_initialized = 0; if (!get_options()->DirReqStatistics) return; if (!arrays_initialized) { memset(ns_v3_responses, 0, sizeof(ns_v3_responses)); arrays_initialized = 1; } tor_assert(response < GEOIP_NS_RESPONSE_NUM); ns_v3_responses[response]++; } /** Do not mention any country from which fewer than this number of IPs have * connected. This conceivably avoids reporting information that could * deanonymize users, though analysis is lacking. */ #define MIN_IPS_TO_NOTE_COUNTRY 1 /** Do not report any geoip data at all if we have fewer than this number of * IPs to report about. */ #define MIN_IPS_TO_NOTE_ANYTHING 1 /** When reporting geoip data about countries, round up to the nearest * multiple of this value. */ #define IP_GRANULARITY 8 /** Helper type: used to sort per-country totals by value. */ typedef struct c_hist_t { char country[3]; /**< Two-letter country code. */ unsigned total; /**< Total IP addresses seen in this country. */ } c_hist_t; /** Sorting helper: return -1, 1, or 0 based on comparison of two * geoip_ipv4_entry_t. Sort in descending order of total, and then by country * code. */ static int c_hist_compare_(const void **_a, const void **_b) { const c_hist_t *a = *_a, *b = *_b; if (a->total > b->total) return -1; else if (a->total < b->total) return 1; else return strcmp(a->country, b->country); } /** When there are incomplete directory requests at the end of a 24-hour * period, consider those requests running for longer than this timeout as * failed, the others as still running. */ #define DIRREQ_TIMEOUT (10*60) /** Entry in a map from either chan->global_identifier for direct requests * or a unique circuit identifier for tunneled requests to request time, * response size, and completion time of a network status request. Used to * measure download times of requests to derive average client * bandwidths. */ typedef struct dirreq_map_entry_t { HT_ENTRY(dirreq_map_entry_t) node; /** Unique identifier for this network status request; this is either the * chan->global_identifier of the dir channel (direct request) or a new * locally unique identifier of a circuit (tunneled request). This ID is * only unique among other direct or tunneled requests, respectively. */ uint64_t dirreq_id; unsigned int state:3; /**< State of this directory request. */ unsigned int type:1; /**< Is this a direct or a tunneled request? */ unsigned int completed:1; /**< Is this request complete? */ /** When did we receive the request and started sending the response? */ struct timeval request_time; size_t response_size; /**< What is the size of the response in bytes? */ struct timeval completion_time; /**< When did the request succeed? */ } dirreq_map_entry_t; /** Map of all directory requests asking for v2 or v3 network statuses in * the current geoip-stats interval. Values are * of type *<b>dirreq_map_entry_t</b>. */ static HT_HEAD(dirreqmap, dirreq_map_entry_t) dirreq_map = HT_INITIALIZER(); static int dirreq_map_ent_eq(const dirreq_map_entry_t *a, const dirreq_map_entry_t *b) { return a->dirreq_id == b->dirreq_id && a->type == b->type; } /* DOCDOC dirreq_map_ent_hash */ static unsigned dirreq_map_ent_hash(const dirreq_map_entry_t *entry) { unsigned u = (unsigned) entry->dirreq_id; u += entry->type << 20; return u; } HT_PROTOTYPE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash, dirreq_map_ent_eq) HT_GENERATE2(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash, dirreq_map_ent_eq, 0.6, tor_reallocarray_, tor_free_) /** Helper: Put <b>entry</b> into map of directory requests using * <b>type</b> and <b>dirreq_id</b> as key parts. If there is * already an entry for that key, print out a BUG warning and return. */ static void dirreq_map_put_(dirreq_map_entry_t *entry, dirreq_type_t type, uint64_t dirreq_id) { dirreq_map_entry_t *old_ent; tor_assert(entry->type == type); tor_assert(entry->dirreq_id == dirreq_id); /* XXXX we could switch this to HT_INSERT some time, since it seems that * this bug doesn't happen. But since this function doesn't seem to be * critical-path, it's sane to leave it alone. */ old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry); if (old_ent && old_ent != entry) { log_warn(LD_BUG, "Error when putting directory request into local " "map. There was already an entry for the same identifier."); return; } } /** Helper: Look up and return an entry in the map of directory requests * using <b>type</b> and <b>dirreq_id</b> as key parts. If there * is no such entry, return NULL. */ static dirreq_map_entry_t * dirreq_map_get_(dirreq_type_t type, uint64_t dirreq_id) { dirreq_map_entry_t lookup; lookup.type = type; lookup.dirreq_id = dirreq_id; return HT_FIND(dirreqmap, &dirreq_map, &lookup); } /** Note that an either direct or tunneled (see <b>type</b>) directory * request for a v3 network status with unique ID <b>dirreq_id</b> of size * <b>response_size</b> has started. */ void geoip_start_dirreq(uint64_t dirreq_id, size_t response_size, dirreq_type_t type) { dirreq_map_entry_t *ent; if (!get_options()->DirReqStatistics) return; ent = tor_malloc_zero(sizeof(dirreq_map_entry_t)); ent->dirreq_id = dirreq_id; tor_gettimeofday(&ent->request_time); ent->response_size = response_size; ent->type = type; dirreq_map_put_(ent, type, dirreq_id); } /** Change the state of the either direct or tunneled (see <b>type</b>) * directory request with <b>dirreq_id</b> to <b>new_state</b> and * possibly mark it as completed. If no entry can be found for the given * key parts (e.g., if this is a directory request that we are not * measuring, or one that was started in the previous measurement period), * or if the state cannot be advanced to <b>new_state</b>, do nothing. */ void geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type, dirreq_state_t new_state) { dirreq_map_entry_t *ent; if (!get_options()->DirReqStatistics) return; ent = dirreq_map_get_(type, dirreq_id); if (!ent) return; if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS) return; if (new_state - 1 != ent->state) return; ent->state = new_state; if ((type == DIRREQ_DIRECT && new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) || (type == DIRREQ_TUNNELED && new_state == DIRREQ_CHANNEL_BUFFER_FLUSHED)) { tor_gettimeofday(&ent->completion_time); ent->completed = 1; } } /** Return the bridge-ip-transports string that should be inserted in * our extra-info descriptor. Return NULL if the bridge-ip-transports * line should be empty. */ char * geoip_get_transport_history(void) { unsigned granularity = IP_GRANULARITY; /** String hash table (name of transport) -> (number of users). */ strmap_t *transport_counts = strmap_new(); /** Smartlist that contains copies of the names of the transports that have been used. */ smartlist_t *transports_used = smartlist_new(); /* Special string to signify that no transport was used for this connection. Pluggable transport names can't have symbols in their names, so this string will never collide with a real transport. */ static const char* no_transport_str = "<OR>"; clientmap_entry_t **ent; smartlist_t *string_chunks = smartlist_new(); char *the_string = NULL; /* If we haven't seen any clients yet, return NULL. */ if (HT_EMPTY(&client_history)) goto done; /** We do the following steps to form the transport history string: * a) Foreach client that uses a pluggable transport, we increase the * times that transport was used by one. If the client did not use * a transport, we increase the number of times someone connected * without obfuscation. * b) Foreach transport we observed, we write its transport history * string and push it to string_chunks. So, for example, if we've * seen 665 obfs2 clients, we write "obfs2=665". * c) We concatenate string_chunks to form the final string. */ log_debug(LD_GENERAL,"Starting iteration for transport history. %d clients.", HT_SIZE(&client_history)); /* Loop through all clients. */ HT_FOREACH(ent, clientmap, &client_history) { uintptr_t val; void *ptr; const char *transport_name = (*ent)->transport_name; if (!transport_name) transport_name = no_transport_str; /* Increase the count for this transport name. */ ptr = strmap_get(transport_counts, transport_name); val = (uintptr_t)ptr; val++; ptr = (void*)val; strmap_set(transport_counts, transport_name, ptr); /* If it's the first time we see this transport, note it. */ if (val == 1) smartlist_add_strdup(transports_used, transport_name); log_debug(LD_GENERAL, "Client from '%s' with transport '%s'. " "I've now seen %d clients.", safe_str_client(fmt_addr(&(*ent)->addr)), transport_name ? transport_name : "<no transport>", (int)val); } /* Sort the transport names (helps with unit testing). */ smartlist_sort_strings(transports_used); /* Loop through all seen transports. */ SMARTLIST_FOREACH_BEGIN(transports_used, const char *, transport_name) { void *transport_count_ptr = strmap_get(transport_counts, transport_name); uintptr_t transport_count = (uintptr_t) transport_count_ptr; log_debug(LD_GENERAL, "We got "U64_FORMAT" clients with transport '%s'.", U64_PRINTF_ARG((uint64_t)transport_count), transport_name); smartlist_add_asprintf(string_chunks, "%s="U64_FORMAT, transport_name, U64_PRINTF_ARG(round_uint64_to_next_multiple_of( (uint64_t)transport_count, granularity))); } SMARTLIST_FOREACH_END(transport_name); the_string = smartlist_join_strings(string_chunks, ",", 0, NULL); log_debug(LD_GENERAL, "Final bridge-ip-transports string: '%s'", the_string); done: strmap_free(transport_counts, NULL); SMARTLIST_FOREACH(transports_used, char *, s, tor_free(s)); smartlist_free(transports_used); SMARTLIST_FOREACH(string_chunks, char *, s, tor_free(s)); smartlist_free(string_chunks); return the_string; } /** Return a newly allocated comma-separated string containing statistics * on network status downloads. The string contains the number of completed * requests, timeouts, and still running requests as well as the download * times by deciles and quartiles. Return NULL if we have not observed * requests for long enough. */ static char * geoip_get_dirreq_history(dirreq_type_t type) { char *result = NULL; smartlist_t *dirreq_completed = NULL; uint32_t complete = 0, timeouts = 0, running = 0; int bufsize = 1024, written; dirreq_map_entry_t **ptr, **next; struct timeval now; tor_gettimeofday(&now); dirreq_completed = smartlist_new(); for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) { dirreq_map_entry_t *ent = *ptr; if (ent->type != type) { next = HT_NEXT(dirreqmap, &dirreq_map, ptr); continue; } else { if (ent->completed) { smartlist_add(dirreq_completed, ent); complete++; next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr); } else { if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT) timeouts++; else running++; next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr); tor_free(ent); } } } #define DIR_REQ_GRANULARITY 4 complete = round_uint32_to_next_multiple_of(complete, DIR_REQ_GRANULARITY); timeouts = round_uint32_to_next_multiple_of(timeouts, DIR_REQ_GRANULARITY); running = round_uint32_to_next_multiple_of(running, DIR_REQ_GRANULARITY); result = tor_malloc_zero(bufsize); written = tor_snprintf(result, bufsize, "complete=%u,timeout=%u," "running=%u", complete, timeouts, running); if (written < 0) { tor_free(result); goto done; } #define MIN_DIR_REQ_RESPONSES 16 if (complete >= MIN_DIR_REQ_RESPONSES) { uint32_t *dltimes; /* We may have rounded 'completed' up. Here we want to use the * real value. */ complete = smartlist_len(dirreq_completed); dltimes = tor_calloc(complete, sizeof(uint32_t)); SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) { uint32_t bytes_per_second; uint32_t time_diff = (uint32_t) tv_mdiff(&ent->request_time, &ent->completion_time); if (time_diff == 0) time_diff = 1; /* Avoid DIV/0; "instant" answers are impossible * by law of nature or something, but a millisecond * is a bit greater than "instantly" */ bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff); dltimes[ent_sl_idx] = bytes_per_second; } SMARTLIST_FOREACH_END(ent); median_uint32(dltimes, complete); /* sorts as a side effect. */ written = tor_snprintf(result + written, bufsize - written, ",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u," "d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u", dltimes[0], dltimes[1*complete/10-1], dltimes[2*complete/10-1], dltimes[1*complete/4-1], dltimes[3*complete/10-1], dltimes[4*complete/10-1], dltimes[5*complete/10-1], dltimes[6*complete/10-1], dltimes[7*complete/10-1], dltimes[3*complete/4-1], dltimes[8*complete/10-1], dltimes[9*complete/10-1], dltimes[complete-1]); if (written<0) tor_free(result); tor_free(dltimes); } done: SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent, tor_free(ent)); smartlist_free(dirreq_completed); return result; } /** Store a newly allocated comma-separated string in * *<a>country_str</a> containing entries for all the countries from * which we've seen enough clients connect as a bridge, directory * server, or entry guard. The entry format is cc=num where num is the * number of IPs we've seen connecting from that country, and cc is a * lowercased country code. *<a>country_str</a> is set to NULL if * we're not ready to export per country data yet. * * Store a newly allocated comma-separated string in <a>ipver_str</a> * containing entries for clients connecting over IPv4 and IPv6. The * format is family=num where num is the nubmer of IPs we've seen * connecting over that protocol family, and family is 'v4' or 'v6'. * * Return 0 on success and -1 if we're missing geoip data. */ int geoip_get_client_history(geoip_client_action_t action, char **country_str, char **ipver_str) { unsigned granularity = IP_GRANULARITY; smartlist_t *entries = NULL; int n_countries = geoip_get_n_countries(); int i; clientmap_entry_t **cm_ent; unsigned *counts = NULL; unsigned total = 0; unsigned ipv4_count = 0, ipv6_count = 0; if (!geoip_is_loaded(AF_INET) && !geoip_is_loaded(AF_INET6)) return -1; counts = tor_calloc(n_countries, sizeof(unsigned)); HT_FOREACH(cm_ent, clientmap, &client_history) { int country; if ((*cm_ent)->action != (int)action) continue; country = geoip_get_country_by_addr(&(*cm_ent)->addr); if (country < 0) country = 0; /** unresolved requests are stored at index 0. */ tor_assert(0 <= country && country < n_countries); ++counts[country]; ++total; switch (tor_addr_family(&(*cm_ent)->addr)) { case AF_INET: ipv4_count++; break; case AF_INET6: ipv6_count++; break; } } if (ipver_str) { smartlist_t *chunks = smartlist_new(); smartlist_add_asprintf(chunks, "v4=%u", round_to_next_multiple_of(ipv4_count, granularity)); smartlist_add_asprintf(chunks, "v6=%u", round_to_next_multiple_of(ipv6_count, granularity)); *ipver_str = smartlist_join_strings(chunks, ",", 0, NULL); SMARTLIST_FOREACH(chunks, char *, c, tor_free(c)); smartlist_free(chunks); } /* Don't record per country data if we haven't seen enough IPs. */ if (total < MIN_IPS_TO_NOTE_ANYTHING) { tor_free(counts); if (country_str) *country_str = NULL; return 0; } /* Make a list of c_hist_t */ entries = smartlist_new(); for (i = 0; i < n_countries; ++i) { unsigned c = counts[i]; const char *countrycode; c_hist_t *ent; /* Only report a country if it has a minimum number of IPs. */ if (c >= MIN_IPS_TO_NOTE_COUNTRY) { c = round_to_next_multiple_of(c, granularity); countrycode = geoip_get_country_name(i); ent = tor_malloc(sizeof(c_hist_t)); strlcpy(ent->country, countrycode, sizeof(ent->country)); ent->total = c; smartlist_add(entries, ent); } } /* Sort entries. Note that we must do this _AFTER_ rounding, or else * the sort order could leak info. */ smartlist_sort(entries, c_hist_compare_); if (country_str) { smartlist_t *chunks = smartlist_new(); SMARTLIST_FOREACH(entries, c_hist_t *, ch, { smartlist_add_asprintf(chunks, "%s=%u", ch->country, ch->total); }); *country_str = smartlist_join_strings(chunks, ",", 0, NULL); SMARTLIST_FOREACH(chunks, char *, c, tor_free(c)); smartlist_free(chunks); } SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c)); smartlist_free(entries); tor_free(counts); return 0; } /** Return a newly allocated string holding the per-country request history * for v3 network statuses in a format suitable for an extra-info document, * or NULL on failure. */ char * geoip_get_request_history(void) { smartlist_t *entries, *strings; char *result; unsigned granularity = IP_GRANULARITY; if (!geoip_countries) return NULL; entries = smartlist_new(); SMARTLIST_FOREACH_BEGIN(geoip_countries, geoip_country_t *, c) { uint32_t tot = 0; c_hist_t *ent; tot = c->n_v3_ns_requests; if (!tot) continue; ent = tor_malloc_zero(sizeof(c_hist_t)); strlcpy(ent->country, c->countrycode, sizeof(ent->country)); ent->total = round_to_next_multiple_of(tot, granularity); smartlist_add(entries, ent); } SMARTLIST_FOREACH_END(c); smartlist_sort(entries, c_hist_compare_); strings = smartlist_new(); SMARTLIST_FOREACH(entries, c_hist_t *, ent, { smartlist_add_asprintf(strings, "%s=%u", ent->country, ent->total); }); result = smartlist_join_strings(strings, ",", 0, NULL); SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp)); SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent)); smartlist_free(strings); smartlist_free(entries); return result; } /** Start time of directory request stats or 0 if we're not collecting * directory request statistics. */ static time_t start_of_dirreq_stats_interval; /** Initialize directory request stats. */ void geoip_dirreq_stats_init(time_t now) { start_of_dirreq_stats_interval = now; } /** Reset counters for dirreq stats. */ void geoip_reset_dirreq_stats(time_t now) { SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, { c->n_v3_ns_requests = 0; }); { clientmap_entry_t **ent, **next, *this; for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) { if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS) { this = *ent; next = HT_NEXT_RMV(clientmap, &client_history, ent); clientmap_entry_free(this); } else { next = HT_NEXT(clientmap, &client_history, ent); } } } memset(ns_v3_responses, 0, sizeof(ns_v3_responses)); { dirreq_map_entry_t **ent, **next, *this; for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) { this = *ent; next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent); tor_free(this); } } start_of_dirreq_stats_interval = now; } /** Stop collecting directory request stats in a way that we can re-start * doing so in geoip_dirreq_stats_init(). */ void geoip_dirreq_stats_term(void) { geoip_reset_dirreq_stats(0); } /** Return a newly allocated string containing the dirreq statistics * until <b>now</b>, or NULL if we're not collecting dirreq stats. Caller * must ensure start_of_dirreq_stats_interval is in the past. */ char * geoip_format_dirreq_stats(time_t now) { char t[ISO_TIME_LEN+1]; int i; char *v3_ips_string = NULL, *v3_reqs_string = NULL, *v3_direct_dl_string = NULL, *v3_tunneled_dl_string = NULL; char *result = NULL; if (!start_of_dirreq_stats_interval) return NULL; /* Not initialized. */ tor_assert(now >= start_of_dirreq_stats_interval); format_iso_time(t, now); geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS, &v3_ips_string, NULL); v3_reqs_string = geoip_get_request_history(); #define RESPONSE_GRANULARITY 8 for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) { ns_v3_responses[i] = round_uint32_to_next_multiple_of( ns_v3_responses[i], RESPONSE_GRANULARITY); } #undef RESPONSE_GRANULARITY v3_direct_dl_string = geoip_get_dirreq_history(DIRREQ_DIRECT); v3_tunneled_dl_string = geoip_get_dirreq_history(DIRREQ_TUNNELED); /* Put everything together into a single string. */ tor_asprintf(&result, "dirreq-stats-end %s (%d s)\n" "dirreq-v3-ips %s\n" "dirreq-v3-reqs %s\n" "dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u," "not-found=%u,not-modified=%u,busy=%u\n" "dirreq-v3-direct-dl %s\n" "dirreq-v3-tunneled-dl %s\n", t, (unsigned) (now - start_of_dirreq_stats_interval), v3_ips_string ? v3_ips_string : "", v3_reqs_string ? v3_reqs_string : "", ns_v3_responses[GEOIP_SUCCESS], ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS], ns_v3_responses[GEOIP_REJECT_UNAVAILABLE], ns_v3_responses[GEOIP_REJECT_NOT_FOUND], ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED], ns_v3_responses[GEOIP_REJECT_BUSY], v3_direct_dl_string ? v3_direct_dl_string : "", v3_tunneled_dl_string ? v3_tunneled_dl_string : ""); /* Free partial strings. */ tor_free(v3_ips_string); tor_free(v3_reqs_string); tor_free(v3_direct_dl_string); tor_free(v3_tunneled_dl_string); return result; } /** If 24 hours have passed since the beginning of the current dirreq * stats period, write dirreq stats to $DATADIR/stats/dirreq-stats * (possibly overwriting an existing file) and reset counters. Return * when we would next want to write dirreq stats or 0 if we never want to * write. */ time_t geoip_dirreq_stats_write(time_t now) { char *str = NULL; if (!start_of_dirreq_stats_interval) return 0; /* Not initialized. */ if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now) goto done; /* Not ready to write. */ /* Discard all items in the client history that are too old. */ geoip_remove_old_clients(start_of_dirreq_stats_interval); /* Generate history string .*/ str = geoip_format_dirreq_stats(now); if (! str) goto done; /* Write dirreq-stats string to disk. */ if (!check_or_create_data_subdir("stats")) { write_to_data_subdir("stats", "dirreq-stats", str, "dirreq statistics"); /* Reset measurement interval start. */ geoip_reset_dirreq_stats(now); } done: tor_free(str); return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL; } /** Start time of bridge stats or 0 if we're not collecting bridge * statistics. */ static time_t start_of_bridge_stats_interval; /** Initialize bridge stats. */ void geoip_bridge_stats_init(time_t now) { start_of_bridge_stats_interval = now; } /** Stop collecting bridge stats in a way that we can re-start doing so in * geoip_bridge_stats_init(). */ void geoip_bridge_stats_term(void) { client_history_clear(); start_of_bridge_stats_interval = 0; } /** Validate a bridge statistics string as it would be written to a * current extra-info descriptor. Return 1 if the string is valid and * recent enough, or 0 otherwise. */ static int validate_bridge_stats(const char *stats_str, time_t now) { char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1], *eos; const char *BRIDGE_STATS_END = "bridge-stats-end "; const char *BRIDGE_IPS = "bridge-ips "; const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n"; const char *BRIDGE_TRANSPORTS = "bridge-ip-transports "; const char *BRIDGE_TRANSPORTS_EMPTY_LINE = "bridge-ip-transports\n"; const char *tmp; time_t stats_end_time; int seconds; tor_assert(stats_str); /* Parse timestamp and number of seconds from "bridge-stats-end YYYY-MM-DD HH:MM:SS (N s)" */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END); if (!tmp) return 0; tmp += strlen(BRIDGE_STATS_END); if (strlen(tmp) < ISO_TIME_LEN + 6) return 0; strlcpy(stats_end_str, tmp, sizeof(stats_end_str)); if (parse_iso_time(stats_end_str, &stats_end_time) < 0) return 0; if (stats_end_time < now - (25*60*60) || stats_end_time > now + (1*60*60)) return 0; seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10); if (!eos || seconds < 23*60*60) return 0; format_iso_time(stats_start_str, stats_end_time - seconds); /* Parse: "bridge-ips CC=N,CC=N,..." */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS); if (!tmp) { /* Look if there is an empty "bridge-ips" line */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE); if (!tmp) return 0; } /* Parse: "bridge-ip-transports PT=N,PT=N,..." */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS); if (!tmp) { /* Look if there is an empty "bridge-ip-transports" line */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS_EMPTY_LINE); if (!tmp) return 0; } return 1; } /** Most recent bridge statistics formatted to be written to extra-info * descriptors. */ static char *bridge_stats_extrainfo = NULL; /** Return a newly allocated string holding our bridge usage stats by country * in a format suitable for inclusion in an extrainfo document. Return NULL on * failure. */ char * geoip_format_bridge_stats(time_t now) { char *out = NULL; char *country_data = NULL, *ipver_data = NULL, *transport_data = NULL; long duration = now - start_of_bridge_stats_interval; char written[ISO_TIME_LEN+1]; if (duration < 0) return NULL; if (!start_of_bridge_stats_interval) return NULL; /* Not initialized. */ format_iso_time(written, now); geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data); transport_data = geoip_get_transport_history(); tor_asprintf(&out, "bridge-stats-end %s (%ld s)\n" "bridge-ips %s\n" "bridge-ip-versions %s\n" "bridge-ip-transports %s\n", written, duration, country_data ? country_data : "", ipver_data ? ipver_data : "", transport_data ? transport_data : ""); tor_free(country_data); tor_free(ipver_data); tor_free(transport_data); return out; } /** Return a newly allocated string holding our bridge usage stats by country * in a format suitable for the answer to a controller request. Return NULL on * failure. */ static char * format_bridge_stats_controller(time_t now) { char *out = NULL, *country_data = NULL, *ipver_data = NULL; char started[ISO_TIME_LEN+1]; (void) now; format_iso_time(started, start_of_bridge_stats_interval); geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data); tor_asprintf(&out, "TimeStarted=\"%s\" CountrySummary=%s IPVersions=%s", started, country_data ? country_data : "", ipver_data ? ipver_data : ""); tor_free(country_data); tor_free(ipver_data); return out; } /** Return a newly allocated string holding our bridge usage stats by * country in a format suitable for inclusion in our heartbeat * message. Return NULL on failure. */ char * format_client_stats_heartbeat(time_t now) { const int n_hours = 6; char *out = NULL; int n_clients = 0; clientmap_entry_t **ent; unsigned cutoff = (unsigned)( (now-n_hours*3600)/60 ); if (!start_of_bridge_stats_interval) return NULL; /* Not initialized. */ /* count unique IPs */ HT_FOREACH(ent, clientmap, &client_history) { /* only count directly connecting clients */ if ((*ent)->action != GEOIP_CLIENT_CONNECT) continue; if ((*ent)->last_seen_in_minutes < cutoff) continue; n_clients++; } tor_asprintf(&out, "Heartbeat: " "In the last %d hours, I have seen %d unique clients.", n_hours, n_clients); return out; } /** Write bridge statistics to $DATADIR/stats/bridge-stats and return * when we should next try to write statistics. */ time_t geoip_bridge_stats_write(time_t now) { char *val = NULL; /* Check if 24 hours have passed since starting measurements. */ if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL) return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL; /* Discard all items in the client history that are too old. */ geoip_remove_old_clients(start_of_bridge_stats_interval); /* Generate formatted string */ val = geoip_format_bridge_stats(now); if (val == NULL) goto done; /* Update the stored value. */ tor_free(bridge_stats_extrainfo); bridge_stats_extrainfo = val; start_of_bridge_stats_interval = now; /* Write it to disk. */ if (!check_or_create_data_subdir("stats")) { write_to_data_subdir("stats", "bridge-stats", bridge_stats_extrainfo, "bridge statistics"); /* Tell the controller, "hey, there are clients!" */ { char *controller_str = format_bridge_stats_controller(now); if (controller_str) control_event_clients_seen(controller_str); tor_free(controller_str); } } done: return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL; } /** Try to load the most recent bridge statistics from disk, unless we * have finished a measurement interval lately, and check whether they * are still recent enough. */ static void load_bridge_stats(time_t now) { char *fname, *contents; if (bridge_stats_extrainfo) return; fname = get_datadir_fname2("stats", "bridge-stats"); contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL); if (contents && validate_bridge_stats(contents, now)) { bridge_stats_extrainfo = contents; } else { tor_free(contents); } tor_free(fname); } /** Return most recent bridge statistics for inclusion in extra-info * descriptors, or NULL if we don't have recent bridge statistics. */ const char * geoip_get_bridge_stats_extrainfo(time_t now) { load_bridge_stats(now); return bridge_stats_extrainfo; } /** Return a new string containing the recent bridge statistics to be returned * to controller clients, or NULL if we don't have any bridge statistics. */ char * geoip_get_bridge_stats_controller(time_t now) { return format_bridge_stats_controller(now); } /** Start time of entry stats or 0 if we're not collecting entry * statistics. */ static time_t start_of_entry_stats_interval; /** Initialize entry stats. */ void geoip_entry_stats_init(time_t now) { start_of_entry_stats_interval = now; } /** Reset counters for entry stats. */ void geoip_reset_entry_stats(time_t now) { client_history_clear(); start_of_entry_stats_interval = now; } /** Stop collecting entry stats in a way that we can re-start doing so in * geoip_entry_stats_init(). */ void geoip_entry_stats_term(void) { geoip_reset_entry_stats(0); } /** Return a newly allocated string containing the entry statistics * until <b>now</b>, or NULL if we're not collecting entry stats. Caller * must ensure start_of_entry_stats_interval lies in the past. */ char * geoip_format_entry_stats(time_t now) { char t[ISO_TIME_LEN+1]; char *data = NULL; char *result; if (!start_of_entry_stats_interval) return NULL; /* Not initialized. */ tor_assert(now >= start_of_entry_stats_interval); geoip_get_client_history(GEOIP_CLIENT_CONNECT, &data, NULL); format_iso_time(t, now); tor_asprintf(&result, "entry-stats-end %s (%u s)\n" "entry-ips %s\n", t, (unsigned) (now - start_of_entry_stats_interval), data ? data : ""); tor_free(data); return result; } /** If 24 hours have passed since the beginning of the current entry stats * period, write entry stats to $DATADIR/stats/entry-stats (possibly * overwriting an existing file) and reset counters. Return when we would * next want to write entry stats or 0 if we never want to write. */ time_t geoip_entry_stats_write(time_t now) { char *str = NULL; if (!start_of_entry_stats_interval) return 0; /* Not initialized. */ if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now) goto done; /* Not ready to write. */ /* Discard all items in the client history that are too old. */ geoip_remove_old_clients(start_of_entry_stats_interval); /* Generate history string .*/ str = geoip_format_entry_stats(now); /* Write entry-stats string to disk. */ if (!check_or_create_data_subdir("stats")) { write_to_data_subdir("stats", "entry-stats", str, "entry statistics"); /* Reset measurement interval start. */ geoip_reset_entry_stats(now); } done: tor_free(str); return start_of_entry_stats_interval + WRITE_STATS_INTERVAL; } /** Helper used to implement GETINFO ip-to-country/... controller command. */ int getinfo_helper_geoip(control_connection_t *control_conn, const char *question, char **answer, const char **errmsg) { (void)control_conn; if (!strcmpstart(question, "ip-to-country/")) { int c; sa_family_t family; tor_addr_t addr; question += strlen("ip-to-country/"); family = tor_addr_parse(&addr, question); if (family != AF_INET && family != AF_INET6) { *errmsg = "Invalid address family"; return -1; } if (!geoip_is_loaded(family)) { *errmsg = "GeoIP data not loaded"; return -1; } if (family == AF_INET) c = geoip_get_country_by_ipv4(tor_addr_to_ipv4h(&addr)); else /* AF_INET6 */ c = geoip_get_country_by_ipv6(tor_addr_to_in6(&addr)); *answer = tor_strdup(geoip_get_country_name(c)); } return 0; } /** Release all storage held by the GeoIP databases and country list. */ STATIC void clear_geoip_db(void) { if (geoip_countries) { SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, tor_free(c)); smartlist_free(geoip_countries); } strmap_free(country_idxplus1_by_lc_code, NULL); if (geoip_ipv4_entries) { SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, ent, tor_free(ent)); smartlist_free(geoip_ipv4_entries); } if (geoip_ipv6_entries) { SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, ent, tor_free(ent)); smartlist_free(geoip_ipv6_entries); } geoip_countries = NULL; country_idxplus1_by_lc_code = NULL; geoip_ipv4_entries = NULL; geoip_ipv6_entries = NULL; } /** Release all storage held in this file. */ void geoip_free_all(void) { { clientmap_entry_t **ent, **next, *this; for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) { this = *ent; next = HT_NEXT_RMV(clientmap, &client_history, ent); clientmap_entry_free(this); } HT_CLEAR(clientmap, &client_history); } { dirreq_map_entry_t **ent, **next, *this; for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) { this = *ent; next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent); tor_free(this); } HT_CLEAR(dirreqmap, &dirreq_map); } clear_geoip_db(); tor_free(bridge_stats_extrainfo); }
Java
# WebSocket [![Swift][swift-badge]][swift-url] [![Zewo][zewo-badge]][zewo-url] [![Platform][platform-badge]][platform-url] [![License][mit-badge]][mit-url] [![Slack][slack-badge]][slack-url] [![Travis][travis-badge]][travis-url] [![Codebeat][codebeat-badge]][codebeat-url] > :warning: This module contains no networking. To create a WebSocket Server, see [WebSocketServer](https://github.com/Zewo/WebSocketServer). To create a WebSocket Client, see [WebSocketClient](https://github.com/Zewo/WebSocketClient). ## Installation ```swift import PackageDescription let package = Package( dependencies: [ .Package(url: "https://github.com/Zewo/WebSocket.git", majorVersion: 0, minor: 14), ] ) ``` ## Support If you need any help you can join our [Slack](http://slack.zewo.io) and go to the **#help** channel. Or you can create a Github [issue](https://github.com/Zewo/Zewo/issues/new) in our main repository. When stating your issue be sure to add enough details, specify what module is causing the problem and reproduction steps. ## Community [![Slack][slack-image]][slack-url] The entire Zewo code base is licensed under MIT. By contributing to Zewo you are contributing to an open and engaged community of brilliant Swift programmers. Join us on [Slack](http://slack.zewo.io) to get to know us! ## License This project is released under the MIT license. See [LICENSE](LICENSE) for details. [swift-badge]: https://img.shields.io/badge/Swift-3.0-orange.svg?style=flat [swift-url]: https://swift.org [zewo-badge]: https://img.shields.io/badge/Zewo-0.14-FF7565.svg?style=flat [zewo-url]: http://zewo.io [platform-badge]: https://img.shields.io/badge/Platforms-OS%20X%20--%20Linux-lightgray.svg?style=flat [platform-url]: https://swift.org [mit-badge]: https://img.shields.io/badge/License-MIT-blue.svg?style=flat [mit-url]: https://tldrlegal.com/license/mit-license [slack-image]: http://s13.postimg.org/ybwy92ktf/Slack.png [slack-badge]: https://zewo-slackin.herokuapp.com/badge.svg [slack-url]: http://slack.zewo.io [travis-badge]: https://travis-ci.org/Zewo/WebSocket.svg?branch=master [travis-url]: https://travis-ci.org/Zewo/WebSocket [codebeat-badge]: https://codebeat.co/badges/7b271ac4-f447-45a5-8cd0-f0f4c2e57690 [codebeat-url]: https://codebeat.co/projects/github-com-zewo-websocket
Java
#ifndef __ABSPRITE_H #define __ABSPRITE_H #include <Arduino.h> #include <Adafruit_GFX.h> #include <Adafruit_ST7735.h> #include <SPI.h> #include "ab_lcd_image.h" #include "abImage.h" #define AB_SPRITE_SIZE 15 #define DEFAULT_MOVE_DIST 20 #define MAX_SCREEN_WIDTH 128 #define MAX_SCREEN_HEIGHT 160 class abSprite { private: int width; int height; abImage image; public: abSprite(); int x_old; int x; int y_old; int y; int current_sheet; int max_sheet; void setImage(abImage image); abImage getImage(); void setCoordinates(int x, int y); void setSize(int width, int height); void moveRight(); void moveLeft(); void moveUp(); void moveDown(); void moveRight(int dist); void moveLeft(int dist); void moveUp(int dist); void moveDown(int dist); void undraw_old(Adafruit_ST7735 *tft, lcd_image_t *bg); void draw(Adafruit_ST7735 *tft); }; #endif
Java
/* * @package jsDAV * @subpackage CardDAV * @copyright Copyright(c) 2013 Mike de Boer. <info AT mikedeboer DOT nl> * @author Mike de Boer <info AT mikedeboer DOT nl> * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License */ "use strict"; var jsDAV_Plugin = require("./../DAV/plugin"); var jsDAV_Property_Href = require("./../DAV/property/href"); var jsDAV_Property_HrefList = require("./../DAV/property/hrefList"); var jsDAV_Property_iHref = require("./../DAV/interfaces/iHref"); var jsCardDAV_iAddressBook = require("./interfaces/iAddressBook"); var jsCardDAV_iCard = require("./interfaces/iCard"); var jsCardDAV_iDirectory = require("./interfaces/iDirectory"); var jsCardDAV_UserAddressBooks = require("./userAddressBooks"); var jsCardDAV_AddressBookQueryParser = require("./addressBookQueryParser"); var jsDAVACL_iPrincipal = require("./../DAVACL/interfaces/iPrincipal"); var jsVObject_Reader = require("./../VObject/reader"); var AsyncEventEmitter = require("./../shared/asyncEvents").EventEmitter; var Exc = require("./../shared/exceptions"); var Util = require("./../shared/util"); var Xml = require("./../shared/xml"); var Async = require("asyncjs"); /** * CardDAV plugin * * The CardDAV plugin adds CardDAV functionality to the WebDAV server */ var jsCardDAV_Plugin = module.exports = jsDAV_Plugin.extend({ /** * Plugin name * * @var String */ name: "carddav", /** * Url to the addressbooks */ ADDRESSBOOK_ROOT: "addressbooks", /** * xml namespace for CardDAV elements */ NS_CARDDAV: "urn:ietf:params:xml:ns:carddav", /** * Add urls to this property to have them automatically exposed as * 'directories' to the user. * * @var array */ directories: null, /** * Handler class * * @var jsDAV_Handler */ handler: null, /** * Initializes the plugin * * @param DAV\Server server * @return void */ initialize: function(handler) { this.directories = []; // Events handler.addEventListener("beforeGetProperties", this.beforeGetProperties.bind(this)); handler.addEventListener("afterGetProperties", this.afterGetProperties.bind(this)); handler.addEventListener("updateProperties", this.updateProperties.bind(this)); handler.addEventListener("report", this.report.bind(this)); handler.addEventListener("onHTMLActionsPanel", this.htmlActionsPanel.bind(this), AsyncEventEmitter.PRIO_HIGH); handler.addEventListener("onBrowserPostAction", this.browserPostAction.bind(this), AsyncEventEmitter.PRIO_HIGH); handler.addEventListener("beforeWriteContent", this.beforeWriteContent.bind(this)); handler.addEventListener("beforeCreateFile", this.beforeCreateFile.bind(this)); // Namespaces Xml.xmlNamespaces[this.NS_CARDDAV] = "card"; // Mapping Interfaces to {DAV:}resourcetype values handler.resourceTypeMapping["{" + this.NS_CARDDAV + "}addressbook"] = jsCardDAV_iAddressBook; handler.resourceTypeMapping["{" + this.NS_CARDDAV + "}directory"] = jsCardDAV_iDirectory; // Adding properties that may never be changed handler.protectedProperties.push( "{" + this.NS_CARDDAV + "}supported-address-data", "{" + this.NS_CARDDAV + "}max-resource-size", "{" + this.NS_CARDDAV + "}addressbook-home-set", "{" + this.NS_CARDDAV + "}supported-collation-set" ); handler.protectedProperties = Util.makeUnique(handler.protectedProperties); handler.propertyMap["{http://calendarserver.org/ns/}me-card"] = jsDAV_Property_Href; this.handler = handler; }, /** * Returns a list of supported features. * * This is used in the DAV: header in the OPTIONS and PROPFIND requests. * * @return array */ getFeatures: function() { return ["addressbook"]; }, /** * Returns a list of reports this plugin supports. * * This will be used in the {DAV:}supported-report-set property. * Note that you still need to subscribe to the 'report' event to actually * implement them * * @param {String} uri * @return array */ getSupportedReportSet: function(uri, callback) { var self = this; this.handler.getNodeForPath(uri, function(err, node) { if (err) return callback(err); if (node.hasFeature(jsCardDAV_iAddressBook) || node.hasFeature(jsCardDAV_iCard)) { return callback(null, [ "{" + self.NS_CARDDAV + "}addressbook-multiget", "{" + self.NS_CARDDAV + "}addressbook-query" ]); } return callback(null, []); }); }, /** * Adds all CardDAV-specific properties * * @param {String} path * @param DAV\INode node * @param {Array} requestedProperties * @param {Array} returnedProperties * @return void */ beforeGetProperties: function(e, path, node, requestedProperties, returnedProperties) { var self = this; if (node.hasFeature(jsDAVACL_iPrincipal)) { // calendar-home-set property var addHome = "{" + this.NS_CARDDAV + "}addressbook-home-set"; if (requestedProperties[addHome]) { var principalId = node.getName(); var addressbookHomePath = this.ADDRESSBOOK_ROOT + "/" + principalId + "/"; delete requestedProperties[addHome]; returnedProperties["200"][addHome] = jsDAV_Property_Href.new(addressbookHomePath); } var directories = "{" + this.NS_CARDDAV + "}directory-gateway"; if (this.directories && requestedProperties[directories]) { delete requestedProperties[directories]; returnedProperties["200"][directories] = jsDAV_Property_HrefList.new(this.directories); } } if (node.hasFeature(jsCardDAV_iCard)) { // The address-data property is not supposed to be a 'real' // property, but in large chunks of the spec it does act as such. // Therefore we simply expose it as a property. var addressDataProp = "{" + this.NS_CARDDAV + "}address-data"; if (requestedProperties[addressDataProp]) { delete requestedProperties[addressDataProp]; node.get(function(err, val) { if (err) return e.next(err); returnedProperties["200"][addressDataProp] = val.toString("utf8"); afterICard(); }); } else afterICard(); } else afterICard(); function afterICard() { if (node.hasFeature(jsCardDAV_UserAddressBooks)) { var meCardProp = "{http://calendarserver.org/ns/}me-card"; if (requestedProperties[meCardProp]) { self.handler.getProperties(node.getOwner(), ["{http://ajax.org/2005/aml}vcard-url"], function(err, props) { if (err) return e.next(err); if (props["{http://ajax.org/2005/aml}vcard-url"]) { returnedProperties["200"][meCardProp] = jsDAV_Property_Href.new( props["{http://ajax.org/2005/aml}vcard-url"] ); delete requestedProperties[meCardProp]; } e.next(); }); } else e.next(); } else e.next(); } }, /** * This event is triggered when a PROPPATCH method is executed * * @param {Array} mutations * @param {Array} result * @param DAV\INode node * @return bool */ updateProperties: function(e, mutations, result, node) { if (!node.hasFeature(jsCardDAV_UserAddressBooks)) return e.next(); var meCard = "{http://calendarserver.org/ns/}me-card"; // The only property we care about if (!mutations[meCard]) return e.next(); var value = mutations[meCard]; delete mutations[meCard]; if (value.hasFeature(jsDAV_Property_iHref)) { value = this.handler.calculateUri(value.getHref()); } else if (!value) { result["400"][meCard] = null; return e.stop(); } this.server.updateProperties(node.getOwner(), {"{http://ajax.org/2005/aml}vcard-url": value}, function(err, innerResult) { if (err) return e.next(err); var closureResult = false; var props; for (var status in innerResult) { props = innerResult[status]; if (props["{http://ajax.org/2005/aml}vcard-url"]) { result[status][meCard] = null; status = parseInt(status); closureResult = (status >= 200 && status < 300); } } if (!closureResult) return e.stop(); e.next(); }); }, /** * This functions handles REPORT requests specific to CardDAV * * @param {String} reportName * @param DOMNode dom * @return bool */ report: function(e, reportName, dom) { switch(reportName) { case "{" + this.NS_CARDDAV + "}addressbook-multiget" : this.addressbookMultiGetReport(e, dom); break; case "{" + this.NS_CARDDAV + "}addressbook-query" : this.addressBookQueryReport(e, dom); break; default : return e.next(); } }, /** * This function handles the addressbook-multiget REPORT. * * This report is used by the client to fetch the content of a series * of urls. Effectively avoiding a lot of redundant requests. * * @param DOMNode dom * @return void */ addressbookMultiGetReport: function(e, dom) { var properties = Object.keys(Xml.parseProperties(dom)); var hrefElems = dom.getElementsByTagNameNS("urn:DAV", "href"); var propertyList = {}; var self = this; Async.list(hrefElems) .each(function(elem, next) { var uri = self.handler.calculateUri(elem.firstChild.nodeValue); //propertyList[uri] self.handler.getPropertiesForPath(uri, properties, 0, function(err, props) { if (err) return next(err); Util.extend(propertyList, props); next(); }); }) .end(function(err) { if (err) return e.next(err); var prefer = self.handler.getHTTPPrefer(); e.stop(); self.handler.httpResponse.writeHead(207, { "content-type": "application/xml; charset=utf-8", "vary": "Brief,Prefer" }); self.handler.httpResponse.end(self.handler.generateMultiStatus(propertyList, prefer["return-minimal"])); }); }, /** * This method is triggered before a file gets updated with new content. * * This plugin uses this method to ensure that Card nodes receive valid * vcard data. * * @param {String} path * @param jsDAV_iFile node * @param resource data * @return void */ beforeWriteContent: function(e, path, node) { if (!node.hasFeature(jsCardDAV_iCard)) return e.next(); var self = this; this.handler.getRequestBody("utf8", null, false, function(err, data) { if (err) return e.next(err); try { self.validateVCard(data); } catch (ex) { return e.next(ex); } e.next(); }); }, /** * This method is triggered before a new file is created. * * This plugin uses this method to ensure that Card nodes receive valid * vcard data. * * @param {String} path * @param resource data * @param jsDAV_iCollection parentNode * @return void */ beforeCreateFile: function(e, path, data, enc, parentNode) { if (!parentNode.hasFeature(jsCardDAV_iAddressBook)) return e.next(); try { this.validateVCard(data); } catch (ex) { return e.next(ex); } e.next(); }, /** * Checks if the submitted iCalendar data is in fact, valid. * * An exception is thrown if it's not. * * @param resource|string data * @return void */ validateVCard: function(data) { // If it's a stream, we convert it to a string first. if (Buffer.isBuffer(data)) data = data.toString("utf8"); var vobj; try { vobj = jsVObject_Reader.read(data); } catch (ex) { throw new Exc.UnsupportedMediaType("This resource only supports valid vcard data. Parse error: " + ex.message); } if (vobj.name != "VCARD") throw new Exc.UnsupportedMediaType("This collection can only support vcard objects."); if (!vobj.UID) throw new Exc.BadRequest("Every vcard must have a UID."); }, /** * This function handles the addressbook-query REPORT * * This report is used by the client to filter an addressbook based on a * complex query. * * @param DOMNode dom * @return void */ addressbookQueryReport: function(e, dom) { var query = jsCardDAV_AddressBookQueryParser.new(dom); try { query.parse(); } catch(ex) { return e.next(ex); } var depth = this.handler.getHTTPDepth(0); if (depth === 0) { this.handler.getNodeForPath(this.handler.getRequestUri(), function(err, node) { if (err) return e.next(err); afterCandidates([node]); }) } else { this.handler.server.tree.getChildren(this.handler.getRequestUri(), function(err, children) { if (err) return e.next(err); afterCandidates(children); }); } var self = this; function afterCandidates(candidateNodes) { var validNodes = []; Async.list(candidateNodes) .each(function(node, next) { if (!node.hasFeature(jsCardDAV_iCard)) return next(); node.get(function(err, blob) { if (err) return next(err); if (!self.validateFilters(blob.toString("utf8"), query.filters, query.test)) return next(); validNodes.push(node); if (query.limit && query.limit <= validNodes.length) { // We hit the maximum number of items, we can stop now. return next(Async.STOP); } next(); }); }) .end(function(err) { if (err) return e.next(err); var result = {}; Async.list(validNodes) .each(function(validNode, next) { var href = self.handler.getRequestUri(); if (depth !== 0) href = href + "/" + validNode.getName(); self.handler.getPropertiesForPath(href, query.requestedProperties, 0, function(err, props) { if (err) return next(err); Util.extend(result, props); next(); }); }) .end(function(err) { if (err) return e.next(err); e.stop(); var prefer = self.handler.getHTTPPRefer(); self.handler.httpResponse.writeHead(207, { "content-type": "application/xml; charset=utf-8", "vary": "Brief,Prefer" }); self.handler.httpResponse.end(self.handler.generateMultiStatus(result, prefer["return-minimal"])); }); }); } }, /** * Validates if a vcard makes it throught a list of filters. * * @param {String} vcardData * @param {Array} filters * @param {String} test anyof or allof (which means OR or AND) * @return bool */ validateFilters: function(vcardData, filters, test) { var vcard; try { vcard = jsVObject_Reader.read(vcardData); } catch (ex) { return false; } if (!filters) return true; var filter, isDefined, success, vProperties, results, texts; for (var i = 0, l = filters.length; i < l; ++i) { filter = filters[i]; isDefined = vcard.get(filter.name); if (filter["is-not-defined"]) { if (isDefined) success = false; else success = true; } else if ((!filter["param-filters"] && !filter["text-matches"]) || !isDefined) { // We only need to check for existence success = isDefined; } else { vProperties = vcard.select(filter.name); results = []; if (filter["param-filters"]) results.push(this.validateParamFilters(vProperties, filter["param-filters"], filter.test)); if (filter["text-matches"]) { texts = vProperties.map(function(vProperty) { return vProperty.value; }); results.push(this.validateTextMatches(texts, filter["text-matches"], filter.test)); } if (results.length === 1) { success = results[0]; } else { if (filter.test == "anyof") success = results[0] || results[1]; else success = results[0] && results[1]; } } // else // There are two conditions where we can already determine whether // or not this filter succeeds. if (test == "anyof" && success) return true; if (test == "allof" && !success) return false; } // foreach // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return test === "allof"; }, /** * Validates if a param-filter can be applied to a specific property. * * @todo currently we're only validating the first parameter of the passed * property. Any subsequence parameters with the same name are * ignored. * @param {Array} vProperties * @param {Array} filters * @param {String} test * @return bool */ validateParamFilters: function(vProperties, filters, test) { var filter, isDefined, success, j, l2, vProperty; for (var i = 0, l = filters.length; i < l; ++i) { filter = filters[i]; isDefined = false; for (j = 0, l2 = vProperties.length; j < l2; ++j) { vProperty = vProperties[j]; isDefined = !!vProperty.get(filter.name); if (isDefined) break; } if (filter["is-not-defined"]) { success = !isDefined; // If there's no text-match, we can just check for existence } else if (!filter["text-match"] || !isDefined) { success = isDefined; } else { success = false; for (j = 0, l2 = vProperties.length; j < l2; ++j) { vProperty = vProperties[j]; // If we got all the way here, we'll need to validate the // text-match filter. success = Util.textMatch(vProperty.get(filter.name).value, filter["text-match"].value, filter["text-match"]["match-type"]); if (success) break; } if (filter["text-match"]["negate-condition"]) success = !success; } // else // There are two conditions where we can already determine whether // or not this filter succeeds. if (test == "anyof" && success) return true; if (test == "allof" && !success) return false; } // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return test == "allof"; }, /** * Validates if a text-filter can be applied to a specific property. * * @param {Array} texts * @param {Array} filters * @param {String} test * @return bool */ validateTextMatches: function(texts, filters, test) { var success, filter, j, l2, haystack; for (var i = 0, l = filters.length; i < l; ++i) { filter = filters[i]; success = false; for (j = 0, l2 = texts.length; j < l2; ++j) { haystack = texts[j]; success = Util.textMatch(haystack, filter.value, filter["match-type"]); // Breaking on the first match if (success) break; } if (filter["negate-condition"]) success = !success; if (success && test == "anyof") return true; if (!success && test == "allof") return false; } // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return test == "allof"; }, /** * This event is triggered after webdav-properties have been retrieved. * * @return bool */ afterGetProperties: function(e, uri, properties) { // If the request was made using the SOGO connector, we must rewrite // the content-type property. By default jsDAV will send back // text/x-vcard; charset=utf-8, but for SOGO we must strip that last // part. if (!properties["200"]["{DAV:}getcontenttype"]) return e.next(); if (this.handler.httpRequest.headers["user-agent"].indexOf("Thunderbird") === -1) return e.next(); if (properties["200"]["{DAV:}getcontenttype"].indexOf("text/x-vcard") === 0) properties["200"]["{DAV:}getcontenttype"] = "text/x-vcard"; e.next(); }, /** * This method is used to generate HTML output for the * Sabre\DAV\Browser\Plugin. This allows us to generate an interface users * can use to create new calendars. * * @param DAV\INode node * @param {String} output * @return bool */ htmlActionsPanel: function(e, node, output) { if (!node.hasFeature(jsCardDAV_UserAddressBooks)) return e.next(); output.html = '<tr><td colspan="2"><form method="post" action="">' + '<h3>Create new address book</h3>' + '<input type="hidden" name="jsdavAction" value="mkaddressbook" />' + '<label>Name (uri):</label> <input type="text" name="name" /><br />' + '<label>Display name:</label> <input type="text" name="{DAV:}displayname" /><br />' + '<input type="submit" value="create" />' + '</form>' + '</td></tr>'; e.stop(); }, /** * This method allows us to intercept the 'mkcalendar' sabreAction. This * action enables the user to create new calendars from the browser plugin. * * @param {String} uri * @param {String} action * @param {Array} postVars * @return bool */ browserPostAction: function(e, uri, action, postVars) { if (action != "mkaddressbook") return e.next(); var resourceType = ["{DAV:}collection", "{urn:ietf:params:xml:ns:carddav}addressbook"]; var properties = {}; if (postVars["{DAV:}displayname"]) properties["{DAV:}displayname"] = postVars["{DAV:}displayname"]; this.handler.createCollection(uri + "/" + postVars.name, resourceType, properties, function(err) { if (err) return e.next(err); e.stop(); }); } });
Java
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Rule, SchematicsException, Tree, UpdateRecorder} from '@angular-devkit/schematics'; import {relative} from 'path'; import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths'; import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host'; import {migrateFile} from './util'; export default function(): Rule { return async (tree: Tree) => { const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree); const basePath = process.cwd(); const allPaths = [...buildPaths, ...testPaths]; if (!allPaths.length) { throw new SchematicsException( 'Could not find any tsconfig file. Cannot migrate to Typed Forms.'); } for (const tsconfigPath of allPaths) { runTypedFormsMigration(tree, tsconfigPath, basePath); } }; } function runTypedFormsMigration(tree: Tree, tsconfigPath: string, basePath: string) { const {program} = createMigrationProgram(tree, tsconfigPath, basePath); const typeChecker = program.getTypeChecker(); const sourceFiles = program.getSourceFiles().filter(sourceFile => canMigrateFile(basePath, sourceFile, program)); for (const sourceFile of sourceFiles) { let update: UpdateRecorder|null = null; const rewriter = (startPos: number, origLength: number, text: string) => { if (update === null) { // Lazily initialize update, because most files will not require migration. update = tree.beginUpdate(relative(basePath, sourceFile.fileName)); } update.remove(startPos, origLength); update.insertLeft(startPos, text); }; migrateFile(sourceFile, typeChecker, rewriter); if (update !== null) { tree.commitUpdate(update); } } }
Java
'@fixture click'; '@page http://example.com'; '@test'['Take a screenshot'] = { '1.Click on non-existing element': function () { act.screenshot(); }, }; '@test'['Screenshot on test code error'] = { '1.Click on non-existing element': function () { throw new Error('STOP'); }, };
Java
///////////////////////////////// // Rich Newman // http://richnewman.wordpress.com/about/code-listings-and-diagrams/hslcolor-class/ // using System; using System.Drawing; namespace AldursLab.Essentials.Extensions.DotNet.Drawing { /// <summary> /// Color with Hue/Saturation/Luminescense representation. /// </summary> public class HslColor { // Private data members below are on scale 0-1 // They are scaled for use externally based on scale private double hue = 1.0; private double saturation = 1.0; private double luminosity = 1.0; private const double scale = 240.0; public double Hue { get { return hue * scale; } set { hue = CheckRange(value / scale); } } public double Saturation { get { return saturation * scale; } set { saturation = CheckRange(value / scale); } } public double Luminosity { get { return luminosity * scale; } set { luminosity = CheckRange(value / scale); } } private double CheckRange(double value) { if (value < 0.0) value = 0.0; else if (value > 1.0) value = 1.0; return value; } public override string ToString() { return String.Format("H: {0:#0.##} S: {1:#0.##} L: {2:#0.##}", Hue, Saturation, Luminosity); } public string ToRGBString() { Color color = (Color)this; return String.Format("R: {0:#0.##} G: {1:#0.##} B: {2:#0.##}", color.R, color.G, color.B); } #region Casts to/from System.Drawing.Color public static implicit operator Color(HslColor hslColor) { double r = 0, g = 0, b = 0; if (hslColor.luminosity != 0) { if (hslColor.saturation == 0) r = g = b = hslColor.luminosity; else { double temp2 = GetTemp2(hslColor); double temp1 = 2.0 * hslColor.luminosity - temp2; r = GetColorComponent(temp1, temp2, hslColor.hue + 1.0 / 3.0); g = GetColorComponent(temp1, temp2, hslColor.hue); b = GetColorComponent(temp1, temp2, hslColor.hue - 1.0 / 3.0); } } return Color.FromArgb((int)(255 * r), (int)(255 * g), (int)(255 * b)); } private static double GetColorComponent(double temp1, double temp2, double temp3) { temp3 = MoveIntoRange(temp3); if (temp3 < 1.0 / 6.0) return temp1 + (temp2 - temp1) * 6.0 * temp3; else if (temp3 < 0.5) return temp2; else if (temp3 < 2.0 / 3.0) return temp1 + ((temp2 - temp1) * ((2.0 / 3.0) - temp3) * 6.0); else return temp1; } private static double MoveIntoRange(double temp3) { if (temp3 < 0.0) temp3 += 1.0; else if (temp3 > 1.0) temp3 -= 1.0; return temp3; } private static double GetTemp2(HslColor hslColor) { double temp2; if (hslColor.luminosity < 0.5) //<=?? temp2 = hslColor.luminosity * (1.0 + hslColor.saturation); else temp2 = hslColor.luminosity + hslColor.saturation - (hslColor.luminosity * hslColor.saturation); return temp2; } public static implicit operator HslColor(Color color) { HslColor hslColor = new HslColor(); hslColor.hue = color.GetHue() / 360.0; // we store hue as 0-1 as opposed to 0-360 hslColor.luminosity = color.GetBrightness(); hslColor.saturation = color.GetSaturation(); return hslColor; } #endregion public void SetRGB(int red, int green, int blue) { HslColor hslColor = (HslColor)Color.FromArgb(red, green, blue); this.hue = hslColor.hue; this.saturation = hslColor.saturation; this.luminosity = hslColor.luminosity; } public HslColor() { } public HslColor(Color color) { SetRGB(color.R, color.G, color.B); } public HslColor(int red, int green, int blue) { SetRGB(red, green, blue); } public HslColor(double hue, double saturation, double luminosity) { this.Hue = hue; this.Saturation = saturation; this.Luminosity = luminosity; } } }
Java
# RegionalSettings.Properties WorkDaysSpecified **Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md) **Assembly:** OfficeDevPnP.Core.dll ## Syntax ```C# public bool WorkDaysSpecified { get; set; } ``` ### Property Value Type: System.Boolean ## See also - [RegionalSettings](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.RegionalSettings.md) - [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)
Java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Sql.Models { public partial class TransparentDataEncryptionActivityListResult { internal static TransparentDataEncryptionActivityListResult DeserializeTransparentDataEncryptionActivityListResult(JsonElement element) { IReadOnlyList<TransparentDataEncryptionActivity> value = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value")) { List<TransparentDataEncryptionActivity> array = new List<TransparentDataEncryptionActivity>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(TransparentDataEncryptionActivity.DeserializeTransparentDataEncryptionActivity(item)); } value = array; continue; } } return new TransparentDataEncryptionActivityListResult(value); } } }
Java
using System; using Marten.Services; using Marten.Testing.Documents; using Marten.Testing.Harness; using Xunit; namespace Marten.Testing.CoreFunctionality { public class foreign_key_persisting_Tests: IntegrationContext { [Fact] public void persist_and_overwrite_foreign_key() { StoreOptions(_ => { _.Schema.For<Issue>().ForeignKey<User>(x => x.AssigneeId); }); var issue = new Issue(); var user = new User(); using (var session = theStore.OpenSession()) { session.Store(user); session.Store(issue); session.SaveChanges(); } issue.AssigneeId = user.Id; using (var session = theStore.OpenSession()) { session.Store(issue); session.SaveChanges(); } issue.AssigneeId = null; using (var session = theStore.OpenSession()) { session.Store(issue); session.SaveChanges(); } } [Fact] public void throws_exception_if_trying_to_delete_referenced_user() { StoreOptions(_ => { _.Schema.For<Issue>() .ForeignKey<User>(x => x.AssigneeId); }); var issue = new Issue(); var user = new User(); issue.AssigneeId = user.Id; using (var session = theStore.OpenSession()) { session.Store(user); session.Store(issue); session.SaveChanges(); } Exception<Marten.Exceptions.MartenCommandException>.ShouldBeThrownBy(() => { using (var session = theStore.OpenSession()) { session.Delete(user); session.SaveChanges(); } }); } [Fact] public void persist_without_referenced_user() { StoreOptions(_ => { _.Schema.For<Issue>() .ForeignKey<User>(x => x.AssigneeId); }); using (var session = theStore.OpenSession()) { session.Store(new Issue()); session.SaveChanges(); } } [Fact] public void order_inserts() { StoreOptions(_ => { _.Schema.For<Issue>() .ForeignKey<User>(x => x.AssigneeId); }); var issue = new Issue(); var user = new User(); issue.AssigneeId = user.Id; using (var session = theStore.OpenSession()) { session.Store(issue); session.Store(user); session.SaveChanges(); } } [Fact] public void throws_exception_on_cyclic_dependency() { Exception<InvalidOperationException>.ShouldBeThrownBy(() => { StoreOptions(_ => { _.Schema.For<Node1>().ForeignKey<Node3>(x => x.Link); _.Schema.For<Node2>().ForeignKey<Node1>(x => x.Link); _.Schema.For<Node3>().ForeignKey<Node2>(x => x.Link); }); }).Message.ShouldContain("Cyclic"); } public class Node1 { public Guid Id { get; set; } public Guid Link { get; set; } } public class Node2 { public Guid Id { get; set; } public Guid Link { get; set; } } public class Node3 { public Guid Id { get; set; } public Guid Link { get; set; } } public foreign_key_persisting_Tests(DefaultStoreFixture fixture) : base(fixture) { DocumentTracking = DocumentTracking.IdentityOnly; } } }
Java
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {global} from '../../src/util/global'; // Not yet available in TypeScript: https://github.com/Microsoft/TypeScript/pull/29332 declare var globalThis: any /** TODO #9100 */; { describe('global', () => { it('should be global this value', () => { const _global = new Function('return this')(); expect(global).toBe(_global); }); if (typeof globalThis !== 'undefined') { it('should use globalThis as global reference', () => { expect(global).toBe(globalThis); }); } }); }
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列属性集 // 控制。更改这些属性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Dos.Tools")] [assembly: AssemblyDescription("ITdos.com")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ITdos.com")] [assembly: AssemblyProduct("Dos.Tools")] [assembly: AssemblyCopyright("Copyright © 2009-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 属性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("014d6eaa-6f9d-4b8a-a4dc-9b992cd94cfa")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.6.0")] [assembly: AssemblyFileVersion("2.0.6.0")]
Java
#include "Halide.h" #include <tiramisu/utils.h> #include <cstdlib> #include <iostream> #include "wrapper_test_71.h" #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } // extern "C" #endif // We assume that the increment is 1. void reference_saxpy(int N1, float alpha, float *A, float *B) { for (int i=0; i<N1; i++) B[i] = alpha*A[i] + B[i]; } int main(int, char **) { Halide::Buffer<float> a(1, "a"); Halide::Buffer<float> x(SIZE, "x"); Halide::Buffer<float> y_ref(SIZE, "y_ref"); Halide::Buffer<float> y(SIZE, "y"); init_buffer(x, (float)1); init_buffer(y, (float)1); init_buffer(y_ref, (float)1); init_buffer(a, (float)1); reference_saxpy(SIZE, 1, x.data(), y_ref.data()); tiramisu_generated_code(a.raw_buffer(), x.raw_buffer(), y.raw_buffer()); compare_buffers("test_" + std::string(TEST_NUMBER_STR) + "_" + std::string(TEST_NAME_STR), y, y_ref); return 0; }
Java
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 0700 074F END
Java
--- date: "2016-12-01T16:00:00+02:00" title: "从源代码安装" slug: "install-from-source" weight: 10 toc: false draft: false menu: sidebar: parent: "installation" name: "从源代码安装" weight: 30 identifier: "install-from-source" --- # 从源代码安装 首先你需要安装Golang,关于Golang的安装,参见官方文档 [install instructions](https://golang.org/doc/install)。 ## 下载 你需要获取Gitea的源码,最方便的方式是使用 go 命令。执行以下命令: ``` go get -d -u code.gitea.io/gitea cd $GOPATH/src/code.gitea.io/gitea ``` 然后你可以选择编译和安装的版本,当前你有多个选择。如果你想编译 `master` 版本,你可以直接跳到 [编译](#build) 部分,这是我们的开发分支,虽然也很稳定但不建议您在正式产品中使用。 如果你想编译最新稳定分支,你可以执行以下命令签出源码: ``` git branch -a git checkout v{{< version >}} ``` 最后,你也可以直接使用标签版本如 `v{{< version >}}`。你可以执行以下命令列出可用的版本并选择某个版本签出: ``` git tag -l git checkout v{{< version >}} ``` ## 编译 要从源代码进行编译,以下依赖程序必须事先安装好: - `go` {{< min-go-version >}} 或以上版本, 详见 [here](https://golang.org/dl/) - `node` {{< min-node-version >}} 或以上版本,并且安装 `npm`, 详见 [here](https://nodejs.org/en/download/) - `make`, 详见 <a href='{{< relref "make.zh-cn.md" >}}'>这里</a> 各种可用的 [make 任务](https://github.com/go-gitea/gitea/blob/master/Makefile) 可以用来使编译过程更方便。 按照您的编译需求,以下 tags 可以使用: * `bindata`: 这个编译选项将会把运行Gitea所需的所有外部资源都打包到可执行文件中,这样部署将非常简单因为除了可执行程序将不再需要任何其他文件。 * `sqlite sqlite_unlock_notify`: 这个编译选项将启用SQLite3数据库的支持,建议只在少数人使用时使用这个模式。 * `pam`: 这个编译选项将会启用 PAM (Linux Pluggable Authentication Modules) 认证,如果你使用这一认证模式的话需要开启这个选项。 使用 bindata 可以打包资源文件到二进制可以使开发和测试更容易,你可以根据自己的需求决定是否打包资源文件。 要包含资源文件,请使用 `bindata` tag: ```bash TAGS="bindata" make build ``` 默认的发布版本中的编译选项是: `TAGS="bindata sqlite sqlite_unlock_notify"`。以下为推荐的编译方式: ```bash TAGS="bindata sqlite sqlite_unlock_notify" make build ``` ## 测试 在执行了以上步骤之后,你将会获得 `gitea` 的二进制文件,在你复制到部署的机器之前可以先测试一下。在命令行执行完后,你可以 `Ctrl + C` 关掉程序。 ``` ./gitea web ``` ## 需要帮助? 如果从本页中没有找到你需要的内容,请访问 [帮助页面]({{< relref "seek-help.zh-cn.md" >}})
Java
// implementation for sturm_equation.h #include <cmath> #include <algorithm> #include <list> #include <utils/array1d.h> #include <algebra/vector.h> #include <algebra/sparse_matrix.h> #include <numerics/eigenvalues.h> #include <numerics/gauss_data.h> namespace WaveletTL { template <class WBASIS> SturmEquation<WBASIS>::SturmEquation(const SimpleSturmBVP& bvp, const bool precompute_f) : bvp_(bvp), basis_(bvp.bc_left(), bvp.bc_right()), normA(0.0), normAinv(0.0) { #ifdef ENERGY // compute_diagonal(); #endif if (precompute_f) precompute_rhs(); //const int jmax = 12; //basis_.set_jmax(jmax); } template <class WBASIS> SturmEquation<WBASIS>::SturmEquation(const SimpleSturmBVP& bvp, const WBASIS& basis, const bool precompute_f) : bvp_(bvp), basis_(basis), normA(0.0), normAinv(0.0) { #ifdef ENERGY compute_diagonal(); #endif if (precompute_f) precompute_rhs(); //const int jmax = 12; //basis_.set_jmax(jmax); } template <class WBASIS> void SturmEquation<WBASIS>::precompute_rhs() const { typedef typename WaveletBasis::Index Index; cout << "precompute rhs.." << endl; // precompute the right-hand side on a fine level InfiniteVector<double,Index> fhelp; InfiniteVector<double,int> fhelp_int; #ifdef FRAME // cout << basis_.degrees_of_freedom() << endl; for (int i=0; i<basis_.degrees_of_freedom();i++) { // cout << "hallo" << endl; // cout << *(basis_.get_quarklet(i)) << endl; const double coeff = f(*(basis_.get_quarklet(i)))/D(*(basis_.get_quarklet(i))); fhelp.set_coefficient(*(basis_.get_quarklet(i)), coeff); fhelp_int.set_coefficient(i, coeff); // cout << *(basis_.get_quarklet(i)) << endl; } // cout << "bin hier1" << endl; #else for (int i=0; i<basis_.degrees_of_freedom();i++) { // cout << "bin hier: " << i << endl; // cout << D(*(basis_.get_wavelet(i))) << endl; // cout << *(basis_.get_wavelet(i)) << endl; const double coeff = f(*(basis_.get_wavelet(i)))/D(*(basis_.get_wavelet(i))); // cout << f(*(basis_.get_wavelet(i))) << endl; // cout << coeff << endl; fhelp.set_coefficient(*(basis_.get_wavelet(i)), coeff); fhelp_int.set_coefficient(i, coeff); // cout << *(basis_.get_wavelet(i)) << endl; } // const int j0 = basis().j0(); // for (Index lambda(basis_.first_generator(j0));;++lambda) // { // const double coeff = f(lambda)/D(lambda); // if (fabs(coeff)>1e-15) // fhelp.set_coefficient(lambda, coeff); // fhelp_int.set_coefficient(i, coeff); // if (lambda == basis_.last_wavelet(jmax)) // break; // // // } #endif fnorm_sqr = l2_norm_sqr(fhelp); // sort the coefficients into fcoeffs fcoeffs.resize(fhelp.size()); fcoeffs_int.resize(fhelp_int.size()); unsigned int id(0), id2(0); for (typename InfiniteVector<double,Index>::const_iterator it(fhelp.begin()), itend(fhelp.end()); it != itend; ++it, ++id) fcoeffs[id] = std::pair<Index,double>(it.index(), *it); sort(fcoeffs.begin(), fcoeffs.end(), typename InfiniteVector<double,Index>::decreasing_order()); for (typename InfiniteVector<double,int>::const_iterator it(fhelp_int.begin()), itend(fhelp_int.end()); it != itend; ++it, ++id2) fcoeffs_int[id2] = std::pair<int,double>(it.index(), *it); sort(fcoeffs_int.begin(), fcoeffs_int.end(), typename InfiniteVector<double,int>::decreasing_order()); rhs_precomputed = true; cout << "end precompute rhs.." << endl; // cout << fhelp << endl; // cout << fcoeffs << endl; } template <class WBASIS> inline double SturmEquation<WBASIS>::D(const typename WBASIS::Index& lambda) const { #ifdef FRAME #ifdef DYADIC return mypow((1<<lambda.j())*mypow(1+lambda.p(),6),operator_order())*mypow(1+lambda.p(),2); //2^j*(p+1)^6, falls operator_order()=1 (\delta=4) // return 1<<(lambda.j()*(int) operator_order()); #endif #ifdef TRIVIAL return 1; #endif #ifdef ENERGY return stiff_diagonal[lambda.number()]*(lambda.p()+1); #endif #endif #ifdef BASIS #ifdef DYADIC return 1<<(lambda.j()*(int) operator_order()); // return pow(ldexp(1.0, lambda.j()),operator_order()); #else #ifdef TRIVIAL return 1; #else #ifdef ENERGY // return sqrt(a(lambda, lambda)); return stiff_diagonal[lambda.number()]; #else return sqrt(a(lambda, lambda)); #endif #endif #endif #else return 1; #endif // return 1; // return lambda.e() == 0 ? 1.0 : ldexp(1.0, lambda.j()); // do not scale the generators // return lambda.e() == 0 ? 1.0 : sqrt(a(lambda, lambda)); // do not scale the generators } template <class WBASIS> inline double SturmEquation<WBASIS>::a(const typename WBASIS::Index& lambda, const typename WBASIS::Index& nu) const { return a(lambda, nu, 2*WBASIS::primal_polynomial_degree()); } template <class WBASIS> double SturmEquation<WBASIS>::a(const typename WBASIS::Index& lambda, const typename WBASIS::Index& nu, const unsigned int p) const { // a(u,v) = \int_0^1 [p(t)u'(t)v'(t)+q(t)u(t)v(t)] dt double r = 0; // Remark: There are of course many possibilities to evaluate // a(u,v) numerically. // In this implementation, we rely on the fact that the primal functions in // WBASIS are splines with respect to a dyadic subgrid. // We can then apply an appropriate composite quadrature rule. // In the scope of WBASIS, the routines intersect_supports() and evaluate() // must exist, which is the case for DSBasis<d,dT>. // First we compute the support intersection of \psi_\lambda and \psi_\nu: typedef typename WBASIS::Support Support; Support supp; if (intersect_supports(basis_, lambda, nu, supp)) { // Set up Gauss points and weights for a composite quadrature formula: // (TODO: maybe use an instance of MathTL::QuadratureRule instead of computing // the Gauss points and weights) #ifdef FRAME const unsigned int N_Gauss = std::min((unsigned int)10,(p+1)/2+ (lambda.p()+nu.p()+1)/2); // const unsigned int N_Gauss = 10; // const unsigned int N_Gauss = (p+1)/2; #else const unsigned int N_Gauss = (p+1)/2; #endif const double h = ldexp(1.0, -supp.j); Array1D<double> gauss_points (N_Gauss*(supp.k2-supp.k1)), func1values, func2values, der1values, der2values; for (int patch = supp.k1, id = 0; patch < supp.k2; patch++) // refers to 2^{-j}[patch,patch+1] for (unsigned int n = 0; n < N_Gauss; n++, id++) gauss_points[id] = h*(2*patch+1+GaussPoints[N_Gauss-1][n])/2.; // - compute point values of the integrands evaluate(basis_, lambda, gauss_points, func1values, der1values); evaluate(basis_, nu, gauss_points, func2values, der2values); // if((lambda.number()==19 && nu.number()==19) || (lambda.number()==26 && nu.number()==26)){ // cout << lambda << endl; // cout << gauss_points << endl; // cout << func1values << endl; // cout << func2values << endl; // } // - add all integral shares for (int patch = supp.k1, id = 0; patch < supp.k2; patch++) for (unsigned int n = 0; n < N_Gauss; n++, id++) { const double t = gauss_points[id]; const double gauss_weight = GaussWeights[N_Gauss-1][n] * h; const double pt = bvp_.p(t); if (pt != 0) r += pt * der1values[id] * der2values[id] * gauss_weight; const double qt = bvp_.q(t); if (qt != 0) r += qt * func1values[id] * func2values[id] * gauss_weight; } } return r; } template <class WBASIS> double SturmEquation<WBASIS>::norm_A() const { if (normA == 0.0) { typedef typename WaveletBasis::Index Index; std::set<Index> Lambda; const int j0 = basis().j0(); const int jmax = j0+3; #ifdef FRAME const int pmax = std::min(basis().get_pmax_(),2); //const int pmax = 0; int p = 0; for (Index lambda = basis().first_generator(j0,0);;) { Lambda.insert(lambda); if (lambda == basis().last_wavelet(jmax,pmax)) break; //if (i==7) break; if (lambda == basis().last_wavelet(jmax,p)){ ++p; lambda = basis().first_generator(j0,p); } else ++lambda; } #else for (Index lambda = first_generator(&basis(), j0);; ++lambda) { Lambda.insert(lambda); if (lambda == last_wavelet(&basis(), jmax)) break; } #endif SparseMatrix<double> A_Lambda; setup_stiffness_matrix(*this, Lambda, A_Lambda); #if 1 double help; unsigned int iterations; LanczosIteration(A_Lambda, 1e-6, help, normA, 200, iterations); normAinv = 1./help; #else Vector<double> xk(Lambda.size(), false); xk = 1; unsigned int iterations; normA = PowerIteration(A_Lambda, xk, 1e-6, 100, iterations); #endif } return normA; } template <class WBASIS> double SturmEquation<WBASIS>::norm_Ainv() const { if (normAinv == 0.0) { typedef typename WaveletBasis::Index Index; std::set<Index> Lambda; const int j0 = basis().j0(); const int jmax = j0+3; #ifdef FRAME const int pmax = std::min(basis().get_pmax_(),2); //const int pmax = 0; int p = 0; for (Index lambda = basis().first_generator(j0,0);;) { Lambda.insert(lambda); if (lambda == basis().last_wavelet(jmax,pmax)) break; //if (i==7) break; if (lambda == basis().last_wavelet(jmax,p)){ ++p; lambda = basis().first_generator(j0,p); } else ++lambda; } #else for (Index lambda = first_generator(&basis(), j0);; ++lambda) { Lambda.insert(lambda); if (lambda == last_wavelet(&basis(), jmax)) break; } #endif SparseMatrix<double> A_Lambda; setup_stiffness_matrix(*this, Lambda, A_Lambda); #if 1 double help; unsigned int iterations; LanczosIteration(A_Lambda, 1e-6, help, normA, 200, iterations); normAinv = 1./help; #else Vector<double> xk(Lambda.size(), false); xk = 1; unsigned int iterations; normAinv = InversePowerIteration(A_Lambda, xk, 1e-6, 200, iterations); #endif } return normAinv; } template <class WBASIS> double SturmEquation<WBASIS>::f(const typename WBASIS::Index& lambda) const { // f(v) = \int_0^1 g(t)v(t) dt // cout << "bin in f" << endl; double r = 0; const int j = lambda.j()+lambda.e(); int k1, k2; support(basis_, lambda, k1, k2); // Set up Gauss points and weights for a composite quadrature formula: const unsigned int N_Gauss = 7; //perhaps we need +lambda.p()/2 @PHK const double h = ldexp(1.0, -j); Array1D<double> gauss_points (N_Gauss*(k2-k1)), vvalues; for (int patch = k1; patch < k2; patch++) // refers to 2^{-j}[patch,patch+1] for (unsigned int n = 0; n < N_Gauss; n++) gauss_points[(patch-k1)*N_Gauss+n] = h*(2*patch+1+GaussPoints[N_Gauss-1][n])/2; // - compute point values of the integrand evaluate(basis_, 0, lambda, gauss_points, vvalues); // cout << "bin immer noch in f" << endl; // - add all integral shares for (int patch = k1, id = 0; patch < k2; patch++) for (unsigned int n = 0; n < N_Gauss; n++, id++) { const double t = gauss_points[id]; const double gauss_weight = GaussWeights[N_Gauss-1][n] * h; const double gt = bvp_.g(t); if (gt != 0) r += gt * vvalues[id] * gauss_weight; } #ifdef DELTADIS // double tmp = 1; // Point<1> p1; // p1[0] = 0.5; // Point<1> p2; // chart->map_point_inv(p1,p2); // tmp = evaluate(basis_, 0, // typename WBASIS::Index(lambda.j(), // lambda.e()[0], // lambda.k()[0], // basis_), // p2[0]); // tmp /= chart->Gram_factor(p2); // // // return 4.0*tmp + r; #ifdef NONZERONEUMANN return r + 4*basis_.evaluate(0, lambda, 0.5)+3*M_PI*(basis_.evaluate(0, lambda, 1)+basis_.evaluate(0, lambda, 0)); #else return r+ 4*basis_.evaluate(0, lambda, 0.5); #endif #else return r; #endif } template <class WBASIS> inline void SturmEquation<WBASIS>::RHS(const double eta, InfiniteVector<double, typename WBASIS::Index>& coeffs) const { if (!rhs_precomputed) precompute_rhs(); coeffs.clear(); double coarsenorm(0); double bound(fnorm_sqr - eta*eta); typedef typename WBASIS::Index Index; typename Array1D<std::pair<Index, double> >::const_iterator it(fcoeffs.begin()); do { coarsenorm += it->second * it->second; coeffs.set_coefficient(it->first, it->second); ++it; } while (it != fcoeffs.end() && coarsenorm < bound); } template <class WBASIS> inline void SturmEquation<WBASIS>::RHS(const double eta, InfiniteVector<double,int>& coeffs) const { if (!rhs_precomputed) precompute_rhs(); coeffs.clear(); double coarsenorm(0); double bound(fnorm_sqr - eta*eta); typename Array1D<std::pair<int, double> >::const_iterator it(fcoeffs_int.begin()); do { coarsenorm += it->second * it->second; coeffs.set_coefficient(it->first, it->second); ++it; } while (it != fcoeffs_int.end() && coarsenorm < bound); } template <class WBASIS> void SturmEquation<WBASIS>::compute_diagonal() { cout << "SturmEquation(): precompute diagonal of stiffness matrix..." << endl; SparseMatrix<double> diag(1,basis_.degrees_of_freedom()); char filename[50]; char matrixname[50]; #ifdef ONE_D int d = WBASIS::primal_polynomial_degree(); int dT = WBASIS::primal_vanishing_moments(); #else #ifdef TWO_D int d = WBASIS::primal_polynomial_degree(); int dT = WBASIS::primal_vanishing_moments(); #endif #endif // prepare filenames for 1D and 2D case #ifdef ONE_D sprintf(filename, "%s%d%s%d", "stiff_diagonal_poisson_interval_lap07_d", d, "_dT", dT); sprintf(matrixname, "%s%d%s%d", "stiff_diagonal_poisson_1D_lap07_d", d, "_dT", dT); #endif #ifdef TWO_D sprintf(filename, "%s%d%s%d", "stiff_diagonal_poisson_lshaped_lap1_d", d, "_dT", dT); sprintf(matrixname, "%s%d%s%d", "stiff_diagonal_poisson_2D_lap1_d", d, "_dT", dT); #endif #ifndef PRECOMP_DIAG std::list<Vector<double>::size_type> indices; std::list<double> entries; #endif #ifdef PRECOMP_DIAG cout << "reading in diagonal of unpreconditioned stiffness matrix from file " << filename << "..." << endl; diag.matlab_input(filename); cout << "...ready" << endl; #endif stiff_diagonal.resize(basis_.degrees_of_freedom()); for (int i = 0; i < basis_.degrees_of_freedom(); i++) { #ifdef PRECOMP_DIAG stiff_diagonal[i] = diag.get_entry(0,i); #endif #ifndef PRECOMP_DIAG #ifdef FRAME stiff_diagonal[i] = sqrt(a(*(basis_.get_quarklet(i)),*(basis_.get_quarklet(i)))); #endif #ifdef BASIS stiff_diagonal[i] = sqrt(a(*(basis_.get_wavelet(i)),*(basis_.get_wavelet(i)))); #endif indices.push_back(i); entries.push_back(stiff_diagonal[i]); #endif //cout << stiff_diagonal[i] << " " << *(basis_->get_wavelet(i)) << endl; } #ifndef PRECOMP_DIAG diag.set_row(0,indices, entries); diag.matlab_output(filename, matrixname, 1); #endif cout << "... done, diagonal of stiffness matrix computed" << endl; } }
Java
module NetSuite module Records class CustomerSubscriptionsList < Support::Sublist include Namespaces::ListRel sublist :subscriptions, CustomerSubscription end end end
Java
# ClientSidePage.Properties PromoteAsNewsArticleSpecified **Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.md) **Assembly:** OfficeDevPnP.Core.dll ## Syntax ```C# public bool PromoteAsNewsArticleSpecified { get; set; } ``` ### Property Value Type: System.Boolean ## See also - [ClientSidePage](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.ClientSidePage.md) - [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.md)
Java
class Downvote < ActiveRecord::Base validates :post, presence: true validates :user, presence: true belongs_to :user, counter_cache: true belongs_to :post end
Java
<?php /* * This file is part of the ONGR package. * * (c) NFQ Technologies UAB <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ONGR\ElasticsearchBundle\Serializer\Normalizer; use Symfony\Component\Serializer\Normalizer\CustomNormalizer; /** * Normalizer used with referenced normalized objects. */ class CustomReferencedNormalizer extends CustomNormalizer { /** * @var array */ private $references = []; /** * {@inheritdoc} */ public function normalize($object, $format = null, array $context = []) { $object->setReferences($this->references); $data = parent::normalize($object, $format, $context); $this->references = array_merge($this->references, $object->getReferences()); return $data; } /** * {@inheritdoc} */ public function supportsNormalization($data, $format = null) { return $data instanceof AbstractNormalizable; } }
Java
--- title: تفکری فراتر date: 22/02/2019 --- دام های شیطان، صفحات ۵١۸-۵۳٠، از کتاب جدال عظیم ، نوشته الن جی وایت را مطالعه کنید. هدف باب ۱۲ مکاشفه یوحنا پیش از هر چیز این است که اولاً به قوم خدا بگوید که رویدادهای آخر زمان بخشی از نبرد بزرگ میان مسیح و شیطان است. کتاب به ایشان درباره آنچه امروزه با آن مواجه هستند و قرار است به گونهای حتی جدیتردر آینده با آن روبرو شوند - یک دشمن با تجربه و خشمگین - هشدار میدهد. پولس در مورد فعالیت آخر زمان مظهر شرارت به ما هشدار میدهد ... با انواع آیات و نشانهها و معجزات فریبنده و هر نوع شرارتی که برای محکومین به هلاکت فریبنده است همراه خواهد بود، چون آنها عشق به حقیقت را که میتواند آنان را نجات بخشد قبول نکردند (دوم تسالونیکیان باب ۲ آیات ۹ و ۱۰). مکاشفه یوحنا ما را برمیانگیزد که آینده را جدی بگیریم و وابستگیمان به خدا را اولویت خود سازیم. از سوی دیگر، مکاشفه یوحنا به ما اطمینان میدهد که اگر چه شیطان دشمنی قوی و باتجربه است، ولی به اندازه کافی برای غلبه بر مسیح قدرتمند نیست (مکاشه یوحنا باب ۱۲ آیه ۸ را ببینید). امید برای قوم خدا تنها میتواند در کسی یافت شود که در گذشته فاتحانه شیطان و نیروهای شریر او را شکست داد. و او وعده داده است همیشه، حتی تا پایان زمان، با پیروان وفادار خود باشد (متی باب ۲۸ آیه ۲۰). **سوالاتی برای بحث ** `۱- ما ادونتیستهای روز هفتم خود را دارای ویژگیهای بازماندگان آخر زمان میبینیم. چه امتیازی! همچنین چه مسئولیتی. (لوقا باب ۱۲ آیه ۴۸ را ببینید.) چرا با این وجود، ما باید مراقب باشیم و فکر نکنیم که این نقش، نجات شخصی ما را تضمین میکند؟` `۲- ما بطور کلی، خیلی زیاد در مورد قدرت شیطان سخن میگوییم. این درست است که شیطان موجود قدرتمندی میباشد؛ اما من از خدا ممنونم برای نجات دهندهای توانا که شیطان را از آسمان بیرون راند. ما درباره دشمن خود صحبت میکنیم، درباره او دعا میکنیم،به او فکر میکنیم؛ و او در تصورات ما بزرگتر و بزرگتر میشود. اکنون چرا در مورد عیسی سخن نگوییم؟چرا در مورد قدرت و محبت وی نگوییم؟ شیطان از اینکه ما قدرتش را بزرگ جلوه دهیم، خشنود میشود. عیسی را در قلب خود نگه دارید، در مورد او بیاندیشید و با متشبه شدن به تصویر وی تغییر خواهید یافت. - الن جی. وایت،Ellen G. White, The Advent Review and Sabbath Herald, March 19, 1889.` `... مسیحیان به چه روشهایی قدرت شیطان را بزرگ جلوه میدهند؟ از سوی دیگر، در انکار نمودن نه تنها حقیقت قدرت شیطان بلکه واقعیت وجودش نیز چه خطراتی وجود دارد؟`
Java
<?php namespace PuphpetBundle\Twig; use RandomLib; class BaseExtension extends \Twig_Extension { /** @var \RandomLib\Factory */ private $randomLib; public function __construct(RandomLib\Factory $randomLib) { $this->randomLib = $randomLib; } public function getFunctions() { return [ new \Twig_SimpleFunction('mt_rand', [$this, 'mt_rand']), new \Twig_SimpleFunction('uniqid', [$this, 'uniqid']), new \Twig_SimpleFunction('merge_unique', [$this, 'mergeUnique']), new \Twig_SimpleFunction('add_available', [$this, 'addAvailable']), new \Twig_SimpleFunction('formValue', [$this, 'formValue']), ]; } public function getFilters() { return [ 'str_replace' => new \Twig_SimpleFilter('str_replace', 'str_replace'), ]; } public function uniqid($prefix) { $random = $this->randomLib->getLowStrengthGenerator(); $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; return $prefix . $random->generateString(12, $characters); } public function mt_rand($min, $max) { return mt_rand($min, $max); } public function str_replace($subject, $search, $replace) { return str_replace($search, $replace, $subject); } public function mergeUnique(array $arr1, array $arr2) { return array_unique(array_merge($arr1, $arr2)); } public function addAvailable(array $arr1, array $arr2) { return array_merge($arr1, ['available' => $arr2]); } public function formValue($value) { if ($value === false) { return 'false'; } if ($value === null) { return 'false'; } return $value; } public function getName() { return 'base_extension'; } }
Java
// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the name Chromium Embedded // Framework nor the names of its contributors may be used to endorse // or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool and should not edited // by hand. See the translator.README.txt file in the tools directory for // more information. // #ifndef CEF_INCLUDE_CAPI_CEF_REQUEST_CAPI_H_ #define CEF_INCLUDE_CAPI_CEF_REQUEST_CAPI_H_ #pragma once #ifdef __cplusplus extern "C" { #endif #include "include/capi/cef_base_capi.h" /// // Structure used to represent a web request. The functions of this structure // may be called on any thread. /// typedef struct _cef_request_t { /// // Base structure. /// cef_base_t base; /// // Returns true (1) if this object is read-only. /// int (CEF_CALLBACK *is_read_only)(struct _cef_request_t* self); /// // Get the fully qualified URL. /// // The resulting string must be freed by calling cef_string_userfree_free(). cef_string_userfree_t (CEF_CALLBACK *get_url)(struct _cef_request_t* self); /// // Set the fully qualified URL. /// void (CEF_CALLBACK *set_url)(struct _cef_request_t* self, const cef_string_t* url); /// // Get the request function type. The value will default to POST if post data // is provided and GET otherwise. /// // The resulting string must be freed by calling cef_string_userfree_free(). cef_string_userfree_t (CEF_CALLBACK *get_method)(struct _cef_request_t* self); /// // Set the request function type. /// void (CEF_CALLBACK *set_method)(struct _cef_request_t* self, const cef_string_t* method); /// // Get the post data. /// struct _cef_post_data_t* (CEF_CALLBACK *get_post_data)( struct _cef_request_t* self); /// // Set the post data. /// void (CEF_CALLBACK *set_post_data)(struct _cef_request_t* self, struct _cef_post_data_t* postData); /// // Get the header values. /// void (CEF_CALLBACK *get_header_map)(struct _cef_request_t* self, cef_string_multimap_t headerMap); /// // Set the header values. /// void (CEF_CALLBACK *set_header_map)(struct _cef_request_t* self, cef_string_multimap_t headerMap); /// // Set all values at one time. /// void (CEF_CALLBACK *set)(struct _cef_request_t* self, const cef_string_t* url, const cef_string_t* method, struct _cef_post_data_t* postData, cef_string_multimap_t headerMap); /// // Get the flags used in combination with cef_urlrequest_t. See // cef_urlrequest_flags_t for supported values. /// int (CEF_CALLBACK *get_flags)(struct _cef_request_t* self); /// // Set the flags used in combination with cef_urlrequest_t. See // cef_urlrequest_flags_t for supported values. /// void (CEF_CALLBACK *set_flags)(struct _cef_request_t* self, int flags); /// // Set the URL to the first party for cookies used in combination with // cef_urlrequest_t. /// // The resulting string must be freed by calling cef_string_userfree_free(). cef_string_userfree_t (CEF_CALLBACK *get_first_party_for_cookies)( struct _cef_request_t* self); /// // Get the URL to the first party for cookies used in combination with // cef_urlrequest_t. /// void (CEF_CALLBACK *set_first_party_for_cookies)(struct _cef_request_t* self, const cef_string_t* url); } cef_request_t; /// // Create a new cef_request_t object. /// CEF_EXPORT cef_request_t* cef_request_create(); /// // Structure used to represent post data for a web request. The functions of // this structure may be called on any thread. /// typedef struct _cef_post_data_t { /// // Base structure. /// cef_base_t base; /// // Returns true (1) if this object is read-only. /// int (CEF_CALLBACK *is_read_only)(struct _cef_post_data_t* self); /// // Returns the number of existing post data elements. /// size_t (CEF_CALLBACK *get_element_count)(struct _cef_post_data_t* self); /// // Retrieve the post data elements. /// void (CEF_CALLBACK *get_elements)(struct _cef_post_data_t* self, size_t* elementsCount, struct _cef_post_data_element_t** elements); /// // Remove the specified post data element. Returns true (1) if the removal // succeeds. /// int (CEF_CALLBACK *remove_element)(struct _cef_post_data_t* self, struct _cef_post_data_element_t* element); /// // Add the specified post data element. Returns true (1) if the add succeeds. /// int (CEF_CALLBACK *add_element)(struct _cef_post_data_t* self, struct _cef_post_data_element_t* element); /// // Remove all existing post data elements. /// void (CEF_CALLBACK *remove_elements)(struct _cef_post_data_t* self); } cef_post_data_t; /// // Create a new cef_post_data_t object. /// CEF_EXPORT cef_post_data_t* cef_post_data_create(); /// // Structure used to represent a single element in the request post data. The // functions of this structure may be called on any thread. /// typedef struct _cef_post_data_element_t { /// // Base structure. /// cef_base_t base; /// // Returns true (1) if this object is read-only. /// int (CEF_CALLBACK *is_read_only)(struct _cef_post_data_element_t* self); /// // Remove all contents from the post data element. /// void (CEF_CALLBACK *set_to_empty)(struct _cef_post_data_element_t* self); /// // The post data element will represent a file. /// void (CEF_CALLBACK *set_to_file)(struct _cef_post_data_element_t* self, const cef_string_t* fileName); /// // The post data element will represent bytes. The bytes passed in will be // copied. /// void (CEF_CALLBACK *set_to_bytes)(struct _cef_post_data_element_t* self, size_t size, const void* bytes); /// // Return the type of this post data element. /// enum cef_postdataelement_type_t (CEF_CALLBACK *get_type)( struct _cef_post_data_element_t* self); /// // Return the file name. /// // The resulting string must be freed by calling cef_string_userfree_free(). cef_string_userfree_t (CEF_CALLBACK *get_file)( struct _cef_post_data_element_t* self); /// // Return the number of bytes. /// size_t (CEF_CALLBACK *get_bytes_count)(struct _cef_post_data_element_t* self); /// // Read up to |size| bytes into |bytes| and return the number of bytes // actually read. /// size_t (CEF_CALLBACK *get_bytes)(struct _cef_post_data_element_t* self, size_t size, void* bytes); } cef_post_data_element_t; /// // Create a new cef_post_data_element_t object. /// CEF_EXPORT cef_post_data_element_t* cef_post_data_element_create(); #ifdef __cplusplus } #endif #endif // CEF_INCLUDE_CAPI_CEF_REQUEST_CAPI_H_
Java
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pycrunchbase.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pycrunchbase.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/pycrunchbase" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pycrunchbase" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
Java
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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.model; import hudson.model.MultiStageTimeSeries.TimeScale; import hudson.model.queue.SubTask; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.jfree.chart.JFreeChart; import org.junit.Test; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; /** * @author Kohsuke Kawaguchi */ public class LoadStatisticsTest { @Test public void graph() throws IOException { LoadStatistics ls = new LoadStatistics(0, 0) { public int computeIdleExecutors() { throw new UnsupportedOperationException(); } public int computeTotalExecutors() { throw new UnsupportedOperationException(); } public int computeQueueLength() { throw new UnsupportedOperationException(); } @Override protected Iterable<Node> getNodes() { throw new UnsupportedOperationException(); } @Override protected boolean matches(Queue.Item item, SubTask subTask) { throw new UnsupportedOperationException(); } }; for (int i = 0; i < 50; i++) { ls.onlineExecutors.update(4); ls.busyExecutors.update(3); ls.availableExecutors.update(1); ls.queueLength.update(3); } for (int i = 0; i < 50; i++) { ls.onlineExecutors.update(0); ls.busyExecutors.update(0); ls.availableExecutors.update(0); ls.queueLength.update(1); } JFreeChart chart = ls.createTrendChart(TimeScale.SEC10).createChart(); BufferedImage image = chart.createBufferedImage(400, 200); File tempFile = File.createTempFile("chart-", "png"); try (OutputStream os = Files.newOutputStream(tempFile.toPath(), StandardOpenOption.DELETE_ON_CLOSE)) { ImageIO.write(image, "PNG", os); } finally { tempFile.delete(); } } @Test public void isModernWorks() throws Exception { assertThat(LoadStatistics.isModern(Modern.class), is(true)); assertThat(LoadStatistics.isModern(LoadStatistics.class), is(false)); } private static class Modern extends LoadStatistics { protected Modern(int initialOnlineExecutors, int initialBusyExecutors) { super(initialOnlineExecutors, initialBusyExecutors); } @Override public int computeIdleExecutors() { return 0; } @Override public int computeTotalExecutors() { return 0; } @Override public int computeQueueLength() { return 0; } @Override protected Iterable<Node> getNodes() { return null; } @Override protected boolean matches(Queue.Item item, SubTask subTask) { return false; } } }
Java
/// <reference path="../../../type-declarations/index.d.ts" /> import * as Phaser from 'phaser'; import { BootState } from './states/boot'; import { SplashState } from './states/splash'; import { GameState } from './states/game'; class Game extends Phaser.Game { constructor() { let width = document.documentElement.clientWidth > 768 * 1.4 // make room for chat ? 768 : document.documentElement.clientWidth * 0.7; let height = document.documentElement.clientHeight > 1024 * 1.67 // give navbar some room ? 1024 : document.documentElement.clientHeight * 0.6; super(width, height, Phaser.AUTO, 'game', null, false, false); this.state.add('Boot', BootState, false); this.state.add('Splash', SplashState, false); this.state.add('Game', GameState, false); this.state.start('Boot'); } } export const runGame = () => { new Game(); }
Java
<h1>Kitchen List</h1> <div id="p_be_list"> <div class="table"> <div class="body"> <table> <thead> <tr> <th colspan="2"><?php echo __('Name')?></th> </tr> </thead> <tbody> <?php if ($kitchen_list->count() !== false && $kitchen_list->count() == 0): ?> <tr class="row_0"> <td colspan="2"><?php echo __('No Results') ?></td> </tr> <?php else: ?> <?php foreach ($kitchen_list as $key => $kitchen): ?> <tr class="<?php if ($key % 2 == 0) echo "row_0"; else echo "row_1"; ?>"> <td width="98%"><?php echo $kitchen->getName() ?></td> <td width="2%"><a href="<?php echo url_for('kitchen/edit?id='.$kitchen->getId()) ?>"><?php echo image_tag('famfamicons/application_edit.png') ?></a></td> </tr> <?php endforeach; ?> <?php endif; ?> </tbody> <tfoot> <tr> <th colspan="2" class="textright"> <a href="<?php echo url_for('kitchen/new') ?>" title="New">New</a> </th> </tr> </tfoot> </table> </div> </div> </div>
Java
import { c } from 'ttag'; export class ImportFatalError extends Error { error: Error; constructor(error: Error) { super(c('Error importing calendar').t`An unexpected error occurred. Import must be restarted.`); this.error = error; Object.setPrototypeOf(this, ImportFatalError.prototype); } }
Java
package com.xruby.runtime.lang; public abstract class RubyConstant extends RubyBasic { public static RubyConstant QFALSE = new RubyConstant(RubyRuntime.FalseClassClass) { public boolean isTrue() { return false; } }; public static RubyConstant QTRUE = new RubyConstant(RubyRuntime.TrueClassClass) { public boolean isTrue() { return true; } }; public static RubyConstant QNIL = new RubyConstant(RubyRuntime.NilClassClass) { public boolean isTrue() { return false; } public String toStr() { throw new RubyException(RubyRuntime.TypeErrorClass, "Cannot convert nil into String"); } }; private RubyConstant(RubyClass c) { super(c); } }
Java
// This file was generated based on '(multiple files)'. // WARNING: Changes might be lost if you edit this file directly. #include <Fuse.Drawing.Meshes.MeshGenerator.h> #include <Fuse.Entities.Mesh.h> #include <Fuse.Entities.MeshHitTestMode.h> #include <Fuse.Entities.Primitives.ConeRenderer.h> #include <Fuse.Entities.Primitives.CubeRenderer.h> #include <Fuse.Entities.Primitives.CylinderRenderer.h> #include <Fuse.Entities.Primitives.SphereRenderer.h> #include <Uno.Bool.h> #include <Uno.Content.Models.ModelMesh.h> #include <Uno.Float.h> #include <Uno.Float3.h> #include <Uno.Int.h> static uType* TYPES[1]; namespace g{ namespace Fuse{ namespace Entities{ namespace Primitives{ // C:\ProgramData\Uno\Packages\Fuse.Entities\0.18.8\$.uno(1788) // ------------------------------------------------------------ // public sealed class ConeRenderer :1788 // { ::g::Fuse::Entities::MeshRenderer_type* ConeRenderer_typeof() { static uSStrong< ::g::Fuse::Entities::MeshRenderer_type*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 6; options.ObjectSize = sizeof(ConeRenderer); options.TypeSize = sizeof(::g::Fuse::Entities::MeshRenderer_type); type = (::g::Fuse::Entities::MeshRenderer_type*)uClassType::New("Fuse.Entities.Primitives.ConeRenderer", options); type->SetBase(::g::Fuse::Entities::MeshRenderer_typeof()); type->fp_ctor_ = (void*)ConeRenderer__New2_fn; ::TYPES[0] = ::g::Fuse::Entities::MeshRenderer_typeof(); type->SetFields(6); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)ConeRenderer__New2_fn, 0, true, ConeRenderer_typeof(), 0)); return type; } // public ConeRenderer() :1790 void ConeRenderer__ctor_2_fn(ConeRenderer* __this) { __this->ctor_2(); } // public ConeRenderer New() :1790 void ConeRenderer__New2_fn(ConeRenderer** __retval) { *__retval = ConeRenderer::New2(); } // public ConeRenderer() [instance] :1790 void ConeRenderer::ctor_2() { ctor_1(); Mesh(::g::Fuse::Entities::Mesh::New2(::g::Fuse::Drawing::Meshes::MeshGenerator::CreateCone(10.0f, 5.0f, 16, 16))); } // public ConeRenderer New() [static] :1790 ConeRenderer* ConeRenderer::New2() { ConeRenderer* obj1 = (ConeRenderer*)uNew(ConeRenderer_typeof()); obj1->ctor_2(); return obj1; } // } // C:\ProgramData\Uno\Packages\Fuse.Entities\0.18.8\$.uno(1729) // ------------------------------------------------------------ // public sealed class CubeRenderer :1729 // { ::g::Fuse::Entities::MeshRenderer_type* CubeRenderer_typeof() { static uSStrong< ::g::Fuse::Entities::MeshRenderer_type*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 6; options.ObjectSize = sizeof(CubeRenderer); options.TypeSize = sizeof(::g::Fuse::Entities::MeshRenderer_type); type = (::g::Fuse::Entities::MeshRenderer_type*)uClassType::New("Fuse.Entities.Primitives.CubeRenderer", options); type->SetBase(::g::Fuse::Entities::MeshRenderer_typeof()); type->fp_ctor_ = (void*)CubeRenderer__New2_fn; ::TYPES[0] = ::g::Fuse::Entities::MeshRenderer_typeof(); type->SetFields(6); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)CubeRenderer__New2_fn, 0, true, CubeRenderer_typeof(), 0)); return type; } // public CubeRenderer() :1731 void CubeRenderer__ctor_2_fn(CubeRenderer* __this) { __this->ctor_2(); } // public CubeRenderer New() :1731 void CubeRenderer__New2_fn(CubeRenderer** __retval) { *__retval = CubeRenderer::New2(); } // public CubeRenderer() [instance] :1731 void CubeRenderer::ctor_2() { ctor_1(); Mesh(::g::Fuse::Entities::Mesh::New2(::g::Fuse::Drawing::Meshes::MeshGenerator::CreateCube(::g::Uno::Float3__New1(0.0f), 5.0f))); HitTestMode(1); } // public CubeRenderer New() [static] :1731 CubeRenderer* CubeRenderer::New2() { CubeRenderer* obj1 = (CubeRenderer*)uNew(CubeRenderer_typeof()); obj1->ctor_2(); return obj1; } // } // C:\ProgramData\Uno\Packages\Fuse.Entities\0.18.8\$.uno(1797) // ------------------------------------------------------------ // public sealed class CylinderRenderer :1797 // { ::g::Fuse::Entities::MeshRenderer_type* CylinderRenderer_typeof() { static uSStrong< ::g::Fuse::Entities::MeshRenderer_type*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 6; options.ObjectSize = sizeof(CylinderRenderer); options.TypeSize = sizeof(::g::Fuse::Entities::MeshRenderer_type); type = (::g::Fuse::Entities::MeshRenderer_type*)uClassType::New("Fuse.Entities.Primitives.CylinderRenderer", options); type->SetBase(::g::Fuse::Entities::MeshRenderer_typeof()); type->fp_ctor_ = (void*)CylinderRenderer__New2_fn; ::TYPES[0] = ::g::Fuse::Entities::MeshRenderer_typeof(); type->SetFields(6); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)CylinderRenderer__New2_fn, 0, true, CylinderRenderer_typeof(), 0)); return type; } // public CylinderRenderer() :1799 void CylinderRenderer__ctor_2_fn(CylinderRenderer* __this) { __this->ctor_2(); } // public CylinderRenderer New() :1799 void CylinderRenderer__New2_fn(CylinderRenderer** __retval) { *__retval = CylinderRenderer::New2(); } // public CylinderRenderer() [instance] :1799 void CylinderRenderer::ctor_2() { ctor_1(); Mesh(::g::Fuse::Entities::Mesh::New2(::g::Fuse::Drawing::Meshes::MeshGenerator::CreateCylinder(10.0f, 5.0f, 16, 16))); } // public CylinderRenderer New() [static] :1799 CylinderRenderer* CylinderRenderer::New2() { CylinderRenderer* obj1 = (CylinderRenderer*)uNew(CylinderRenderer_typeof()); obj1->ctor_2(); return obj1; } // } // C:\ProgramData\Uno\Packages\Fuse.Entities\0.18.8\$.uno(1739) // ------------------------------------------------------------ // public sealed class SphereRenderer :1739 // { ::g::Fuse::Entities::MeshRenderer_type* SphereRenderer_typeof() { static uSStrong< ::g::Fuse::Entities::MeshRenderer_type*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 9; options.ObjectSize = sizeof(SphereRenderer); options.TypeSize = sizeof(::g::Fuse::Entities::MeshRenderer_type); type = (::g::Fuse::Entities::MeshRenderer_type*)uClassType::New("Fuse.Entities.Primitives.SphereRenderer", options); type->SetBase(::g::Fuse::Entities::MeshRenderer_typeof()); type->fp_ctor_ = (void*)SphereRenderer__New2_fn; type->fp_Validate = (void(*)(::g::Fuse::Entities::MeshRenderer*))SphereRenderer__Validate_fn; ::TYPES[0] = ::g::Fuse::Entities::MeshRenderer_typeof(); type->SetFields(6, ::g::Uno::Bool_typeof(), offsetof(::g::Fuse::Entities::Primitives::SphereRenderer, _isDirty), 0, ::g::Uno::Int_typeof(), offsetof(::g::Fuse::Entities::Primitives::SphereRenderer, _quality), 0, ::g::Uno::Float_typeof(), offsetof(::g::Fuse::Entities::Primitives::SphereRenderer, _radius), 0); type->Reflection.SetFunctions(5, new uFunction(".ctor", NULL, (void*)SphereRenderer__New2_fn, 0, true, SphereRenderer_typeof(), 0), new uFunction("get_Quality", NULL, (void*)SphereRenderer__get_Quality_fn, 0, false, ::g::Uno::Int_typeof(), 0), new uFunction("set_Quality", NULL, (void*)SphereRenderer__set_Quality_fn, 0, false, uVoid_typeof(), 1, ::g::Uno::Int_typeof()), new uFunction("get_Radius", NULL, (void*)SphereRenderer__get_Radius_fn, 0, false, ::g::Uno::Float_typeof(), 0), new uFunction("set_Radius", NULL, (void*)SphereRenderer__set_Radius_fn, 0, false, uVoid_typeof(), 1, ::g::Uno::Float_typeof())); return type; } // public SphereRenderer() :1771 void SphereRenderer__ctor_2_fn(SphereRenderer* __this) { __this->ctor_2(); } // public SphereRenderer New() :1771 void SphereRenderer__New2_fn(SphereRenderer** __retval) { *__retval = SphereRenderer::New2(); } // public int get_Quality() :1760 void SphereRenderer__get_Quality_fn(SphereRenderer* __this, int* __retval) { *__retval = __this->Quality(); } // public void set_Quality(int value) :1761 void SphereRenderer__set_Quality_fn(SphereRenderer* __this, int* value) { __this->Quality(*value); } // public float get_Radius() :1746 void SphereRenderer__get_Radius_fn(SphereRenderer* __this, float* __retval) { *__retval = __this->Radius(); } // public void set_Radius(float value) :1747 void SphereRenderer__set_Radius_fn(SphereRenderer* __this, float* value) { __this->Radius(*value); } // protected override sealed void Validate() :1776 void SphereRenderer__Validate_fn(SphereRenderer* __this) { if (__this->_isDirty || (__this->Mesh() == NULL)) { if (__this->Mesh() != NULL) uPtr(__this->Mesh())->Dispose(); __this->Mesh(::g::Fuse::Entities::Mesh::New2(::g::Fuse::Drawing::Meshes::MeshGenerator::CreateSphere(::g::Uno::Float3__New1(0.0f), __this->_radius, __this->_quality, __this->_quality))); __this->_isDirty = false; } } // public SphereRenderer() [instance] :1771 void SphereRenderer::ctor_2() { _radius = 5.0f; _quality = 16; ctor_1(); HitTestMode(2); } // public int get_Quality() [instance] :1760 int SphereRenderer::Quality() { return _quality; } // public void set_Quality(int value) [instance] :1761 void SphereRenderer::Quality(int value) { if (_quality != value) { _quality = value; _isDirty = true; } } // public float get_Radius() [instance] :1746 float SphereRenderer::Radius() { return _radius; } // public void set_Radius(float value) [instance] :1747 void SphereRenderer::Radius(float value) { if (_radius != value) { _radius = value; _isDirty = true; } } // public SphereRenderer New() [static] :1771 SphereRenderer* SphereRenderer::New2() { SphereRenderer* obj1 = (SphereRenderer*)uNew(SphereRenderer_typeof()); obj1->ctor_2(); return obj1; } // } }}}} // ::g::Fuse::Entities::Primitives
Java
game.LoadProfile = me.ScreenObject.extend({ /** * action to perform on state change */ onResetEvent: function() { me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('load-screen')), -10); //puts load screen in when game starts document.getElementById("input").style.visibility = "visible"; document.getElementById("load").style.visibility = "visible"; me.input.unbindKey(me.input.KEY.B); me.input.unbindKey(me.input.KEY.I); me.input.unbindKey(me.input.KEY.O); me.input.unbindKey(me.input.KEY.P); me.input.unbindKey(me.input.KEY.SPACE); //unbinds keys var exp1cost = ((game.data.exp1 + 1) * 10); var exp2cost = ((game.data.exp2 + 1) * 10); var exp3cost = ((game.data.exp3 + 1) * 10); var exp4cost = ((game.data.exp4 + 1) * 10); me.game.world.addChild(new (me.Renderable.extend({ init: function() { this._super(me.Renderable, 'init', [10, 10, 300, 50]); this.font = new me.Font("Arial", 26, "white"); }, draw: function(renderer) { this.font.draw(renderer.getContext(), "Enter Username & Password", this.pos.x, this.pos.y); } }))); }, /** * action to perform when leaving this screen (state change) */ onDestroyEvent: function() { document.getElementById("input").style.visibility = "hidden"; document.getElementById("load").style.visibility = "hidden"; } });
Java
/* --- MooTools: the javascript framework web build: - http://mootools.net/core/8423c12ffd6a6bfcde9ea22554aec795 packager build: - packager build Core/Core Core/Array Core/String Core/Number Core/Function Core/Object Core/Event Core/Browser Core/Class Core/Class.Extras Core/Slick.Parser Core/Slick.Finder Core/Element Core/Element.Style Core/Element.Event Core/Element.Delegation Core/Element.Dimensions Core/Fx Core/Fx.CSS Core/Fx.Tween Core/Fx.Morph Core/Fx.Transitions Core/Request Core/Request.HTML Core/Request.JSON Core/Cookie Core/JSON Core/DOMReady ... */ /* --- name: Core description: The heart of MooTools. license: MIT-style license. copyright: Copyright (c) 2006-2012 [Valerio Proietti](http://mad4milk.net/). authors: The MooTools production team (http://mootools.net/developers/) inspiration: - Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php) - Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php) provides: [Core, MooTools, Type, typeOf, instanceOf, Native] ... */ (function(){ this.MooTools = { version: '1.4.5', build: 'ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0' }; // typeOf, instanceOf var typeOf = this.typeOf = function(item){ if (item == null) return 'null'; if (item.$family != null) return item.$family(); if (item.nodeName){ if (item.nodeType == 1) return 'element'; if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace'; } else if (typeof item.length == 'number'){ if (item.callee) return 'arguments'; if ('item' in item) return 'collection'; } return typeof item; }; var instanceOf = this.instanceOf = function(item, object){ if (item == null) return false; var constructor = item.$constructor || item.constructor; while (constructor){ if (constructor === object) return true; constructor = constructor.parent; } /*<ltIE8>*/ if (!item.hasOwnProperty) return false; /*</ltIE8>*/ return item instanceof object; }; // Function overloading var Function = this.Function; var enumerables = true; for (var i in {toString: 1}) enumerables = null; if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor']; Function.prototype.overloadSetter = function(usePlural){ var self = this; return function(a, b){ if (a == null) return this; if (usePlural || typeof a != 'string'){ for (var k in a) self.call(this, k, a[k]); if (enumerables) for (var i = enumerables.length; i--;){ k = enumerables[i]; if (a.hasOwnProperty(k)) self.call(this, k, a[k]); } } else { self.call(this, a, b); } return this; }; }; Function.prototype.overloadGetter = function(usePlural){ var self = this; return function(a){ var args, result; if (typeof a != 'string') args = a; else if (arguments.length > 1) args = arguments; else if (usePlural) args = [a]; if (args){ result = {}; for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]); } else { result = self.call(this, a); } return result; }; }; Function.prototype.extend = function(key, value){ this[key] = value; }.overloadSetter(); Function.prototype.implement = function(key, value){ this.prototype[key] = value; }.overloadSetter(); // From var slice = Array.prototype.slice; Function.from = function(item){ return (typeOf(item) == 'function') ? item : function(){ return item; }; }; Array.from = function(item){ if (item == null) return []; return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item]; }; Number.from = function(item){ var number = parseFloat(item); return isFinite(number) ? number : null; }; String.from = function(item){ return item + ''; }; // hide, protect Function.implement({ hide: function(){ this.$hidden = true; return this; }, protect: function(){ this.$protected = true; return this; } }); // Type var Type = this.Type = function(name, object){ if (name){ var lower = name.toLowerCase(); var typeCheck = function(item){ return (typeOf(item) == lower); }; Type['is' + name] = typeCheck; if (object != null){ object.prototype.$family = (function(){ return lower; }).hide(); } } if (object == null) return null; object.extend(this); object.$constructor = Type; object.prototype.$constructor = object; return object; }; var toString = Object.prototype.toString; Type.isEnumerable = function(item){ return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' ); }; var hooks = {}; var hooksOf = function(object){ var type = typeOf(object.prototype); return hooks[type] || (hooks[type] = []); }; var implement = function(name, method){ if (method && method.$hidden) return; var hooks = hooksOf(this); for (var i = 0; i < hooks.length; i++){ var hook = hooks[i]; if (typeOf(hook) == 'type') implement.call(hook, name, method); else hook.call(this, name, method); } var previous = this.prototype[name]; if (previous == null || !previous.$protected) this.prototype[name] = method; if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){ return method.apply(item, slice.call(arguments, 1)); }); }; var extend = function(name, method){ if (method && method.$hidden) return; var previous = this[name]; if (previous == null || !previous.$protected) this[name] = method; }; Type.implement({ implement: implement.overloadSetter(), extend: extend.overloadSetter(), alias: function(name, existing){ implement.call(this, name, this.prototype[existing]); }.overloadSetter(), mirror: function(hook){ hooksOf(this).push(hook); return this; } }); new Type('Type', Type); // Default Types var force = function(name, object, methods){ var isType = (object != Object), prototype = object.prototype; if (isType) object = new Type(name, object); for (var i = 0, l = methods.length; i < l; i++){ var key = methods[i], generic = object[key], proto = prototype[key]; if (generic) generic.protect(); if (isType && proto) object.implement(key, proto.protect()); } if (isType){ var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]); object.forEachMethod = function(fn){ if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){ fn.call(prototype, prototype[methods[i]], methods[i]); } for (var key in prototype) fn.call(prototype, prototype[key], key) }; } return force; }; force('String', String, [ 'charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search', 'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase' ])('Array', Array, [ 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice', 'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight' ])('Number', Number, [ 'toExponential', 'toFixed', 'toLocaleString', 'toPrecision' ])('Function', Function, [ 'apply', 'call', 'bind' ])('RegExp', RegExp, [ 'exec', 'test' ])('Object', Object, [ 'create', 'defineProperty', 'defineProperties', 'keys', 'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames', 'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen' ])('Date', Date, ['now']); Object.extend = extend.overloadSetter(); Date.extend('now', function(){ return +(new Date); }); new Type('Boolean', Boolean); // fixes NaN returning as Number Number.prototype.$family = function(){ return isFinite(this) ? 'number' : 'null'; }.hide(); // Number.random Number.extend('random', function(min, max){ return Math.floor(Math.random() * (max - min + 1) + min); }); // forEach, each var hasOwnProperty = Object.prototype.hasOwnProperty; Object.extend('forEach', function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object); } }); Object.each = Object.forEach; Array.implement({ forEach: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++){ if (i in this) fn.call(bind, this[i], i, this); } }, each: function(fn, bind){ Array.forEach(this, fn, bind); return this; } }); // Array & Object cloning, Object merging and appending var cloneOf = function(item){ switch (typeOf(item)){ case 'array': return item.clone(); case 'object': return Object.clone(item); default: return item; } }; Array.implement('clone', function(){ var i = this.length, clone = new Array(i); while (i--) clone[i] = cloneOf(this[i]); return clone; }); var mergeOne = function(source, key, current){ switch (typeOf(current)){ case 'object': if (typeOf(source[key]) == 'object') Object.merge(source[key], current); else source[key] = Object.clone(current); break; case 'array': source[key] = current.clone(); break; default: source[key] = current; } return source; }; Object.extend({ merge: function(source, k, v){ if (typeOf(k) == 'string') return mergeOne(source, k, v); for (var i = 1, l = arguments.length; i < l; i++){ var object = arguments[i]; for (var key in object) mergeOne(source, key, object[key]); } return source; }, clone: function(object){ var clone = {}; for (var key in object) clone[key] = cloneOf(object[key]); return clone; }, append: function(original){ for (var i = 1, l = arguments.length; i < l; i++){ var extended = arguments[i] || {}; for (var key in extended) original[key] = extended[key]; } return original; } }); // Object-less types ['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){ new Type(name); }); // Unique ID var UID = Date.now(); String.extend('uniqueID', function(){ return (UID++).toString(36); }); })(); /* --- name: Array description: Contains Array Prototypes like each, contains, and erase. license: MIT-style license. requires: Type provides: Array ... */ Array.implement({ /*<!ES5>*/ every: function(fn, bind){ for (var i = 0, l = this.length >>> 0; i < l; i++){ if ((i in this) && !fn.call(bind, this[i], i, this)) return false; } return true; }, filter: function(fn, bind){ var results = []; for (var value, i = 0, l = this.length >>> 0; i < l; i++) if (i in this){ value = this[i]; if (fn.call(bind, value, i, this)) results.push(value); } return results; }, indexOf: function(item, from){ var length = this.length >>> 0; for (var i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++){ if (this[i] === item) return i; } return -1; }, map: function(fn, bind){ var length = this.length >>> 0, results = Array(length); for (var i = 0; i < length; i++){ if (i in this) results[i] = fn.call(bind, this[i], i, this); } return results; }, some: function(fn, bind){ for (var i = 0, l = this.length >>> 0; i < l; i++){ if ((i in this) && fn.call(bind, this[i], i, this)) return true; } return false; }, /*</!ES5>*/ clean: function(){ return this.filter(function(item){ return item != null; }); }, invoke: function(methodName){ var args = Array.slice(arguments, 1); return this.map(function(item){ return item[methodName].apply(item, args); }); }, associate: function(keys){ var obj = {}, length = Math.min(this.length, keys.length); for (var i = 0; i < length; i++) obj[keys[i]] = this[i]; return obj; }, link: function(object){ var result = {}; for (var i = 0, l = this.length; i < l; i++){ for (var key in object){ if (object[key](this[i])){ result[key] = this[i]; delete object[key]; break; } } } return result; }, contains: function(item, from){ return this.indexOf(item, from) != -1; }, append: function(array){ this.push.apply(this, array); return this; }, getLast: function(){ return (this.length) ? this[this.length - 1] : null; }, getRandom: function(){ return (this.length) ? this[Number.random(0, this.length - 1)] : null; }, include: function(item){ if (!this.contains(item)) this.push(item); return this; }, combine: function(array){ for (var i = 0, l = array.length; i < l; i++) this.include(array[i]); return this; }, erase: function(item){ for (var i = this.length; i--;){ if (this[i] === item) this.splice(i, 1); } return this; }, empty: function(){ this.length = 0; return this; }, flatten: function(){ var array = []; for (var i = 0, l = this.length; i < l; i++){ var type = typeOf(this[i]); if (type == 'null') continue; array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]); } return array; }, pick: function(){ for (var i = 0, l = this.length; i < l; i++){ if (this[i] != null) return this[i]; } return null; }, hexToRgb: function(array){ if (this.length != 3) return null; var rgb = this.map(function(value){ if (value.length == 1) value += value; return value.toInt(16); }); return (array) ? rgb : 'rgb(' + rgb + ')'; }, rgbToHex: function(array){ if (this.length < 3) return null; if (this.length == 4 && this[3] == 0 && !array) return 'transparent'; var hex = []; for (var i = 0; i < 3; i++){ var bit = (this[i] - 0).toString(16); hex.push((bit.length == 1) ? '0' + bit : bit); } return (array) ? hex : '#' + hex.join(''); } }); /* --- name: String description: Contains String Prototypes like camelCase, capitalize, test, and toInt. license: MIT-style license. requires: Type provides: String ... */ String.implement({ test: function(regex, params){ return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this); }, contains: function(string, separator){ return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : String(this).indexOf(string) > -1; }, trim: function(){ return String(this).replace(/^\s+|\s+$/g, ''); }, clean: function(){ return String(this).replace(/\s+/g, ' ').trim(); }, camelCase: function(){ return String(this).replace(/-\D/g, function(match){ return match.charAt(1).toUpperCase(); }); }, hyphenate: function(){ return String(this).replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); }, capitalize: function(){ return String(this).replace(/\b[a-z]/g, function(match){ return match.toUpperCase(); }); }, escapeRegExp: function(){ return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'); }, toInt: function(base){ return parseInt(this, base || 10); }, toFloat: function(){ return parseFloat(this); }, hexToRgb: function(array){ var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); return (hex) ? hex.slice(1).hexToRgb(array) : null; }, rgbToHex: function(array){ var rgb = String(this).match(/\d{1,3}/g); return (rgb) ? rgb.rgbToHex(array) : null; }, substitute: function(object, regexp){ return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){ if (match.charAt(0) == '\\') return match.slice(1); return (object[name] != null) ? object[name] : ''; }); } }); /* --- name: Number description: Contains Number Prototypes like limit, round, times, and ceil. license: MIT-style license. requires: Type provides: Number ... */ Number.implement({ limit: function(min, max){ return Math.min(max, Math.max(min, this)); }, round: function(precision){ precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0); return Math.round(this * precision) / precision; }, times: function(fn, bind){ for (var i = 0; i < this; i++) fn.call(bind, i, this); }, toFloat: function(){ return parseFloat(this); }, toInt: function(base){ return parseInt(this, base || 10); } }); Number.alias('each', 'times'); (function(math){ var methods = {}; math.each(function(name){ if (!Number[name]) methods[name] = function(){ return Math[name].apply(null, [this].concat(Array.from(arguments))); }; }); Number.implement(methods); })(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']); /* --- name: Function description: Contains Function Prototypes like create, bind, pass, and delay. license: MIT-style license. requires: Type provides: Function ... */ Function.extend({ attempt: function(){ for (var i = 0, l = arguments.length; i < l; i++){ try { return arguments[i](); } catch (e){} } return null; } }); Function.implement({ attempt: function(args, bind){ try { return this.apply(bind, Array.from(args)); } catch (e){} return null; }, /*<!ES5-bind>*/ bind: function(that){ var self = this, args = arguments.length > 1 ? Array.slice(arguments, 1) : null, F = function(){}; var bound = function(){ var context = that, length = arguments.length; if (this instanceof bound){ F.prototype = self.prototype; context = new F; } var result = (!args && !length) ? self.call(context) : self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments); return context == that ? result : context; }; return bound; }, /*</!ES5-bind>*/ pass: function(args, bind){ var self = this; if (args != null) args = Array.from(args); return function(){ return self.apply(bind, args || arguments); }; }, delay: function(delay, bind, args){ return setTimeout(this.pass((args == null ? [] : args), bind), delay); }, periodical: function(periodical, bind, args){ return setInterval(this.pass((args == null ? [] : args), bind), periodical); } }); /* --- name: Object description: Object generic methods license: MIT-style license. requires: Type provides: [Object, Hash] ... */ (function(){ var hasOwnProperty = Object.prototype.hasOwnProperty; Object.extend({ subset: function(object, keys){ var results = {}; for (var i = 0, l = keys.length; i < l; i++){ var k = keys[i]; if (k in object) results[k] = object[k]; } return results; }, map: function(object, fn, bind){ var results = {}; for (var key in object){ if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object); } return results; }, filter: function(object, fn, bind){ var results = {}; for (var key in object){ var value = object[key]; if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value; } return results; }, every: function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false; } return true; }, some: function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true; } return false; }, keys: function(object){ var keys = []; for (var key in object){ if (hasOwnProperty.call(object, key)) keys.push(key); } return keys; }, values: function(object){ var values = []; for (var key in object){ if (hasOwnProperty.call(object, key)) values.push(object[key]); } return values; }, getLength: function(object){ return Object.keys(object).length; }, keyOf: function(object, value){ for (var key in object){ if (hasOwnProperty.call(object, key) && object[key] === value) return key; } return null; }, contains: function(object, value){ return Object.keyOf(object, value) != null; }, toQueryString: function(object, base){ var queryString = []; Object.each(object, function(value, key){ if (base) key = base + '[' + key + ']'; var result; switch (typeOf(value)){ case 'object': result = Object.toQueryString(value, key); break; case 'array': var qs = {}; value.each(function(val, i){ qs[i] = val; }); result = Object.toQueryString(qs, key); break; default: result = key + '=' + encodeURIComponent(value); } if (value != null) queryString.push(result); }); return queryString.join('&'); } }); })(); /* --- name: Browser description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash. license: MIT-style license. requires: [Array, Function, Number, String] provides: [Browser, Window, Document] ... */ (function(){ var document = this.document; var window = document.window = this; var ua = navigator.userAgent.toLowerCase(), platform = navigator.platform.toLowerCase(), UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0], mode = UA[1] == 'ie' && document.documentMode; var Browser = this.Browser = { extend: Function.prototype.extend, name: (UA[1] == 'version') ? UA[3] : UA[1], version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]), Platform: { name: ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0] }, Features: { xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector), json: !!(window.JSON) }, Plugins: {} }; Browser[Browser.name] = true; Browser[Browser.name + parseInt(Browser.version, 10)] = true; Browser.Platform[Browser.Platform.name] = true; // Request Browser.Request = (function(){ var XMLHTTP = function(){ return new XMLHttpRequest(); }; var MSXML2 = function(){ return new ActiveXObject('MSXML2.XMLHTTP'); }; var MSXML = function(){ return new ActiveXObject('Microsoft.XMLHTTP'); }; return Function.attempt(function(){ XMLHTTP(); return XMLHTTP; }, function(){ MSXML2(); return MSXML2; }, function(){ MSXML(); return MSXML; }); })(); Browser.Features.xhr = !!(Browser.Request); // Flash detection var version = (Function.attempt(function(){ return navigator.plugins['Shockwave Flash'].description; }, function(){ return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); }) || '0 r0').match(/\d+/g); Browser.Plugins.Flash = { version: Number(version[0] || '0.' + version[1]) || 0, build: Number(version[2]) || 0 }; // String scripts Browser.exec = function(text){ if (!text) return text; if (window.execScript){ window.execScript(text); } else { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.text = text; document.head.appendChild(script); document.head.removeChild(script); } return text; }; String.implement('stripScripts', function(exec){ var scripts = ''; var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){ scripts += code + '\n'; return ''; }); if (exec === true) Browser.exec(scripts); else if (typeOf(exec) == 'function') exec(scripts, text); return text; }); // Window, Document Browser.extend({ Document: this.Document, Window: this.Window, Element: this.Element, Event: this.Event }); this.Window = this.$constructor = new Type('Window', function(){}); this.$family = Function.from('window').hide(); Window.mirror(function(name, method){ window[name] = method; }); this.Document = document.$constructor = new Type('Document', function(){}); document.$family = Function.from('document').hide(); Document.mirror(function(name, method){ document[name] = method; }); document.html = document.documentElement; if (!document.head) document.head = document.getElementsByTagName('head')[0]; if (document.execCommand) try { document.execCommand("BackgroundImageCache", false, true); } catch (e){} /*<ltIE9>*/ if (this.attachEvent && !this.addEventListener){ var unloadEvent = function(){ this.detachEvent('onunload', unloadEvent); document.head = document.html = document.window = null; }; this.attachEvent('onunload', unloadEvent); } // IE fails on collections and <select>.options (refers to <select>) var arrayFrom = Array.from; try { arrayFrom(document.html.childNodes); } catch(e){ Array.from = function(item){ if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){ var i = item.length, array = new Array(i); while (i--) array[i] = item[i]; return array; } return arrayFrom(item); }; var prototype = Array.prototype, slice = prototype.slice; ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){ var method = prototype[name]; Array[name] = function(item){ return method.apply(Array.from(item), slice.call(arguments, 1)); }; }); } /*</ltIE9>*/ })(); /* --- name: Event description: Contains the Event Type, to make the event object cross-browser. license: MIT-style license. requires: [Window, Document, Array, Function, String, Object] provides: Event ... */ (function() { var _keys = {}; var DOMEvent = this.DOMEvent = new Type('DOMEvent', function(event, win){ if (!win) win = window; event = event || win.event; if (event.$extended) return event; this.event = event; this.$extended = true; this.shift = event.shiftKey; this.control = event.ctrlKey; this.alt = event.altKey; this.meta = event.metaKey; var type = this.type = event.type; var target = event.target || event.srcElement; while (target && target.nodeType == 3) target = target.parentNode; this.target = document.id(target); if (type.indexOf('key') == 0){ var code = this.code = (event.which || event.keyCode); this.key = _keys[code]; if (type == 'keydown'){ if (code > 111 && code < 124) this.key = 'f' + (code - 111); else if (code > 95 && code < 106) this.key = code - 96; } if (this.key == null) this.key = String.fromCharCode(code).toLowerCase(); } else if (type == 'click' || type == 'dblclick' || type == 'contextmenu' || type == 'DOMMouseScroll' || type.indexOf('mouse') == 0){ var doc = win.document; doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; this.page = { x: (event.pageX != null) ? event.pageX : event.clientX + doc.scrollLeft, y: (event.pageY != null) ? event.pageY : event.clientY + doc.scrollTop }; this.client = { x: (event.pageX != null) ? event.pageX - win.pageXOffset : event.clientX, y: (event.pageY != null) ? event.pageY - win.pageYOffset : event.clientY }; if (type == 'DOMMouseScroll' || type == 'mousewheel') this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3; this.rightClick = (event.which == 3 || event.button == 2); if (type == 'mouseover' || type == 'mouseout'){ var related = event.relatedTarget || event[(type == 'mouseover' ? 'from' : 'to') + 'Element']; while (related && related.nodeType == 3) related = related.parentNode; this.relatedTarget = document.id(related); } } else if (type.indexOf('touch') == 0 || type.indexOf('gesture') == 0){ this.rotation = event.rotation; this.scale = event.scale; this.targetTouches = event.targetTouches; this.changedTouches = event.changedTouches; var touches = this.touches = event.touches; if (touches && touches[0]){ var touch = touches[0]; this.page = {x: touch.pageX, y: touch.pageY}; this.client = {x: touch.clientX, y: touch.clientY}; } } if (!this.client) this.client = {}; if (!this.page) this.page = {}; }); DOMEvent.implement({ stop: function(){ return this.preventDefault().stopPropagation(); }, stopPropagation: function(){ if (this.event.stopPropagation) this.event.stopPropagation(); else this.event.cancelBubble = true; return this; }, preventDefault: function(){ if (this.event.preventDefault) this.event.preventDefault(); else this.event.returnValue = false; return this; } }); DOMEvent.defineKey = function(code, key){ _keys[code] = key; return this; }; DOMEvent.defineKeys = DOMEvent.defineKey.overloadSetter(true); DOMEvent.defineKeys({ '38': 'up', '40': 'down', '37': 'left', '39': 'right', '27': 'esc', '32': 'space', '8': 'backspace', '9': 'tab', '46': 'delete', '13': 'enter' }); })(); /* --- name: Class description: Contains the Class Function for easily creating, extending, and implementing reusable Classes. license: MIT-style license. requires: [Array, String, Function, Number] provides: Class ... */ (function(){ var Class = this.Class = new Type('Class', function(params){ if (instanceOf(params, Function)) params = {initialize: params}; var newClass = function(){ reset(this); if (newClass.$prototyping) return this; this.$caller = null; var value = (this.initialize) ? this.initialize.apply(this, arguments) : this; this.$caller = this.caller = null; return value; }.extend(this).implement(params); newClass.$constructor = Class; newClass.prototype.$constructor = newClass; newClass.prototype.parent = parent; return newClass; }); var parent = function(){ if (!this.$caller) throw new Error('The method "parent" cannot be called.'); var name = this.$caller.$name, parent = this.$caller.$owner.parent, previous = (parent) ? parent.prototype[name] : null; if (!previous) throw new Error('The method "' + name + '" has no parent.'); return previous.apply(this, arguments); }; var reset = function(object){ for (var key in object){ var value = object[key]; switch (typeOf(value)){ case 'object': var F = function(){}; F.prototype = value; object[key] = reset(new F); break; case 'array': object[key] = value.clone(); break; } } return object; }; var wrap = function(self, key, method){ if (method.$origin) method = method.$origin; var wrapper = function(){ if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.'); var caller = this.caller, current = this.$caller; this.caller = current; this.$caller = wrapper; var result = method.apply(this, arguments); this.$caller = current; this.caller = caller; return result; }.extend({$owner: self, $origin: method, $name: key}); return wrapper; }; var implement = function(key, value, retain){ if (Class.Mutators.hasOwnProperty(key)){ value = Class.Mutators[key].call(this, value); if (value == null) return this; } if (typeOf(value) == 'function'){ if (value.$hidden) return this; this.prototype[key] = (retain) ? value : wrap(this, key, value); } else { Object.merge(this.prototype, key, value); } return this; }; var getInstance = function(klass){ klass.$prototyping = true; var proto = new klass; delete klass.$prototyping; return proto; }; Class.implement('implement', implement.overloadSetter()); Class.Mutators = { Extends: function(parent){ this.parent = parent; this.prototype = getInstance(parent); }, Implements: function(items){ Array.from(items).each(function(item){ var instance = new item; for (var key in instance) implement.call(this, key, instance[key], true); }, this); } }; })(); /* --- name: Class.Extras description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks. license: MIT-style license. requires: Class provides: [Class.Extras, Chain, Events, Options] ... */ (function(){ this.Chain = new Class({ $chain: [], chain: function(){ this.$chain.append(Array.flatten(arguments)); return this; }, callChain: function(){ return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false; }, clearChain: function(){ this.$chain.empty(); return this; } }); var removeOn = function(string){ return string.replace(/^on([A-Z])/, function(full, first){ return first.toLowerCase(); }); }; this.Events = new Class({ $events: {}, addEvent: function(type, fn, internal){ type = removeOn(type); this.$events[type] = (this.$events[type] || []).include(fn); if (internal) fn.internal = true; return this; }, addEvents: function(events){ for (var type in events) this.addEvent(type, events[type]); return this; }, fireEvent: function(type, args, delay){ type = removeOn(type); var events = this.$events[type]; if (!events) return this; args = Array.from(args); events.each(function(fn){ if (delay) fn.delay(delay, this, args); else fn.apply(this, args); }, this); return this; }, removeEvent: function(type, fn){ type = removeOn(type); var events = this.$events[type]; if (events && !fn.internal){ var index = events.indexOf(fn); if (index != -1) delete events[index]; } return this; }, removeEvents: function(events){ var type; if (typeOf(events) == 'object'){ for (type in events) this.removeEvent(type, events[type]); return this; } if (events) events = removeOn(events); for (type in this.$events){ if (events && events != type) continue; var fns = this.$events[type]; for (var i = fns.length; i--;) if (i in fns){ this.removeEvent(type, fns[i]); } } return this; } }); this.Options = new Class({ setOptions: function(){ var options = this.options = Object.merge.apply(null, [{}, this.options].append(arguments)); if (this.addEvent) for (var option in options){ if (typeOf(options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue; this.addEvent(option, options[option]); delete options[option]; } return this; } }); })(); /* --- name: Slick.Parser description: Standalone CSS3 Selector parser provides: Slick.Parser ... */ ;(function(){ var parsed, separatorIndex, combinatorIndex, reversed, cache = {}, reverseCache = {}, reUnescape = /\\/g; var parse = function(expression, isReversed){ if (expression == null) return null; if (expression.Slick === true) return expression; expression = ('' + expression).replace(/^\s+|\s+$/g, ''); reversed = !!isReversed; var currentCache = (reversed) ? reverseCache : cache; if (currentCache[expression]) return currentCache[expression]; parsed = { Slick: true, expressions: [], raw: expression, reverse: function(){ return parse(this.raw, true); } }; separatorIndex = -1; while (expression != (expression = expression.replace(regexp, parser))); parsed.length = parsed.expressions.length; return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed; }; var reverseCombinator = function(combinator){ if (combinator === '!') return ' '; else if (combinator === ' ') return '!'; else if ((/^!/).test(combinator)) return combinator.replace(/^!/, ''); else return '!' + combinator; }; var reverse = function(expression){ var expressions = expression.expressions; for (var i = 0; i < expressions.length; i++){ var exp = expressions[i]; var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)}; for (var j = 0; j < exp.length; j++){ var cexp = exp[j]; if (!cexp.reverseCombinator) cexp.reverseCombinator = ' '; cexp.combinator = cexp.reverseCombinator; delete cexp.reverseCombinator; } exp.reverse().push(last); } return expression; }; var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){ return '\\' + match; }); }; var regexp = new RegExp( /* #!/usr/bin/env ruby puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'') __END__ "(?x)^(?:\ \\s* ( , ) \\s* # Separator \n\ | \\s* ( <combinator>+ ) \\s* # Combinator \n\ | ( \\s+ ) # CombinatorChildren \n\ | ( <unicode>+ | \\* ) # Tag \n\ | \\# ( <unicode>+ ) # ID \n\ | \\. ( <unicode>+ ) # ClassName \n\ | # Attribute \n\ \\[ \ \\s* (<unicode1>+) (?: \ \\s* ([*^$!~|]?=) (?: \ \\s* (?:\ ([\"']?)(.*?)\\9 \ )\ ) \ )? \\s* \ \\](?!\\]) \n\ | :+ ( <unicode>+ )(?:\ \\( (?:\ (?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\ ) \\)\ )?\ )" */ "^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)" .replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']') .replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])') .replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])') ); function parser( rawMatch, separator, combinator, combinatorChildren, tagName, id, className, attributeKey, attributeOperator, attributeQuote, attributeValue, pseudoMarker, pseudoClass, pseudoQuote, pseudoClassQuotedValue, pseudoClassValue ){ if (separator || separatorIndex === -1){ parsed.expressions[++separatorIndex] = []; combinatorIndex = -1; if (separator) return ''; } if (combinator || combinatorChildren || combinatorIndex === -1){ combinator = combinator || ' '; var currentSeparator = parsed.expressions[separatorIndex]; if (reversed && currentSeparator[combinatorIndex]) currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator); currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'}; } var currentParsed = parsed.expressions[separatorIndex][combinatorIndex]; if (tagName){ currentParsed.tag = tagName.replace(reUnescape, ''); } else if (id){ currentParsed.id = id.replace(reUnescape, ''); } else if (className){ className = className.replace(reUnescape, ''); if (!currentParsed.classList) currentParsed.classList = []; if (!currentParsed.classes) currentParsed.classes = []; currentParsed.classList.push(className); currentParsed.classes.push({ value: className, regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)') }); } else if (pseudoClass){ pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue; pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null; if (!currentParsed.pseudos) currentParsed.pseudos = []; currentParsed.pseudos.push({ key: pseudoClass.replace(reUnescape, ''), value: pseudoClassValue, type: pseudoMarker.length == 1 ? 'class' : 'element' }); } else if (attributeKey){ attributeKey = attributeKey.replace(reUnescape, ''); attributeValue = (attributeValue || '').replace(reUnescape, ''); var test, regexp; switch (attributeOperator){ case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break; case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break; case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break; case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break; case '=' : test = function(value){ return attributeValue == value; }; break; case '*=' : test = function(value){ return value && value.indexOf(attributeValue) > -1; }; break; case '!=' : test = function(value){ return attributeValue != value; }; break; default : test = function(value){ return !!value; }; } if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){ return false; }; if (!test) test = function(value){ return value && regexp.test(value); }; if (!currentParsed.attributes) currentParsed.attributes = []; currentParsed.attributes.push({ key: attributeKey, operator: attributeOperator, value: attributeValue, test: test }); } return ''; }; // Slick NS var Slick = (this.Slick || {}); Slick.parse = function(expression){ return parse(expression); }; Slick.escapeRegExp = escapeRegExp; if (!this.Slick) this.Slick = Slick; }).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this); /* --- name: Slick.Finder description: The new, superfast css selector engine. provides: Slick.Finder requires: Slick.Parser ... */ ;(function(){ var local = {}, featuresCache = {}, toString = Object.prototype.toString; // Feature / Bug detection local.isNativeCode = function(fn){ return (/\{\s*\[native code\]\s*\}/).test('' + fn); }; local.isXML = function(document){ return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') || (document.nodeType == 9 && document.documentElement.nodeName != 'HTML'); }; local.setDocument = function(document){ // convert elements / window arguments to document. if document cannot be extrapolated, the function returns. var nodeType = document.nodeType; if (nodeType == 9); // document else if (nodeType) document = document.ownerDocument; // node else if (document.navigator) document = document.document; // window else return; // check if it's the old document if (this.document === document) return; this.document = document; // check if we have done feature detection on this document before var root = document.documentElement, rootUid = this.getUIDXML(root), features = featuresCache[rootUid], feature; if (features){ for (feature in features){ this[feature] = features[feature]; } return; } features = featuresCache[rootUid] = {}; features.root = root; features.isXMLDocument = this.isXML(document); features.brokenStarGEBTN = features.starSelectsClosedQSA = features.idGetsName = features.brokenMixedCaseQSA = features.brokenGEBCN = features.brokenCheckedQSA = features.brokenEmptyAttributeQSA = features.isHTMLDocument = features.nativeMatchesSelector = false; var starSelectsClosed, starSelectsComments, brokenSecondClassNameGEBCN, cachedGetElementsByClassName, brokenFormAttributeGetter; var selected, id = 'slick_uniqueid'; var testNode = document.createElement('div'); var testRoot = document.body || document.getElementsByTagName('body')[0] || root; testRoot.appendChild(testNode); // on non-HTML documents innerHTML and getElementsById doesnt work properly try { testNode.innerHTML = '<a id="'+id+'"></a>'; features.isHTMLDocument = !!document.getElementById(id); } catch(e){}; if (features.isHTMLDocument){ testNode.style.display = 'none'; // IE returns comment nodes for getElementsByTagName('*') for some documents testNode.appendChild(document.createComment('')); starSelectsComments = (testNode.getElementsByTagName('*').length > 1); // IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents try { testNode.innerHTML = 'foo</foo>'; selected = testNode.getElementsByTagName('*'); starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/'); } catch(e){}; features.brokenStarGEBTN = starSelectsComments || starSelectsClosed; // IE returns elements with the name instead of just id for getElementsById for some documents try { testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>'; features.idGetsName = document.getElementById(id) === testNode.firstChild; } catch(e){}; if (testNode.getElementsByClassName){ // Safari 3.2 getElementsByClassName caches results try { testNode.innerHTML = '<a class="f"></a><a class="b"></a>'; testNode.getElementsByClassName('b').length; testNode.firstChild.className = 'b'; cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2); } catch(e){}; // Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one try { testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>'; brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2); } catch(e){}; features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN; } if (testNode.querySelectorAll){ // IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents try { testNode.innerHTML = 'foo</foo>'; selected = testNode.querySelectorAll('*'); features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/'); } catch(e){}; // Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode try { testNode.innerHTML = '<a class="MiX"></a>'; features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length; } catch(e){}; // Webkit and Opera dont return selected options on querySelectorAll try { testNode.innerHTML = '<select><option selected="selected">a</option></select>'; features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0); } catch(e){}; // IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll try { testNode.innerHTML = '<a class=""></a>'; features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0); } catch(e){}; } // IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input try { testNode.innerHTML = '<form action="s"><input id="action"/></form>'; brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's'); } catch(e){}; // native matchesSelector function features.nativeMatchesSelector = root.matchesSelector || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector; if (features.nativeMatchesSelector) try { // if matchesSelector trows errors on incorrect sintaxes we can use it features.nativeMatchesSelector.call(root, ':slick'); features.nativeMatchesSelector = null; } catch(e){}; } try { root.slick_expando = 1; delete root.slick_expando; features.getUID = this.getUIDHTML; } catch(e) { features.getUID = this.getUIDXML; } testRoot.removeChild(testNode); testNode = selected = testRoot = null; // getAttribute features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){ var method = this.attributeGetters[name]; if (method) return method.call(node); var attributeNode = node.getAttributeNode(name); return (attributeNode) ? attributeNode.nodeValue : null; } : function(node, name){ var method = this.attributeGetters[name]; return (method) ? method.call(node) : node.getAttribute(name); }; // hasAttribute features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute) { return node.hasAttribute(attribute); } : function(node, attribute) { node = node.getAttributeNode(attribute); return !!(node && (node.specified || node.nodeValue)); }; // contains // FIXME: Add specs: local.contains should be different for xml and html documents? var nativeRootContains = root && this.isNativeCode(root.contains), nativeDocumentContains = document && this.isNativeCode(document.contains); features.contains = (nativeRootContains && nativeDocumentContains) ? function(context, node){ return context.contains(node); } : (nativeRootContains && !nativeDocumentContains) ? function(context, node){ // IE8 does not have .contains on document. return context === node || ((context === document) ? document.documentElement : context).contains(node); } : (root && root.compareDocumentPosition) ? function(context, node){ return context === node || !!(context.compareDocumentPosition(node) & 16); } : function(context, node){ if (node) do { if (node === context) return true; } while ((node = node.parentNode)); return false; }; // document order sorting // credits to Sizzle (http://sizzlejs.com/) features.documentSorter = (root.compareDocumentPosition) ? function(a, b){ if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0; return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; } : ('sourceIndex' in root) ? function(a, b){ if (!a.sourceIndex || !b.sourceIndex) return 0; return a.sourceIndex - b.sourceIndex; } : (document.createRange) ? function(a, b){ if (!a.ownerDocument || !b.ownerDocument) return 0; var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); return aRange.compareBoundaryPoints(Range.START_TO_END, bRange); } : null ; root = null; for (feature in features){ this[feature] = features[feature]; } }; // Main Method var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/, reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/, qsaFailExpCache = {}; local.search = function(context, expression, append, first){ var found = this.found = (first) ? null : (append || []); if (!context) return found; else if (context.navigator) context = context.document; // Convert the node from a window to a document else if (!context.nodeType) return found; // setup var parsed, i, uniques = this.uniques = {}, hasOthers = !!(append && append.length), contextIsDocument = (context.nodeType == 9); if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context); // avoid duplicating items already in the append array if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true; // expression checks if (typeof expression == 'string'){ // expression is a string /*<simple-selectors-override>*/ var simpleSelector = expression.match(reSimpleSelector); simpleSelectors: if (simpleSelector) { var symbol = simpleSelector[1], name = simpleSelector[2], node, nodes; if (!symbol){ if (name == '*' && this.brokenStarGEBTN) break simpleSelectors; nodes = context.getElementsByTagName(name); if (first) return nodes[0] || null; for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } else if (symbol == '#'){ if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors; node = context.getElementById(name); if (!node) return found; if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors; if (first) return node || null; if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } else if (symbol == '.'){ if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors; if (context.getElementsByClassName && !this.brokenGEBCN){ nodes = context.getElementsByClassName(name); if (first) return nodes[0] || null; for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } else { var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)'); nodes = context.getElementsByTagName('*'); for (i = 0; node = nodes[i++];){ className = node.className; if (!(className && matchClass.test(className))) continue; if (first) return node; if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } } if (hasOthers) this.sort(found); return (first) ? null : found; } /*</simple-selectors-override>*/ /*<query-selector-override>*/ querySelector: if (context.querySelectorAll) { if (!this.isHTMLDocument || qsaFailExpCache[expression] //TODO: only skip when expression is actually mixed case || this.brokenMixedCaseQSA || (this.brokenCheckedQSA && expression.indexOf(':checked') > -1) || (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression)) || (!contextIsDocument //Abort when !contextIsDocument and... // there are multiple expressions in the selector // since we currently only fix non-document rooted QSA for single expression selectors && expression.indexOf(',') > -1 ) || Slick.disableQSA ) break querySelector; var _expression = expression, _context = context; if (!contextIsDocument){ // non-document rooted QSA // credits to Andrew Dupont var currentId = _context.getAttribute('id'), slickid = 'slickid__'; _context.setAttribute('id', slickid); _expression = '#' + slickid + ' ' + _expression; context = _context.parentNode; } try { if (first) return context.querySelector(_expression) || null; else nodes = context.querySelectorAll(_expression); } catch(e) { qsaFailExpCache[expression] = 1; break querySelector; } finally { if (!contextIsDocument){ if (currentId) _context.setAttribute('id', currentId); else _context.removeAttribute('id'); context = _context; } } if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){ if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node); } else for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } if (hasOthers) this.sort(found); return found; } /*</query-selector-override>*/ parsed = this.Slick.parse(expression); if (!parsed.length) return found; } else if (expression == null){ // there is no expression return found; } else if (expression.Slick){ // expression is a parsed Slick object parsed = expression; } else if (this.contains(context.documentElement || context, expression)){ // expression is a node (found) ? found.push(expression) : found = expression; return found; } else { // other junk return found; } /*<pseudo-selectors>*//*<nth-pseudo-selectors>*/ // cache elements for the nth selectors this.posNTH = {}; this.posNTHLast = {}; this.posNTHType = {}; this.posNTHTypeLast = {}; /*</nth-pseudo-selectors>*//*</pseudo-selectors>*/ // if append is null and there is only a single selector with one expression use pushArray, else use pushUID this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID; if (found == null) found = []; // default engine var j, m, n; var combinator, tag, id, classList, classes, attributes, pseudos; var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions; search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){ combinator = 'combinator:' + currentBit.combinator; if (!this[combinator]) continue search; tag = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase(); id = currentBit.id; classList = currentBit.classList; classes = currentBit.classes; attributes = currentBit.attributes; pseudos = currentBit.pseudos; lastBit = (j === (currentExpression.length - 1)); this.bitUniques = {}; if (lastBit){ this.uniques = uniques; this.found = found; } else { this.uniques = {}; this.found = []; } if (j === 0){ this[combinator](context, tag, id, classes, attributes, pseudos, classList); if (first && lastBit && found.length) break search; } else { if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){ this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList); if (found.length) break search; } else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList); } currentItems = this.found; } // should sort if there are nodes in append and if you pass multiple expressions. if (hasOthers || (parsed.expressions.length > 1)) this.sort(found); return (first) ? (found[0] || null) : found; }; // Utils local.uidx = 1; local.uidk = 'slick-uniqueid'; local.getUIDXML = function(node){ var uid = node.getAttribute(this.uidk); if (!uid){ uid = this.uidx++; node.setAttribute(this.uidk, uid); } return uid; }; local.getUIDHTML = function(node){ return node.uniqueNumber || (node.uniqueNumber = this.uidx++); }; // sort based on the setDocument documentSorter method. local.sort = function(results){ if (!this.documentSorter) return results; results.sort(this.documentSorter); return results; }; /*<pseudo-selectors>*//*<nth-pseudo-selectors>*/ local.cacheNTH = {}; local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/; local.parseNTHArgument = function(argument){ var parsed = argument.match(this.matchNTH); if (!parsed) return false; var special = parsed[2] || false; var a = parsed[1] || 1; if (a == '-') a = -1; var b = +parsed[3] || 0; parsed = (special == 'n') ? {a: a, b: b} : (special == 'odd') ? {a: 2, b: 1} : (special == 'even') ? {a: 2, b: 0} : {a: 0, b: a}; return (this.cacheNTH[argument] = parsed); }; local.createNTHPseudo = function(child, sibling, positions, ofType){ return function(node, argument){ var uid = this.getUID(node); if (!this[positions][uid]){ var parent = node.parentNode; if (!parent) return false; var el = parent[child], count = 1; if (ofType){ var nodeName = node.nodeName; do { if (el.nodeName != nodeName) continue; this[positions][this.getUID(el)] = count++; } while ((el = el[sibling])); } else { do { if (el.nodeType != 1) continue; this[positions][this.getUID(el)] = count++; } while ((el = el[sibling])); } } argument = argument || 'n'; var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument); if (!parsed) return false; var a = parsed.a, b = parsed.b, pos = this[positions][uid]; if (a == 0) return b == pos; if (a > 0){ if (pos < b) return false; } else { if (b < pos) return false; } return ((pos - b) % a) == 0; }; }; /*</nth-pseudo-selectors>*//*</pseudo-selectors>*/ local.pushArray = function(node, tag, id, classes, attributes, pseudos){ if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node); }; local.pushUID = function(node, tag, id, classes, attributes, pseudos){ var uid = this.getUID(node); if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){ this.uniques[uid] = true; this.found.push(node); } }; local.matchNode = function(node, selector){ if (this.isHTMLDocument && this.nativeMatchesSelector){ try { return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]')); } catch(matchError) {} } var parsed = this.Slick.parse(selector); if (!parsed) return true; // simple (single) selectors var expressions = parsed.expressions, simpleExpCounter = 0, i; for (i = 0; (currentExpression = expressions[i]); i++){ if (currentExpression.length == 1){ var exp = currentExpression[0]; if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true; simpleExpCounter++; } } if (simpleExpCounter == parsed.length) return false; var nodes = this.search(this.document, parsed), item; for (i = 0; item = nodes[i++];){ if (item === node) return true; } return false; }; local.matchPseudo = function(node, name, argument){ var pseudoName = 'pseudo:' + name; if (this[pseudoName]) return this[pseudoName](node, argument); var attribute = this.getAttribute(node, name); return (argument) ? argument == attribute : !!attribute; }; local.matchSelector = function(node, tag, id, classes, attributes, pseudos){ if (tag){ var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase(); if (tag == '*'){ if (nodeName < '@') return false; // Fix for comment nodes and closed nodes } else { if (nodeName != tag) return false; } } if (id && node.getAttribute('id') != id) return false; var i, part, cls; if (classes) for (i = classes.length; i--;){ cls = this.getAttribute(node, 'class'); if (!(cls && classes[i].regexp.test(cls))) return false; } if (attributes) for (i = attributes.length; i--;){ part = attributes[i]; if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false; } if (pseudos) for (i = pseudos.length; i--;){ part = pseudos[i]; if (!this.matchPseudo(node, part.key, part.value)) return false; } return true; }; var combinators = { ' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level var i, item, children; if (this.isHTMLDocument){ getById: if (id){ item = this.document.getElementById(id); if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){ // all[id] returns all the elements with that name or id inside node // if theres just one it will return the element, else it will be a collection children = node.all[id]; if (!children) return; if (!children[0]) children = [children]; for (i = 0; item = children[i++];){ var idNode = item.getAttributeNode('id'); if (idNode && idNode.nodeValue == id){ this.push(item, tag, null, classes, attributes, pseudos); break; } } return; } if (!item){ // if the context is in the dom we return, else we will try GEBTN, breaking the getById label if (this.contains(this.root, node)) return; else break getById; } else if (this.document !== node && !this.contains(node, item)) return; this.push(item, tag, null, classes, attributes, pseudos); return; } getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){ children = node.getElementsByClassName(classList.join(' ')); if (!(children && children.length)) break getByClass; for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos); return; } } getByTag: { children = node.getElementsByTagName(tag); if (!(children && children.length)) break getByTag; if (!this.brokenStarGEBTN) tag = null; for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos); } }, '>': function(node, tag, id, classes, attributes, pseudos){ // direct children if ((node = node.firstChild)) do { if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); } while ((node = node.nextSibling)); }, '+': function(node, tag, id, classes, attributes, pseudos){ // next sibling while ((node = node.nextSibling)) if (node.nodeType == 1){ this.push(node, tag, id, classes, attributes, pseudos); break; } }, '^': function(node, tag, id, classes, attributes, pseudos){ // first child node = node.firstChild; if (node){ if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); else this['combinator:+'](node, tag, id, classes, attributes, pseudos); } }, '~': function(node, tag, id, classes, attributes, pseudos){ // next siblings while ((node = node.nextSibling)){ if (node.nodeType != 1) continue; var uid = this.getUID(node); if (this.bitUniques[uid]) break; this.bitUniques[uid] = true; this.push(node, tag, id, classes, attributes, pseudos); } }, '++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling this['combinator:+'](node, tag, id, classes, attributes, pseudos); this['combinator:!+'](node, tag, id, classes, attributes, pseudos); }, '~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings this['combinator:~'](node, tag, id, classes, attributes, pseudos); this['combinator:!~'](node, tag, id, classes, attributes, pseudos); }, '!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos); }, '!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level) node = node.parentNode; if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos); }, '!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling while ((node = node.previousSibling)) if (node.nodeType == 1){ this.push(node, tag, id, classes, attributes, pseudos); break; } }, '!^': function(node, tag, id, classes, attributes, pseudos){ // last child node = node.lastChild; if (node){ if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); else this['combinator:!+'](node, tag, id, classes, attributes, pseudos); } }, '!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings while ((node = node.previousSibling)){ if (node.nodeType != 1) continue; var uid = this.getUID(node); if (this.bitUniques[uid]) break; this.bitUniques[uid] = true; this.push(node, tag, id, classes, attributes, pseudos); } } }; for (var c in combinators) local['combinator:' + c] = combinators[c]; var pseudos = { /*<pseudo-selectors>*/ 'empty': function(node){ var child = node.firstChild; return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length; }, 'not': function(node, expression){ return !this.matchNode(node, expression); }, 'contains': function(node, text){ return (node.innerText || node.textContent || '').indexOf(text) > -1; }, 'first-child': function(node){ while ((node = node.previousSibling)) if (node.nodeType == 1) return false; return true; }, 'last-child': function(node){ while ((node = node.nextSibling)) if (node.nodeType == 1) return false; return true; }, 'only-child': function(node){ var prev = node; while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false; var next = node; while ((next = next.nextSibling)) if (next.nodeType == 1) return false; return true; }, /*<nth-pseudo-selectors>*/ 'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'), 'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'), 'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true), 'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true), 'index': function(node, index){ return this['pseudo:nth-child'](node, '' + (index + 1)); }, 'even': function(node){ return this['pseudo:nth-child'](node, '2n'); }, 'odd': function(node){ return this['pseudo:nth-child'](node, '2n+1'); }, /*</nth-pseudo-selectors>*/ /*<of-type-pseudo-selectors>*/ 'first-of-type': function(node){ var nodeName = node.nodeName; while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false; return true; }, 'last-of-type': function(node){ var nodeName = node.nodeName; while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false; return true; }, 'only-of-type': function(node){ var prev = node, nodeName = node.nodeName; while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false; var next = node; while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false; return true; }, /*</of-type-pseudo-selectors>*/ // custom pseudos 'enabled': function(node){ return !node.disabled; }, 'disabled': function(node){ return node.disabled; }, 'checked': function(node){ return node.checked || node.selected; }, 'focus': function(node){ return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex')); }, 'root': function(node){ return (node === this.root); }, 'selected': function(node){ return node.selected; } /*</pseudo-selectors>*/ }; for (var p in pseudos) local['pseudo:' + p] = pseudos[p]; // attributes methods var attributeGetters = local.attributeGetters = { 'for': function(){ return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for'); }, 'href': function(){ return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href'); }, 'style': function(){ return (this.style) ? this.style.cssText : this.getAttribute('style'); }, 'tabindex': function(){ var attributeNode = this.getAttributeNode('tabindex'); return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null; }, 'type': function(){ return this.getAttribute('type'); }, 'maxlength': function(){ var attributeNode = this.getAttributeNode('maxLength'); return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null; } }; attributeGetters.MAXLENGTH = attributeGetters.maxLength = attributeGetters.maxlength; // Slick var Slick = local.Slick = (this.Slick || {}); Slick.version = '1.1.7'; // Slick finder Slick.search = function(context, expression, append){ return local.search(context, expression, append); }; Slick.find = function(context, expression){ return local.search(context, expression, null, true); }; // Slick containment checker Slick.contains = function(container, node){ local.setDocument(container); return local.contains(container, node); }; // Slick attribute getter Slick.getAttribute = function(node, name){ local.setDocument(node); return local.getAttribute(node, name); }; Slick.hasAttribute = function(node, name){ local.setDocument(node); return local.hasAttribute(node, name); }; // Slick matcher Slick.match = function(node, selector){ if (!(node && selector)) return false; if (!selector || selector === node) return true; local.setDocument(node); return local.matchNode(node, selector); }; // Slick attribute accessor Slick.defineAttributeGetter = function(name, fn){ local.attributeGetters[name] = fn; return this; }; Slick.lookupAttributeGetter = function(name){ return local.attributeGetters[name]; }; // Slick pseudo accessor Slick.definePseudo = function(name, fn){ local['pseudo:' + name] = function(node, argument){ return fn.call(node, argument); }; return this; }; Slick.lookupPseudo = function(name){ var pseudo = local['pseudo:' + name]; if (pseudo) return function(argument){ return pseudo.call(this, argument); }; return null; }; // Slick overrides accessor Slick.override = function(regexp, fn){ local.override(regexp, fn); return this; }; Slick.isXML = local.isXML; Slick.uidOf = function(node){ return local.getUIDHTML(node); }; if (!this.Slick) this.Slick = Slick; }).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this); /* --- name: Element description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements. license: MIT-style license. requires: [Window, Document, Array, String, Function, Object, Number, Slick.Parser, Slick.Finder] provides: [Element, Elements, $, $$, Iframe, Selectors] ... */ var Element = function(tag, props){ var konstructor = Element.Constructors[tag]; if (konstructor) return konstructor(props); if (typeof tag != 'string') return document.id(tag).set(props); if (!props) props = {}; if (!(/^[\w-]+$/).test(tag)){ var parsed = Slick.parse(tag).expressions[0][0]; tag = (parsed.tag == '*') ? 'div' : parsed.tag; if (parsed.id && props.id == null) props.id = parsed.id; var attributes = parsed.attributes; if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){ attr = attributes[i]; if (props[attr.key] != null) continue; if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value; else if (!attr.value && !attr.operator) props[attr.key] = true; } if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' '); } return document.newElement(tag, props); }; if (Browser.Element){ Element.prototype = Browser.Element.prototype; // IE8 and IE9 require the wrapping. Element.prototype._fireEvent = (function(fireEvent){ return function(type, event){ return fireEvent.call(this, type, event); }; })(Element.prototype.fireEvent); } new Type('Element', Element).mirror(function(name){ if (Array.prototype[name]) return; var obj = {}; obj[name] = function(){ var results = [], args = arguments, elements = true; for (var i = 0, l = this.length; i < l; i++){ var element = this[i], result = results[i] = element[name].apply(element, args); elements = (elements && typeOf(result) == 'element'); } return (elements) ? new Elements(results) : results; }; Elements.implement(obj); }); if (!Browser.Element){ Element.parent = Object; Element.Prototype = { '$constructor': Element, '$family': Function.from('element').hide() }; Element.mirror(function(name, method){ Element.Prototype[name] = method; }); } Element.Constructors = {}; var IFrame = new Type('IFrame', function(){ var params = Array.link(arguments, { properties: Type.isObject, iframe: function(obj){ return (obj != null); } }); var props = params.properties || {}, iframe; if (params.iframe) iframe = document.id(params.iframe); var onload = props.onload || function(){}; delete props.onload; props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick(); iframe = new Element(iframe || 'iframe', props); var onLoad = function(){ onload.call(iframe.contentWindow); }; if (window.frames[props.id]) onLoad(); else iframe.addListener('load', onLoad); return iframe; }); var Elements = this.Elements = function(nodes){ if (nodes && nodes.length){ var uniques = {}, node; for (var i = 0; node = nodes[i++];){ var uid = Slick.uidOf(node); if (!uniques[uid]){ uniques[uid] = true; this.push(node); } } } }; Elements.prototype = {length: 0}; Elements.parent = Array; new Type('Elements', Elements).implement({ filter: function(filter, bind){ if (!filter) return this; return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){ return item.match(filter); } : filter, bind)); }.protect(), push: function(){ var length = this.length; for (var i = 0, l = arguments.length; i < l; i++){ var item = document.id(arguments[i]); if (item) this[length++] = item; } return (this.length = length); }.protect(), unshift: function(){ var items = []; for (var i = 0, l = arguments.length; i < l; i++){ var item = document.id(arguments[i]); if (item) items.push(item); } return Array.prototype.unshift.apply(this, items); }.protect(), concat: function(){ var newElements = new Elements(this); for (var i = 0, l = arguments.length; i < l; i++){ var item = arguments[i]; if (Type.isEnumerable(item)) newElements.append(item); else newElements.push(item); } return newElements; }.protect(), append: function(collection){ for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]); return this; }.protect(), empty: function(){ while (this.length) delete this[--this.length]; return this; }.protect() }); (function(){ // FF, IE var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2}; splice.call(object, 1, 1); if (object[1] == 1) Elements.implement('splice', function(){ var length = this.length; var result = splice.apply(this, arguments); while (length >= this.length) delete this[length--]; return result; }.protect()); Array.forEachMethod(function(method, name){ Elements.implement(name, method); }); Array.mirror(Elements); /*<ltIE8>*/ var createElementAcceptsHTML; try { createElementAcceptsHTML = (document.createElement('<input name=x>').name == 'x'); } catch (e){} var escapeQuotes = function(html){ return ('' + html).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); }; /*</ltIE8>*/ Document.implement({ newElement: function(tag, props){ if (props && props.checked != null) props.defaultChecked = props.checked; /*<ltIE8>*/// Fix for readonly name and type properties in IE < 8 if (createElementAcceptsHTML && props){ tag = '<' + tag; if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"'; if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"'; tag += '>'; delete props.name; delete props.type; } /*</ltIE8>*/ return this.id(this.createElement(tag)).set(props); } }); })(); (function(){ Slick.uidOf(window); Slick.uidOf(document); Document.implement({ newTextNode: function(text){ return this.createTextNode(text); }, getDocument: function(){ return this; }, getWindow: function(){ return this.window; }, id: (function(){ var types = { string: function(id, nocash, doc){ id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1')); return (id) ? types.element(id, nocash) : null; }, element: function(el, nocash){ Slick.uidOf(el); if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){ var fireEvent = el.fireEvent; // wrapping needed in IE7, or else crash el._fireEvent = function(type, event){ return fireEvent(type, event); }; Object.append(el, Element.Prototype); } return el; }, object: function(obj, nocash, doc){ if (obj.toElement) return types.element(obj.toElement(doc), nocash); return null; } }; types.textnode = types.whitespace = types.window = types.document = function(zero){ return zero; }; return function(el, nocash, doc){ if (el && el.$family && el.uniqueNumber) return el; var type = typeOf(el); return (types[type]) ? types[type](el, nocash, doc || document) : null; }; })() }); if (window.$ == null) Window.implement('$', function(el, nc){ return document.id(el, nc, this.document); }); Window.implement({ getDocument: function(){ return this.document; }, getWindow: function(){ return this; } }); [Document, Element].invoke('implement', { getElements: function(expression){ return Slick.search(this, expression, new Elements); }, getElement: function(expression){ return document.id(Slick.find(this, expression)); } }); var contains = {contains: function(element){ return Slick.contains(this, element); }}; if (!document.contains) Document.implement(contains); if (!document.createElement('div').contains) Element.implement(contains); // tree walking var injectCombinator = function(expression, combinator){ if (!expression) return combinator; expression = Object.clone(Slick.parse(expression)); var expressions = expression.expressions; for (var i = expressions.length; i--;) expressions[i][0].combinator = combinator; return expression; }; Object.forEach({ getNext: '~', getPrevious: '!~', getParent: '!' }, function(combinator, method){ Element.implement(method, function(expression){ return this.getElement(injectCombinator(expression, combinator)); }); }); Object.forEach({ getAllNext: '~', getAllPrevious: '!~', getSiblings: '~~', getChildren: '>', getParents: '!' }, function(combinator, method){ Element.implement(method, function(expression){ return this.getElements(injectCombinator(expression, combinator)); }); }); Element.implement({ getFirst: function(expression){ return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]); }, getLast: function(expression){ return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast()); }, getWindow: function(){ return this.ownerDocument.window; }, getDocument: function(){ return this.ownerDocument; }, getElementById: function(id){ return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1'))); }, match: function(expression){ return !expression || Slick.match(this, expression); } }); if (window.$$ == null) Window.implement('$$', function(selector){ if (arguments.length == 1){ if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements); else if (Type.isEnumerable(selector)) return new Elements(selector); } return new Elements(arguments); }); // Inserters var inserters = { before: function(context, element){ var parent = element.parentNode; if (parent) parent.insertBefore(context, element); }, after: function(context, element){ var parent = element.parentNode; if (parent) parent.insertBefore(context, element.nextSibling); }, bottom: function(context, element){ element.appendChild(context); }, top: function(context, element){ element.insertBefore(context, element.firstChild); } }; inserters.inside = inserters.bottom; // getProperty / setProperty var propertyGetters = {}, propertySetters = {}; // properties var properties = {}; Array.forEach([ 'type', 'value', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'rowSpan', 'tabIndex', 'useMap' ], function(property){ properties[property.toLowerCase()] = property; }); properties.html = 'innerHTML'; properties.text = (document.createElement('div').textContent == null) ? 'innerText': 'textContent'; Object.forEach(properties, function(real, key){ propertySetters[key] = function(node, value){ node[real] = value; }; propertyGetters[key] = function(node){ return node[real]; }; }); // Booleans var bools = [ 'compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readOnly', 'multiple', 'selected', 'noresize', 'defer', 'defaultChecked', 'autofocus', 'controls', 'autoplay', 'loop' ]; var booleans = {}; Array.forEach(bools, function(bool){ var lower = bool.toLowerCase(); booleans[lower] = bool; propertySetters[lower] = function(node, value){ node[bool] = !!value; }; propertyGetters[lower] = function(node){ return !!node[bool]; }; }); // Special cases Object.append(propertySetters, { 'class': function(node, value){ ('className' in node) ? node.className = (value || '') : node.setAttribute('class', value); }, 'for': function(node, value){ ('htmlFor' in node) ? node.htmlFor = value : node.setAttribute('for', value); }, 'style': function(node, value){ (node.style) ? node.style.cssText = value : node.setAttribute('style', value); }, 'value': function(node, value){ node.value = (value != null) ? value : ''; } }); propertyGetters['class'] = function(node){ return ('className' in node) ? node.className || null : node.getAttribute('class'); }; /* <webkit> */ var el = document.createElement('button'); // IE sets type as readonly and throws try { el.type = 'button'; } catch(e){} if (el.type != 'button') propertySetters.type = function(node, value){ node.setAttribute('type', value); }; el = null; /* </webkit> */ /*<IE>*/ var input = document.createElement('input'); input.value = 't'; input.type = 'submit'; if (input.value != 't') propertySetters.type = function(node, type){ var value = node.value; node.type = type; node.value = value; }; input = null; /*</IE>*/ /* getProperty, setProperty */ /* <ltIE9> */ var pollutesGetAttribute = (function(div){ div.random = 'attribute'; return (div.getAttribute('random') == 'attribute'); })(document.createElement('div')); /* <ltIE9> */ Element.implement({ setProperty: function(name, value){ var setter = propertySetters[name.toLowerCase()]; if (setter){ setter(this, value); } else { /* <ltIE9> */ if (pollutesGetAttribute) var attributeWhiteList = this.retrieve('$attributeWhiteList', {}); /* </ltIE9> */ if (value == null){ this.removeAttribute(name); /* <ltIE9> */ if (pollutesGetAttribute) delete attributeWhiteList[name]; /* </ltIE9> */ } else { this.setAttribute(name, '' + value); /* <ltIE9> */ if (pollutesGetAttribute) attributeWhiteList[name] = true; /* </ltIE9> */ } } return this; }, setProperties: function(attributes){ for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]); return this; }, getProperty: function(name){ var getter = propertyGetters[name.toLowerCase()]; if (getter) return getter(this); /* <ltIE9> */ if (pollutesGetAttribute){ var attr = this.getAttributeNode(name), attributeWhiteList = this.retrieve('$attributeWhiteList', {}); if (!attr) return null; if (attr.expando && !attributeWhiteList[name]){ var outer = this.outerHTML; // segment by the opening tag and find mention of attribute name if (outer.substr(0, outer.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(name) < 0) return null; attributeWhiteList[name] = true; } } /* </ltIE9> */ var result = Slick.getAttribute(this, name); return (!result && !Slick.hasAttribute(this, name)) ? null : result; }, getProperties: function(){ var args = Array.from(arguments); return args.map(this.getProperty, this).associate(args); }, removeProperty: function(name){ return this.setProperty(name, null); }, removeProperties: function(){ Array.each(arguments, this.removeProperty, this); return this; }, set: function(prop, value){ var property = Element.Properties[prop]; (property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value); }.overloadSetter(), get: function(prop){ var property = Element.Properties[prop]; return (property && property.get) ? property.get.apply(this) : this.getProperty(prop); }.overloadGetter(), erase: function(prop){ var property = Element.Properties[prop]; (property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop); return this; }, hasClass: function(className){ return this.className.clean().contains(className, ' '); }, addClass: function(className){ if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean(); return this; }, removeClass: function(className){ this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1'); return this; }, toggleClass: function(className, force){ if (force == null) force = !this.hasClass(className); return (force) ? this.addClass(className) : this.removeClass(className); }, adopt: function(){ var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length; if (length > 1) parent = fragment = document.createDocumentFragment(); for (var i = 0; i < length; i++){ var element = document.id(elements[i], true); if (element) parent.appendChild(element); } if (fragment) this.appendChild(fragment); return this; }, appendText: function(text, where){ return this.grab(this.getDocument().newTextNode(text), where); }, grab: function(el, where){ inserters[where || 'bottom'](document.id(el, true), this); return this; }, inject: function(el, where){ inserters[where || 'bottom'](this, document.id(el, true)); return this; }, replaces: function(el){ el = document.id(el, true); el.parentNode.replaceChild(this, el); return this; }, wraps: function(el, where){ el = document.id(el, true); return this.replaces(el).grab(el, where); }, getSelected: function(){ this.selectedIndex; // Safari 3.2.1 return new Elements(Array.from(this.options).filter(function(option){ return option.selected; })); }, toQueryString: function(){ var queryString = []; this.getElements('input, select, textarea').each(function(el){ var type = el.type; if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return; var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){ // IE return document.id(opt).get('value'); }) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value'); Array.from(value).each(function(val){ if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val)); }); }); return queryString.join('&'); } }); var collected = {}, storage = {}; var get = function(uid){ return (storage[uid] || (storage[uid] = {})); }; var clean = function(item){ var uid = item.uniqueNumber; if (item.removeEvents) item.removeEvents(); if (item.clearAttributes) item.clearAttributes(); if (uid != null){ delete collected[uid]; delete storage[uid]; } return item; }; var formProps = {input: 'checked', option: 'selected', textarea: 'value'}; Element.implement({ destroy: function(){ var children = clean(this).getElementsByTagName('*'); Array.each(children, clean); Element.dispose(this); return null; }, empty: function(){ Array.from(this.childNodes).each(Element.dispose); return this; }, dispose: function(){ return (this.parentNode) ? this.parentNode.removeChild(this) : this; }, clone: function(contents, keepid){ contents = contents !== false; var clone = this.cloneNode(contents), ce = [clone], te = [this], i; if (contents){ ce.append(Array.from(clone.getElementsByTagName('*'))); te.append(Array.from(this.getElementsByTagName('*'))); } for (i = ce.length; i--;){ var node = ce[i], element = te[i]; if (!keepid) node.removeAttribute('id'); /*<ltIE9>*/ if (node.clearAttributes){ node.clearAttributes(); node.mergeAttributes(element); node.removeAttribute('uniqueNumber'); if (node.options){ var no = node.options, eo = element.options; for (var j = no.length; j--;) no[j].selected = eo[j].selected; } } /*</ltIE9>*/ var prop = formProps[element.tagName.toLowerCase()]; if (prop && element[prop]) node[prop] = element[prop]; } /*<ltIE9>*/ if (Browser.ie){ var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object'); for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML; } /*</ltIE9>*/ return document.id(clone); } }); [Element, Window, Document].invoke('implement', { addListener: function(type, fn){ if (type == 'unload'){ var old = fn, self = this; fn = function(){ self.removeListener('unload', fn); old(); }; } else { collected[Slick.uidOf(this)] = this; } if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]); else this.attachEvent('on' + type, fn); return this; }, removeListener: function(type, fn){ if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]); else this.detachEvent('on' + type, fn); return this; }, retrieve: function(property, dflt){ var storage = get(Slick.uidOf(this)), prop = storage[property]; if (dflt != null && prop == null) prop = storage[property] = dflt; return prop != null ? prop : null; }, store: function(property, value){ var storage = get(Slick.uidOf(this)); storage[property] = value; return this; }, eliminate: function(property){ var storage = get(Slick.uidOf(this)); delete storage[property]; return this; } }); /*<ltIE9>*/ if (window.attachEvent && !window.addEventListener) window.addListener('unload', function(){ Object.each(collected, clean); if (window.CollectGarbage) CollectGarbage(); }); /*</ltIE9>*/ Element.Properties = {}; Element.Properties.style = { set: function(style){ this.style.cssText = style; }, get: function(){ return this.style.cssText; }, erase: function(){ this.style.cssText = ''; } }; Element.Properties.tag = { get: function(){ return this.tagName.toLowerCase(); } }; Element.Properties.html = { set: function(html){ if (html == null) html = ''; else if (typeOf(html) == 'array') html = html.join(''); this.innerHTML = html; }, erase: function(){ this.innerHTML = ''; } }; /*<ltIE9>*/ // technique by jdbarlett - http://jdbartlett.com/innershiv/ var div = document.createElement('div'); div.innerHTML = '<nav></nav>'; var supportsHTML5Elements = (div.childNodes.length == 1); if (!supportsHTML5Elements){ var tags = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' '), fragment = document.createDocumentFragment(), l = tags.length; while (l--) fragment.createElement(tags[l]); } div = null; /*</ltIE9>*/ /*<IE>*/ var supportsTableInnerHTML = Function.attempt(function(){ var table = document.createElement('table'); table.innerHTML = '<tr><td></td></tr>'; return true; }); /*<ltFF4>*/ var tr = document.createElement('tr'), html = '<td></td>'; tr.innerHTML = html; var supportsTRInnerHTML = (tr.innerHTML == html); tr = null; /*</ltFF4>*/ if (!supportsTableInnerHTML || !supportsTRInnerHTML || !supportsHTML5Elements){ Element.Properties.html.set = (function(set){ var translations = { table: [1, '<table>', '</table>'], select: [1, '<select>', '</select>'], tbody: [2, '<table><tbody>', '</tbody></table>'], tr: [3, '<table><tbody><tr>', '</tr></tbody></table>'] }; translations.thead = translations.tfoot = translations.tbody; return function(html){ var wrap = translations[this.get('tag')]; if (!wrap && !supportsHTML5Elements) wrap = [0, '', '']; if (!wrap) return set.call(this, html); var level = wrap[0], wrapper = document.createElement('div'), target = wrapper; if (!supportsHTML5Elements) fragment.appendChild(wrapper); wrapper.innerHTML = [wrap[1], html, wrap[2]].flatten().join(''); while (level--) target = target.firstChild; this.empty().adopt(target.childNodes); if (!supportsHTML5Elements) fragment.removeChild(wrapper); wrapper = null; }; })(Element.Properties.html.set); } /*</IE>*/ /*<ltIE9>*/ var testForm = document.createElement('form'); testForm.innerHTML = '<select><option>s</option></select>'; if (testForm.firstChild.value != 's') Element.Properties.value = { set: function(value){ var tag = this.get('tag'); if (tag != 'select') return this.setProperty('value', value); var options = this.getElements('option'); for (var i = 0; i < options.length; i++){ var option = options[i], attr = option.getAttributeNode('value'), optionValue = (attr && attr.specified) ? option.value : option.get('text'); if (optionValue == value) return option.selected = true; } }, get: function(){ var option = this, tag = option.get('tag'); if (tag != 'select' && tag != 'option') return this.getProperty('value'); if (tag == 'select' && !(option = option.getSelected()[0])) return ''; var attr = option.getAttributeNode('value'); return (attr && attr.specified) ? option.value : option.get('text'); } }; testForm = null; /*</ltIE9>*/ /*<IE>*/ if (document.createElement('div').getAttributeNode('id')) Element.Properties.id = { set: function(id){ this.id = this.getAttributeNode('id').value = id; }, get: function(){ return this.id || null; }, erase: function(){ this.id = this.getAttributeNode('id').value = ''; } }; /*</IE>*/ })(); /* --- name: Element.Style description: Contains methods for interacting with the styles of Elements in a fashionable way. license: MIT-style license. requires: Element provides: Element.Style ... */ (function(){ var html = document.html; //<ltIE9> // Check for oldIE, which does not remove styles when they're set to null var el = document.createElement('div'); el.style.color = 'red'; el.style.color = null; var doesNotRemoveStyles = el.style.color == 'red'; el = null; //</ltIE9> Element.Properties.styles = {set: function(styles){ this.setStyles(styles); }}; var hasOpacity = (html.style.opacity != null), hasFilter = (html.style.filter != null), reAlpha = /alpha\(opacity=([\d.]+)\)/i; var setVisibility = function(element, opacity){ element.store('$opacity', opacity); element.style.visibility = opacity > 0 || opacity == null ? 'visible' : 'hidden'; }; var setOpacity = (hasOpacity ? function(element, opacity){ element.style.opacity = opacity; } : (hasFilter ? function(element, opacity){ var style = element.style; if (!element.currentStyle || !element.currentStyle.hasLayout) style.zoom = 1; if (opacity == null || opacity == 1) opacity = ''; else opacity = 'alpha(opacity=' + (opacity * 100).limit(0, 100).round() + ')'; var filter = style.filter || element.getComputedStyle('filter') || ''; style.filter = reAlpha.test(filter) ? filter.replace(reAlpha, opacity) : filter + opacity; if (!style.filter) style.removeAttribute('filter'); } : setVisibility)); var getOpacity = (hasOpacity ? function(element){ var opacity = element.style.opacity || element.getComputedStyle('opacity'); return (opacity == '') ? 1 : opacity.toFloat(); } : (hasFilter ? function(element){ var filter = (element.style.filter || element.getComputedStyle('filter')), opacity; if (filter) opacity = filter.match(reAlpha); return (opacity == null || filter == null) ? 1 : (opacity[1] / 100); } : function(element){ var opacity = element.retrieve('$opacity'); if (opacity == null) opacity = (element.style.visibility == 'hidden' ? 0 : 1); return opacity; })); var floatName = (html.style.cssFloat == null) ? 'styleFloat' : 'cssFloat'; Element.implement({ getComputedStyle: function(property){ if (this.currentStyle) return this.currentStyle[property.camelCase()]; var defaultView = Element.getDocument(this).defaultView, computed = defaultView ? defaultView.getComputedStyle(this, null) : null; return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null; }, setStyle: function(property, value){ if (property == 'opacity'){ if (value != null) value = parseFloat(value); setOpacity(this, value); return this; } property = (property == 'float' ? floatName : property).camelCase(); if (typeOf(value) != 'string'){ var map = (Element.Styles[property] || '@').split(' '); value = Array.from(value).map(function(val, i){ if (!map[i]) return ''; return (typeOf(val) == 'number') ? map[i].replace('@', Math.round(val)) : val; }).join(' '); } else if (value == String(Number(value))){ value = Math.round(value); } this.style[property] = value; //<ltIE9> if ((value == '' || value == null) && doesNotRemoveStyles && this.style.removeAttribute){ this.style.removeAttribute(property); } //</ltIE9> return this; }, getStyle: function(property){ if (property == 'opacity') return getOpacity(this); property = (property == 'float' ? floatName : property).camelCase(); var result = this.style[property]; if (!result || property == 'zIndex'){ result = []; for (var style in Element.ShortStyles){ if (property != style) continue; for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s)); return result.join(' '); } result = this.getComputedStyle(property); } if (result){ result = String(result); var color = result.match(/rgba?\([\d\s,]+\)/); if (color) result = result.replace(color[0], color[0].rgbToHex()); } if (Browser.opera || Browser.ie){ if ((/^(height|width)$/).test(property) && !(/px$/.test(result))){ var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0; values.each(function(value){ size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt(); }, this); return this['offset' + property.capitalize()] - size + 'px'; } if (Browser.ie && (/^border(.+)Width|margin|padding/).test(property) && isNaN(parseFloat(result))){ return '0px'; } } return result; }, setStyles: function(styles){ for (var style in styles) this.setStyle(style, styles[style]); return this; }, getStyles: function(){ var result = {}; Array.flatten(arguments).each(function(key){ result[key] = this.getStyle(key); }, this); return result; } }); Element.Styles = { left: '@px', top: '@px', bottom: '@px', right: '@px', width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px', backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)', fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)', margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)', borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)', zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@' }; Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}}; ['Top', 'Right', 'Bottom', 'Left'].each(function(direction){ var Short = Element.ShortStyles; var All = Element.Styles; ['margin', 'padding'].each(function(style){ var sd = style + direction; Short[style][sd] = All[sd] = '@px'; }); var bd = 'border' + direction; Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)'; var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color'; Short[bd] = {}; Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px'; Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@'; Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)'; }); })(); /* --- name: Element.Event description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events, if necessary. license: MIT-style license. requires: [Element, Event] provides: Element.Event ... */ (function(){ Element.Properties.events = {set: function(events){ this.addEvents(events); }}; [Element, Window, Document].invoke('implement', { addEvent: function(type, fn){ var events = this.retrieve('events', {}); if (!events[type]) events[type] = {keys: [], values: []}; if (events[type].keys.contains(fn)) return this; events[type].keys.push(fn); var realType = type, custom = Element.Events[type], condition = fn, self = this; if (custom){ if (custom.onAdd) custom.onAdd.call(this, fn, type); if (custom.condition){ condition = function(event){ if (custom.condition.call(this, event, type)) return fn.call(this, event); return true; }; } if (custom.base) realType = Function.from(custom.base).call(this, type); } var defn = function(){ return fn.call(self); }; var nativeEvent = Element.NativeEvents[realType]; if (nativeEvent){ if (nativeEvent == 2){ defn = function(event){ event = new DOMEvent(event, self.getWindow()); if (condition.call(self, event) === false) event.stop(); }; } this.addListener(realType, defn, arguments[2]); } events[type].values.push(defn); return this; }, removeEvent: function(type, fn){ var events = this.retrieve('events'); if (!events || !events[type]) return this; var list = events[type]; var index = list.keys.indexOf(fn); if (index == -1) return this; var value = list.values[index]; delete list.keys[index]; delete list.values[index]; var custom = Element.Events[type]; if (custom){ if (custom.onRemove) custom.onRemove.call(this, fn, type); if (custom.base) type = Function.from(custom.base).call(this, type); } return (Element.NativeEvents[type]) ? this.removeListener(type, value, arguments[2]) : this; }, addEvents: function(events){ for (var event in events) this.addEvent(event, events[event]); return this; }, removeEvents: function(events){ var type; if (typeOf(events) == 'object'){ for (type in events) this.removeEvent(type, events[type]); return this; } var attached = this.retrieve('events'); if (!attached) return this; if (!events){ for (type in attached) this.removeEvents(type); this.eliminate('events'); } else if (attached[events]){ attached[events].keys.each(function(fn){ this.removeEvent(events, fn); }, this); delete attached[events]; } return this; }, fireEvent: function(type, args, delay){ var events = this.retrieve('events'); if (!events || !events[type]) return this; args = Array.from(args); events[type].keys.each(function(fn){ if (delay) fn.delay(delay, this, args); else fn.apply(this, args); }, this); return this; }, cloneEvents: function(from, type){ from = document.id(from); var events = from.retrieve('events'); if (!events) return this; if (!type){ for (var eventType in events) this.cloneEvents(from, eventType); } else if (events[type]){ events[type].keys.each(function(fn){ this.addEvent(type, fn); }, this); } return this; } }); Element.NativeEvents = { click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons mousewheel: 2, DOMMouseScroll: 2, //mouse wheel mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement keydown: 2, keypress: 2, keyup: 2, //keyboard orientationchange: 2, // mobile touchstart: 2, touchmove: 2, touchend: 2, touchcancel: 2, // touch gesturestart: 2, gesturechange: 2, gestureend: 2, // gesture focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, paste: 2, input: 2, //form elements load: 2, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window error: 1, abort: 1, scroll: 1 //misc }; Element.Events = {mousewheel: { base: (Browser.firefox) ? 'DOMMouseScroll' : 'mousewheel' }}; if ('onmouseenter' in document.documentElement){ Element.NativeEvents.mouseenter = Element.NativeEvents.mouseleave = 2; } else { var check = function(event){ var related = event.relatedTarget; if (related == null) return true; if (!related) return false; return (related != this && related.prefix != 'xul' && typeOf(this) != 'document' && !this.contains(related)); }; Element.Events.mouseenter = { base: 'mouseover', condition: check }; Element.Events.mouseleave = { base: 'mouseout', condition: check }; } /*<ltIE9>*/ if (!window.addEventListener){ Element.NativeEvents.propertychange = 2; Element.Events.change = { base: function(){ var type = this.type; return (this.get('tag') == 'input' && (type == 'radio' || type == 'checkbox')) ? 'propertychange' : 'change' }, condition: function(event){ return this.type != 'radio' || (event.event.propertyName == 'checked' && this.checked); } } } /*</ltIE9>*/ })(); /* --- name: Element.Delegation description: Extends the Element native object to include the delegate method for more efficient event management. license: MIT-style license. requires: [Element.Event] provides: [Element.Delegation] ... */ (function(){ var eventListenerSupport = !!window.addEventListener; Element.NativeEvents.focusin = Element.NativeEvents.focusout = 2; var bubbleUp = function(self, match, fn, event, target){ while (target && target != self){ if (match(target, event)) return fn.call(target, event, target); target = document.id(target.parentNode); } }; var map = { mouseenter: { base: 'mouseover' }, mouseleave: { base: 'mouseout' }, focus: { base: 'focus' + (eventListenerSupport ? '' : 'in'), capture: true }, blur: { base: eventListenerSupport ? 'blur' : 'focusout', capture: true } }; /*<ltIE9>*/ var _key = '$delegation:'; var formObserver = function(type){ return { base: 'focusin', remove: function(self, uid){ var list = self.retrieve(_key + type + 'listeners', {})[uid]; if (list && list.forms) for (var i = list.forms.length; i--;){ list.forms[i].removeEvent(type, list.fns[i]); } }, listen: function(self, match, fn, event, target, uid){ var form = (target.get('tag') == 'form') ? target : event.target.getParent('form'); if (!form) return; var listeners = self.retrieve(_key + type + 'listeners', {}), listener = listeners[uid] || {forms: [], fns: []}, forms = listener.forms, fns = listener.fns; if (forms.indexOf(form) != -1) return; forms.push(form); var _fn = function(event){ bubbleUp(self, match, fn, event, target); }; form.addEvent(type, _fn); fns.push(_fn); listeners[uid] = listener; self.store(_key + type + 'listeners', listeners); } }; }; var inputObserver = function(type){ return { base: 'focusin', listen: function(self, match, fn, event, target){ var events = {blur: function(){ this.removeEvents(events); }}; events[type] = function(event){ bubbleUp(self, match, fn, event, target); }; event.target.addEvents(events); } }; }; if (!eventListenerSupport) Object.append(map, { submit: formObserver('submit'), reset: formObserver('reset'), change: inputObserver('change'), select: inputObserver('select') }); /*</ltIE9>*/ var proto = Element.prototype, addEvent = proto.addEvent, removeEvent = proto.removeEvent; var relay = function(old, method){ return function(type, fn, useCapture){ if (type.indexOf(':relay') == -1) return old.call(this, type, fn, useCapture); var parsed = Slick.parse(type).expressions[0][0]; if (parsed.pseudos[0].key != 'relay') return old.call(this, type, fn, useCapture); var newType = parsed.tag; parsed.pseudos.slice(1).each(function(pseudo){ newType += ':' + pseudo.key + (pseudo.value ? '(' + pseudo.value + ')' : ''); }); old.call(this, type, fn); return method.call(this, newType, parsed.pseudos[0].value, fn); }; }; var delegation = { addEvent: function(type, match, fn){ var storage = this.retrieve('$delegates', {}), stored = storage[type]; if (stored) for (var _uid in stored){ if (stored[_uid].fn == fn && stored[_uid].match == match) return this; } var _type = type, _match = match, _fn = fn, _map = map[type] || {}; type = _map.base || _type; match = function(target){ return Slick.match(target, _match); }; var elementEvent = Element.Events[_type]; if (elementEvent && elementEvent.condition){ var __match = match, condition = elementEvent.condition; match = function(target, event){ return __match(target, event) && condition.call(target, event, type); }; } var self = this, uid = String.uniqueID(); var delegator = _map.listen ? function(event, target){ if (!target && event && event.target) target = event.target; if (target) _map.listen(self, match, fn, event, target, uid); } : function(event, target){ if (!target && event && event.target) target = event.target; if (target) bubbleUp(self, match, fn, event, target); }; if (!stored) stored = {}; stored[uid] = { match: _match, fn: _fn, delegator: delegator }; storage[_type] = stored; return addEvent.call(this, type, delegator, _map.capture); }, removeEvent: function(type, match, fn, _uid){ var storage = this.retrieve('$delegates', {}), stored = storage[type]; if (!stored) return this; if (_uid){ var _type = type, delegator = stored[_uid].delegator, _map = map[type] || {}; type = _map.base || _type; if (_map.remove) _map.remove(this, _uid); delete stored[_uid]; storage[_type] = stored; return removeEvent.call(this, type, delegator); } var __uid, s; if (fn) for (__uid in stored){ s = stored[__uid]; if (s.match == match && s.fn == fn) return delegation.removeEvent.call(this, type, match, fn, __uid); } else for (__uid in stored){ s = stored[__uid]; if (s.match == match) delegation.removeEvent.call(this, type, match, s.fn, __uid); } return this; } }; [Element, Window, Document].invoke('implement', { addEvent: relay(addEvent, delegation.addEvent), removeEvent: relay(removeEvent, delegation.removeEvent) }); })(); /* --- name: Element.Dimensions description: Contains methods to work with size, scroll, or positioning of Elements and the window object. license: MIT-style license. credits: - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html). - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html). requires: [Element, Element.Style] provides: [Element.Dimensions] ... */ (function(){ var element = document.createElement('div'), child = document.createElement('div'); element.style.height = '0'; element.appendChild(child); var brokenOffsetParent = (child.offsetParent === element); element = child = null; var isOffset = function(el){ return styleString(el, 'position') != 'static' || isBody(el); }; var isOffsetStatic = function(el){ return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName); }; Element.implement({ scrollTo: function(x, y){ if (isBody(this)){ this.getWindow().scrollTo(x, y); } else { this.scrollLeft = x; this.scrollTop = y; } return this; }, getSize: function(){ if (isBody(this)) return this.getWindow().getSize(); return {x: this.offsetWidth, y: this.offsetHeight}; }, getScrollSize: function(){ if (isBody(this)) return this.getWindow().getScrollSize(); return {x: this.scrollWidth, y: this.scrollHeight}; }, getScroll: function(){ if (isBody(this)) return this.getWindow().getScroll(); return {x: this.scrollLeft, y: this.scrollTop}; }, getScrolls: function(){ var element = this.parentNode, position = {x: 0, y: 0}; while (element && !isBody(element)){ position.x += element.scrollLeft; position.y += element.scrollTop; element = element.parentNode; } return position; }, getOffsetParent: brokenOffsetParent ? function(){ var element = this; if (isBody(element) || styleString(element, 'position') == 'fixed') return null; var isOffsetCheck = (styleString(element, 'position') == 'static') ? isOffsetStatic : isOffset; while ((element = element.parentNode)){ if (isOffsetCheck(element)) return element; } return null; } : function(){ var element = this; if (isBody(element) || styleString(element, 'position') == 'fixed') return null; try { return element.offsetParent; } catch(e) {} return null; }, getOffsets: function(){ if (this.getBoundingClientRect && !Browser.Platform.ios){ var bound = this.getBoundingClientRect(), html = document.id(this.getDocument().documentElement), htmlScroll = html.getScroll(), elemScrolls = this.getScrolls(), isFixed = (styleString(this, 'position') == 'fixed'); return { x: bound.left.toInt() + elemScrolls.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft, y: bound.top.toInt() + elemScrolls.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop }; } var element = this, position = {x: 0, y: 0}; if (isBody(this)) return position; while (element && !isBody(element)){ position.x += element.offsetLeft; position.y += element.offsetTop; if (Browser.firefox){ if (!borderBox(element)){ position.x += leftBorder(element); position.y += topBorder(element); } var parent = element.parentNode; if (parent && styleString(parent, 'overflow') != 'visible'){ position.x += leftBorder(parent); position.y += topBorder(parent); } } else if (element != this && Browser.safari){ position.x += leftBorder(element); position.y += topBorder(element); } element = element.offsetParent; } if (Browser.firefox && !borderBox(this)){ position.x -= leftBorder(this); position.y -= topBorder(this); } return position; }, getPosition: function(relative){ var offset = this.getOffsets(), scroll = this.getScrolls(); var position = { x: offset.x - scroll.x, y: offset.y - scroll.y }; if (relative && (relative = document.id(relative))){ var relativePosition = relative.getPosition(); return {x: position.x - relativePosition.x - leftBorder(relative), y: position.y - relativePosition.y - topBorder(relative)}; } return position; }, getCoordinates: function(element){ if (isBody(this)) return this.getWindow().getCoordinates(); var position = this.getPosition(element), size = this.getSize(); var obj = { left: position.x, top: position.y, width: size.x, height: size.y }; obj.right = obj.left + obj.width; obj.bottom = obj.top + obj.height; return obj; }, computePosition: function(obj){ return { left: obj.x - styleNumber(this, 'margin-left'), top: obj.y - styleNumber(this, 'margin-top') }; }, setPosition: function(obj){ return this.setStyles(this.computePosition(obj)); } }); [Document, Window].invoke('implement', { getSize: function(){ var doc = getCompatElement(this); return {x: doc.clientWidth, y: doc.clientHeight}; }, getScroll: function(){ var win = this.getWindow(), doc = getCompatElement(this); return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop}; }, getScrollSize: function(){ var doc = getCompatElement(this), min = this.getSize(), body = this.getDocument().body; return {x: Math.max(doc.scrollWidth, body.scrollWidth, min.x), y: Math.max(doc.scrollHeight, body.scrollHeight, min.y)}; }, getPosition: function(){ return {x: 0, y: 0}; }, getCoordinates: function(){ var size = this.getSize(); return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x}; } }); // private methods var styleString = Element.getComputedStyle; function styleNumber(element, style){ return styleString(element, style).toInt() || 0; } function borderBox(element){ return styleString(element, '-moz-box-sizing') == 'border-box'; } function topBorder(element){ return styleNumber(element, 'border-top-width'); } function leftBorder(element){ return styleNumber(element, 'border-left-width'); } function isBody(element){ return (/^(?:body|html)$/i).test(element.tagName); } function getCompatElement(element){ var doc = element.getDocument(); return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; } })(); //aliases Element.alias({position: 'setPosition'}); //compatability [Window, Document, Element].invoke('implement', { getHeight: function(){ return this.getSize().y; }, getWidth: function(){ return this.getSize().x; }, getScrollTop: function(){ return this.getScroll().y; }, getScrollLeft: function(){ return this.getScroll().x; }, getScrollHeight: function(){ return this.getScrollSize().y; }, getScrollWidth: function(){ return this.getScrollSize().x; }, getTop: function(){ return this.getPosition().y; }, getLeft: function(){ return this.getPosition().x; } }); /* --- name: Fx description: Contains the basic animation logic to be extended by all other Fx Classes. license: MIT-style license. requires: [Chain, Events, Options] provides: Fx ... */ (function(){ var Fx = this.Fx = new Class({ Implements: [Chain, Events, Options], options: { /* onStart: nil, onCancel: nil, onComplete: nil, */ fps: 60, unit: false, duration: 500, frames: null, frameSkip: true, link: 'ignore' }, initialize: function(options){ this.subject = this.subject || this; this.setOptions(options); }, getTransition: function(){ return function(p){ return -(Math.cos(Math.PI * p) - 1) / 2; }; }, step: function(now){ if (this.options.frameSkip){ var diff = (this.time != null) ? (now - this.time) : 0, frames = diff / this.frameInterval; this.time = now; this.frame += frames; } else { this.frame++; } if (this.frame < this.frames){ var delta = this.transition(this.frame / this.frames); this.set(this.compute(this.from, this.to, delta)); } else { this.frame = this.frames; this.set(this.compute(this.from, this.to, 1)); this.stop(); } }, set: function(now){ return now; }, compute: function(from, to, delta){ return Fx.compute(from, to, delta); }, check: function(){ if (!this.isRunning()) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(this.caller.pass(arguments, this)); return false; } return false; }, start: function(from, to){ if (!this.check(from, to)) return this; this.from = from; this.to = to; this.frame = (this.options.frameSkip) ? 0 : -1; this.time = null; this.transition = this.getTransition(); var frames = this.options.frames, fps = this.options.fps, duration = this.options.duration; this.duration = Fx.Durations[duration] || duration.toInt(); this.frameInterval = 1000 / fps; this.frames = frames || Math.round(this.duration / this.frameInterval); this.fireEvent('start', this.subject); pushInstance.call(this, fps); return this; }, stop: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); if (this.frames == this.frame){ this.fireEvent('complete', this.subject); if (!this.callChain()) this.fireEvent('chainComplete', this.subject); } else { this.fireEvent('stop', this.subject); } } return this; }, cancel: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); this.frame = this.frames; this.fireEvent('cancel', this.subject).clearChain(); } return this; }, pause: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); } return this; }, resume: function(){ if ((this.frame < this.frames) && !this.isRunning()) pushInstance.call(this, this.options.fps); return this; }, isRunning: function(){ var list = instances[this.options.fps]; return list && list.contains(this); } }); Fx.compute = function(from, to, delta){ return (to - from) * delta + from; }; Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000}; // global timers var instances = {}, timers = {}; var loop = function(){ var now = Date.now(); for (var i = this.length; i--;){ var instance = this[i]; if (instance) instance.step(now); } }; var pushInstance = function(fps){ var list = instances[fps] || (instances[fps] = []); list.push(this); if (!timers[fps]) timers[fps] = loop.periodical(Math.round(1000 / fps), list); }; var pullInstance = function(fps){ var list = instances[fps]; if (list){ list.erase(this); if (!list.length && timers[fps]){ delete instances[fps]; timers[fps] = clearInterval(timers[fps]); } } }; })(); /* --- name: Fx.CSS description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements. license: MIT-style license. requires: [Fx, Element.Style] provides: Fx.CSS ... */ Fx.CSS = new Class({ Extends: Fx, //prepares the base from/to object prepare: function(element, property, values){ values = Array.from(values); var from = values[0], to = values[1]; if (to == null){ to = from; from = element.getStyle(property); var unit = this.options.unit; // adapted from: https://github.com/ryanmorr/fx/blob/master/fx.js#L299 if (unit && from.slice(-unit.length) != unit && parseFloat(from) != 0){ element.setStyle(property, to + unit); var value = element.getComputedStyle(property); // IE and Opera support pixelLeft or pixelWidth if (!(/px$/.test(value))){ value = element.style[('pixel-' + property).camelCase()]; if (value == null){ // adapted from Dean Edwards' http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 var left = element.style.left; element.style.left = to + unit; value = element.style.pixelLeft; element.style.left = left; } } from = (to || 1) / (parseFloat(value) || 1) * (parseFloat(from) || 0); element.setStyle(property, from + unit); } } return {from: this.parse(from), to: this.parse(to)}; }, //parses a value into an array parse: function(value){ value = Function.from(value)(); value = (typeof value == 'string') ? value.split(' ') : Array.from(value); return value.map(function(val){ val = String(val); var found = false; Object.each(Fx.CSS.Parsers, function(parser, key){ if (found) return; var parsed = parser.parse(val); if (parsed || parsed === 0) found = {value: parsed, parser: parser}; }); found = found || {value: val, parser: Fx.CSS.Parsers.String}; return found; }); }, //computes by a from and to prepared objects, using their parsers. compute: function(from, to, delta){ var computed = []; (Math.min(from.length, to.length)).times(function(i){ computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser}); }); computed.$family = Function.from('fx:css:value'); return computed; }, //serves the value as settable serve: function(value, unit){ if (typeOf(value) != 'fx:css:value') value = this.parse(value); var returned = []; value.each(function(bit){ returned = returned.concat(bit.parser.serve(bit.value, unit)); }); return returned; }, //renders the change to an element render: function(element, property, value, unit){ element.setStyle(property, this.serve(value, unit)); }, //searches inside the page css to find the values for a selector search: function(selector){ if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector]; var to = {}, selectorTest = new RegExp('^' + selector.escapeRegExp() + '$'); Array.each(document.styleSheets, function(sheet, j){ var href = sheet.href; if (href && href.contains('://') && !href.contains(document.domain)) return; var rules = sheet.rules || sheet.cssRules; Array.each(rules, function(rule, i){ if (!rule.style) return; var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){ return m.toLowerCase(); }) : null; if (!selectorText || !selectorTest.test(selectorText)) return; Object.each(Element.Styles, function(value, style){ if (!rule.style[style] || Element.ShortStyles[style]) return; value = String(rule.style[style]); to[style] = ((/^rgb/).test(value)) ? value.rgbToHex() : value; }); }); }); return Fx.CSS.Cache[selector] = to; } }); Fx.CSS.Cache = {}; Fx.CSS.Parsers = { Color: { parse: function(value){ if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true); return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false; }, compute: function(from, to, delta){ return from.map(function(value, i){ return Math.round(Fx.compute(from[i], to[i], delta)); }); }, serve: function(value){ return value.map(Number); } }, Number: { parse: parseFloat, compute: Fx.compute, serve: function(value, unit){ return (unit) ? value + unit : value; } }, String: { parse: Function.from(false), compute: function(zero, one){ return one; }, serve: function(zero){ return zero; } } }; /* --- name: Fx.Tween description: Formerly Fx.Style, effect to transition any CSS property for an element. license: MIT-style license. requires: Fx.CSS provides: [Fx.Tween, Element.fade, Element.highlight] ... */ Fx.Tween = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); }, set: function(property, now){ if (arguments.length == 1){ now = property; property = this.property || this.options.property; } this.render(this.element, property, now, this.options.unit); return this; }, start: function(property, from, to){ if (!this.check(property, from, to)) return this; var args = Array.flatten(arguments); this.property = this.options.property || args.shift(); var parsed = this.prepare(this.element, this.property, args); return this.parent(parsed.from, parsed.to); } }); Element.Properties.tween = { set: function(options){ this.get('tween').cancel().setOptions(options); return this; }, get: function(){ var tween = this.retrieve('tween'); if (!tween){ tween = new Fx.Tween(this, {link: 'cancel'}); this.store('tween', tween); } return tween; } }; Element.implement({ tween: function(property, from, to){ this.get('tween').start(property, from, to); return this; }, fade: function(how){ var fade = this.get('tween'), method, args = ['opacity'].append(arguments), toggle; if (args[1] == null) args[1] = 'toggle'; switch (args[1]){ case 'in': method = 'start'; args[1] = 1; break; case 'out': method = 'start'; args[1] = 0; break; case 'show': method = 'set'; args[1] = 1; break; case 'hide': method = 'set'; args[1] = 0; break; case 'toggle': var flag = this.retrieve('fade:flag', this.getStyle('opacity') == 1); method = 'start'; args[1] = flag ? 0 : 1; this.store('fade:flag', !flag); toggle = true; break; default: method = 'start'; } if (!toggle) this.eliminate('fade:flag'); fade[method].apply(fade, args); var to = args[args.length - 1]; if (method == 'set' || to != 0) this.setStyle('visibility', to == 0 ? 'hidden' : 'visible'); else fade.chain(function(){ this.element.setStyle('visibility', 'hidden'); this.callChain(); }); return this; }, highlight: function(start, end){ if (!end){ end = this.retrieve('highlight:original', this.getStyle('background-color')); end = (end == 'transparent') ? '#fff' : end; } var tween = this.get('tween'); tween.start('background-color', start || '#ffff88', end).chain(function(){ this.setStyle('background-color', this.retrieve('highlight:original')); tween.callChain(); }.bind(this)); return this; } }); /* --- name: Fx.Morph description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules. license: MIT-style license. requires: Fx.CSS provides: Fx.Morph ... */ Fx.Morph = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); }, set: function(now){ if (typeof now == 'string') now = this.search(now); for (var p in now) this.render(this.element, p, now[p], this.options.unit); return this; }, compute: function(from, to, delta){ var now = {}; for (var p in from) now[p] = this.parent(from[p], to[p], delta); return now; }, start: function(properties){ if (!this.check(properties)) return this; if (typeof properties == 'string') properties = this.search(properties); var from = {}, to = {}; for (var p in properties){ var parsed = this.prepare(this.element, p, properties[p]); from[p] = parsed.from; to[p] = parsed.to; } return this.parent(from, to); } }); Element.Properties.morph = { set: function(options){ this.get('morph').cancel().setOptions(options); return this; }, get: function(){ var morph = this.retrieve('morph'); if (!morph){ morph = new Fx.Morph(this, {link: 'cancel'}); this.store('morph', morph); } return morph; } }; Element.implement({ morph: function(props){ this.get('morph').start(props); return this; } }); /* --- name: Fx.Transitions description: Contains a set of advanced transitions to be used with any of the Fx Classes. license: MIT-style license. credits: - Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools. requires: Fx provides: Fx.Transitions ... */ Fx.implement({ getTransition: function(){ var trans = this.options.transition || Fx.Transitions.Sine.easeInOut; if (typeof trans == 'string'){ var data = trans.split(':'); trans = Fx.Transitions; trans = trans[data[0]] || trans[data[0].capitalize()]; if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')]; } return trans; } }); Fx.Transition = function(transition, params){ params = Array.from(params); var easeIn = function(pos){ return transition(pos, params); }; return Object.append(easeIn, { easeIn: easeIn, easeOut: function(pos){ return 1 - transition(1 - pos, params); }, easeInOut: function(pos){ return (pos <= 0.5 ? transition(2 * pos, params) : (2 - transition(2 * (1 - pos), params))) / 2; } }); }; Fx.Transitions = { linear: function(zero){ return zero; } }; Fx.Transitions.extend = function(transitions){ for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]); }; Fx.Transitions.extend({ Pow: function(p, x){ return Math.pow(p, x && x[0] || 6); }, Expo: function(p){ return Math.pow(2, 8 * (p - 1)); }, Circ: function(p){ return 1 - Math.sin(Math.acos(p)); }, Sine: function(p){ return 1 - Math.cos(p * Math.PI / 2); }, Back: function(p, x){ x = x && x[0] || 1.618; return Math.pow(p, 2) * ((x + 1) * p - x); }, Bounce: function(p){ var value; for (var a = 0, b = 1; 1; a += b, b /= 2){ if (p >= (7 - 4 * a) / 11){ value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2); break; } } return value; }, Elastic: function(p, x){ return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x && x[0] || 1) / 3); } }); ['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){ Fx.Transitions[transition] = new Fx.Transition(function(p){ return Math.pow(p, i + 2); }); }); /* --- name: Request description: Powerful all purpose Request Class. Uses XMLHTTPRequest. license: MIT-style license. requires: [Object, Element, Chain, Events, Options, Browser] provides: Request ... */ (function(){ var empty = function(){}, progressSupport = ('onprogress' in new Browser.Request); var Request = this.Request = new Class({ Implements: [Chain, Events, Options], options: {/* onRequest: function(){}, onLoadstart: function(event, xhr){}, onProgress: function(event, xhr){}, onUploadProgress: function(event, xhr){}, onComplete: function(){}, onCancel: function(){}, onSuccess: function(responseText, responseXML){}, onFailure: function(xhr){}, onException: function(headerName, value){}, onTimeout: function(){}, user: '', password: '',*/ url: '', data: '', processData: true, responseType: null, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }, async: true, format: false, method: 'post', link: 'ignore', isSuccess: null, emulation: true, urlEncoded: true, encoding: 'utf-8', evalScripts: false, evalResponse: false, timeout: 0, noCache: false }, initialize: function(options){ this.xhr = new Browser.Request(); this.setOptions(options); if ((typeof ArrayBuffer != 'undefined' && options.data instanceof ArrayBuffer) || (typeof Blob != 'undefined' && options.data instanceof Blob) || (typeof Uint8Array != 'undefined' && options.data instanceof Uint8Array)){ // set data in directly if we're passing binary data because // otherwise setOptions will convert the data into an empty object this.options.data = options.data; } this.headers = this.options.headers; }, onStateChange: function(){ var xhr = this.xhr; if (xhr.readyState != 4 || !this.running) return; this.running = false; this.status = 0; Function.attempt(function(){ var status = xhr.status; this.status = (status == 1223) ? 204 : status; }.bind(this)); xhr.onreadystatechange = empty; if (progressSupport) xhr.onprogress = xhr.onloadstart = empty; clearTimeout(this.timer); this.response = {text: (!this.options.responseType && this.xhr.responseText) || '', xml: (!this.options.responseType && this.xhr.responseXML)}; if (this.options.isSuccess.call(this, this.status)) this.success(this.options.responseType ? this.xhr.response : this.response.text, this.response.xml); else this.failure(); }, isSuccess: function(){ var status = this.status; return (status >= 200 && status < 300); }, isRunning: function(){ return !!this.running; }, processScripts: function(text){ if (typeof text != 'string') return text; if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return Browser.exec(text); return text.stripScripts(this.options.evalScripts); }, success: function(text, xml){ this.onSuccess(this.processScripts(text), xml); }, onSuccess: function(){ this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain(); }, failure: function(){ this.onFailure(); }, onFailure: function(){ this.fireEvent('complete').fireEvent('failure', this.xhr); }, loadstart: function(event){ this.fireEvent('loadstart', [event, this.xhr]); }, progress: function(event){ this.fireEvent('progress', [event, this.xhr]); }, uploadprogress: function(event){ this.fireEvent('uploadprogress', [event, this.xhr]); }, timeout: function(){ this.fireEvent('timeout', this.xhr); }, setHeader: function(name, value){ this.headers[name] = value; return this; }, getHeader: function(name){ return Function.attempt(function(){ return this.xhr.getResponseHeader(name); }.bind(this)); }, check: function(){ if (!this.running) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(this.caller.pass(arguments, this)); return false; } return false; }, send: function(options){ if (!this.check(options)) return this; this.options.isSuccess = this.options.isSuccess || this.isSuccess; this.running = true; var type = typeOf(options); if (type == 'string' || type == 'element') options = {data: options}; var old = this.options; options = Object.append({data: old.data, url: old.url, method: old.method}, options); var data = options.data, url = String(options.url), method = options.method.toLowerCase(); if (this.options.processData || method == 'get' || method == 'delete'){ switch (typeOf(data)){ case 'element': data = document.id(data).toQueryString(); break; case 'object': case 'hash': data = Object.toQueryString(data); } if (this.options.format){ var format = 'format=' + this.options.format; data = (data) ? format + '&' + data : format; } if (this.options.emulation && !['get', 'post'].contains(method)){ var _method = '_method=' + method; data = (data) ? _method + '&' + data : _method; method = 'post'; } } if (this.options.urlEncoded && ['post', 'put'].contains(method)){ var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : ''; this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding; } if (!url) url = document.location.pathname; var trimPosition = url.lastIndexOf('/'); if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition); if (this.options.noCache) url += (url.contains('?') ? '&' : '?') + String.uniqueID(); if (data && method == 'get'){ url += (url.contains('?') ? '&' : '?') + data; data = null; } var xhr = this.xhr; if (progressSupport){ xhr.onloadstart = this.loadstart.bind(this); xhr.onprogress = this.progress.bind(this); if(xhr.upload) xhr.upload.onprogress = this.uploadprogress.bind(this); } xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password); if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true; xhr.onreadystatechange = this.onStateChange.bind(this); Object.each(this.headers, function(value, key){ try { xhr.setRequestHeader(key, value); } catch (e){ this.fireEvent('exception', [key, value]); } }, this); if (this.options.responseType){ xhr.responseType = this.options.responseType.toLowerCase(); } this.fireEvent('request'); xhr.send(data); if (!this.options.async) this.onStateChange(); else if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this); return this; }, cancel: function(){ if (!this.running) return this; this.running = false; var xhr = this.xhr; xhr.abort(); clearTimeout(this.timer); xhr.onreadystatechange = empty; if (progressSupport) xhr.onprogress = xhr.onloadstart = empty; this.xhr = new Browser.Request(); this.fireEvent('cancel'); return this; } }); var methods = {}; ['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){ methods[method] = function(data){ var object = { method: method }; if (data != null) object.data = data; return this.send(object); }; }); Request.implement(methods); Element.Properties.send = { set: function(options){ var send = this.get('send').cancel(); send.setOptions(options); return this; }, get: function(){ var send = this.retrieve('send'); if (!send){ send = new Request({ data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action') }); this.store('send', send); } return send; } }; Element.implement({ send: function(url){ var sender = this.get('send'); sender.send({data: this, url: url || sender.options.url}); return this; } }); })(); /* --- name: Request.HTML description: Extends the basic Request Class with additional methods for interacting with HTML responses. license: MIT-style license. requires: [Element, Request] provides: Request.HTML ... */ Request.HTML = new Class({ Extends: Request, options: { update: false, append: false, evalScripts: true, filter: false, headers: { Accept: 'text/html, application/xml, text/xml, */*' } }, success: function(text){ var options = this.options, response = this.response; response.html = text.stripScripts(function(script){ response.javascript = script; }); var match = response.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i); if (match) response.html = match[1]; var temp = new Element('div').set('html', response.html); response.tree = temp.childNodes; response.elements = temp.getElements(options.filter || '*'); if (options.filter) response.tree = response.elements; if (options.update){ var update = document.id(options.update).empty(); if (options.filter) update.adopt(response.elements); else update.set('html', response.html); } else if (options.append){ var append = document.id(options.append); if (options.filter) response.elements.reverse().inject(append); else append.adopt(temp.getChildren()); } if (options.evalScripts) Browser.exec(response.javascript); this.onSuccess(response.tree, response.elements, response.html, response.javascript); } }); Element.Properties.load = { set: function(options){ var load = this.get('load').cancel(); load.setOptions(options); return this; }, get: function(){ var load = this.retrieve('load'); if (!load){ load = new Request.HTML({data: this, link: 'cancel', update: this, method: 'get'}); this.store('load', load); } return load; } }; Element.implement({ load: function(){ this.get('load').send(Array.link(arguments, {data: Type.isObject, url: Type.isString})); return this; } }); /* --- name: JSON description: JSON encoder and decoder. license: MIT-style license. SeeAlso: <http://www.json.org/> requires: [Array, String, Number, Function] provides: JSON ... */ if (typeof JSON == 'undefined') this.JSON = {}; (function(){ var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'}; var escape = function(chr){ return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4); }; JSON.validate = function(string){ string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''); return (/^[\],:{}\s]*$/).test(string); }; JSON.encode = JSON.stringify ? function(obj){ return JSON.stringify(obj); } : function(obj){ if (obj && obj.toJSON) obj = obj.toJSON(); switch (typeOf(obj)){ case 'string': return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"'; case 'array': return '[' + obj.map(JSON.encode).clean() + ']'; case 'object': case 'hash': var string = []; Object.each(obj, function(value, key){ var json = JSON.encode(value); if (json) string.push(JSON.encode(key) + ':' + json); }); return '{' + string + '}'; case 'number': case 'boolean': return '' + obj; case 'null': return 'null'; } return null; }; JSON.decode = function(string, secure){ if (!string || typeOf(string) != 'string') return null; if (secure || JSON.secure){ if (JSON.parse) return JSON.parse(string); if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.'); } return eval('(' + string + ')'); }; })(); /* --- name: Request.JSON description: Extends the basic Request Class with additional methods for sending and receiving JSON data. license: MIT-style license. requires: [Request, JSON] provides: Request.JSON ... */ Request.JSON = new Class({ Extends: Request, options: { /*onError: function(text, error){},*/ secure: true }, initialize: function(options){ this.parent(options); Object.append(this.headers, { 'Accept': 'application/json', 'X-Request': 'JSON' }); }, success: function(text){ var json; try { json = this.response.json = JSON.decode(text, this.options.secure); } catch (error){ this.fireEvent('error', [text, error]); return; } if (json == null) this.onFailure(); else this.onSuccess(json, text); } }); /* --- name: Cookie description: Class for creating, reading, and deleting browser Cookies. license: MIT-style license. credits: - Based on the functions by Peter-Paul Koch (http://quirksmode.org). requires: [Options, Browser] provides: Cookie ... */ var Cookie = new Class({ Implements: Options, options: { path: '/', domain: false, duration: false, secure: false, document: document, encode: true }, initialize: function(key, options){ this.key = key; this.setOptions(options); }, write: function(value){ if (this.options.encode) value = encodeURIComponent(value); if (this.options.domain) value += '; domain=' + this.options.domain; if (this.options.path) value += '; path=' + this.options.path; if (this.options.duration){ var date = new Date(); date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000); value += '; expires=' + date.toGMTString(); } if (this.options.secure) value += '; secure'; this.options.document.cookie = this.key + '=' + value; return this; }, read: function(){ var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)'); return (value) ? decodeURIComponent(value[1]) : null; }, dispose: function(){ new Cookie(this.key, Object.merge({}, this.options, {duration: -1})).write(''); return this; } }); Cookie.write = function(key, value, options){ return new Cookie(key, options).write(value); }; Cookie.read = function(key){ return new Cookie(key).read(); }; Cookie.dispose = function(key, options){ return new Cookie(key, options).dispose(); }; /* --- name: DOMReady description: Contains the custom event domready. license: MIT-style license. requires: [Browser, Element, Element.Event] provides: [DOMReady, DomReady] ... */ (function(window, document){ var ready, loaded, checks = [], shouldPoll, timer, testElement = document.createElement('div'); var domready = function(){ clearTimeout(timer); if (ready) return; Browser.loaded = ready = true; document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check); document.fireEvent('domready'); window.fireEvent('domready'); }; var check = function(){ for (var i = checks.length; i--;) if (checks[i]()){ domready(); return true; } return false; }; var poll = function(){ clearTimeout(timer); if (!check()) timer = setTimeout(poll, 10); }; document.addListener('DOMContentLoaded', domready); /*<ltIE8>*/ // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/ // testElement.doScroll() throws when the DOM is not ready, only in the top window var doScrollWorks = function(){ try { testElement.doScroll(); return true; } catch (e){} return false; }; // If doScroll works already, it can't be used to determine domready // e.g. in an iframe if (testElement.doScroll && !doScrollWorks()){ checks.push(doScrollWorks); shouldPoll = true; } /*</ltIE8>*/ if (document.readyState) checks.push(function(){ var state = document.readyState; return (state == 'loaded' || state == 'complete'); }); if ('onreadystatechange' in document) document.addListener('readystatechange', check); else shouldPoll = true; if (shouldPoll) poll(); Element.Events.domready = { onAdd: function(fn){ if (ready) fn.call(this); } }; // Make sure that domready fires before load Element.Events.load = { base: 'load', onAdd: function(fn){ if (loaded && this == window) fn.call(this); }, condition: function(){ if (this == window){ domready(); delete Element.Events.load; } return true; } }; // This is based on the custom load event window.addEvent('load', function(){ loaded = true; }); })(window, document);
Java
using System; namespace TestAPI.Areas.HelpPage { /// <summary> /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. /// </summary> public class InvalidSample { public InvalidSample(string errorMessage) { if (errorMessage == null) { throw new ArgumentNullException("errorMessage"); } ErrorMessage = errorMessage; } public string ErrorMessage { get; private set; } public override bool Equals(object obj) { InvalidSample other = obj as InvalidSample; return other != null && ErrorMessage == other.ErrorMessage; } public override int GetHashCode() { return ErrorMessage.GetHashCode(); } public override string ToString() { return ErrorMessage; } } }
Java
// //Copyright (C) 2002-2005 3Dlabs Inc. Ltd. //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions //are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // Neither the name of 3Dlabs Inc. Ltd. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //POSSIBILITY OF SUCH DAMAGE. // #include "osinclude.h" #define STRICT #define VC_EXTRALEAN 1 #include <windows.h> #include <assert.h> #include <process.h> #include <psapi.h> #include <stdio.h> // // This file contains contains the Window-OS-specific functions // #if !(defined(_WIN32) || defined(_WIN64)) #error Trying to build a windows specific file in a non windows build. #endif namespace glslang { // // Thread Local Storage Operations // OS_TLSIndex OS_AllocTLSIndex() { DWORD dwIndex = TlsAlloc(); if (dwIndex == TLS_OUT_OF_INDEXES) { assert(0 && "OS_AllocTLSIndex(): Unable to allocate Thread Local Storage"); return OS_INVALID_TLS_INDEX; } return dwIndex; } bool OS_SetTLSValue(OS_TLSIndex nIndex, void *lpvValue) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (TlsSetValue(nIndex, lpvValue)) return true; else return false; } void* OS_GetTLSValue(OS_TLSIndex nIndex) { assert(nIndex != OS_INVALID_TLS_INDEX); return TlsGetValue(nIndex); } bool OS_FreeTLSIndex(OS_TLSIndex nIndex) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (TlsFree(nIndex)) return true; else return false; } HANDLE GlobalLock; void InitGlobalLock() { GlobalLock = CreateMutex(0, false, 0); } void GetGlobalLock() { WaitForSingleObject(GlobalLock, INFINITE); } void ReleaseGlobalLock() { ReleaseMutex(GlobalLock); } void* OS_CreateThread(TThreadEntrypoint entry) { return (void*)_beginthreadex(0, 0, entry, 0, 0, 0); //return CreateThread(0, 0, entry, 0, 0, 0); } void OS_WaitForAllThreads(void* threads, int numThreads) { WaitForMultipleObjects(numThreads, (HANDLE*)threads, true, INFINITE); } void OS_Sleep(int milliseconds) { Sleep(milliseconds); } void OS_DumpMemoryCounters() { #ifdef DUMP_COUNTERS PROCESS_MEMORY_COUNTERS counters; GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)); printf("Working set size: %d\n", counters.WorkingSetSize); #else printf("Recompile with DUMP_COUNTERS defined to see counters.\n"); #endif } } // namespace glslang
Java
/* swdp-m0sub.c * * Copyright 2015 Brian Swetland <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <app.h> #include <debug.h> #include <string.h> #include <stdlib.h> #include <printf.h> #include <platform.h> #include <arch/arm.h> #include <kernel/thread.h> #include <platform/lpc43xx-gpio.h> #include <platform/lpc43xx-sgpio.h> #include <platform/lpc43xx-clocks.h> #include "rswdp.h" #define PIN_LED PIN(1,1) #define PIN_RESET PIN(2,5) #define PIN_RESET_TXEN PIN(2,6) #define PIN_SWDIO_TXEN PIN(1,5) // SGPIO15=6 #define PIN_SWDIO PIN(1,6) // SGPIO14=6 #define PIN_SWO PIN(1,14) // U1_RXD=1 #define PIN_SWCLK PIN(1,17) // SGPIO11=6 #define GPIO_LED GPIO(0,8) #define GPIO_RESET GPIO(5,5) #define GPIO_RESET_TXEN GPIO(5,6) #define GPIO_SWDIO_TXEN GPIO(1,8) #define GPIO_SWDIO GPIO(1,9) #define GPIO_SWCLK GPIO(0,12) static void gpio_init(void) { pin_config(PIN_LED, PIN_MODE(0) | PIN_PLAIN); pin_config(PIN_RESET, PIN_MODE(4) | PIN_PLAIN); pin_config(PIN_RESET_TXEN, PIN_MODE(4) | PIN_PLAIN); pin_config(PIN_SWDIO_TXEN, PIN_MODE(6) | PIN_PLAIN | PIN_FAST); pin_config(PIN_SWDIO, PIN_MODE(6) | PIN_PLAIN | PIN_INPUT | PIN_FAST); pin_config(PIN_SWCLK, PIN_MODE(6) | PIN_PLAIN | PIN_FAST); pin_config(PIN_SWO, PIN_MODE(1) | PIN_PLAIN | PIN_INPUT | PIN_FAST); gpio_set(GPIO_LED, 0); gpio_set(GPIO_RESET, 1); gpio_set(GPIO_RESET_TXEN, 0); gpio_config(GPIO_LED, GPIO_OUTPUT); gpio_config(GPIO_RESET, GPIO_OUTPUT); gpio_config(GPIO_RESET_TXEN, GPIO_OUTPUT); } /* returns 1 if the number of bits set in n is odd */ static unsigned parity(unsigned n) { n = (n & 0x55555555) + ((n & 0xaaaaaaaa) >> 1); n = (n & 0x33333333) + ((n & 0xcccccccc) >> 2); n = (n & 0x0f0f0f0f) + ((n & 0xf0f0f0f0) >> 4); n = (n & 0x00ff00ff) + ((n & 0xff00ff00) >> 8); n = (n & 0x0000ffff) + ((n & 0xffff0000) >> 16); return n & 1; } #include "fw-m0sub.h" #define M0SUB_ZEROMAP 0x40043308 #define M0SUB_TXEV 0x40043314 // write 0 to clear #define M4_TXEV 0x40043130 // write 0 to clear #define RESET_CTRL0 0x40053100 #define M0_SUB_RST (1 << 12) #define COMM_CMD 0x18004000 #define COMM_ARG1 0x18004004 #define COMM_ARG2 0x18004008 #define COMM_RESP 0x1800400C #define CMD_ERR 0 #define CMD_NOP 1 #define CMD_READ 2 #define CMD_WRITE 3 #define CMD_RESET 4 #define CMD_SETCLOCK 5 #define RSP_BUSY 0xFFFFFFFF void swd_init(void) { gpio_init(); writel(BASE_CLK_SEL(CLK_PLL1), BASE_PERIPH_CLK); spin(1000); // SGPIO15 SWDIO_TXEN writel(CFG_OUT_GPIO | CFG_OE_GPIO, SGPIO_OUT_CFG(15)); // SGPIO14 SWDIO writel(CFG_OUT_GPIO | CFG_OE_GPIO, SGPIO_OUT_CFG(14)); // SGPIO11 SWCLK writel(CFG_OUT_GPIO | CFG_OE_GPIO, SGPIO_OUT_CFG(11)); // all outputs enabled and high writel((1 << 11) | (1 << 14) | (1 << 15), SGPIO_OUT); writel((1 << 11) | (1 << 14) | (1 << 15), SGPIO_OEN); writel(0, M4_TXEV); writel(M0_SUB_RST, RESET_CTRL0); writel(0x18000000, M0SUB_ZEROMAP); writel(0xffffffff, 0x18004000); memcpy((void*) 0x18000000, zero_bin, sizeof(zero_bin)); DSB; writel(0, RESET_CTRL0); } int swd_write(unsigned hdr, unsigned data) { unsigned n; unsigned p = parity(data); writel(CMD_WRITE, COMM_CMD); writel((hdr << 8) | (p << 16), COMM_ARG1); writel(data, COMM_ARG2); writel(RSP_BUSY, COMM_RESP); DSB; asm("sev"); while ((n = readl(COMM_RESP)) == RSP_BUSY) ; //printf("wr s=%d\n", n); return n; } int swd_read(unsigned hdr, unsigned *val) { unsigned n, data, p; writel(CMD_READ, COMM_CMD); writel(hdr << 8, COMM_ARG1); writel(RSP_BUSY, COMM_RESP); DSB; asm("sev"); while ((n = readl(COMM_RESP)) == RSP_BUSY) ; if (n) { return n; } data = readl(COMM_ARG1); p = readl(COMM_ARG2); if (p != parity(data)) { return ERR_PARITY; } //printf("rd s=%d p=%d d=%08x\n", n, p, data); *val = data; return 0; } void swd_reset(void) { unsigned n; writel(CMD_RESET, COMM_CMD); writel(RSP_BUSY, COMM_RESP); DSB; asm("sev"); while ((n = readl(COMM_RESP)) == RSP_BUSY) ; } unsigned swd_set_clock(unsigned khz) { unsigned n; if (khz > 8000) { khz = 8000; } writel(CMD_SETCLOCK, COMM_CMD); writel(khz/1000, COMM_ARG1); writel(RSP_BUSY, COMM_RESP); DSB; asm("sev"); while ((n = readl(COMM_RESP)) == RSP_BUSY) ; // todo: accurate value return khz; } void swd_hw_reset(int assert) { if (assert) { gpio_set(GPIO_RESET, 0); gpio_set(GPIO_RESET_TXEN, 1); } else { gpio_set(GPIO_RESET, 1); gpio_set(GPIO_RESET_TXEN, 0); } }
Java
/* General styles */ body { background-color:#fff; font-family:Arial,Verdan,Sans-Serif; font-size:75%; } /* Text Shadow ( CSS3 ony ) */ #navigation li a, .portlet-header, .ui-datepicker-title, .page-title h1, .ui-widget-header, .hastable thead td, .hastable thead th, #page-wrapper .other-box h3 { text-shadow:0 1px 0 #fff; } /* Rounded corners ( CSS3 ony ) */ .ui-corner-tl { -moz-border-radius-topleft:3px; -webkit-border-top-left-radius:3px; } .ui-corner-tr { -moz-border-radius-topright:3px; -webkit-border-top-right-radius:3px; } .ui-corner-bl { -moz-border-radius-bottomleft:3px; -webkit-border-bottom-left-radius:3px; } .ui-corner-br { -moz-border-radius-bottomright:3px; -webkit-border-bottom-right-radius:3px; } .ui-corner-top { -moz-border-radius-topleft:3px; -webkit-border-top-left-radius:3px; -moz-border-radius-topright:3px; -webkit-border-top-right-radius:3px; } .ui-corner-bottom { -moz-border-radius-bottomleft:3px; -webkit-border-bottom-left-radius:3px; -moz-border-radius-bottomright:3px; -webkit-border-bottom-right-radius:3px; } .ui-corner-right { -moz-border-radius-topright:3px; -webkit-border-top-right-radius:3px; -moz-border-radius-bottomright:3px; -webkit-border-bottom-right-radius:3px; } .ui-corner-left { -moz-border-radius-topleft:3px; -webkit-border-top-left-radius:3px; -moz-border-radius-bottomleft:3px; -webkit-border-bottom-left-radius:3px; } .ui-corner-all, .pagination li a, .pagination li, #tooltip, ul#dashboard-buttons li a, .fixed #sidebar { -moz-border-radius:3px; -webkit-border-radius:3px; } /* States and Images */ .ui-icon { background-image:url(images/icons-blue.png); } .ui-widget-content .ui-icon { background-image: url(images/icons-blue.png); } .ui-widget-header .ui-icon { background-image: url(images/icons-lgray.png); } .ui-state-default .ui-icon { background-image:url(images/icons-lgray.png); } .ui-state-hover .ui-icon { background-image: url(images/icons-gray.png); } .ui-state-focus .ui-icon { background-image: url(images/icons-blue.png); } .ui-state-active .ui-icon { background-image:url(images/icons-blue.png); } .ui-state-highlight .ui-icon { background-image:url(images/icons-blue.png); } /* Component containers */ .ui-widget-content { border: 1px solid #ddd; background: #fff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; color:#444; } .ui-widget-header { border:1px solid #ddd; background:#ddd url(images/ui-bg_highlight-soft_50_dddddd_1x100.png) 50% 50% repeat-x; color:#444; text-transform:uppercase; } .ui-widget-header a { color: #444; } /* Interaction states */ .ui-state-default, .ui-widget-content .ui-state-default, .pagination a { border:1px solid #ddd; background:#f6f6f6 url(images/ui-bg_highlight-soft_100_f6f6f6_1x100.png) 50% 50% repeat-x; font-weight:bold; color:#0073ea; outline:none; } #page-wrapper #main-wrapper #main-content .page-title h1 b, .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited, #page-wrapper #main-wrapper .title h2, #page-wrapper #main-wrapper .title h3, a { color:#0073ea; text-decoration:none;outline:none; } .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .pagination a:hover, a.btn:hover, button.ui-state-default:hover { border: 1px solid #9d9d9d; background:#0073ea url(images/ui-bg_highlight-soft_25_0073ea_1x100.png) 50% 50% repeat-x; font-weight:bold; color:#333; outline:none; } .ui-state-hover a, .ui-state-hover a:hover { color:#222; text-decoration:none;outline:none; } .ui-state-active, .ui-widget-content .ui-state-active { border:1px solid #ddd!important; background: #fff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight:bold; color:#333; outline:none; } a:hover, .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color:#333; outline:none; text-decoration:none; } #main-content .page-title, .form-bg, #page-wrapper #sidebar .side-menu li a:hover { /* add to any div to change background color */ background:#F9F9F9; } .linetop { border-top:#c7c7c7 solid 1px; } /* Header Style */ #header { background:url('images/header-bg.png') repeat-x; } #header #top-menu { color:#646464; } #header #top-menu a { color:#e6e6e6; } #header #top-menu span { color:#d7d7d7; } #header #sitename a.logo { color:#fff; background:url('../../../images/logo.png') no-repeat; text-shadow:1px 1px 0 #000; } #header #top-menu a:hover, #header #sitename a.logo:hover { color:#b7cbdf; } /* Header navigation menu */ #navigation li a { color:#454545; font-weight:bold; border-right:#d0d0d0 solid 1px; border-left:#f7f7f7 solid 1px; } #navigation li.sfHover, #navigation li.sfHover2 { background:#fff; border-left:#b2b2b2 solid 1px; border-right:#b2b2b2 solid 1px; } #navigation li ul { background:#fff; border:#b2b2b2 solid 1px; } #navigation li ul li { border-bottom:#ccc dotted 1px; background:#f0f0f0; } #navigation li ul li a { color:#7c7c7c; } #navigation li ul li a:hover { color:#696969; background:#f7f7f7; } #navigation li ul li.sfHover, #navigation li ul li.sfHover2 { background:#e0e0e0; } #navigation li ul li.sfHover a { color:#333; } #navigation li ul li ul li a:hover { color:#000; } /* Pages title box */ #page-wrapper #main-wrapper #main-content .page-title .other { color:#515151; border-top:#dadada dotted 1px; } /* Dashboard buttons */ #page-wrapper #main-wrapper #main-content .page-title .other ul#dashboard-buttons li { border:#fff solid 4px; } #page-wrapper #main-wrapper #main-content .page-title .other ul#dashboard-buttons li a { background-color:#f3f3f3; border:#dcdfe3 solid 1px; border-color:#dcdfe3 #d0d4d8 #d0d4d8 #dcdfe3; color:#666; } #page-wrapper #main-wrapper #main-content .page-title .other ul#dashboard-buttons li a:hover { background-color:#e4e7ea; border-color:#c3c9ce; color:#333; } #page-wrapper #main-wrapper #main-content .page-title .other ul#dashboard-buttons li a:active { border-color:#9d9d9d; } /* Different title styles */ #page-wrapper #main-wrapper .title, #page-wrapper #sidebar .side-menu li { color:#616161; border-bottom:#8f8f8f dotted 1px; } .ui-sortable-placeholder { background:#ffffcc; } #page-wrapper #sidebar { background:#f4f4f4; border-color:#d0d0d0; } /* Note */ i.note { font-weight:bold; padding:15px 0 15px 25px; color:#8f8f8f; display:block; } .red { color:red; } /* Footer */ #footer { border-top:#e3e3e3 solid 6px; background:#4c4c4c; color:#c1c1c1; } #footer #menu a { color:#fff; } #footer #menu a:hover { text-decoration:underline; }
Java
/* * Changes: * Jan 22, 2010: Created (Cristiano Giuffrida) */ #include "inc.h" /*===========================================================================* * do_up * *===========================================================================*/ PUBLIC int do_up(m_ptr) message *m_ptr; /* request message pointer */ { /* A request was made to start a new system service. */ struct rproc *rp; struct rprocpub *rpub; int r; struct rs_start rs_start; int noblock; /* Check if the call can be allowed. */ if((r = check_call_permission(m_ptr->m_source, RS_UP, NULL)) != OK) return r; /* Allocate a new system service slot. */ r = alloc_slot(&rp); if(r != OK) { printf("RS: do_up: unable to allocate a new slot: %d\n", r); return r; } rpub = rp->r_pub; /* Copy the request structure. */ r = copy_rs_start(m_ptr->m_source, m_ptr->RS_CMD_ADDR, &rs_start); if (r != OK) { return r; } noblock = (rs_start.rss_flags & RSS_NOBLOCK); /* Initialize the slot as requested. */ r = init_slot(rp, &rs_start, m_ptr->m_source); if(r != OK) { printf("RS: do_up: unable to init the new slot: %d\n", r); return r; } /* Check for duplicates */ if(lookup_slot_by_label(rpub->label)) { printf("RS: service with the same label '%s' already exists\n", rpub->label); return EBUSY; } if(rpub->dev_nr>0 && lookup_slot_by_dev_nr(rpub->dev_nr)) { printf("RS: service with the same device number %d already exists\n", rpub->dev_nr); return EBUSY; } /* All information was gathered. Now try to start the system service. */ r = start_service(rp); if(r != OK) { return r; } /* Unblock the caller immediately if requested. */ if(noblock) { return OK; } /* Late reply - send a reply when service completes initialization. */ rp->r_flags |= RS_LATEREPLY; rp->r_caller = m_ptr->m_source; rp->r_caller_request = RS_UP; return EDONTREPLY; } /*===========================================================================* * do_down * *===========================================================================*/ PUBLIC int do_down(message *m_ptr) { register struct rproc *rp; register struct rprocpub *rpub; int s; char label[RS_MAX_LABEL_LEN]; /* Copy label. */ s = copy_label(m_ptr->m_source, m_ptr->RS_CMD_ADDR, m_ptr->RS_CMD_LEN, label, sizeof(label)); if(s != OK) { return s; } /* Lookup slot by label. */ rp = lookup_slot_by_label(label); if(!rp) { if(rs_verbose) printf("RS: do_down: service '%s' not found\n", label); return(ESRCH); } rpub = rp->r_pub; /* Check if the call can be allowed. */ if((s = check_call_permission(m_ptr->m_source, RS_DOWN, rp)) != OK) return s; /* Stop service. */ if (rp->r_flags & RS_TERMINATED) { /* A recovery script is requesting us to bring down the service. * The service is already gone, simply perform cleanup. */ if(rs_verbose) printf("RS: recovery script performs service down...\n"); unpublish_service(rp); cleanup_service(rp); return(OK); } stop_service(rp,RS_EXITING); /* Late reply - send a reply when service dies. */ rp->r_flags |= RS_LATEREPLY; rp->r_caller = m_ptr->m_source; rp->r_caller_request = RS_DOWN; return EDONTREPLY; } /*===========================================================================* * do_restart * *===========================================================================*/ PUBLIC int do_restart(message *m_ptr) { struct rproc *rp; int s, r; char label[RS_MAX_LABEL_LEN]; char script[MAX_SCRIPT_LEN]; /* Copy label. */ s = copy_label(m_ptr->m_source, m_ptr->RS_CMD_ADDR, m_ptr->RS_CMD_LEN, label, sizeof(label)); if(s != OK) { return s; } /* Lookup slot by label. */ rp = lookup_slot_by_label(label); if(!rp) { if(rs_verbose) printf("RS: do_restart: service '%s' not found\n", label); return(ESRCH); } /* Check if the call can be allowed. */ if((r = check_call_permission(m_ptr->m_source, RS_RESTART, rp)) != OK) return r; /* We can only be asked to restart a service from a recovery script. */ if (! (rp->r_flags & RS_TERMINATED) ) { if(rs_verbose) printf("RS: %s is still running\n", srv_to_string(rp)); return EBUSY; } if(rs_verbose) printf("RS: recovery script performs service restart...\n"); /* Restart the service, but make sure we don't call the script again. */ strcpy(script, rp->r_script); rp->r_script[0] = '\0'; restart_service(rp); strcpy(rp->r_script, script); return OK; } /*===========================================================================* * do_refresh * *===========================================================================*/ PUBLIC int do_refresh(message *m_ptr) { register struct rproc *rp; register struct rprocpub *rpub; int s; char label[RS_MAX_LABEL_LEN]; /* Copy label. */ s = copy_label(m_ptr->m_source, m_ptr->RS_CMD_ADDR, m_ptr->RS_CMD_LEN, label, sizeof(label)); if(s != OK) { return s; } /* Lookup slot by label. */ rp = lookup_slot_by_label(label); if(!rp) { if(rs_verbose) printf("RS: do_refresh: service '%s' not found\n", label); return(ESRCH); } rpub = rp->r_pub; /* Check if the call can be allowed. */ if((s = check_call_permission(m_ptr->m_source, RS_REFRESH, rp)) != OK) return s; /* Refresh service. */ if(rs_verbose) printf("RS: %s refreshing\n", srv_to_string(rp)); stop_service(rp,RS_REFRESHING); return OK; } /*===========================================================================* * do_shutdown * *===========================================================================*/ PUBLIC int do_shutdown(message *m_ptr) { int slot_nr; struct rproc *rp; int r; /* Check if the call can be allowed. */ if (m_ptr != NULL) { if((r = check_call_permission(m_ptr->m_source, RS_SHUTDOWN, NULL)) != OK) return r; } if(rs_verbose) printf("RS: shutting down...\n"); /* Set flag to tell RS we are shutting down. */ shutting_down = TRUE; /* Don't restart dead services. */ for (slot_nr = 0; slot_nr < NR_SYS_PROCS; slot_nr++) { rp = &rproc[slot_nr]; if (rp->r_flags & RS_IN_USE) { rp->r_flags |= RS_EXITING; } } return(OK); } /*===========================================================================* * do_init_ready * *===========================================================================*/ PUBLIC int do_init_ready(message *m_ptr) { int who_p; struct rproc *rp; struct rprocpub *rpub; int result; int r; who_p = _ENDPOINT_P(m_ptr->m_source); rp = rproc_ptr[who_p]; rpub = rp->r_pub; result = m_ptr->RS_INIT_RESULT; /* Make sure the originating service was requested to initialize. */ if(! (rp->r_flags & RS_INITIALIZING) ) { if(rs_verbose) printf("RS: do_init_ready: got unexpected init ready msg from %d\n", m_ptr->m_source); return(EDONTREPLY); } /* Check if something went wrong and the service failed to init. * In that case, kill the service. */ if(result != OK) { if(rs_verbose) printf("RS: %s initialization error: %s\n", srv_to_string(rp), init_strerror(result)); crash_service(rp); /* simulate crash */ return(EDONTREPLY); } /* Mark the slot as no longer initializing. */ rp->r_flags &= ~RS_INITIALIZING; rp->r_check_tm = 0; getuptime(&rp->r_alive_tm); /* See if a late reply has to be sent. */ late_reply(rp, OK); if(rs_verbose) printf("RS: %s initialized\n", srv_to_string(rp)); /* If the service has completed initialization after a live * update, end the update now. */ if(rp->r_flags & RS_UPDATING) { printf("RS: update succeeded\n"); end_update(OK); } /* If the service has completed initialization after a crash * make the new instance active and cleanup the old replica. */ if(rp->r_prev_rp) { cleanup_service(rp->r_prev_rp); rp->r_prev_rp = NULL; if(rs_verbose) printf("RS: %s completed restart\n", srv_to_string(rp)); } /* If we must keep a replica of this system service, create it now. */ if(rpub->sys_flags & SF_USE_REPL) { if ((r = clone_service(rp)) != OK) { printf("RS: warning: unable to clone %s\n", srv_to_string(rp)); } } return(OK); } /*===========================================================================* * do_update * *===========================================================================*/ PUBLIC int do_update(message *m_ptr) { struct rproc *rp; struct rproc *new_rp; struct rprocpub *rpub; struct rs_start rs_start; int noblock; int s; char label[RS_MAX_LABEL_LEN]; int lu_state; int prepare_maxtime; /* Copy the request structure. */ s = copy_rs_start(m_ptr->m_source, m_ptr->RS_CMD_ADDR, &rs_start); if (s != OK) { return s; } noblock = (rs_start.rss_flags & RSS_NOBLOCK); /* Copy label. */ s = copy_label(m_ptr->m_source, rs_start.rss_label.l_addr, rs_start.rss_label.l_len, label, sizeof(label)); if(s != OK) { return s; } /* Lookup slot by label. */ rp = lookup_slot_by_label(label); if(!rp) { if(rs_verbose) printf("RS: do_update: service '%s' not found\n", label); return ESRCH; } rpub = rp->r_pub; /* Check if the call can be allowed. */ if((s = check_call_permission(m_ptr->m_source, RS_UPDATE, rp)) != OK) return s; /* Retrieve live update state. */ lu_state = m_ptr->RS_LU_STATE; if(lu_state == SEF_LU_STATE_NULL) { return(EINVAL); } /* Retrieve prepare max time. */ prepare_maxtime = m_ptr->RS_LU_PREPARE_MAXTIME; if(prepare_maxtime) { if(prepare_maxtime < 0 || prepare_maxtime > RS_MAX_PREPARE_MAXTIME) { return(EINVAL); } } else { prepare_maxtime = RS_DEFAULT_PREPARE_MAXTIME; } /* Make sure we are not already updating. */ if(rupdate.flags & RS_UPDATING) { if(rs_verbose) printf("RS: do_update: an update is already in progress\n"); return EBUSY; } /* Allocate a system service slot for the new version. */ s = alloc_slot(&new_rp); if(s != OK) { printf("RS: do_update: unable to allocate a new slot: %d\n", s); return s; } /* Initialize the slot as requested. */ s = init_slot(new_rp, &rs_start, m_ptr->m_source); if(s != OK) { printf("RS: do_update: unable to init the new slot: %d\n", s); return s; } /* Let the new version inherit defaults from the old one. */ inherit_service_defaults(rp, new_rp); /* Create new version of the service but don't let it run. */ s = create_service(new_rp); if(s != OK) { printf("RS: do_update: unable to create a new service: %d\n", s); return s; } /* Link old version to new version and mark both as updating. */ rp->r_new_rp = new_rp; new_rp->r_old_rp = rp; rp->r_flags |= RS_UPDATING; rp->r_new_rp->r_flags |= RS_UPDATING; rupdate.flags |= RS_UPDATING; getuptime(&rupdate.prepare_tm); rupdate.prepare_maxtime = prepare_maxtime; rupdate.rp = rp; if(rs_verbose) printf("RS: %s updating\n", srv_to_string(rp)); /* Request to update. */ m_ptr->m_type = RS_LU_PREPARE; asynsend3(rpub->endpoint, m_ptr, AMF_NOREPLY); /* Unblock the caller immediately if requested. */ if(noblock) { return OK; } /* Late reply - send a reply when the new version completes initialization. */ rp->r_flags |= RS_LATEREPLY; rp->r_caller = m_ptr->m_source; rp->r_caller_request = RS_UPDATE; return EDONTREPLY; } /*===========================================================================* * do_upd_ready * *===========================================================================*/ PUBLIC int do_upd_ready(message *m_ptr) { struct rproc *rp, *old_rp, *new_rp; int who_p; int result; int r; who_p = _ENDPOINT_P(m_ptr->m_source); rp = rproc_ptr[who_p]; result = m_ptr->RS_LU_RESULT; /* Make sure the originating service was requested to prepare for update. */ if(rp != rupdate.rp) { if(rs_verbose) printf("RS: do_upd_ready: got unexpected update ready msg from %d\n", m_ptr->m_source); return(EINVAL); } /* Check if something went wrong and the service failed to prepare * for the update. In that case, end the update process. The old version will * be replied to and continue executing. */ if(result != OK) { end_update(result); printf("RS: update failed: %s\n", lu_strerror(result)); return OK; } /* Perform the update. */ old_rp = rp; new_rp = rp->r_new_rp; r = update_service(&old_rp, &new_rp); if(r != OK) { end_update(r); printf("RS: update failed: error %d\n", r); return r; } /* Let the new version run. */ r = run_service(new_rp, SEF_INIT_LU); if(r != OK) { update_service(&new_rp, &old_rp); /* rollback, can't fail. */ end_update(r); printf("RS: update failed: error %d\n", r); return r; } return(EDONTREPLY); } /*===========================================================================* * do_period * *===========================================================================*/ PUBLIC void do_period(m_ptr) message *m_ptr; { register struct rproc *rp; register struct rprocpub *rpub; clock_t now = m_ptr->NOTIFY_TIMESTAMP; int s; long period; /* If an update is in progress, check its status. */ if(rupdate.flags & RS_UPDATING) { update_period(m_ptr); } /* Search system services table. Only check slots that are in use and not * updating. */ for (rp=BEG_RPROC_ADDR; rp<END_RPROC_ADDR; rp++) { rpub = rp->r_pub; if ((rp->r_flags & RS_IN_USE) && !(rp->r_flags & RS_UPDATING)) { /* Compute period. */ period = rpub->period; if(rp->r_flags & RS_INITIALIZING) { period = RS_INIT_T; } /* If the service is to be revived (because it repeatedly exited, * and was not directly restarted), the binary backoff field is * greater than zero. */ if (rp->r_backoff > 0) { rp->r_backoff -= 1; if (rp->r_backoff == 0) { restart_service(rp); } } /* If the service was signaled with a SIGTERM and fails to respond, * kill the system service with a SIGKILL signal. */ else if (rp->r_stop_tm > 0 && now - rp->r_stop_tm > 2*RS_DELTA_T && rp->r_pid > 0) { crash_service(rp); /* simulate crash */ rp->r_stop_tm = 0; } /* There seems to be no special conditions. If the service has a * period assigned check its status. */ else if (period > 0) { /* Check if an answer to a status request is still pending. If * the service didn't respond within time, kill it to simulate * a crash. The failure will be detected and the service will * be restarted automatically. */ if (rp->r_alive_tm < rp->r_check_tm) { if (now - rp->r_alive_tm > 2*period && rp->r_pid > 0 && !(rp->r_flags & RS_NOPINGREPLY)) { if(rs_verbose) printf("RS: %s reported late\n", srv_to_string(rp)); rp->r_flags |= RS_NOPINGREPLY; crash_service(rp); /* simulate crash */ } } /* No answer pending. Check if a period expired since the last * check and, if so request the system service's status. */ else if (now - rp->r_check_tm > rpub->period) { notify(rpub->endpoint); /* request status */ rp->r_check_tm = now; /* mark time */ } } } } /* Reschedule a synchronous alarm for the next period. */ if (OK != (s=sys_setalarm(RS_DELTA_T, 0))) panic("couldn't set alarm: %d", s); } /*===========================================================================* * do_sigchld * *===========================================================================*/ PUBLIC void do_sigchld() { /* PM informed us that there are dead children to cleanup. Go get them. */ pid_t pid; int status; struct rproc *rp; struct rproc **rps; struct rprocpub *rpub; int i, nr_rps; if(rs_verbose) printf("RS: got SIGCHLD signal, cleaning up dead children\n"); while ( (pid = waitpid(-1, &status, WNOHANG)) != 0 ) { rp = lookup_slot_by_pid(pid); if(rp != NULL) { rpub = rp->r_pub; if(rs_verbose) printf("RS: %s exited via another signal manager\n", srv_to_string(rp)); /* The slot is still there. This means RS is not the signal * manager assigned to the process. Ignore the event but * free slots for all the service instances and send a late * reply if necessary. */ get_service_instances(rp, &rps, &nr_rps); for(i=0;i<nr_rps;i++) { if(rupdate.flags & RS_UPDATING) { rupdate.flags &= ~RS_UPDATING; } free_slot(rps[i]); } } } } /*===========================================================================* * do_getsysinfo * *===========================================================================*/ PUBLIC int do_getsysinfo(m_ptr) message *m_ptr; { vir_bytes src_addr, dst_addr; int dst_proc; size_t len; int s; /* Check if the call can be allowed. */ if((s = check_call_permission(m_ptr->m_source, 0, NULL)) != OK) return s; switch(m_ptr->m1_i1) { case SI_PROC_TAB: src_addr = (vir_bytes) rproc; len = sizeof(struct rproc) * NR_SYS_PROCS; break; case SI_PROCPUB_TAB: src_addr = (vir_bytes) rprocpub; len = sizeof(struct rprocpub) * NR_SYS_PROCS; break; default: return(EINVAL); } dst_proc = m_ptr->m_source; dst_addr = (vir_bytes) m_ptr->m1_p1; if (OK != (s=sys_datacopy(SELF, src_addr, dst_proc, dst_addr, len))) return(s); return(OK); } /*===========================================================================* * do_lookup * *===========================================================================*/ PUBLIC int do_lookup(m_ptr) message *m_ptr; { static char namebuf[100]; int len, r; struct rproc *rrp; struct rprocpub *rrpub; len = m_ptr->RS_NAME_LEN; if(len < 2 || len >= sizeof(namebuf)) { printf("RS: len too weird (%d)\n", len); return EINVAL; } if((r=sys_vircopy(m_ptr->m_source, D, (vir_bytes) m_ptr->RS_NAME, SELF, D, (vir_bytes) namebuf, len)) != OK) { printf("RS: name copy failed\n"); return r; } namebuf[len] = '\0'; rrp = lookup_slot_by_label(namebuf); if(!rrp) { return ESRCH; } rrpub = rrp->r_pub; m_ptr->RS_ENDPOINT = rrpub->endpoint; return OK; }
Java
Template.HostList.events({ }); Template.HostList.helpers({ // Get list of Hosts sorted by the sort field. hosts: function () { return Hosts.find({}, {sort: {sort: 1}}); } }); Template.HostList.rendered = function () { // Make rows sortable/draggable using Jquery-UI. this.$('#sortable').sortable({ stop: function (event, ui) { // Define target row items. target = ui.item.get(0); before = ui.item.prev().get(0); after = ui.item.next().get(0); // Change the sort value dependnig on target location. // If target is now first, subtract 1 from sort value. if (!before) { newSort = Blaze.getData(after).sort - 1; // If target is now last, add 1 to sort value. } else if (!after) { newSort = Blaze.getData(before).sort + 1; // Get value of prev and next elements // to determine new target sort value. } else { newSort = (Blaze.getData(after).sort + Blaze.getData(before).sort) / 2; } // Update the database with new sort value. Hosts.update({_id: Blaze.getData(target)._id}, { $set: { sort: newSort } }); } }); };
Java
import Helper, { states } from './_helper'; import { module, test } from 'qunit'; module('Integration | ORM | Has Many | Named Reflexive | association #set', function(hooks) { hooks.beforeEach(function() { this.helper = new Helper(); }); /* The model can update its association via parent, for all states */ states.forEach((state) => { test(`a ${state} can update its association to a list of saved children`, function(assert) { let [ tag, originalTags ] = this.helper[state](); let savedTag = this.helper.savedChild(); tag.labels = [ savedTag ]; assert.ok(tag.labels.includes(savedTag)); assert.equal(tag.labelIds[0], savedTag.id); assert.ok(savedTag.labels.includes(tag), 'the inverse was set'); tag.save(); originalTags.forEach(originalTag => { originalTag.reload(); assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared'); }); }); test(`a ${state} can update its association to a new parent`, function(assert) { let [ tag, originalTags ] = this.helper[state](); let newTag = this.helper.newChild(); tag.labels = [ newTag ]; assert.ok(tag.labels.includes(newTag)); assert.equal(tag.labelIds[0], undefined); assert.ok(newTag.labels.includes(tag), 'the inverse was set'); tag.save(); originalTags.forEach(originalTag => { originalTag.reload(); assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared'); }); }); test(`a ${state} can clear its association via an empty list`, function(assert) { let [ tag, originalTags ] = this.helper[state](); tag.labels = [ ]; assert.deepEqual(tag.labelIds, [ ]); assert.equal(tag.labels.models.length, 0); tag.save(); originalTags.forEach(originalTag => { originalTag.reload(); assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared'); }); }); test(`a ${state} can clear its association via an empty list`, function(assert) { let [ tag, originalTags ] = this.helper[state](); tag.labels = null; assert.deepEqual(tag.labelIds, [ ]); assert.equal(tag.labels.models.length, 0); tag.save(); originalTags.forEach(originalTag => { originalTag.reload(); assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared'); }); }); }); });
Java
{{ partial "head.html" . }} {{ partial "body-before.html" . }} <!-- Layout for Content Area of Markdown Page Goes Here --> <div id="default__title">{{ .Title }}</div> <div id="default__subtitle">{{ .Params.subtitle }}</div> <div>{{ .Date.Format "Jan 02, 2006" }}</div> <div id="default_text"> {{ .Content }} </div> <!-- ************************************************** --> {{ partial "body-after.html" . }}
Java
import * as React from 'react'; export interface LabelDetailProps { [key: string]: any; /** An element type to render as (string or function). */ as?: any; /** Primary content. */ children?: React.ReactNode; /** Additional classes. */ className?: string; /** Shorthand for primary content. */ content?: React.ReactNode; } declare const LabelDetail: React.StatelessComponent<LabelDetailProps>; export default LabelDetail;
Java
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Runtime.Scheduler; using UnitTests.GrainInterfaces; using UnitTests.Grains; namespace UnitTestGrains { public class TimerGrain : Grain, ITimerGrain { private bool deactivating; int counter = 0; Dictionary<string, IDisposable> allTimers; IDisposable defaultTimer; private static readonly TimeSpan period = TimeSpan.FromMilliseconds(100); string DefaultTimerName = "DEFAULT TIMER"; ISchedulingContext context; private Logger logger; public override Task OnActivateAsync() { ThrowIfDeactivating(); logger = this.GetLogger("TimerGrain_" + base.Data.Address.ToString()); context = RuntimeContext.Current.ActivationContext; defaultTimer = this.RegisterTimer(Tick, DefaultTimerName, period, period); allTimers = new Dictionary<string, IDisposable>(); return Task.CompletedTask; } public Task StopDefaultTimer() { ThrowIfDeactivating(); defaultTimer.Dispose(); return Task.CompletedTask; } private Task Tick(object data) { counter++; logger.Info(data.ToString() + " Tick # " + counter + " RuntimeContext = " + RuntimeContext.Current.ActivationContext.ToString()); // make sure we run in the right activation context. if(!Equals(context, RuntimeContext.Current.ActivationContext)) logger.Error((int)ErrorCode.Runtime_Error_100146, "grain not running in the right activation context"); string name = (string)data; IDisposable timer = null; if (name == DefaultTimerName) { timer = defaultTimer; } else { timer = allTimers[(string)data]; } if(timer == null) logger.Error((int)ErrorCode.Runtime_Error_100146, "Timer is null"); if (timer != null && counter > 10000) { // do not let orphan timers ticking for long periods timer.Dispose(); } return Task.CompletedTask; } public Task<TimeSpan> GetTimerPeriod() { return Task.FromResult(period); } public Task<int> GetCounter() { ThrowIfDeactivating(); return Task.FromResult(counter); } public Task SetCounter(int value) { ThrowIfDeactivating(); lock (this) { counter = value; } return Task.CompletedTask; } public Task StartTimer(string timerName) { ThrowIfDeactivating(); IDisposable timer = this.RegisterTimer(Tick, timerName, TimeSpan.Zero, period); allTimers.Add(timerName, timer); return Task.CompletedTask; } public Task StopTimer(string timerName) { ThrowIfDeactivating(); IDisposable timer = allTimers[timerName]; timer.Dispose(); return Task.CompletedTask; } public Task LongWait(TimeSpan time) { ThrowIfDeactivating(); Thread.Sleep(time); return Task.CompletedTask; } public Task Deactivate() { deactivating = true; DeactivateOnIdle(); return Task.CompletedTask; } private void ThrowIfDeactivating() { if (deactivating) throw new InvalidOperationException("This activation is deactivating"); } } public class TimerCallGrain : Grain, ITimerCallGrain { private int tickCount; private Exception tickException; private IDisposable timer; private string timerName; private ISchedulingContext context; private TaskScheduler activationTaskScheduler; private Logger logger; public Task<int> GetTickCount() { return Task.FromResult(tickCount); } public Task<Exception> GetException() { return Task.FromResult(tickException); } public override Task OnActivateAsync() { logger = this.GetLogger("TimerCallGrain_" + base.Data.Address); context = RuntimeContext.Current.ActivationContext; activationTaskScheduler = TaskScheduler.Current; return Task.CompletedTask; } public Task StartTimer(string name, TimeSpan delay) { logger.Info("StartTimer Name={0} Delay={1}", name, delay); this.timerName = name; this.timer = base.RegisterTimer(TimerTick, name, delay, Constants.INFINITE_TIMESPAN); // One shot timer return Task.CompletedTask; } public Task StopTimer(string name) { logger.Info("StopTimer Name={0}", name); if (name != this.timerName) { throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name)); } timer.Dispose(); return Task.CompletedTask; } private async Task TimerTick(object data) { try { await ProcessTimerTick(data); } catch (Exception exc) { this.tickException = exc; throw; } } private async Task ProcessTimerTick(object data) { string step = "TimerTick"; LogStatus(step); // make sure we run in the right activation context. CheckRuntimeContext(step); string name = (string)data; if (name != this.timerName) { throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name)); } ISimpleGrain grain = GrainFactory.GetGrain<ISimpleGrain>(0, SimpleGrain.SimpleGrainNamePrefix); LogStatus("Before grain call #1"); await grain.SetA(tickCount); step = "After grain call #1"; LogStatus(step); CheckRuntimeContext(step); LogStatus("Before Delay"); await Task.Delay(TimeSpan.FromSeconds(1)); step = "After Delay"; LogStatus(step); CheckRuntimeContext(step); LogStatus("Before grain call #2"); await grain.SetB(tickCount); step = "After grain call #2"; LogStatus(step); CheckRuntimeContext(step); LogStatus("Before grain call #3"); int res = await grain.GetAxB(); step = "After grain call #3 - Result = " + res; LogStatus(step); CheckRuntimeContext(step); tickCount++; } private void CheckRuntimeContext(string what) { if (RuntimeContext.Current.ActivationContext == null || !RuntimeContext.Current.ActivationContext.Equals(context)) { throw new InvalidOperationException( string.Format("{0} in timer callback with unexpected activation context: Expected={1} Actual={2}", what, context, RuntimeContext.Current.ActivationContext)); } if (TaskScheduler.Current.Equals(activationTaskScheduler) && TaskScheduler.Current is ActivationTaskScheduler) { // Everything is as expected } else { throw new InvalidOperationException( string.Format("{0} in timer callback with unexpected TaskScheduler.Current context: Expected={1} Actual={2}", what, activationTaskScheduler, TaskScheduler.Current)); } } private void LogStatus(string what) { logger.Info("{0} Tick # {1} - {2} - RuntimeContext.Current={3} TaskScheduler.Current={4} CurrentWorkerThread={5}", timerName, tickCount, what, RuntimeContext.Current, TaskScheduler.Current, WorkerPoolThread.CurrentWorkerThread); } } }
Java
--- layout: theme title: "Streamflow Prediction Research" date: 2016-08-03 16:55:00 categories: - themes img: theme_streamflow_prediction.jpg ref: stream tags: [themes] --- One of the four overarching research themes addressed in this collection of work. Our ability to understand how much and when... < more about this research theme, coming soon >
Java
#!/usr/bin/env python import sys def fix_terminator(tokens): if not tokens: return last = tokens[-1] if last not in ('.', '?', '!') and last.endswith('.'): tokens[-1] = last[:-1] tokens.append('.') def balance_quotes(tokens): count = tokens.count("'") if not count: return processed = 0 for i, token in enumerate(tokens): if token == "'": if processed % 2 == 0 and (i == 0 or processed != count - 1): tokens[i] = "`" processed += 1 def output(tokens): if not tokens: return # fix_terminator(tokens) balance_quotes(tokens) print ' '.join(tokens) prev = None for line in sys.stdin: tokens = line.split() if len(tokens) == 1 and tokens[0] in ('"', "'", ')', ']'): prev.append(tokens[0]) else: output(prev) prev = tokens output(prev)
Java
<?php namespace YOOtheme\Widgetkit\Framework\View\Asset; interface AssetInterface { /** * Gets the name. * * @return string */ public function getName(); /** * Gets the source. * * @return string */ public function getSource(); /** * Gets the dependencies. * * @return array */ public function getDependencies(); /** * Gets the content. * * @return string */ public function getContent(); /** * Sets the content. * * @param string $content */ public function setContent($content); /** * Gets all options. * * @return array */ public function getOptions(); /** * Gets a option. * * @param string $name * @return mixed */ public function getOption($name); /** * Sets a option. * * @param string $name * @param mixed $value */ public function setOption($name, $value); /** * Gets the unique hash. * * @param string $salt * @return string */ public function hash($salt = ''); /** * Applies filters and returns the asset as a string. * * @param array $filters * @return string */ public function dump(array $filters = array()); }
Java
class Item < ActiveRecord::Base serialize :raw_info , Hash has_many :ownerships , foreign_key: "item_id" , dependent: :destroy has_many :users , through: :ownerships has_many :wants, class_name: "Want", foreign_key: "item_id", dependent: :destroy has_many :want_users, through: :wants, source: :user has_many :haves, class_name: "Have", foreign_key: "item_id", dependent: :destroy has_many :have_users, through: :haves, source: :user end
Java
unsigned, 32-bit integer
Java
package br.pucrio.opus.smells.tests.visitor; import java.io.File; import java.io.IOException; import java.util.List; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import br.pucrio.opus.smells.ast.visitors.FieldDeclarationCollector; import br.pucrio.opus.smells.tests.util.CompilationUnitLoader; public class FieldDeclarationCollectorTest { private CompilationUnit compilationUnit; @Before public void setUp() throws IOException{ File file = new File("test/br/pucrio/opus/smells/tests/dummy/FieldDeclaration.java"); this.compilationUnit = CompilationUnitLoader.getCompilationUnit(file); } @Test public void allFieldsCollectionCountTest() { FieldDeclarationCollector visitor = new FieldDeclarationCollector(); this.compilationUnit.accept(visitor); List<FieldDeclaration> collectedFields = visitor.getNodesCollected(); Assert.assertEquals(6, collectedFields.size()); } }
Java
module rl.utilities.services.momentWrapper { export var moduleName: string = 'rl.utilities.services.momentWrapper'; export var serviceName: string = 'momentWrapper'; export function momentWrapper(): void { 'use strict'; // Using `any` instead of MomentStatic because // createFromInputFallback doesn't appear to be // defined in MomentStatic... :-( var momentWrapper: any = moment; // moment must already be loaded // Set default method for handling non-ISO date conversions. // See 4/28 comment in https://github.com/moment/moment/issues/1407 // This also prevents the deprecation warning message to the console. momentWrapper.createFromInputFallback = (config: any): void => { config._d = new Date(config._i); }; return momentWrapper; } angular.module(moduleName, []) .factory(serviceName, momentWrapper); }
Java
/* describe, it, afterEach, beforeEach */ import './snoocore-mocha'; import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; chai.use(chaiAsPromised); let expect = chai.expect; import config from '../config'; import util from './util'; import ResponseError from '../../src/ResponseError'; import Endpoint from '../../src/Endpoint'; describe(__filename, function () { this.timeout(config.testTimeout); it('should get a proper response error', function() { var message = 'oh hello there'; var response = { _status: 200, _body: 'a response body' }; var userConfig = util.getScriptUserConfig(); var endpoint = new Endpoint(userConfig, userConfig.serverOAuth, 'get', '/some/path', {}, // headers { some: 'args' }); var responseError = new ResponseError(message, response, endpoint); expect(responseError instanceof ResponseError); expect(responseError.status).to.eql(200); expect(responseError.url).to.eql('https://oauth.reddit.com/some/path'); expect(responseError.args).to.eql({ some: 'args', api_type: 'json' }); expect(responseError.message.indexOf('oh hello there')).to.not.eql(-1); expect(responseError.message.indexOf('Response Status')).to.not.eql(-1); expect(responseError.message.indexOf('Endpoint URL')).to.not.eql(-1); expect(responseError.message.indexOf('Arguments')).to.not.eql(-1); expect(responseError.message.indexOf('Response Body')).to.not.eql(-1); }); });
Java
# -*- coding: utf-8 -*- """ webModifySqlAPI ~~~~~~~~~~~~~~ 为web应用与后台数据库操作(插入,更新,删除操作)的接口 api_functions 中的DataApiFunc.py为其接口函数汇聚点,所有全局变量设置都在此;所有后台函数调用都在此设置 Implementation helpers for the JSON support in Flask. :copyright: (c) 2015 by Armin kissf lu. :license: ukl, see LICENSE for more details. """ from . import api from flask import json from flask import request from bson import json_util # DataApiFunc 为数据库更新、插入、删除数据等操作函数 from api_functions.DataApiFunc import (deleManuleVsimSrc, insertManuleVsimSrc, updateManuleVsimSrc, deleteNewVsimTestInfo, insertNewVsimTestInfo, updateNewVsimTestInfo) @api.route('/delet_manulVsim/', methods=['POST']) def delet_manulVsim(): """ :return: """ if request.method == 'POST': arrayData = request.get_array(field_name='file') return deleManuleVsimSrc(array_data=arrayData) else: returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []} return json.dumps(returnJsonData, sort_keys=True, indent=4, default=json_util.default) @api.route('/insert_manulVsim/', methods=['POST']) def insert_manulVsim(): """ :return: """ if request.method == 'POST': arrayData = request.get_array(field_name='file') return insertManuleVsimSrc(array_data=arrayData) else: returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []} return json.dumps(returnJsonData, sort_keys=True, indent=4, default=json_util.default) @api.route('/update_manulVsim/', methods=['POST']) def update_manulVsim(): """ :return: """ if request.method == 'POST': arrayData = request.get_array(field_name='file') return updateManuleVsimSrc(array_data=arrayData) else: returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []} return json.dumps(returnJsonData, sort_keys=True, indent=4, default=json_util.default) @api.route('/delet_newvsimtest_info_table/', methods=['POST']) def delet_newvsimtest_info_table(): """ :return: """ if request.method == 'POST': arrayData = request.get_array(field_name='file') return deleteNewVsimTestInfo(array_data=arrayData) else: returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []} return json.dumps(returnJsonData, sort_keys=True, indent=4, default=json_util.default) @api.route('/insert_newvsimtest_info_table/', methods=['POST']) def insert_newvsimtest_info_table(): """ :return: """ if request.method == 'POST': arrayData = request.get_array(field_name='file') return insertNewVsimTestInfo(array_data=arrayData) else: returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []} return json.dumps(returnJsonData, sort_keys=True, indent=4, default=json_util.default) @api.route('/update_newvsimtest_info_table/', methods=['POST']) def update_newvsimtest_info_table(): """ :return: """ if request.method == 'POST': arrayData = request.get_array(field_name='file') return updateNewVsimTestInfo(array_data=arrayData) else: returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []} return json.dumps(returnJsonData, sort_keys=True, indent=4, default=json_util.default)
Java
--- title: 異言の賜物 date: 08/07/2018 --- イエスの命令に従い、信者たちはエルサレムで約束の“霊”を待ちました。彼らは熱心に祈り、心から悔い改め、賛美しながら待ったのです。その日が来たとき、彼らは「一つになって集まって」(使徒 2:1)いました。たぶん、使徒言行録 1章の同じ家の上の部屋でしょう。しかし間もなく、彼らはもっと公の場に出て行くことになります(同 2:6 ~ 13)。 使徒言行録 2:1 ~ 3を読んでください。“霊”の注ぎの光景は強烈なものでした。突然、激しい嵐のとどろきのような音が天から聞こえてきてその場を満たし、次には炎の舌のようなものがあらわれて、そこにいた人々の上にとどまったのです。聖書では、「神の顕現」、つまり神が姿をあらわされることに、火や風がしばしば伴います(例えば、出 3:2、19:18、申 4:15)。加えて、火や風は神の“霊”をあらわすためにも用いられます(ヨハ 3:8、マタ3:11)。五旬祭の場合、そのような現象の正確な意味がどうであれ、それらは、約束された霊”の注ぎという特異な瞬間が救済史の中に入り込んだしるしでした。 “霊”は常に働いてこられました。旧約聖書の時代、神の民に対するその影響力は、しばしば目立つ形であらわれましたが、決して満ちあふれるほどではありませんでした。「父祖の時代には聖霊の感化はしばしば著しく現されたが、決して満ちあふれるほどではなかった。今、救い主のみ言葉に従って、弟子たちはこの賜物を懇願し、天においてはキリストがそのとりなしをしておられた。主はその民にみ霊を注ぐことができるように、み霊の賜物をお求めになったのである」(『希望への光』1369 ページ、『患難から栄光へ』上巻 31 ページ)。 バプテスマのヨハネは、メシアの到来に伴う“霊”によるバプテスマを予告し(ルカ3:16 参照、使徒 11:16と比較)、イエス御自身もこのことを何度か口になさいました(ルカ24:49、使徒 1:8)。この注ぎは、神の前におけるイエスの最初の執り成しの業だったのでしょう(ヨハ14:16、26、15:26)。五旬祭で、その約束は成就しました。 五旬祭での“霊”によるバプテスマは、十字架におけるイエスの勝利と天でイエスが高められたことに関係する特別な出来事でしたが、“霊”に満たされることは、信者たちの人生の中で継続的に繰り返される体験です(使徒 4:8、31、11:24、13:9、52、エフェ5:18)。 `◆ あなた自身の人生の中で“霊”が働いておられるというどのような証拠を、あなたは持っていますか。`
Java
using System; using System.Collections.Generic; using Csla; namespace Templates { [Serializable] public class DynamicRootBindingList : DynamicBindingListBase<DynamicRoot> { protected override object AddNewCore() { DynamicRoot item = DataPortal.Create<DynamicRoot>(); Add(item); return item; } private static void AddObjectAuthorizationRules() { // TODO: add authorization rules //AuthorizationRules.AllowGet(typeof(DynamicRootBindingList), "Role"); //AuthorizationRules.AllowEdit(typeof(DynamicRootBindingList), "Role"); } [Fetch] private void Fetch() { // TODO: load values RaiseListChangedEvents = false; object listData = null; foreach (var item in (List<object>)listData) Add(DataPortal.Fetch<DynamicRoot>(item)); RaiseListChangedEvents = true; } } }
Java
/* * Copyright (c) 1999-2003 Damien Miller. 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 AUTHOR ``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 AUTHOR 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. */ #ifndef _DEFINES_H #define _DEFINES_H /* $Id: defines.h,v 1.171 2013/03/07 09:06:13 dtucker Exp $ */ /* Constants */ #if defined(HAVE_DECL_SHUT_RD) && HAVE_DECL_SHUT_RD == 0 enum { SHUT_RD = 0, /* No more receptions. */ SHUT_WR, /* No more transmissions. */ SHUT_RDWR /* No more receptions or transmissions. */ }; # define SHUT_RD SHUT_RD # define SHUT_WR SHUT_WR # define SHUT_RDWR SHUT_RDWR #endif /* * Definitions for IP type of service (ip_tos) */ #include <netinet/in_systm.h> #include <netinet/ip.h> #ifndef IPTOS_LOWDELAY # define IPTOS_LOWDELAY 0x10 # define IPTOS_THROUGHPUT 0x08 # define IPTOS_RELIABILITY 0x04 # define IPTOS_LOWCOST 0x02 # define IPTOS_MINCOST IPTOS_LOWCOST #endif /* IPTOS_LOWDELAY */ /* * Definitions for DiffServ Codepoints as per RFC2474 */ #ifndef IPTOS_DSCP_AF11 # define IPTOS_DSCP_AF11 0x28 # define IPTOS_DSCP_AF12 0x30 # define IPTOS_DSCP_AF13 0x38 # define IPTOS_DSCP_AF21 0x48 # define IPTOS_DSCP_AF22 0x50 # define IPTOS_DSCP_AF23 0x58 # define IPTOS_DSCP_AF31 0x68 # define IPTOS_DSCP_AF32 0x70 # define IPTOS_DSCP_AF33 0x78 # define IPTOS_DSCP_AF41 0x88 # define IPTOS_DSCP_AF42 0x90 # define IPTOS_DSCP_AF43 0x98 # define IPTOS_DSCP_EF 0xb8 #endif /* IPTOS_DSCP_AF11 */ #ifndef IPTOS_DSCP_CS0 # define IPTOS_DSCP_CS0 0x00 # define IPTOS_DSCP_CS1 0x20 # define IPTOS_DSCP_CS2 0x40 # define IPTOS_DSCP_CS3 0x60 # define IPTOS_DSCP_CS4 0x80 # define IPTOS_DSCP_CS5 0xa0 # define IPTOS_DSCP_CS6 0xc0 # define IPTOS_DSCP_CS7 0xe0 #endif /* IPTOS_DSCP_CS0 */ #ifndef IPTOS_DSCP_EF # define IPTOS_DSCP_EF 0xb8 #endif /* IPTOS_DSCP_EF */ #ifndef PATH_MAX # ifdef _POSIX_PATH_MAX # define PATH_MAX _POSIX_PATH_MAX # endif #endif #ifndef MAXPATHLEN # ifdef PATH_MAX # define MAXPATHLEN PATH_MAX # else /* PATH_MAX */ # define MAXPATHLEN 64 /* realpath uses a fixed buffer of size MAXPATHLEN, so force use of ours */ # ifndef BROKEN_REALPATH # define BROKEN_REALPATH 1 # endif /* BROKEN_REALPATH */ # endif /* PATH_MAX */ #endif /* MAXPATHLEN */ #if defined(HAVE_DECL_MAXSYMLINKS) && HAVE_DECL_MAXSYMLINKS == 0 # define MAXSYMLINKS 5 #endif #ifndef STDIN_FILENO # define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO # define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO # define STDERR_FILENO 2 #endif #ifndef NGROUPS_MAX /* Disable groupaccess if NGROUP_MAX is not set */ #ifdef NGROUPS #define NGROUPS_MAX NGROUPS #else #define NGROUPS_MAX 0 #endif #endif #if defined(HAVE_DECL_O_NONBLOCK) && HAVE_DECL_O_NONBLOCK == 0 # define O_NONBLOCK 00004 /* Non Blocking Open */ #endif #ifndef S_IFSOCK # define S_IFSOCK 0 #endif /* S_IFSOCK */ #ifndef S_ISDIR # define S_ISDIR(mode) (((mode) & (_S_IFMT)) == (_S_IFDIR)) #endif /* S_ISDIR */ #ifndef S_ISREG # define S_ISREG(mode) (((mode) & (_S_IFMT)) == (_S_IFREG)) #endif /* S_ISREG */ #ifndef S_ISLNK # define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) #endif /* S_ISLNK */ #ifndef S_IXUSR # define S_IXUSR 0000100 /* execute/search permission, */ # define S_IXGRP 0000010 /* execute/search permission, */ # define S_IXOTH 0000001 /* execute/search permission, */ # define _S_IWUSR 0000200 /* write permission, */ # define S_IWUSR _S_IWUSR /* write permission, owner */ # define S_IWGRP 0000020 /* write permission, group */ # define S_IWOTH 0000002 /* write permission, other */ # define S_IRUSR 0000400 /* read permission, owner */ # define S_IRGRP 0000040 /* read permission, group */ # define S_IROTH 0000004 /* read permission, other */ # define S_IRWXU 0000700 /* read, write, execute */ # define S_IRWXG 0000070 /* read, write, execute */ # define S_IRWXO 0000007 /* read, write, execute */ #endif /* S_IXUSR */ #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS) #define MAP_ANON MAP_ANONYMOUS #endif #ifndef MAP_FAILED # define MAP_FAILED ((void *)-1) #endif /* *-*-nto-qnx doesn't define this constant in the system headers */ #ifdef MISSING_NFDBITS # define NFDBITS (8 * sizeof(unsigned long)) #endif /* SCO Open Server 3 has INADDR_LOOPBACK defined in rpc/rpc.h but including rpc/rpc.h breaks Solaris 6 */ #ifndef INADDR_LOOPBACK #define INADDR_LOOPBACK ((u_long)0x7f000001) #endif /* Types */ /* If sys/types.h does not supply intXX_t, supply them ourselves */ /* (or die trying) */ #ifndef HAVE_U_INT typedef unsigned int u_int; #endif #ifndef HAVE_INTXX_T typedef signed char int8_t; # if (SIZEOF_SHORT_INT == 2) typedef short int int16_t; # else # ifdef _UNICOS # if (SIZEOF_SHORT_INT == 4) typedef short int16_t; # else typedef long int16_t; # endif # else # error "16 bit int type not found." # endif /* _UNICOS */ # endif # if (SIZEOF_INT == 4) typedef int int32_t; # else # ifdef _UNICOS typedef long int32_t; # else # error "32 bit int type not found." # endif /* _UNICOS */ # endif #endif /* If sys/types.h does not supply u_intXX_t, supply them ourselves */ #ifndef HAVE_U_INTXX_T # ifdef HAVE_UINTXX_T typedef uint8_t u_int8_t; typedef uint16_t u_int16_t; typedef uint32_t u_int32_t; # define HAVE_U_INTXX_T 1 # else typedef unsigned char u_int8_t; # if (SIZEOF_SHORT_INT == 2) typedef unsigned short int u_int16_t; # else # ifdef _UNICOS # if (SIZEOF_SHORT_INT == 4) typedef unsigned short u_int16_t; # else typedef unsigned long u_int16_t; # endif # else # error "16 bit int type not found." # endif # endif # if (SIZEOF_INT == 4) typedef unsigned int u_int32_t; # else # ifdef _UNICOS typedef unsigned long u_int32_t; # else # error "32 bit int type not found." # endif # endif # endif #define __BIT_TYPES_DEFINED__ #endif /* 64-bit types */ #ifndef HAVE_INT64_T # if (SIZEOF_LONG_INT == 8) typedef long int int64_t; # else # if (SIZEOF_LONG_LONG_INT == 8) typedef long long int int64_t; # endif # endif #endif #ifndef HAVE_U_INT64_T # if (SIZEOF_LONG_INT == 8) typedef unsigned long int u_int64_t; # else # if (SIZEOF_LONG_LONG_INT == 8) typedef unsigned long long int u_int64_t; # endif # endif #endif #ifndef HAVE_U_CHAR typedef unsigned char u_char; # define HAVE_U_CHAR #endif /* HAVE_U_CHAR */ #ifndef ULLONG_MAX # define ULLONG_MAX ((unsigned long long)-1) #endif #ifndef SIZE_T_MAX #define SIZE_T_MAX ULONG_MAX #endif /* SIZE_T_MAX */ #ifndef HAVE_SIZE_T typedef unsigned int size_t; # define HAVE_SIZE_T # define SIZE_T_MAX UINT_MAX #endif /* HAVE_SIZE_T */ #ifndef SIZE_MAX #define SIZE_MAX SIZE_T_MAX #endif #ifndef HAVE_SSIZE_T typedef int ssize_t; # define HAVE_SSIZE_T #endif /* HAVE_SSIZE_T */ #ifndef HAVE_CLOCK_T typedef long clock_t; # define HAVE_CLOCK_T #endif /* HAVE_CLOCK_T */ #ifndef HAVE_SA_FAMILY_T typedef int sa_family_t; # define HAVE_SA_FAMILY_T #endif /* HAVE_SA_FAMILY_T */ #ifndef HAVE_PID_T typedef int pid_t; # define HAVE_PID_T #endif /* HAVE_PID_T */ #ifndef HAVE_SIG_ATOMIC_T typedef int sig_atomic_t; # define HAVE_SIG_ATOMIC_T #endif /* HAVE_SIG_ATOMIC_T */ #ifndef HAVE_MODE_T typedef int mode_t; # define HAVE_MODE_T #endif /* HAVE_MODE_T */ #if !defined(HAVE_SS_FAMILY_IN_SS) && defined(HAVE___SS_FAMILY_IN_SS) # define ss_family __ss_family #endif /* !defined(HAVE_SS_FAMILY_IN_SS) && defined(HAVE_SA_FAMILY_IN_SS) */ #ifndef HAVE_SYS_UN_H struct sockaddr_un { short sun_family; /* AF_UNIX */ char sun_path[108]; /* path name (gag) */ }; #endif /* HAVE_SYS_UN_H */ #ifndef HAVE_IN_ADDR_T typedef u_int32_t in_addr_t; #endif #ifndef HAVE_IN_PORT_T typedef u_int16_t in_port_t; #endif #if defined(BROKEN_SYS_TERMIO_H) && !defined(_STRUCT_WINSIZE) #define _STRUCT_WINSIZE struct winsize { unsigned short ws_row; /* rows, in characters */ unsigned short ws_col; /* columns, in character */ unsigned short ws_xpixel; /* horizontal size, pixels */ unsigned short ws_ypixel; /* vertical size, pixels */ }; #endif /* *-*-nto-qnx does not define this type in the system headers */ #ifdef MISSING_FD_MASK typedef unsigned long int fd_mask; #endif /* Paths */ #ifndef _PATH_BSHELL # define _PATH_BSHELL "/bin/sh" #endif #ifdef USER_PATH # ifdef _PATH_STDPATH # undef _PATH_STDPATH # endif # define _PATH_STDPATH USER_PATH #endif #ifndef _PATH_STDPATH # define _PATH_STDPATH "/usr/bin:/bin:/usr/sbin:/sbin" #endif #ifndef SUPERUSER_PATH # define SUPERUSER_PATH _PATH_STDPATH #endif #ifndef _PATH_DEVNULL # define _PATH_DEVNULL "/dev/null" #endif /* user may have set a different path */ #if defined(_PATH_MAILDIR) && defined(MAIL_DIRECTORY) # undef _PATH_MAILDIR MAILDIR #endif /* defined(_PATH_MAILDIR) && defined(MAIL_DIRECTORY) */ #ifdef MAIL_DIRECTORY # define _PATH_MAILDIR MAIL_DIRECTORY #endif #ifndef _PATH_NOLOGIN # define _PATH_NOLOGIN "/etc/nologin" #endif /* Define this to be the path of the xauth program. */ #ifdef XAUTH_PATH #define _PATH_XAUTH XAUTH_PATH #endif /* XAUTH_PATH */ /* derived from XF4/xc/lib/dps/Xlibnet.h */ #ifndef X_UNIX_PATH # ifdef __hpux # define X_UNIX_PATH "/var/spool/sockets/X11/%u" # else # define X_UNIX_PATH "/tmp/.X11-unix/X%u" # endif #endif /* X_UNIX_PATH */ #define _PATH_UNIX_X X_UNIX_PATH #ifndef _PATH_TTY # define _PATH_TTY "/dev/tty" #endif /* Macros */ #if defined(HAVE_LOGIN_GETCAPBOOL) && defined(HAVE_LOGIN_CAP_H) # define HAVE_LOGIN_CAP #endif #ifndef MAX # define MAX(a,b) (((a)>(b))?(a):(b)) # define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef roundup # define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) #endif #ifndef timersub #define timersub(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0) #endif #ifndef TIMEVAL_TO_TIMESPEC #define TIMEVAL_TO_TIMESPEC(tv, ts) { \ (ts)->tv_sec = (tv)->tv_sec; \ (ts)->tv_nsec = (tv)->tv_usec * 1000; \ } #endif #ifndef TIMESPEC_TO_TIMEVAL #define TIMESPEC_TO_TIMEVAL(tv, ts) { \ (tv)->tv_sec = (ts)->tv_sec; \ (tv)->tv_usec = (ts)->tv_nsec / 1000; \ } #endif #ifndef __P # define __P(x) x #endif #if !defined(IN6_IS_ADDR_V4MAPPED) # define IN6_IS_ADDR_V4MAPPED(a) \ ((((u_int32_t *) (a))[0] == 0) && (((u_int32_t *) (a))[1] == 0) && \ (((u_int32_t *) (a))[2] == htonl (0xffff))) #endif /* !defined(IN6_IS_ADDR_V4MAPPED) */ #if !defined(__GNUC__) || (__GNUC__ < 2) # define __attribute__(x) #endif /* !defined(__GNUC__) || (__GNUC__ < 2) */ #if !defined(HAVE_ATTRIBUTE__SENTINEL__) && !defined(__sentinel__) # define __sentinel__ #endif #if !defined(HAVE_ATTRIBUTE__BOUNDED__) && !defined(__bounded__) # define __bounded__(x, y, z) #endif #if !defined(HAVE_ATTRIBUTE__NONNULL__) && !defined(__nonnull__) # define __nonnull__(x) #endif /* *-*-nto-qnx doesn't define this macro in the system headers */ #ifdef MISSING_HOWMANY # define howmany(x,y) (((x)+((y)-1))/(y)) #endif #ifndef OSSH_ALIGNBYTES #define OSSH_ALIGNBYTES (sizeof(int) - 1) #endif #ifndef __CMSG_ALIGN #define __CMSG_ALIGN(p) (((u_int)(p) + OSSH_ALIGNBYTES) &~ OSSH_ALIGNBYTES) #endif /* Length of the contents of a control message of length len */ #ifndef CMSG_LEN #define CMSG_LEN(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + (len)) #endif /* Length of the space taken up by a padded control message of length len */ #ifndef CMSG_SPACE #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len)) #endif /* given pointer to struct cmsghdr, return pointer to data */ #ifndef CMSG_DATA #define CMSG_DATA(cmsg) ((u_char *)(cmsg) + __CMSG_ALIGN(sizeof(struct cmsghdr))) #endif /* CMSG_DATA */ /* * RFC 2292 requires to check msg_controllen, in case that the kernel returns * an empty list for some reasons. */ #ifndef CMSG_FIRSTHDR #define CMSG_FIRSTHDR(mhdr) \ ((mhdr)->msg_controllen >= sizeof(struct cmsghdr) ? \ (struct cmsghdr *)(mhdr)->msg_control : \ (struct cmsghdr *)NULL) #endif /* CMSG_FIRSTHDR */ #if defined(HAVE_DECL_OFFSETOF) && HAVE_DECL_OFFSETOF == 0 # define offsetof(type, member) ((size_t) &((type *)0)->member) #endif /* Set up BSD-style BYTE_ORDER definition if it isn't there already */ /* XXX: doesn't try to cope with strange byte orders (PDP_ENDIAN) */ #ifndef BYTE_ORDER # ifndef LITTLE_ENDIAN # define LITTLE_ENDIAN 1234 # endif /* LITTLE_ENDIAN */ # ifndef BIG_ENDIAN # define BIG_ENDIAN 4321 # endif /* BIG_ENDIAN */ # ifdef WORDS_BIGENDIAN # define BYTE_ORDER BIG_ENDIAN # else /* WORDS_BIGENDIAN */ # define BYTE_ORDER LITTLE_ENDIAN # endif /* WORDS_BIGENDIAN */ #endif /* BYTE_ORDER */ /* Function replacement / compatibility hacks */ #if !defined(HAVE_GETADDRINFO) && (defined(HAVE_OGETADDRINFO) || defined(HAVE_NGETADDRINFO)) # define HAVE_GETADDRINFO #endif #ifndef HAVE_GETOPT_OPTRESET # undef getopt # undef opterr # undef optind # undef optopt # undef optreset # undef optarg # define getopt(ac, av, o) BSDgetopt(ac, av, o) # define opterr BSDopterr # define optind BSDoptind # define optopt BSDoptopt # define optreset BSDoptreset # define optarg BSDoptarg #endif #if defined(BROKEN_GETADDRINFO) && defined(HAVE_GETADDRINFO) # undef HAVE_GETADDRINFO #endif #if defined(BROKEN_GETADDRINFO) && defined(HAVE_FREEADDRINFO) # undef HAVE_FREEADDRINFO #endif #if defined(BROKEN_GETADDRINFO) && defined(HAVE_GAI_STRERROR) # undef HAVE_GAI_STRERROR #endif #if defined(BROKEN_UPDWTMPX) && defined(HAVE_UPDWTMPX) # undef HAVE_UPDWTMPX #endif #if defined(BROKEN_SHADOW_EXPIRE) && defined(HAS_SHADOW_EXPIRE) # undef HAS_SHADOW_EXPIRE #endif #if defined(HAVE_OPENLOG_R) && defined(SYSLOG_DATA_INIT) && \ defined(SYSLOG_R_SAFE_IN_SIGHAND) # define DO_LOG_SAFE_IN_SIGHAND #endif #if !defined(HAVE_MEMMOVE) && defined(HAVE_BCOPY) # define memmove(s1, s2, n) bcopy((s2), (s1), (n)) #endif /* !defined(HAVE_MEMMOVE) && defined(HAVE_BCOPY) */ #if defined(HAVE_VHANGUP) && !defined(HAVE_DEV_PTMX) # define USE_VHANGUP #endif /* defined(HAVE_VHANGUP) && !defined(HAVE_DEV_PTMX) */ #ifndef GETPGRP_VOID # include <unistd.h> # define getpgrp() getpgrp(0) #endif #ifdef USE_BSM_AUDIT # define SSH_AUDIT_EVENTS # define CUSTOM_SSH_AUDIT_EVENTS #endif #ifdef USE_LINUX_AUDIT # define SSH_AUDIT_EVENTS # define CUSTOM_SSH_AUDIT_EVENTS #endif #if !defined(HAVE___func__) && defined(HAVE___FUNCTION__) # define __func__ __FUNCTION__ #elif !defined(HAVE___func__) # define __func__ "" #endif #if defined(KRB5) && !defined(HEIMDAL) # define krb5_get_err_text(context,code) error_message(code) #endif #if defined(SKEYCHALLENGE_4ARG) # define _compat_skeychallenge(a,b,c,d) skeychallenge(a,b,c,d) #else # define _compat_skeychallenge(a,b,c,d) skeychallenge(a,b,c) #endif /* Maximum number of file descriptors available */ #ifdef HAVE_SYSCONF # define SSH_SYSFDMAX sysconf(_SC_OPEN_MAX) #else # define SSH_SYSFDMAX 10000 #endif #ifdef FSID_HAS_VAL /* encode f_fsid into a 64 bit value */ #define FSID_TO_ULONG(f) \ ((((u_int64_t)(f).val[0] & 0xffffffffUL) << 32) | \ ((f).val[1] & 0xffffffffUL)) #elif defined(FSID_HAS___VAL) #define FSID_TO_ULONG(f) \ ((((u_int64_t)(f).__val[0] & 0xffffffffUL) << 32) | \ ((f).__val[1] & 0xffffffffUL)) #else # define FSID_TO_ULONG(f) ((f)) #endif #if defined(__Lynx__) /* * LynxOS defines these in param.h which we do not want to include since * it will also pull in a bunch of kernel definitions. */ # define ALIGNBYTES (sizeof(int) - 1) # define ALIGN(p) (((unsigned)p + ALIGNBYTES) & ~ALIGNBYTES) /* Missing prototypes on LynxOS */ int snprintf (char *, size_t, const char *, ...); int mkstemp (char *); char *crypt (const char *, const char *); int seteuid (uid_t); int setegid (gid_t); char *mkdtemp (char *); int rresvport_af (int *, sa_family_t); int innetgr (const char *, const char *, const char *, const char *); #endif /* * Define this to use pipes instead of socketpairs for communicating with the * client program. Socketpairs do not seem to work on all systems. * * configure.ac sets this for a few OS's which are known to have problems * but you may need to set it yourself */ /* #define USE_PIPES 1 */ /** ** login recorder definitions **/ /* FIXME: put default paths back in */ #ifndef UTMP_FILE # ifdef _PATH_UTMP # define UTMP_FILE _PATH_UTMP # else # ifdef CONF_UTMP_FILE # define UTMP_FILE CONF_UTMP_FILE # endif # endif #endif #ifndef WTMP_FILE # ifdef _PATH_WTMP # define WTMP_FILE _PATH_WTMP # else # ifdef CONF_WTMP_FILE # define WTMP_FILE CONF_WTMP_FILE # endif # endif #endif /* pick up the user's location for lastlog if given */ #ifndef LASTLOG_FILE # ifdef _PATH_LASTLOG # define LASTLOG_FILE _PATH_LASTLOG # else # ifdef CONF_LASTLOG_FILE # define LASTLOG_FILE CONF_LASTLOG_FILE # endif # endif #endif #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW) # define USE_SHADOW #endif /* The login() library function in libutil is first choice */ #if defined(HAVE_LOGIN) && !defined(DISABLE_LOGIN) # define USE_LOGIN #else /* Simply select your favourite login types. */ /* Can't do if-else because some systems use several... <sigh> */ # if !defined(DISABLE_UTMPX) # define USE_UTMPX # endif # if defined(UTMP_FILE) && !defined(DISABLE_UTMP) # define USE_UTMP # endif # if defined(WTMPX_FILE) && !defined(DISABLE_WTMPX) # define USE_WTMPX # endif # if defined(WTMP_FILE) && !defined(DISABLE_WTMP) # define USE_WTMP # endif #endif #ifndef UT_LINESIZE # define UT_LINESIZE 8 #endif /* I hope that the presence of LASTLOG_FILE is enough to detect this */ #if defined(LASTLOG_FILE) && !defined(DISABLE_LASTLOG) # define USE_LASTLOG #endif #ifdef HAVE_OSF_SIA # ifdef USE_SHADOW # undef USE_SHADOW # endif # define CUSTOM_SYS_AUTH_PASSWD 1 #endif #if defined(HAVE_LIBIAF) && defined(HAVE_SET_ID) && !defined(HAVE_SECUREWARE) # define CUSTOM_SYS_AUTH_PASSWD 1 #endif #if defined(HAVE_LIBIAF) && defined(HAVE_SET_ID) && !defined(BROKEN_LIBIAF) # define USE_LIBIAF #endif /* HP-UX 11.11 */ #ifdef BTMP_FILE # define _PATH_BTMP BTMP_FILE #endif #if defined(USE_BTMP) && defined(_PATH_BTMP) # define CUSTOM_FAILED_LOGIN #endif /** end of login recorder definitions */ #ifdef BROKEN_GETGROUPS # define getgroups(a,b) ((a)==0 && (b)==NULL ? NGROUPS_MAX : getgroups((a),(b))) #endif #if defined(HAVE_MMAP) && defined(BROKEN_MMAP) # undef HAVE_MMAP #endif #ifndef IOV_MAX # if defined(_XOPEN_IOV_MAX) # define IOV_MAX _XOPEN_IOV_MAX # elif defined(DEF_IOV_MAX) # define IOV_MAX DEF_IOV_MAX # else # define IOV_MAX 16 # endif #endif #ifndef EWOULDBLOCK # define EWOULDBLOCK EAGAIN #endif #ifndef INET6_ADDRSTRLEN /* for non IPv6 machines */ #define INET6_ADDRSTRLEN 46 #endif #ifndef SSH_IOBUFSZ # define SSH_IOBUFSZ 8192 #endif #ifndef _NSIG # ifdef NSIG # define _NSIG NSIG # else # define _NSIG 128 # endif #endif #endif /* _DEFINES_H */
Java
<?php /** * Created by PhpStorm. * User: faustos * Date: 05.06.14 * Time: 13:58 */ namespace Tixi\App\AppBundle\Interfaces; class DrivingOrderHandleDTO { public $id; public $anchorDate; public $lookaheadaddressFrom; public $lookaheadaddressTo; public $zoneStatus; public $zoneId; public $zoneName; public $orderTime; public $isRepeated; public $compagnion; public $memo; //repeated part public $endDate; public $mondayOrderTime; public $tuesdayOrderTime; public $wednesdayOrderTime; public $thursdayOrderTime; public $fridayOrderTime; public $saturdayOrderTime; public $sundayOrderTime; }
Java
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2013, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif /*********************************************************************** * Only for ares-enabled builds * And only for functions that fulfill the asynch resolver backend API * as defined in asyn.h, nothing else belongs in this file! **********************************************************************/ #ifdef CURLRES_ARES #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "strerror.h" #include "url.h" #include "multiif.h" #include "inet_pton.h" #include "connect.h" #include "select.h" #include "progress.h" #define _MPRINTF_REPLACE /* use our functions only */ #include <curl/mprintf.h> # if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \ (defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)) # define CARES_STATICLIB # endif # include <ares.h> # include <ares_version.h> /* really old c-ares didn't include this by itself */ #if ARES_VERSION >= 0x010500 /* c-ares 1.5.0 or later, the callback proto is modified */ #define HAVE_CARES_CALLBACK_TIMEOUTS 1 #endif #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" struct ResolverResults { int num_pending; /* number of ares_gethostbyname() requests */ Curl_addrinfo *temp_ai; /* intermediary result while fetching c-ares parts */ int last_status; }; /* * Curl_resolver_global_init() - the generic low-level asynchronous name * resolve API. Called from curl_global_init() to initialize global resolver * environment. Initializes ares library. */ int Curl_resolver_global_init(void) { #ifdef CARES_HAVE_ARES_LIBRARY_INIT if(ares_library_init(ARES_LIB_INIT_ALL)) { return CURLE_FAILED_INIT; } #endif return CURLE_OK; } /* * Curl_resolver_global_cleanup() * * Called from curl_global_cleanup() to destroy global resolver environment. * Deinitializes ares library. */ void Curl_resolver_global_cleanup(void) { #ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP ares_library_cleanup(); #endif } /* * Curl_resolver_init() * * Called from curl_easy_init() -> Curl_open() to initialize resolver * URL-state specific environment ('resolver' member of the UrlState * structure). Fills the passed pointer by the initialized ares_channel. */ CURLcode Curl_resolver_init(void **resolver) { int status = ares_init((ares_channel*)resolver); if(status != ARES_SUCCESS) { if(status == ARES_ENOMEM) return CURLE_OUT_OF_MEMORY; else return CURLE_FAILED_INIT; } return CURLE_OK; /* make sure that all other returns from this function should destroy the ares channel before returning error! */ } /* * Curl_resolver_cleanup() * * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver * URL-state specific environment ('resolver' member of the UrlState * structure). Destroys the ares channel. */ void Curl_resolver_cleanup(void *resolver) { ares_destroy((ares_channel)resolver); } /* * Curl_resolver_duphandle() * * Called from curl_easy_duphandle() to duplicate resolver URL-state specific * environment ('resolver' member of the UrlState structure). Duplicates the * 'from' ares channel and passes the resulting channel to the 'to' pointer. */ int Curl_resolver_duphandle(void **to, void *from) { /* Clone the ares channel for the new handle */ if(ARES_SUCCESS != ares_dup((ares_channel*)to,(ares_channel)from)) return CURLE_FAILED_INIT; return CURLE_OK; } static void destroy_async_data (struct Curl_async *async); /* * Cancel all possibly still on-going resolves for this connection. */ void Curl_resolver_cancel(struct connectdata *conn) { if(conn && conn->data && conn->data->state.resolver) ares_cancel((ares_channel)conn->data->state.resolver); destroy_async_data(&conn->async); } /* * destroy_async_data() cleans up async resolver data. */ static void destroy_async_data (struct Curl_async *async) { if(async->hostname) free(async->hostname); if(async->os_specific) { struct ResolverResults *res = (struct ResolverResults *)async->os_specific; if(res) { if(res->temp_ai) { Curl_freeaddrinfo(res->temp_ai); res->temp_ai = NULL; } free(res); } async->os_specific = NULL; } async->hostname = NULL; } /* * Curl_resolver_getsock() is called when someone from the outside world * (using curl_multi_fdset()) wants to get our fd_set setup and we're talking * with ares. The caller must make sure that this function is only called when * we have a working ares channel. * * Returns: sockets-in-use-bitmap */ int Curl_resolver_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { struct timeval maxtime; struct timeval timebuf; struct timeval *timeout; long milli; int max = ares_getsock((ares_channel)conn->data->state.resolver, (ares_socket_t *)socks, numsocks); maxtime.tv_sec = CURL_TIMEOUT_RESOLVE; maxtime.tv_usec = 0; timeout = ares_timeout((ares_channel)conn->data->state.resolver, &maxtime, &timebuf); milli = (timeout->tv_sec * 1000) + (timeout->tv_usec/1000); if(milli == 0) milli += 10; Curl_expire(conn->data, milli); return max; } /* * waitperform() * * 1) Ask ares what sockets it currently plays with, then * 2) wait for the timeout period to check for action on ares' sockets. * 3) tell ares to act on all the sockets marked as "with action" * * return number of sockets it worked on */ static int waitperform(struct connectdata *conn, int timeout_ms) { struct SessionHandle *data = conn->data; int nfds; int bitmask; ares_socket_t socks[ARES_GETSOCK_MAXNUM]; struct pollfd pfd[ARES_GETSOCK_MAXNUM]; int i; int num = 0; bitmask = ares_getsock((ares_channel)data->state.resolver, socks, ARES_GETSOCK_MAXNUM); for(i=0; i < ARES_GETSOCK_MAXNUM; i++) { pfd[i].events = 0; pfd[i].revents = 0; if(ARES_GETSOCK_READABLE(bitmask, i)) { pfd[i].fd = socks[i]; pfd[i].events |= POLLRDNORM|POLLIN; } if(ARES_GETSOCK_WRITABLE(bitmask, i)) { pfd[i].fd = socks[i]; pfd[i].events |= POLLWRNORM|POLLOUT; } if(pfd[i].events != 0) num++; else break; } if(num) nfds = Curl_poll(pfd, num, timeout_ms); else nfds = 0; if(!nfds) /* Call ares_process() unconditonally here, even if we simply timed out above, as otherwise the ares name resolve won't timeout! */ ares_process_fd((ares_channel)data->state.resolver, ARES_SOCKET_BAD, ARES_SOCKET_BAD); else { /* move through the descriptors and ask for processing on them */ for(i=0; i < num; i++) ares_process_fd((ares_channel)data->state.resolver, pfd[i].revents & (POLLRDNORM|POLLIN)? pfd[i].fd:ARES_SOCKET_BAD, pfd[i].revents & (POLLWRNORM|POLLOUT)? pfd[i].fd:ARES_SOCKET_BAD); } return nfds; } /* * Curl_resolver_is_resolved() is called repeatedly to check if a previous * name resolve request has completed. It should also make sure to time-out if * the operation seems to take too long. * * Returns normal CURLcode errors. */ CURLcode Curl_resolver_is_resolved(struct connectdata *conn, struct Curl_dns_entry **dns) { struct SessionHandle *data = conn->data; struct ResolverResults *res = (struct ResolverResults *) conn->async.os_specific; CURLcode rc = CURLE_OK; *dns = NULL; waitperform(conn, 0); if(res && !res->num_pending) { (void)Curl_addrinfo_callback(conn, res->last_status, res->temp_ai); /* temp_ai ownership is moved to the connection, so we need not free-up them */ res->temp_ai = NULL; if(!conn->async.dns) { failf(data, "Could not resolve: %s (%s)", conn->async.hostname, ares_strerror(conn->async.status)); rc = conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY: CURLE_COULDNT_RESOLVE_HOST; } else *dns = conn->async.dns; destroy_async_data(&conn->async); } return rc; } /* * Curl_resolver_wait_resolv() * * waits for a resolve to finish. This function should be avoided since using * this risk getting the multi interface to "hang". * * If 'entry' is non-NULL, make it point to the resolved dns entry * * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, and * CURLE_OPERATION_TIMEDOUT if a time-out occurred. */ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode rc=CURLE_OK; struct SessionHandle *data = conn->data; long timeout; struct timeval now = Curl_tvnow(); struct Curl_dns_entry *temp_entry; timeout = Curl_timeleft(data, &now, TRUE); if(!timeout) timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */ /* Wait for the name resolve query to complete. */ for(;;) { struct timeval *tvp, tv, store; long timediff; int itimeout; int timeout_ms; itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; store.tv_sec = itimeout/1000; store.tv_usec = (itimeout%1000)*1000; tvp = ares_timeout((ares_channel)data->state.resolver, &store, &tv); /* use the timeout period ares returned to us above if less than one second is left, otherwise just use 1000ms to make sure the progress callback gets called frequent enough */ if(!tvp->tv_sec) timeout_ms = (int)(tvp->tv_usec/1000); else timeout_ms = 1000; waitperform(conn, timeout_ms); Curl_resolver_is_resolved(conn,&temp_entry); if(conn->async.done) break; if(Curl_pgrsUpdate(conn)) { rc = CURLE_ABORTED_BY_CALLBACK; timeout = -1; /* trigger the cancel below */ } else { struct timeval now2 = Curl_tvnow(); timediff = Curl_tvdiff(now2, now); /* spent time */ timeout -= timediff?timediff:1; /* always deduct at least 1 */ now = now2; /* for next loop */ } if(timeout < 0) { /* our timeout, so we cancel the ares operation */ ares_cancel((ares_channel)data->state.resolver); break; } } /* Operation complete, if the lookup was successful we now have the entry in the cache. */ if(entry) *entry = conn->async.dns; if(rc) /* close the connection, since we can't return failure here without cleaning up this connection properly. TODO: remove this action from here, it is not a name resolver decision. */ conn->bits.close = TRUE; return rc; } /* Connects results to the list */ static void compound_results(struct ResolverResults *res, Curl_addrinfo *ai) { Curl_addrinfo *ai_tail; if(!ai) return; ai_tail = ai; while(ai_tail->ai_next) ai_tail = ai_tail->ai_next; /* Add the new results to the list of old results. */ ai_tail->ai_next = res->temp_ai; res->temp_ai = ai; } /* * ares_query_completed_cb() is the callback that ares will call when * the host query initiated by ares_gethostbyname() from Curl_getaddrinfo(), * when using ares, is completed either successfully or with failure. */ static void query_completed_cb(void *arg, /* (struct connectdata *) */ int status, #ifdef HAVE_CARES_CALLBACK_TIMEOUTS int timeouts, #endif struct hostent *hostent) { struct connectdata *conn = (struct connectdata *)arg; struct ResolverResults *res; #ifdef HAVE_CARES_CALLBACK_TIMEOUTS (void)timeouts; /* ignored */ #endif if(ARES_EDESTRUCTION == status) /* when this ares handle is getting destroyed, the 'arg' pointer may not be valid so only defer it when we know the 'status' says its fine! */ return; res = (struct ResolverResults *)conn->async.os_specific; res->num_pending--; if(CURL_ASYNC_SUCCESS == status) { Curl_addrinfo *ai = Curl_he2ai(hostent, conn->async.port); if(ai) { compound_results(res, ai); } } /* A successful result overwrites any previous error */ if(res->last_status != ARES_SUCCESS) res->last_status = status; } /* * Curl_resolver_getaddrinfo() - when using ares * * Returns name information about the given hostname and port number. If * successful, the 'hostent' is returned and the forth argument will point to * memory we need to free after use. That memory *MUST* be freed with * Curl_freeaddrinfo(), nothing else. */ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn, const char *hostname, int port, int *waitp) { char *bufp; struct SessionHandle *data = conn->data; struct in_addr in; int family = PF_INET; #ifdef ENABLE_IPV6 /* CURLRES_IPV6 */ struct in6_addr in6; #endif /* CURLRES_IPV6 */ *waitp = 0; /* default to synchronous response */ /* First check if this is an IPv4 address string */ if(Curl_inet_pton(AF_INET, hostname, &in) > 0) { /* This is a dotted IP address 123.123.123.123-style */ return Curl_ip2addr(AF_INET, &in, hostname, port); } #ifdef ENABLE_IPV6 /* CURLRES_IPV6 */ /* Otherwise, check if this is an IPv6 address string */ if(Curl_inet_pton (AF_INET6, hostname, &in6) > 0) /* This must be an IPv6 address literal. */ return Curl_ip2addr(AF_INET6, &in6, hostname, port); switch(conn->ip_version) { default: #if ARES_VERSION >= 0x010601 family = PF_UNSPEC; /* supported by c-ares since 1.6.1, so for older c-ares versions this just falls through and defaults to PF_INET */ break; #endif case CURL_IPRESOLVE_V4: family = PF_INET; break; case CURL_IPRESOLVE_V6: family = PF_INET6; break; } #endif /* CURLRES_IPV6 */ bufp = strdup(hostname); if(bufp) { struct ResolverResults *res = NULL; Curl_safefree(conn->async.hostname); conn->async.hostname = bufp; conn->async.port = port; conn->async.done = FALSE; /* not done */ conn->async.status = 0; /* clear */ conn->async.dns = NULL; /* clear */ res = calloc(sizeof(struct ResolverResults),1); if(!res) { Curl_safefree(conn->async.hostname); conn->async.hostname = NULL; return NULL; } conn->async.os_specific = res; /* initial status - failed */ res->last_status = ARES_ENOTFOUND; #ifdef ENABLE_IPV6 /* CURLRES_IPV6 */ if(family == PF_UNSPEC) { if(Curl_ipv6works()) { res->num_pending = 2; /* areschannel is already setup in the Curl_open() function */ ares_gethostbyname((ares_channel)data->state.resolver, hostname, PF_INET, query_completed_cb, conn); ares_gethostbyname((ares_channel)data->state.resolver, hostname, PF_INET6, query_completed_cb, conn); } else { res->num_pending = 1; /* areschannel is already setup in the Curl_open() function */ ares_gethostbyname((ares_channel)data->state.resolver, hostname, PF_INET, query_completed_cb, conn); } } else #endif /* CURLRES_IPV6 */ { res->num_pending = 1; /* areschannel is already setup in the Curl_open() function */ ares_gethostbyname((ares_channel)data->state.resolver, hostname, family, query_completed_cb, conn); } *waitp = 1; /* expect asynchronous response */ } return NULL; /* no struct yet */ } CURLcode Curl_set_dns_servers(struct SessionHandle *data, char *servers) { CURLcode result = CURLE_NOT_BUILT_IN; int ares_result; /* If server is NULL or empty, this would purge all DNS servers * from ares library, which will cause any and all queries to fail. * So, just return OK if none are configured and don't actually make * any changes to c-ares. This lets c-ares use it's defaults, which * it gets from the OS (for instance from /etc/resolv.conf on Linux). */ if(!(servers && servers[0])) return CURLE_OK; #if (ARES_VERSION >= 0x010704) ares_result = ares_set_servers_csv(data->state.resolver, servers); switch(ares_result) { case ARES_SUCCESS: result = CURLE_OK; break; case ARES_ENOMEM: result = CURLE_OUT_OF_MEMORY; break; case ARES_ENOTINITIALIZED: case ARES_ENODATA: case ARES_EBADSTR: default: result = CURLE_BAD_FUNCTION_ARGUMENT; break; } #else /* too old c-ares version! */ (void)data; (void)(ares_result); #endif return result; } CURLcode Curl_set_dns_interface(struct SessionHandle *data, const char *interf) { #if (ARES_VERSION >= 0x010704) if(!interf) interf = ""; ares_set_local_dev((ares_channel)data->state.resolver, interf); return CURLE_OK; #else /* c-ares version too old! */ (void)data; (void)interf; return CURLE_NOT_BUILT_IN; #endif } CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, const char *local_ip4) { #if (ARES_VERSION >= 0x010704) uint32_t a4; if((!local_ip4) || (local_ip4[0] == 0)) { a4 = 0; /* disabled: do not bind to a specific address */ } else { if(Curl_inet_pton(AF_INET, local_ip4, &a4) != 1) { return CURLE_BAD_FUNCTION_ARGUMENT; } } ares_set_local_ip4((ares_channel)data->state.resolver, ntohl(a4)); return CURLE_OK; #else /* c-ares version too old! */ (void)data; (void)local_ip4; return CURLE_NOT_BUILT_IN; #endif } CURLcode Curl_set_dns_local_ip6(struct SessionHandle *data, const char *local_ip6) { #if (ARES_VERSION >= 0x010704) unsigned char a6[INET6_ADDRSTRLEN]; if((!local_ip6) || (local_ip6[0] == 0)) { /* disabled: do not bind to a specific address */ memset(a6, 0, sizeof(a6)); } else { if(Curl_inet_pton(AF_INET6, local_ip6, a6) != 1) { return CURLE_BAD_FUNCTION_ARGUMENT; } } ares_set_local_ip6((ares_channel)data->state.resolver, a6); return CURLE_OK; #else /* c-ares version too old! */ (void)data; (void)local_ip6; return CURLE_NOT_BUILT_IN; #endif } #endif /* CURLRES_ARES */
Java
package org.jsondoc.core.issues.issue151; import org.jsondoc.core.annotation.Api; import org.jsondoc.core.annotation.ApiMethod; import org.jsondoc.core.annotation.ApiResponseObject; @Api(name = "Foo Services", description = "bla, bla, bla ...", group = "foogroup") public class FooController { @ApiMethod(path = { "/api/foo" }, description = "Main foo service") @ApiResponseObject public FooWrapper<BarPojo> getBar() { return null; } @ApiMethod(path = { "/api/foo-wildcard" }, description = "Main foo service with wildcard") @ApiResponseObject public FooWrapper<?> wildcard() { return null; } }
Java
 namespace Porter2Stemmer { public interface IStemmer { /// <summary> /// Stem a word. /// </summary> /// <param name="word">Word to stem.</param> /// <returns> /// The stemmed word, with a reference to the original unstemmed word. /// </returns> StemmedWord Stem(string word); } }
Java
function someFunctionWithAVeryLongName(firstParameter='something', secondParameter='booooo', third=null, fourthParameter=false, fifthParameter=123.12, sixthParam=true ){ } function someFunctionWithAVeryLongName2( firstParameter='something', secondParameter='booooo', ) { } function blah() { } function blah() { } var object = { someFunctionWithAVeryLongName: function( firstParameter='something', secondParameter='booooo', third=null, fourthParameter=false, fifthParameter=123.12, sixthParam=true ) /** w00t */ { } someFunctionWithAVeryLongName2: function (firstParameter='something', secondParameter='booooo', third=null ) { } someFunctionWithAVeryLongName3: function ( firstParameter, secondParameter, third=null ) { } someFunctionWithAVeryLongName4: function ( firstParameter, secondParameter ) { } someFunctionWithAVeryLongName5: function ( firstParameter, secondParameter=array(1,2,3), third=null ) { } } var a = Function('return 1+1');
Java