repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
AICP/external_chromium_org
chrome/browser/supervised_user/supervised_user_resource_throttle.cc
2651
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/supervised_user/supervised_user_resource_throttle.h" #include "base/bind.h" #include "chrome/browser/supervised_user/supervised_user_interstitial.h" #include "chrome/browser/supervised_user/supervised_user_navigation_observer.h" #include "chrome/browser/supervised_user/supervised_user_url_filter.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_controller.h" #include "content/public/browser/resource_request_info.h" #include "net/url_request/url_request.h" using content::BrowserThread; SupervisedUserResourceThrottle::SupervisedUserResourceThrottle( const net::URLRequest* request, bool is_main_frame, const SupervisedUserURLFilter* url_filter) : request_(request), is_main_frame_(is_main_frame), url_filter_(url_filter), weak_ptr_factory_(this) {} SupervisedUserResourceThrottle::~SupervisedUserResourceThrottle() {} void SupervisedUserResourceThrottle::ShowInterstitialIfNeeded(bool is_redirect, const GURL& url, bool* defer) { // Only treat main frame requests for now (ignoring subresources). if (!is_main_frame_) return; if (url_filter_->GetFilteringBehaviorForURL(url) != SupervisedUserURLFilter::BLOCK) { return; } *defer = true; const content::ResourceRequestInfo* info = content::ResourceRequestInfo::ForRequest(request_); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&SupervisedUserNavigationObserver::OnRequestBlocked, info->GetChildID(), info->GetRouteID(), url, base::Bind( &SupervisedUserResourceThrottle::OnInterstitialResult, weak_ptr_factory_.GetWeakPtr()))); } void SupervisedUserResourceThrottle::WillStartRequest(bool* defer) { ShowInterstitialIfNeeded(false, request_->url(), defer); } void SupervisedUserResourceThrottle::WillRedirectRequest(const GURL& new_url, bool* defer) { ShowInterstitialIfNeeded(true, new_url, defer); } const char* SupervisedUserResourceThrottle::GetNameForLogging() const { return "SupervisedUserResourceThrottle"; } void SupervisedUserResourceThrottle::OnInterstitialResult( bool continue_request) { if (continue_request) controller()->Resume(); else controller()->Cancel(); }
bsd-3-clause
ptoonen/corefx
src/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs
5576
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection.Context.Custom; using System.Reflection.Context.Projection; using System.Reflection.Context.Virtual; namespace System.Reflection.Context { internal class IdentityReflectionContext : ReflectionContext { public override Assembly MapAssembly(Assembly assembly) { return assembly; } public override TypeInfo MapType(TypeInfo type) { return type; } } public abstract partial class CustomReflectionContext : ReflectionContext { private readonly ReflectionContextProjector _projector; protected CustomReflectionContext() : this(new IdentityReflectionContext()) { } protected CustomReflectionContext(ReflectionContext source) { SourceContext = source ?? throw new ArgumentNullException(nameof(source)); _projector = new ReflectionContextProjector(this); } public override Assembly MapAssembly(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } return _projector.ProjectAssemblyIfNeeded(assembly); } public override TypeInfo MapType(TypeInfo type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return _projector.ProjectTypeIfNeeded(type); } protected virtual IEnumerable<object> GetCustomAttributes(MemberInfo member, IEnumerable<object> declaredAttributes) { return declaredAttributes; } protected virtual IEnumerable<object> GetCustomAttributes(ParameterInfo parameter, IEnumerable<object> declaredAttributes) { return declaredAttributes; } // The default implementation of GetProperties: just return an empty list. protected virtual IEnumerable<PropertyInfo> AddProperties(Type type) { // return an empty enumeration yield break; } protected PropertyInfo CreateProperty( Type propertyType, string name, Func<object, object> getter, Action<object, object> setter) { return new VirtualPropertyInfo( name, propertyType, getter, setter, null, null, null, this); } protected PropertyInfo CreateProperty( Type propertyType, string name, Func<object, object> getter, Action<object, object> setter, IEnumerable<Attribute> propertyCustomAttributes, IEnumerable<Attribute> getterCustomAttributes, IEnumerable<Attribute> setterCustomAttributes) { return new VirtualPropertyInfo( name, propertyType, getter, setter, propertyCustomAttributes, getterCustomAttributes, setterCustomAttributes, this); } internal IEnumerable<PropertyInfo> GetNewPropertiesForType(CustomType type) { // We don't support adding properties on these types. if (type.IsInterface || type.IsGenericParameter || type.HasElementType) yield break; // Passing in the underlying type. IEnumerable<PropertyInfo> newProperties = AddProperties(type.UnderlyingType); // Setting DeclaringType on the user provided virtual properties. foreach (PropertyInfo prop in newProperties) { if (prop == null) throw new InvalidOperationException(SR.InvalidOperation_AddNullProperty); VirtualPropertyBase vp = prop as VirtualPropertyBase; if (vp == null || vp.ReflectionContext != this) throw new InvalidOperationException(SR.InvalidOperation_AddPropertyDifferentContext); if (vp.DeclaringType == null) vp.SetDeclaringType(type); else if (!vp.DeclaringType.Equals(type)) throw new InvalidOperationException(SR.InvalidOperation_AddPropertyDifferentType); yield return prop; } } internal IEnumerable<object> GetCustomAttributesOnMember(MemberInfo member, IEnumerable<object> declaredAttributes, Type attributeFilterType) { IEnumerable<object> attributes = GetCustomAttributes(member, declaredAttributes); return AttributeUtils.FilterCustomAttributes(attributes, attributeFilterType); } internal IEnumerable<object> GetCustomAttributesOnParameter(ParameterInfo parameter, IEnumerable<object> declaredAttributes, Type attributeFilterType) { IEnumerable<object> attributes = GetCustomAttributes(parameter, declaredAttributes); return AttributeUtils.FilterCustomAttributes(attributes, attributeFilterType); } internal Projector Projector { get { return _projector; } } internal ReflectionContext SourceContext { get; } } }
mit
fredrikeldh/gcc4-mapip2
libstdc++-v3/testsuite/27_io/basic_istream/extractors_other/pod/3983-3.cc
1859
// 2001-06-05 Benjamin Kosnik <[email protected]> // Copyright (C) 2001, 2002, 2003, 2005, 2009 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 27.4.2.1.6 class ios_base::init #include <sstream> #include <typeinfo> #include <testsuite_hooks.h> #include <testsuite_character.h> // libstdc++/3983 // Sentry uses locale info, so have to try one formatted input/output. void test03() { using namespace std; using __gnu_test::pod_ushort; typedef basic_stringbuf<pod_ushort> stringbuf_type; typedef basic_istream<pod_ushort> istream_type; stringbuf_type strbuf01; istream_type iss(&strbuf01); bool test __attribute__((unused)) = true; try { iss >> std::ws; } catch (std::bad_cast& obj) { } catch (std::exception& obj) { VERIFY( false ); } } #if !__GXX_WEAK__ // Explicitly instantiate for systems with no COMDAT or weak support. template const std::basic_string<__gnu_test::pod_ushort>::size_type std::basic_string<__gnu_test::pod_ushort>::_Rep::_S_max_size; template const __gnu_test::pod_ushort std::basic_string<__gnu_test::pod_ushort>::_Rep::_S_terminal; #endif int main() { test03(); return 0; }
gpl-2.0
buuck/root
tutorials/cocoa/parallelcoordtrans.C
5448
/// \file /// \ingroup tutorial_cocoa /// Script illustrating the use of transparency with ||-Coord. /// It displays the same data set twice. The first time without transparency and /// the second time with transparency. On the second plot, several clusters /// appear. /// /// \macro_code /// /// \authors Timur Pocheptsov, Olivier Couet //All these includes are (only) to make the macro //ACLiCable. #include <cassert> #include "TParallelCoordVar.h" #include "TParallelCoord.h" #include "TVirtualX.h" #include "TNtuple.h" #include "TCanvas.h" #include "TRandom.h" #include "TColor.h" #include "Rtypes.h" #include "TError.h" #include "TList.h" #include "TROOT.h" namespace ROOT { namespace CocoaTutorials { Double_t r1, r2, r3, r4, r5, r6, r7, r8, r9; TRandom r; //______________________________________________________________________ void generate_random(Int_t i) { const Double_t dr = 3.5; r.Rannor(r1, r4); r.Rannor(r7, r9); r2 = (2 * dr * r.Rndm(i)) - dr; r3 = (2 * dr * r.Rndm(i)) - dr; r5 = (2 * dr * r.Rndm(i)) - dr; r6 = (2 * dr * r.Rndm(i)) - dr; r8 = (2 * dr * r.Rndm(i)) - dr; } }//CocoaTutorials }//ROOT void parallelcoordtrans() { //This macro shows how to use parallel coords and semi-transparent lines //(the system color is updated with alpha == 0.01 (1% opaque). //It does not demonstrate the right memory management/error handling. //Requires OS X and ROOT configured with --enable-cocoa. using namespace ROOT::CocoaTutorials; Double_t s1x = 0., s1y = 0., s1z = 0.; Double_t s2x = 0., s2y = 0., s2z = 0.; Double_t s3x = 0., s3y = 0., s3z = 0.; TCanvas *c1 = new TCanvas("parallel coords", "parallel coords", 0, 0, 900, 1000); if (gVirtualX && !gVirtualX->InheritsFrom("TGCocoa")) { ::Error("generate_random", "This macro works only on OS X with --enable-cocoa"); delete c1; return; } TNtuple * const nt = new TNtuple("nt", "Demo ntuple", "x:y:z:u:v:w:a:b:c"); for (Int_t i = 0; i < 1500; ++i) { r.Sphere(s1x, s1y, s1z, 0.1); r.Sphere(s2x, s2y, s2z, 0.2); r.Sphere(s3x, s3y, s3z, 0.05); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, r8, r9); generate_random(i); nt->Fill(s1x, s1y, s1z, s2x, s2y, s2z, r7, r8, r9); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, s3y, r9); generate_random(i); nt->Fill(s2x - 1, s2y - 1, s2z, s1x + .5, s1y + .5, s1z + .5, r7, r8, r9); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, r8, r9); generate_random(i); nt->Fill(s1x + 1, s1y + 1, s1z + 1, s3x - 2, s3y - 2, s3z - 2, r7, r8, r9); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, s3x, r8, s3z); } c1->Divide(1, 2); c1->cd(1); // ||-Coord plot without transparency nt->Draw("x:y:z:u:v:w:a:b:c", "", "para"); TParallelCoord * const para1 = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord"); assert(para1 != 0 && "parallelcoordtrans, 'ParaCoord' is null"); para1->SetLineColor(25); TParallelCoordVar *pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("x"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("y"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("z"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("a"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("b"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("c"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("u"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("v"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("w"); pcv->SetHistogramHeight(0.); // ||-Coord plot with transparency // We modify a 'system' color! You'll probably // have to restart ROOT or reset this color later. TColor * const col26 = gROOT->GetColor(26); assert(col26 != 0 && "parallelcoordtrans, color with index 26 not found"); col26->SetAlpha(0.01); c1->cd(2); nt->Draw("x:y:z:u:v:w:a:b:c","","para"); TParallelCoord * const para2 = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord"); assert(para2 != 0 && "parallelcoordtrans, 'ParaCoord' is null"); para2->SetLineColor(26); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("x"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("y"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("z"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("a"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("b"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("c"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("u"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("v"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("w"); pcv->SetHistogramHeight(0.); }
lgpl-2.1
IDKA/coreos-kubernetes
multi-node/aws/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/ec2/metadata_test.go
5910
// Copyright 2015 CoreOS, Inc. // // 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. package ec2 import ( "fmt" "net" "reflect" "testing" "github.com/coreos/coreos-cloudinit/datasource" "github.com/coreos/coreos-cloudinit/datasource/metadata" "github.com/coreos/coreos-cloudinit/datasource/metadata/test" "github.com/coreos/coreos-cloudinit/pkg" ) func TestType(t *testing.T) { want := "ec2-metadata-service" if kind := (metadataService{}).Type(); kind != want { t.Fatalf("bad type: want %q, got %q", want, kind) } } func TestFetchAttributes(t *testing.T) { for _, s := range []struct { resources map[string]string err error tests []struct { path string val []string } }{ { resources: map[string]string{ "/": "a\nb\nc/", "/c/": "d\ne/", "/c/e/": "f", "/a": "1", "/b": "2", "/c/d": "3", "/c/e/f": "4", }, tests: []struct { path string val []string }{ {"/", []string{"a", "b", "c/"}}, {"/b", []string{"2"}}, {"/c/d", []string{"3"}}, {"/c/e/", []string{"f"}}, }, }, { err: fmt.Errorf("test error"), tests: []struct { path string val []string }{ {"", nil}, }, }, } { service := metadataService{metadata.MetadataService{ Client: &test.HttpClient{Resources: s.resources, Err: s.err}, }} for _, tt := range s.tests { attrs, err := service.fetchAttributes(tt.path) if err != s.err { t.Fatalf("bad error for %q (%q): want %q, got %q", tt.path, s.resources, s.err, err) } if !reflect.DeepEqual(attrs, tt.val) { t.Fatalf("bad fetch for %q (%q): want %q, got %q", tt.path, s.resources, tt.val, attrs) } } } } func TestFetchAttribute(t *testing.T) { for _, s := range []struct { resources map[string]string err error tests []struct { path string val string } }{ { resources: map[string]string{ "/": "a\nb\nc/", "/c/": "d\ne/", "/c/e/": "f", "/a": "1", "/b": "2", "/c/d": "3", "/c/e/f": "4", }, tests: []struct { path string val string }{ {"/a", "1"}, {"/b", "2"}, {"/c/d", "3"}, {"/c/e/f", "4"}, }, }, { err: fmt.Errorf("test error"), tests: []struct { path string val string }{ {"", ""}, }, }, } { service := metadataService{metadata.MetadataService{ Client: &test.HttpClient{Resources: s.resources, Err: s.err}, }} for _, tt := range s.tests { attr, err := service.fetchAttribute(tt.path) if err != s.err { t.Fatalf("bad error for %q (%q): want %q, got %q", tt.path, s.resources, s.err, err) } if attr != tt.val { t.Fatalf("bad fetch for %q (%q): want %q, got %q", tt.path, s.resources, tt.val, attr) } } } } func TestFetchMetadata(t *testing.T) { for _, tt := range []struct { root string metadataPath string resources map[string]string expect datasource.Metadata clientErr error expectErr error }{ { root: "/", metadataPath: "2009-04-04/meta-data", resources: map[string]string{ "/2009-04-04/meta-data/public-keys": "bad\n", }, expectErr: fmt.Errorf("malformed public key: \"bad\""), }, { root: "/", metadataPath: "2009-04-04/meta-data", resources: map[string]string{ "/2009-04-04/meta-data/hostname": "host", "/2009-04-04/meta-data/local-ipv4": "1.2.3.4", "/2009-04-04/meta-data/public-ipv4": "5.6.7.8", "/2009-04-04/meta-data/public-keys": "0=test1\n", "/2009-04-04/meta-data/public-keys/0": "openssh-key", "/2009-04-04/meta-data/public-keys/0/openssh-key": "key", }, expect: datasource.Metadata{ Hostname: "host", PrivateIPv4: net.ParseIP("1.2.3.4"), PublicIPv4: net.ParseIP("5.6.7.8"), SSHPublicKeys: map[string]string{"test1": "key"}, }, }, { root: "/", metadataPath: "2009-04-04/meta-data", resources: map[string]string{ "/2009-04-04/meta-data/hostname": "host domain another_domain", "/2009-04-04/meta-data/local-ipv4": "1.2.3.4", "/2009-04-04/meta-data/public-ipv4": "5.6.7.8", "/2009-04-04/meta-data/public-keys": "0=test1\n", "/2009-04-04/meta-data/public-keys/0": "openssh-key", "/2009-04-04/meta-data/public-keys/0/openssh-key": "key", }, expect: datasource.Metadata{ Hostname: "host", PrivateIPv4: net.ParseIP("1.2.3.4"), PublicIPv4: net.ParseIP("5.6.7.8"), SSHPublicKeys: map[string]string{"test1": "key"}, }, }, { clientErr: pkg.ErrTimeout{Err: fmt.Errorf("test error")}, expectErr: pkg.ErrTimeout{Err: fmt.Errorf("test error")}, }, } { service := &metadataService{metadata.MetadataService{ Root: tt.root, Client: &test.HttpClient{Resources: tt.resources, Err: tt.clientErr}, MetadataPath: tt.metadataPath, }} metadata, err := service.FetchMetadata() if Error(err) != Error(tt.expectErr) { t.Fatalf("bad error (%q): want %q, got %q", tt.resources, tt.expectErr, err) } if !reflect.DeepEqual(tt.expect, metadata) { t.Fatalf("bad fetch (%q): want %#v, got %#v", tt.resources, tt.expect, metadata) } } } func Error(err error) string { if err != nil { return err.Error() } return "" }
apache-2.0
kma14/Zhua
Zhua.Website/plugins/parsleyjs/src/parsley/field.js
10619
define('parsley/field', [ 'parsley/factory/constraint', 'parsley/ui', 'parsley/utils' ], function (ConstraintFactory, ParsleyUI, ParsleyUtils) { var ParsleyField = function (field, domOptions, options, parsleyFormInstance) { this.__class__ = 'ParsleyField'; this.__id__ = ParsleyUtils.generateID(); this.$element = $(field); // Set parent if we have one if ('undefined' !== typeof parsleyFormInstance) { this.parent = parsleyFormInstance; } this.options = options; this.domOptions = domOptions; // Initialize some properties this.constraints = []; this.constraintsByName = {}; this.validationResult = []; // Bind constraints this._bindConstraints(); }; ParsleyField.prototype = { // # Public API // Validate field and trigger some events for mainly `ParsleyUI` // @returns validationResult: // - `true` if field valid // - `[Violation, [Violation...]]` if there were validation errors validate: function (force) { this.value = this.getValue(); // Field Validate event. `this.value` could be altered for custom needs this._trigger('validate'); this._trigger(this.isValid(force, this.value) ? 'success' : 'error'); // Field validated event. `this.validationResult` could be altered for custom needs too this._trigger('validated'); return this.validationResult; }, hasConstraints: function () { return 0 !== this.constraints.length; }, // An empty optional field does not need validation needsValidation: function (value) { if ('undefined' === typeof value) value = this.getValue(); // If a field is empty and not required, it is valid // Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators if (!value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty) return false; return true; }, // Just validate field. Do not trigger any event // - `false` if there are constraints and at least one of them failed // - `true` in all other cases isValid: function (force, value) { // Recompute options and rebind constraints to have latest changes this.refreshConstraints(); this.validationResult = true; // A field without constraint is valid if (!this.hasConstraints()) return true; // Value could be passed as argument, needed to add more power to 'parsley:field:validate' if ('undefined' === typeof value || null === value) value = this.getValue(); if (!this.needsValidation(value) && true !== force) return true; // If we want to validate field against all constraints, just call Validator and let it do the job var priorities = ['Any']; if (false !== this.options.priorityEnabled) { // Sort priorities to validate more important first priorities = this._getConstraintsSortedPriorities(); } // Iterate over priorities one by one, and validate related asserts one by one for (var i = 0; i < priorities.length; i++) if (true !== (this.validationResult = this.validateThroughValidator(value, this.constraints, priorities[i]))) return false; return true; }, // @returns Parsley field computed value that could be overrided or configured in DOM getValue: function () { var value; // Value could be overriden in DOM or with explicit options if ('function' === typeof this.options.value) value = this.options.value(this); else if ('undefined' !== typeof this.options.value) value = this.options.value; else value = this.$element.val(); // Handle wrong DOM or configurations if ('undefined' === typeof value || null === value) return ''; return this._handleWhitespace(value); }, // Actualize options that could have change since previous validation // Re-bind accordingly constraints (could be some new, removed or updated) refreshConstraints: function () { return this.actualizeOptions()._bindConstraints(); }, /** * Add a new constraint to a field * * @method addConstraint * @param {String} name * @param {Mixed} requirements optional * @param {Number} priority optional * @param {Boolean} isDomConstraint optional */ addConstraint: function (name, requirements, priority, isDomConstraint) { if ('function' === typeof window.ParsleyValidator.validators[name]) { var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint); // if constraint already exist, delete it and push new version if ('undefined' !== this.constraintsByName[constraint.name]) this.removeConstraint(constraint.name); this.constraints.push(constraint); this.constraintsByName[constraint.name] = constraint; } return this; }, // Remove a constraint removeConstraint: function (name) { for (var i = 0; i < this.constraints.length; i++) if (name === this.constraints[i].name) { this.constraints.splice(i, 1); break; } delete this.constraintsByName[name]; return this; }, // Update a constraint (Remove + re-add) updateConstraint: function (name, parameters, priority) { return this.removeConstraint(name) .addConstraint(name, parameters, priority); }, // # Internals // Internal only. // Bind constraints from config + options + DOM _bindConstraints: function () { var constraints = [], constraintsByName = {}; // clean all existing DOM constraints to only keep javascript user constraints for (var i = 0; i < this.constraints.length; i++) if (false === this.constraints[i].isDomConstraint) { constraints.push(this.constraints[i]); constraintsByName[this.constraints[i].name] = this.constraints[i]; } this.constraints = constraints; this.constraintsByName = constraintsByName; // then re-add Parsley DOM-API constraints for (var name in this.options) this.addConstraint(name, this.options[name]); // finally, bind special HTML5 constraints return this._bindHtml5Constraints(); }, // Internal only. // Bind specific HTML5 constraints to be HTML5 compliant _bindHtml5Constraints: function () { // html5 required if (this.$element.hasClass('required') || this.$element.attr('required')) this.addConstraint('required', true, undefined, true); // html5 pattern if ('string' === typeof this.$element.attr('pattern')) this.addConstraint('pattern', this.$element.attr('pattern'), undefined, true); // range if ('undefined' !== typeof this.$element.attr('min') && 'undefined' !== typeof this.$element.attr('max')) this.addConstraint('range', [this.$element.attr('min'), this.$element.attr('max')], undefined, true); // HTML5 min else if ('undefined' !== typeof this.$element.attr('min')) this.addConstraint('min', this.$element.attr('min'), undefined, true); // HTML5 max else if ('undefined' !== typeof this.$element.attr('max')) this.addConstraint('max', this.$element.attr('max'), undefined, true); // length if ('undefined' !== typeof this.$element.attr('minlength') && 'undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('length', [this.$element.attr('minlength'), this.$element.attr('maxlength')], undefined, true); // HTML5 minlength else if ('undefined' !== typeof this.$element.attr('minlength')) this.addConstraint('minlength', this.$element.attr('minlength'), undefined, true); // HTML5 maxlength else if ('undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('maxlength', this.$element.attr('maxlength'), undefined, true); // html5 types var type = this.$element.attr('type'); if ('undefined' === typeof type) return this; // Small special case here for HTML5 number: integer validator if step attribute is undefined or an integer value, number otherwise if ('number' === type) { if (('undefined' === typeof this.$element.attr('step')) || (0 === parseFloat(this.$element.attr('step')) % 1)) { return this.addConstraint('type', 'integer', undefined, true); } else { return this.addConstraint('type', 'number', undefined, true); } // Regular other HTML5 supported types } else if (/^(email|url|range)$/i.test(type)) { return this.addConstraint('type', type, undefined, true); } return this; }, // Internal only. // Field is required if have required constraint without `false` value _isRequired: function () { if ('undefined' === typeof this.constraintsByName.required) return false; return false !== this.constraintsByName.required.requirements; }, // Internal only. // Shortcut to trigger an event _trigger: function (eventName) { eventName = 'field:' + eventName; return this.trigger.apply(this, arguments); }, // Internal only // Handles whitespace in a value // Use `data-parsley-whitespace="squish"` to auto squish input value // Use `data-parsley-whitespace="trim"` to auto trim input value _handleWhitespace: function (value) { if (true === this.options.trimValue) ParsleyUtils.warnOnce('data-parsley-trim-value="true" is deprecated, please use data-parsley-whitespace="trim"'); if ('squish' === this.options.whitespace) value = value.replace(/\s{2,}/g, ' '); if (('trim' === this.options.whitespace) || ('squish' === this.options.whitespace) || (true === this.options.trimValue)) value = value.replace(/^\s+|\s+$/g, ''); return value; }, // Internal only. // Sort constraints by priority DESC _getConstraintsSortedPriorities: function () { var priorities = []; // Create array unique of priorities for (var i = 0; i < this.constraints.length; i++) if (-1 === priorities.indexOf(this.constraints[i].priority)) priorities.push(this.constraints[i].priority); // Sort them by priority DESC priorities.sort(function (a, b) { return b - a; }); return priorities; } }; return ParsleyField; });
mit
alexdresko/DefinitelyTyped
types/nodemailer/lib/addressparser.d.ts
480
declare namespace addressparser { interface Address { name: string; address: string; } } /** * Parses structured e-mail addresses from an address field * * Example: * * 'Name <address@domain>' * * will be converted to * * [{name: 'Name', address: 'address@domain'}] * * @param str Address field * @return An array of address objects */ declare function addressparser(address: string): addressparser.Address[]; export = addressparser;
mit
akopytov/mysql-server
storage/ndb/mcc/frontend/dojo/dojox/editor/plugins/nls/hu/latinEntities.js
9778
//>>built define( //begin v1.x content ({ /* These are already handled in the default RTE amp:"ampersand",lt:"less-than sign", gt:"greater-than sign", nbsp:"no-break space\nnon-breaking space", quot:"quote", */ iexcl:"fordított felkiáltójel", cent:"cent jel", pound:"font jel", curren:"pénznem jel", yen:"jen jel\nyuan jel", brvbar:"megszakított vonal\nmegszakított függőleges vonal", sect:"paragrafusjel", uml:"dupla ékezet\numlaut", copy:"copyright jel", ordf:"nőnemű sorszámnév jelzése a felső indexben", laquo:"balra mutató dupla hegyes idézőjel\nbalra mutató belső idézőjel", not:"nem jel", shy:"lágy kötőjel\nfeltételes kötőjel", reg:"védjegy jel\nbejegyzett védjegy jel", macr:"föléhúzás jel\nAPL felülhúzás", deg:"fok jel", plusmn:"plus-mínusz jel\nplusz-vagy-mínusz jel", sup2:"2 felső indexben\nfelső indexbe írt kettes számjegy\nnégyzetre emelés", sup3:"3 felső indexben\nfelső indexbe írt hármas számjegy\nköbre emelés", acute:"hegyes ékezet\nkalapos ékezet", micro:"mikro jel", para:"sorvége jel\nbekezdés jel", middot:"középső pont\nGregorián vessző\nGörög középső pont", cedil:"cedill\nbalra hajló alsó hurok", sup1:"1 a felső indexben\nfelső indexbe írt egyes számjegy", ordm:"hímnemű sorszámnév jelzése a felső indexben", raquo:"jobbra mutató dupla hegyes idézőjel\njobbra mutató belső idézőjel", frac14:"közönséges egynegyed tört\nnegyed", frac12:"közönséges fél tört\nfél", frac34:"közönséges háromnegyed tört\nháromnegyed", iquest:"fordított kérdőjel\nmegfordított kérdőjel", Agrave:"Latin nagy A betű tompa ékezettel\nTompa ékezetes latin nagy A betű", Aacute:"Latin nagy A betű éles ékezettel", Acirc:"Latin kalapos nagy A betű", Atilde:"Latin hullámvonalas nagy A betű", Auml:"Latin kétpontos nagy A betű", Aring:"Latin nagy A betű felül körrel\nLatin nagy A betű felső körrel", AElig:"Latin nagy AE\nLatin nagy AE ikerbetű", Ccedil:"Latin nagy C betű cedillel", Egrave:"Latin nagy E betű tompa ékezettel", Eacute:"Latin nagy E betű éles ékezettel", Ecirc:"Latin kalapos nagy E betű", Euml:"Latin kétpontos nagy E betű", Igrave:"Latin nagy I betű tompa ékezettel", Iacute:"Latin nagy I betű éles ékezettel", Icirc:"Latin kalapos nagy I betű", Iuml:"Latin kétpontos nagy I betű", ETH:"Latin nagy ETH betű", Ntilde:"Latin hullámvonalas nagy N betű", Ograve:"Latin nagy O betű tompa ékezettel", Oacute:"Latin nagy O betű éles ékezettel", Ocirc:"Latin kalapos nagy O betű", Otilde:"Latin hullámvonalas nagy O betű", Ouml:"Latin kétpontos nagy O betű", times:"szorzásjel", Oslash:"Latin áthúzott nagy O betű\nLatin nagy O betű osztásjellel", Ugrave:"Latin nagy U betű tompa ékezettel", Uacute:"Latin nagy U betű éles ékezettel", Ucirc:"Latin kalapos nagy U betű", Uuml:"Latin kétpontos nagy U betű", Yacute:"Latin nagy Y betű éles ékezettel", THORN:"Latin nagy THORN betű", szlig:"Latin kis sharfes s\neszett", agrave:"Latin kis a betű tompa ékezettel\nTompa ékezetes latin kis a betű", aacute:"Latin kis a betű éles ékezettel", acirc:"Latin kalapos kis a betű", atilde:"Latin hullámvonalas kis a betű", auml:"Latin kétpontos kis a betű", aring:"Latin kis a betű felül körrel\nLatin kis a betű felső körrel", aelig:"Latin kis ae betű\nLatin kis ae ikerbetű", ccedil:"Latin kis c betű cedillel", egrave:"Latin kis e betű tompa ékezettel", eacute:"Latin kis e betű éles ékezettel", ecirc:"Latin kalapos kis e betű", euml:"Latin kétpontos kis e betű", igrave:"Latin kis i betű tompa ékezettel", iacute:"Latin kis i betű éles ékezettel", icirc:"Latin kalapos kis i betű", iuml:"Latin kétpontos kis i betű", eth:"Latin kis eth betű", ntilde:"Latin hullámvonalas kis n betű", ograve:"Latin kis o betű tompa ékezettel", oacute:"Latin kis o betű éles ékezettel", ocirc:"Latin kalapos kis o betű", otilde:"Latin hullámvonalas kis o betű", ouml:"Latin kétpontos kis o betű", divide:"osztásjel", oslash:"Latin áthúzott kis o betű\nLatin kis o betű osztásjellel", ugrave:"Latin kis u betű tompa ékezettel", uacute:"Latin kis u betű éles ékezettel", ucirc:"Latin kalapos kis u betű", uuml:"Latin kétpontos kis u betű", yacute:"Latin kis y éles ékezettel", thorn:"Latin kis thorn betű", yuml:"Latin kétpontos kis y", // Greek Characters and Symbols fnof:"Latin kis f horoggal\nfüggvény\nforint", Alpha:"Görög nagy alfa betű", Beta:"Görög nagy béta betű", Gamma:"Görög nagy gamma betű", Delta:"Görög nagy delta betű", Epsilon:"Görög nagy epszilon betű", Zeta:"Görög nagy dzéta betű", Eta:"Görög nagy éta betű", Theta:"Görög nagy théta betű", Iota:"Görög nagy iota betű", Kappa:"Görög nagy kappa betű", Lambda:"Görög nagy lambda betű", Mu:"Görög nagy mű betű", Nu:"Görög nagy nű betű", Xi:"Görög nagy kszí betű", Omicron:"Görög nagy omikron betű", Pi:"Görög nagy pi betű", Rho:"Görög nagy ró betű", Sigma:"Görög nagy szigma betű", Tau:"Görög nagy tau betű", Upsilon:"Görög nagy üpszilon betű", Phi:"Görög nagy fí betű", Chi:"Görög nagy khí betű", Psi:"Görög nagy pszí betű", Omega:"Görög nagy ómega betű", alpha:"Görög kis alfa betű", beta:"Görög kis béta betű", gamma:"Görög kis gamma betű", delta:"Görög kis delta betű", epsilon:"Görög kis epszilon betű", zeta:"Görög kis dzéta betű", eta:"Görög kis éta betű", theta:"Görög kis théta betű", iota:"Görög kis ióta betű", kappa:"Görög kis kappa betű", lambda:"Görög kis lambda betű", mu:"Görög kis mű betű", nu:"Görög kis nű betű", xi:"Görög kis kszí betű", omicron:"Görög kis omikron betű", pi:"Görög kis pí betű", rho:"Görög kis ró betű", sigmaf:"Görög kis szigma betű utolsó helyen", sigma:"Görög kis szigma betű", tau:"Görög kis taú betű", upsilon:"Görög kis üpszilon betű", phi:"Görög kis fí betű", chi:"Görög kis khí betű", psi:"Görög kis pszí betű", omega:"Görög kis ómega betű", thetasym:"Görög kis théta betű szimbólum", upsih:"Görög üpszilon horog szimbólummal", piv:"Görög pí szimbólum", bull:"pont felsorolásjel\nkis fekete kör", hellip:"vízszintes hármaspont\nbevezető hármas pont", prime:"szimpla egyenes idézőjel\nperc\nláb", Prime:"dupla egyenes idézőjel\nmásodperc\nhüvelyk", oline:"felső vonal\nfelülvonás", frasl:"tört osztásjel", weierp:"írott nagy P\nhatványhalmaz\nWeierstrass p", image:"megtört nagy I\nképzetes (imaginárius) rész", real:"megtört nagy R\nvalós rész szimbólum", trade:"védjegy jel", alefsym:"alef szimbólum\nelső transzfinit pozitív egész szám", larr:"balra mutató nyíl", uarr:"felfelé mutató nyíl", rarr:"jobbra mutató nyíl", darr:"lefelé mutató nyíl", harr:"balra-jobbra mutató nyíl", crarr:"lefelé mutató nyíl bal oldalon sarokkal\nsoremelés", lArr:"balra mutató dupla nyíl", uArr:"felfelé mutató dupla nyíl", rArr:"jobbra mutató dupla nyíl", dArr:"lefelé mutató dupla nyíl", hArr:"balra-jobbra mutató dupla nyíl", forall:"minden\nfordított nagy A betű", part:"részleges differenciál", exist:"létezik", empty:"üres halmaz\nnull halmaz\nátmérő", nabla:"nabla\nfordított különbség", isin:"eleme", notin:"nem eleme", ni:"tagként tartalmazza", prod:"n-tagú Descartes szorzat\nszorzatjel", sum:"n-tagú összegzés", minus:"mínusz jel", lowast:"csillag operátor", radic:"négyzetgyök\nnégyzetgyök jel", prop:"arányos", infin:"végtelen", ang:"szög", and:"logikai és\nék", or:"logikai vagy\nv-alak", cap:"metszet", cup:"unió","int":"integrál", there4:"ezért", sim:"hullám operátor\nváltakozik\nhasonló", cong:"megközelítőleg egyenlő", asymp:"majdnem egyenlő\naszimptotikus", ne:"nem egyenlő", equiv:"azonos", le:"kisebb vagy egyenlő", ge:"nagyobb vagy egyenlő", sub:"részhalmaza", sup:"bővített halmaza", nsub:"nem részhalmaza", sube:"részhalmaza vagy egyenlő", supe:"bővített halmaza vagy egyenlő", oplus:"bekarikázott plusz jel\nközvetlen összeg", otimes:"bekarikázott x\nvektor szorzat", perp:"merőleges\nortogonális", sdot:"pont operátor", lceil:"bal szögletes zárójel felső sarok\nAPL felső keret", rceil:"jobb szögletes zárójel felső sarok", lfloor:"bal szögletes zárójel alsó sarok\nAPL alsó keret", rfloor:"jobb szögletes zárójel alsó sarok", lang:"balra mutató hegyes zárójel", rang:"jobbra mutató hegyes zárójel", loz:"rombusz", spades:"fekete pikk kártyajel", clubs:"fekete treff kártyjel\nlóhere", hearts:"fekete kör kártyajel\nszívalak", diams:"fekete káró káryajel", OElig:"Latin nagy OE ikerbetű", oelig:"Latin kis oe ikerbetű", Scaron:"Latin nagy S betű csónakkal", scaron:"Latin kis s betű csónakkal", Yuml:"Latin kétpontos nagy Y betű", circ:"betűt módosító kalap ékezet", tilde:"kis hullám", ensp:"n szóköz", emsp:"m szóköz", thinsp:"szűk szóköz", zwnj:"törhető üres jel", zwj:"nem törhető üres jel", lrm:"balról jobbra jel", rlm:"jobbról balra jel", ndash:"n kötőjel", mdash:"m kötőjel", lsquo:"bal szimpla idézőjel", rsquo:"jobb szimpla idézőjel", sbquo:"alsó 9-es szimpla idézőjel", ldquo:"bal dupla idézőjel", rdquo:"jobb dupla idézőjel", bdquo:"alsó 9-es dupla idézőjel", dagger:"kereszt", Dagger:"dupla kereszt", permil:"ezrelékjel", lsaquo:"szimpla balra mutató hegyes idézőjel", rsaquo:"szimpla jobbra mutató hegyes idézőjel", euro:"euro jel" }) //end v1.x content );
gpl-2.0
jegelstaff/formulize
libraries/googleapiclient/vendor/google/apiclient-services/src/Google/Service/People/ListConnectionsResponse.php
1411
<?php /* * Copyright 2014 Google Inc. * * 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. */ class Google_Service_People_ListConnectionsResponse extends Google_Collection { protected $collection_key = 'connections'; protected $connectionsType = 'Google_Service_People_Person'; protected $connectionsDataType = 'array'; public $nextPageToken; public $nextSyncToken; public function setConnections($connections) { $this->connections = $connections; } public function getConnections() { return $this->connections; } public function setNextPageToken($nextPageToken) { $this->nextPageToken = $nextPageToken; } public function getNextPageToken() { return $this->nextPageToken; } public function setNextSyncToken($nextSyncToken) { $this->nextSyncToken = $nextSyncToken; } public function getNextSyncToken() { return $this->nextSyncToken; } }
gpl-2.0
tkrille/spring-security-oauth
samples/oauth2/sparklr/src/main/java/org/springframework/security/oauth/examples/sparklr/PhotoService.java
550
package org.springframework.security.oauth.examples.sparklr; import java.io.InputStream; import java.util.Collection; /** * Service for retrieving photos. * * @author Ryan Heaton */ public interface PhotoService { /** * Load the photos for the current user. * * @return The photos for the current user. */ Collection<PhotoInfo> getPhotosForCurrentUser(String username); /** * Load a photo by id. * * @param id The id of the photo. * @return The photo that was read. */ InputStream loadPhoto(String id); }
apache-2.0
stronglee/UltimateAndroid
UltimateAndroidGradle/ultimateandroiduicomponent/src/main/java/com/marshalchen/common/uimodule/cardsSwiped/view/BaseCardStackAdapter.java
163
package com.marshalchen.common.uimodule.cardsSwiped.view; import android.widget.BaseAdapter; public abstract class BaseCardStackAdapter extends BaseAdapter { }
apache-2.0
gabrielfalcao/lettuce
tests/integration/lib/Django-1.2.5/django/db/transaction.py
12689
""" This module implements a transaction manager that can be used to define transaction handling in a request or view function. It is used by transaction control middleware and decorators. The transaction manager can be in managed or in auto state. Auto state means the system is using a commit-on-save strategy (actually it's more like commit-on-change). As soon as the .save() or .delete() (or related) methods are called, a commit is made. Managed transactions don't do those commits, but will need some kind of manual or implicit commits or rollbacks. """ try: import thread except ImportError: import dummy_thread as thread try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. from django.db import connections, DEFAULT_DB_ALIAS from django.conf import settings class TransactionManagementError(Exception): """ This exception is thrown when something bad happens with transaction management. """ pass # The states are dictionaries of dictionaries of lists. The key to the outer # dict is the current thread, and the key to the inner dictionary is the # connection alias and the list is handled as a stack of values. state = {} savepoint_state = {} # The dirty flag is set by *_unless_managed functions to denote that the # code under transaction management has changed things to require a # database commit. # This is a dictionary mapping thread to a dictionary mapping connection # alias to a boolean. dirty = {} def enter_transaction_management(managed=True, using=None): """ Enters transaction management for a running thread. It must be balanced with the appropriate leave_transaction_management call, since the actual state is managed as a stack. The state and dirty flag are carried over from the surrounding block or from the settings, if there is no surrounding block (dirty is always false when no current block is running). """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() if thread_ident in state and state[thread_ident].get(using): state[thread_ident][using].append(state[thread_ident][using][-1]) else: state.setdefault(thread_ident, {}) state[thread_ident][using] = [settings.TRANSACTIONS_MANAGED] if thread_ident not in dirty or using not in dirty[thread_ident]: dirty.setdefault(thread_ident, {}) dirty[thread_ident][using] = False connection._enter_transaction_management(managed) def leave_transaction_management(using=None): """ Leaves transaction management for a running thread. A dirty flag is carried over to the surrounding block, as a commit will commit all changes, even those from outside. (Commits are on connection level.) """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] connection._leave_transaction_management(is_managed(using=using)) thread_ident = thread.get_ident() if thread_ident in state and state[thread_ident].get(using): del state[thread_ident][using][-1] else: raise TransactionManagementError("This code isn't under transaction management") if dirty.get(thread_ident, {}).get(using, False): rollback(using=using) raise TransactionManagementError("Transaction managed block ended with pending COMMIT/ROLLBACK") dirty[thread_ident][using] = False def is_dirty(using=None): """ Returns True if the current transaction requires a commit for changes to happen. """ if using is None: using = DEFAULT_DB_ALIAS return dirty.get(thread.get_ident(), {}).get(using, False) def set_dirty(using=None): """ Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit. """ if using is None: using = DEFAULT_DB_ALIAS thread_ident = thread.get_ident() if thread_ident in dirty and using in dirty[thread_ident]: dirty[thread_ident][using] = True else: raise TransactionManagementError("This code isn't under transaction management") def set_clean(using=None): """ Resets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether a commit or rollback should happen. """ if using is None: using = DEFAULT_DB_ALIAS thread_ident = thread.get_ident() if thread_ident in dirty and using in dirty[thread_ident]: dirty[thread_ident][using] = False else: raise TransactionManagementError("This code isn't under transaction management") clean_savepoints(using=using) def clean_savepoints(using=None): if using is None: using = DEFAULT_DB_ALIAS thread_ident = thread.get_ident() if thread_ident in savepoint_state and using in savepoint_state[thread_ident]: del savepoint_state[thread_ident][using] def is_managed(using=None): """ Checks whether the transaction manager is in manual or in auto state. """ if using is None: using = DEFAULT_DB_ALIAS thread_ident = thread.get_ident() if thread_ident in state and using in state[thread_ident]: if state[thread_ident][using]: return state[thread_ident][using][-1] return settings.TRANSACTIONS_MANAGED def managed(flag=True, using=None): """ Puts the transaction manager into a manual state: managed transactions have to be committed explicitly by the user. If you switch off transaction management and there is a pending commit/rollback, the data will be commited. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() top = state.get(thread_ident, {}).get(using, None) if top: top[-1] = flag if not flag and is_dirty(using=using): connection._commit() set_clean(using=using) else: raise TransactionManagementError("This code isn't under transaction management") def commit_unless_managed(using=None): """ Commits changes if the system is not in managed transaction mode. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] if not is_managed(using=using): connection._commit() clean_savepoints(using=using) else: set_dirty(using=using) def rollback_unless_managed(using=None): """ Rolls back changes if the system is not in managed transaction mode. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] if not is_managed(using=using): connection._rollback() else: set_dirty(using=using) def commit(using=None): """ Does the commit itself and resets the dirty flag. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] connection._commit() set_clean(using=using) def rollback(using=None): """ This function does the rollback itself and resets the dirty flag. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] connection._rollback() set_clean(using=using) def savepoint(using=None): """ Creates a savepoint (if supported and required by the backend) inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() if thread_ident in savepoint_state and using in savepoint_state[thread_ident]: savepoint_state[thread_ident][using].append(None) else: savepoint_state.setdefault(thread_ident, {}) savepoint_state[thread_ident][using] = [None] tid = str(thread_ident).replace('-', '') sid = "s%s_x%d" % (tid, len(savepoint_state[thread_ident][using])) connection._savepoint(sid) return sid def savepoint_rollback(sid, using=None): """ Rolls back the most recent savepoint (if one exists). Does nothing if savepoints are not supported. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() if thread_ident in savepoint_state and using in savepoint_state[thread_ident]: connection._savepoint_rollback(sid) def savepoint_commit(sid, using=None): """ Commits the most recent savepoint (if one exists). Does nothing if savepoints are not supported. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() if thread_ident in savepoint_state and using in savepoint_state[thread_ident]: connection._savepoint_commit(sid) ############## # DECORATORS # ############## def autocommit(using=None): """ Decorator that activates commit on save. This is Django's default behavior; this decorator is useful if you globally activated transaction management in your settings file and want the default behavior in some view functions. """ def inner_autocommit(func, db=None): def _autocommit(*args, **kw): try: enter_transaction_management(managed=False, using=db) managed(False, using=db) return func(*args, **kw) finally: leave_transaction_management(using=db) return wraps(func)(_autocommit) # Note that although the first argument is *called* `using`, it # may actually be a function; @autocommit and @autocommit('foo') # are both allowed forms. if using is None: using = DEFAULT_DB_ALIAS if callable(using): return inner_autocommit(using, DEFAULT_DB_ALIAS) return lambda func: inner_autocommit(func, using) def commit_on_success(using=None): """ This decorator activates commit on response. This way, if the view function runs successfully, a commit is made; if the viewfunc produces an exception, a rollback is made. This is one of the most common ways to do transaction control in Web apps. """ def inner_commit_on_success(func, db=None): def _commit_on_success(*args, **kw): try: enter_transaction_management(using=db) managed(True, using=db) try: res = func(*args, **kw) except: # All exceptions must be handled here (even string ones). if is_dirty(using=db): rollback(using=db) raise else: if is_dirty(using=db): try: commit(using=db) except: rollback(using=db) raise return res finally: leave_transaction_management(using=db) return wraps(func)(_commit_on_success) # Note that although the first argument is *called* `using`, it # may actually be a function; @autocommit and @autocommit('foo') # are both allowed forms. if using is None: using = DEFAULT_DB_ALIAS if callable(using): return inner_commit_on_success(using, DEFAULT_DB_ALIAS) return lambda func: inner_commit_on_success(func, using) def commit_manually(using=None): """ Decorator that activates manual transaction control. It just disables automatic transaction control and doesn't do any commit/rollback of its own -- it's up to the user to call the commit and rollback functions themselves. """ def inner_commit_manually(func, db=None): def _commit_manually(*args, **kw): try: enter_transaction_management(using=db) managed(True, using=db) return func(*args, **kw) finally: leave_transaction_management(using=db) return wraps(func)(_commit_manually) # Note that although the first argument is *called* `using`, it # may actually be a function; @autocommit and @autocommit('foo') # are both allowed forms. if using is None: using = DEFAULT_DB_ALIAS if callable(using): return inner_commit_manually(using, DEFAULT_DB_ALIAS) return lambda func: inner_commit_manually(func, using)
gpl-3.0
wolv-dev/shopware
_sql/migrations/430-add-shop-page-form-shopid.php
316
<?php class Migrations_Migration430 Extends Shopware\Components\Migrations\AbstractMigration { public function up($modus) { $this->addSql("ALTER TABLE `s_cms_static` ADD `shop_ids` VARCHAR(255) NULL;"); $this->addSql("ALTER TABLE `s_cms_support` ADD `shop_ids` VARCHAR(255) NULL;"); } }
agpl-3.0
qjcjerry/j2ee-arch
web/src/main/java/com/sishuok/es/sys/group/entity/Group.java
1693
/** * Copyright (c) 2005-2012 https://github.com/zhangkaitao * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.sishuok.es.sys.group.entity; import com.sishuok.es.common.entity.BaseEntity; import com.sishuok.es.common.repository.support.annotation.EnableQueryCache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; /** * 分组超类 * <p>User: Zhang Kaitao * <p>Date: 13-4-19 上午7:13 * <p>Version: 1.0 */ @Entity @Table(name = "sys_group") @EnableQueryCache @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Group extends BaseEntity<Long> { /** * 分组名称 */ private String name; /** * 分组类型 如 用户分组/组织机构分组 */ @Enumerated(EnumType.STRING) private GroupType type; /** * 是否是默认分组 */ @Column(name = "default_group") private Boolean defaultGroup = Boolean.FALSE; /** * 是否显示/可用 */ @Column(name = "is_show") private Boolean show = Boolean.FALSE; public String getName() { return name; } public void setName(String name) { this.name = name; } public GroupType getType() { return type; } public void setType(GroupType type) { this.type = type; } public Boolean getDefaultGroup() { return defaultGroup; } public void setDefaultGroup(Boolean defaultGroup) { this.defaultGroup = defaultGroup; } public Boolean getShow() { return show; } public void setShow(Boolean show) { this.show = show; } }
apache-2.0
CE-KMITL-CLOUD-2014/Responsive_LMS
laravel/public/sdkazure/vendor/pear-pear.php.net/PEAR/PEAR/Builder.php
16774
<?php /** * PEAR_Builder for building PHP extensions (PECL packages) * * PHP versions 4 and 5 * * @category pear * @package PEAR * @author Stig Bakken <[email protected]> * @author Greg Beaver <[email protected]> * @copyright 1997-2009 The Authors * @license http://opensource.org/licenses/bsd-license.php New BSD License * @version CVS: $Id$ * @link http://pear.php.net/package/PEAR * @since File available since Release 0.1 * * TODO: log output parameters in PECL command line * TODO: msdev path in configuration */ /** * Needed for extending PEAR_Builder */ require_once 'PEAR/Common.php'; require_once 'PEAR/PackageFile.php'; /** * Class to handle building (compiling) extensions. * * @category pear * @package PEAR * @author Stig Bakken <[email protected]> * @author Greg Beaver <[email protected]> * @copyright 1997-2009 The Authors * @license http://opensource.org/licenses/bsd-license.php New BSD License * @version Release: 1.9.5 * @link http://pear.php.net/package/PEAR * @since Class available since PHP 4.0.2 * @see http://pear.php.net/manual/en/core.ppm.pear-builder.php */ class PEAR_Builder extends PEAR_Common { var $php_api_version = 0; var $zend_module_api_no = 0; var $zend_extension_api_no = 0; var $extensions_built = array(); /** * @var string Used for reporting when it is not possible to pass function * via extra parameter, e.g. log, msdevCallback */ var $current_callback = null; // used for msdev builds var $_lastline = null; var $_firstline = null; /** * PEAR_Builder constructor. * * @param object $ui user interface object (instance of PEAR_Frontend_*) * * @access public */ function PEAR_Builder(&$ui) { parent::PEAR_Common(); $this->setFrontendObject($ui); } /** * Build an extension from source on windows. * requires msdev */ function _build_win32($descfile, $callback = null) { if (is_object($descfile)) { $pkg = $descfile; $descfile = $pkg->getPackageFile(); } else { $pf = &new PEAR_PackageFile($this->config, $this->debug); $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pkg)) { return $pkg; } } $dir = dirname($descfile); $old_cwd = getcwd(); if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) { return $this->raiseError("could not chdir to $dir"); } // packages that were in a .tar have the packagefile in this directory $vdir = $pkg->getPackage() . '-' . $pkg->getVersion(); if (file_exists($dir) && is_dir($vdir)) { if (!chdir($vdir)) { return $this->raiseError("could not chdir to " . realpath($vdir)); } $dir = getcwd(); } $this->log(2, "building in $dir"); $dsp = $pkg->getPackage().'.dsp'; if (!file_exists("$dir/$dsp")) { return $this->raiseError("The DSP $dsp does not exist."); } // XXX TODO: make release build type configurable $command = 'msdev '.$dsp.' /MAKE "'.$pkg->getPackage(). ' - Release"'; $err = $this->_runCommand($command, array(&$this, 'msdevCallback')); if (PEAR::isError($err)) { return $err; } // figure out the build platform and type $platform = 'Win32'; $buildtype = 'Release'; if (preg_match('/.*?'.$pkg->getPackage().'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) { $platform = $matches[1]; $buildtype = $matches[2]; } if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/', $this->_lastline, $matches)) { if ($matches[2]) { // there were errors in the build return $this->raiseError("There were errors during compilation."); } $out = $matches[1]; } else { return $this->raiseError("Did not understand the completion status returned from msdev.exe."); } // msdev doesn't tell us the output directory :/ // open the dsp, find /out and use that directory $dsptext = join(file($dsp),''); // this regex depends on the build platform and type having been // correctly identified above. $regex ='/.*?!IF\s+"\$\(CFG\)"\s+==\s+("'. $pkg->getPackage().'\s-\s'. $platform.'\s'. $buildtype.'").*?'. '\/out:"(.*?)"/is'; if ($dsptext && preg_match($regex, $dsptext, $matches)) { // what we get back is a relative path to the output file itself. $outfile = realpath($matches[2]); } else { return $this->raiseError("Could not retrieve output information from $dsp."); } // realpath returns false if the file doesn't exist if ($outfile && copy($outfile, "$dir/$out")) { $outfile = "$dir/$out"; } $built_files[] = array( 'file' => "$outfile", 'php_api' => $this->php_api_version, 'zend_mod_api' => $this->zend_module_api_no, 'zend_ext_api' => $this->zend_extension_api_no, ); return $built_files; } // }}} // {{{ msdevCallback() function msdevCallback($what, $data) { if (!$this->_firstline) $this->_firstline = $data; $this->_lastline = $data; call_user_func($this->current_callback, $what, $data); } /** * @param string * @param string * @param array * @access private */ function _harvestInstDir($dest_prefix, $dirname, &$built_files) { $d = opendir($dirname); if (!$d) return false; $ret = true; while (($ent = readdir($d)) !== false) { if ($ent{0} == '.') continue; $full = $dirname . DIRECTORY_SEPARATOR . $ent; if (is_dir($full)) { if (!$this->_harvestInstDir( $dest_prefix . DIRECTORY_SEPARATOR . $ent, $full, $built_files)) { $ret = false; break; } } else { $dest = $dest_prefix . DIRECTORY_SEPARATOR . $ent; $built_files[] = array( 'file' => $full, 'dest' => $dest, 'php_api' => $this->php_api_version, 'zend_mod_api' => $this->zend_module_api_no, 'zend_ext_api' => $this->zend_extension_api_no, ); } } closedir($d); return $ret; } /** * Build an extension from source. Runs "phpize" in the source * directory, but compiles in a temporary directory * (TMPDIR/pear-build-USER/PACKAGE-VERSION). * * @param string|PEAR_PackageFile_v* $descfile path to XML package description file, or * a PEAR_PackageFile object * * @param mixed $callback callback function used to report output, * see PEAR_Builder::_runCommand for details * * @return array an array of associative arrays with built files, * format: * array( array( 'file' => '/path/to/ext.so', * 'php_api' => YYYYMMDD, * 'zend_mod_api' => YYYYMMDD, * 'zend_ext_api' => YYYYMMDD ), * ... ) * * @access public * * @see PEAR_Builder::_runCommand */ function build($descfile, $callback = null) { if (preg_match('/(\\/|\\\\|^)([^\\/\\\\]+)?php([^\\/\\\\]+)?$/', $this->config->get('php_bin'), $matches)) { if (isset($matches[2]) && strlen($matches[2]) && trim($matches[2]) != trim($this->config->get('php_prefix'))) { $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') . ' appears to have a prefix ' . $matches[2] . ', but' . ' config variable php_prefix does not match'); } if (isset($matches[3]) && strlen($matches[3]) && trim($matches[3]) != trim($this->config->get('php_suffix'))) { $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') . ' appears to have a suffix ' . $matches[3] . ', but' . ' config variable php_suffix does not match'); } } $this->current_callback = $callback; if (PEAR_OS == "Windows") { return $this->_build_win32($descfile, $callback); } if (PEAR_OS != 'Unix') { return $this->raiseError("building extensions not supported on this platform"); } if (is_object($descfile)) { $pkg = $descfile; $descfile = $pkg->getPackageFile(); if (is_a($pkg, 'PEAR_PackageFile_v1')) { $dir = dirname($descfile); } else { $dir = $pkg->_config->get('temp_dir') . '/' . $pkg->getName(); // automatically delete at session end $this->addTempFile($dir); } } else { $pf = &new PEAR_PackageFile($this->config); $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pkg)) { return $pkg; } $dir = dirname($descfile); } // Find config. outside of normal path - e.g. config.m4 foreach (array_keys($pkg->getInstallationFileList()) as $item) { if (stristr(basename($item), 'config.m4') && dirname($item) != '.') { $dir .= DIRECTORY_SEPARATOR . dirname($item); break; } } $old_cwd = getcwd(); if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) { return $this->raiseError("could not chdir to $dir"); } $vdir = $pkg->getPackage() . '-' . $pkg->getVersion(); if (is_dir($vdir)) { chdir($vdir); } $dir = getcwd(); $this->log(2, "building in $dir"); putenv('PATH=' . $this->config->get('bin_dir') . ':' . getenv('PATH')); $err = $this->_runCommand($this->config->get('php_prefix') . "phpize" . $this->config->get('php_suffix'), array(&$this, 'phpizeCallback')); if (PEAR::isError($err)) { return $err; } if (!$err) { return $this->raiseError("`phpize' failed"); } // {{{ start of interactive part $configure_command = "$dir/configure"; $configure_options = $pkg->getConfigureOptions(); if ($configure_options) { foreach ($configure_options as $o) { $default = array_key_exists('default', $o) ? $o['default'] : null; list($r) = $this->ui->userDialog('build', array($o['prompt']), array('text'), array($default)); if (substr($o['name'], 0, 5) == 'with-' && ($r == 'yes' || $r == 'autodetect')) { $configure_command .= " --$o[name]"; } else { $configure_command .= " --$o[name]=".trim($r); } } } // }}} end of interactive part // FIXME make configurable if (!$user=getenv('USER')) { $user='defaultuser'; } $tmpdir = $this->config->get('temp_dir'); $build_basedir = System::mktemp(' -t "' . $tmpdir . '" -d "pear-build-' . $user . '"'); $build_dir = "$build_basedir/$vdir"; $inst_dir = "$build_basedir/install-$vdir"; $this->log(1, "building in $build_dir"); if (is_dir($build_dir)) { System::rm(array('-rf', $build_dir)); } if (!System::mkDir(array('-p', $build_dir))) { return $this->raiseError("could not create build dir: $build_dir"); } $this->addTempFile($build_dir); if (!System::mkDir(array('-p', $inst_dir))) { return $this->raiseError("could not create temporary install dir: $inst_dir"); } $this->addTempFile($inst_dir); $make_command = getenv('MAKE') ? getenv('MAKE') : 'make'; $to_run = array( $configure_command, $make_command, "$make_command INSTALL_ROOT=\"$inst_dir\" install", "find \"$inst_dir\" | xargs ls -dils" ); if (!file_exists($build_dir) || !is_dir($build_dir) || !chdir($build_dir)) { return $this->raiseError("could not chdir to $build_dir"); } putenv('PHP_PEAR_VERSION=1.9.5'); foreach ($to_run as $cmd) { $err = $this->_runCommand($cmd, $callback); if (PEAR::isError($err)) { chdir($old_cwd); return $err; } if (!$err) { chdir($old_cwd); return $this->raiseError("`$cmd' failed"); } } if (!($dp = opendir("modules"))) { chdir($old_cwd); return $this->raiseError("no `modules' directory found"); } $built_files = array(); $prefix = exec($this->config->get('php_prefix') . "php-config" . $this->config->get('php_suffix') . " --prefix"); $this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files); chdir($old_cwd); return $built_files; } /** * Message callback function used when running the "phpize" * program. Extracts the API numbers used. Ignores other message * types than "cmdoutput". * * @param string $what the type of message * @param mixed $data the message * * @return void * * @access public */ function phpizeCallback($what, $data) { if ($what != 'cmdoutput') { return; } $this->log(1, rtrim($data)); if (preg_match('/You should update your .aclocal.m4/', $data)) { return; } $matches = array(); if (preg_match('/^\s+(\S[^:]+):\s+(\d{8})/', $data, $matches)) { $member = preg_replace('/[^a-z]/', '_', strtolower($matches[1])); $apino = (int)$matches[2]; if (isset($this->$member)) { $this->$member = $apino; //$msg = sprintf("%-22s : %d", $matches[1], $apino); //$this->log(1, $msg); } } } /** * Run an external command, using a message callback to report * output. The command will be run through popen and output is * reported for every line with a "cmdoutput" message with the * line string, including newlines, as payload. * * @param string $command the command to run * * @param mixed $callback (optional) function to use as message * callback * * @return bool whether the command was successful (exit code 0 * means success, any other means failure) * * @access private */ function _runCommand($command, $callback = null) { $this->log(1, "running: $command"); $pp = popen("$command 2>&1", "r"); if (!$pp) { return $this->raiseError("failed to run `$command'"); } if ($callback && $callback[0]->debug == 1) { $olddbg = $callback[0]->debug; $callback[0]->debug = 2; } while ($line = fgets($pp, 1024)) { if ($callback) { call_user_func($callback, 'cmdoutput', $line); } else { $this->log(2, rtrim($line)); } } if ($callback && isset($olddbg)) { $callback[0]->debug = $olddbg; } $exitcode = is_resource($pp) ? pclose($pp) : -1; return ($exitcode == 0); } function log($level, $msg) { if ($this->current_callback) { if ($this->debug >= $level) { call_user_func($this->current_callback, 'output', $msg); } return; } return PEAR_Common::log($level, $msg); } }
apache-2.0
xcatliu/react-native
packager/launchEditor.js
1324
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var fs = require('fs'); var spawn = require('child_process').spawn; var firstLaunch = true; function guessEditor() { if (firstLaunch) { console.log('When you see Red Box with stack trace, you can click any ' + 'stack frame to jump to the source file. The packager will launch your ' + 'editor of choice. It will first look at REACT_EDITOR environment ' + 'variable, then at EDITOR. To set it up, you can add something like ' + 'REACT_EDITOR=atom to your .bashrc.'); firstLaunch = false; } var editor = process.env.REACT_EDITOR || process.env.EDITOR || 'subl'; return editor; } function launchEditor(fileName, lineNumber) { if (!fs.existsSync(fileName)) { return; } var argument = fileName; if (lineNumber) { argument += ':' + lineNumber; } var editor = guessEditor(); console.log('Opening ' + fileName + ' with ' + editor); spawn(editor, [argument], { stdio: ['pipe', 'pipe', process.stderr] }); } module.exports = launchEditor;
bsd-3-clause
aospx-kitkat/platform_external_chromium_org
third_party/harfbuzz-ng/src/hb-ot-shape-complex-indic-private.hh
5104
/* * Copyright © 2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Google Author(s): Behdad Esfahbod */ #ifndef HB_OT_SHAPE_COMPLEX_INDIC_PRIVATE_HH #define HB_OT_SHAPE_COMPLEX_INDIC_PRIVATE_HH #include "hb-private.hh" #include "hb-ot-shape-complex-private.hh" #include "hb-ot-shape-private.hh" /* XXX Remove */ #define INDIC_TABLE_ELEMENT_TYPE uint16_t /* Cateories used in the OpenType spec: * https://www.microsoft.com/typography/otfntdev/devanot/shaping.aspx */ /* Note: This enum is duplicated in the -machine.rl source file. * Not sure how to avoid duplication. */ enum indic_category_t { OT_X = 0, OT_C, OT_V, OT_N, OT_H, OT_ZWNJ, OT_ZWJ, OT_M, OT_SM, OT_VD, OT_A, OT_NBSP, OT_DOTTEDCIRCLE, /* Not in the spec, but special in Uniscribe. /Very very/ special! */ OT_RS, /* Register Shifter, used in Khmer OT spec */ OT_Coeng, OT_Repha, OT_Ra, /* Not explicitly listed in the OT spec, but used in the grammar. */ OT_CM }; /* Visual positions in a syllable from left to right. */ enum indic_position_t { POS_START, POS_RA_TO_BECOME_REPH, POS_PRE_M, POS_PRE_C, POS_BASE_C, POS_AFTER_MAIN, POS_ABOVE_C, POS_BEFORE_SUB, POS_BELOW_C, POS_AFTER_SUB, POS_BEFORE_POST, POS_POST_C, POS_AFTER_POST, POS_FINAL_C, POS_SMVD, POS_END }; /* Categories used in IndicSyllabicCategory.txt from UCD. */ enum indic_syllabic_category_t { INDIC_SYLLABIC_CATEGORY_OTHER = OT_X, INDIC_SYLLABIC_CATEGORY_AVAGRAHA = OT_X, INDIC_SYLLABIC_CATEGORY_BINDU = OT_SM, INDIC_SYLLABIC_CATEGORY_CONSONANT = OT_C, INDIC_SYLLABIC_CATEGORY_CONSONANT_DEAD = OT_C, INDIC_SYLLABIC_CATEGORY_CONSONANT_FINAL = OT_CM, INDIC_SYLLABIC_CATEGORY_CONSONANT_HEAD_LETTER = OT_C, INDIC_SYLLABIC_CATEGORY_CONSONANT_MEDIAL = OT_CM, INDIC_SYLLABIC_CATEGORY_CONSONANT_PLACEHOLDER = OT_NBSP, INDIC_SYLLABIC_CATEGORY_CONSONANT_SUBJOINED = OT_C, INDIC_SYLLABIC_CATEGORY_CONSONANT_REPHA = OT_Repha, INDIC_SYLLABIC_CATEGORY_MODIFYING_LETTER = OT_X, INDIC_SYLLABIC_CATEGORY_NUKTA = OT_N, INDIC_SYLLABIC_CATEGORY_REGISTER_SHIFTER = OT_RS, INDIC_SYLLABIC_CATEGORY_TONE_LETTER = OT_X, INDIC_SYLLABIC_CATEGORY_TONE_MARK = OT_N, INDIC_SYLLABIC_CATEGORY_VIRAMA = OT_H, INDIC_SYLLABIC_CATEGORY_VISARGA = OT_SM, INDIC_SYLLABIC_CATEGORY_VOWEL = OT_V, INDIC_SYLLABIC_CATEGORY_VOWEL_DEPENDENT = OT_M, INDIC_SYLLABIC_CATEGORY_VOWEL_INDEPENDENT = OT_V }; /* Categories used in IndicSMatraCategory.txt from UCD */ enum indic_matra_category_t { INDIC_MATRA_CATEGORY_NOT_APPLICABLE = POS_END, INDIC_MATRA_CATEGORY_LEFT = POS_PRE_C, INDIC_MATRA_CATEGORY_TOP = POS_ABOVE_C, INDIC_MATRA_CATEGORY_BOTTOM = POS_BELOW_C, INDIC_MATRA_CATEGORY_RIGHT = POS_POST_C, /* These should resolve to the position of the last part of the split sequence. */ INDIC_MATRA_CATEGORY_BOTTOM_AND_RIGHT = INDIC_MATRA_CATEGORY_RIGHT, INDIC_MATRA_CATEGORY_LEFT_AND_RIGHT = INDIC_MATRA_CATEGORY_RIGHT, INDIC_MATRA_CATEGORY_TOP_AND_BOTTOM = INDIC_MATRA_CATEGORY_BOTTOM, INDIC_MATRA_CATEGORY_TOP_AND_BOTTOM_AND_RIGHT = INDIC_MATRA_CATEGORY_RIGHT, INDIC_MATRA_CATEGORY_TOP_AND_LEFT = INDIC_MATRA_CATEGORY_TOP, INDIC_MATRA_CATEGORY_TOP_AND_LEFT_AND_RIGHT = INDIC_MATRA_CATEGORY_RIGHT, INDIC_MATRA_CATEGORY_TOP_AND_RIGHT = INDIC_MATRA_CATEGORY_RIGHT, INDIC_MATRA_CATEGORY_INVISIBLE = INDIC_MATRA_CATEGORY_NOT_APPLICABLE, INDIC_MATRA_CATEGORY_OVERSTRUCK = POS_AFTER_MAIN, INDIC_MATRA_CATEGORY_VISUAL_ORDER_LEFT = POS_PRE_M }; /* Note: We use ASSERT_STATIC_EXPR_ZERO() instead of ASSERT_STATIC_EXPR() and the comma operation * because gcc fails to optimize the latter and fills the table in at runtime. */ #define INDIC_COMBINE_CATEGORIES(S,M) \ (ASSERT_STATIC_EXPR_ZERO (M == INDIC_MATRA_CATEGORY_NOT_APPLICABLE || (S == INDIC_SYLLABIC_CATEGORY_VIRAMA || S == INDIC_SYLLABIC_CATEGORY_VOWEL_DEPENDENT)) + \ ASSERT_STATIC_EXPR_ZERO (S < 255 && M < 255) + \ ((M << 8) | S)) HB_INTERNAL INDIC_TABLE_ELEMENT_TYPE hb_indic_get_categories (hb_codepoint_t u); #endif /* HB_OT_SHAPE_COMPLEX_INDIC_PRIVATE_HH */
bsd-3-clause
odooo/design
vendor/giggsey/libphonenumber-for-php/src/geocoding/data/fr/225.php
409
<?php /** * This file is automatically @generated by {@link GeneratePhonePrefixData}. * Please don't modify it directly. */ return array ( 22520 => 'Plateau', 22521 => 'Abidjan', 22522 => 'Cocody', 22523 => 'Banco', 22524 => 'Abobo', 22530 => 'Yamoussoukro', 22531 => 'Bouaké', 22532 => 'Daloa', 22533 => 'Man', 22534 => 'San Pedro', 22535 => 'Abengourou', 22536 => 'Korhogo', );
mit
isman-usoh/DefinitelyTyped
types/lodash-es/isArrayLikeObject/index.d.ts
124
import * as _ from "lodash"; declare const isArrayLikeObject: typeof _.isArrayLikeObject; export default isArrayLikeObject;
mit
jeffvance/origin
vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/controller/repair.go
6042
/* Copyright 2015 The Kubernetes Authors. 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. */ package controller import ( "fmt" "net" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/registry/rangeallocation" "k8s.io/kubernetes/pkg/registry/service" "k8s.io/kubernetes/pkg/registry/service/ipallocator" "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/wait" ) // Repair is a controller loop that periodically examines all service ClusterIP allocations // and logs any errors, and then sets the compacted and accurate list of all allocated IPs. // // Handles: // * Duplicate ClusterIP assignments caused by operator action or undetected race conditions // * ClusterIPs that do not match the currently configured range // * Allocations to services that were not actually created due to a crash or powerloss // * Migrates old versions of Kubernetes services into the atomic ipallocator model automatically // // Can be run at infrequent intervals, and is best performed on startup of the master. // Is level driven and idempotent - all valid ClusterIPs will be updated into the ipallocator // map at the end of a single execution loop if no race is encountered. // // TODO: allocate new IPs if necessary // TODO: perform repair? type Repair struct { interval time.Duration registry service.Registry network *net.IPNet alloc rangeallocation.RangeRegistry } // NewRepair creates a controller that periodically ensures that all clusterIPs are uniquely allocated across the cluster // and generates informational warnings for a cluster that is not in sync. func NewRepair(interval time.Duration, registry service.Registry, network *net.IPNet, alloc rangeallocation.RangeRegistry) *Repair { return &Repair{ interval: interval, registry: registry, network: network, alloc: alloc, } } // RunUntil starts the controller until the provided ch is closed. func (c *Repair) RunUntil(ch chan struct{}) { wait.Until(func() { if err := c.RunOnce(); err != nil { runtime.HandleError(err) } }, c.interval, ch) } // RunOnce verifies the state of the cluster IP allocations and returns an error if an unrecoverable problem occurs. func (c *Repair) RunOnce() error { return client.RetryOnConflict(client.DefaultBackoff, c.runOnce) } // runOnce verifies the state of the cluster IP allocations and returns an error if an unrecoverable problem occurs. func (c *Repair) runOnce() error { // TODO: (per smarterclayton) if Get() or ListServices() is a weak consistency read, // or if they are executed against different leaders, // the ordering guarantee required to ensure no IP is allocated twice is violated. // ListServices must return a ResourceVersion higher than the etcd index Get triggers, // and the release code must not release services that have had IPs allocated but not yet been created // See #8295 // If etcd server is not running we should wait for some time and fail only then. This is particularly // important when we start apiserver and etcd at the same time. var latest *api.RangeAllocation var err error err = wait.PollImmediate(time.Second, 10*time.Second, func() (bool, error) { latest, err = c.alloc.Get() return err == nil, err }) if err != nil { return fmt.Errorf("unable to refresh the service IP block: %v", err) } ctx := api.WithNamespace(api.NewDefaultContext(), api.NamespaceAll) // We explicitly send no resource version, since the resource version // of 'latest' is from a different collection, it's not comparable to // the service collection. The caching layer keeps per-collection RVs, // and this is proper, since in theory the collections could be hosted // in separate etcd (or even non-etcd) instances. list, err := c.registry.ListServices(ctx, nil) if err != nil { return fmt.Errorf("unable to refresh the service IP block: %v", err) } r := ipallocator.NewCIDRRange(c.network) for _, svc := range list.Items { if !api.IsServiceIPSet(&svc) { continue } ip := net.ParseIP(svc.Spec.ClusterIP) if ip == nil { // cluster IP is broken, reallocate runtime.HandleError(fmt.Errorf("the cluster IP %s for service %s/%s is not a valid IP; please recreate", svc.Spec.ClusterIP, svc.Name, svc.Namespace)) continue } switch err := r.Allocate(ip); err { case nil: case ipallocator.ErrAllocated: // TODO: send event // cluster IP is broken, reallocate runtime.HandleError(fmt.Errorf("the cluster IP %s for service %s/%s was assigned to multiple services; please recreate", ip, svc.Name, svc.Namespace)) case ipallocator.ErrNotInRange: // TODO: send event // cluster IP is broken, reallocate runtime.HandleError(fmt.Errorf("the cluster IP %s for service %s/%s is not within the service CIDR %s; please recreate", ip, svc.Name, svc.Namespace, c.network)) case ipallocator.ErrFull: // TODO: send event return fmt.Errorf("the service CIDR %v is full; you must widen the CIDR in order to create new services", r) default: return fmt.Errorf("unable to allocate cluster IP %s for service %s/%s due to an unknown error, exiting: %v", ip, svc.Name, svc.Namespace, err) } } if err := r.Snapshot(latest); err != nil { return fmt.Errorf("unable to snapshot the updated service IP allocations: %v", err) } if err := c.alloc.CreateOrUpdate(latest); err != nil { if errors.IsConflict(err) { return err } return fmt.Errorf("unable to persist the updated service IP allocations: %v", err) } return nil }
apache-2.0
colindunn/homebrew-cask
Casks/comictagger.rb
511
cask 'comictagger' do version '1.1.16-beta-rc2' sha256 '3d2d883371a22074205ef96f98fdd0ccc35399f9439bc235b6f4c1c21e856bc5' url "https://github.com/davide-romanini/comictagger/releases/download/#{version}/ComicTagger-#{version}.dmg" appcast 'https://github.com/davide-romanini/comictagger/releases.atom', checkpoint: '6f8c330b4be724d22619da7536028e38c4a86d126fd636ce8e1bd64b3451beb0' name 'ComicTagger' homepage 'https://github.com/davide-romanini/comictagger' app 'ComicTagger.app' end
bsd-2-clause
redmunds/cdnjs
ajax/libs/froala-editor/2.3.3/js/languages/zh_tw.js
9202
/*! * froala_editor v2.3.3 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2016 Froala Labs */ /** * Traditional Chinese spoken in Taiwan. */ $.FE.LANGUAGE['zh_tw'] = { translation: { // Place holder "Type something": "\u8f38\u5165\u4e00\u4e9b\u5167\u5bb9", // Basic formatting "Bold": "\u7c97\u9ad4", "Italic": "\u659c\u9ad4", "Underline": "\u5e95\u7dda", "Strikethrough": "\u522a\u9664\u7dda", // Main buttons "Insert": "\u63d2\u5165", "Delete": "\u522a\u9664", "Cancel": "\u53d6\u6d88", "OK": "\u78ba\u5b9a", "Back": "\u5f8c", "Remove": "\u79fb\u9664", "More": "\u66f4\u591a", "Update": "\u66f4\u65b0", "Style": "\u6a23\u5f0f", // Font "Font Family": "\u5b57\u9ad4", "Font Size": "\u5b57\u578b\u5927\u5c0f", // Colors "Colors": "\u984f\u8272", "Background": "\u80cc\u666f", "Text": "\u6587\u5b57", // Paragraphs "Paragraph Format": "\u683c\u5f0f", "Normal": "\u6b63\u5e38", "Code": "\u7a0b\u5f0f\u78bc", "Heading 1": "\u6a19\u984c 1", "Heading 2": "\u6a19\u984c 2", "Heading 3": "\u6a19\u984c 3", "Heading 4": "\u6a19\u984c 4", // Style "Paragraph Style": "\u6bb5\u843d\u6a23\u5f0f", "Inline Style": "\u5167\u806f\u6a23\u5f0f", // Alignment "Align": "\u5c0d\u9f4a", "Align Left": "\u7f6e\u5de6\u5c0d\u9f4a", "Align Center": "\u7f6e\u4e2d\u5c0d\u9f4a", "Align Right": "\u7f6e\u53f3\u5c0d\u9f4a", "Align Justify": "\u5de6\u53f3\u5c0d\u9f4a", "None": "\u7121", // Lists "Ordered List": "\u6578\u5b57\u6e05\u55ae", "Unordered List": "\u9805\u76ee\u6e05\u55ae", // Indent "Decrease Indent": "\u6e1b\u5c11\u7e2e\u6392", "Increase Indent": "\u589e\u52a0\u7e2e\u6392", // Links "Insert Link": "\u63d2\u5165\u9023\u7d50", "Open in new tab": "\u5728\u65b0\u5206\u9801\u958b\u555f", "Open Link": "\u958b\u555f\u9023\u7d50", "Edit Link": "\u7de8\u8f2f\u9023\u7d50", "Unlink": "\u79fb\u9664\u9023\u7d50", "Choose Link": "\u9078\u64c7\u9023\u7d50", // Images "Insert Image": "\u63d2\u5165\u5716\u7247", "Upload Image": "\u4e0a\u50b3\u5716\u7247", "By URL": "\u7db2\u5740\u4e0a\u50b3", "Browse": "\u700f\u89bd", "Drop image": "\u5716\u7247\u62d6\u66f3", "or click": "\u6216\u9ede\u64ca", "Manage Images": "\u7ba1\u7406\u5716\u7247", "Loading": "\u8f09\u5165\u4e2d", "Deleting": "\u522a\u9664", "Tags": "\u6a19\u7c64", "Are you sure? Image will be deleted.": "\u78ba\u5b9a\u522a\u9664\u5716\u7247\uff1f", "Replace": "\u66f4\u63db", "Uploading": "\u4e0a\u50b3", "Loading image": "\u4e0a\u50b3\u4e2d", "Display": "\u986f\u793a", "Inline": "\u5d4c\u5165", "Break Text": "\u8207\u6587\u5b57\u5206\u96e2", "Alternate Text": "\u6587\u5b57\u74b0\u7e5e", "Change Size": "\u8abf\u6574\u5927\u5c0f", "Width": "\u5bec\u5ea6", "Height": "\u9ad8\u5ea6", "Something went wrong. Please try again.": "\u932f\u8aa4\uff0c\u8acb\u518d\u8a66\u4e00\u6b21\u3002", // Video "Insert Video": "\u63d2\u5165\u5f71\u7247", "Embedded Code": "\u5d4c\u5165\u7a0b\u5f0f\u78bc", // Tables "Insert Table": "\u63d2\u5165\u8868\u683c", "Table Header": "\u8868\u982d", "Remove Table": "\u522a\u9664\u8868", "Table Style": "\u8868\u6a23\u5f0f", "Horizontal Align": "\u6c34\u6e96\u5c0d\u9f4a\u65b9\u5f0f", "Row": "\u884c", "Insert row above": "\u5411\u4e0a\u63d2\u5165\u4e00\u884c", "Insert row below": "\u5411\u4e0b\u63d2\u5165\u4e00\u884c", "Delete row": "\u522a\u9664\u884c", "Column": "\u5217", "Insert column before": "\u5411\u5de6\u63d2\u5165\u4e00\u5217", "Insert column after": "\u5411\u53f3\u63d2\u5165\u4e00\u5217", "Delete column": "\u522a\u9664\u884c", "Cell": "\u5132\u5b58\u683c", "Merge cells": "\u5408\u4f75\u5132\u5b58\u683c", "Horizontal split": "\u6c34\u5e73\u5206\u5272", "Vertical split": "\u5782\u76f4\u5206\u5272", "Cell Background": "\u5132\u5b58\u683c\u80cc\u666f", "Vertical Align": "\u5782\u76f4\u5c0d\u9f4a\u65b9\u5f0f", "Top": "\u4e0a", "Middle": "\u4e2d", "Bottom": "\u4e0b", "Align Top": "\u5411\u4e0a\u5c0d\u9f4a", "Align Middle": "\u4e2d\u9593\u5c0d\u9f4a", "Align Bottom": "\u5e95\u90e8\u5c0d\u9f4a", "Cell Style": "\u5132\u5b58\u683c\u6a23\u5f0f", // Files "Upload File": "\u4e0a\u50b3\u6587\u4ef6", "Drop file": "\u6587\u4ef6\u62d6\u66f3", // Emoticons "Emoticons": "\u8868\u60c5", "Grinning face": "\u81c9\u4e0a\u7b11\u563b\u563b", "Grinning face with smiling eyes": "\u7b11\u563b\u563b\u7684\u81c9\uff0c\u542b\u7b11\u7684\u773c\u775b", "Face with tears of joy": "\u81c9\u4e0a\u5e36\u8457\u559c\u6085\u7684\u6dda\u6c34", "Smiling face with open mouth": "\u7b11\u81c9\u5f35\u958b\u5634", "Smiling face with open mouth and smiling eyes": "\u7b11\u81c9\u5f35\u958b\u5634\u5fae\u7b11\u7684\u773c\u775b", "Smiling face with open mouth and cold sweat": "\u7b11\u81c9\u5f35\u958b\u5634\uff0c\u4e00\u8eab\u51b7\u6c57", "Smiling face with open mouth and tightly-closed eyes": "\u7b11\u81c9\u5f35\u958b\u5634\uff0c\u7dca\u7dca\u9589\u8457\u773c\u775b", "Smiling face with halo": "\u7b11\u81c9\u6688", "Smiling face with horns": "\u5fae\u7b11\u7684\u81c9\u89d2", "Winking face": "\u7728\u773c\u8868\u60c5", "Smiling face with smiling eyes": "\u9762\u5e36\u5fae\u7b11\u7684\u773c\u775b", "Face savoring delicious food": "\u9762\u5c0d\u54c1\u5690\u7f8e\u5473\u7684\u98df\u7269", "Relieved face": "\u9762\u5c0d\u5982\u91cb\u91cd\u8ca0", "Smiling face with heart-shaped eyes": "\u5fae\u7b11\u7684\u81c9\uff0c\u5fc3\u81df\u5f62\u7684\u773c\u775b", "Smiling face with sunglasses": "\u7b11\u81c9\u592a\u967d\u93e1", "Smirking face": "\u9762\u5c0d\u9762\u5e36\u7b11\u5bb9", "Neutral face": "\u4e2d\u6027\u9762", "Expressionless face": "\u9762\u7121\u8868\u60c5", "Unamused face": "\u4e00\u81c9\u4e0d\u5feb\u7684\u81c9", "Face with cold sweat": "\u9762\u5c0d\u51b7\u6c57", "Pensive face": "\u6c89\u601d\u7684\u81c9", "Confused face": "\u9762\u5c0d\u56f0\u60d1", "Confounded face": "\u8a72\u6b7b\u7684\u81c9", "Kissing face": "\u9762\u5c0d\u63a5\u543b", "Face throwing a kiss": "\u9762\u5c0d\u6295\u64f2\u4e00\u500b\u543b", "Kissing face with smiling eyes": "\u63a5\u543b\u81c9\uff0c\u542b\u7b11\u7684\u773c\u775b", "Kissing face with closed eyes": "\u63a5\u543b\u7684\u81c9\u9589\u8457\u773c\u775b", "Face with stuck out tongue": "\u9762\u5c0d\u4f38\u51fa\u820c\u982d", "Face with stuck out tongue and winking eye": "\u9762\u5c0d\u4f38\u51fa\u820c\u982d\u548c\u7728\u52d5\u7684\u773c\u775b", "Face with stuck out tongue and tightly-closed eyes": "\u9762\u5c0d\u4f38\u51fa\u820c\u982d\u548c\u7dca\u9589\u7684\u773c\u775b", "Disappointed face": "\u9762\u5c0d\u5931\u671b", "Worried face": "\u9762\u5c0d\u64d4\u5fc3", "Angry face": "\u61a4\u6012\u7684\u81c9", "Pouting face": "\u9762\u5c0d\u5658\u5634", "Crying face": "\u54ed\u6ce3\u7684\u81c9", "Persevering face": "\u600e\u5948\u81c9", "Face with look of triumph": "\u9762\u5e36\u770b\u7684\u52dd\u5229", "Disappointed but relieved face": "\u5931\u671b\uff0c\u4f46\u81c9\u4e0a\u91cb\u7136", "Frowning face with open mouth": "\u9762\u5c0d\u76ba\u8457\u7709\u982d\u5f35\u53e3", "Anguished face": "\u9762\u5c0d\u75db\u82e6", "Fearful face": "\u53ef\u6015\u7684\u81c9", "Weary face": "\u9762\u5c0d\u53ad\u5026", "Sleepy face": "\u9762\u5c0d\u56f0", "Tired face": "\u75b2\u618a\u7684\u81c9", "Grimacing face": "\u7319\u7370\u7684\u81c9", "Loudly crying face": "\u5927\u8072\u54ed\u81c9", "Face with open mouth": "\u9762\u5c0d\u5f35\u958b\u5634", "Hushed face": "\u5b89\u975c\u7684\u81c9", "Face with open mouth and cold sweat": "\u9762\u5c0d\u5f35\u958b\u5634\uff0c\u4e00\u8eab\u51b7\u6c57", "Face screaming in fear": "\u9762\u5c0d\u5c16\u53eb\u5728\u6050\u61fc\u4e2d", "Astonished face": "\u9762\u5c0d\u9a5a\u8a1d", "Flushed face": "\u7d05\u64b2\u64b2\u7684\u81c9\u86cb", "Sleeping face": "\u719f\u7761\u7684\u81c9", "Dizzy face": "\u9762\u5c0d\u7729", "Face without mouth": "\u81c9\u4e0a\u6c92\u6709\u5634", "Face with medical mask": "\u9762\u5c0d\u91ab\u7642\u53e3\u7f69", // Line breaker "Break": "\u63db\u884c", // Math "Subscript": "\u4e0b\u6a19", "Superscript": "\u4e0a\u6a19", // Full screen "Fullscreen": "\u5168\u87a2\u5e55", // Horizontal line "Insert Horizontal Line": "\u63d2\u5165\u6c34\u5e73\u7dda", // Clear formatting "Clear Formatting": "\u6e05\u9664\u683c\u5f0f", // Undo, redo "Undo": "\u5fa9\u539f", "Redo": "\u53d6\u6d88\u5fa9\u539f", // Select all "Select All": "\u5168\u9078", // Code view "Code View": "\u539f\u59cb\u78bc", // Quote "Quote": "\u5f15\u6587", "Increase": "\u7e2e\u6392", "Decrease": "\u53bb\u9664\u7e2e\u6392", // Quick Insert "Quick Insert": "\u5feb\u63d2" }, direction: "ltr" };
mit
iains/darwin-gcc-5
libstdc++-v3/testsuite/25_algorithms/includes/check_type.cc
1220
// Copyright (C) 2005-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 25.3.5.1 [lib.includes] // { dg-do compile } #include <algorithm> #include <testsuite_iterators.h> using __gnu_test::input_iterator_wrapper; struct S { }; bool operator<(const S&, const S&) { return true; } struct X { }; bool predicate(const X&, const X&) { return true; } bool test1(input_iterator_wrapper<S>& s) { return std::includes(s, s, s, s); } bool test2(input_iterator_wrapper<X>& x) { return std::includes(x, x, x, x, predicate); }
gpl-2.0
liquuid/liquuidme
src/wp-content/plugins/wordpress-seo/cli/class-cli-redirect-upsell-command-namespace.php
296
<?php /** * WPSEO plugin file. * * @package WPSEO\CLI */ use WP_CLI\Dispatcher\CommandNamespace; /** * The redirect functionality is only available in Yoast SEO Premium. */ final class WPSEO_CLI_Redirect_Upsell_Command_Namespace extends CommandNamespace { // Intentionally left empty. }
gpl-3.0
ICML14MoMCompare/spectral-learn
code/tensor/cpp/include/boost/wave/util/cpp_macromap_predef.hpp
10013
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Definition of the predefined macros http://www.boost.org/ Copyright (c) 2001-2012 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(CPP_MACROMAP_PREDEF_HPP_HK041119) #define CPP_MACROMAP_PREDEF_HPP_HK041119 #include <cstdio> #include <boost/assert.hpp> #include <boost/wave/wave_config.hpp> #include <boost/wave/wave_config_constant.hpp> #include <boost/wave/token_ids.hpp> #include <boost/wave/util/time_conversion_helper.hpp> // time_conversion_helper // this must occur after all of the includes and before any code appears #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_PREFIX #endif /////////////////////////////////////////////////////////////////////////////// // // This file contains the definition of functions needed for the management // of static and dynamic predefined macros, such as __DATE__, __TIME__ etc. // // Note: __FILE__, __LINE__ and __INCLUDE_LEVEL__ are handled in the file // cpp_macromap.hpp. // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace wave { namespace util { /////////////////////////////////////////////////////////////////////////// class predefined_macros { typedef BOOST_WAVE_STRINGTYPE string_type; public: // list of static predefined macros struct static_macros { char const *name; boost::wave::token_id token_id; char const *value; }; // list of dynamic predefined macros struct dynamic_macros { char const *name; boost::wave::token_id token_id; string_type (predefined_macros:: *generator)() const; }; private: boost::wave::util::time_conversion_helper compilation_time_; string_type datestr_; // __DATE__ string_type timestr_; // __TIME__ string_type version_; // __SPIRIT_PP_VERSION__/__WAVE_VERSION__ string_type versionstr_; // __SPIRIT_PP_VERSION_STR__/__WAVE_VERSION_STR__ protected: void reset_datestr() { static const char *const monthnames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // for some systems sprintf, time_t etc. is in namespace std using namespace std; time_t tt = time(0); struct tm *tb = 0; if (tt != (time_t)-1) { char buffer[sizeof("\"Oct 11 1347\"")+1]; tb = localtime (&tt); sprintf (buffer, "\"%s %2d %4d\"", monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900); datestr_ = buffer; } else { datestr_ = "\"??? ?? ????\""; } } void reset_timestr() { // for some systems sprintf, time_t etc. is in namespace std using namespace std; time_t tt = time(0); struct tm *tb = 0; if (tt != (time_t)-1) { char buffer[sizeof("\"12:34:56\"")+1]; tb = localtime (&tt); sprintf (buffer, "\"%02d:%02d:%02d\"", tb->tm_hour, tb->tm_min, tb->tm_sec); timestr_ = buffer; } else { timestr_ = "\"??:??:??\""; } } void reset_version() { char buffer[sizeof("0x00000000")+1]; // for some systems sprintf, time_t etc. is in namespace std using namespace std; // calculate the number of days since Dec 13 2001 // (the day the Wave project was started) tm first_day; using namespace std; // for some systems memset is in namespace std memset (&first_day, 0, sizeof(tm)); first_day.tm_mon = 11; // Dec first_day.tm_mday = 13; // 13 first_day.tm_year = 101; // 2001 long seconds = long(difftime(compilation_time_.get_time(), mktime(&first_day))); sprintf(buffer, "0x%02d%1d%1d%04ld", BOOST_WAVE_VERSION_MAJOR, BOOST_WAVE_VERSION_MINOR, BOOST_WAVE_VERSION_SUBMINOR, seconds/(3600*24)); version_ = buffer; } void reset_versionstr() { char buffer[sizeof("\"00.00.00.0000 \"")+sizeof(BOOST_PLATFORM)+sizeof(BOOST_COMPILER)+4]; // for some systems sprintf, time_t etc. is in namespace std using namespace std; // calculate the number of days since Dec 13 2001 // (the day the Wave project was started) tm first_day; memset (&first_day, 0, sizeof(tm)); first_day.tm_mon = 11; // Dec first_day.tm_mday = 13; // 13 first_day.tm_year = 101; // 2001 long seconds = long(difftime(compilation_time_.get_time(), mktime(&first_day))); sprintf(buffer, "\"%d.%d.%d.%ld [%s/%s]\"", BOOST_WAVE_VERSION_MAJOR, BOOST_WAVE_VERSION_MINOR, BOOST_WAVE_VERSION_SUBMINOR, seconds/(3600*24), BOOST_PLATFORM, BOOST_COMPILER); versionstr_ = buffer; } // dynamic predefined macros string_type get_date() const { return datestr_; } // __DATE__ string_type get_time() const { return timestr_; } // __TIME__ // __SPIRIT_PP__/__WAVE__ string_type get_version() const { char buffer[sizeof("0x0000")+1]; using namespace std; // for some systems sprintf is in namespace std sprintf(buffer, "0x%02d%1d%1d", BOOST_WAVE_VERSION_MAJOR, BOOST_WAVE_VERSION_MINOR, BOOST_WAVE_VERSION_SUBMINOR); return buffer; } // __WAVE_CONFIG__ string_type get_config() const { char buffer[sizeof("0x00000000")+1]; using namespace std; // for some systems sprintf is in namespace std sprintf(buffer, "0x%08x", BOOST_WAVE_CONFIG); return buffer; } public: predefined_macros() : compilation_time_(__DATE__ " " __TIME__) { reset(); reset_version(); reset_versionstr(); } void reset() { reset_datestr(); reset_timestr(); } // __SPIRIT_PP_VERSION__/__WAVE_VERSION__ string_type get_fullversion() const { return version_; } // __SPIRIT_PP_VERSION_STR__/__WAVE_VERSION_STR__ string_type get_versionstr() const { return versionstr_; } // C++ mode static_macros const& static_data_cpp(std::size_t i) const { static static_macros data[] = { { "__STDC__", T_INTLIT, "1" }, { "__cplusplus", T_INTLIT, "199711L" }, { 0, T_EOF, 0 } }; BOOST_ASSERT(i < sizeof(data)/sizeof(data[0])); return data[i]; } #if BOOST_WAVE_SUPPORT_CPP0X != 0 // C++11 mode static_macros const& static_data_cpp0x(std::size_t i) const { static static_macros data[] = { { "__STDC__", T_INTLIT, "1" }, { "__cplusplus", T_INTLIT, "201103L" }, { "__STDC_VERSION__", T_INTLIT, "199901L" }, { "__STDC_HOSTED__", T_INTLIT, "0" }, { "__WAVE_HAS_VARIADICS__", T_INTLIT, "1" }, { 0, T_EOF, 0 } }; BOOST_ASSERT(i < sizeof(data)/sizeof(data[0])); return data[i]; } #endif #if BOOST_WAVE_SUPPORT_VARIADICS_PLACEMARKERS != 0 // C99 mode static_macros const& static_data_c99(std::size_t i) const { static static_macros data[] = { { "__STDC__", T_INTLIT, "1" }, { "__STDC_VERSION__", T_INTLIT, "199901L" }, { "__STDC_HOSTED__", T_INTLIT, "0" }, { "__WAVE_HAS_VARIADICS__", T_INTLIT, "1" }, { 0, T_EOF, 0 } }; BOOST_ASSERT(i < sizeof(data)/sizeof(data[0])); return data[i]; } #endif dynamic_macros const& dynamic_data(std::size_t i) const { static dynamic_macros data[] = { { "__DATE__", T_STRINGLIT, &predefined_macros::get_date }, { "__TIME__", T_STRINGLIT, &predefined_macros::get_time }, { "__SPIRIT_PP__", T_INTLIT, &predefined_macros::get_version }, { "__SPIRIT_PP_VERSION__", T_INTLIT, &predefined_macros::get_fullversion }, { "__SPIRIT_PP_VERSION_STR__", T_STRINGLIT, &predefined_macros::get_versionstr }, { "__WAVE__", T_INTLIT, &predefined_macros::get_version }, { "__WAVE_VERSION__", T_INTLIT, &predefined_macros::get_fullversion }, { "__WAVE_VERSION_STR__", T_STRINGLIT, &predefined_macros::get_versionstr }, { "__WAVE_CONFIG__", T_INTLIT, &predefined_macros::get_config }, { 0, T_EOF, 0 } }; BOOST_ASSERT(i < sizeof(data)/sizeof(data[0])); return data[i]; } }; // predefined_macros /////////////////////////////////////////////////////////////////////////////// } // namespace util } // namespace wave } // namespace boost // the suffix header occurs after all of the code #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // !defined(CPP_MACROMAP_PREDEF_HPP_HK041119)
apache-2.0
wout/cdnjs
ajax/libs/unibox/1.2.0/js/unibox.js
10171
(function($) { $.fn.unibox = function(options) { var searchBox = this; // settings with default options. var settings = $.extend({ // these are the defaults. suggestUrl: '', queryVisualizationHeadline: '', highlight: true, throttleTime: 300, animationSpeed: 300, instantVisualFeedback: 'all', enterCallback: undefined, minChars: 3, maxWidth: searchBox.outerWidth() }, options); UniBox.init(searchBox, settings); return this; }; }(jQuery)); var UniBox = function() { //// common vars // div line height // index of selected entry var selectedEntryIndex = -1; // the search box var searchBox; // the suggest box var suggestBox; // the URL where to get the search suggests var suggestUrl = ''; // the number of ms before the update of the search box is triggered var throttleTime; // the list of all selectable divs var selectables = []; // whether the search words should be highlighted in the results var highlight = true; // general animation speed var animationSpeed = 300; // the headline of the query visualization var queryVisualizationHeadline = ''; // the minimum input before the suggest pops up var minChars = 2; // the action that should happen if enter is pressed var enterCallback; // the words that were highlighted above the search bar var ivfWords = []; // where to show the ivf var instantVisualFeedback = 'all'; // hide the search suggests function hideSuggestBox(event) { if (event !== undefined) { var inputText = searchBox.val(); // hide if tab or enter was pressed if (event.keyCode == 9 || event.keyCode == 13 || inputText.length < minChars) { suggestBox.slideUp(animationSpeed); selectedEntryIndex = -1; } } else { suggestBox.slideUp(animationSpeed); selectedEntryIndex = -1; } } function throttle(f, delay){ var timer = null; return function(){ var context = this, args = arguments; clearTimeout(timer); timer = window.setTimeout(function(){ f.apply(context, args); }, delay || 500); }; } // highlight search words function highlightSearchWords(string, searchString) { if (!highlight) { return string; } var words = searchString.split(' '); var markers = {}; $.each(words, function(key, word) { if (word.length < 2) { return; } //string = string.replace(new RegExp(word,'gi'),'<span>'+word+'</span>'); string = string.replace(new RegExp(word,'gi'),'##'+key+'##'); markers['##'+key+'##'] = '<span>'+word+'</span>'; }); $.each(markers, function(marker, replacement) { string = string.replace(new RegExp(marker,'gi'),replacement); }); return string; } // update suggest box when new data is given function updateSuggestBox(data){ //data = JSON.parse(data); //console.log(data); var searchString = searchBox.val(); //// fill the box suggestBox.html(''); // suggest $.each(data['suggests'], function(key, values) { //console.log('key: ' + key); if (key.replace(/_/,'').length > 0 && values.length > 0) { var keyNode = $('<h4>'+key+'</h4>'); suggestBox.append(keyNode); } $.each(values, function(index, suggest) { //console.log(suggest); var suggestLine = '<div class="unibox-selectable">'; if (suggest['image'] != undefined) { suggestLine += '<img src="'+suggest['image']+'"/>'; } if (suggest['link'] != undefined) { suggestLine += '<a href="'+suggest['link']+'">'; suggestLine += highlightSearchWords(suggest['name'],searchString); suggestLine += '</a>'; } else { suggestLine += highlightSearchWords(suggest['name'],searchString); } suggestLine += '<div class="unibox-ca"></div></div>'; var suggestNode = $(suggestLine); suggestBox.append(suggestNode); }); }); // click handler on selectables $('.unibox-selectable').click(function() { searchBox.val($(this).text()); enterCallback($(this).text()); hideSuggestBox(); }); // trigger words / visualization if (data['words'].length > 0 && queryVisualizationHeadline.length > 0 && (instantVisualFeedback == 'all' || instantVisualFeedback == 'bottom')) { suggestBox.append('<h4>'+queryVisualizationHeadline+'</h4>'); } $.each(data['words'], function(key, word) { //console.log(word); //console.log(ivfWords); if ((instantVisualFeedback == 'all' || instantVisualFeedback == 'bottom')) { if (word['overlayImage'] != undefined) { suggestBox.append('<img class="unibox-vis" src="'+word['overlayImage'] +'" style="background-image: url(\''+word['image']+'\');background-size: 75%;background-repeat: no-repeat;background-position: center;">'); } else { suggestBox.append('<img class="unibox-vis" src="'+word['image']+'">'); } } var invisibleBox = $('#unibox-invisible'); invisibleBox.html(searchString.replace(new RegExp(word['name'],'gi'),'<span>'+word['name']+'</span>')); // show visuals above search bar if ((instantVisualFeedback == 'all' || instantVisualFeedback == 'top') && jQuery.inArray(word['image'], ivfWords) == -1) { var span = $('#unibox-invisible span'); if (span != undefined && word['name'].length > 0) { var posLeft = $('#unibox-invisible span').position().left; console.log(posLeft); visImage = $('<div class="unibox-ivf"><img src="'+word['image']+'" alt="'+word['name']+'"></div>'); visImage.css('left', searchBox.offset().left + posLeft - 10); visImage.css('top', searchBox.offset().top - 80); $('body').append(visImage); setTimeout(function() {$('.unibox-ivf').find('img').addClass('l'); }, 10); } //visImage.find('img').addClass('l'); ivfWords.push(word['image']); } }); $("img").error(function () { $(this).hide(); }); //// position it suggestBox.css('left',searchBox.offset().left); suggestBox.css('top',searchBox.offset().top+searchBox.outerHeight()); //// show it suggestBox.slideDown(animationSpeed, function() { //// re-position it (in some cases the slide down moves the search box and the suggest box is not aligned anymore) suggestBox.css('left',searchBox.offset().left); suggestBox.css('top',searchBox.offset().top+searchBox.outerHeight()); }); //// update selectables for cursor navigation selectables = $('.unibox-selectable'); selectedEntryIndex = -1; } function clearIvf() { ivfWords = []; $('.unibox-ivf').remove(); } function scrollList(event) { if (searchBox.val().length <= 1) { clearIvf(); } // return if NOT up or down is pressed if (event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 13) { if (event.keyCode == 46 || event.keyCode == 8) { clearIvf(); } return; } // if up or down arrows are pressed move selected entry if (event.keyCode == 38 && selectedEntryIndex > 0) { selectedEntryIndex--; } else if (event.keyCode == 40) { selectedEntryIndex++; } // mark the selected selectable if (selectables.length > 0) { selectedEntryIndex = selectedEntryIndex % selectables.length; selectables.removeClass('active'); var selected = $(selectables[selectedEntryIndex]); selected.addClass('active'); } if (event.keyCode == 13) { if (enterCallback != undefined) { var selectedText = searchBox.val(); if (selectedEntryIndex != -1) { selectedText = $($('.unibox-selectable.active')[0]).text(); } enterCallback(selectedText); } else if (selectedEntryIndex != -1) { window.location.href = $($('.unibox-selectable.active')[0]).find('a').attr('href'); } return false; } } // provide search suggests function searchSuggest(event) { // scroll list when up or down is pressed if (event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 13) { return; } var inputText = searchBox.val(); if (inputText.length >= minChars) { $.ajax(suggestUrl+encodeURIComponent(inputText),{dataType:'json', success: function(data) { updateSuggestBox(data); }}); } } // return an object, through closure all methods keep bound to returned object return { init: function(searchBoxObject, options) { searchBox = searchBoxObject; highlight = options.highlight; suggestUrl = options.suggestUrl; throttleTime = options.throttleTime; animationSpeed = options.animationSpeed; minChars = options.minChars; enterCallback = options.enterCallback; instantVisualFeedback = options.instantVisualFeedback; queryVisualizationHeadline = options.queryVisualizationHeadline; // insert necessary values for inputfield searchBox.attr("autocomplete", "off"); // position and size the suggest box suggestBox = $('<div id="unibox-suggest-box"></div>'); $('body').append(suggestBox); suggestBox.css('min-width', searchBox.outerWidth()); suggestBox.css('max-width', options.maxWidth); // add event listeners searchBox.keydown(scrollList); searchBox.keydown(throttle(searchSuggest,throttleTime)); searchBox.keydown(hideSuggestBox); searchBox.keyup(hideSuggestBox); // click outside of suggest div closes it $('html').click(function() { suggestBox.slideUp(animationSpeed); }); suggestBox.click(function(event){ event.stopPropagation(); }); // copy search box styles to an invisible element so we can determine the text width var invisible = $('<div id="unibox-invisible">text whatever <span>this one</span></div>'); searchBox.parent().append(invisible); console.log('unibox initialized'); } } }();
mit
sufuf3/cdnjs
ajax/libs/ng-quill/1.4.2/ng-quill.js
25806
/*global Quill*/ (function () { 'use strict'; var app; // declare ngQuill module app = angular.module('ngQuill', []); app.provider('ngQuillConfig', function () { var config = { // default fontFamilies fontSizes: [{ size: '10px', alias: 'small' }, { size: '13px', alias: 'normal' }, { size: '18px', alias: 'large' }, { size: '32px', alias: 'huge' }], // default fontFamilies fontFamilies: [{ label: 'Sans Serif', alias: 'sans-serif' }, { label: 'Serif', alias: 'serif' }, { label: 'Monospace', alias: 'monospace' }], // formats list formats: [ 'link', 'image', 'bold', 'italic', 'underline', 'strike', 'color', 'background', 'align', 'font', 'size', 'bullet', 'list' ], // default translations translations: { font: 'Font', size: 'Size', small: 'Small', normal: 'Normal', large: 'Large', huge: 'Huge', bold: 'Bold', italic: 'Italic', underline: 'Underline', strike: 'Strikethrough', textColor: 'Text Color', backgroundColor: 'Background Color', list: 'List', bullet: 'Bullet', textAlign: 'Text Align', left: 'Left', center: 'Center', right: 'Right', justify: 'Justify', link: 'Link', image: 'Image', visitURL: 'Visit URL', change: 'Change', done: 'Done', cancel: 'Cancel', remove: 'Remove', insert: 'Insert', preview: 'Preview' } }; this.set = function (fontSizes, fontFamilies) { if (fontSizes) { config.fontSizes = fontSizes; } if (fontFamilies) { config.fontFamilies = fontFamilies; } }; this.$get = function () { return config; }; }); app.service('ngQuillService', ['ngQuillConfig', function (ngQuillConfig) { // validate formats this.validateFormats = function (checkFormats) { var correctFormats = [], i = 0; for (i; i < checkFormats.length; i = i + 1) { if (ngQuillConfig.formats.indexOf(checkFormats[i]) !== -1) { correctFormats.push(checkFormats[i]); } } return correctFormats; }; }]); app.directive('ngQuillEditor', [ '$timeout', 'ngQuillService', 'ngQuillConfig', function ($timeout, ngQuillService, ngQuillConfig) { return { scope: { 'toolbarEntries': '@?', 'toolbar': '@?', 'showToolbar': '=?', 'fontfamilyOptions': '=?', 'fontsizeOptions': '=?', 'linkTooltip': '@?', 'imageTooltip': '@?', 'theme': '@?', 'save': '@?', 'translations': '=?', 'required': '@?editorRequired', 'readOnly': '&?', 'errorClass': '@?', 'ngModel': '=', 'callback': '&?', 'name': '@?', 'editorStyles': '=?' }, require: 'ngModel', restrict: 'E', templateUrl: 'ngQuill/template.html', link: function ($scope, element, attr, ngModel) { var config = { theme: $scope.theme || 'snow', save: $scope.save || 'html', readOnly: $scope.readOnly || false, formats: $scope.toolbarEntries ? ngQuillService.validateFormats($scope.toolbarEntries.split(' ')) : ngQuillConfig.formats, modules: {}, styles: $scope.editorStyles || false }, changed = false, editor, setClass = function () { // if editor content length <= 1 and content is required -> add custom error clas and ng-invalid if ($scope.required && (!$scope.modelLength || $scope.modelLength <= 1)) { element.addClass('ng-invalid'); element.removeClass('ng-valid'); // if form was reseted and input field set to empty if ($scope.errorClass && changed && element.hasClass('ng-dirty')) { element.children().addClass($scope.errorClass); } } else { // set to valid element.removeClass('ng-invalid'); element.addClass('ng-valid'); if ($scope.errorClass) { element.children().removeClass($scope.errorClass); } } }; // set required flag (if text editor is required) if ($scope.required && $scope.required === 'true') { $scope.required = true; } else { $scope.required = false; } // overwrite global settings dynamically $scope.fontsizeOptions = $scope.fontsizeOptions || ngQuillConfig.fontSizes; $scope.fontfamilyOptions = $scope.fontfamilyOptions || ngQuillConfig.fontFamilies; // default translations $scope.dict = ngQuillConfig.translations; $scope.shouldShow = function (formats) { var okay = false, i = 0; for (i; i < formats.length; i = i + 1) { if (config.formats.indexOf(formats[i]) !== -1) { okay = true; break; } } return okay; }; // if there are custom translations if ($scope.translations) { $scope.dict = $scope.translations; } // add tooltip modules if ($scope.linkTooltip && $scope.linkTooltip === 'true') { config.modules['link-tooltip'] = { template: '<span class="title">' + $scope.dict.visitURL + ':&nbsp;</span>' + '<a href="#" class="url" target="_blank" href="about:blank"></a>' + '<input class="input" type="text">' + '<span>&nbsp;&#45;&nbsp;</span>' + '<a href="javascript:;" class="change">' + $scope.dict.change + '</a>' + '<a href="javascript:;" class="remove">' + $scope.dict.remove + '</a>' + '<a href="javascript:;" class="done">' + $scope.dict.done + '</a>' }; } if ($scope.imageTooltip && $scope.imageTooltip === 'true') { config.modules['image-tooltip'] = { template: '<input class="input" type="textbox">' + '<div class="preview">' + ' <span>' + $scope.dict.preview + '</span>' + '</div>' + '<a href="javascript:;" class="cancel">' + $scope.dict.cancel + '</a>' + '<a href="javascript:;" class="insert">' + $scope.dict.insert + '</a>' }; } // init editor editor = new Quill(element[0].querySelector('.advanced-wrapper .editor-container'), config); // add toolbar afterwards with a timeout to be sure that translations has replaced. if ($scope.toolbar && $scope.toolbar === 'true') { $timeout(function () { editor.addModule('toolbar', { container: element[0].querySelector('.advanced-wrapper .toolbar-container') }); $scope.toolbarCreated = true; $scope.showToolbar = $scope.hasOwnProperty('showToolbar') ? $scope.showToolbar : true; }, 0); } // provide event to get recognized when editor is created -> pass editor object. $timeout(function(){ $scope.$emit('editorCreated', editor, $scope.name); if ($scope.callback) { $scope.callback({ editor: editor, name: $scope.name }); } // clear history of undo manager to avoid removing inital model value via ctrl + z editor.getModule('undo-manager').clear(); }); var updateFromPlugin = false; var updateInPlugin = false; // set initial value $scope.$watch(function () { return $scope.ngModel; }, function (newText) { if (updateFromPlugin) { return; } if (newText !== undefined) { updateInPlugin = true; if (config.save === 'text') { editor.setText(newText); } else if (config.save === 'contents') { editor.setContents(newText); } else { editor.setHTML(newText); } } }); // toggle readOnly if ($scope.readOnly) { $scope.$watch(function () { return $scope.readOnly(); }, function (readOnly) { editor.editor[readOnly ? 'disable' : 'enable'](); }); } $scope.regEx = /^([2-9]|[1-9][0-9]+)$/; // Update model on textchange editor.on('text-change', function () { var oldChange = changed; changed = true; updateFromPlugin = true; if (!updateInPlugin) { $scope.$apply(function () { // Calculate content length $scope.modelLength = editor.getLength(); // Check if error class should be set if (oldChange) { setClass(); } var setValue; if (config.save === 'text') { setValue = editor.getText(); } else if (config.save === 'contents') { setValue = editor.getContents(); } else { setValue = editor.getHTML(); } // Set new model value ngModel.$setViewValue(setValue); }); } updateInPlugin = false; updateFromPlugin = false; }); // Clean-up element.on('$destroy', function () { editor.destroy(); }); } }; } ]); app.run([ '$templateCache', '$rootScope', '$window', function ($templateCache) { // put template in template cache return $templateCache.put('ngQuill/template.html', '<div id="content-container">' + '<div class="advanced-wrapper">' + '<div class="toolbar toolbar-container" ng-if="toolbar" ng-show="toolbarCreated && showToolbar">' + '<span class="ql-format-group" ng-if="shouldShow([\'font\', \'size\'])">' + '<select title="{{dict.font}}" class="ql-font" ng-if="shouldShow([\'font\'])">' + '<option ng-repeat="option in fontfamilyOptions" value="{{option.alias}}">{{option.label}}</option>' + '</select>' + '<select title="{{dict.size}}" class="ql-size" ng-if="shouldShow([\'size\'])">' + '<option ng-repeat="option in fontsizeOptions" ng-selected="$index === 1" value="{{option.size}}">{{dict[option.alias] || option.alias}}</option>' + '</select>' + '</span>' + '<span class="ql-format-group" ng-if="shouldShow([\'bold\', \'italic\', \'underline\', \'strike\'])">' + '<span title="{{dict.bold}}" class="ql-format-button ql-bold" ng-if="shouldShow([\'bold\'])"></span>' + '<span title="{{dict.italic}}" class="ql-format-button ql-italic" ng-if="shouldShow([\'italic\'])"></span>' + '<span title="{{dict.underline}}" class="ql-format-button ql-underline" ng-if="shouldShow([\'underline\'])"></span>' + '<span title="{{dict.strike}}" class="ql-format-button ql-strike" ng-if="shouldShow([\'strike\'])"></span>' + '</span>' + '<span class="ql-format-group" ng-if="shouldShow([\'color\', \'background\'])">' + '<select title="{{dict.textColor}}" class="ql-color" ng-if="shouldShow([\'color\'])">' + '<option value="rgb(0, 0, 0)" label="rgb(0, 0, 0)" selected=""></option>' + '<option value="rgb(230, 0, 0)" label="rgb(230, 0, 0)"></option>' + '<option value="rgb(255, 153, 0)" label="rgb(255, 153, 0)"></option>' + '<option value="rgb(255, 255, 0)" label="rgb(255, 255, 0)"></option>' + '<option value="rgb(0, 138, 0)" label="rgb(0, 138, 0)"></option>' + '<option value="rgb(0, 102, 204)" label="rgb(0, 102, 204)"></option>' + '<option value="rgb(153, 51, 255)" label="rgb(153, 51, 255)"></option>' + '<option value="rgb(255, 255, 255)" label="rgb(255, 255, 255)"></option>' + '<option value="rgb(250, 204, 204)" label="rgb(250, 204, 204)"></option>' + '<option value="rgb(255, 235, 204)" label="rgb(255, 235, 204)"></option>' + '<option value="rgb(255, 255, 204)" label="rgb(255, 255, 204)"></option>' + '<option value="rgb(204, 232, 204)" label="rgb(204, 232, 204)"></option>' + '<option value="rgb(204, 224, 245)" label="rgb(204, 224, 245)"></option>' + '<option value="rgb(235, 214, 255)" label="rgb(235, 214, 255)"></option>' + '<option value="rgb(187, 187, 187)" label="rgb(187, 187, 187)"></option>' + '<option value="rgb(240, 102, 102)" label="rgb(240, 102, 102)"></option>' + '<option value="rgb(255, 194, 102)" label="rgb(255, 194, 102)"></option>' + '<option value="rgb(255, 255, 102)" label="rgb(255, 255, 102)"></option>' + '<option value="rgb(102, 185, 102)" label="rgb(102, 185, 102)"></option>' + '<option value="rgb(102, 163, 224)" label="rgb(102, 163, 224)"></option>' + '<option value="rgb(194, 133, 255)" label="rgb(194, 133, 255)"></option>' + '<option value="rgb(136, 136, 136)" label="rgb(136, 136, 136)"></option>' + '<option value="rgb(161, 0, 0)" label="rgb(161, 0, 0)"></option>' + '<option value="rgb(178, 107, 0)" label="rgb(178, 107, 0)"></option>' + '<option value="rgb(178, 178, 0)" label="rgb(178, 178, 0)"></option>' + '<option value="rgb(0, 97, 0)" label="rgb(0, 97, 0)"></option>' + '<option value="rgb(0, 71, 178)" label="rgb(0, 71, 178)"></option>' + '<option value="rgb(107, 36, 178)" label="rgb(107, 36, 178)"></option>' + '<option value="rgb(68, 68, 68)" label="rgb(68, 68, 68)"></option>' + '<option value="rgb(92, 0, 0)" label="rgb(92, 0, 0)"></option>' + '<option value="rgb(102, 61, 0)" label="rgb(102, 61, 0)"></option>' + '<option value="rgb(102, 102, 0)" label="rgb(102, 102, 0)"></option>' + '<option value="rgb(0, 55, 0)" label="rgb(0, 55, 0)"></option>' + '<option value="rgb(0, 41, 102)" label="rgb(0, 41, 102)"></option>' + '<option value="rgb(61, 20, 102)" label="rgb(61, 20, 102)"></option>' + '</select>' + '<select title="{{dict.backgroundColor}}" class="ql-background" ng-if="shouldShow([\'background\'])">' + '<option value="rgb(0, 0, 0)" label="rgb(0, 0, 0)"></option>' + '<option value="rgb(230, 0, 0)" label="rgb(230, 0, 0)"></option>' + '<option value="rgb(255, 153, 0)" label="rgb(255, 153, 0)"></option>' + '<option value="rgb(255, 255, 0)" label="rgb(255, 255, 0)"></option>' + '<option value="rgb(0, 138, 0)" label="rgb(0, 138, 0)"></option>' + '<option value="rgb(0, 102, 204)" label="rgb(0, 102, 204)"></option>' + '<option value="rgb(153, 51, 255)" label="rgb(153, 51, 255)"></option>' + '<option value="rgb(255, 255, 255)" label="rgb(255, 255, 255)" selected=""></option>' + '<option value="rgb(250, 204, 204)" label="rgb(250, 204, 204)"></option>' + '<option value="rgb(255, 235, 204)" label="rgb(255, 235, 204)"></option>' + '<option value="rgb(255, 255, 204)" label="rgb(255, 255, 204)"></option>' + '<option value="rgb(204, 232, 204)" label="rgb(204, 232, 204)"></option>' + '<option value="rgb(204, 224, 245)" label="rgb(204, 224, 245)"></option>' + '<option value="rgb(235, 214, 255)" label="rgb(235, 214, 255)"></option>' + '<option value="rgb(187, 187, 187)" label="rgb(187, 187, 187)"></option>' + '<option value="rgb(240, 102, 102)" label="rgb(240, 102, 102)"></option>' + '<option value="rgb(255, 194, 102)" label="rgb(255, 194, 102)"></option>' + '<option value="rgb(255, 255, 102)" label="rgb(255, 255, 102)"></option>' + '<option value="rgb(102, 185, 102)" label="rgb(102, 185, 102)"></option>' + '<option value="rgb(102, 163, 224)" label="rgb(102, 163, 224)"></option>' + '<option value="rgb(194, 133, 255)" label="rgb(194, 133, 255)"></option>' + '<option value="rgb(136, 136, 136)" label="rgb(136, 136, 136)"></option>' + '<option value="rgb(161, 0, 0)" label="rgb(161, 0, 0)"></option>' + '<option value="rgb(178, 107, 0)" label="rgb(178, 107, 0)"></option>' + '<option value="rgb(178, 178, 0)" label="rgb(178, 178, 0)"></option>' + '<option value="rgb(0, 97, 0)" label="rgb(0, 97, 0)"></option>' + '<option value="rgb(0, 71, 178)" label="rgb(0, 71, 178)"></option>' + '<option value="rgb(107, 36, 178)" label="rgb(107, 36, 178)"></option>' + '<option value="rgb(68, 68, 68)" label="rgb(68, 68, 68)"></option>' + '<option value="rgb(92, 0, 0)" label="rgb(92, 0, 0)"></option>' + '<option value="rgb(102, 61, 0)" label="rgb(102, 61, 0)"></option>' + '<option value="rgb(102, 102, 0)" label="rgb(102, 102, 0)"></option>' + '<option value="rgb(0, 55, 0)" label="rgb(0, 55, 0)"></option>' + '<option value="rgb(0, 41, 102)" label="rgb(0, 41, 102)"></option>' + '<option value="rgb(61, 20, 102)" label="rgb(61, 20, 102)"></option>' + '</select>' + '</span>' + '<span class="ql-format-group" ng-if="shouldShow([\'list\', \'bullet\'])">' + '<span title="{{dict.list}}" class="ql-format-button ql-list" ng-if="shouldShow([\'list\'])"></span>' + '<span title="{{dict.bullet}}" class="ql-format-button ql-bullet" ng-if="shouldShow([\'bullet\'])"></span>' + '</span>' + '<span class="ql-format-group" ng-if="shouldShow([\'align\'])">' + '<select title="{{dict.textAlign}}" class="ql-align">' + '<option value="left" label="{{dict.left}}" selected=""></option>' + '<option value="center" label="{{dict.center}}"></option>' + '<option value="right" label="{{dict.right}}"></option>' + '<option value="justify" label="{{dict.justify}}"></option>' + '</select>' + '</span>' + '<span class="ql-format-group" ng-if="shouldShow([\'link\', \'image\'])">' + '<span title="{{dict.link}}" class="ql-format-button ql-link" ng-if="shouldShow([\'link\'])"></span>' + '<span title="{{dict.image}}" class="ql-format-button ql-image" ng-if="shouldShow([\'image\'])"></span>' + '</span>' + '</div>' + '<div class="editor-container"></div>' + '<input type="text" ng-model="modelLength" ng-if="required" ng-hide="true" ng-pattern="/^([2-9]|[1-9][0-9]+)$/">' + '</div>' + '</div>'); } ]); }).call(this);
mit
cdnjs/cdnjs
ajax/libs/simple-icons/5.17.0/codeberg.min.js
514
module.exports={title:"Codeberg",slug:"codeberg",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Codeberg</title><path d="M11.955.49A12 12 0 0 0 0 12.49a12 12 0 0 0 1.832 6.373L11.838 5.928a.187.14 0 0 1 .324 0l10.006 12.935A12 12 0 0 0 24 12.49a12 12 0 0 0-12-12 12 12 0 0 0-.045 0zm.375 6.467l4.416 16.553a12 12 0 0 0 5.137-4.213z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://codeberg.org",hex:"2185D0",guidelines:void 0,license:void 0};
mit
damien-dg/horizon
openstack_dashboard/dashboards/project/firewalls/urls.py
2378
# Copyright 2013, Big Switch Networks, Inc. # # 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. from django.conf.urls import patterns from django.conf.urls import url from openstack_dashboard.dashboards.project.firewalls import views urlpatterns = patterns( 'openstack_dashboard.dashboards.project.firewalls.views', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^addrule$', views.AddRuleView.as_view(), name='addrule'), url(r'^addpolicy$', views.AddPolicyView.as_view(), name='addpolicy'), url(r'^addfirewall/(?P<policy_id>[^/]+)/$', views.AddFirewallView.as_view(), name='addfirewall'), url(r'^addfirewall$', views.AddFirewallView.as_view(), name='addfirewall'), url(r'^insertrule/(?P<policy_id>[^/]+)/$', views.InsertRuleToPolicyView.as_view(), name='insertrule'), url(r'^removerule/(?P<policy_id>[^/]+)/$', views.RemoveRuleFromPolicyView.as_view(), name='removerule'), url(r'^updaterule/(?P<rule_id>[^/]+)/$', views.UpdateRuleView.as_view(), name='updaterule'), url(r'^updatepolicy/(?P<policy_id>[^/]+)/$', views.UpdatePolicyView.as_view(), name='updatepolicy'), url(r'^updatefirewall/(?P<firewall_id>[^/]+)/$', views.UpdateFirewallView.as_view(), name='updatefirewall'), url(r'^rule/(?P<rule_id>[^/]+)/$', views.RuleDetailsView.as_view(), name='ruledetails'), url(r'^policy/(?P<policy_id>[^/]+)/$', views.PolicyDetailsView.as_view(), name='policydetails'), url(r'^addrouter/(?P<firewall_id>[^/]+)/$', views.AddRouterToFirewallView.as_view(), name='addrouter'), url(r'^removerouter/(?P<firewall_id>[^/]+)/$', views.RemoveRouterFromFirewallView.as_view(), name='removerouter'), url(r'^firewall/(?P<firewall_id>[^/]+)/$', views.FirewallDetailsView.as_view(), name='firewalldetails'))
apache-2.0
RupomAhsan/rupstartJS
node_modules/cssstyle/lib/properties/webkitTransition.js
266
'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-transition', v); }, get: function () { return this.getPropertyValue('-webkit-transition'); }, enumerable: true, configurable: true };
mit
iwdmb/cdnjs
ajax/libs/twix.js/0.1.7/twix.js
10039
// Generated by CoffeeScript 1.3.3 (function() { var Twix, extend, moment; if (typeof module !== "undefined") { moment = require('moment'); } else { moment = this.moment; } if (typeof moment === "undefined") { throw "Can't find moment"; } Twix = (function() { function Twix(start, end, allDay) { this.start = moment(start); this.end = moment(end); this.allDay = allDay || false; } Twix.prototype.sameDay = function() { return this.start.year() === this.end.year() && this.start.month() === this.end.month() && this.start.date() === this.end.date(); }; Twix.prototype.sameYear = function() { return this.start.year() === this.end.year(); }; Twix.prototype.countDays = function() { var endDate, startDate; startDate = this.start.clone().startOf("day"); endDate = this.end.clone().startOf("day"); return endDate.diff(startDate, 'days') + 1; }; Twix.prototype.daysIn = function(minHours) { var endDate, hasNext, iter, _this = this; iter = this.start.clone().startOf("day"); endDate = this.end.clone().startOf("day"); hasNext = function() { return iter <= endDate && (!minHours || iter.valueOf() !== endDate.valueOf() || _this.end.hours() > minHours || _this.allDay); }; return { next: function() { var val; if (!hasNext()) { return null; } else { val = iter.clone(); iter.add('days', 1); return val; } }, hasNext: hasNext }; }; Twix.prototype.duration = function() { if (this.allDay) { if (this.sameDay()) { return "all day"; } else { return this.start.from(this.end.clone().add('days', 1), true); } } else { return this.start.from(this.end, true); } }; Twix.prototype.past = function() { if (this.allDay) { return this.end.clone().endOf("day") < moment(); } else { return this.end < moment(); } }; Twix.prototype.overlaps = function(other) { return !(this._trueEnd() < other._trueStart() || this._trueStart() > other._trueEnd()); }; Twix.prototype.engulfs = function(other) { return this._trueStart() <= other._trueStart() && this._trueEnd() >= other._trueEnd(); }; Twix.prototype.merge = function(other) { var allDay, newEnd, newStart; allDay = this.allDay && other.allDay; if (allDay) { newStart = this.start < other.start ? this.start : other.start; newEnd = this.end > other.end ? this.end : other.end; } else { newStart = this._trueStart() < other._trueStart() ? this._trueStart() : other._trueStart(); newEnd = this._trueEnd() > other._trueEnd() ? this._trueEnd() : other._trueEnd(); } return new Twix(newStart, newEnd, allDay); }; Twix.prototype._trueStart = function() { if (this.allDay) { return this.start.clone().startOf("day"); } else { return this.start; } }; Twix.prototype._trueEnd = function() { if (this.allDay) { return this.end.clone().endOf("day"); } else { return this.end; } }; Twix.prototype.equals = function(other) { return (other instanceof Twix) && this.allDay === other.allDay && this.start.valueOf() === other.start.valueOf() && this.end.valueOf() === other.end.valueOf(); }; Twix.prototype.format = function(inopts) { var common_bucket, end_bucket, fold, format, fs, global_first, goesIntoTheMorning, needDate, options, process, start_bucket, together, _i, _len, _this = this; options = { groupMeridiems: true, spaceBeforeMeridiem: true, showDate: true, showDayOfWeek: false, twentyFourHour: false, implicitMinutes: true, yearFormat: "YYYY", monthFormat: "MMM", weekdayFormat: "ddd", dayFormat: "D", meridiemFormat: "A", hourFormat: "h", minuteFormat: "mm", allDay: "all day", explicitAllDay: false, lastNightEndsAt: 0 }; extend(options, inopts || {}); fs = []; if (options.twentyFourHour) { options.hourFormat = options.hourFormat.replace("h", "H"); } goesIntoTheMorning = options.lastNightEndsAt > 0 && !this.allDay && this.end.clone().startOf('day').valueOf() === this.start.clone().add('days', 1).startOf("day").valueOf() && this.start.hours() > 12 && this.end.hours() < options.lastNightEndsAt; needDate = options.showDate || (!this.sameDay() && !goesIntoTheMorning); if (this.allDay && this.sameDay() && (!options.showDate || options.explicitAllDay)) { fs.push({ name: "all day simple", fn: function() { return options.allDay; }, slot: 0, pre: " " }); } if (needDate && (this.start.year() !== moment().year() || !this.sameYear())) { fs.push({ name: "year", fn: function(date) { return date.format(options.yearFormat); }, pre: ", ", slot: 4 }); } if (!this.allDay && needDate) { fs.push({ name: "all day month", fn: function(date) { return date.format("" + options.monthFormat + " " + options.dayFormat); }, ignoreEnd: function() { return goesIntoTheMorning; }, slot: 2, pre: " " }); } if (this.allDay && needDate) { fs.push({ name: "month", fn: function(date) { return date.format("MMM"); }, slot: 2, pre: " " }); } if (this.allDay && needDate) { fs.push({ name: "date", fn: function(date) { return date.format(options.dayFormat); }, slot: 3, pre: " " }); } if (needDate && options.showDayOfWeek) { fs.push({ name: "day of week", fn: function(date) { return date.format(options.weekdayFormat); }, pre: " ", slot: 1 }); } if (options.groupMeridiems && !options.twentyFourHour && !this.allDay) { fs.push({ name: "meridiem", fn: function(t) { return t.format(options.meridiemFormat); }, slot: 6, pre: options.spaceBeforeMeridiem ? " " : "" }); } if (!this.allDay) { fs.push({ name: "time", fn: function(date) { var str; str = date.minutes() === 0 && options.implicitMinutes && !options.twentyFourHour ? date.format(options.hourFormat) : date.format("" + options.hourFormat + ":" + options.minuteFormat); if (!options.groupMeridiems && !options.twentyFourHour) { if (options.spaceBeforeMeridiem) { str += " "; } str += date.format(options.meridiemFormat); } return str; }, pre: ", ", slot: 5 }); } start_bucket = []; end_bucket = []; common_bucket = []; together = true; process = function(format) { var end_str, start_group, start_str; start_str = format.fn(_this.start); end_str = format.ignoreEnd && format.ignoreEnd() ? start_str : format.fn(_this.end); start_group = { format: format, value: function() { return start_str; } }; if (end_str === start_str && together) { return common_bucket.push(start_group); } else { if (together) { together = false; common_bucket.push({ format: { slot: format.slot, pre: "" }, value: function() { return "" + (fold(start_bucket)) + " -" + (fold(end_bucket, true)); } }); } start_bucket.push(start_group); return end_bucket.push({ format: format, value: function() { return end_str; } }); } }; for (_i = 0, _len = fs.length; _i < _len; _i++) { format = fs[_i]; process(format); } global_first = true; fold = function(array, skip_pre) { var local_first, section, str, _j, _len1, _ref; local_first = true; str = ""; _ref = array.sort(function(a, b) { return a.format.slot - b.format.slot; }); for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { section = _ref[_j]; if (!global_first) { if (local_first && skip_pre) { str += " "; } else { str += section.format.pre; } } str += section.value(); global_first = false; local_first = false; } return str; }; return fold(common_bucket); }; return Twix; })(); extend = function(first, second) { var attr, _results; _results = []; for (attr in second) { if (typeof second[attr] !== "undefined") { _results.push(first[attr] = second[attr]); } else { _results.push(void 0); } } return _results; }; if (typeof module !== "undefined") { module.exports = Twix; } else { window.Twix = Twix; } moment.twix = function() { return (function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args), t = typeof result; return t == "object" || t == "function" ? result || child : child; })(Twix, arguments, function(){}); }; }).call(this);
mit
NapkinBrasil/napkinapp.com.br
node_modules/babel-generator/lib/generators/jsx.js
2493
"use strict"; var _getIterator = require("babel-runtime/core-js/get-iterator")["default"]; exports.__esModule = true; exports.JSXAttribute = JSXAttribute; exports.JSXIdentifier = JSXIdentifier; exports.JSXNamespacedName = JSXNamespacedName; exports.JSXMemberExpression = JSXMemberExpression; exports.JSXSpreadAttribute = JSXSpreadAttribute; exports.JSXExpressionContainer = JSXExpressionContainer; exports.JSXText = JSXText; exports.JSXElement = JSXElement; exports.JSXOpeningElement = JSXOpeningElement; exports.JSXClosingElement = JSXClosingElement; exports.JSXEmptyExpression = JSXEmptyExpression; function JSXAttribute(node /*: Object*/) { this.print(node.name, node); if (node.value) { this.push("="); this.print(node.value, node); } } function JSXIdentifier(node /*: Object*/) { this.push(node.name); } function JSXNamespacedName(node /*: Object*/) { this.print(node.namespace, node); this.push(":"); this.print(node.name, node); } function JSXMemberExpression(node /*: Object*/) { this.print(node.object, node); this.push("."); this.print(node.property, node); } function JSXSpreadAttribute(node /*: Object*/) { this.push("{..."); this.print(node.argument, node); this.push("}"); } function JSXExpressionContainer(node /*: Object*/) { this.push("{"); this.print(node.expression, node); this.push("}"); } function JSXText(node /*: Object*/) { this.push(node.value, true); } function JSXElement(node /*: Object*/) { var open = node.openingElement; this.print(open, node); if (open.selfClosing) return; this.indent(); for (var _iterator = (node.children /*: Array<Object>*/), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var child = _ref; this.print(child, node); } this.dedent(); this.print(node.closingElement, node); } function JSXOpeningElement(node /*: Object*/) { this.push("<"); this.print(node.name, node); if (node.attributes.length > 0) { this.push(" "); this.printJoin(node.attributes, node, { separator: " " }); } this.push(node.selfClosing ? " />" : ">"); } function JSXClosingElement(node /*: Object*/) { this.push("</"); this.print(node.name, node); this.push(">"); } function JSXEmptyExpression() {}
mit
vbauerster/react-starter-kit
src/decorators/withStyles.js
2130
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes } from 'react'; // eslint-disable-line no-unused-vars import invariant from '../../node_modules/react/lib/invariant'; import { canUseDOM } from '../../node_modules/react/lib/ExecutionEnvironment'; let count = 0; function withStyles(styles) { return (ComposedComponent) => class WithStyles { static contextTypes = { onInsertCss: PropTypes.func }; constructor() { this.refCount = 0; ComposedComponent.prototype.renderCss = function (css) { let style; if (canUseDOM) { if (this.styleId && (style = document.getElementById(this.styleId))) { if ('textContent' in style) { style.textContent = css; } else { style.styleSheet.cssText = css; } } else { this.styleId = `dynamic-css-${count++}`; style = document.createElement('style'); style.setAttribute('id', this.styleId); style.setAttribute('type', 'text/css'); if ('textContent' in style) { style.textContent = css; } else { style.styleSheet.cssText = css; } document.getElementsByTagName('head')[0].appendChild(style); this.refCount++; } } else { this.context.onInsertCss(css); } }.bind(this); } componentWillMount() { if (canUseDOM) { invariant(styles.use, `The style-loader must be configured with reference-counted API.`); styles.use(); } else { this.context.onInsertCss(styles.toString()); } } componentWillUnmount() { styles.unuse(); if (this.styleId) { this.refCount--; if (this.refCount < 1) { let style = document.getElementById(this.styleId); if (style) { style.parentNode.removeChild(style); } } } } render() { return <ComposedComponent {...this.props} />; } }; } export default withStyles;
mit
joeljacobson/ghost
node_modules/knex/lib/builder.js
16114
// Builder // ------- (function(define) { "use strict"; // The `Builder` is the interface for constructing a regular // `select`, `insert`, `update`, or `delete` query, as well // as some aggregate helpers. define(function(require, exports) { var _ = require('lodash'); var Raw = require('./raw').Raw; var Common = require('./common').Common; var Helpers = require('./helpers').Helpers; var JoinClause = require('./builder/joinclause').JoinClause; var array = []; var push = array.push; // Constructor for the builder instance, typically called from // `knex.builder`, accepting the current `knex` instance, // and pulling out the `client` and `grammar` from the current // knex instance. var Builder = function(knex) { this.knex = knex; this.client = knex.client; this.grammar = knex.grammar; this.reset(); _.bindAll(this, 'handleResponse'); }; // All operators used in the `where` clause generation. var operators = ['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike']; // Valid values for the `order by` clause generation. var orderBys = ['asc', 'desc']; _.extend(Builder.prototype, Common, { _source: 'Builder', // Sets the `tableName` on the query. from: function(tableName) { if (!tableName) return this.table; this.table = tableName; return this; }, // Alias to from, for "insert" statements // e.g. builder.insert({a: value}).into('tableName') into: function(tableName) { this.table = tableName; return this; }, // Adds a column or columns to the list of "columns" // being selected on the query. column: function(columns) { if (columns) { push.apply(this.columns, _.isArray(columns) ? columns : _.toArray(arguments)); } return this; }, // Adds a `distinct` clause to the query. distinct: function(column) { this.column(column); this.flags.distinct = true; return this; }, // Clones the current query builder, including any // pieces that have been set thus far. clone: function() { var item = new Builder(this.knex); item.table = this.table; var items = [ 'aggregates', 'type', 'joins', 'wheres', 'orders', 'columns', 'values', 'bindings', 'grammar', 'groups', 'transaction', 'unions', 'flags', 'havings' ]; for (var i = 0, l = items.length; i < l; i++) { var k = items[i]; item[k] = this[k]; } return item; }, // Resets all attributes on the query builder. reset: function() { this.aggregates = []; this.bindings = []; this.columns = []; this.flags = {}; this.havings = []; this.joins = []; this.orders = []; this.unions = []; this.values = []; this.wheres = []; }, // Adds a join clause to the query, allowing for advanced joins // with an anonymous function as the second argument. join: function(table, first, operator, second, type) { var join; if (_.isFunction(first)) { type = operator; join = new JoinClause(type || 'inner', table); first.call(join, join); } else { join = new JoinClause(type || 'inner', table); join.on(first, operator, second); } this.joins.push(join); return this; }, // The where function can be used in several ways: // The most basic is `where(key, value)`, which expands to // where key = value. where: function(column, operator, value) { var bool = this._boolFlag || 'and'; this._boolFlag = 'and'; // Check if the column is a function, in which case it's // a grouped where statement (wrapped in parens). if (_.isFunction(column)) { return this._whereNested(column, bool); } // Allow a raw statement to be passed along to the query. if (column instanceof Raw) { return this.whereRaw(column.sql, column.bindings, bool); } // Allows `where({id: 2})` syntax. if (_.isObject(column)) { for (var key in column) { value = column[key]; this[bool + 'Where'](key, '=', value); } return this; } // Enable the where('key', value) syntax, only when there // are explicitly two arguments passed, so it's not possible to // do where('key', '!=') and have that turn into where key != null if (arguments.length === 2) { value = operator; operator = '='; } // If the value is null, and the operator is equals, assume that we're // going for a `whereNull` statement here. if (value == null && operator === '=') { return this.whereNull(column, bool); } // If the value is a function, assume it's for building a sub-select. if (_.isFunction(value)) { return this._whereSub(column, operator, value, bool); } this.wheres.push({ type: 'Basic', column: column, operator: operator, value: value, bool: bool }); this.bindings.push(value); return this; }, // Alias to `where`, for internal builder consistency. andWhere: function(column, operator, value) { return this.where.apply(this, arguments); }, // Adds an `or where` clause to the query. orWhere: function(column, operator, value) { this._boolFlag = 'or'; return this.where.apply(this, arguments); }, // Adds a raw `where` clause to the query. whereRaw: function(sql, bindings, bool) { bindings = _.isArray(bindings) ? bindings : (bindings ? [bindings] : []); this.wheres.push({type: 'Raw', sql: sql, bool: bool || 'and'}); push.apply(this.bindings, bindings); return this; }, // Adds a raw `or where` clause to the query. orWhereRaw: function(sql, bindings) { return this.whereRaw(sql, bindings, 'or'); }, // Adds a `where exists` clause to the query. whereExists: function(callback, bool, type) { var query = new Builder(this.knex); callback.call(query, query); this.wheres.push({ type: (type || 'Exists'), query: query, bool: (bool || 'and') }); push.apply(this.bindings, query.bindings); return this; }, // Adds an `or where exists` clause to the query. orWhereExists: function(callback) { return this.whereExists(callback, 'or'); }, // Adds a `where not exists` clause to the query. whereNotExists: function(callback) { return this.whereExists(callback, 'and', 'NotExists'); }, // Adds a `or where not exists` clause to the query. orWhereNotExists: function(callback) { return this.whereExists(callback, 'or', 'NotExists'); }, // Adds a `where in` clause to the query. whereIn: function(column, values, bool, condition) { bool || (bool = 'and'); if (_.isFunction(values)) { return this._whereInSub(column, values, bool, (condition || 'In')); } this.wheres.push({ type: (condition || 'In'), column: column, value: values, bool: bool }); push.apply(this.bindings, values); return this; }, // Adds a `or where in` clause to the query. orWhereIn: function(column, values) { return this.whereIn(column, values, 'or'); }, // Adds a `where not in` clause to the query. whereNotIn: function(column, values) { return this.whereIn(column, values, 'and', 'NotIn'); }, // Adds a `or where not in` clause to the query. orWhereNotIn: function(column, values) { return this.whereIn(column, values, 'or', 'NotIn'); }, // Adds a `where null` clause to the query. whereNull: function(column, bool, type) { this.wheres.push({type: (type || 'Null'), column: column, bool: (bool || 'and')}); return this; }, // Adds a `or where null` clause to the query. orWhereNull: function(column) { return this.whereNull(column, 'or', 'Null'); }, // Adds a `where not null` clause to the query. whereNotNull: function(column) { return this.whereNull(column, 'and', 'NotNull'); }, // Adds a `or where not null` clause to the query. orWhereNotNull: function(column) { return this.whereNull(column, 'or', 'NotNull'); }, // Adds a `where between` clause to the query. whereBetween: function(column, values) { this.wheres.push({column: column, type: 'Between', bool: 'and'}); push.apply(this.bindings, values); return this; }, // Adds a `or where between` clause to the query. orWhereBetween: function(column, values) { this.wheres.push({column: column, type: 'Between', bool: 'or'}); push.apply(this.bindings, values); return this; }, // Adds a `group by` clause to the query. groupBy: function() { this.groups = (this.groups || []).concat(_.toArray(arguments)); return this; }, // Adds a `order by` clause to the query. orderBy: function(column, direction) { if (!(direction instanceof Raw)) { if (!_.contains(orderBys, (direction || '').toLowerCase())) direction = 'asc'; } this.orders.push({column: column, direction: direction}); return this; }, // Add a union statement to the query. union: function(callback) { this._union(callback, false); return this; }, // Adds a union all statement to the query. unionAll: function(callback) { this._union(callback, true); return this; }, // Adds a `having` clause to the query. having: function(column, operator, value, bool) { if (column instanceof Raw) { return this.havingRaw(column.sql, column.bindings, bool); } this.havings.push({column: column, operator: (operator || ''), value: (value || ''), bool: bool || 'and'}); this.bindings.push(value); return this; }, // Adds an `or having` clause to the query. orHaving: function(column, operator, value) { return this.having(column, operator, value, 'or'); }, // Adds a raw `having` clause to the query. havingRaw: function(sql, bindings, bool) { bindings = _.isArray(bindings) ? bindings : (bindings ? [bindings] : []); this.havings.push({type: 'Raw', sql: sql, bool: bool || 'and'}); push.apply(this.bindings, bindings); return this; }, // Adds a raw `or having` clause to the query. orHavingRaw: function(sql, bindings) { return this.havingRaw(sql, bindings, 'or'); }, offset: function(value) { if (value == null) return this.flags.offset; this.flags.offset = value; return this; }, limit: function(value) { if (value == null) return this.flags.limit; this.flags.limit = value; return this; }, // Retrieve the "count" result of the query. count: function(column) { return this._aggregate('count', column); }, // Retrieve the minimum value of a given column. min: function(column) { return this._aggregate('min', column); }, // Retrieve the maximum value of a given column. max: function(column) { return this._aggregate('max', column); }, // Retrieve the sum of the values of a given column. sum: function(column) { return this._aggregate('sum', column); }, // Increments a column's value by the specified amount. increment: function(column, amount) { return this._counter(column, amount); }, // Decrements a column's value by the specified amount. decrement: function(column, amount) { return this._counter(column, amount, '-'); }, // Sets the values for a `select` query. select: function(columns) { if (columns) { push.apply(this.columns, _.isArray(columns) ? columns : _.toArray(arguments)); } return this._setType('select'); }, // Sets the values for an `insert` query. insert: function(values, returning) { if (returning) this.returning(returning); this.values = this.prepValues(_.clone(values)); return this._setType('insert'); }, // Sets the returning value for the query. returning: function(returning) { this.flags.returning = returning; return this; }, // Sets the values for an `update` query. update: function(values) { var obj = Helpers.sortObject(values); var bindings = []; for (var i = 0, l = obj.length; i < l; i++) { bindings[i] = obj[i][1]; } this.bindings = bindings.concat(this.bindings || []); this.values = obj; return this._setType('update'); }, // Alias to del. "delete": function() { return this._setType('delete'); }, // Executes a delete statement on the query; del: function() { return this._setType('delete'); }, option: function(opts) { this.opts = _.extend(this.opts, opts); return this; }, // Truncate truncate: function() { return this._setType('truncate'); }, // Set by `transacting` - contains the object with the connection // needed to execute a transaction transaction: false, // Preps the values for `insert` or `update`. prepValues: function(values) { if (!_.isArray(values)) values = values ? [values] : []; for (var i = 0, l = values.length; i<l; i++) { var obj = values[i] = Helpers.sortObject(values[i]); for (var i2 = 0, l2 = obj.length; i2 < l2; i2++) { this.bindings.push(obj[i2][1]); } } return values; }, // ---------------------------------------------------------------------- // Helper for compiling any advanced `where in` queries. _whereInSub: function(column, callback, bool, condition) { condition += 'Sub'; var query = new Builder(this.knex); callback.call(query, query); this.wheres.push({type: condition, column: column, query: query, bool: bool}); push.apply(this.bindings, query.bindings); return this; }, // Helper for compiling any advanced `where` queries. _whereNested: function(callback, bool) { var query = new Builder(this.knex); callback.call(query, query); this.wheres.push({type: 'Nested', query: query, bool: bool}); push.apply(this.bindings, query.bindings); return this; }, // Helper for compiling any of the `where` advanced queries. _whereSub: function(column, operator, callback, bool) { var query = new Builder(this.knex); callback.call(query, query); this.wheres.push({ type: 'Sub', column: column, operator: operator, query: query, bool: bool }); push.apply(this.bindings, query.bindings); return this; }, // Helper for compiling any aggregate queries. _aggregate: function(type, columns) { this.aggregates.push({type: type, columns: columns}); this.type && this.type === 'select' || this._setType('select'); return this; }, // Helper for the incrementing/decrementing queries. _counter: function(column, amount, symbol) { amount = parseInt(amount, 10); if (isNaN(amount)) amount = 1; var toUpdate = {}; toUpdate[column] = this.knex.raw(this.grammar.wrap(column) + ' ' + (symbol || '+') + ' ' + amount); return this.update(toUpdate); }, // Helper for compiling any `union` queries. _union: function(callback, bool) { var query = new Builder(this.knex); callback.call(query, query); this.unions.push({query: query, all: bool}); push.apply(this.bindings, query.bindings); } }); exports.Builder = Builder; }); })( typeof define === 'function' && define.amd ? define : function (factory) { factory(require, exports); } );
mit
shakamunyi/kubernetes
pkg/apis/extensions/v1beta1/types.go
55261
/* Copyright 2015 The Kubernetes Authors. 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. */ package v1beta1 import ( "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/api/v1" appsv1beta1 "k8s.io/kubernetes/pkg/apis/apps/v1beta1" ) // describes the attributes of a scale subresource type ScaleSpec struct { // desired number of instances for the scaled object. // +optional Replicas int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` } // represents the current status of a scale subresource. type ScaleStatus struct { // actual number of observed instances of the scaled object. Replicas int32 `json:"replicas" protobuf:"varint,1,opt,name=replicas"` // label query over pods that should match the replicas count. More info: http://kubernetes.io/docs/user-guide/labels#label-selectors // +optional Selector map[string]string `json:"selector,omitempty" protobuf:"bytes,2,rep,name=selector"` // label selector for pods that should match the replicas count. This is a serializated // version of both map-based and more expressive set-based selectors. This is done to // avoid introspection in the clients. The string will be in the same format as the // query-param syntax. If the target type only supports map-based selectors, both this // field and map-based selector field are populated. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors // +optional TargetSelector string `json:"targetSelector,omitempty" protobuf:"bytes,3,opt,name=targetSelector"` } // +genclient=true // +noMethods=true // represents a scaling request for a resource. type Scale struct { metav1.TypeMeta `json:",inline"` // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. // +optional Spec ScaleSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // current status of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. Read-only. // +optional Status ScaleStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // Dummy definition type ReplicationControllerDummy struct { metav1.TypeMeta `json:",inline"` } // Alpha-level support for Custom Metrics in HPA (as annotations). type CustomMetricTarget struct { // Custom Metric name. Name string `json:"name" protobuf:"bytes,1,opt,name=name"` // Custom Metric value (average). TargetValue resource.Quantity `json:"value" protobuf:"bytes,2,opt,name=value"` } type CustomMetricTargetList struct { Items []CustomMetricTarget `json:"items" protobuf:"bytes,1,rep,name=items"` } type CustomMetricCurrentStatus struct { // Custom Metric name. Name string `json:"name" protobuf:"bytes,1,opt,name=name"` // Custom Metric value (average). CurrentValue resource.Quantity `json:"value" protobuf:"bytes,2,opt,name=value"` } type CustomMetricCurrentStatusList struct { Items []CustomMetricCurrentStatus `json:"items" protobuf:"bytes,1,rep,name=items"` } // +genclient=true // +nonNamespaced=true // A ThirdPartyResource is a generic representation of a resource, it is used by add-ons and plugins to add new resource // types to the API. It consists of one or more Versions of the api. type ThirdPartyResource struct { metav1.TypeMeta `json:",inline"` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Description is the description of this object. // +optional Description string `json:"description,omitempty" protobuf:"bytes,2,opt,name=description"` // Versions are versions for this third party object // +optional Versions []APIVersion `json:"versions,omitempty" protobuf:"bytes,3,rep,name=versions"` } // ThirdPartyResourceList is a list of ThirdPartyResources. type ThirdPartyResourceList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of ThirdPartyResources. Items []ThirdPartyResource `json:"items" protobuf:"bytes,2,rep,name=items"` } // An APIVersion represents a single concrete version of an object model. type APIVersion struct { // Name of this version (e.g. 'v1'). // +optional Name string `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"` } // An internal object, used for versioned storage in etcd. Not exposed to the end user. type ThirdPartyResourceData struct { metav1.TypeMeta `json:",inline"` // Standard object metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Data is the raw JSON data for this data. // +optional Data []byte `json:"data,omitempty" protobuf:"bytes,2,opt,name=data"` } // +genclient=true // Deployment enables declarative updates for Pods and ReplicaSets. type Deployment struct { metav1.TypeMeta `json:",inline"` // Standard object metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the Deployment. // +optional Spec DeploymentSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the Deployment. // +optional Status DeploymentStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // DeploymentSpec is the specification of the desired behavior of the Deployment. type DeploymentSpec struct { // Number of desired pods. This is a pointer to distinguish between explicit // zero and not specified. Defaults to 1. // +optional Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` // Label selector for pods. Existing ReplicaSets whose pods are // selected by this will be the ones affected by this deployment. // +optional Selector *metav1.LabelSelector `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` // Template describes the pods that will be created. Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"` // The deployment strategy to use to replace existing pods with new ones. // +optional Strategy DeploymentStrategy `json:"strategy,omitempty" protobuf:"bytes,4,opt,name=strategy"` // Minimum number of seconds for which a newly created pod should be ready // without any of its container crashing, for it to be considered available. // Defaults to 0 (pod will be considered available as soon as it is ready) // +optional MinReadySeconds int32 `json:"minReadySeconds,omitempty" protobuf:"varint,5,opt,name=minReadySeconds"` // The number of old ReplicaSets to retain to allow rollback. // This is a pointer to distinguish between explicit zero and not specified. // +optional RevisionHistoryLimit *int32 `json:"revisionHistoryLimit,omitempty" protobuf:"varint,6,opt,name=revisionHistoryLimit"` // Indicates that the deployment is paused and will not be processed by the // deployment controller. // +optional Paused bool `json:"paused,omitempty" protobuf:"varint,7,opt,name=paused"` // The config this deployment is rolling back to. Will be cleared after rollback is done. // +optional RollbackTo *RollbackConfig `json:"rollbackTo,omitempty" protobuf:"bytes,8,opt,name=rollbackTo"` // The maximum time in seconds for a deployment to make progress before it // is considered to be failed. The deployment controller will continue to // process failed deployments and a condition with a ProgressDeadlineExceeded // reason will be surfaced in the deployment status. Once autoRollback is // implemented, the deployment controller will automatically rollback failed // deployments. Note that progress will not be estimated during the time a // deployment is paused. This is not set by default. ProgressDeadlineSeconds *int32 `json:"progressDeadlineSeconds,omitempty" protobuf:"varint,9,opt,name=progressDeadlineSeconds"` } // DeploymentRollback stores the information required to rollback a deployment. type DeploymentRollback struct { metav1.TypeMeta `json:",inline"` // Required: This must match the Name of a deployment. Name string `json:"name" protobuf:"bytes,1,opt,name=name"` // The annotations to be updated to a deployment // +optional UpdatedAnnotations map[string]string `json:"updatedAnnotations,omitempty" protobuf:"bytes,2,rep,name=updatedAnnotations"` // The config of this deployment rollback. RollbackTo RollbackConfig `json:"rollbackTo" protobuf:"bytes,3,opt,name=rollbackTo"` } type RollbackConfig struct { // The revision to rollback to. If set to 0, rollback to the last revision. // +optional Revision int64 `json:"revision,omitempty" protobuf:"varint,1,opt,name=revision"` } const ( // DefaultDeploymentUniqueLabelKey is the default key of the selector that is added // to existing RCs (and label key that is added to its pods) to prevent the existing RCs // to select new pods (and old pods being select by new RC). DefaultDeploymentUniqueLabelKey string = "pod-template-hash" ) // DeploymentStrategy describes how to replace existing pods with new ones. type DeploymentStrategy struct { // Type of deployment. Can be "Recreate" or "RollingUpdate". Default is RollingUpdate. // +optional Type DeploymentStrategyType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type,casttype=DeploymentStrategyType"` // Rolling update config params. Present only if DeploymentStrategyType = // RollingUpdate. //--- // TODO: Update this to follow our convention for oneOf, whatever we decide it // to be. // +optional RollingUpdate *RollingUpdateDeployment `json:"rollingUpdate,omitempty" protobuf:"bytes,2,opt,name=rollingUpdate"` } type DeploymentStrategyType string const ( // Kill all existing pods before creating new ones. RecreateDeploymentStrategyType DeploymentStrategyType = "Recreate" // Replace the old RCs by new one using rolling update i.e gradually scale down the old RCs and scale up the new one. RollingUpdateDeploymentStrategyType DeploymentStrategyType = "RollingUpdate" ) // Spec to control the desired behavior of rolling update. type RollingUpdateDeployment struct { // The maximum number of pods that can be unavailable during the update. // Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). // Absolute number is calculated from percentage by rounding down. // This can not be 0 if MaxSurge is 0. // By default, a fixed value of 1 is used. // Example: when this is set to 30%, the old RC can be scaled down to 70% of desired pods // immediately when the rolling update starts. Once new pods are ready, old RC // can be scaled down further, followed by scaling up the new RC, ensuring // that the total number of pods available at all times during the update is at // least 70% of desired pods. // +optional MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty" protobuf:"bytes,1,opt,name=maxUnavailable"` // The maximum number of pods that can be scheduled above the desired number of // pods. // Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). // This can not be 0 if MaxUnavailable is 0. // Absolute number is calculated from percentage by rounding up. // By default, a value of 1 is used. // Example: when this is set to 30%, the new RC can be scaled up immediately when // the rolling update starts, such that the total number of old and new pods do not exceed // 130% of desired pods. Once old pods have been killed, // new RC can be scaled up further, ensuring that total number of pods running // at any time during the update is atmost 130% of desired pods. // +optional MaxSurge *intstr.IntOrString `json:"maxSurge,omitempty" protobuf:"bytes,2,opt,name=maxSurge"` } // DeploymentStatus is the most recently observed status of the Deployment. type DeploymentStatus struct { // The generation observed by the deployment controller. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty" protobuf:"varint,1,opt,name=observedGeneration"` // Total number of non-terminated pods targeted by this deployment (their labels match the selector). // +optional Replicas int32 `json:"replicas,omitempty" protobuf:"varint,2,opt,name=replicas"` // Total number of non-terminated pods targeted by this deployment that have the desired template spec. // +optional UpdatedReplicas int32 `json:"updatedReplicas,omitempty" protobuf:"varint,3,opt,name=updatedReplicas"` // Total number of ready pods targeted by this deployment. // +optional ReadyReplicas int32 `json:"readyReplicas,omitempty" protobuf:"varint,7,opt,name=readyReplicas"` // Total number of available pods (ready for at least minReadySeconds) targeted by this deployment. // +optional AvailableReplicas int32 `json:"availableReplicas,omitempty" protobuf:"varint,4,opt,name=availableReplicas"` // Total number of unavailable pods targeted by this deployment. // +optional UnavailableReplicas int32 `json:"unavailableReplicas,omitempty" protobuf:"varint,5,opt,name=unavailableReplicas"` // Represents the latest available observations of a deployment's current state. // +patchMergeKey=type // +patchStrategy=merge Conditions []DeploymentCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,6,rep,name=conditions"` // Count of hash collisions for the Deployment. The Deployment controller uses this // field as a collision avoidance mechanism when it needs to create the name for the // newest ReplicaSet. // +optional CollisionCount *int64 `json:"collisionCount,omitempty" protobuf:"varint,8,opt,name=collisionCount"` } type DeploymentConditionType string // These are valid conditions of a deployment. const ( // Available means the deployment is available, ie. at least the minimum available // replicas required are up and running for at least minReadySeconds. DeploymentAvailable DeploymentConditionType = "Available" // Progressing means the deployment is progressing. Progress for a deployment is // considered when a new replica set is created or adopted, and when new pods scale // up or old pods scale down. Progress is not estimated for paused deployments or // when progressDeadlineSeconds is not specified. DeploymentProgressing DeploymentConditionType = "Progressing" // ReplicaFailure is added in a deployment when one of its pods fails to be created // or deleted. DeploymentReplicaFailure DeploymentConditionType = "ReplicaFailure" ) // DeploymentCondition describes the state of a deployment at a certain point. type DeploymentCondition struct { // Type of deployment condition. Type DeploymentConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=DeploymentConditionType"` // Status of the condition, one of True, False, Unknown. Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/kubernetes/pkg/api/v1.ConditionStatus"` // The last time this condition was updated. LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty" protobuf:"bytes,6,opt,name=lastUpdateTime"` // Last time the condition transitioned from one status to another. LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,7,opt,name=lastTransitionTime"` // The reason for the condition's last transition. Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // A human readable message indicating details about the transition. Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } // DeploymentList is a list of Deployments. type DeploymentList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of Deployments. Items []Deployment `json:"items" protobuf:"bytes,2,rep,name=items"` } type DaemonSetUpdateStrategy struct { // Type of daemon set update. Can be "RollingUpdate" or "OnDelete". // Default is OnDelete. // +optional Type DaemonSetUpdateStrategyType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // Rolling update config params. Present only if type = "RollingUpdate". //--- // TODO: Update this to follow our convention for oneOf, whatever we decide it // to be. Same as Deployment `strategy.rollingUpdate`. // See https://github.com/kubernetes/kubernetes/issues/35345 // +optional RollingUpdate *RollingUpdateDaemonSet `json:"rollingUpdate,omitempty" protobuf:"bytes,2,opt,name=rollingUpdate"` } type DaemonSetUpdateStrategyType string const ( // Replace the old daemons by new ones using rolling update i.e replace them on each node one after the other. RollingUpdateDaemonSetStrategyType DaemonSetUpdateStrategyType = "RollingUpdate" // Replace the old daemons only when it's killed OnDeleteDaemonSetStrategyType DaemonSetUpdateStrategyType = "OnDelete" ) // Spec to control the desired behavior of daemon set rolling update. type RollingUpdateDaemonSet struct { // The maximum number of DaemonSet pods that can be unavailable during the // update. Value can be an absolute number (ex: 5) or a percentage of total // number of DaemonSet pods at the start of the update (ex: 10%). Absolute // number is calculated from percentage by rounding up. // This cannot be 0. // Default value is 1. // Example: when this is set to 30%, at most 30% of the total number of nodes // that should be running the daemon pod (i.e. status.desiredNumberScheduled) // can have their pods stopped for an update at any given // time. The update starts by stopping at most 30% of those DaemonSet pods // and then brings up new DaemonSet pods in their place. Once the new pods // are available, it then proceeds onto other DaemonSet pods, thus ensuring // that at least 70% of original number of DaemonSet pods are available at // all times during the update. // +optional MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty" protobuf:"bytes,1,opt,name=maxUnavailable"` } // DaemonSetSpec is the specification of a daemon set. type DaemonSetSpec struct { // A label query over pods that are managed by the daemon set. // Must match in order to be controlled. // If empty, defaulted to labels on Pod template. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors // +optional Selector *metav1.LabelSelector `json:"selector,omitempty" protobuf:"bytes,1,opt,name=selector"` // An object that describes the pod that will be created. // The DaemonSet will create exactly one copy of this pod on every node // that matches the template's node selector (or on every node if no node // selector is specified). // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,2,opt,name=template"` // An update strategy to replace existing DaemonSet pods with new pods. // +optional UpdateStrategy DaemonSetUpdateStrategy `json:"updateStrategy,omitempty" protobuf:"bytes,3,opt,name=updateStrategy"` // The minimum number of seconds for which a newly created DaemonSet pod should // be ready without any of its container crashing, for it to be considered // available. Defaults to 0 (pod will be considered available as soon as it // is ready). // +optional MinReadySeconds int32 `json:"minReadySeconds,omitempty" protobuf:"varint,4,opt,name=minReadySeconds"` // DEPRECATED. // A sequence number representing a specific generation of the template. // Populated by the system. It can be set only during the creation. // +optional TemplateGeneration int64 `json:"templateGeneration,omitempty" protobuf:"varint,5,opt,name=templateGeneration"` // The number of old history to retain to allow rollback. // This is a pointer to distinguish between explicit zero and not specified. // Defaults to 10. // +optional RevisionHistoryLimit *int32 `json:"revisionHistoryLimit,omitempty" protobuf:"varint,6,opt,name=revisionHistoryLimit"` } // DaemonSetStatus represents the current status of a daemon set. type DaemonSetStatus struct { // The number of nodes that are running at least 1 // daemon pod and are supposed to run the daemon pod. // More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/ CurrentNumberScheduled int32 `json:"currentNumberScheduled" protobuf:"varint,1,opt,name=currentNumberScheduled"` // The number of nodes that are running the daemon pod, but are // not supposed to run the daemon pod. // More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/ NumberMisscheduled int32 `json:"numberMisscheduled" protobuf:"varint,2,opt,name=numberMisscheduled"` // The total number of nodes that should be running the daemon // pod (including nodes correctly running the daemon pod). // More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/ DesiredNumberScheduled int32 `json:"desiredNumberScheduled" protobuf:"varint,3,opt,name=desiredNumberScheduled"` // The number of nodes that should be running the daemon pod and have one // or more of the daemon pod running and ready. NumberReady int32 `json:"numberReady" protobuf:"varint,4,opt,name=numberReady"` // The most recent generation observed by the daemon set controller. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty" protobuf:"varint,5,opt,name=observedGeneration"` // The total number of nodes that are running updated daemon pod // +optional UpdatedNumberScheduled int32 `json:"updatedNumberScheduled,omitempty" protobuf:"varint,6,opt,name=updatedNumberScheduled"` // The number of nodes that should be running the // daemon pod and have one or more of the daemon pod running and // available (ready for at least spec.minReadySeconds) // +optional NumberAvailable int32 `json:"numberAvailable,omitempty" protobuf:"varint,7,opt,name=numberAvailable"` // The number of nodes that should be running the // daemon pod and have none of the daemon pod running and available // (ready for at least spec.minReadySeconds) // +optional NumberUnavailable int32 `json:"numberUnavailable,omitempty" protobuf:"varint,8,opt,name=numberUnavailable"` // Count of hash collisions for the DaemonSet. The DaemonSet controller // uses this field as a collision avoidance mechanism when it needs to // create the name for the newest ControllerRevision. // +optional CollisionCount *int64 `json:"collisionCount,omitempty" protobuf:"varint,9,opt,name=collisionCount"` } // +genclient=true // DaemonSet represents the configuration of a daemon set. type DaemonSet struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // The desired behavior of this daemon set. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status // +optional Spec DaemonSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // The current status of this daemon set. This data may be // out of date by some window of time. // Populated by the system. // Read-only. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status // +optional Status DaemonSetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } const ( // DEPRECATED: DefaultDaemonSetUniqueLabelKey is used instead. // DaemonSetTemplateGenerationKey is the key of the labels that is added // to daemon set pods to distinguish between old and new pod templates // during DaemonSet template update. DaemonSetTemplateGenerationKey string = "pod-template-generation" // DefaultDaemonSetUniqueLabelKey is the default label key that is added // to existing DaemonSet pods to distinguish between old and new // DaemonSet pods during DaemonSet template updates. DefaultDaemonSetUniqueLabelKey = appsv1beta1.ControllerRevisionHashLabelKey ) // DaemonSetList is a collection of daemon sets. type DaemonSetList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // A list of daemon sets. Items []DaemonSet `json:"items" protobuf:"bytes,2,rep,name=items"` } // ThirdPartyResrouceDataList is a list of ThirdPartyResourceData. type ThirdPartyResourceDataList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of ThirdpartyResourceData. Items []ThirdPartyResourceData `json:"items" protobuf:"bytes,2,rep,name=items"` } // +genclient=true // Ingress is a collection of rules that allow inbound connections to reach the // endpoints defined by a backend. An Ingress can be configured to give services // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. type Ingress struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec is the desired state of the Ingress. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status // +optional Spec IngressSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the current state of the Ingress. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status // +optional Status IngressStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // IngressList is a collection of Ingress. type IngressList struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of Ingress. Items []Ingress `json:"items" protobuf:"bytes,2,rep,name=items"` } // IngressSpec describes the Ingress the user wishes to exist. type IngressSpec struct { // A default backend capable of servicing requests that don't match any // rule. At least one of 'backend' or 'rules' must be specified. This field // is optional to allow the loadbalancer controller or defaulting logic to // specify a global default. // +optional Backend *IngressBackend `json:"backend,omitempty" protobuf:"bytes,1,opt,name=backend"` // TLS configuration. Currently the Ingress only supports a single TLS // port, 443. If multiple members of this list specify different hosts, they // will be multiplexed on the same port according to the hostname specified // through the SNI TLS extension, if the ingress controller fulfilling the // ingress supports SNI. // +optional TLS []IngressTLS `json:"tls,omitempty" protobuf:"bytes,2,rep,name=tls"` // A list of host rules used to configure the Ingress. If unspecified, or // no rule matches, all traffic is sent to the default backend. // +optional Rules []IngressRule `json:"rules,omitempty" protobuf:"bytes,3,rep,name=rules"` // TODO: Add the ability to specify load-balancer IP through claims } // IngressTLS describes the transport layer security associated with an Ingress. type IngressTLS struct { // Hosts are a list of hosts included in the TLS certificate. The values in // this list must match the name/s used in the tlsSecret. Defaults to the // wildcard host setting for the loadbalancer controller fulfilling this // Ingress, if left unspecified. // +optional Hosts []string `json:"hosts,omitempty" protobuf:"bytes,1,rep,name=hosts"` // SecretName is the name of the secret used to terminate SSL traffic on 443. // Field is left optional to allow SSL routing based on SNI hostname alone. // If the SNI host in a listener conflicts with the "Host" header field used // by an IngressRule, the SNI host is used for termination and value of the // Host header is used for routing. // +optional SecretName string `json:"secretName,omitempty" protobuf:"bytes,2,opt,name=secretName"` // TODO: Consider specifying different modes of termination, protocols etc. } // IngressStatus describe the current state of the Ingress. type IngressStatus struct { // LoadBalancer contains the current status of the load-balancer. // +optional LoadBalancer v1.LoadBalancerStatus `json:"loadBalancer,omitempty" protobuf:"bytes,1,opt,name=loadBalancer"` } // IngressRule represents the rules mapping the paths under a specified host to // the related backend services. Incoming requests are first evaluated for a host // match, then routed to the backend associated with the matching IngressRuleValue. type IngressRule struct { // Host is the fully qualified domain name of a network host, as defined // by RFC 3986. Note the following deviations from the "host" part of the // URI as defined in the RFC: // 1. IPs are not allowed. Currently an IngressRuleValue can only apply to the // IP in the Spec of the parent Ingress. // 2. The `:` delimiter is not respected because ports are not allowed. // Currently the port of an Ingress is implicitly :80 for http and // :443 for https. // Both these may change in the future. // Incoming requests are matched against the host before the IngressRuleValue. // If the host is unspecified, the Ingress routes all traffic based on the // specified IngressRuleValue. // +optional Host string `json:"host,omitempty" protobuf:"bytes,1,opt,name=host"` // IngressRuleValue represents a rule to route requests for this IngressRule. // If unspecified, the rule defaults to a http catch-all. Whether that sends // just traffic matching the host to the default backend or all traffic to the // default backend, is left to the controller fulfilling the Ingress. Http is // currently the only supported IngressRuleValue. // +optional IngressRuleValue `json:",inline,omitempty" protobuf:"bytes,2,opt,name=ingressRuleValue"` } // IngressRuleValue represents a rule to apply against incoming requests. If the // rule is satisfied, the request is routed to the specified backend. Currently // mixing different types of rules in a single Ingress is disallowed, so exactly // one of the following must be set. type IngressRuleValue struct { //TODO: // 1. Consider renaming this resource and the associated rules so they // aren't tied to Ingress. They can be used to route intra-cluster traffic. // 2. Consider adding fields for ingress-type specific global options // usable by a loadbalancer, like http keep-alive. // +optional HTTP *HTTPIngressRuleValue `json:"http,omitempty" protobuf:"bytes,1,opt,name=http"` } // HTTPIngressRuleValue is a list of http selectors pointing to backends. // In the example: http://<host>/<path>?<searchpart> -> backend where // where parts of the url correspond to RFC 3986, this resource will be used // to match against everything after the last '/' and before the first '?' // or '#'. type HTTPIngressRuleValue struct { // A collection of paths that map requests to backends. Paths []HTTPIngressPath `json:"paths" protobuf:"bytes,1,rep,name=paths"` // TODO: Consider adding fields for ingress-type specific global // options usable by a loadbalancer, like http keep-alive. } // HTTPIngressPath associates a path regex with a backend. Incoming urls matching // the path are forwarded to the backend. type HTTPIngressPath struct { // Path is an extended POSIX regex as defined by IEEE Std 1003.1, // (i.e this follows the egrep/unix syntax, not the perl syntax) // matched against the path of an incoming request. Currently it can // contain characters disallowed from the conventional "path" // part of a URL as defined by RFC 3986. Paths must begin with // a '/'. If unspecified, the path defaults to a catch all sending // traffic to the backend. // +optional Path string `json:"path,omitempty" protobuf:"bytes,1,opt,name=path"` // Backend defines the referenced service endpoint to which the traffic // will be forwarded to. Backend IngressBackend `json:"backend" protobuf:"bytes,2,opt,name=backend"` } // IngressBackend describes all endpoints for a given service and port. type IngressBackend struct { // Specifies the name of the referenced service. ServiceName string `json:"serviceName" protobuf:"bytes,1,opt,name=serviceName"` // Specifies the port of the referenced service. ServicePort intstr.IntOrString `json:"servicePort" protobuf:"bytes,2,opt,name=servicePort"` } // +genclient=true // ReplicaSet represents the configuration of a ReplicaSet. type ReplicaSet struct { metav1.TypeMeta `json:",inline"` // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the specification of the desired behavior of the ReplicaSet. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status // +optional Spec ReplicaSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the most recently observed status of the ReplicaSet. // This data may be out of date by some window of time. // Populated by the system. // Read-only. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status // +optional Status ReplicaSetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // ReplicaSetList is a collection of ReplicaSets. type ReplicaSetList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of ReplicaSets. // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller Items []ReplicaSet `json:"items" protobuf:"bytes,2,rep,name=items"` } // ReplicaSetSpec is the specification of a ReplicaSet. type ReplicaSetSpec struct { // Replicas is the number of desired replicas. // This is a pointer to distinguish between explicit zero and unspecified. // Defaults to 1. // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller // +optional Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` // Minimum number of seconds for which a newly created pod should be ready // without any of its container crashing, for it to be considered available. // Defaults to 0 (pod will be considered available as soon as it is ready) // +optional MinReadySeconds int32 `json:"minReadySeconds,omitempty" protobuf:"varint,4,opt,name=minReadySeconds"` // Selector is a label query over pods that should match the replica count. // If the selector is empty, it is defaulted to the labels present on the pod template. // Label keys and values that must match in order to be controlled by this replica set. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors // +optional Selector *metav1.LabelSelector `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` // Template is the object that describes the pod that will be created if // insufficient replicas are detected. // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template // +optional Template v1.PodTemplateSpec `json:"template,omitempty" protobuf:"bytes,3,opt,name=template"` } // ReplicaSetStatus represents the current status of a ReplicaSet. type ReplicaSetStatus struct { // Replicas is the most recently oberved number of replicas. // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller Replicas int32 `json:"replicas" protobuf:"varint,1,opt,name=replicas"` // The number of pods that have labels matching the labels of the pod template of the replicaset. // +optional FullyLabeledReplicas int32 `json:"fullyLabeledReplicas,omitempty" protobuf:"varint,2,opt,name=fullyLabeledReplicas"` // The number of ready replicas for this replica set. // +optional ReadyReplicas int32 `json:"readyReplicas,omitempty" protobuf:"varint,4,opt,name=readyReplicas"` // The number of available replicas (ready for at least minReadySeconds) for this replica set. // +optional AvailableReplicas int32 `json:"availableReplicas,omitempty" protobuf:"varint,5,opt,name=availableReplicas"` // ObservedGeneration reflects the generation of the most recently observed ReplicaSet. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty" protobuf:"varint,3,opt,name=observedGeneration"` // Represents the latest available observations of a replica set's current state. // +optional // +patchMergeKey=type // +patchStrategy=merge Conditions []ReplicaSetCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,6,rep,name=conditions"` } type ReplicaSetConditionType string // These are valid conditions of a replica set. const ( // ReplicaSetReplicaFailure is added in a replica set when one of its pods fails to be created // due to insufficient quota, limit ranges, pod security policy, node selectors, etc. or deleted // due to kubelet being down or finalizers are failing. ReplicaSetReplicaFailure ReplicaSetConditionType = "ReplicaFailure" ) // ReplicaSetCondition describes the state of a replica set at a certain point. type ReplicaSetCondition struct { // Type of replica set condition. Type ReplicaSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=ReplicaSetConditionType"` // Status of the condition, one of True, False, Unknown. Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/kubernetes/pkg/api/v1.ConditionStatus"` // The last time the condition transitioned from one status to another. // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // The reason for the condition's last transition. // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // A human readable message indicating details about the transition. // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } // +genclient=true // +nonNamespaced=true // Pod Security Policy governs the ability to make requests that affect the Security Context // that will be applied to a pod and container. type PodSecurityPolicy struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec defines the policy enforced. // +optional Spec PodSecurityPolicySpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` } // Pod Security Policy Spec defines the policy enforced. type PodSecurityPolicySpec struct { // privileged determines if a pod can request to be run as privileged. // +optional Privileged bool `json:"privileged,omitempty" protobuf:"varint,1,opt,name=privileged"` // DefaultAddCapabilities is the default set of capabilities that will be added to the container // unless the pod spec specifically drops the capability. You may not list a capabiility in both // DefaultAddCapabilities and RequiredDropCapabilities. // +optional DefaultAddCapabilities []v1.Capability `json:"defaultAddCapabilities,omitempty" protobuf:"bytes,2,rep,name=defaultAddCapabilities,casttype=k8s.io/kubernetes/pkg/api/v1.Capability"` // RequiredDropCapabilities are the capabilities that will be dropped from the container. These // are required to be dropped and cannot be added. // +optional RequiredDropCapabilities []v1.Capability `json:"requiredDropCapabilities,omitempty" protobuf:"bytes,3,rep,name=requiredDropCapabilities,casttype=k8s.io/kubernetes/pkg/api/v1.Capability"` // AllowedCapabilities is a list of capabilities that can be requested to add to the container. // Capabilities in this field may be added at the pod author's discretion. // You must not list a capability in both AllowedCapabilities and RequiredDropCapabilities. // +optional AllowedCapabilities []v1.Capability `json:"allowedCapabilities,omitempty" protobuf:"bytes,4,rep,name=allowedCapabilities,casttype=k8s.io/kubernetes/pkg/api/v1.Capability"` // volumes is a white list of allowed volume plugins. Empty indicates that all plugins // may be used. // +optional Volumes []FSType `json:"volumes,omitempty" protobuf:"bytes,5,rep,name=volumes,casttype=FSType"` // hostNetwork determines if the policy allows the use of HostNetwork in the pod spec. // +optional HostNetwork bool `json:"hostNetwork,omitempty" protobuf:"varint,6,opt,name=hostNetwork"` // hostPorts determines which host port ranges are allowed to be exposed. // +optional HostPorts []HostPortRange `json:"hostPorts,omitempty" protobuf:"bytes,7,rep,name=hostPorts"` // hostPID determines if the policy allows the use of HostPID in the pod spec. // +optional HostPID bool `json:"hostPID,omitempty" protobuf:"varint,8,opt,name=hostPID"` // hostIPC determines if the policy allows the use of HostIPC in the pod spec. // +optional HostIPC bool `json:"hostIPC,omitempty" protobuf:"varint,9,opt,name=hostIPC"` // seLinux is the strategy that will dictate the allowable labels that may be set. SELinux SELinuxStrategyOptions `json:"seLinux" protobuf:"bytes,10,opt,name=seLinux"` // runAsUser is the strategy that will dictate the allowable RunAsUser values that may be set. RunAsUser RunAsUserStrategyOptions `json:"runAsUser" protobuf:"bytes,11,opt,name=runAsUser"` // SupplementalGroups is the strategy that will dictate what supplemental groups are used by the SecurityContext. SupplementalGroups SupplementalGroupsStrategyOptions `json:"supplementalGroups" protobuf:"bytes,12,opt,name=supplementalGroups"` // FSGroup is the strategy that will dictate what fs group is used by the SecurityContext. FSGroup FSGroupStrategyOptions `json:"fsGroup" protobuf:"bytes,13,opt,name=fsGroup"` // ReadOnlyRootFilesystem when set to true will force containers to run with a read only root file // system. If the container specifically requests to run with a non-read only root file system // the PSP should deny the pod. // If set to false the container may run with a read only root file system if it wishes but it // will not be forced to. // +optional ReadOnlyRootFilesystem bool `json:"readOnlyRootFilesystem,omitempty" protobuf:"varint,14,opt,name=readOnlyRootFilesystem"` } // FS Type gives strong typing to different file systems that are used by volumes. type FSType string var ( AzureFile FSType = "azureFile" Flocker FSType = "flocker" FlexVolume FSType = "flexVolume" HostPath FSType = "hostPath" EmptyDir FSType = "emptyDir" GCEPersistentDisk FSType = "gcePersistentDisk" AWSElasticBlockStore FSType = "awsElasticBlockStore" GitRepo FSType = "gitRepo" Secret FSType = "secret" NFS FSType = "nfs" ISCSI FSType = "iscsi" Glusterfs FSType = "glusterfs" PersistentVolumeClaim FSType = "persistentVolumeClaim" RBD FSType = "rbd" Cinder FSType = "cinder" CephFS FSType = "cephFS" DownwardAPI FSType = "downwardAPI" FC FSType = "fc" ConfigMap FSType = "configMap" Quobyte FSType = "quobyte" AzureDisk FSType = "azureDisk" All FSType = "*" ) // Host Port Range defines a range of host ports that will be enabled by a policy // for pods to use. It requires both the start and end to be defined. type HostPortRange struct { // min is the start of the range, inclusive. Min int32 `json:"min" protobuf:"varint,1,opt,name=min"` // max is the end of the range, inclusive. Max int32 `json:"max" protobuf:"varint,2,opt,name=max"` } // SELinux Strategy Options defines the strategy type and any options used to create the strategy. type SELinuxStrategyOptions struct { // type is the strategy that will dictate the allowable labels that may be set. Rule SELinuxStrategy `json:"rule" protobuf:"bytes,1,opt,name=rule,casttype=SELinuxStrategy"` // seLinuxOptions required to run as; required for MustRunAs // More info: https://git.k8s.io/community/contributors/design-proposals/security_context.md // +optional SELinuxOptions *v1.SELinuxOptions `json:"seLinuxOptions,omitempty" protobuf:"bytes,2,opt,name=seLinuxOptions"` } // SELinuxStrategy denotes strategy types for generating SELinux options for a // Security Context. type SELinuxStrategy string const ( // container must have SELinux labels of X applied. SELinuxStrategyMustRunAs SELinuxStrategy = "MustRunAs" // container may make requests for any SELinux context labels. SELinuxStrategyRunAsAny SELinuxStrategy = "RunAsAny" ) // Run A sUser Strategy Options defines the strategy type and any options used to create the strategy. type RunAsUserStrategyOptions struct { // Rule is the strategy that will dictate the allowable RunAsUser values that may be set. Rule RunAsUserStrategy `json:"rule" protobuf:"bytes,1,opt,name=rule,casttype=RunAsUserStrategy"` // Ranges are the allowed ranges of uids that may be used. // +optional Ranges []IDRange `json:"ranges,omitempty" protobuf:"bytes,2,rep,name=ranges"` } // ID Range provides a min/max of an allowed range of IDs. type IDRange struct { // Min is the start of the range, inclusive. Min int64 `json:"min" protobuf:"varint,1,opt,name=min"` // Max is the end of the range, inclusive. Max int64 `json:"max" protobuf:"varint,2,opt,name=max"` } // RunAsUserStrategy denotes strategy types for generating RunAsUser values for a // Security Context. type RunAsUserStrategy string const ( // container must run as a particular uid. RunAsUserStrategyMustRunAs RunAsUserStrategy = "MustRunAs" // container must run as a non-root uid RunAsUserStrategyMustRunAsNonRoot RunAsUserStrategy = "MustRunAsNonRoot" // container may make requests for any uid. RunAsUserStrategyRunAsAny RunAsUserStrategy = "RunAsAny" ) // FSGroupStrategyOptions defines the strategy type and options used to create the strategy. type FSGroupStrategyOptions struct { // Rule is the strategy that will dictate what FSGroup is used in the SecurityContext. // +optional Rule FSGroupStrategyType `json:"rule,omitempty" protobuf:"bytes,1,opt,name=rule,casttype=FSGroupStrategyType"` // Ranges are the allowed ranges of fs groups. If you would like to force a single // fs group then supply a single range with the same start and end. // +optional Ranges []IDRange `json:"ranges,omitempty" protobuf:"bytes,2,rep,name=ranges"` } // FSGroupStrategyType denotes strategy types for generating FSGroup values for a // SecurityContext type FSGroupStrategyType string const ( // container must have FSGroup of X applied. FSGroupStrategyMustRunAs FSGroupStrategyType = "MustRunAs" // container may make requests for any FSGroup labels. FSGroupStrategyRunAsAny FSGroupStrategyType = "RunAsAny" ) // SupplementalGroupsStrategyOptions defines the strategy type and options used to create the strategy. type SupplementalGroupsStrategyOptions struct { // Rule is the strategy that will dictate what supplemental groups is used in the SecurityContext. // +optional Rule SupplementalGroupsStrategyType `json:"rule,omitempty" protobuf:"bytes,1,opt,name=rule,casttype=SupplementalGroupsStrategyType"` // Ranges are the allowed ranges of supplemental groups. If you would like to force a single // supplemental group then supply a single range with the same start and end. // +optional Ranges []IDRange `json:"ranges,omitempty" protobuf:"bytes,2,rep,name=ranges"` } // SupplementalGroupsStrategyType denotes strategy types for determining valid supplemental // groups for a SecurityContext. type SupplementalGroupsStrategyType string const ( // container must run as a particular gid. SupplementalGroupsStrategyMustRunAs SupplementalGroupsStrategyType = "MustRunAs" // container may make requests for any gid. SupplementalGroupsStrategyRunAsAny SupplementalGroupsStrategyType = "RunAsAny" ) // Pod Security Policy List is a list of PodSecurityPolicy objects. type PodSecurityPolicyList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of schema objects. Items []PodSecurityPolicy `json:"items" protobuf:"bytes,2,rep,name=items"` } // NetworkPolicy describes what network traffic is allowed for a set of Pods type NetworkPolicy struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior for this NetworkPolicy. // +optional Spec NetworkPolicySpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` } type NetworkPolicySpec struct { // Selects the pods to which this NetworkPolicy object applies. The array of ingress rules // is applied to any pods selected by this field. Multiple network policies can select the // same set of pods. In this case, the ingress rules for each are combined additively. // This field is NOT optional and follows standard label selector semantics. // An empty podSelector matches all pods in this namespace. PodSelector metav1.LabelSelector `json:"podSelector" protobuf:"bytes,1,opt,name=podSelector"` // List of ingress rules to be applied to the selected pods. // Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod // OR if the traffic source is the pod's local node, // OR if the traffic matches at least one ingress rule across all of the NetworkPolicy // objects whose podSelector matches the pod. // If this field is empty then this NetworkPolicy does not allow any traffic // (and serves solely to ensure that the pods it selects are isolated by default). // +optional Ingress []NetworkPolicyIngressRule `json:"ingress,omitempty" protobuf:"bytes,2,rep,name=ingress"` } // This NetworkPolicyIngressRule matches traffic if and only if the traffic matches both ports AND from. type NetworkPolicyIngressRule struct { // List of ports which should be made accessible on the pods selected for this rule. // Each item in this list is combined using a logical OR. // If this field is empty or missing, this rule matches all ports (traffic not restricted by port). // If this field is present and contains at least one item, then this rule allows traffic // only if the traffic matches at least one port in the list. // +optional Ports []NetworkPolicyPort `json:"ports,omitempty" protobuf:"bytes,1,rep,name=ports"` // List of sources which should be able to access the pods selected for this rule. // Items in this list are combined using a logical OR operation. // If this field is empty or missing, this rule matches all sources (traffic not restricted by source). // If this field is present and contains at least on item, this rule allows traffic only if the // traffic matches at least one item in the from list. // +optional From []NetworkPolicyPeer `json:"from,omitempty" protobuf:"bytes,2,rep,name=from"` } type NetworkPolicyPort struct { // Optional. The protocol (TCP or UDP) which traffic must match. // If not specified, this field defaults to TCP. // +optional Protocol *v1.Protocol `json:"protocol,omitempty" protobuf:"bytes,1,opt,name=protocol,casttype=k8s.io/kubernetes/pkg/api/v1.Protocol"` // If specified, the port on the given protocol. This can // either be a numerical or named port on a pod. If this field is not provided, // this matches all port names and numbers. // If present, only traffic on the specified protocol AND port // will be matched. // +optional Port *intstr.IntOrString `json:"port,omitempty" protobuf:"bytes,2,opt,name=port"` } type NetworkPolicyPeer struct { // Exactly one of the following must be specified. // This is a label selector which selects Pods in this namespace. // This field follows standard label selector semantics. // If present but empty, this selector selects all pods in this namespace. // +optional PodSelector *metav1.LabelSelector `json:"podSelector,omitempty" protobuf:"bytes,1,opt,name=podSelector"` // Selects Namespaces using cluster scoped-labels. This // matches all pods in all namespaces selected by this label selector. // This field follows standard label selector semantics. // If present but empty, this selector selects all namespaces. // +optional NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty" protobuf:"bytes,2,opt,name=namespaceSelector"` } // Network Policy List is a list of NetworkPolicy objects. type NetworkPolicyList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of schema objects. Items []NetworkPolicy `json:"items" protobuf:"bytes,2,rep,name=items"` }
apache-2.0
ShinyROM/android_external_chromium_org
ui/gl/gl_bindings_skia_in_process.cc
23406
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gl/gl_bindings_skia_in_process.h" #include "base/logging.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_implementation.h" namespace { extern "C" { // The following stub functions are required because the glXXX routines exported // via gl_bindings.h use call-type GL_BINDING_CALL, which on Windows is stdcall. // Skia has been built such that its GrGLInterface GL pointers are __cdecl. GLvoid StubGLActiveTexture(GLenum texture) { glActiveTexture(texture); } GLvoid StubGLAttachShader(GLuint program, GLuint shader) { glAttachShader(program, shader); } GLvoid StubGLBeginQuery(GLenum target, GLuint id) { glBeginQuery(target, id); } GLvoid StubGLBindAttribLocation(GLuint program, GLuint index, const char* name) { glBindAttribLocation(program, index, name); } GLvoid StubGLBindBuffer(GLenum target, GLuint buffer) { glBindBuffer(target, buffer); } GLvoid StubGLBindFragDataLocation(GLuint program, GLuint colorNumber, const GLchar * name) { glBindFragDataLocation(program, colorNumber, name); } GLvoid StubGLBindFragDataLocationIndexed(GLuint program, GLuint colorNumber, GLuint index, const GLchar * name) { glBindFragDataLocationIndexed(program, colorNumber, index, name); } GLvoid StubGLBindFramebuffer(GLenum target, GLuint framebuffer) { glBindFramebufferEXT(target, framebuffer); } GLvoid StubGLBindRenderbuffer(GLenum target, GLuint renderbuffer) { glBindRenderbufferEXT(target, renderbuffer); } GLvoid StubGLBindTexture(GLenum target, GLuint texture) { glBindTexture(target, texture); } GLvoid StubGLBindVertexArray(GLuint array) { glBindVertexArrayOES(array); } GLvoid StubGLBlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { glBlendColor(red, green, blue, alpha); } GLvoid StubGLBlendFunc(GLenum sfactor, GLenum dfactor) { glBlendFunc(sfactor, dfactor); } GLvoid StubGLBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) { glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } GLvoid StubGLBufferData(GLenum target, GLsizeiptr size, const void* data, GLenum usage) { glBufferData(target, size, data, usage); } GLvoid StubGLBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void* data) { glBufferSubData(target, offset, size, data); } GLenum StubGLCheckFramebufferStatus(GLenum target) { return glCheckFramebufferStatusEXT(target); } GLvoid StubGLClear(GLbitfield mask) { glClear(mask); } GLvoid StubGLClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { glClearColor(red, green, blue, alpha); } GLvoid StubGLClearStencil(GLint s) { glClearStencil(s); } GLvoid StubGLColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { glColorMask(red, green, blue, alpha); } GLvoid StubGLCompileShader(GLuint shader) { glCompileShader(shader); } GLvoid StubGLCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data) { glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } GLvoid StubGLCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } GLuint StubGLCreateProgram(void) { return glCreateProgram(); } GLuint StubGLCreateShader(GLenum type) { return glCreateShader(type); } GLvoid StubGLCullFace(GLenum mode) { glCullFace(mode); } GLvoid StubGLDeleteBuffers(GLsizei n, const GLuint* buffers) { glDeleteBuffersARB(n, buffers); } GLvoid StubGLDeleteFramebuffers(GLsizei n, const GLuint* framebuffers) { glDeleteFramebuffersEXT(n, framebuffers); } GLvoid StubGLDeleteQueries(GLsizei n, const GLuint* ids) { glDeleteQueries(n, ids); } GLvoid StubGLDeleteProgram(GLuint program) { glDeleteProgram(program); } GLvoid StubGLDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers) { glDeleteRenderbuffersEXT(n, renderbuffers); } GLvoid StubGLDeleteShader(GLuint shader) { glDeleteShader(shader); } GLvoid StubGLDeleteTextures(GLsizei n, const GLuint* textures) { glDeleteTextures(n, textures); } GLvoid StubGLDeleteVertexArrays(GLsizei n, const GLuint* arrays) { glDeleteVertexArraysOES(n, arrays); } GLvoid StubGLDepthMask(GLboolean flag) { glDepthMask(flag); } GLvoid StubGLDisable(GLenum cap) { glDisable(cap); } GLvoid StubGLDisableVertexAttribArray(GLuint index) { glDisableVertexAttribArray(index); } GLvoid StubGLDrawArrays(GLenum mode, GLint first, GLsizei count) { glDrawArrays(mode, first, count); } GLvoid StubGLDrawBuffer(GLenum mode) { glDrawBuffer(mode); } GLvoid StubGLDrawBuffers(GLsizei n, const GLenum* bufs) { glDrawBuffersARB(n, bufs); } GLvoid StubGLDrawElements(GLenum mode, GLsizei count, GLenum type, const void* indices) { glDrawElements(mode, count, type, indices); } GLvoid StubGLEnable(GLenum cap) { glEnable(cap); } GLvoid StubGLEnableVertexAttribArray(GLuint index) { glEnableVertexAttribArray(index); } GLvoid StubGLEndQuery(GLenum target) { glEndQuery(target); } GLvoid StubGLFinish() { glFinish(); } GLvoid StubGLFlush() { glFlush(); } GLvoid StubGLFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) { glFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer); } GLvoid StubGLFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) { glFramebufferTexture2DEXT(target, attachment, textarget, texture, level); } GLvoid StubGLFramebufferTexture2DMultisample(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples) { glFramebufferTexture2DMultisampleEXT(target, attachment, textarget, texture, level, samples); } GLvoid StubGLFrontFace(GLenum mode) { glFrontFace(mode); } GLvoid StubGLGenBuffers(GLsizei n, GLuint* buffers) { glGenBuffersARB(n, buffers); } GLvoid StubGLGenFramebuffers(GLsizei n, GLuint* framebuffers) { glGenFramebuffersEXT(n, framebuffers); } GLvoid StubGLGenQueries(GLsizei n, GLuint* ids) { glGenQueries(n, ids); } GLvoid StubGLGenRenderbuffers(GLsizei n, GLuint* renderbuffers) { glGenRenderbuffersEXT(n, renderbuffers); } GLvoid StubGLGenTextures(GLsizei n, GLuint* textures) { glGenTextures(n, textures); } GLvoid StubGLGenVertexArrays(GLsizei n, GLuint* arrays) { glGenVertexArraysOES(n, arrays); } GLvoid StubGLGetBufferParameteriv(GLenum target, GLenum pname, GLint* params) { glGetBufferParameteriv(target, pname, params); } GLvoid StubGLGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params) { glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, params); } GLenum StubGLGetError() { return glGetError(); } GLvoid StubGLGetIntegerv(GLenum pname, GLint* params) { glGetIntegerv(pname, params); } GLvoid StubGLGetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, char* infolog) { glGetProgramInfoLog(program, bufsize, length, infolog); } GLvoid StubGLGetProgramiv(GLuint program, GLenum pname, GLint* params) { glGetProgramiv(program, pname, params); } GLvoid StubGLGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params) { glGetRenderbufferParameterivEXT(target, pname, params); } GLvoid StubGLGetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog) { glGetShaderInfoLog(shader, bufsize, length, infolog); } GLvoid StubGLGetShaderiv(GLuint shader, GLenum pname, GLint* params) { glGetShaderiv(shader, pname, params); } const GLubyte* StubGLGetString(GLenum name) { return glGetString(name); } GLvoid StubGLGetQueryiv(GLenum target, GLenum pname, GLint* params) { glGetQueryiv(target, pname, params); } GLvoid StubGLGetQueryObjecti64v(GLuint id, GLenum pname, GLint64* params) { glGetQueryObjecti64v(id, pname, params); } GLvoid StubGLGetQueryObjectiv(GLuint id, GLenum pname, GLint* params) { glGetQueryObjectiv(id, pname, params); } GLvoid StubGLGetQueryObjectui64v(GLuint id, GLenum pname, GLuint64* params) { glGetQueryObjectui64v(id, pname, params); } GLvoid StubGLGetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params) { glGetQueryObjectuiv(id, pname, params); } GLvoid StubGLGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint* params) { glGetTexLevelParameteriv(target, level, pname, params); } GLint StubGLGetUniformLocation(GLuint program, const char* name) { return glGetUniformLocation(program, name); } GLvoid StubGLLineWidth(GLfloat width) { glLineWidth(width); } GLvoid StubGLLinkProgram(GLuint program) { glLinkProgram(program); } void* StubGLMapBuffer(GLenum target, GLenum access) { return glMapBuffer(target, access); } GLvoid StubGLPixelStorei(GLenum pname, GLint param) { glPixelStorei(pname, param); } GLvoid StubGLQueryCounter(GLuint id, GLenum target) { glQueryCounter(id, target); } GLvoid StubGLReadBuffer(GLenum src) { glReadBuffer(src); } GLvoid StubGLReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) { glReadPixels(x, y, width, height, format, type, pixels); } GLvoid StubGLRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { glRenderbufferStorageEXT(target, internalformat, width, height); } GLvoid StubGLRenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) { glRenderbufferStorageMultisampleEXT(target, samples, internalformat, width, height); } GLvoid StubGLScissor(GLint x, GLint y, GLsizei width, GLsizei height) { glScissor(x, y, width, height); } GLvoid StubGLShaderSource(GLuint shader, GLsizei count, const char* const* str, const GLint* length) { glShaderSource(shader, count, str, length); } GLvoid StubGLStencilFunc(GLenum func, GLint ref, GLuint mask) { glStencilFunc(func, ref, mask); } GLvoid StubGLStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask) { glStencilFuncSeparate(face, func, ref, mask); } GLvoid StubGLStencilMask(GLuint mask) { glStencilMask(mask); } GLvoid StubGLStencilMaskSeparate(GLenum face, GLuint mask) { glStencilMaskSeparate(face, mask); } GLvoid StubGLStencilOp(GLenum fail, GLenum zfail, GLenum zpass) { glStencilOp(fail, zfail, zpass); } GLvoid StubGLStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass) { glStencilOpSeparate(face, fail, zfail, zpass); } GLvoid StubGLTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } GLvoid StubGLTexParameteri(GLenum target, GLenum pname, GLint param) { glTexParameteri(target, pname, param); } GLvoid StubGLTexParameteriv(GLenum target, GLenum pname, const GLint* params) { glTexParameteriv(target, pname, params); } GLvoid StubGLTexStorage2D(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height) { glTexStorage2DEXT(target, levels, internalFormat, width, height); } GLvoid StubGLTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels) { glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } GLvoid StubGLUniform1f(GLint location, GLfloat v) { glUniform1i(location, v); } GLvoid StubGLUniform1i(GLint location, GLint v) { glUniform1i(location, v); } GLvoid StubGLUniform1fv(GLint location, GLsizei count, const GLfloat* v) { glUniform1fv(location, count, v); } GLvoid StubGLUniform1iv(GLint location, GLsizei count, const GLint* v) { glUniform1iv(location, count, v); } GLvoid StubGLUniform2f(GLint location, GLfloat v0, GLfloat v1) { glUniform2i(location, v0, v1); } GLvoid StubGLUniform2i(GLint location, GLint v0, GLint v1) { glUniform2i(location, v0, v1); } GLvoid StubGLUniform2fv(GLint location, GLsizei count, const GLfloat* v) { glUniform2fv(location, count, v); } GLvoid StubGLUniform2iv(GLint location, GLsizei count, const GLint* v) { glUniform2iv(location, count, v); } GLvoid StubGLUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { glUniform3i(location, v0, v1, v2); } GLvoid StubGLUniform3i(GLint location, GLint v0, GLint v1, GLint v2) { glUniform3i(location, v0, v1, v2); } GLvoid StubGLUniform3fv(GLint location, GLsizei count, const GLfloat* v) { glUniform3fv(location, count, v); } GLvoid StubGLUniform3iv(GLint location, GLsizei count, const GLint* v) { glUniform3iv(location, count, v); } GLvoid StubGLUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { glUniform4i(location, v0, v1, v2, v3); } GLvoid StubGLUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) { glUniform4i(location, v0, v1, v2, v3); } GLvoid StubGLUniform4fv(GLint location, GLsizei count, const GLfloat* v) { glUniform4fv(location, count, v); } GLvoid StubGLUniform4iv(GLint location, GLsizei count, const GLint* v) { glUniform4iv(location, count, v); } GLvoid StubGLUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { glUniformMatrix2fv(location, count, transpose, value); } GLvoid StubGLUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { glUniformMatrix3fv(location, count, transpose, value); } GLvoid StubGLUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { glUniformMatrix4fv(location, count, transpose, value); } GLboolean StubGLUnmapBuffer(GLenum target) { return glUnmapBuffer(target); } GLvoid StubGLUseProgram(GLuint program) { glUseProgram(program); } GLvoid StubGLVertexAttrib4fv(GLuint indx, const GLfloat* values) { glVertexAttrib4fv(indx, values); } GLvoid StubGLVertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr) { glVertexAttribPointer(indx, size, type, normalized, stride, ptr); } GLvoid StubGLViewport(GLint x, GLint y, GLsizei width, GLsizei height) { glViewport(x, y, width, height); } } // extern "C" } // namespace namespace gfx { GrGLInterface* CreateInProcessSkiaGLBinding() { GrGLBinding binding; switch (gfx::GetGLImplementation()) { case gfx::kGLImplementationNone: NOTREACHED(); return NULL; case gfx::kGLImplementationDesktopGL: case gfx::kGLImplementationAppleGL: binding = kDesktop_GrGLBinding; break; case gfx::kGLImplementationOSMesaGL: binding = kDesktop_GrGLBinding; break; case gfx::kGLImplementationEGLGLES2: binding = kES2_GrGLBinding; break; case gfx::kGLImplementationMockGL: NOTREACHED(); return NULL; default: NOTREACHED(); return NULL; } GrGLInterface* interface = new GrGLInterface; interface->fBindingsExported = binding; interface->fActiveTexture = StubGLActiveTexture; interface->fAttachShader = StubGLAttachShader; interface->fBeginQuery = StubGLBeginQuery; interface->fBindAttribLocation = StubGLBindAttribLocation; interface->fBindBuffer = StubGLBindBuffer; interface->fBindFragDataLocation = StubGLBindFragDataLocation; interface->fBindTexture = StubGLBindTexture; interface->fBindVertexArray = StubGLBindVertexArray; interface->fBlendColor = StubGLBlendColor; interface->fBlendFunc = StubGLBlendFunc; interface->fBufferData = StubGLBufferData; interface->fBufferSubData = StubGLBufferSubData; interface->fClear = StubGLClear; interface->fClearColor = StubGLClearColor; interface->fClearStencil = StubGLClearStencil; interface->fColorMask = StubGLColorMask; interface->fCompileShader = StubGLCompileShader; interface->fCompressedTexImage2D = StubGLCompressedTexImage2D; interface->fCopyTexSubImage2D = StubGLCopyTexSubImage2D; interface->fCreateProgram = StubGLCreateProgram; interface->fCreateShader = StubGLCreateShader; interface->fCullFace = StubGLCullFace; interface->fDeleteBuffers = StubGLDeleteBuffers; interface->fDeleteProgram = StubGLDeleteProgram; interface->fDeleteQueries = StubGLDeleteQueries; interface->fDeleteShader = StubGLDeleteShader; interface->fDeleteTextures = StubGLDeleteTextures; interface->fDeleteVertexArrays = StubGLDeleteVertexArrays; interface->fDepthMask = StubGLDepthMask; interface->fDisable = StubGLDisable; interface->fDisableVertexAttribArray = StubGLDisableVertexAttribArray; interface->fDrawArrays = StubGLDrawArrays; interface->fDrawBuffer = StubGLDrawBuffer; interface->fDrawBuffers = StubGLDrawBuffers; interface->fDrawElements = StubGLDrawElements; interface->fEnable = StubGLEnable; interface->fEnableVertexAttribArray = StubGLEnableVertexAttribArray; interface->fEndQuery = StubGLEndQuery; interface->fFinish = StubGLFinish; interface->fFlush = StubGLFlush; interface->fFrontFace = StubGLFrontFace; interface->fGenBuffers = StubGLGenBuffers; interface->fGenQueries = StubGLGenQueries; interface->fGenTextures = StubGLGenTextures; interface->fGenVertexArrays = StubGLGenVertexArrays; interface->fGetBufferParameteriv = StubGLGetBufferParameteriv; interface->fGetError = StubGLGetError; interface->fGetIntegerv = StubGLGetIntegerv; interface->fGetQueryiv = StubGLGetQueryiv; interface->fGetQueryObjecti64v = StubGLGetQueryObjecti64v; interface->fGetQueryObjectiv = StubGLGetQueryObjectiv; interface->fGetQueryObjectui64v = StubGLGetQueryObjectui64v; interface->fGetQueryObjectuiv = StubGLGetQueryObjectuiv; interface->fGetProgramInfoLog = StubGLGetProgramInfoLog; interface->fGetProgramiv = StubGLGetProgramiv; interface->fGetShaderInfoLog = StubGLGetShaderInfoLog; interface->fGetShaderiv = StubGLGetShaderiv; interface->fGetString = StubGLGetString; interface->fGetTexLevelParameteriv = StubGLGetTexLevelParameteriv; interface->fGetUniformLocation = StubGLGetUniformLocation; interface->fLineWidth = StubGLLineWidth; interface->fLinkProgram = StubGLLinkProgram; interface->fPixelStorei = StubGLPixelStorei; interface->fQueryCounter = StubGLQueryCounter; interface->fReadBuffer = StubGLReadBuffer; interface->fReadPixels = StubGLReadPixels; interface->fScissor = StubGLScissor; interface->fShaderSource = StubGLShaderSource; interface->fStencilFunc = StubGLStencilFunc; interface->fStencilFuncSeparate = StubGLStencilFuncSeparate; interface->fStencilMask = StubGLStencilMask; interface->fStencilMaskSeparate = StubGLStencilMaskSeparate; interface->fStencilOp = StubGLStencilOp; interface->fStencilOpSeparate = StubGLStencilOpSeparate; interface->fTexImage2D = StubGLTexImage2D; interface->fTexParameteri = StubGLTexParameteri; interface->fTexParameteriv = StubGLTexParameteriv; interface->fTexSubImage2D = StubGLTexSubImage2D; interface->fTexStorage2D = StubGLTexStorage2D; interface->fUniform1f = StubGLUniform1f; interface->fUniform1i = StubGLUniform1i; interface->fUniform1fv = StubGLUniform1fv; interface->fUniform1iv = StubGLUniform1iv; interface->fUniform2f = StubGLUniform2f; interface->fUniform2i = StubGLUniform2i; interface->fUniform2fv = StubGLUniform2fv; interface->fUniform2iv = StubGLUniform2iv; interface->fUniform3f = StubGLUniform3f; interface->fUniform3i = StubGLUniform3i; interface->fUniform3fv = StubGLUniform3fv; interface->fUniform3iv = StubGLUniform3iv; interface->fUniform4f = StubGLUniform4f; interface->fUniform4i = StubGLUniform4i; interface->fUniform4fv = StubGLUniform4fv; interface->fUniform4iv = StubGLUniform4iv; interface->fUniformMatrix2fv = StubGLUniformMatrix2fv; interface->fUniformMatrix3fv = StubGLUniformMatrix3fv; interface->fUniformMatrix4fv = StubGLUniformMatrix4fv; interface->fUseProgram = StubGLUseProgram; interface->fVertexAttrib4fv = StubGLVertexAttrib4fv; interface->fVertexAttribPointer = StubGLVertexAttribPointer; interface->fViewport = StubGLViewport; interface->fBindFramebuffer = StubGLBindFramebuffer; interface->fBindRenderbuffer = StubGLBindRenderbuffer; interface->fCheckFramebufferStatus = StubGLCheckFramebufferStatus; interface->fDeleteFramebuffers = StubGLDeleteFramebuffers; interface->fDeleteRenderbuffers = StubGLDeleteRenderbuffers; interface->fFramebufferRenderbuffer = StubGLFramebufferRenderbuffer; interface->fFramebufferTexture2D = StubGLFramebufferTexture2D; interface->fFramebufferTexture2DMultisample = StubGLFramebufferTexture2DMultisample; interface->fGenFramebuffers = StubGLGenFramebuffers; interface->fGenRenderbuffers = StubGLGenRenderbuffers; interface->fGetFramebufferAttachmentParameteriv = StubGLGetFramebufferAttachmentParameteriv; interface->fGetRenderbufferParameteriv = StubGLGetRenderbufferParameteriv; interface->fRenderbufferStorage = StubGLRenderbufferStorage; interface->fRenderbufferStorageMultisample = StubGLRenderbufferStorageMultisample; interface->fBlitFramebuffer = StubGLBlitFramebuffer; interface->fMapBuffer = StubGLMapBuffer; interface->fUnmapBuffer = StubGLUnmapBuffer; interface->fBindFragDataLocationIndexed = StubGLBindFragDataLocationIndexed; return interface; } } // namespace gfx
bsd-3-clause
arivera12/cbooks
plugins/system/t3/base-bs3/html/com_users/reset/default.php
1552
<?php /** * @package Joomla.Site * @subpackage com_users * * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; JHtml::_('behavior.keepalive'); if(version_compare(JVERSION, '3.0', 'lt')){ JHtml::_('behavior.tooltip'); } JHtml::_('behavior.formvalidation'); ?> <div class="reset <?php echo $this->pageclass_sfx?>"> <?php if ($this->params->get('show_page_heading')) : ?> <div class="page-header"> <h1> <?php echo $this->escape($this->params->get('page_heading')); ?> </h1> </div> <?php endif; ?> <form id="user-registration" action="<?php echo JRoute::_('index.php?option=com_users&task=reset.request'); ?>" method="post" class="form-validate form-horizontal"> <?php foreach ($this->form->getFieldsets() as $fieldset): ?> <p><?php echo JText::_($fieldset->label); ?></p> <fieldset> <?php foreach ($this->form->getFieldset($fieldset->name) as $name => $field): ?> <div class="form-group"> <div class="col-sm-3 control-label"> <?php echo $field->label; ?> </div> <div class="col-sm-9"> <?php echo $field->input; ?> </div> </div> <?php endforeach; ?> </fieldset> <?php endforeach; ?> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-primary validate"><?php echo JText::_('JSUBMIT'); ?></button> <?php echo JHtml::_('form.token'); ?> </div> </div> </form> </div>
mit
Icedroid/yii2-web
common/behaviors/FileStorageLogBehavior.php
1846
<?php namespace common\behaviors; use League\Flysystem\File; use Yii; use yii\base\Behavior; use trntv\filekit\Storage; use common\models\FileStorageItem; use yii\base\InvalidConfigException; /** * Class FileStorageLogBehavior * @package common\behaviors * @author Eugene Terentev <[email protected]> */ class FileStorageLogBehavior extends Behavior { public $component; public function events() { return [ Storage::EVENT_AFTER_SAVE => 'afterSave', Storage::EVENT_AFTER_DELETE => 'afterDelete' ]; } /** * @param $event \trntv\filekit\events\StorageEvent */ public function afterSave($event) { $file = new File($event->filesystem, $event->path); $model = new FileStorageItem(); $model->component = $this->component; $model->path = $file->getPath(); $model->base_url = $this->getStorage()->baseUrl; $model->size = $file->getSize(); $model->type = $file->getMimeType(); $model->name = pathinfo($file->getPath(), PATHINFO_FILENAME); if (Yii::$app->request->getIsConsoleRequest() === false) { $model->upload_ip = Yii::$app->request->getUserIP(); } $model->save(false); } /** * @param $event \trntv\filekit\events\StorageEvent */ public function afterDelete($event) { FileStorageItem::deleteAll([ 'component' => $this->component, 'path' => $event->path ]); } /** * @return \trntv\filekit\Storage * @throws \yii\base\InvalidConfigException */ public function getStorage() { if ($this->component === null) { throw new InvalidConfigException('Storage component name must be set'); } return Yii::$app->get($this->component); } }
bsd-3-clause
CodeCorp/Arpiano
node_modules/engine.io/lib/socket.js
11156
/** * Module dependencies. */ var EventEmitter = require('events').EventEmitter; var debug = require('debug')('engine:socket'); /** * Module exports. */ module.exports = Socket; /** * Client class (abstract). * * @api private */ function Socket (id, server, transport, req) { this.id = id; this.server = server; this.upgrading = false; this.upgraded = false; this.readyState = 'opening'; this.writeBuffer = []; this.packetsFn = []; this.sentCallbackFn = []; this.cleanupFn = []; this.request = req; // Cache IP since it might not be in the req later this.remoteAddress = req.connection.remoteAddress; this.checkIntervalTimer = null; this.upgradeTimeoutTimer = null; this.pingTimeoutTimer = null; this.setTransport(transport); this.onOpen(); } /** * Inherits from EventEmitter. */ Socket.prototype.__proto__ = EventEmitter.prototype; /** * Called upon transport considered open. * * @api private */ Socket.prototype.onOpen = function () { this.readyState = 'open'; // sends an `open` packet this.transport.sid = this.id; this.sendPacket('open', JSON.stringify({ sid: this.id , upgrades: this.getAvailableUpgrades() , pingInterval: this.server.pingInterval , pingTimeout: this.server.pingTimeout })); this.emit('open'); this.setPingTimeout(); }; /** * Called upon transport packet. * * @param {Object} packet * @api private */ Socket.prototype.onPacket = function (packet) { if ('open' == this.readyState) { // export packet event debug('packet'); this.emit('packet', packet); // Reset ping timeout on any packet, incoming data is a good sign of // other side's liveness this.setPingTimeout(); switch (packet.type) { case 'ping': debug('got ping'); this.sendPacket('pong'); this.emit('heartbeat'); break; case 'error': this.onClose('parse error'); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); break; } } else { debug('packet received with closed socket'); } }; /** * Called upon transport error. * * @param {Error} error object * @api private */ Socket.prototype.onError = function (err) { debug('transport error'); this.onClose('transport error', err); }; /** * Sets and resets ping timeout timer based on client pings. * * @api private */ Socket.prototype.setPingTimeout = function () { var self = this; clearTimeout(self.pingTimeoutTimer); self.pingTimeoutTimer = setTimeout(function () { self.onClose('ping timeout'); }, self.server.pingInterval + self.server.pingTimeout); }; /** * Attaches handlers for the given transport. * * @param {Transport} transport * @api private */ Socket.prototype.setTransport = function (transport) { var onError = this.onError.bind(this); var onPacket = this.onPacket.bind(this); var flush = this.flush.bind(this); var onClose = this.onClose.bind(this, 'transport close'); this.transport = transport; this.transport.once('error', onError); this.transport.on('packet', onPacket); this.transport.on('drain', flush); this.transport.once('close', onClose); //this function will manage packet events (also message callbacks) this.setupSendCallback(); this.cleanupFn.push(function() { transport.removeListener('error', onError); transport.removeListener('packet', onPacket); transport.removeListener('drain', flush); transport.removeListener('close', onClose); }); }; /** * Upgrades socket to the given transport * * @param {Transport} transport * @api private */ Socket.prototype.maybeUpgrade = function (transport) { debug('might upgrade socket transport from "%s" to "%s"' , this.transport.name, transport.name); this.upgrading = true; var self = this; // set transport upgrade timer self.upgradeTimeoutTimer = setTimeout(function () { debug('client did not complete upgrade - closing transport'); cleanup(); if ('open' == transport.readyState) { transport.close(); } }, this.server.upgradeTimeout); function onPacket(packet){ if ('ping' == packet.type && 'probe' == packet.data) { transport.send([{ type: 'pong', data: 'probe' }]); self.emit('upgrading', transport); clearInterval(self.checkIntervalTimer); self.checkIntervalTimer = setInterval(check, 100); } else if ('upgrade' == packet.type && self.readyState != 'closed') { debug('got upgrade packet - upgrading'); cleanup(); self.transport.discard(); self.upgraded = true; self.clearTransport(); self.setTransport(transport); self.emit('upgrade', transport); self.setPingTimeout(); self.flush(); if (self.readyState == 'closing') { transport.close(function () { self.onClose('forced close'); }); } } else { cleanup(); transport.close(); } } // we force a polling cycle to ensure a fast upgrade function check(){ if ('polling' == self.transport.name && self.transport.writable) { debug('writing a noop packet to polling for fast upgrade'); self.transport.send([{ type: 'noop' }]); } } function cleanup() { self.upgrading = false; clearInterval(self.checkIntervalTimer); self.checkIntervalTimer = null; clearTimeout(self.upgradeTimeoutTimer); self.upgradeTimeoutTimer = null; transport.removeListener('packet', onPacket); transport.removeListener('close', onTransportClose); transport.removeListener('error', onError); self.removeListener('close', onClose); } function onError(err) { debug('client did not complete upgrade - %s', err); cleanup(); transport.close(); transport = null; } function onTransportClose(){ onError("transport closed"); } function onClose() { onError("socket closed"); } transport.on('packet', onPacket); transport.once('close', onTransportClose); transport.once('error', onError); self.once('close', onClose); }; /** * Clears listeners and timers associated with current transport. * * @api private */ Socket.prototype.clearTransport = function () { var cleanup; while (cleanup = this.cleanupFn.shift()) cleanup(); // silence further transport errors and prevent uncaught exceptions this.transport.on('error', function(){ debug('error triggered by discarded transport'); }); // ensure transport won't stay open this.transport.close(); clearTimeout(this.pingTimeoutTimer); }; /** * Called upon transport considered closed. * Possible reasons: `ping timeout`, `client error`, `parse error`, * `transport error`, `server close`, `transport close` */ Socket.prototype.onClose = function (reason, description) { if ('closed' != this.readyState) { this.readyState = 'closed'; clearTimeout(this.pingTimeoutTimer); clearInterval(this.checkIntervalTimer); this.checkIntervalTimer = null; clearTimeout(this.upgradeTimeoutTimer); var self = this; // clean writeBuffer in next tick, so developers can still // grab the writeBuffer on 'close' event process.nextTick(function() { self.writeBuffer = []; }); this.packetsFn = []; this.sentCallbackFn = []; this.clearTransport(); this.emit('close', reason, description); } }; /** * Setup and manage send callback * * @api private */ Socket.prototype.setupSendCallback = function () { var self = this; this.transport.on('drain', onDrain); this.cleanupFn.push(function() { self.transport.removeListener('drain', onDrain); }); //the message was sent successfully, execute the callback function onDrain() { if (self.sentCallbackFn.length > 0) { var seqFn = self.sentCallbackFn.splice(0,1)[0]; if ('function' == typeof seqFn) { debug('executing send callback'); seqFn(self.transport); } else if (Array.isArray(seqFn)) { debug('executing batch send callback'); for (var l = seqFn.length, i = 0; i < l; i++) { if ('function' == typeof seqFn[i]) { seqFn[i](self.transport); } } } } } }; /** * Sends a message packet. * * @param {String} message * @param {Object} options * @param {Function} callback * @return {Socket} for chaining * @api public */ Socket.prototype.send = Socket.prototype.write = function(data, options, callback){ this.sendPacket('message', data, options, callback); return this; }; /** * Sends a packet. * * @param {String} packet type * @param {String} optional, data * @param {Object} options * @api private */ Socket.prototype.sendPacket = function (type, data, options, callback) { if ('function' == typeof options) { callback = options; options = null; } options = options || {}; options.compress = false !== options.compress; if ('closing' != this.readyState) { debug('sending packet "%s" (%s)', type, data); var packet = { type: type, options: options }; if (data) packet.data = data; // exports packetCreate event this.emit('packetCreate', packet); this.writeBuffer.push(packet); //add send callback to object this.packetsFn.push(callback); this.flush(); } }; /** * Attempts to flush the packets buffer. * * @api private */ Socket.prototype.flush = function () { if ('closed' != this.readyState && this.transport.writable && this.writeBuffer.length) { debug('flushing buffer to transport'); this.emit('flush', this.writeBuffer); this.server.emit('flush', this, this.writeBuffer); var wbuf = this.writeBuffer; this.writeBuffer = []; if (!this.transport.supportsFraming) { this.sentCallbackFn.push(this.packetsFn); } else { this.sentCallbackFn.push.apply(this.sentCallbackFn, this.packetsFn); } this.packetsFn = []; this.transport.send(wbuf); this.emit('drain'); this.server.emit('drain', this); } }; /** * Get available upgrades for this socket. * * @api private */ Socket.prototype.getAvailableUpgrades = function () { var availableUpgrades = []; var allUpgrades = this.server.upgrades(this.transport.name); for (var i = 0, l = allUpgrades.length; i < l; ++i) { var upg = allUpgrades[i]; if (this.server.transports.indexOf(upg) != -1) { availableUpgrades.push(upg); } } return availableUpgrades; }; /** * Closes the socket and underlying transport. * * @param {Boolean} optional, discard * @return {Socket} for chaining * @api public */ Socket.prototype.close = function (discard) { if ('open' != this.readyState) return; this.readyState = 'closing'; if (this.writeBuffer.length) { this.once('drain', this.closeTransport.bind(this, discard)); return; } this.closeTransport(discard); }; /** * Closes the underlying transport. * * @param {Boolean} discard * @api private */ Socket.prototype.closeTransport = function (discard) { if (discard) this.transport.discard(); this.transport.close(this.onClose.bind(this, 'forced close')); };
mit
sean-johnson/sean-johnson.github.io
node_modules/rxjs/internal/operators/elementAt.js
900
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError"); var filter_1 = require("./filter"); var throwIfEmpty_1 = require("./throwIfEmpty"); var defaultIfEmpty_1 = require("./defaultIfEmpty"); var take_1 = require("./take"); function elementAt(index, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError(); } var hasDefaultValue = arguments.length >= 2; return function (source) { return source.pipe(filter_1.filter(function (v, i) { return i === index; }), take_1.take(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError(); })); }; } exports.elementAt = elementAt; //# sourceMappingURL=elementAt.js.map
mit
lvalenzuela/wheelie
content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js
14606
/*! * Variations Plugin */ ;(function ( $, window, document, undefined ) { $.fn.wc_variation_form = function () { $.fn.wc_variation_form.find_matching_variations = function( product_variations, settings ) { var matching = []; for ( var i = 0; i < product_variations.length; i++ ) { var variation = product_variations[i]; var variation_id = variation.variation_id; if ( $.fn.wc_variation_form.variations_match( variation.attributes, settings ) ) { matching.push( variation ); } } return matching; }; $.fn.wc_variation_form.variations_match = function( attrs1, attrs2 ) { var match = true; for ( var attr_name in attrs1 ) { if ( attrs1.hasOwnProperty( attr_name ) ) { var val1 = attrs1[ attr_name ]; var val2 = attrs2[ attr_name ]; if ( val1 !== undefined && val2 !== undefined && val1.length !== 0 && val2.length !== 0 && val1 !== val2 ) { match = false; } } } return match; }; // Unbind any existing events this.unbind( 'check_variations update_variation_values found_variation' ); this.find( '.reset_variations' ).unbind( 'click' ); this.find( '.variations select' ).unbind( 'change focusin' ); // Bind events $form = this // On clicking the reset variation button .on( 'click', '.reset_variations', function( event ) { $( this ).closest( '.variations_form' ).find( '.variations select' ).val( '' ).change(); var $sku = $( this ).closest( '.product' ).find( '.sku' ), $weight = $( this ).closest( '.product' ).find( '.product_weight' ), $dimensions = $( this ).closest( '.product' ).find( '.product_dimensions' ); if ( $sku.attr( 'data-o_sku' ) ) $sku.text( $sku.attr( 'data-o_sku' ) ); if ( $weight.attr( 'data-o_weight' ) ) $weight.text( $weight.attr( 'data-o_weight' ) ); if ( $dimensions.attr( 'data-o_dimensions' ) ) $dimensions.text( $dimensions.attr( 'data-o_dimensions' ) ); return false; } ) // Upon changing an option .on( 'change', '.variations select', function( event ) { $variation_form = $( this ).closest( '.variations_form' ); if ( $variation_form.find( 'input.variation_id' ).length > 0 ) $variation_form.find( 'input.variation_id' ).val( '' ).change(); else $variation_form.find( 'input[name=variation_id]' ).val( '' ).change(); $variation_form .trigger( 'woocommerce_variation_select_change' ) .trigger( 'check_variations', [ '', false ] ); $( this ).blur(); if( $().uniform && $.isFunction( $.uniform.update ) ) { $.uniform.update(); } // Custom event for when variation selection has been changed $variation_form.trigger( 'woocommerce_variation_has_changed' ); } ) // Upon gaining focus .on( 'focusin touchstart', '.variations select', function( event ) { $variation_form = $( this ).closest( '.variations_form' ); // Get attribute name from data-attribute_name, or from input name if it doesn't exist if ( typeof( $( this ).data( 'attribute_name' ) ) != 'undefined' ) attribute_name = $( this ).data( 'attribute_name' ); else attribute_name = $( this ).attr( 'name' ); $variation_form .trigger( 'woocommerce_variation_select_focusin' ) .trigger( 'check_variations', [ attribute_name, true ] ); } ) // Check variations .on( 'check_variations', function( event, exclude, focus ) { var all_set = true, any_set = false, showing_variation = false, current_settings = {}, $variation_form = $( this ), $reset_variations = $variation_form.find( '.reset_variations' ); $variation_form.find( '.variations select' ).each( function() { // Get attribute name from data-attribute_name, or from input name if it doesn't exist if ( typeof( $( this ).data( 'attribute_name' ) ) != 'undefined' ) attribute_name = $( this ).data( 'attribute_name' ); else attribute_name = $( this ).attr( 'name' ); if ( $( this ).val().length === 0 ) { all_set = false; } else { any_set = true; } if ( exclude && attribute_name === exclude ) { all_set = false; current_settings[ attribute_name ] = ''; } else { // Encode entities value = $( this ).val(); // Add to settings array current_settings[ attribute_name ] = value; } }); var product_id = parseInt( $variation_form.data( 'product_id' ) ), all_variations = $variation_form.data( 'product_variations' ); // Fallback to window property if not set - backwards compat if ( ! all_variations ) all_variations = window.product_variations.product_id; if ( ! all_variations ) all_variations = window.product_variations; if ( ! all_variations ) all_variations = window['product_variations_' + product_id ]; var matching_variations = $.fn.wc_variation_form.find_matching_variations( all_variations, current_settings ); if ( all_set ) { var variation = matching_variations.shift(); if ( variation ) { // Found - set ID // Get variation input by class, or by input name if class doesn't exist if ( $variation_form.find( 'input.variation_id' ).length > 0 ) $variation_input = $variation_form.find( 'input.variation_id' ); else $variation_input = $variation_form.find( 'input[name=variation_id]' ); // Set ID $variation_input .val( variation.variation_id ) .change(); $variation_form.trigger( 'found_variation', [ variation ] ); } else { // Nothing found - reset fields $variation_form.find( '.variations select' ).val( '' ); if ( ! focus ) $variation_form.trigger( 'reset_image' ); alert( wc_add_to_cart_variation_params.i18n_no_matching_variations_text ); } } else { $variation_form.trigger( 'update_variation_values', [ matching_variations ] ); if ( ! focus ) $variation_form.trigger( 'reset_image' ); if ( ! exclude ) { $variation_form.find( '.single_variation_wrap' ).slideUp( 200 ).trigger( 'hide_variation' ); } } if ( any_set ) { if ( $reset_variations.css( 'visibility' ) === 'hidden' ) $reset_variations.css( 'visibility', 'visible' ).hide().fadeIn(); } else { $reset_variations.css( 'visibility', 'hidden' ); } } ) // Reset product image .on( 'reset_image', function( event ) { var $product = $(this).closest( '.product' ), $product_img = $product.find( 'div.images img:eq(0)' ), $product_link = $product.find( 'div.images a.zoom:eq(0)' ), o_src = $product_img.attr( 'data-o_src' ), o_title = $product_img.attr( 'data-o_title' ), o_alt = $product_img.attr( 'data-o_alt' ), o_href = $product_link.attr( 'data-o_href' ); if ( o_src !== undefined ) { $product_img .attr( 'src', o_src ); } if ( o_href !== undefined ) { $product_link .attr( 'href', o_href ); } if ( o_title !== undefined ) { $product_img .attr( 'title', o_title ); $product_link .attr( 'title', o_title ); } if ( o_alt !== undefined ) { $product_img .attr( 'alt', o_alt ); } } ) // Disable option fields that are unavaiable for current set of attributes .on( 'update_variation_values', function( event, variations ) { $variation_form = $( this ).closest( '.variations_form' ); // Loop through selects and disable/enable options based on selections $variation_form.find( '.variations select' ).each( function( index, el ) { current_attr_select = $( el ); // Reset options if ( ! current_attr_select.data( 'attribute_options' ) ) current_attr_select.data( 'attribute_options', current_attr_select.find( 'option:gt(0)' ).get() ); current_attr_select.find( 'option:gt(0)' ).remove(); current_attr_select.append( current_attr_select.data( 'attribute_options' ) ); current_attr_select.find( 'option:gt(0)' ).removeClass( 'attached' ); current_attr_select.find( 'option:gt(0)' ).removeClass( 'enabled' ); current_attr_select.find( 'option:gt(0)' ).removeAttr( 'disabled' ); // Get name from data-attribute_name, or from input name if it doesn't exist if ( typeof( current_attr_select.data( 'attribute_name' ) ) != 'undefined' ) current_attr_name = current_attr_select.data( 'attribute_name' ); else current_attr_name = current_attr_select.attr( 'name' ); // Loop through variations for ( var num in variations ) { if ( typeof( variations[ num ] ) != 'undefined' ) { var attributes = variations[ num ].attributes; for ( var attr_name in attributes ) { if ( attributes.hasOwnProperty( attr_name ) ) { var attr_val = attributes[ attr_name ]; if ( attr_name == current_attr_name ) { if ( variations[ num ].variation_is_active ) variation_active = 'enabled'; else variation_active = ''; if ( attr_val ) { // Decode entities attr_val = $( '<div/>' ).html( attr_val ).text(); // Add slashes attr_val = attr_val.replace( /'/g, "\\'" ); attr_val = attr_val.replace( /"/g, "\\\"" ); // Compare the meerkat current_attr_select.find( 'option[value="' + attr_val + '"]' ).addClass( 'attached ' + variation_active ); } else { current_attr_select.find( 'option:gt(0)' ).addClass( 'attached ' + variation_active ); } } } } } } // Detach unattached current_attr_select.find( 'option:gt(0):not(.attached)' ).remove(); // Grey out disabled current_attr_select.find( 'option:gt(0):not(.enabled)' ).attr( 'disabled', 'disabled' ); }); // Custom event for when variations have been updated $variation_form.trigger( 'woocommerce_update_variation_values' ); } ) // Show single variation details (price, stock, image) .on( 'found_variation', function( event, variation ) { var $variation_form = $( this ), $product = $( this ).closest( '.product' ), $product_img = $product.find( 'div.images img:eq(0)' ), $product_link = $product.find( 'div.images a.zoom:eq(0)' ), o_src = $product_img.attr( 'data-o_src' ), o_title = $product_img.attr( 'data-o_title' ), o_alt = $product_img.attr( 'data-o_alt' ), o_href = $product_link.attr( 'data-o_href' ), variation_image = variation.image_src, variation_link = variation.image_link, variation_title = variation.image_title, variation_alt = variation.image_alt; $variation_form.find( '.variations_button' ).show(); $variation_form.find( '.single_variation' ).html( variation.price_html + variation.availability_html ); if ( o_src === undefined ) { o_src = ( ! $product_img.attr( 'src' ) ) ? '' : $product_img.attr( 'src' ); $product_img.attr( 'data-o_src', o_src ); } if ( o_href === undefined ) { o_href = ( ! $product_link.attr( 'href' ) ) ? '' : $product_link.attr( 'href' ); $product_link.attr( 'data-o_href', o_href ); } if ( o_title === undefined ) { o_title = ( ! $product_img.attr( 'title' ) ) ? '' : $product_img.attr( 'title' ); $product_img.attr( 'data-o_title', o_title ); } if ( o_alt === undefined ) { o_alt = ( ! $product_img.attr( 'alt' ) ) ? '' : $product_img.attr( 'alt' ); $product_img.attr( 'data-o_alt', o_alt ); } if ( variation_image && variation_image.length > 1 ) { $product_img .attr( 'src', variation_image ) .attr( 'alt', variation_alt ) .attr( 'title', variation_title ); $product_link .attr( 'href', variation_link ) .attr( 'title', variation_title ); } else { $product_img .attr( 'src', o_src ) .attr( 'alt', o_alt ) .attr( 'title', o_title ); $product_link .attr( 'href', o_href ) .attr( 'title', o_title ); } var $single_variation_wrap = $variation_form.find( '.single_variation_wrap' ), $sku = $product.find( '.product_meta' ).find( '.sku' ), $weight = $product.find( '.product_weight' ), $dimensions = $product.find( '.product_dimensions' ); if ( ! $sku.attr( 'data-o_sku' ) ) $sku.attr( 'data-o_sku', $sku.text() ); if ( ! $weight.attr( 'data-o_weight' ) ) $weight.attr( 'data-o_weight', $weight.text() ); if ( ! $dimensions.attr( 'data-o_dimensions' ) ) $dimensions.attr( 'data-o_dimensions', $dimensions.text() ); if ( variation.sku ) { $sku.text( variation.sku ); } else { $sku.text( $sku.attr( 'data-o_sku' ) ); } if ( variation.weight ) { $weight.text( variation.weight ); } else { $weight.text( $weight.attr( 'data-o_weight' ) ); } if ( variation.dimensions ) { $dimensions.text( variation.dimensions ); } else { $dimensions.text( $dimensions.attr( 'data-o_dimensions' ) ); } $single_variation_wrap.find( '.quantity' ).show(); if ( ! variation.is_purchasable || ! variation.is_in_stock || ! variation.variation_is_visible ) { $variation_form.find( '.variations_button' ).hide(); } if ( ! variation.variation_is_visible ) { $variation_form.find( '.single_variation' ).html( '<p>' + wc_add_to_cart_variation_params.i18n_unavailable_text + '</p>' ); } if ( variation.min_qty !== '' ) $single_variation_wrap.find( '.quantity input.qty' ).attr( 'min', variation.min_qty ).val( variation.min_qty ); else $single_variation_wrap.find( '.quantity input.qty' ).removeAttr( 'min' ); if ( variation.max_qty !== '' ) $single_variation_wrap.find( '.quantity input.qty' ).attr( 'max', variation.max_qty ); else $single_variation_wrap.find( '.quantity input.qty' ).removeAttr( 'max' ); if ( variation.is_sold_individually === 'yes' ) { $single_variation_wrap.find( '.quantity input.qty' ).val( '1' ); $single_variation_wrap.find( '.quantity' ).hide(); } $single_variation_wrap.slideDown( 200 ).trigger( 'show_variation', [ variation ] ); }); $form.trigger( 'wc_variation_form' ); return $form; }; $( function() { // wc_add_to_cart_variation_params is required to continue, ensure the object exists if ( typeof wc_add_to_cart_variation_params === 'undefined' ) return false; $( '.variations_form' ).wc_variation_form(); $( '.variations_form .variations select' ).change(); }); })( jQuery, window, document );
mit
perfectphase/coreclr
tests/src/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26863/b26863.cs
2039
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /* JE1 JR1 C(null) I1 S(null) G0 ..\regalloc.cpp, Line 8037 : Assertion failed 'passes <= 4' in 'DefaultNamespace.Obj.Static3():ref' Running time 0.310 sec JE1 JR1 C(null) I0 S(null) G0 Running time 1.693 sec JE0 JR0 C(null) I0 S(null) G0 Running time 0.921 sec */ namespace Test { using System; class Obj { bool[] Method1() { return null; } uint Method2(bool param1) { return 0; } int Method3() { return 0; } bool Method4() { return false; } static uint[] Recurse(float[] param1, bool param2, uint[] param3) { return null; } static double[] Static2() { return null; } static float[] Static3() { Obj obj = new Obj(); do { do { Recurse(new float[4], new Obj().Method1()[2], Recurse(new float[4], obj.Method1()[2], Recurse(new float[4], true, Recurse(new float[4], obj.Method3() != Recurse(new float[4], new Obj().Method4(), Recurse(new float[4], false, null))[2], Recurse(new float[4], new Obj().Method1()[2], Recurse(new float[4], obj.Method1()[2], Recurse(new float[4], obj.Method1()[2], Recurse(new float[4], true, null)))))))); obj.Method1(); } while (new Random().Next(16) != 5 && new Obj().Method4()); obj.Method1(); } while (new Random().Next(16) != 5 && new Obj().Method4()); return new float[4]; } static int Main() { try { Static3(); } catch (Exception) { } return 100; } } }
mit
ayuso2013/drh-visual-odometry
src/OpticalFlow/Properties/Resources.Designer.cs
2500
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace OpticalFlow.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OpticalFlow.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
gpl-3.0
blueskybcl/log4net
src/Util/TypeConverters/IConvertFrom.cs
2096
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; namespace log4net.Util.TypeConverters { /// <summary> /// Interface supported by type converters /// </summary> /// <remarks> /// <para> /// This interface supports conversion from arbitrary types /// to a single target type. See <see cref="TypeConverterAttribute"/>. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public interface IConvertFrom { /// <summary> /// Can the source type be converted to the type supported by this object /// </summary> /// <param name="sourceType">the type to convert</param> /// <returns>true if the conversion is possible</returns> /// <remarks> /// <para> /// Test if the <paramref name="sourceType"/> can be converted to the /// type supported by this converter. /// </para> /// </remarks> bool CanConvertFrom(Type sourceType); /// <summary> /// Convert the source object to the type supported by this object /// </summary> /// <param name="source">the object to convert</param> /// <returns>the converted object</returns> /// <remarks> /// <para> /// Converts the <paramref name="source"/> to the type supported /// by this converter. /// </para> /// </remarks> object ConvertFrom(object source); } }
apache-2.0
BrianBland/distribution
vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go
3654
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ctxhttp provides helper functions for performing context-aware HTTP requests. package ctxhttp import ( "io" "net/http" "net/url" "strings" "golang.org/x/net/context" ) func nop() {} var ( testHookContextDoneBeforeHeaders = nop testHookDoReturned = nop testHookDidBodyClose = nop ) // Do sends an HTTP request with the provided http.Client and returns an HTTP response. // If the client is nil, http.DefaultClient is used. // If the context is canceled or times out, ctx.Err() will be returned. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { if client == nil { client = http.DefaultClient } // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go. cancel := canceler(client, req) type responseAndError struct { resp *http.Response err error } result := make(chan responseAndError, 1) // Make local copies of test hooks closed over by goroutines below. // Prevents data races in tests. testHookDoReturned := testHookDoReturned testHookDidBodyClose := testHookDidBodyClose go func() { resp, err := client.Do(req) testHookDoReturned() result <- responseAndError{resp, err} }() var resp *http.Response select { case <-ctx.Done(): testHookContextDoneBeforeHeaders() cancel() // Clean up after the goroutine calling client.Do: go func() { if r := <-result; r.resp != nil { testHookDidBodyClose() r.resp.Body.Close() } }() return nil, ctx.Err() case r := <-result: var err error resp, err = r.resp, r.err if err != nil { return resp, err } } c := make(chan struct{}) go func() { select { case <-ctx.Done(): cancel() case <-c: // The response's Body is closed. } }() resp.Body = &notifyingReader{resp.Body, c} return resp, nil } // Get issues a GET request via the Do function. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } return Do(ctx, client, req) } // Head issues a HEAD request via the Do function. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { req, err := http.NewRequest("HEAD", url, nil) if err != nil { return nil, err } return Do(ctx, client, req) } // Post issues a POST request via the Do function. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest("POST", url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", bodyType) return Do(ctx, client, req) } // PostForm issues a POST request via the Do function. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) } // notifyingReader is an io.ReadCloser that closes the notify channel after // Close is called or a Read fails on the underlying ReadCloser. type notifyingReader struct { io.ReadCloser notify chan<- struct{} } func (r *notifyingReader) Read(p []byte) (int, error) { n, err := r.ReadCloser.Read(p) if err != nil && r.notify != nil { close(r.notify) r.notify = nil } return n, err } func (r *notifyingReader) Close() error { err := r.ReadCloser.Close() if r.notify != nil { close(r.notify) r.notify = nil } return err }
apache-2.0
devinbalkind/eden
static/scripts/gis/gxp/plugins/StyleWriter.js
3060
/** * Copyright (c) 2008-2011 The Open Planning Project * * Published under the GPL license. * See https://github.com/opengeo/gxp/raw/master/license.txt for the full text * of the license. */ /** api: (define) * module = gxp.plugins * class = StyleWriter * base_link = `Ext.util.Observable <http://extjs.com/deploy/dev/docs/?class=Ext.util.Observable>`_ */ Ext.namespace("gxp.plugins"); /** api: constructor * .. class:: StyleWriter(config) * * Base class for plugins that plug into :class:`gxp.WMSStylesDialog` or * similar classes that have a ``layerRecord`` and a ``stylesStore`` with * a ``userStyle`` field. The plugin provides a save method, which will * persist style changes from the ``stylesStore`` to the server and * associate them with the layer referenced in the target's * ``layerRecord``. */ gxp.plugins.StyleWriter = Ext.extend(Ext.util.Observable, { /** private: property[target] * ``Object`` * The object that this plugin is plugged into. */ /** api: property[deletedStyles] * ``Array(String)`` style names of styles from the server that were * deleted and have to be removed from the server */ deletedStyles: null, /** private: method[constructor] */ constructor: function(config) { this.initialConfig = config; Ext.apply(this, config); this.deletedStyles = []; gxp.plugins.StyleWriter.superclass.constructor.apply(this, arguments); }, /** private: method[init] * :arg target: ``Object`` The object initializing this plugin. */ init: function(target) { this.target = target; // keep track of removed style records, because Ext.Store does not. target.stylesStore.on({ "remove": function(store, record, index) { var styleName = record.get("name"); // only proceed if the style comes from the server record.get("name") === styleName && this.deletedStyles.push(styleName); }, scope: this }); target.on({ "beforesaved": this.write, scope: this }); }, /** private: method[write] * :arg target: :class:`gxp.WMSStylesDialog` * :arg options: ``Object`` * * Listener for the target's ``beforesaved`` event. Saves the styles of * the target's ``layerRecord``. To be implemented by subclasses. * Subclasses should make sure to commit changes to the target's * stylesStore. It is the responsibility of the application to update * displayed layers with the new style set in the target's * ``selectedStyle`` record. */ write: function(target, options) { target.stylesStore.commitChanges(); target.fireEvent("saved", target, target.selectedStyle.get("name")); } });
mit
Quiark/go-ipfs
p2p/net/swarm/swarm_stream.go
1322
package swarm import ( inet "github.com/ipfs/go-ipfs/p2p/net" ps "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-peerstream" ) // a Stream is a wrapper around a ps.Stream that exposes a way to get // our Conn and Swarm (instead of just the ps.Conn and ps.Swarm) type Stream ps.Stream // Stream returns the underlying peerstream.Stream func (s *Stream) Stream() *ps.Stream { return (*ps.Stream)(s) } // Conn returns the Conn associated with this Stream, as an inet.Conn func (s *Stream) Conn() inet.Conn { return s.SwarmConn() } // SwarmConn returns the Conn associated with this Stream, as a *Conn func (s *Stream) SwarmConn() *Conn { return (*Conn)(s.Stream().Conn()) } // Read reads bytes from a stream. func (s *Stream) Read(p []byte) (n int, err error) { return s.Stream().Read(p) } // Write writes bytes to a stream, flushing for each call. func (s *Stream) Write(p []byte) (n int, err error) { return s.Stream().Write(p) } // Close closes the stream, indicating this side is finished // with the stream. func (s *Stream) Close() error { return s.Stream().Close() } func wrapStream(pss *ps.Stream) *Stream { return (*Stream)(pss) } func wrapStreams(st []*ps.Stream) []*Stream { out := make([]*Stream, len(st)) for i, s := range st { out[i] = wrapStream(s) } return out }
mit
mwhitlaw/openemr
contrib/forms/phone_exam/print.php
543
<?php include_once("../../globals.php"); include_once("../../../library/api.inc"); formHeader("Phone Exam"); ?> <html> <head> <?php html_header_show();?> <title>New Patient Encounter</title> <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css"> </head> <body class="body_top"> <br><br> <?php $row = formFetch('form_phone_exam', $_GET['id']); echo $row['notes']; ?> <br><br> <a href="<?php echo $GLOBALS['form_exit_url']; ?>" onclick="top.restoreSession()">Done</a> </body> <?php formFooter(); ?>
gpl-2.0
martinwoodward/coreclr
src/utilcode/securityutil.cpp
13965
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "stdafx.h" #include "securityutil.h" #include "ex.h" #include "securitywrapper.h" // This is defined in ipcmanagerinterface.h, but including that is problematic at the moment... // These are the right that we will give to the global section and global events used // in communicating between debugger and debugee // // SECTION_ALL_ACCESS is needed for the IPC block. Unfortunately, we DACL our events and // IPC block identically. Or this particular right does not need to bleed into here. // #ifndef CLR_IPC_GENERIC_RIGHT #define CLR_IPC_GENERIC_RIGHT (GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | STANDARD_RIGHTS_ALL | SECTION_ALL_ACCESS) #endif //***************************************************************** // static helper function // // helper to form ACL that contains AllowedACE of users of current // process and target process // // [IN] pid - target process id // [OUT] ppACL - ACL for the process // // Clean up - // Caller remember to call FreeACL() on *ppACL //***************************************************************** HRESULT SecurityUtil::GetACLOfPid(DWORD pid, PACL *ppACL) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; HRESULT hr = S_OK; _ASSERTE(ppACL); *ppACL = NULL; PSID pCurrentProcessSid = NULL; PSID pTargetProcessSid = NULL; PSID pTargetProcessAppContainerSid = NULL; DWORD cSid = 0; DWORD dwAclSize = 0; LOG((LF_CORDB, LL_INFO10000, "SecurityUtil::GetACLOfPid on pid : 0x%08x\n", pid)); SidBuffer sidCurrentProcess; SidBuffer sidTargetProcess; SidBuffer sidTargetProcessAppContainer; // Get sid for current process. EX_TRY { sidCurrentProcess.InitFromProcess(GetCurrentProcessId()); // throw on error. pCurrentProcessSid = sidCurrentProcess.GetSid().RawSid(); cSid++; } EX_CATCH { } EX_END_CATCH(RethrowTerminalExceptions); // Get sid for target process. EX_TRY { sidTargetProcess.InitFromProcess(pid); // throws on error. pTargetProcessSid = sidTargetProcess.GetSid().RawSid(); cSid++; } EX_CATCH { } EX_END_CATCH(RethrowTerminalExceptions); //FISHY: what is the scenario where only one of the above calls succeeds? if (cSid == 0) { // failed to get any useful sid. Just return. // need a better error. // hr = E_FAIL; goto exit; } hr = sidTargetProcessAppContainer.InitFromProcessAppContainerSidNoThrow(pid); if (FAILED(hr)) { goto exit; } else if (hr == S_OK) { pTargetProcessAppContainerSid = sidTargetProcessAppContainer.GetSid().RawSid(); cSid++; } else if(hr == S_FALSE) //not an app container, no sid to add { hr = S_OK; // don't leak S_FALSE } LOG((LF_CORDB, LL_INFO10000, "SecurityUtil::GetACLOfPid number of sid : 0x%08x\n", cSid)); // Now allocate space for ACL. First calculate the space is need to hold ACL dwAclSize = sizeof(ACL) + (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * cSid; if (pCurrentProcessSid) { dwAclSize += GetLengthSid(pCurrentProcessSid); } if (pTargetProcessSid) { dwAclSize += GetLengthSid(pTargetProcessSid); } if (pTargetProcessAppContainerSid) { dwAclSize += GetLengthSid(pTargetProcessAppContainerSid); } *ppACL = (PACL) new (nothrow) char[dwAclSize]; if (*ppACL == NULL) { hr = E_OUTOFMEMORY; goto exit; } // Initialize ACL // add each sid to the allowed ace list if (!InitializeAcl(*ppACL, dwAclSize, ACL_REVISION)) { hr = HRESULT_FROM_GetLastError(); goto exit; } if (pCurrentProcessSid) { // add the current process's sid into ACL if we have it if (!AddAccessAllowedAce(*ppACL, ACL_REVISION, CLR_IPC_GENERIC_RIGHT, pCurrentProcessSid)) { hr = HRESULT_FROM_GetLastError(); goto exit; } } if (pTargetProcessSid) { // add the target process's sid into ACL if we have it if (!AddAccessAllowedAce(*ppACL, ACL_REVISION, CLR_IPC_GENERIC_RIGHT, pTargetProcessSid)) { hr = HRESULT_FROM_GetLastError(); goto exit; } } if (pTargetProcessAppContainerSid) { // add the target process's AppContainer's sid into ACL if we have it if (!AddAccessAllowedAce(*ppACL, ACL_REVISION, CLR_IPC_GENERIC_RIGHT, pTargetProcessAppContainerSid)) { hr = HRESULT_FROM_GetLastError(); goto exit; } } // we better to form a valid ACL to return _ASSERTE(IsValidAcl(*ppACL)); exit: if (FAILED(hr) && *ppACL) { delete [] (reinterpret_cast<char*>(ppACL)); } return hr; } // SecurityUtil::GetACLOfPid //***************************************************************** // static helper function // // free the ACL allocated by SecurityUtil::GetACLOfPid // // [IN] pACL - ACL to be freed // //***************************************************************** void SecurityUtil::FreeACL(PACL pACL) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; if (pACL) { delete [] (reinterpret_cast<char*>(pACL)); } } // SecurityUtil::FreeACL //***************************************************************** // constructor // // [IN] pACL - ACL that this instance of SecurityUtil will held on to // //***************************************************************** SecurityUtil::SecurityUtil(PACL pACL) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; m_pACL = pACL; m_pSacl = NULL; m_fInitialized = false; } //***************************************************************** // destructor // // free the ACL that this instance of SecurityUtil helds on to // //***************************************************************** SecurityUtil::~SecurityUtil() { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; FreeACL(m_pACL); FreeACL(m_pSacl); } //***************************************************************** // Initialization function // // form the SecurityDescriptor that will represent the m_pACL // //***************************************************************** HRESULT SecurityUtil::Init() { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; HRESULT hr = S_OK; if (m_pACL) { if (!InitializeSecurityDescriptor(&m_SD, SECURITY_DESCRIPTOR_REVISION)) { hr = HRESULT_FROM_GetLastError(); return hr; } if (!SetSecurityDescriptorDacl(&m_SD, TRUE, m_pACL, FALSE)) { hr = HRESULT_FROM_GetLastError(); return hr; } m_SA.nLength = sizeof(SECURITY_ATTRIBUTES); m_SA.lpSecurityDescriptor = &m_SD; m_SA.bInheritHandle = FALSE; m_fInitialized = true; } return S_OK; } // *************************************************************************** // Initialization functions which will call the normal Init and add a // mandatory label entry to the sacl // // Expects hProcess to be a valid handle to the process which has the desired // mandatory label // *************************************************************************** HRESULT SecurityUtil::Init(HANDLE hProcess) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; HRESULT hr = Init(); if (FAILED(hr)) { return hr; } NewArrayHolder<BYTE> pLabel; hr = GetMandatoryLabelFromProcess(hProcess, &pLabel); if (FAILED(hr)) { return hr; } TOKEN_MANDATORY_LABEL * ptml = (TOKEN_MANDATORY_LABEL *) pLabel.GetValue(); hr = SetSecurityDescriptorMandatoryLabel(ptml->Label.Sid); return hr; } // *************************************************************************** // Given a process, this will put the mandatory label into a buffer and point // ppbLabel at the buffer. // // Caller must free ppbLabel via the array "delete []" operator // *************************************************************************** HRESULT SecurityUtil::GetMandatoryLabelFromProcess(HANDLE hProcess, LPBYTE * ppbLabel) { *ppbLabel = NULL; DWORD dwSize = 0; HandleHolder hToken; DWORD err = 0; if(!OpenProcessToken(hProcess, TOKEN_READ, &hToken)) { return HRESULT_FROM_GetLastError(); } if(!GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS)TokenIntegrityLevel, NULL, 0, &dwSize)) { err = GetLastError(); } // We need to make sure that GetTokenInformation failed in a predictable manner so we know that // dwSize has the correct buffer size in it. if (err != ERROR_INSUFFICIENT_BUFFER || dwSize == 0) { return HRESULT_FROM_WIN32(err); } NewArrayHolder<BYTE> pLabel = new (nothrow) BYTE[dwSize]; if (pLabel == NULL) { return E_OUTOFMEMORY; } if(!GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS)TokenIntegrityLevel, pLabel, dwSize, &dwSize)) { return HRESULT_FROM_GetLastError(); } // Our caller will be freeing the memory so use Extract *ppbLabel = pLabel.Extract(); return S_OK; } //--------------------------------------------------------------------------------------- // // Returns pointer inside the specified mandatory SID to the DWORD representing the // integrity level of the process. This DWORD will be one of the // SECURITY_MANDATORY_*_RID constants. // // Arguments: // psidIntegrityLevelLabel - [in] PSID in which to find the integrity level. // // Return Value: // Pointer to the RID stored in the specified SID. This RID represents the // integrity level of the process // // static DWORD * SecurityUtil::GetIntegrityLevelFromMandatorySID(PSID psidIntegrityLevelLabel) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; return GetSidSubAuthority(psidIntegrityLevelLabel, (*GetSidSubAuthorityCount(psidIntegrityLevelLabel) - 1)); } // Creates a mandatory label ace and sets it to be the entry in the // security descriptor's sacl. This assumes there are no other entries // in the sacl HRESULT SecurityUtil::SetSecurityDescriptorMandatoryLabel(PSID psidIntegrityLevelLabel) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; HRESULT hr; DWORD cbSid = GetLengthSid(psidIntegrityLevelLabel); DWORD cbAceStart = offsetof(SYSTEM_MANDATORY_LABEL_ACE, SidStart); // We are about allocate memory for a ACL and an ACE so we need space for: // 1) the ACL: sizeof(ACL) // 2) the entry: the sid is of variable size, so the SYSTEM_MANDATORY_LABEL_ACE // structure has only the first DWORD of the sid in its definition, to get the // appropriate size we get size without SidStart and add on the actual size of the sid DWORD cbSacl = sizeof(ACL) + cbAceStart + cbSid; NewArrayHolder<BYTE> sacl = new (nothrow) BYTE[cbSacl]; m_pSacl = NULL; if (sacl == NULL) { return E_OUTOFMEMORY; } ZeroMemory(sacl.GetValue(), cbSacl); PACL pSacl = reinterpret_cast<ACL *>(sacl.GetValue()); SYSTEM_MANDATORY_LABEL_ACE * pLabelAce = reinterpret_cast<SYSTEM_MANDATORY_LABEL_ACE *>(sacl.GetValue() + sizeof(ACL)); PSID psid = reinterpret_cast<SID *>(&pLabelAce->SidStart); // Our buffer looks like this now: (not drawn to scale) // sacl pSacl pLabelAce psid // - - // | | // | - - // | | // | | - // | - | // - - DWORD dwIntegrityLevel = *(GetIntegrityLevelFromMandatorySID(psidIntegrityLevelLabel)); if (dwIntegrityLevel >= SECURITY_MANDATORY_MEDIUM_RID) { // No need to set the integrity level unless it's lower than medium return S_OK; } if(!InitializeAcl(pSacl, cbSacl, ACL_REVISION)) { return HRESULT_FROM_GetLastError(); } pSacl->AceCount = 1; pLabelAce->Header.AceType = SYSTEM_MANDATORY_LABEL_ACE_TYPE; pLabelAce->Header.AceSize = WORD(cbAceStart + cbSid); pLabelAce->Mask = SYSTEM_MANDATORY_LABEL_NO_WRITE_UP; memcpy(psid, psidIntegrityLevelLabel, cbSid); if(!SetSecurityDescriptorSacl(m_SA.lpSecurityDescriptor, TRUE, pSacl, FALSE)) { return HRESULT_FROM_GetLastError(); } // No need to delete the sacl buffer, it will be deleted in the // destructor of this class m_pSacl = (PACL)sacl.Extract(); return S_OK; } //***************************************************************** // Return SECURITY_ATTRIBUTES that we form in the Init function // // No clean up is needed after calling this function. The destructor of the // instance will do the right thing. Note that this is designed such that // we minimize memory allocation, ie the SECURITY_DESCRIPTOR and // SECURITY_ATTRIBUTES are embedded in the SecurityUtil instance. // // Caller should not modify the returned SECURITY_ATTRIBUTES!!! //***************************************************************** HRESULT SecurityUtil::GetSA(SECURITY_ATTRIBUTES **ppSA) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; _ASSERTE(ppSA); if (m_fInitialized == false) { _ASSERTE(!"Bad code path!"); *ppSA = NULL; return E_FAIL; } *ppSA = &m_SA; return S_OK; }
mit
elbruno/Blog
20170314 HoloToolkit AirTap Click/Assets/HoloToolkit/Utilities/Scripts/TimerScheduler.cs
7131
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// A scheduler that manages various timers. /// </summary> /// <example> /// <code> /// private int myTimer = 0; /// /// private void MyTimerCallback() /// { /// // Do stuff /// } /// /// private void StartMyTimer() /// { /// float durationInSec = 0.5f; /// myTimer = TimerId.Start(durationInSec, MyTimerCallback); /// } /// /// private void StopMyTimer() /// { /// myTimer.Stop(); /// } /// </code> /// </example> public sealed class TimerScheduler : Singleton<TimerScheduler> { private struct TimerData { public Callback Callback; public float Duration; public bool Loop; public int Id; public TimerData(float time, Callback callback, bool loop, int id) { Callback = callback; Loop = loop; Duration = time; Id = id; } } private struct TimerIdPair { public int Id; public int KeyTime; } public delegate void Callback(); private PriorityQueue<int, TimerData> timers; private List<TimerData> deferredTimers; private List<TimerIdPair> activeTimers; private int nextTimerId; protected override void Awake() { base.Awake(); timers = new PriorityQueue<int, TimerData>(); deferredTimers = new List<TimerData>(10); activeTimers = new List<TimerIdPair>(20); nextTimerId = 1; // 0 is reserved } private int GetKeyTime(float time) { // key time is nearest millisecond return (int)(time * 1000); } private bool HasKeyTimePassed(int key) { return key <= GetKeyTime(Time.time); } private int AddTimer(TimerData timer, bool deferred = false) { if (deferred) { deferredTimers.Add(timer); } else { // calculate the key time for the evaluation point. Multiple timers can have this value. int keyTime = GetKeyTime(Time.time + timer.Duration); // re-add timer to queue timers.Push(keyTime, timer); // add to list of active timers activeTimers.Add(new TimerIdPair { Id = timer.Id, KeyTime = keyTime }); } // make sure the scheduler is enabled now that we have a new timer. enabled = true; return timer.Id; } private int GetActiveTimerIndex(int timerId) { for (int i = 0; i < activeTimers.Count; ++i) { if (activeTimers[i].Id == timerId) { return i; } } return -1; } private bool RemoveActiveTimer(int timerId) { int index = GetActiveTimerIndex(timerId); if (index > -1) { activeTimers.RemoveAt(index); return true; } return false; } private int GetTimerDeferredIndex(int timerId) { for (int i = 0; i < deferredTimers.Count; ++i) { if (deferredTimers[i].Id == timerId) { return i; } } return -1; } private void AddDeferredTimers() { for (int i = 0; i < deferredTimers.Count; i++) { AddTimer(deferredTimers[i]); } deferredTimers.Clear(); } private void Update() { // while waiting for an event to happen, we'll just early out while (timers.Count > 0 && HasKeyTimePassed(timers.Top.Key)) { TimerData timer = timers.Top.Value; // remove from active timers RemoveActiveTimer(timer.Id); // remove from queue timers.Pop(); // loop events by just reinserting them if (timer.Loop) { // re-add timer AddTimer(timer); } // activate the callback. call this after loop reinsertion, because // the callback could call StopTimer. timer.Callback(); } AddDeferredTimers(); // if there are no active timers there is no need to update every frame. if (timers.Count == 0) { enabled = false; } } /// <summary> /// Creates a new timer event which will be added next frame. /// </summary> /// <param name="timeSeconds"></param> /// <param name="callback"></param> /// <param name="loop"></param> /// <param name="deferred"> Deferred timers will be pushed to the priority queue during next update</param> public Timer StartTimer(float timeSeconds, Callback callback, bool loop = false, bool deferred = false) { int id = AddTimer(new TimerData(timeSeconds, callback, loop, nextTimerId++), deferred); // create a new id, and make a new timer with it return new Timer(id); } /// <summary> /// Disable an active timer. /// </summary> /// <param name="timerId"></param> /// <returns></returns> public void StopTimer(Timer timerId) { if (timerId.Id != Timer.Invalid.Id) { int index = GetActiveTimerIndex(timerId.Id); if (index > -1) { int priority = activeTimers[index].KeyTime; activeTimers.RemoveAt(index); // TODO: remove specific value // allocation here is fine, since it's a temporary, and will get cleaned in gen 0 GC int id = timerId.Id; timers.RemoveAtPriority(priority, t => t.Id == id); } else { int deferredIndex = GetTimerDeferredIndex(timerId.Id); if (deferredIndex > -1) { deferredTimers.RemoveAt(deferredIndex); } } } } public bool IsTimerActive(Timer timerId) { return GetActiveTimerIndex(timerId.Id) > -1 || GetTimerDeferredIndex(timerId.Id) > -1; } } }
gpl-2.0
ashenkar/sanga
wp-content/plugins/jetpack/modules/sharedaddy/sharing-service.php
22697
<?php include_once dirname( __FILE__ ).'/sharing-sources.php'; define( 'WP_SHARING_PLUGIN_VERSION', JETPACK__VERSION ); class Sharing_Service { private $global = false; public $default_sharing_label = ''; public function __construct() { $this->default_sharing_label = __( 'Share this:', 'jetpack' ); } /** * Gets a generic list of all services, without any config */ public function get_all_services_blog() { $options = get_option( 'sharing-options' ); $all = $this->get_all_services(); $services = array(); foreach ( $all AS $id => $name ) { if ( isset( $all[$id] ) ) { $config = array(); // Pre-load custom modules otherwise they won't know who they are if ( substr( $id, 0, 7 ) == 'custom-' && is_array( $options[$id] ) ) $config = $options[$id]; $services[$id] = new $all[$id]( $id, $config ); } } return $services; } /** * Gets a list of all available service names and classes */ public function get_all_services( $include_custom = true ) { // Default services // if you update this list, please update the REST API tests // in bin/tests/api/suites/SharingTest.php $services = array( 'email' => 'Share_Email', 'print' => 'Share_Print', 'facebook' => 'Share_Facebook', 'linkedin' => 'Share_LinkedIn', 'reddit' => 'Share_Reddit', 'twitter' => 'Share_Twitter', 'press-this' => 'Share_PressThis', 'google-plus-1' => 'Share_GooglePlus1', 'tumblr' => 'Share_Tumblr', 'pinterest' => 'Share_Pinterest', 'pocket' => 'Share_Pocket', ); if ( $include_custom ) { // Add any custom services in $options = $this->get_global_options(); foreach ( (array) $options['custom'] AS $custom_id ) { $services[$custom_id] = 'Share_Custom'; } } /** * Filters the list of available Sharing Services. * * @since 1.1.0 * * @param array $services Array of all available Sharing Services. */ return apply_filters( 'sharing_services', $services ); } public function new_service( $label, $url, $icon ) { // Validate $label = trim( wp_html_excerpt( wp_kses( $label, array() ), 30 ) ); $url = trim( esc_url_raw( $url ) ); $icon = trim( esc_url_raw( $icon ) ); if ( $label && $url && $icon ) { $options = get_option( 'sharing-options' ); if ( !is_array( $options ) ) $options = array(); $service_id = 'custom-'.time(); // Add a new custom service $options['global']['custom'][] = $service_id; if ( false !== $this->global ) { $this->global['custom'][] = $service_id; } update_option( 'sharing-options', $options ); // Create a custom service and set the options for it $service = new Share_Custom( $service_id, array( 'name' => $label, 'url' => $url, 'icon' => $icon ) ); $this->set_service( $service_id, $service ); // Return the service return $service; } return false; } public function delete_service( $service_id ) { $options = get_option( 'sharing-options' ); if ( isset( $options[$service_id] ) ) unset( $options[$service_id] ); $key = array_search( $service_id, $options['global']['custom'] ); if ( $key !== false ) unset( $options['global']['custom'][$key] ); update_option( 'sharing-options', $options ); return true; } public function set_blog_services( array $visible, array $hidden ) { $services = $this->get_all_services(); // Validate the services $available = array_keys( $services ); // Only allow services that we have defined $hidden = array_intersect( $hidden, $available ); $visible = array_intersect( $visible, $available ); // Ensure we don't have the same ones in hidden and visible $hidden = array_diff( $hidden, $visible ); /** * Control the state of the list of sharing services. * * @since 1.1.0 * * @param array $args { * Array of options describing the state of the sharing services. * * @type array $services List of all available service names and classes. * @type array $available Validated list of all available service names and classes. * @type array $hidden List of services hidden behind a "More" button. * @type array $visible List of visible services. * @type array $this->get_blog_services() Array of Sharing Services currently enabled. * } */ do_action( 'sharing_get_services_state', array( 'services' => $services, 'available' => $available, 'hidden' => $hidden, 'visible' => $visible, 'currently_enabled' => $this->get_blog_services() ) ); update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) ); } public function get_blog_services() { $options = get_option( 'sharing-options' ); $enabled = get_option( 'sharing-services' ); $services = $this->get_all_services(); if ( !is_array( $options ) ) $options = array( 'global' => $this->get_global_options() ); $global = $options['global']; // Default services if ( ! is_array( $enabled ) ) { $enabled = array( 'visible' => array(), 'hidden' => array() ); /** * Filters the list of default Sharing Services. * * @since 1.1.0 * * @param array $enabled Array of default Sharing Services. */ $enabled = apply_filters( 'sharing_default_services', $enabled ); } // Cleanup after any filters that may have produced duplicate services $enabled['visible'] = array_unique( $enabled['visible'] ); $enabled['hidden'] = array_unique( $enabled['hidden'] ); // Form the enabled services $blog = array( 'visible' => array(), 'hidden' => array() ); foreach ( $blog AS $area => $stuff ) { foreach ( (array)$enabled[$area] AS $service ) { if ( isset( $services[$service] ) ) { $blog[$area][$service] = new $services[$service]( $service, array_merge( $global, isset( $options[$service] ) ? $options[$service] : array() ) ); } } } /** * Filters the list of enabled Sharing Services. * * @since 1.1.0 * * @param array $blog Array of enabled Sharing Services. */ $blog = apply_filters( 'sharing_services_enabled', $blog ); // Add CSS for NASCAR if ( count( $blog['visible'] ) || count( $blog['hidden'] ) ) add_filter( 'post_flair_block_css', 'post_flair_service_enabled_sharing' ); // Convenience for checking if a service is present $blog['all'] = array_flip( array_merge( array_keys( $blog['visible'] ), array_keys( $blog['hidden'] ) ) ); return $blog; } public function get_service( $service_name ) { $services = $this->get_blog_services(); if ( isset( $services['visible'][$service_name] ) ) return $services['visible'][$service_name]; if ( isset( $services['hidden'][$service_name] ) ) return $services['hidden'][$service_name]; return false; } public function set_global_options( $data ) { $options = get_option( 'sharing-options' ); // No options yet if ( !is_array( $options ) ) $options = array(); // Defaults $options['global'] = array( 'button_style' => 'icon-text', 'sharing_label' => $this->default_sharing_label, 'open_links' => 'same', 'show' => array(), 'custom' => isset( $options['global']['custom'] ) ? $options['global']['custom'] : array() ); /** * Filters global sharing settings. * * @since 1.1.0 * * @param array $options['global'] Array of global sharing settings. */ $options['global'] = apply_filters( 'sharing_default_global', $options['global'] ); // Validate options and set from our data if ( isset( $data['button_style'] ) && in_array( $data['button_style'], array( 'icon-text', 'icon', 'text', 'official' ) ) ) $options['global']['button_style'] = $data['button_style']; if ( isset( $data['sharing_label'] ) ) { if ( $this->default_sharing_label === $data['sharing_label'] ) { $options['global']['sharing_label'] = false; } else { $options['global']['sharing_label'] = trim( wp_kses( stripslashes( $data['sharing_label'] ), array() ) ); } } if ( isset( $data['open_links'] ) && in_array( $data['open_links'], array( 'new', 'same' ) ) ) $options['global']['open_links'] = $data['open_links']; $shows = array_values( get_post_types( array( 'public' => true ) ) ); $shows[] = 'index'; if ( isset( $data['show'] ) ) { if ( is_scalar( $data['show'] ) ) { switch ( $data['show'] ) { case 'posts' : $data['show'] = array( 'post', 'page' ); break; case 'index' : $data['show'] = array( 'index' ); break; case 'posts-index' : $data['show'] = array( 'post', 'page', 'index' ); break; } } if ( $data['show'] = array_intersect( $data['show'], $shows ) ) { $options['global']['show'] = $data['show']; } } update_option( 'sharing-options', $options ); return $options['global']; } public function get_global_options() { if ( $this->global === false ) { $options = get_option( 'sharing-options' ); if ( is_array( $options ) && isset( $options['global'] ) ) $this->global = $options['global']; else $this->global = $this->set_global_options( $options['global'] ); } if ( ! isset( $this->global['show'] ) ) { $this->global['show'] = array( 'post', 'page' ); } elseif ( is_scalar( $this->global['show'] ) ) { switch ( $this->global['show'] ) { case 'posts' : $this->global['show'] = array( 'post', 'page' ); break; case 'index' : $this->global['show'] = array( 'index' ); break; case 'posts-index' : $this->global['show'] = array( 'post', 'page', 'index' ); break; } } if ( false === $this->global['sharing_label'] ) { $this->global['sharing_label'] = $this->default_sharing_label; } return $this->global; } public function set_service( $id, Sharing_Source $service ) { // Update the options for this service $options = get_option( 'sharing-options' ); // No options yet if ( ! is_array( $options ) ) { $options = array(); } /** * Get the state of a sharing button. * * @since 1.1.0 * * @param array $args { * State of a sharing button. * * @type string $id Service ID. * @type array $options Array of all sharing options. * @type array $service Details about a service. * } */ do_action( 'sharing_get_button_state', array( 'id' => $id, 'options' => $options, 'service' => $service ) ); $options[$id] = $service->get_options(); update_option( 'sharing-options', array_filter( $options ) ); } // Soon to come to a .org plugin near you! public function get_total( $service_name = false, $post_id = false, $_blog_id = false ) { global $wpdb, $blog_id; if ( !$_blog_id ) { $_blog_id = $blog_id; } if ( $service_name == false ) { if ( $post_id > 0 ) { // total number of shares for this post return (int) $wpdb->get_var( $wpdb->prepare( "SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d AND post_id = %d", $_blog_id, $post_id ) ); } else { // total number of shares for this blog return (int) $wpdb->get_var( $wpdb->prepare( "SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d", $_blog_id ) ); } } if ( $post_id > 0 ) return (int) $wpdb->get_var( $wpdb->prepare( "SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d AND post_id = %d AND share_service = %s", $_blog_id, $post_id, $service_name ) ); else return (int) $wpdb->get_var( $wpdb->prepare( "SELECT SUM( count ) FROM sharing_stats WHERE blog_id = %d AND share_service = %s", $_blog_id, $service_name ) ); } public function get_services_total( $post_id = false ) { $totals = array(); $services = $this->get_blog_services(); if ( !empty( $services ) && isset( $services[ 'all' ] ) ) foreach( $services[ 'all' ] as $key => $value ) { $totals[$key] = new Sharing_Service_Total( $key, $this->get_total( $key, $post_id ) ); } usort( $totals, array( 'Sharing_Service_Total', 'cmp' ) ); return $totals; } public function get_posts_total() { $totals = array(); global $wpdb, $blog_id; $my_data = $wpdb->get_results( $wpdb->prepare( "SELECT post_id as id, SUM( count ) as total FROM sharing_stats WHERE blog_id = %d GROUP BY post_id ORDER BY count DESC ", $blog_id ) ); if ( !empty( $my_data ) ) foreach( $my_data as $row ) $totals[] = new Sharing_Post_Total( $row->id, $row->total ); usort( $totals, array( 'Sharing_Post_Total', 'cmp' ) ); return $totals; } } class Sharing_Service_Total { public $id = ''; public $name = ''; public $service = ''; public $total = 0; public function __construct( $id, $total ) { $services = new Sharing_Service(); $this->id = esc_html( $id ); $this->service = $services->get_service( $id ); $this->total = (int) $total; $this->name = $this->service->get_name(); } static function cmp( $a, $b ) { if ( $a->total == $b->total ) return $a->name < $b->name; return $a->total < $b->total; } } class Sharing_Post_Total { public $id = 0; public $total = 0; public $title = ''; public $url = ''; public function __construct( $id, $total ) { $this->id = (int) $id; $this->total = (int) $total; $this->title = get_the_title( $this->id ); $this->url = get_permalink( $this->id ); } static function cmp( $a, $b ) { if ( $a->total == $b->total ) return $a->id < $b->id; return $a->total < $b->total; } } function sharing_register_post_for_share_counts( $post_id ) { global $jetpack_sharing_counts; if ( ! isset( $jetpack_sharing_counts ) || ! is_array( $jetpack_sharing_counts ) ) $jetpack_sharing_counts = array(); $jetpack_sharing_counts[ (int) $post_id ] = get_permalink( $post_id ); } function sharing_maybe_enqueue_scripts() { $sharer = new Sharing_Service(); $global_options = $sharer->get_global_options(); $enqueue = false; if ( is_singular() && in_array( get_post_type(), $global_options['show'] ) ) { $enqueue = true; } elseif ( in_array( 'index', $global_options['show'] ) && ( is_home() || is_front_page() || is_archive() || is_search() || in_array( get_post_type(), $global_options['show'] ) ) ) { $enqueue = true; } /** * Filter to decide when sharing scripts should be enqueued. * * @since 3.2.0 * * @param bool $enqueue Decide if the sharing scripts should be enqueued. */ return (bool) apply_filters( 'sharing_enqueue_scripts', $enqueue ); } function sharing_add_footer() { global $jetpack_sharing_counts; /** * Filter all Javascript output by the sharing module. * * @since 1.1.0 * * @param bool true Control whether the sharing module should add any Javascript to the site. Default to true. */ if ( apply_filters( 'sharing_js', true ) && sharing_maybe_enqueue_scripts() ) { /** * Filter the display of sharing counts next to the sharing buttons. * * @since 3.2.0 * * @param bool true Control the display of counters next to the sharing buttons. Default to true. */ if ( apply_filters( 'jetpack_sharing_counts', true ) && is_array( $jetpack_sharing_counts ) && count( $jetpack_sharing_counts ) ) : $sharing_post_urls = array_filter( $jetpack_sharing_counts ); if ( $sharing_post_urls ) : ?> <script type="text/javascript"> window.WPCOM_sharing_counts = <?php echo json_encode( array_flip( $sharing_post_urls ) ); ?>; </script> <?php endif; endif; wp_enqueue_script( 'sharing-js' ); $sharing_js_options = array( 'lang' => get_base_recaptcha_lang_code(), /** This filter is documented in modules/sharedaddy/sharing-service.php */ 'counts' => apply_filters( 'jetpack_sharing_counts', true ) ); wp_localize_script( 'sharing-js', 'sharing_js_options', $sharing_js_options); } $sharer = new Sharing_Service(); $enabled = $sharer->get_blog_services(); foreach ( array_merge( $enabled['visible'], $enabled['hidden'] ) AS $service ) { $service->display_footer(); } } function sharing_add_header() { $sharer = new Sharing_Service(); $enabled = $sharer->get_blog_services(); foreach ( array_merge( $enabled['visible'], $enabled['hidden'] ) AS $service ) { $service->display_header(); } if ( count( $enabled['all'] ) > 0 && sharing_maybe_enqueue_scripts() ) { wp_enqueue_style( 'sharedaddy', plugin_dir_url( __FILE__ ) .'sharing.css', array(), JETPACK__VERSION ); wp_enqueue_style( 'genericons' ); } } add_action( 'wp_head', 'sharing_add_header', 1 ); function sharing_process_requests() { global $post; // Only process if: single post and share=X defined if ( ( is_page() || is_single() ) && isset( $_GET['share'] ) ) { $sharer = new Sharing_Service(); $service = $sharer->get_service( $_GET['share'] ); if ( $service ) { $service->process_request( $post, $_POST ); } } } add_action( 'template_redirect', 'sharing_process_requests', 9 ); function sharing_display( $text = '', $echo = false ) { global $post, $wp_current_filter; if ( empty( $post ) ) return $text; if ( ( is_preview() || is_admin() ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { return $text; } // Don't output flair on excerpts if ( in_array( 'get_the_excerpt', (array) $wp_current_filter ) ) { return $text; } // Don't allow flair to be added to the_content more than once (prevent infinite loops) $done = false; foreach ( $wp_current_filter as $filter ) { if ( 'the_content' == $filter ) { if ( $done ) return $text; else $done = true; } } // check whether we are viewing the front page and whether the front page option is checked $options = get_option( 'sharing-options' ); $display_options = $options['global']['show']; if ( is_front_page() && ( is_array( $display_options ) && ! in_array( 'index', $display_options ) ) ) return $text; if ( is_attachment() && in_array( 'the_excerpt', (array) $wp_current_filter ) ) { // Many themes run the_excerpt() conditionally on an attachment page, then run the_content(). // We only want to output the sharing buttons once. Let's stick with the_content(). return $text; } $sharer = new Sharing_Service(); $global = $sharer->get_global_options(); $show = false; if ( !is_feed() ) { if ( is_singular() && in_array( get_post_type(), $global['show'] ) ) { $show = true; } elseif ( in_array( 'index', $global['show'] ) && ( is_home() || is_front_page() || is_archive() || is_search() || in_array( get_post_type(), $global['show'] ) ) ) { $show = true; } } /** * Filter to decide if sharing buttons should be displayed. * * @since 1.1.0 * * @param * @param WP_Post $post The post to share. */ $show = apply_filters( 'sharing_show', $show, $post ); // Disabled for this post? $switched_status = get_post_meta( $post->ID, 'sharing_disabled', false ); if ( !empty( $switched_status ) ) $show = false; // Private post? $post_status = get_post_status( $post->ID ); if ( 'private' === $post_status ) { $show = false; } // Allow to be used on P2 ajax requests for latest posts. if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_REQUEST['action'] ) && 'get_latest_posts' == $_REQUEST['action'] ) $show = true; $sharing_content = ''; if ( $show ) { /** * Filters the list of enabled Sharing Services. * * @since 2.2.3 * * @param array $sharer->get_blog_services() Array of Sharing Services currently enabled. */ $enabled = apply_filters( 'sharing_enabled', $sharer->get_blog_services() ); if ( count( $enabled['all'] ) > 0 ) { global $post; $dir = get_option( 'text_direction' ); // Wrapper $sharing_content .= '<div class="sharedaddy sd-sharing-enabled"><div class="robots-nocontent sd-block sd-social sd-social-' . $global['button_style'] . ' sd-sharing">'; if ( $global['sharing_label'] != '' ) $sharing_content .= '<h3 class="sd-title">' . $global['sharing_label'] . '</h3>'; $sharing_content .= '<div class="sd-content"><ul>'; // Visible items $visible = ''; foreach ( $enabled['visible'] as $id => $service ) { // Individual HTML for sharing service $visible .= '<li class="share-' . $service->get_class() . '">' . $service->get_display( $post ) . '</li>'; } $parts = array(); $parts[] = $visible; if ( count( $enabled['hidden'] ) > 0 ) { if ( count( $enabled['visible'] ) > 0 ) $expand = __( 'More', 'jetpack' ); else $expand = __( 'Share', 'jetpack' ); $parts[] = '<li><a href="#" class="sharing-anchor sd-button share-more"><span>'.$expand.'</span></a></li>'; } if ( $dir == 'rtl' ) $parts = array_reverse( $parts ); $sharing_content .= implode( '', $parts ); $sharing_content .= '<li class="share-end"></li></ul>'; if ( count( $enabled['hidden'] ) > 0 ) { $sharing_content .= '<div class="sharing-hidden"><div class="inner" style="display: none;'; if ( count( $enabled['hidden'] ) == 1 ) $sharing_content .= 'width:150px;'; $sharing_content .= '">'; if ( count( $enabled['hidden'] ) == 1 ) $sharing_content .= '<ul style="background-image:none;">'; else $sharing_content .= '<ul>'; $count = 1; foreach ( $enabled['hidden'] as $id => $service ) { // Individual HTML for sharing service $sharing_content .= '<li class="share-'.$service->get_class().'">'; $sharing_content .= $service->get_display( $post ); $sharing_content .= '</li>'; if ( ( $count % 2 ) == 0 ) $sharing_content .= '<li class="share-end"></li>'; $count ++; } // End of wrapper $sharing_content .= '<li class="share-end"></li></ul></div></div>'; } $sharing_content .= '</div></div></div>'; // Register our JS if ( defined( 'JETPACK__VERSION' ) ) { $ver = JETPACK__VERSION; } else { $ver = '20141212'; } wp_register_script( 'sharing-js', plugin_dir_url( __FILE__ ).'sharing.js', array( 'jquery' ), $ver ); add_action( 'wp_footer', 'sharing_add_footer' ); } } if ( $echo ) echo $text.$sharing_content; else return $text.$sharing_content; } add_filter( 'the_content', 'sharing_display', 19 ); add_filter( 'the_excerpt', 'sharing_display', 19 ); function get_base_recaptcha_lang_code() { $base_recaptcha_lang_code_mapping = array( 'en' => 'en', 'nl' => 'nl', 'fr' => 'fr', 'fr-be' => 'fr', 'fr-ca' => 'fr', 'fr-ch' => 'fr', 'de' => 'de', 'pt' => 'pt', 'pt-br' => 'pt', 'ru' => 'ru', 'es' => 'es', 'tr' => 'tr' ); $blog_lang_code = function_exists( 'get_blog_lang_code' ) ? get_blog_lang_code() : get_bloginfo( 'language' ); if( isset( $base_recaptcha_lang_code_mapping[ $blog_lang_code ] ) ) return $base_recaptcha_lang_code_mapping[ $blog_lang_code ]; // if no base mapping is found return default 'en' return 'en'; }
gpl-2.0
jackkiej/SickRage
lib/dateutil/relativedelta.py
21509
# -*- coding: utf-8 -*- import datetime import calendar import operator from math import copysign from six import integer_types from warnings import warn __all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] class weekday(object): __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(self.weekday, n) def __eq__(self, other): try: if self.weekday != other.weekday or self.n != other.n: return False except AttributeError: return False return True def __repr__(self): s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] if not self.n: return s else: return "%s(%+d)" % (s, self.n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)]) class relativedelta(object): """ The relativedelta type is based on the specification of the excellent work done by M.-A. Lemburg in his `mx.DateTime <http://www.egenix.com/files/python/mxDateTime.html>`_ extension. However, notice that this type does *NOT* implement the same algorithm as his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. There are two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes:: relativedelta(datetime1, datetime2) The second one is passing it any number of the following keyword arguments:: relativedelta(arg1=x,arg2=y,arg3=z...) year, month, day, hour, minute, second, microsecond: Absolute information (argument is singular); adding or subtracting a relativedelta with absolute information does not perform an aritmetic operation, but rather REPLACES the corresponding value in the original datetime with the value(s) in relativedelta. years, months, weeks, days, hours, minutes, seconds, microseconds: Relative information, may be negative (argument is plural); adding or subtracting a relativedelta with relative information performs the corresponding aritmetic operation on the original datetime value with the information in the relativedelta. weekday: One of the weekday instances (MO, TU, etc). These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2). Not specifying it is the same as specifying +1. You can also use an integer, where 0=MO. leapdays: Will add given days to the date found, if year is a leap year, and the date found is post 28 of february. yearday, nlyearday: Set the yearday or the non-leap year day (jump leap days). These are converted to day/month/leapdays information. Here is the behavior of operations with relativedelta: 1. Calculate the absolute year, using the 'year' argument, or the original datetime year, if the argument is not present. 2. Add the relative 'years' argument to the absolute year. 3. Do steps 1 and 2 for month/months. 4. Calculate the absolute day, using the 'day' argument, or the original datetime day, if the argument is not present. Then, subtract from the day until it fits in the year and month found after their operations. 5. Add the relative 'days' argument to the absolute day. Notice that the 'weeks' argument is multiplied by 7 and added to 'days'. 6. Do steps 1 and 2 for hour/hours, minute/minutes, second/seconds, microsecond/microseconds. 7. If the 'weekday' argument is present, calculate the weekday, with the given (wday, nth) tuple. wday is the index of the weekday (0-6, 0=Mon), and nth is the number of weeks to add forward or backward, depending on its signal. Notice that if the calculated date is already Monday, for example, using (0, 1) or (0, -1) won't change the day. """ def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None): # Check for non-integer values in integer-only quantities if any(x is not None and x != int(x) for x in (years, months)): raise ValueError("Non-integer years and months are " "ambiguous and not currently supported.") if dt1 and dt2: # datetime is a subclass of date. So both must be date if not (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date)): raise TypeError("relativedelta only diffs datetime/date") # We allow two dates, or two datetimes, so we coerce them to be # of the same type if (isinstance(dt1, datetime.datetime) != isinstance(dt2, datetime.datetime)): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) elif not isinstance(dt2, datetime.datetime): dt2 = datetime.datetime.fromordinal(dt2.toordinal()) self.years = 0 self.months = 0 self.days = 0 self.leapdays = 0 self.hours = 0 self.minutes = 0 self.seconds = 0 self.microseconds = 0 self.year = None self.month = None self.day = None self.weekday = None self.hour = None self.minute = None self.second = None self.microsecond = None self._has_time = 0 # Get year / month delta between the two months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) self._set_months(months) # Remove the year/month delta so the timedelta is just well-defined # time units (seconds, days and microseconds) dtm = self.__radd__(dt2) # If we've overshot our target, make an adjustment if dt1 < dt2: compare = operator.gt increment = 1 else: compare = operator.lt increment = -1 while compare(dt1, dtm): months += increment self._set_months(months) dtm = self.__radd__(dt2) # Get the timedelta between the "months-adjusted" date and dt1 delta = dt1 - dtm self.seconds = delta.seconds + delta.days * 86400 self.microseconds = delta.microseconds else: # Relative information self.years = years self.months = months self.days = days + weeks * 7 self.leapdays = leapdays self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds # Absolute information self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.microsecond = microsecond if any(x is not None and int(x) != x for x in (year, month, day, hour, minute, second, microsecond)): # For now we'll deprecate floats - later it'll be an error. warn("Non-integer value passed as absolute information. " + "This is not a well-defined condition and will raise " + "errors in future versions.", DeprecationWarning) if isinstance(weekday, integer_types): self.weekday = weekdays[weekday] else: self.weekday = weekday yday = 0 if nlyearday: yday = nlyearday elif yearday: yday = yearday if yearday > 59: self.leapdays = -1 if yday: ydayidx = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 366] for idx, ydays in enumerate(ydayidx): if yday <= ydays: self.month = idx+1 if idx == 0: self.day = yday else: self.day = yday-ydayidx[idx-1] break else: raise ValueError("invalid year day (%d)" % yday) self._fix() def _fix(self): if abs(self.microseconds) > 999999: s = _sign(self.microseconds) div, mod = divmod(self.microseconds * s, 1000000) self.microseconds = mod * s self.seconds += div * s if abs(self.seconds) > 59: s = _sign(self.seconds) div, mod = divmod(self.seconds * s, 60) self.seconds = mod * s self.minutes += div * s if abs(self.minutes) > 59: s = _sign(self.minutes) div, mod = divmod(self.minutes * s, 60) self.minutes = mod * s self.hours += div * s if abs(self.hours) > 23: s = _sign(self.hours) div, mod = divmod(self.hours * s, 24) self.hours = mod * s self.days += div * s if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years += div * s if (self.hours or self.minutes or self.seconds or self.microseconds or self.hour is not None or self.minute is not None or self.second is not None or self.microsecond is not None): self._has_time = 1 else: self._has_time = 0 @property def weeks(self): return self.days // 7 @weeks.setter def weeks(self, value): self.days = self.days - (self.weeks * 7) + value * 7 def _set_months(self, months): self.months = months if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years = div * s else: self.years = 0 def normalized(self): """ Return a version of this object represented entirely using integer values for the relative attributes. >>> relativedelta(days=1.5, hours=2).normalized() relativedelta(days=1, hours=14) :return: Returns a :class:`dateutil.relativedelta.relativedelta` object. """ # Cascade remainders down (rounding each to roughly nearest microsecond) days = int(self.days) hours_f = round(self.hours + 24 * (self.days - days), 11) hours = int(hours_f) minutes_f = round(self.minutes + 60 * (hours_f - hours), 10) minutes = int(minutes_f) seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8) seconds = int(seconds_f) microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds)) # Constructor carries overflow back up with call to _fix() return self.__class__(years=self.years, months=self.months, days=days, hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __add__(self, other): if isinstance(other, relativedelta): return self.__class__(years=other.years + self.years, months=other.months + self.months, days=other.days + self.days, hours=other.hours + self.hours, minutes=other.minutes + self.minutes, seconds=other.seconds + self.seconds, microseconds=(other.microseconds + self.microseconds), leapdays=other.leapdays or self.leapdays, year=other.year or self.year, month=other.month or self.month, day=other.day or self.day, weekday=other.weekday or self.weekday, hour=other.hour or self.hour, minute=other.minute or self.minute, second=other.second or self.second, microsecond=(other.microsecond or self.microsecond)) if not isinstance(other, datetime.date): raise TypeError("unsupported type for add operation") elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth) - 1) * 7 if nth > 0: jumpdays += (7 - ret.weekday() + weekday) % 7 else: jumpdays += (ret.weekday() - weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return self.__neg__().__radd__(other) def __sub__(self, other): if not isinstance(other, relativedelta): raise TypeError("unsupported type for sub operation") return self.__class__(years=self.years - other.years, months=self.months - other.months, days=self.days - other.days, hours=self.hours - other.hours, minutes=self.minutes - other.minutes, seconds=self.seconds - other.seconds, microseconds=self.microseconds - other.microseconds, leapdays=self.leapdays or other.leapdays, year=self.year or other.year, month=self.month or other.month, day=self.day or other.day, weekday=self.weekday or other.weekday, hour=self.hour or other.hour, minute=self.minute or other.minute, second=self.second or other.second, microsecond=self.microsecond or other.microsecond) def __neg__(self): return self.__class__(years=-self.years, months=-self.months, days=-self.days, hours=-self.hours, minutes=-self.minutes, seconds=-self.seconds, microseconds=-self.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __bool__(self): return not (not self.years and not self.months and not self.days and not self.hours and not self.minutes and not self.seconds and not self.microseconds and not self.leapdays and self.year is None and self.month is None and self.day is None and self.weekday is None and self.hour is None and self.minute is None and self.second is None and self.microsecond is None) # Compatibility with Python 2.x __nonzero__ = __bool__ def __mul__(self, other): f = float(other) return self.__class__(years=int(self.years * f), months=int(self.months * f), days=int(self.days * f), hours=int(self.hours * f), minutes=int(self.minutes * f), seconds=int(self.seconds * f), microseconds=int(self.microseconds * f), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) __rmul__ = __mul__ def __eq__(self, other): if not isinstance(other, relativedelta): return False if self.weekday or other.weekday: if not self.weekday or not other.weekday: return False if self.weekday.weekday != other.weekday.weekday: return False n1, n2 = self.weekday.n, other.weekday.n if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): return False return (self.years == other.years and self.months == other.months and self.days == other.days and self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds and self.microseconds == other.microseconds and self.leapdays == other.leapdays and self.year == other.year and self.month == other.month and self.day == other.day and self.hour == other.hour and self.minute == other.minute and self.second == other.second and self.microsecond == other.microsecond) def __ne__(self, other): return not self.__eq__(other) def __div__(self, other): return self.__mul__(1/float(other)) __truediv__ = __div__ def __repr__(self): l = [] for attr in ["years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"]: value = getattr(self, attr) if value: l.append("{attr}={value:+g}".format(attr=attr, value=value)) for attr in ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: l.append("{attr}={value}".format(attr=attr, value=repr(value))) return "{classname}({attrs})".format(classname=self.__class__.__name__, attrs=", ".join(l)) def _sign(x): return int(copysign(1, x)) # vim:ts=4:sw=4:et
gpl-3.0
leomastakusuma/Gateway
library/Zend/View/Helper/ServerUrl.php
4206
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Helper for returning the current server URL (optionally with request URI) * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_View_Helper_ServerUrl { /** * Scheme * * @var string */ protected $_scheme; /** * Host (including port) * * @var string */ protected $_host; /** * Constructor * * @return void */ public function __construct() { switch (true) { case (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] === true)): case (isset($_SERVER['HTTP_SCHEME']) && ($_SERVER['HTTP_SCHEME'] == 'https')): case (isset($_SERVER['SERVER_PORT']) && ($_SERVER['SERVER_PORT'] == 443)): $scheme = 'https'; break; default: $scheme = 'http'; } $this->setScheme($scheme); if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) { $this->setHost($_SERVER['HTTP_HOST']); } else if (isset($_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT'])) { $name = $_SERVER['SERVER_NAME']; $port = $_SERVER['SERVER_PORT']; if (($scheme == 'http' && $port == 80) || ($scheme == 'https' && $port == 443)) { $this->setHost($name); } else { $this->setHost($name . ':' . $port); } } } /** * View helper entry point: * Returns the current host's URL like http://site.com * * @param string|boolean $requestUri [optional] if true, the request URI * found in $_SERVER will be appended * as a path. If a string is given, it * will be appended as a path. Default * is to not append any path. * @return string server url */ public function serverUrl($requestUri = null) { if ($requestUri === true) { $path = $_SERVER['REQUEST_URI']; } else if (is_string($requestUri)) { $path = $requestUri; } else { $path = ''; } return $this->getScheme() . '://' . $this->getHost() . $path; } /** * Returns host * * @return string host */ public function getHost() { return $this->_host; } /** * Sets host * * @param string $host new host * @return Zend_View_Helper_ServerUrl fluent interface, returns self */ public function setHost($host) { $this->_host = $host; return $this; } /** * Returns scheme (typically http or https) * * @return string scheme (typically http or https) */ public function getScheme() { return $this->_scheme; } /** * Sets scheme (typically http or https) * * @param string $scheme new scheme (typically http or https) * @return Zend_View_Helper_ServerUrl fluent interface, returns self */ public function setScheme($scheme) { $this->_scheme = $scheme; return $this; } }
apache-2.0
WilliamNouet/nifi
nifi-nar-bundles/nifi-standard-services/nifi-hbase-client-service-api/src/main/java/org/apache/nifi/hbase/validate/ConfigFilesValidator.java
1669
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.hbase.validate; import org.apache.nifi.components.ValidationContext; import org.apache.nifi.components.ValidationResult; import org.apache.nifi.components.Validator; import org.apache.nifi.processor.util.StandardValidators; public class ConfigFilesValidator implements Validator { @Override public ValidationResult validate(final String subject, final String value, final ValidationContext context) { final String[] filenames = value.split(","); for (final String filename : filenames) { final ValidationResult result = StandardValidators.FILE_EXISTS_VALIDATOR.validate(subject, filename.trim(), context); if (!result.isValid()) { return result; } } return new ValidationResult.Builder().subject(subject).input(value).valid(true).build(); } }
apache-2.0
Toosman/WGTOTW
src/Content/CTextFilter.php
7668
<?php namespace Anax\Content; /** * Filter and format content. * */ class CTextFilter { use \Anax\TConfigure, \Anax\DI\TInjectionAware; /** * Call each filter. * * @param string $text the text to filter. * @param string $filters as comma separated list of filter. * * @return string the formatted text. */ public function doFilter($text, $filters) { // Define all valid filters with their callback function. $callbacks = array( 'bbcode' => 'bbcode2html', 'clickable' => 'makeClickable', 'markdown' => 'markdown', 'nl2br' => 'nl2br', 'shortcode' => 'shortCode', ); // Make an array of the comma separated string $filters $filter = preg_replace('/\s/', '', explode(',', $filters)); // For each filter, call its function with the $text as parameter. foreach ($filter as $key) { if (isset($callbacks[$key])) { $text = call_user_func_array([$this, $callbacks[$key]], [$text]); } else { throw new \Exception("The filter '$filter' is not a valid filter string."); } } return $text; } /** * Helper, BBCode formatting converting to HTML. * * @param string $text The text to be converted. * * @return string the formatted text. * * @link http://dbwebb.se/coachen/reguljara-uttryck-i-php-ger-bbcode-formattering */ public function bbcode2html($text) { $search = [ '/\[b\](.*?)\[\/b\]/is', '/\[i\](.*?)\[\/i\]/is', '/\[u\](.*?)\[\/u\]/is', '/\[img\](https?.*?)\[\/img\]/is', '/\[url\](https?.*?)\[\/url\]/is', '/\[url=(https?.*?)\](.*?)\[\/url\]/is' ]; $replace = [ '<strong>$1</strong>', '<em>$1</em>', '<u>$1</u>', '<img src="$1" />', '<a href="$1">$1</a>', '<a href="$1">$2</a>' ]; return preg_replace($search, $replace, $text); } /** * Make clickable links from URLs in text. * * @param string $text the text that should be formatted. * * @return string with formatted anchors. * * @link http://dbwebb.se/coachen/lat-php-funktion-make-clickable-automatiskt-skapa-klickbara-lankar */ public function makeClickable($text) { return preg_replace_callback( '#\b(?<![href|src]=[\'"])https?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', function ($matches) { return "<a href=\'{$matches[0]}\'>{$matches[0]}</a>"; }, $text ); } /** * Format text according to Markdown syntax. * * @param string $text the text that should be formatted. * * @return string as the formatted html-text. * * @link http://dbwebb.se/coachen/skriv-for-webben-med-markdown-och-formattera-till-html-med-php */ public function markdown($text) { return \Michelf\MarkdownExtra::defaultTransform($text); } /** * For convenience access to nl2br * * @param string $text text to be converted. * * @return string the formatted text. */ public function nl2br($text) { return nl2br($text); } /** * Shortcode to to quicker format text as HTML. * * @param string $text text to be converted. * * @return string the formatted text. */ public function shortCode($text) { $patterns = [ '/\[(FIGURE)[\s+](.+)\]/', '/\[(BASEURL)\]/', '/\[(RELURL)\]/', '/\[(ASSET)\]/', ]; return preg_replace_callback( $patterns, function ($matches) { switch ($matches[1]) { case 'FIGURE': return CTextFilter::ShortCodeFigure($matches[2]); break; case 'BASEURL': return CTextFilter::ShortCodeBaseurl(); break; case 'RELURL': return CTextFilter::ShortCodeRelurl(); break; case 'ASSET': return CTextFilter::ShortCodeAsset(); break; default: return "{$matches[1]} is unknown shortcode."; } }, $text ); } /** * Init shortcode handling by preparing the option list to an array, for those using arguments. * * @param string $options for the shortcode. * * @return array with all the options. */ protected static function shortCodeInit($options) { preg_match_all('/[a-zA-Z0-9]+="[^"]+"|\S+/', $options, $matches); $res = []; foreach ($matches[0] as $match) { $pos = strpos($match, '='); if ($pos == false) { $res[$match] = true; } else { $key = substr($match, 0, $pos); $val = trim(substr($match, $pos+1), '"'); $res[$key] = $val; } } return $res; } /** * Shortcode for <figure>. * * Usage example: [FIGURE src="img/home/me.jpg" caption="Me" alt="Bild på mig" nolink="nolink"] * * @param string $options for the shortcode. * * @return array with all the options. */ protected static function shortCodeFigure($options) { extract( array_merge( [ 'id' => null, 'class' => null, 'src' => null, 'title' => null, 'alt' => null, 'caption' => null, 'href' => null, 'nolink' => false, ], CTextFilter::ShortCodeInit($options) ), EXTR_SKIP ); $id = $id ? " id='$id'" : null; $class = $class ? " class='figure $class'" : " class='figure'"; $title = $title ? " title='$title'" : null; if (!$alt && $caption) { $alt = $caption; } if (!$href) { $pos = strpos($src, '?'); $href = $pos ? substr($src, 0, $pos) : $src; } $a_start = null; $a_end = null; if (!$nolink) { $a_start = "<a href='{$href}'>"; $a_end = "</a>"; } $html = <<<EOD <figure{$id}{$class}> {$a_start}<img src='{$src}' alt='{$alt}'{$title}/>{$a_end} <figcaption markdown=1>{$caption}</figcaption> </figure> EOD; return $html; } /** * Shortcode for adding BASEURL to links. * * Usage example: [BASEURL] * * @return array with all the options. */ protected function shortCodeBaseurl() { return $this->di->url->create() . "/"; } /** * Shortcode for adding RELURL to links. * * Usage example: [RELURL] * * @return array with all the options. */ protected function shortCodeRelurl() { return $this->di->url->createRelative() . "/"; } /** * Shortcode for adding RELURL to links. * * Usage example: [RELURL] * * @return array with all the options. */ protected function shortCodeAsset() { return $this->di->url->asset() . "/"; } }
mit
mehulsbhatt/cdr
vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php
50497
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpFoundation\Tests; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Request; class RequestTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\HttpFoundation\Request::__construct */ public function testConstructor() { $this->testInitialize(); } /** * @covers Symfony\Component\HttpFoundation\Request::initialize */ public function testInitialize() { $request = new Request(); $request->initialize(array('foo' => 'bar')); $this->assertEquals('bar', $request->query->get('foo'), '->initialize() takes an array of query parameters as its first argument'); $request->initialize(array(), array('foo' => 'bar')); $this->assertEquals('bar', $request->request->get('foo'), '->initialize() takes an array of request parameters as its second argument'); $request->initialize(array(), array(), array('foo' => 'bar')); $this->assertEquals('bar', $request->attributes->get('foo'), '->initialize() takes an array of attributes as its third argument'); $request->initialize(array(), array(), array(), array(), array(), array('HTTP_FOO' => 'bar')); $this->assertEquals('bar', $request->headers->get('FOO'), '->initialize() takes an array of HTTP headers as its fourth argument'); } /** * @covers Symfony\Component\HttpFoundation\Request::create */ public function testCreate() { $request = Request::create('http://test.com/foo?bar=baz'); $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('bar=baz', $request->getQueryString()); $this->assertEquals(80, $request->getPort()); $this->assertEquals('test.com', $request->getHttpHost()); $this->assertFalse($request->isSecure()); $request = Request::create('http://test.com/foo', 'GET', array('bar' => 'baz')); $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('bar=baz', $request->getQueryString()); $this->assertEquals(80, $request->getPort()); $this->assertEquals('test.com', $request->getHttpHost()); $this->assertFalse($request->isSecure()); $request = Request::create('http://test.com/foo?bar=foo', 'GET', array('bar' => 'baz')); $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('bar=baz', $request->getQueryString()); $this->assertEquals(80, $request->getPort()); $this->assertEquals('test.com', $request->getHttpHost()); $this->assertFalse($request->isSecure()); $request = Request::create('https://test.com/foo?bar=baz'); $this->assertEquals('https://test.com/foo?bar=baz', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('bar=baz', $request->getQueryString()); $this->assertEquals(443, $request->getPort()); $this->assertEquals('test.com', $request->getHttpHost()); $this->assertTrue($request->isSecure()); $request = Request::create('test.com:90/foo'); $this->assertEquals('http://test.com:90/foo', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('test.com', $request->getHost()); $this->assertEquals('test.com:90', $request->getHttpHost()); $this->assertEquals(90, $request->getPort()); $this->assertFalse($request->isSecure()); $request = Request::create('https://test.com:90/foo'); $this->assertEquals('https://test.com:90/foo', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('test.com', $request->getHost()); $this->assertEquals('test.com:90', $request->getHttpHost()); $this->assertEquals(90, $request->getPort()); $this->assertTrue($request->isSecure()); $request = Request::create('https://127.0.0.1:90/foo'); $this->assertEquals('https://127.0.0.1:90/foo', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('127.0.0.1', $request->getHost()); $this->assertEquals('127.0.0.1:90', $request->getHttpHost()); $this->assertEquals(90, $request->getPort()); $this->assertTrue($request->isSecure()); $request = Request::create('https://[::1]:90/foo'); $this->assertEquals('https://[::1]:90/foo', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('[::1]', $request->getHost()); $this->assertEquals('[::1]:90', $request->getHttpHost()); $this->assertEquals(90, $request->getPort()); $this->assertTrue($request->isSecure()); $json = '{"jsonrpc":"2.0","method":"echo","id":7,"params":["Hello World"]}'; $request = Request::create('http://example.com/jsonrpc', 'POST', array(), array(), array(), array(), $json); $this->assertEquals($json, $request->getContent()); $this->assertFalse($request->isSecure()); $request = Request::create('http://test.com'); $this->assertEquals('http://test.com/', $request->getUri()); $this->assertEquals('/', $request->getPathInfo()); $this->assertEquals('', $request->getQueryString()); $this->assertEquals(80, $request->getPort()); $this->assertEquals('test.com', $request->getHttpHost()); $this->assertFalse($request->isSecure()); $request = Request::create('http://test.com:90/?test=1'); $this->assertEquals('http://test.com:90/?test=1', $request->getUri()); $this->assertEquals('/', $request->getPathInfo()); $this->assertEquals('test=1', $request->getQueryString()); $this->assertEquals(90, $request->getPort()); $this->assertEquals('test.com:90', $request->getHttpHost()); $this->assertFalse($request->isSecure()); $request = Request::create('http://test:[email protected]'); $this->assertEquals('http://test:[email protected]/', $request->getUri()); $this->assertEquals('/', $request->getPathInfo()); $this->assertEquals('', $request->getQueryString()); $this->assertEquals(80, $request->getPort()); $this->assertEquals('test.com', $request->getHttpHost()); $this->assertEquals('test', $request->getUser()); $this->assertEquals('test', $request->getPassword()); $this->assertFalse($request->isSecure()); $request = Request::create('http://[email protected]'); $this->assertEquals('http://[email protected]/', $request->getUri()); $this->assertEquals('/', $request->getPathInfo()); $this->assertEquals('', $request->getQueryString()); $this->assertEquals(80, $request->getPort()); $this->assertEquals('test.com', $request->getHttpHost()); $this->assertEquals('testnopass', $request->getUser()); $this->assertNull($request->getPassword()); $this->assertFalse($request->isSecure()); } /** * @covers Symfony\Component\HttpFoundation\Request::duplicate */ public function testDuplicate() { $request = new Request(array('foo' => 'bar'), array('foo' => 'bar'), array('foo' => 'bar'), array(), array(), array('HTTP_FOO' => 'bar')); $dup = $request->duplicate(); $this->assertEquals($request->query->all(), $dup->query->all(), '->duplicate() duplicates a request an copy the current query parameters'); $this->assertEquals($request->request->all(), $dup->request->all(), '->duplicate() duplicates a request an copy the current request parameters'); $this->assertEquals($request->attributes->all(), $dup->attributes->all(), '->duplicate() duplicates a request an copy the current attributes'); $this->assertEquals($request->headers->all(), $dup->headers->all(), '->duplicate() duplicates a request an copy the current HTTP headers'); $dup = $request->duplicate(array('foo' => 'foobar'), array('foo' => 'foobar'), array('foo' => 'foobar'), array(), array(), array('HTTP_FOO' => 'foobar')); $this->assertEquals(array('foo' => 'foobar'), $dup->query->all(), '->duplicate() overrides the query parameters if provided'); $this->assertEquals(array('foo' => 'foobar'), $dup->request->all(), '->duplicate() overrides the request parameters if provided'); $this->assertEquals(array('foo' => 'foobar'), $dup->attributes->all(), '->duplicate() overrides the attributes if provided'); $this->assertEquals(array('foo' => array('foobar')), $dup->headers->all(), '->duplicate() overrides the HTTP header if provided'); } /** * @covers Symfony\Component\HttpFoundation\Request::getFormat * @covers Symfony\Component\HttpFoundation\Request::setFormat * @dataProvider getFormatToMimeTypeMapProvider */ public function testGetFormatFromMimeType($format, $mimeTypes) { $request = new Request(); foreach ($mimeTypes as $mime) { $this->assertEquals($format, $request->getFormat($mime)); } $request->setFormat($format, $mimeTypes); foreach ($mimeTypes as $mime) { $this->assertEquals($format, $request->getFormat($mime)); } } /** * @covers Symfony\Component\HttpFoundation\Request::getFormat */ public function testGetFormatFromMimeTypeWithParameters() { $request = new Request(); $this->assertEquals('json', $request->getFormat('application/json; charset=utf-8')); } /** * @covers Symfony\Component\HttpFoundation\Request::getMimeType * @dataProvider getFormatToMimeTypeMapProvider */ public function testGetMimeTypeFromFormat($format, $mimeTypes) { if (null !== $format) { $request = new Request(); $this->assertEquals($mimeTypes[0], $request->getMimeType($format)); } } public function getFormatToMimeTypeMapProvider() { return array( array(null, array(null, 'unexistent-mime-type')), array('txt', array('text/plain')), array('js', array('application/javascript', 'application/x-javascript', 'text/javascript')), array('css', array('text/css')), array('json', array('application/json', 'application/x-json')), array('xml', array('text/xml', 'application/xml', 'application/x-xml')), array('rdf', array('application/rdf+xml')), array('atom',array('application/atom+xml')), ); } /** * @covers Symfony\Component\HttpFoundation\Request::getUri */ public function testGetUri() { $server = array(); // Standard Request on non default PORT // http://hostname:8080/index.php/path/info?query=string $server['HTTP_HOST'] = 'hostname:8080'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '8080'; $server['QUERY_STRING'] = 'query=string'; $server['REQUEST_URI'] = '/index.php/path/info?query=string'; $server['SCRIPT_NAME'] = '/index.php'; $server['PATH_INFO'] = '/path/info'; $server['PATH_TRANSLATED'] = 'redirect:/index.php/path/info'; $server['PHP_SELF'] = '/index_dev.php/path/info'; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $request = new Request(); $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://hostname:8080/index.php/path/info?query=string', $request->getUri(), '->getUri() with non default port'); // Use std port number $server['HTTP_HOST'] = 'hostname'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://hostname/index.php/path/info?query=string', $request->getUri(), '->getUri() with default port'); // Without HOST HEADER unset($server['HTTP_HOST']); $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://servername/index.php/path/info?query=string', $request->getUri(), '->getUri() with default port without HOST_HEADER'); // Request with URL REWRITING (hide index.php) // RewriteCond %{REQUEST_FILENAME} !-f // RewriteRule ^(.*)$ index.php [QSA,L] // http://hostname:8080/path/info?query=string $server = array(); $server['HTTP_HOST'] = 'hostname:8080'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '8080'; $server['REDIRECT_QUERY_STRING'] = 'query=string'; $server['REDIRECT_URL'] = '/path/info'; $server['SCRIPT_NAME'] = '/index.php'; $server['QUERY_STRING'] = 'query=string'; $server['REQUEST_URI'] = '/path/info?toto=test&1=1'; $server['SCRIPT_NAME'] = '/index.php'; $server['PHP_SELF'] = '/index.php'; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://hostname:8080/path/info?query=string', $request->getUri(), '->getUri() with rewrite'); // Use std port number // http://hostname/path/info?query=string $server['HTTP_HOST'] = 'hostname'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://hostname/path/info?query=string', $request->getUri(), '->getUri() with rewrite and default port'); // Without HOST HEADER unset($server['HTTP_HOST']); $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://servername/path/info?query=string', $request->getUri(), '->getUri() with rewrite, default port without HOST_HEADER'); // With encoded characters $server = array( 'HTTP_HOST' => 'hostname:8080', 'SERVER_NAME' => 'servername', 'SERVER_PORT' => '8080', 'QUERY_STRING' => 'query=string', 'REQUEST_URI' => '/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', 'SCRIPT_NAME' => '/ba se/index_dev.php', 'PATH_TRANSLATED' => 'redirect:/index.php/foo bar/in+fo', 'PHP_SELF' => '/ba se/index_dev.php/path/info', 'SCRIPT_FILENAME' => '/some/where/ba se/index_dev.php', ); $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals( 'http://hostname:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri() ); // with user info $server['PHP_AUTH_USER'] = 'fabien'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://fabien@hostname:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri()); $server['PHP_AUTH_PW'] = 'symfony'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://fabien:symfony@hostname:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri()); } /** * @covers Symfony\Component\HttpFoundation\Request::getUriForPath */ public function testGetUriForPath() { $request = Request::create('http://test.com/foo?bar=baz'); $this->assertEquals('http://test.com/some/path', $request->getUriForPath('/some/path')); $request = Request::create('http://test.com:90/foo?bar=baz'); $this->assertEquals('http://test.com:90/some/path', $request->getUriForPath('/some/path')); $request = Request::create('https://test.com/foo?bar=baz'); $this->assertEquals('https://test.com/some/path', $request->getUriForPath('/some/path')); $request = Request::create('https://test.com:90/foo?bar=baz'); $this->assertEquals('https://test.com:90/some/path', $request->getUriForPath('/some/path')); $server = array(); // Standard Request on non default PORT // http://hostname:8080/index.php/path/info?query=string $server['HTTP_HOST'] = 'hostname:8080'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '8080'; $server['QUERY_STRING'] = 'query=string'; $server['REQUEST_URI'] = '/index.php/path/info?query=string'; $server['SCRIPT_NAME'] = '/index.php'; $server['PATH_INFO'] = '/path/info'; $server['PATH_TRANSLATED'] = 'redirect:/index.php/path/info'; $server['PHP_SELF'] = '/index_dev.php/path/info'; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $request = new Request(); $request->initialize(array(), array(), array(), array(), array(),$server); $this->assertEquals('http://hostname:8080/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with non default port'); // Use std port number $server['HTTP_HOST'] = 'hostname'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://hostname/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port'); // Without HOST HEADER unset($server['HTTP_HOST']); $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://servername/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port without HOST_HEADER'); // Request with URL REWRITING (hide index.php) // RewriteCond %{REQUEST_FILENAME} !-f // RewriteRule ^(.*)$ index.php [QSA,L] // http://hostname:8080/path/info?query=string $server = array(); $server['HTTP_HOST'] = 'hostname:8080'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '8080'; $server['REDIRECT_QUERY_STRING'] = 'query=string'; $server['REDIRECT_URL'] = '/path/info'; $server['SCRIPT_NAME'] = '/index.php'; $server['QUERY_STRING'] = 'query=string'; $server['REQUEST_URI'] = '/path/info?toto=test&1=1'; $server['SCRIPT_NAME'] = '/index.php'; $server['PHP_SELF'] = '/index.php'; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://hostname:8080/some/path', $request->getUriForPath('/some/path'), '->getUri() with rewrite'); // Use std port number // http://hostname/path/info?query=string $server['HTTP_HOST'] = 'hostname'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://hostname/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite and default port'); // Without HOST HEADER unset($server['HTTP_HOST']); $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite, default port without HOST_HEADER'); $this->assertEquals('servername', $request->getHttpHost()); // with user info $server['PHP_AUTH_USER'] = 'fabien'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://fabien@servername/some/path', $request->getUriForPath('/some/path')); $server['PHP_AUTH_PW'] = 'symfony'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://fabien:symfony@servername/some/path', $request->getUriForPath('/some/path')); } /** * @covers Symfony\Component\HttpFoundation\Request::getUserInfo */ public function testGetUserInfo() { $request = new Request(); $server['PHP_AUTH_USER'] = 'fabien'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('fabien', $request->getUserInfo()); $server['PHP_AUTH_USER'] = '0'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('0', $request->getUserInfo()); $server['PHP_AUTH_PW'] = '0'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('0:0', $request->getUserInfo()); } /** * @covers Symfony\Component\HttpFoundation\Request::getSchemeAndHttpHost */ public function testGetSchemeAndHttpHost() { $request = new Request(); $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '90'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost()); $server['PHP_AUTH_USER'] = 'fabien'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://fabien@servername:90', $request->getSchemeAndHttpHost()); $server['PHP_AUTH_USER'] = '0'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://0@servername:90', $request->getSchemeAndHttpHost()); $server['PHP_AUTH_PW'] = '0'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('http://0:0@servername:90', $request->getSchemeAndHttpHost()); } /** * @covers Symfony\Component\HttpFoundation\Request::getQueryString * @covers Symfony\Component\HttpFoundation\Request::normalizeQueryString * @dataProvider getQueryStringNormalizationData */ public function testGetQueryString($query, $expectedQuery, $msg) { $request = new Request(); $request->server->set('QUERY_STRING', $query); $this->assertSame($expectedQuery, $request->getQueryString(), $msg); } public function getQueryStringNormalizationData() { return array( array('foo', 'foo', 'works with valueless parameters'), array('foo=', 'foo=', 'includes a dangling equal sign'), array('bar=&foo=bar', 'bar=&foo=bar', '->works with empty parameters'), array('foo=bar&bar=', 'bar=&foo=bar', 'sorts keys alphabetically'), // GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded). // PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. array('him=John%20Doe&her=Jane+Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes spaces in both encodings "%20" and "+"'), array('foo[]=1&foo[]=2', 'foo%5B%5D=1&foo%5B%5D=2', 'allows array notation'), array('foo=1&foo=2', 'foo=1&foo=2', 'allows repeated parameters'), array('pa%3Dram=foo%26bar%3Dbaz&test=test', 'pa%3Dram=foo%26bar%3Dbaz&test=test', 'works with encoded delimiters'), array('0', '0', 'allows "0"'), array('Jane Doe&John%20Doe', 'Jane%20Doe&John%20Doe', 'normalizes encoding in keys'), array('her=Jane Doe&him=John%20Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes encoding in values'), array('foo=bar&&&test&&', 'foo=bar&test', 'removes unneeded delimiters'), array('formula=e=m*c^2', 'formula=e%3Dm%2Ac%5E2', 'correctly treats only the first "=" as delimiter and the next as value'), // Ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway. // PHP also does not include them when building _GET. array('foo=bar&=a=b&=x=y', 'foo=bar', 'removes params with empty key'), ); } public function testGetQueryStringReturnsNull() { $request = new Request(); $this->assertNull($request->getQueryString(), '->getQueryString() returns null for non-existent query string'); $request->server->set('QUERY_STRING', ''); $this->assertNull($request->getQueryString(), '->getQueryString() returns null for empty query string'); } /** * @covers Symfony\Component\HttpFoundation\Request::getHost */ public function testGetHost() { $request = new Request(); $request->initialize(array('foo' => 'bar')); $this->assertEquals('', $request->getHost(), '->getHost() return empty string if not initialized'); $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.exemple.com')); $this->assertEquals('www.exemple.com', $request->getHost(), '->getHost() from Host Header'); // Host header with port number. $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.exemple.com:8080')); $this->assertEquals('www.exemple.com', $request->getHost(), '->getHost() from Host Header with port number'); // Server values. $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.exemple.com')); $this->assertEquals('www.exemple.com', $request->getHost(), '->getHost() from server name'); $this->startTrustingProxyData(); // X_FORWARDED_HOST. $request->initialize(array(), array(), array(), array(), array(), array('HTTP_X_FORWARDED_HOST' => 'www.exemple.com')); $this->assertEquals('www.exemple.com', $request->getHost(), '->getHost() from X_FORWARDED_HOST'); // X_FORWARDED_HOST $request->initialize(array(), array(), array(), array(), array(), array('HTTP_X_FORWARDED_HOST' => 'www.exemple.com, www.second.com')); $this->assertEquals('www.second.com', $request->getHost(), '->getHost() value from X_FORWARDED_HOST use last value'); // X_FORWARDED_HOST with port number $request->initialize(array(), array(), array(), array(), array(), array('HTTP_X_FORWARDED_HOST' => 'www.exemple.com, www.second.com:8080')); $this->assertEquals('www.second.com', $request->getHost(), '->getHost() value from X_FORWARDED_HOST with port number'); $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.exemple.com', 'HTTP_X_FORWARDED_HOST' => 'www.forward.com')); $this->assertEquals('www.forward.com', $request->getHost(), '->getHost() value from X_FORWARDED_HOST has priority over Host'); $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.exemple.com', 'HTTP_X_FORWARDED_HOST' => 'www.forward.com')); $this->assertEquals('www.forward.com', $request->getHost(), '->getHost() value from X_FORWARDED_HOST has priority over SERVER_NAME '); $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.exemple.com', 'HTTP_HOST' => 'www.host.com')); $this->assertEquals('www.host.com', $request->getHost(), '->getHost() value from Host header has priority over SERVER_NAME '); $this->stopTrustingProxyData(); } /** * @covers Symfony\Component\HttpFoundation\Request::setMethod * @covers Symfony\Component\HttpFoundation\Request::getMethod */ public function testGetSetMethod() { $request = new Request(); $this->assertEquals('GET', $request->getMethod(), '->getMethod() returns GET if no method is defined'); $request->setMethod('get'); $this->assertEquals('GET', $request->getMethod(), '->getMethod() returns an uppercased string'); $request->setMethod('PURGE'); $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method even if it is not a standard one'); $request->setMethod('POST'); $this->assertEquals('POST', $request->getMethod(), '->getMethod() returns the method POST if no _method is defined'); $request->setMethod('POST'); $request->request->set('_method', 'purge'); $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method from _method if defined and POST'); $request->setMethod('POST'); $request->request->remove('_method'); $request->query->set('_method', 'purge'); $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method from _method if defined and POST'); $request->setMethod('POST'); $request->headers->set('X-HTTP-METHOD-OVERRIDE', 'delete'); $this->assertEquals('DELETE', $request->getMethod(), '->getMethod() returns the method from X-HTTP-Method-Override even though _method is set if defined and POST'); $request = new Request(); $request->setMethod('POST'); $request->headers->set('X-HTTP-METHOD-OVERRIDE', 'delete'); $this->assertEquals('DELETE', $request->getMethod(), '->getMethod() returns the method from X-HTTP-Method-Override if defined and POST'); } /** * @dataProvider testGetClientIpProvider */ public function testGetClientIp($expected, $proxy, $remoteAddr, $httpClientIp, $httpForwardedFor) { $request = new Request(); $this->assertEquals('', $request->getClientIp()); $server = array('REMOTE_ADDR' => $remoteAddr); if (null !== $httpClientIp) { $server['HTTP_CLIENT_IP'] = $httpClientIp; } if (null !== $httpForwardedFor) { $server['HTTP_X_FORWARDED_FOR'] = $httpForwardedFor; } $request->initialize(array(), array(), array(), array(), array(), $server); if ($proxy) { $this->startTrustingProxyData(); } $this->assertEquals($expected, $request->getClientIp($proxy)); if ($proxy) { $this->stopTrustingProxyData(); } } public function testGetClientIpProvider() { return array( array('88.88.88.88', false, '88.88.88.88', null, null), array('127.0.0.1', false, '127.0.0.1', '88.88.88.88', null), array('88.88.88.88', true, '127.0.0.1', '88.88.88.88', null), array('127.0.0.1', false, '127.0.0.1', null, '88.88.88.88'), array('88.88.88.88', true, '127.0.0.1', null, '88.88.88.88'), array('::1', false, '::1', null, null), array('2620:0:1cfe:face:b00c::3', true, '::1', '2620:0:1cfe:face:b00c::3', null), array('2620:0:1cfe:face:b00c::3', true, '::1', null, '2620:0:1cfe:face:b00c::3, ::1'), array('88.88.88.88', true, '123.45.67.89', null, '88.88.88.88, 87.65.43.21, 127.0.0.1'), array('88.88.88.88', true, '123.45.67.89', null, 'unknown, 88.88.88.88'), ); } public function testGetContentWorksTwiceInDefaultMode() { $req = new Request; $this->assertEquals('', $req->getContent()); $this->assertEquals('', $req->getContent()); } public function testGetContentReturnsResource() { $req = new Request; $retval = $req->getContent(true); $this->assertInternalType('resource', $retval); $this->assertEquals("", fread($retval, 1)); $this->assertTrue(feof($retval)); } /** * @expectedException LogicException * @dataProvider getContentCantBeCalledTwiceWithResourcesProvider */ public function testGetContentCantBeCalledTwiceWithResources($first, $second) { $req = new Request; $req->getContent($first); $req->getContent($second); } public function getContentCantBeCalledTwiceWithResourcesProvider() { return array( 'Resource then fetch' => array(true, false), 'Resource then resource' => array(true, true), 'Fetch then resource' => array(false, true), ); } public function provideOverloadedMethods() { return array( array('PUT'), array('DELETE'), array('PATCH'), ); } /** * @dataProvider provideOverloadedMethods */ public function testCreateFromGlobals($method) { $_GET['foo1'] = 'bar1'; $_POST['foo2'] = 'bar2'; $_COOKIE['foo3'] = 'bar3'; $_FILES['foo4'] = array('bar4'); $_SERVER['foo5'] = 'bar5'; $request = Request::createFromGlobals(); $this->assertEquals('bar1', $request->query->get('foo1'), '::fromGlobals() uses values from $_GET'); $this->assertEquals('bar2', $request->request->get('foo2'), '::fromGlobals() uses values from $_POST'); $this->assertEquals('bar3', $request->cookies->get('foo3'), '::fromGlobals() uses values from $_COOKIE'); $this->assertEquals(array('bar4'), $request->files->get('foo4'), '::fromGlobals() uses values from $_FILES'); $this->assertEquals('bar5', $request->server->get('foo5'), '::fromGlobals() uses values from $_SERVER'); unset($_GET['foo1'], $_POST['foo2'], $_COOKIE['foo3'], $_FILES['foo4'], $_SERVER['foo5']); $_SERVER['REQUEST_METHOD'] = $method; $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; $request = RequestContentProxy::createFromGlobals(); $this->assertEquals($method, $request->getMethod()); $this->assertEquals('mycontent', $request->request->get('content')); unset($_SERVER['REQUEST_METHOD'], $_SERVER['CONTENT_TYPE']); $_POST['_method'] = $method; $_POST['foo6'] = 'bar6'; $_SERVER['REQUEST_METHOD'] = 'POST'; $request = Request::createFromGlobals(); $this->assertEquals($method, $request->getMethod()); $this->assertEquals('bar6', $request->request->get('foo6')); unset($_POST['_method'], $_POST['foo6'], $_SERVER['REQUEST_METHOD']); } public function testOverrideGlobals() { $request = new Request(); $request->initialize(array('foo' => 'bar')); // as the Request::overrideGlobals really work, it erase $_SERVER, so we must backup it $server = $_SERVER; $request->overrideGlobals(); $this->assertEquals(array('foo' => 'bar'), $_GET); $request->initialize(array(), array('foo' => 'bar')); $request->overrideGlobals(); $this->assertEquals(array('foo' => 'bar'), $_POST); $this->assertArrayNotHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER); $this->startTrustingProxyData(); $request->headers->set('X_FORWARDED_PROTO', 'https'); $this->assertTrue($request->isSecure()); $this->stopTrustingProxyData(); $request->overrideGlobals(); $this->assertArrayHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER); // restore initial $_SERVER array $_SERVER = $server; } public function testGetScriptName() { $request = new Request(); $this->assertEquals('', $request->getScriptName()); $server = array(); $server['SCRIPT_NAME'] = '/index.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('/index.php', $request->getScriptName()); $server = array(); $server['ORIG_SCRIPT_NAME'] = '/frontend.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('/frontend.php', $request->getScriptName()); $server = array(); $server['SCRIPT_NAME'] = '/index.php'; $server['ORIG_SCRIPT_NAME'] = '/frontend.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('/index.php', $request->getScriptName()); } public function testGetBasePath() { $request = new Request(); $this->assertEquals('', $request->getBasePath()); $server = array(); $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('', $request->getBasePath()); $server = array(); $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $server['SCRIPT_NAME'] = '/index.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('', $request->getBasePath()); $server = array(); $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $server['PHP_SELF'] = '/index.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('', $request->getBasePath()); $server = array(); $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $server['ORIG_SCRIPT_NAME'] = '/index.php'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('', $request->getBasePath()); } public function testGetPathInfo() { $request = new Request(); $this->assertEquals('/', $request->getPathInfo()); $server = array(); $server['REQUEST_URI'] = '/path/info'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('/path/info', $request->getPathInfo()); $server = array(); $server['REQUEST_URI'] = '/path%20test/info'; $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('/path%20test/info', $request->getPathInfo()); } public function testGetPreferredLanguage() { $request = new Request(); $this->assertNull($request->getPreferredLanguage()); $this->assertNull($request->getPreferredLanguage(array())); $this->assertEquals('fr', $request->getPreferredLanguage(array('fr'))); $this->assertEquals('fr', $request->getPreferredLanguage(array('fr', 'en'))); $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'fr'))); $this->assertEquals('fr-ch', $request->getPreferredLanguage(array('fr-ch', 'fr-fr'))); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'en-us'))); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en'))); } public function testIsXmlHttpRequest() { $request = new Request(); $this->assertFalse($request->isXmlHttpRequest()); $request->headers->set('X-Requested-With', 'XMLHttpRequest'); $this->assertTrue($request->isXmlHttpRequest()); $request->headers->remove('X-Requested-With'); $this->assertFalse($request->isXmlHttpRequest()); } public function testGetCharsets() { $request = new Request(); $this->assertEquals(array(), $request->getCharsets()); $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6'); $this->assertEquals(array(), $request->getCharsets()); // testing caching $request = new Request(); $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6'); $this->assertEquals(array('ISO-8859-1', 'US-ASCII', 'UTF-8', 'ISO-10646-UCS-2'), $request->getCharsets()); $request = new Request(); $request->headers->set('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'); $this->assertEquals(array('ISO-8859-1', '*', 'utf-8'), $request->getCharsets()); } public function testGetAcceptableContentTypes() { $request = new Request(); $this->assertEquals(array(), $request->getAcceptableContentTypes()); $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*'); $this->assertEquals(array(), $request->getAcceptableContentTypes()); // testing caching $request = new Request(); $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*'); $this->assertEquals(array('multipart/mixed', '*/*', 'text/html', 'application/xhtml+xml', 'text/vnd.wap.wml', 'application/vnd.wap.xhtml+xml', 'application/vnd.wap.wmlscriptc'), $request->getAcceptableContentTypes()); } public function testGetLanguages() { $request = new Request(); $this->assertEquals(array(), $request->getLanguages()); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); $this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages()); $this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages()); $request = new Request(); $request->headers->set('Accept-language', 'zh, i-cherokee; q=0.6'); $this->assertEquals(array('zh', 'cherokee'), $request->getLanguages()); } public function testGetRequestFormat() { $request = new Request(); $this->assertEquals('html', $request->getRequestFormat()); $request = new Request(); $this->assertNull($request->getRequestFormat(null)); $request = new Request(); $this->assertNull($request->setRequestFormat('foo')); $this->assertEquals('foo', $request->getRequestFormat(null)); } public function testForwardedSecure() { $request = new Request(); $request->headers->set('X-Forwarded-Proto', 'https'); $request->headers->set('X-Forwarded-Port', 443); $this->startTrustingProxyData(); $this->assertTrue($request->isSecure()); $this->assertEquals(443, $request->getPort()); $this->stopTrustingProxyData(); } public function testHasSession() { $request = new Request(); $this->assertFalse($request->hasSession()); $request->setSession(new Session(new MockArraySessionStorage())); $this->assertTrue($request->hasSession()); } public function testHasPreviousSession() { $request = new Request(); $this->assertFalse($request->hasPreviousSession()); $request->cookies->set('MOCKSESSID', 'foo'); $this->assertFalse($request->hasPreviousSession()); $request->setSession(new Session(new MockArraySessionStorage())); $this->assertTrue($request->hasPreviousSession()); } public function testToString() { $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); $this->assertContains('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $request->__toString()); } /** * @dataProvider splitHttpAcceptHeaderData */ public function testSplitHttpAcceptHeader($acceptHeader, $expected) { $request = new Request(); $this->assertEquals($expected, $request->splitHttpAcceptHeader($acceptHeader)); } public function splitHttpAcceptHeaderData() { return array( array(null, array()), array('text/html;q=0.8', array('text/html' => 0.8)), array('text/html;foo=bar;q=0.8 ', array('text/html;foo=bar' => 0.8)), array('text/html;charset=utf-8; q=0.8', array('text/html;charset=utf-8' => 0.8)), array('text/html,application/xml;q=0.9,*/*;charset=utf-8; q=0.8', array('text/html' => 1, 'application/xml' => 0.9, '*/*;charset=utf-8' => 0.8)), array('text/html,application/xhtml+xml;q=0.9,*/*;q=0.8; foo=bar', array('text/html' => 1, 'application/xhtml+xml' => 0.9, '*/*' => 0.8)), array('text/html,application/xhtml+xml;charset=utf-8;q=0.9; foo=bar,*/*', array('text/html' => 1, '*/*' => 1, 'application/xhtml+xml;charset=utf-8' => 0.9)), array('text/html,application/xhtml+xml', array('application/xhtml+xml' => 1, 'text/html' => 1)), ); } public function testIsProxyTrusted() { $this->startTrustingProxyData(); $this->assertTrue(Request::isProxyTrusted()); $this->stopTrustingProxyData(); $this->assertFalse(Request::isProxyTrusted()); } public function testIsMethod() { $request = new Request(); $request->setMethod('POST'); $this->assertTrue($request->isMethod('POST')); $this->assertTrue($request->isMethod('post')); $this->assertFalse($request->isMethod('GET')); $this->assertFalse($request->isMethod('get')); $request->setMethod('GET'); $this->assertTrue($request->isMethod('GET')); $this->assertTrue($request->isMethod('get')); $this->assertFalse($request->isMethod('POST')); $this->assertFalse($request->isMethod('post')); } private function startTrustingProxyData() { Request::trustProxyData(); } /** * @dataProvider getBaseUrlData */ public function testGetBaseUrl($uri, $server, $expectedBaseUrl, $expectedPathInfo) { $request = Request::create($uri, 'GET', array(), array(), array(), $server); $this->assertSame($expectedBaseUrl, $request->getBaseUrl(), 'baseUrl'); $this->assertSame($expectedPathInfo, $request->getPathInfo(), 'pathInfo'); } public function getBaseUrlData() { return array( array( '/foo%20bar', array( 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php', 'SCRIPT_NAME' => '/foo bar/app.php', 'PHP_SELF' => '/foo bar/app.php', ), '/foo%20bar', '/', ), array( '/foo%20bar/home', array( 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php', 'SCRIPT_NAME' => '/foo bar/app.php', 'PHP_SELF' => '/foo bar/app.php', ), '/foo%20bar', '/home', ), array( '/foo%20bar/app.php/home', array( 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php', 'SCRIPT_NAME' => '/foo bar/app.php', 'PHP_SELF' => '/foo bar/app.php', ), '/foo%20bar/app.php', '/home', ), array( '/foo%20bar/app.php/home%3Dbaz', array( 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php', 'SCRIPT_NAME' => '/foo bar/app.php', 'PHP_SELF' => '/foo bar/app.php', ), '/foo%20bar/app.php', '/home%3Dbaz', ), array( '/foo/bar+baz', array( 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo/app.php', 'SCRIPT_NAME' => '/foo/app.php', 'PHP_SELF' => '/foo/app.php', ), '/foo', '/bar+baz', ), ); } /** * @dataProvider urlencodedStringPrefixData */ public function testUrlencodedStringPrefix($string, $prefix, $expect) { $request = new Request; $me = new \ReflectionMethod($request, 'getUrlencodedPrefix'); $me->setAccessible(true); $this->assertSame($expect, $me->invoke($request, $string, $prefix)); } public function urlencodedStringPrefixData() { return array( array('foo', 'foo', 'foo'), array('fo%6f', 'foo', 'fo%6f'), array('foo/bar', 'foo', 'foo'), array('fo%6f/bar', 'foo', 'fo%6f'), array('f%6f%6f/bar', 'foo', 'f%6f%6f'), array('%66%6F%6F/bar', 'foo', '%66%6F%6F'), array('fo+o/bar', 'fo+o', 'fo+o'), array('fo%2Bo/bar', 'fo+o', 'fo%2Bo'), ); } private function stopTrustingProxyData() { $class = new \ReflectionClass('Symfony\\Component\\HttpFoundation\\Request'); $property = $class->getProperty('trustProxy'); $property->setAccessible(true); $property->setValue(false); } } class RequestContentProxy extends Request { public function getContent($asResource = false) { return http_build_query(array('_method' => 'PUT', 'content' => 'mycontent')); } }
mit
marc-barry/arpwatch
Godeps/_workspace/src/code.google.com/p/gopacket/macs/benchmark_test.go
368
// Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. package macs import ( "testing" ) func BenchmarkCheckEthernetPrefix(b *testing.B) { key := [3]byte{5, 5, 5} for i := 0; i < b.N; i++ { _ = ValidMACPrefixMap[key] } }
mit
jiangyifangh/presto
presto-local-file/src/test/java/com/facebook/presto/localfile/TestLocalFileColumnHandle.java
2051
/* * 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. */ package com.facebook.presto.localfile; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; import java.util.List; import static com.facebook.presto.localfile.MetadataUtil.COLUMN_CODEC; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DateType.DATE; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP; import static com.facebook.presto.spi.type.VarcharType.createUnboundedVarcharType; import static org.testng.Assert.assertEquals; public class TestLocalFileColumnHandle { private final List<LocalFileColumnHandle> columnHandle = ImmutableList.of( new LocalFileColumnHandle("columnName", createUnboundedVarcharType(), 0), new LocalFileColumnHandle("columnName", BIGINT, 0), new LocalFileColumnHandle("columnName", DOUBLE, 0), new LocalFileColumnHandle("columnName", DATE, 0), new LocalFileColumnHandle("columnName", TIMESTAMP, 0), new LocalFileColumnHandle("columnName", BOOLEAN, 0)); @Test public void testJsonRoundTrip() { for (LocalFileColumnHandle handle : columnHandle) { String json = COLUMN_CODEC.toJson(handle); LocalFileColumnHandle copy = COLUMN_CODEC.fromJson(json); assertEquals(copy, handle); } } }
apache-2.0
vinodkc/spark
core/src/main/resources/org/apache/spark/ui/static/dataTables.bootstrap4.1.10.20.min.js
3159
/*! DataTables Bootstrap 4 integration ©2011-2017 SpryMedia Ltd - datatables.net/license */ var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(a,b,c){a instanceof String&&(a=String(a));for(var e=a.length,d=0;d<e;d++){var k=a[d];if(b.call(c,k,d,a))return{i:d,v:k}}return{i:-1,v:void 0}};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1; $jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){a!=Array.prototype&&a!=Object.prototype&&(a[b]=c.value)};$jscomp.getGlobal=function(a){return"undefined"!=typeof window&&window===a?a:"undefined"!=typeof global&&null!=global?global:a};$jscomp.global=$jscomp.getGlobal(this); $jscomp.polyfill=function(a,b,c,e){if(b){c=$jscomp.global;a=a.split(".");for(e=0;e<a.length-1;e++){var d=a[e];d in c||(c[d]={});c=c[d]}a=a[a.length-1];e=c[a];b=b(e);b!=e&&null!=b&&$jscomp.defineProperty(c,a,{configurable:!0,writable:!0,value:b})}};$jscomp.polyfill("Array.prototype.find",function(a){return a?a:function(a,c){return $jscomp.findInternal(this,a,c).v}},"es6","es3"); (function(a){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(b){return a(b,window,document)}):"object"===typeof exports?module.exports=function(b,c){b||(b=window);c&&c.fn.dataTable||(c=require("datatables.net")(b,c).$);return a(c,b,b.document)}:a(jQuery,window,document)})(function(a,b,c,e){var d=a.fn.dataTable;a.extend(!0,d.defaults,{dom:"<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>", renderer:"bootstrap"});a.extend(d.ext.classes,{sWrapper:"dataTables_wrapper dt-bootstrap4",sFilterInput:"form-control form-control-sm",sLengthSelect:"custom-select custom-select-sm form-control form-control-sm",sProcessing:"dataTables_processing card",sPageButton:"paginate_button page-item"});d.ext.renderer.pageButton.bootstrap=function(b,l,v,w,m,r){var k=new d.Api(b),x=b.oClasses,n=b.oLanguage.oPaginate,y=b.oLanguage.oAria.paginate||{},g,h,t=0,u=function(c,d){var e,l=function(b){b.preventDefault(); a(b.currentTarget).hasClass("disabled")||k.page()==b.data.action||k.page(b.data.action).draw("page")};var q=0;for(e=d.length;q<e;q++){var f=d[q];if(a.isArray(f))u(c,f);else{h=g="";switch(f){case "ellipsis":g="&#x2026;";h="disabled";break;case "first":g=n.sFirst;h=f+(0<m?"":" disabled");break;case "previous":g=n.sPrevious;h=f+(0<m?"":" disabled");break;case "next":g=n.sNext;h=f+(m<r-1?"":" disabled");break;case "last":g=n.sLast;h=f+(m<r-1?"":" disabled");break;default:g=f+1,h=m===f?"active":""}if(g){var p= a("<li>",{"class":x.sPageButton+" "+h,id:0===v&&"string"===typeof f?b.sTableId+"_"+f:null}).append(a("<a>",{href:"#","aria-controls":b.sTableId,"aria-label":y[f],"data-dt-idx":t,tabindex:b.iTabIndex,"class":"page-link"}).html(g)).appendTo(c);b.oApi._fnBindAction(p,{action:f},l);t++}}}};try{var p=a(l).find(c.activeElement).data("dt-idx")}catch(z){}u(a(l).empty().html('<ul class="pagination"/>').children("ul"),w);p!==e&&a(l).find("[data-dt-idx="+p+"]").focus()};return d});
apache-2.0
KitoHo/actor-platform
actor-apps/core/src/main/java/im/actor/model/mvvm/generics/UserPresenceValueModel.java
589
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.model.mvvm.generics; import im.actor.model.mvvm.ValueModel; import im.actor.model.viewmodel.UserPresence; public class UserPresenceValueModel extends ValueModel<UserPresence> { /** * Create ValueModel * * @param name name of variable * @param defaultValue default value */ public UserPresenceValueModel(String name, UserPresence defaultValue) { super(name, defaultValue); } @Override public UserPresence get() { return super.get(); } }
mit
argos83/faker
test/test_faker_bitcoin.rb
395
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerBitcoin < Test::Unit::TestCase def test_address assert Faker::Bitcoin.address.match(/^[13][1-9A-Za-z][^OIl]{20,40}/) end def test_testnet_address assert_match(/\A[mn][1-9A-Za-z]{32,34}\Z/, Faker::Bitcoin.testnet_address) assert_not_match(/[OIl]/, Faker::Bitcoin.testnet_address) end end
mit
xnox/docker
vendor/src/github.com/docker/libnetwork/drivers/bridge/setup_device.go
1301
package bridge import ( "github.com/docker/docker/pkg/parsers/kernel" "github.com/vishvananda/netlink" ) // SetupDevice create a new bridge interface/ func setupDevice(config *networkConfiguration, i *bridgeInterface) error { var setMac bool // We only attempt to create the bridge when the requested device name is // the default one. if config.BridgeName != DefaultBridgeName && !config.AllowNonDefaultBridge { return NonDefaultBridgeExistError(config.BridgeName) } // Set the bridgeInterface netlink.Bridge. i.Link = &netlink.Bridge{ LinkAttrs: netlink.LinkAttrs{ Name: config.BridgeName, }, } // Only set the bridge's MAC address if the kernel version is > 3.3, as it // was not supported before that. kv, err := kernel.GetKernelVersion() if err == nil && (kv.Kernel >= 3 && kv.Major >= 3) { setMac = true } return ioctlCreateBridge(config.BridgeName, setMac) } // SetupDeviceUp ups the given bridge interface. func setupDeviceUp(config *networkConfiguration, i *bridgeInterface) error { err := netlink.LinkSetUp(i.Link) if err != nil { return err } // Attempt to update the bridge interface to refresh the flags status, // ignoring any failure to do so. if lnk, err := netlink.LinkByName(config.BridgeName); err == nil { i.Link = lnk } return nil }
apache-2.0
ubgarbage/gae-blog
django/contrib/gis/db/backends/spatialite/base.py
4480
from ctypes.util import find_library from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.base import ( _sqlite_extract, _sqlite_date_trunc, _sqlite_regexp, _sqlite_format_dtdelta, connection_created, Database, DatabaseWrapper as SQLiteDatabaseWrapper, SQLiteCursorWrapper) from django.contrib.gis.db.backends.spatialite.client import SpatiaLiteClient from django.contrib.gis.db.backends.spatialite.creation import SpatiaLiteCreation from django.contrib.gis.db.backends.spatialite.introspection import SpatiaLiteIntrospection from django.contrib.gis.db.backends.spatialite.operations import SpatiaLiteOperations class DatabaseWrapper(SQLiteDatabaseWrapper): def __init__(self, *args, **kwargs): # Before we get too far, make sure pysqlite 2.5+ is installed. if Database.version_info < (2, 5, 0): raise ImproperlyConfigured('Only versions of pysqlite 2.5+ are ' 'compatible with SpatiaLite and GeoDjango.') # Trying to find the location of the SpatiaLite library. # Here we are figuring out the path to the SpatiaLite library # (`libspatialite`). If it's not in the system library path (e.g., it # cannot be found by `ctypes.util.find_library`), then it may be set # manually in the settings via the `SPATIALITE_LIBRARY_PATH` setting. self.spatialite_lib = getattr(settings, 'SPATIALITE_LIBRARY_PATH', find_library('spatialite')) if not self.spatialite_lib: raise ImproperlyConfigured('Unable to locate the SpatiaLite library. ' 'Make sure it is in your library path, or set ' 'SPATIALITE_LIBRARY_PATH in your settings.' ) super(DatabaseWrapper, self).__init__(*args, **kwargs) self.ops = SpatiaLiteOperations(self) self.client = SpatiaLiteClient(self) self.creation = SpatiaLiteCreation(self) self.introspection = SpatiaLiteIntrospection(self) def _cursor(self): if self.connection is None: ## The following is the same as in django.db.backends.sqlite3.base ## settings_dict = self.settings_dict if not settings_dict['NAME']: raise ImproperlyConfigured("Please fill out the database NAME in the settings module before using the database.") kwargs = { 'database': settings_dict['NAME'], 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, } kwargs.update(settings_dict['OPTIONS']) self.connection = Database.connect(**kwargs) # Register extract, date_trunc, and regexp functions. self.connection.create_function("django_extract", 2, _sqlite_extract) self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc) self.connection.create_function("regexp", 2, _sqlite_regexp) self.connection.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta) connection_created.send(sender=self.__class__, connection=self) ## From here on, customized for GeoDjango ## # Enabling extension loading on the SQLite connection. try: self.connection.enable_load_extension(True) except AttributeError: raise ImproperlyConfigured('The pysqlite library does not support C extension loading. ' 'Both SQLite and pysqlite must be configured to allow ' 'the loading of extensions to use SpatiaLite.' ) # Loading the SpatiaLite library extension on the connection, and returning # the created cursor. cur = self.connection.cursor(factory=SQLiteCursorWrapper) try: cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,)) except Exception, msg: raise ImproperlyConfigured('Unable to load the SpatiaLite library extension ' '"%s" because: %s' % (self.spatialite_lib, msg)) return cur else: return self.connection.cursor(factory=SQLiteCursorWrapper)
bsd-3-clause
ahocevar/cdnjs
ajax/libs/select2/4.0.4/js/i18n/el.js
1132
/*! Select2 4.0.4 | https://github.com/select2/select2/blob/master/LICENSE.md */ (function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/el",[],function(){return{errorLoading:function(){return"Τα αποτελέσματα δεν μπόρεσαν να φορτώσουν."},inputTooLong:function(e){var t=e.input.length-e.maximum,n="Παρακαλώ διαγράψτε "+t+" χαρακτήρ";return t==1&&(n+="α"),t!=1&&(n+="ες"),n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="Παρακαλώ συμπληρώστε "+t+" ή περισσότερους χαρακτήρες";return n},loadingMore:function(){return"Φόρτωση περισσότερων αποτελεσμάτων…"},maximumSelected:function(e){var t="Μπορείτε να επιλέξετε μόνο "+e.maximum+" επιλογ";return e.maximum==1&&(t+="ή"),e.maximum!=1&&(t+="ές"),t},noResults:function(){return"Δεν βρέθηκαν αποτελέσματα"},searching:function(){return"Αναζήτηση…"}}}),{define:e.define,require:e.require}})();
mit
askannon/camel
components/camel-netty4-http/src/test/java/org/apache/camel/component/netty4/http/NettyRecipientListHttpBaseTest.java
2305
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.netty4.http; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.junit.Test; public class NettyRecipientListHttpBaseTest extends BaseNettyTest { @Test public void testRecipientListHttpBase() throws Exception { getMockEndpoint("mock:foo").expectedHeaderValuesReceivedInAnyOrder(Exchange.HTTP_PATH, "/bar", "/baz", "/bar/baz", "/baz/bar"); getMockEndpoint("mock:foo").expectedHeaderValuesReceivedInAnyOrder("num", "1", "2", "3", "4"); template.sendBodyAndHeader("direct:start", "A", Exchange.HTTP_PATH, "/foo/bar?num=1"); template.sendBodyAndHeader("direct:start", "B", Exchange.HTTP_PATH, "/foo/baz?num=2"); template.sendBodyAndHeader("direct:start", "C", Exchange.HTTP_PATH, "/foo/bar/baz?num=3"); template.sendBodyAndHeader("direct:start", "D", Exchange.HTTP_PATH, "/foo/baz/bar?num=4"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("netty4-http:http://0.0.0.0:{{port}}/foo?matchOnUriPrefix=true") .to("mock:foo") .transform(body().prepend("Bye ")); from("direct:start") .recipientList().constant("netty4-http:http://0.0.0.0:{{port}}"); } }; } }
apache-2.0
CLAMP-IT/moodle
question/type/gapselect/lang/en/qtype_gapselect.php
3337
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Language strings for the gap-select question type. * * @package qtype_gapselect * @copyright 2011 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['addmorechoiceblanks'] = 'Blanks for {no} more choices'; $string['answer'] = 'Answer'; $string['choices'] = 'Choices'; $string['choicex'] = 'Choice [[{no}]]'; $string['combinedcontrolnamegapselect'] = 'drop-down menu'; $string['combinedcontrolnamegapselectplural'] = 'drop-down menus'; $string['correctansweris'] = 'The correct answer is: {$a}'; $string['errorblankchoice'] = 'Please check the choices: Choice {$a} is empty.'; $string['errormissingchoice'] = 'Please check the question text: {$a} was not found in the choices! Only numbers with choice answers specified are allowed to be used as placeholders.'; $string['errornoslots'] = 'The question text must contain placeholders like [[1]] to show where the missing words go.'; $string['errorquestiontextblank'] = 'You must enter some question text.'; $string['group'] = 'Group'; $string['pleaseputananswerineachbox'] = 'Please put an answer in each box.'; $string['pluginname'] = 'Select missing words'; $string['pluginname_help'] = 'Select missing words questions require the respondent to select correct answers from drop-down menus. [[1]], [[2]], [[3]], ... are used as placeholders in the question text, with the correct answers specified as choice answers 1, 2, 3, ... respectively. Extra choice answers may be added to make the question harder. Choice answers may be grouped to restrict answers available in each drop-down menu.'; $string['pluginname_link'] = 'question/type/gapselect'; $string['pluginnameadding'] = 'Adding a select missing words question'; $string['pluginnameediting'] = 'Editing a select missing words question'; $string['pluginnamesummary'] = 'Missing words in the question text are filled in using drop-down menus.'; $string['privacy:metadata'] = 'Select missing words question type plugin allows question authors to set default options as user preferences.'; $string['privacy:preference:defaultmark'] = 'The default mark set for a given question.'; $string['privacy:preference:penalty'] = 'The penalty for each incorrect try when questions are run using the \'Interactive with multiple tries\' or \'Adaptive mode\' behaviour.'; $string['privacy:preference:shuffleanswers'] = 'Whether the answers should be automatically shuffled.'; $string['shuffle'] = 'Shuffle'; $string['tagsnotallowed'] = '{$a->tag} is not allowed. (Only {$a->allowed} are permitted.)'; $string['tagsnotallowedatall'] = '{$a->tag} is not allowed. (No HTML is allowed here.)';
gpl-3.0
tskurauskas/Arduino
arduino-core/src/cc/arduino/contributions/ConsoleProgressListener.java
1750
/* * This file is part of Arduino. * * Copyright 2015 Arduino LLC (http://www.arduino.cc/) * * Arduino is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. */ package cc.arduino.contributions; import cc.arduino.utils.Progress; public class ConsoleProgressListener implements ProgressListener { private String lastStatus = ""; @Override public void onProgress(Progress progress) { if (!lastStatus.equals(progress.getStatus())) { System.out.println(progress.getStatus()); } lastStatus = progress.getStatus(); } }
lgpl-2.1
Hootis/plymouth-webapp
external/adodb5/drivers/adodb-vfp.inc.php
2479
<?php /* V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved. Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Set tabs to 4 for best viewing. Latest version is available at http://adodb.sourceforge.net Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows. */ // security - hide paths if (!defined('ADODB_DIR')) die(); if (!defined('_ADODB_ODBC_LAYER')) { include(ADODB_DIR."/drivers/adodb-odbc.inc.php"); } if (!defined('ADODB_VFP')){ define('ADODB_VFP',1); class ADODB_vfp extends ADODB_odbc { var $databaseType = "vfp"; var $fmtDate = "{^Y-m-d}"; var $fmtTimeStamp = "{^Y-m-d, h:i:sA}"; var $replaceQuote = "'+chr(39)+'" ; var $true = '.T.'; var $false = '.F.'; var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE var $_bindInputArray = false; // strangely enough, setting to true does not work reliably var $sysTimeStamp = 'datetime()'; var $sysDate = 'date()'; var $ansiOuter = true; var $hasTransactions = false; var $curmode = false ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L function ADODB_vfp() { $this->ADODB_odbc(); } function Time() { return time(); } function BeginTrans() { return false;} // quote string to be sent back to database function qstr($s,$nofixquotes=false) { if (!$nofixquotes) return "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'"; return "'".$s."'"; } // TOP requires ORDER BY for VFP function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) { $this->hasTop = preg_match('/ORDER[ \t\r\n]+BY/is',$sql) ? 'top' : false; $ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); return $ret; } }; class ADORecordSet_vfp extends ADORecordSet_odbc { var $databaseType = "vfp"; function ADORecordSet_vfp($id,$mode=false) { return $this->ADORecordSet_odbc($id,$mode); } function MetaType($t,$len=-1) { if (is_object($t)) { $fieldobj = $t; $t = $fieldobj->type; $len = $fieldobj->max_length; } switch (strtoupper($t)) { case 'C': if ($len <= $this->blobSize) return 'C'; case 'M': return 'X'; case 'D': return 'D'; case 'T': return 'T'; case 'L': return 'L'; case 'I': return 'I'; default: return 'N'; } } } } //define ?>
mit
vladbar/SuiteCRM
modules/Project/views/view.templatesdetail.php
3514
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd. * Copyright (C) 2011 - 2014 Salesagility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". ********************************************************************************/ require_once('include/MVC/View/views/view.detail.php'); class ProjectViewTemplatesDetail extends ViewDetail { /** * @see SugarView::_getModuleTitleParams() */ protected function _getModuleTitleParams($browserTitle = false) { global $mod_strings; return array( $this->_getModuleTitleListParam($browserTitle), "<a href='index.php?module=Project&action=EditView&record={$this->bean->id}'>{$this->bean->name}</a>", $mod_strings['LBL_PROJECT_TEMPLATE'] ); } function display() { global $beanFiles; require_once($beanFiles['Project']); $focus = new Project(); $focus->retrieve($_REQUEST['record']); global $app_list_strings, $current_user, $mod_strings; $this->ss->assign('APP_LIST_STRINGS', $app_list_strings); if($current_user->id == $focus->assigned_user_id || $current_user->is_admin){ $this->ss->assign('OWNER_ONLY', true); } else{ $this->ss->assign('OWNER_ONLY', false); } parent::display(); } /** * @see SugarView::_displaySubPanels() */ protected function _displaySubPanels() { require_once ('include/SubPanel/SubPanelTiles.php'); $subpanel = new SubPanelTiles( $this->bean, 'ProjectTemplates' ); echo $subpanel->display( true, true ); } }
agpl-3.0
dominiqa/azure-sdk-for-net
src/ResourceManagement/ApiManagement/ApiManagement.Tests/ScenarioTests/SmapiTests/SmapiFunctionalTests.ProductApis.cs
4440
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Azure.Management.ApiManagement.Tests.ScenarioTests.SmapiTests { using System.Linq; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Microsoft.Azure.Test; using Xunit; public partial class SmapiFunctionalTests { [Fact] public void ProductApisListAddRemove() { TestUtilities.StartTest("SmapiFunctionalTests", "ProductApisListAddRemove"); try { // there should be 'Echo API' which is created by default for every new instance of API Management and // 'Starter' product var getProductsResponse = ApiManagementClient.Products.List( ResourceGroupName, ApiManagementServiceName, new QueryParameters { Filter = "name eq 'Starter'" }); Assert.NotNull(getProductsResponse); Assert.NotNull(getProductsResponse.Result); Assert.Equal(1, getProductsResponse.Result.Values.Count); var product = getProductsResponse.Result.Values.Single(); // list product apis: there sould be 1 var listApisResponse = ApiManagementClient.ProductApis.List( ResourceGroupName, ApiManagementServiceName, product.Id, null); Assert.NotNull(listApisResponse); Assert.NotNull(listApisResponse.Result); Assert.Equal(1, listApisResponse.Result.TotalCount); Assert.Equal(1, listApisResponse.Result.Values.Count); // get api var getResponse = ApiManagementClient.Apis.Get( ResourceGroupName, ApiManagementServiceName, listApisResponse.Result.Values.Single().Id); Assert.NotNull(getResponse); // remove api from product var removeResponse = ApiManagementClient.ProductApis.Remove( ResourceGroupName, ApiManagementServiceName, product.Id, listApisResponse.Result.Values.Single().Id); Assert.NotNull(removeResponse); // list to check it was removed listApisResponse = ApiManagementClient.ProductApis.List( ResourceGroupName, ApiManagementServiceName, product.Id, null); Assert.NotNull(listApisResponse); Assert.NotNull(listApisResponse.Result); Assert.Equal(0, listApisResponse.Result.TotalCount); Assert.Equal(0, listApisResponse.Result.Values.Count); // add the api to product var addResponse = ApiManagementClient.ProductApis.Add( ResourceGroupName, ApiManagementServiceName, product.Id, getResponse.Value.Id); Assert.NotNull(addResponse); // list to check it was added listApisResponse = ApiManagementClient.ProductApis.List( ResourceGroupName, ApiManagementServiceName, product.Id, null); Assert.NotNull(listApisResponse); Assert.NotNull(listApisResponse.Result); Assert.Equal(1, listApisResponse.Result.TotalCount); Assert.Equal(1, listApisResponse.Result.Values.Count); } finally { TestUtilities.EndTest(); } } } }
apache-2.0
Sumith1896/sympy
sympy/physics/mechanics/tests/test_kane2.py
18815
from sympy.core.compatibility import range from sympy import cos, Matrix, simplify, sin, solve, tan, pi from sympy import symbols, trigsimp, zeros from sympy.physics.mechanics import (cross, dot, dynamicsymbols, KanesMethod, inertia, inertia_of_point_mass, Point, ReferenceFrame, RigidBody) def test_aux_dep(): # This test is about rolling disc dynamics, comparing the results found # with KanesMethod to those found when deriving the equations "manually" # with SymPy. # The terms Fr, Fr*, and Fr*_steady are all compared between the two # methods. Here, Fr*_steady refers to the generalized inertia forces for an # equilibrium configuration. # Note: comparing to the test of test_rolling_disc() in test_kane.py, this # test also tests auxiliary speeds and configuration and motion constraints #, seen in the generalized dependent coordinates q[3], and depend speeds # u[3], u[4] and u[5]. # First, mannual derivation of Fr, Fr_star, Fr_star_steady. # Symbols for time and constant parameters. # Symbols for contact forces: Fx, Fy, Fz. t, r, m, g, I, J = symbols('t r m g I J') Fx, Fy, Fz = symbols('Fx Fy Fz') # Configuration variables and their time derivatives: # q[0] -- yaw # q[1] -- lean # q[2] -- spin # q[3] -- dot(-r*B.z, A.z) -- distance from ground plane to disc center in # A.z direction # Generalized speeds and their time derivatives: # u[0] -- disc angular velocity component, disc fixed x direction # u[1] -- disc angular velocity component, disc fixed y direction # u[2] -- disc angular velocity component, disc fixed z direction # u[3] -- disc velocity component, A.x direction # u[4] -- disc velocity component, A.y direction # u[5] -- disc velocity component, A.z direction # Auxiliary generalized speeds: # ua[0] -- contact point auxiliary generalized speed, A.x direction # ua[1] -- contact point auxiliary generalized speed, A.y direction # ua[2] -- contact point auxiliary generalized speed, A.z direction q = dynamicsymbols('q:4') qd = [qi.diff(t) for qi in q] u = dynamicsymbols('u:6') ud = [ui.diff(t) for ui in u] ud_zero = dict(zip(ud, [0.]*len(ud))) ua = dynamicsymbols('ua:3') ua_zero = dict(zip(ua, [0.]*len(ua))) # Reference frames: # Yaw intermediate frame: A. # Lean intermediate frame: B. # Disc fixed frame: C. N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [q[0], N.z]) B = A.orientnew('B', 'Axis', [q[1], A.x]) C = B.orientnew('C', 'Axis', [q[2], B.y]) # Angular velocity and angular acceleration of disc fixed frame # u[0], u[1] and u[2] are generalized independent speeds. C.set_ang_vel(N, u[0]*B.x + u[1]*B.y + u[2]*B.z) C.set_ang_acc(N, C.ang_vel_in(N).diff(t, B) + cross(B.ang_vel_in(N), C.ang_vel_in(N))) # Velocity and acceleration of points: # Disc-ground contact point: P. # Center of disc: O, defined from point P with depend coordinate: q[3] # u[3], u[4] and u[5] are generalized dependent speeds. P = Point('P') P.set_vel(N, ua[0]*A.x + ua[1]*A.y + ua[2]*A.z) O = P.locatenew('O', q[3]*A.z + r*sin(q[1])*A.y) O.set_vel(N, u[3]*A.x + u[4]*A.y + u[5]*A.z) O.set_acc(N, O.vel(N).diff(t, A) + cross(A.ang_vel_in(N), O.vel(N))) # Kinematic differential equations: # Two equalities: one is w_c_n_qd = C.ang_vel_in(N) in three coordinates # directions of B, for qd0, qd1 and qd2. # the other is v_o_n_qd = O.vel(N) in A.z direction for qd3. # Then, solve for dq/dt's in terms of u's: qd_kd. w_c_n_qd = qd[0]*A.z + qd[1]*B.x + qd[2]*B.y v_o_n_qd = O.pos_from(P).diff(t, A) + cross(A.ang_vel_in(N), O.pos_from(P)) kindiffs = Matrix([dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B] + [dot(v_o_n_qd - O.vel(N), A.z)]) qd_kd = solve(kindiffs, qd) # Values of generalized speeds during a steady turn for later substitution # into the Fr_star_steady. steady_conditions = solve(kindiffs.subs({qd[1] : 0, qd[3] : 0}), u) steady_conditions.update({qd[1] : 0, qd[3] : 0}) # Partial angular velocities and velocities. partial_w_C = [C.ang_vel_in(N).diff(ui, N) for ui in u + ua] partial_v_O = [O.vel(N).diff(ui, N) for ui in u + ua] partial_v_P = [P.vel(N).diff(ui, N) for ui in u + ua] # Configuration constraint: f_c, the projection of radius r in A.z direction # is q[3]. # Velocity constraints: f_v, for u3, u4 and u5. # Acceleration constraints: f_a. f_c = Matrix([dot(-r*B.z, A.z) - q[3]]) f_v = Matrix([dot(O.vel(N) - (P.vel(N) + cross(C.ang_vel_in(N), O.pos_from(P))), ai).expand() for ai in A]) v_o_n = cross(C.ang_vel_in(N), O.pos_from(P)) a_o_n = v_o_n.diff(t, A) + cross(A.ang_vel_in(N), v_o_n) f_a = Matrix([dot(O.acc(N) - a_o_n, ai) for ai in A]) # Solve for constraint equations in the form of # u_dependent = A_rs * [u_i; u_aux]. # First, obtain constraint coefficient matrix: M_v * [u; ua] = 0; # Second, taking u[0], u[1], u[2] as independent, # taking u[3], u[4], u[5] as dependent, # rearranging the matrix of M_v to be A_rs for u_dependent. # Third, u_aux ==0 for u_dep, and resulting dictionary of u_dep_dict. M_v = zeros(3, 9) for i in range(3): for j, ui in enumerate(u + ua): M_v[i, j] = f_v[i].diff(ui) M_v_i = M_v[:, :3] M_v_d = M_v[:, 3:6] M_v_aux = M_v[:, 6:] M_v_i_aux = M_v_i.row_join(M_v_aux) A_rs = - M_v_d.inv() * M_v_i_aux u_dep = A_rs[:, :3] * Matrix(u[:3]) u_dep_dict = dict(zip(u[3:], u_dep)) # Active forces: F_O acting on point O; F_P acting on point P. # Generalized active forces (unconstrained): Fr_u = F_point * pv_point. F_O = m*g*A.z F_P = Fx * A.x + Fy * A.y + Fz * A.z Fr_u = Matrix([dot(F_O, pv_o) + dot(F_P, pv_p) for pv_o, pv_p in zip(partial_v_O, partial_v_P)]) # Inertia force: R_star_O. # Inertia of disc: I_C_O, where J is a inertia component about principal axis. # Inertia torque: T_star_C. # Generalized inertia forces (unconstrained): Fr_star_u. R_star_O = -m*O.acc(N) I_C_O = inertia(B, I, J, I) T_star_C = -(dot(I_C_O, C.ang_acc_in(N)) \ + cross(C.ang_vel_in(N), dot(I_C_O, C.ang_vel_in(N)))) Fr_star_u = Matrix([dot(R_star_O, pv) + dot(T_star_C, pav) for pv, pav in zip(partial_v_O, partial_w_C)]) # Form nonholonomic Fr: Fr_c, and nonholonomic Fr_star: Fr_star_c. # Also, nonholonomic Fr_star in steady turning condition: Fr_star_steady. Fr_c = Fr_u[:3, :].col_join(Fr_u[6:, :]) + A_rs.T * Fr_u[3:6, :] Fr_star_c = Fr_star_u[:3, :].col_join(Fr_star_u[6:, :])\ + A_rs.T * Fr_star_u[3:6, :] Fr_star_steady = Fr_star_c.subs(ud_zero).subs(u_dep_dict)\ .subs(steady_conditions).subs({q[3]: -r*cos(q[1])}).expand() # Second, using KaneMethod in mechanics for fr, frstar and frstar_steady. # Rigid Bodies: disc, with inertia I_C_O. iner_tuple = (I_C_O, O) disc = RigidBody('disc', O, C, m, iner_tuple) bodyList = [disc] # Generalized forces: Gravity: F_o; Auxiliary forces: F_p. F_o = (O, F_O) F_p = (P, F_P) forceList = [F_o, F_p] # KanesMethod. kane = KanesMethod( N, q_ind= q[:3], u_ind= u[:3], kd_eqs=kindiffs, q_dependent=q[3:], configuration_constraints = f_c, u_dependent=u[3:], velocity_constraints= f_v, u_auxiliary=ua ) # fr, frstar, frstar_steady and kdd(kinematic differential equations). (fr, frstar)= kane.kanes_equations(forceList, bodyList) frstar_steady = frstar.subs(ud_zero).subs(u_dep_dict).subs(steady_conditions)\ .subs({q[3]: -r*cos(q[1])}).expand() kdd = kane.kindiffdict() assert Matrix(Fr_c).expand() == fr.expand() assert Matrix(Fr_star_c.subs(kdd)).expand() == frstar.expand() assert (simplify(Matrix(Fr_star_steady).expand()) == simplify(frstar_steady.expand())) def test_non_central_inertia(): # This tests that the calculation of Fr* does not depend the point # about which the inertia of a rigid body is defined. This test solves # exercises 8.12, 8.17 from Kane 1985. # Declare symbols q1, q2, q3 = dynamicsymbols('q1:4') q1d, q2d, q3d = dynamicsymbols('q1:4', level=1) u1, u2, u3, u4, u5 = dynamicsymbols('u1:6') u_prime, R, M, g, e, f, theta = symbols('u\' R, M, g, e, f, theta') a, b, mA, mB, IA, J, K, t = symbols('a b mA mB IA J K t') Q1, Q2, Q3 = symbols('Q1, Q2 Q3') IA22, IA23, IA33 = symbols('IA22 IA23 IA33') # Reference Frames F = ReferenceFrame('F') P = F.orientnew('P', 'axis', [-theta, F.y]) A = P.orientnew('A', 'axis', [q1, P.x]) A.set_ang_vel(F, u1*A.x + u3*A.z) # define frames for wheels B = A.orientnew('B', 'axis', [q2, A.z]) C = A.orientnew('C', 'axis', [q3, A.z]) B.set_ang_vel(A, u4 * A.z) C.set_ang_vel(A, u5 * A.z) # define points D, S*, Q on frame A and their velocities pD = Point('D') pD.set_vel(A, 0) # u3 will not change v_D_F since wheels are still assumed to roll without slip. pD.set_vel(F, u2 * A.y) pS_star = pD.locatenew('S*', e*A.y) pQ = pD.locatenew('Q', f*A.y - R*A.x) for p in [pS_star, pQ]: p.v2pt_theory(pD, F, A) # masscenters of bodies A, B, C pA_star = pD.locatenew('A*', a*A.y) pB_star = pD.locatenew('B*', b*A.z) pC_star = pD.locatenew('C*', -b*A.z) for p in [pA_star, pB_star, pC_star]: p.v2pt_theory(pD, F, A) # points of B, C touching the plane P pB_hat = pB_star.locatenew('B^', -R*A.x) pC_hat = pC_star.locatenew('C^', -R*A.x) pB_hat.v2pt_theory(pB_star, F, B) pC_hat.v2pt_theory(pC_star, F, C) # the velocities of B^, C^ are zero since B, C are assumed to roll without slip kde = [q1d - u1, q2d - u4, q3d - u5] vc = [dot(p.vel(F), A.y) for p in [pB_hat, pC_hat]] # inertias of bodies A, B, C # IA22, IA23, IA33 are not specified in the problem statement, but are # necessary to define an inertia object. Although the values of # IA22, IA23, IA33 are not known in terms of the variables given in the # problem statement, they do not appear in the general inertia terms. inertia_A = inertia(A, IA, IA22, IA33, 0, IA23, 0) inertia_B = inertia(B, K, K, J) inertia_C = inertia(C, K, K, J) # define the rigid bodies A, B, C rbA = RigidBody('rbA', pA_star, A, mA, (inertia_A, pA_star)) rbB = RigidBody('rbB', pB_star, B, mB, (inertia_B, pB_star)) rbC = RigidBody('rbC', pC_star, C, mB, (inertia_C, pC_star)) km = KanesMethod(F, q_ind=[q1, q2, q3], u_ind=[u1, u2], kd_eqs=kde, u_dependent=[u4, u5], velocity_constraints=vc, u_auxiliary=[u3]) forces = [(pS_star, -M*g*F.x), (pQ, Q1*A.x + Q2*A.y + Q3*A.z)] bodies = [rbA, rbB, rbC] fr, fr_star = km.kanes_equations(forces, bodies) vc_map = solve(vc, [u4, u5]) # KanesMethod returns the negative of Fr, Fr* as defined in Kane1985. fr_star_expected = Matrix([ -(IA + 2*J*b**2/R**2 + 2*K + mA*a**2 + 2*mB*b**2) * u1.diff(t) - mA*a*u1*u2, -(mA + 2*mB +2*J/R**2) * u2.diff(t) + mA*a*u1**2, 0]) assert (trigsimp(fr_star.subs(vc_map).subs(u3, 0)).doit().expand() == fr_star_expected.expand()) # define inertias of rigid bodies A, B, C about point D # I_S/O = I_S/S* + I_S*/O bodies2 = [] for rb, I_star in zip([rbA, rbB, rbC], [inertia_A, inertia_B, inertia_C]): I = I_star + inertia_of_point_mass(rb.mass, rb.masscenter.pos_from(pD), rb.frame) bodies2.append(RigidBody('', rb.masscenter, rb.frame, rb.mass, (I, pD))) fr2, fr_star2 = km.kanes_equations(forces, bodies2) assert (trigsimp(fr_star2.subs(vc_map).subs(u3, 0)).doit().expand() == fr_star_expected.expand()) def test_sub_qdot(): # This test solves exercises 8.12, 8.17 from Kane 1985 and defines # some velocities in terms of q, qdot. ## --- Declare symbols --- q1, q2, q3 = dynamicsymbols('q1:4') q1d, q2d, q3d = dynamicsymbols('q1:4', level=1) u1, u2, u3 = dynamicsymbols('u1:4') u_prime, R, M, g, e, f, theta = symbols('u\' R, M, g, e, f, theta') a, b, mA, mB, IA, J, K, t = symbols('a b mA mB IA J K t') IA22, IA23, IA33 = symbols('IA22 IA23 IA33') Q1, Q2, Q3 = symbols('Q1 Q2 Q3') # --- Reference Frames --- F = ReferenceFrame('F') P = F.orientnew('P', 'axis', [-theta, F.y]) A = P.orientnew('A', 'axis', [q1, P.x]) A.set_ang_vel(F, u1*A.x + u3*A.z) # define frames for wheels B = A.orientnew('B', 'axis', [q2, A.z]) C = A.orientnew('C', 'axis', [q3, A.z]) ## --- define points D, S*, Q on frame A and their velocities --- pD = Point('D') pD.set_vel(A, 0) # u3 will not change v_D_F since wheels are still assumed to roll w/o slip pD.set_vel(F, u2 * A.y) pS_star = pD.locatenew('S*', e*A.y) pQ = pD.locatenew('Q', f*A.y - R*A.x) # masscenters of bodies A, B, C pA_star = pD.locatenew('A*', a*A.y) pB_star = pD.locatenew('B*', b*A.z) pC_star = pD.locatenew('C*', -b*A.z) for p in [pS_star, pQ, pA_star, pB_star, pC_star]: p.v2pt_theory(pD, F, A) # points of B, C touching the plane P pB_hat = pB_star.locatenew('B^', -R*A.x) pC_hat = pC_star.locatenew('C^', -R*A.x) pB_hat.v2pt_theory(pB_star, F, B) pC_hat.v2pt_theory(pC_star, F, C) # --- relate qdot, u --- # the velocities of B^, C^ are zero since B, C are assumed to roll w/o slip kde = [dot(p.vel(F), A.y) for p in [pB_hat, pC_hat]] kde += [u1 - q1d] kde_map = solve(kde, [q1d, q2d, q3d]) for k, v in list(kde_map.items()): kde_map[k.diff(t)] = v.diff(t) # inertias of bodies A, B, C # IA22, IA23, IA33 are not specified in the problem statement, but are # necessary to define an inertia object. Although the values of # IA22, IA23, IA33 are not known in terms of the variables given in the # problem statement, they do not appear in the general inertia terms. inertia_A = inertia(A, IA, IA22, IA33, 0, IA23, 0) inertia_B = inertia(B, K, K, J) inertia_C = inertia(C, K, K, J) # define the rigid bodies A, B, C rbA = RigidBody('rbA', pA_star, A, mA, (inertia_A, pA_star)) rbB = RigidBody('rbB', pB_star, B, mB, (inertia_B, pB_star)) rbC = RigidBody('rbC', pC_star, C, mB, (inertia_C, pC_star)) ## --- use kanes method --- km = KanesMethod(F, [q1, q2, q3], [u1, u2], kd_eqs=kde, u_auxiliary=[u3]) forces = [(pS_star, -M*g*F.x), (pQ, Q1*A.x + Q2*A.y + Q3*A.z)] bodies = [rbA, rbB, rbC] # Q2 = -u_prime * u2 * Q1 / sqrt(u2**2 + f**2 * u1**2) # -u_prime * R * u2 / sqrt(u2**2 + f**2 * u1**2) = R / Q1 * Q2 fr_expected = Matrix([ f*Q3 + M*g*e*sin(theta)*cos(q1), Q2 + M*g*sin(theta)*sin(q1), e*M*g*cos(theta) - Q1*f - Q2*R]) #Q1 * (f - u_prime * R * u2 / sqrt(u2**2 + f**2 * u1**2)))]) fr_star_expected = Matrix([ -(IA + 2*J*b**2/R**2 + 2*K + mA*a**2 + 2*mB*b**2) * u1.diff(t) - mA*a*u1*u2, -(mA + 2*mB +2*J/R**2) * u2.diff(t) + mA*a*u1**2, 0]) fr, fr_star = km.kanes_equations(forces, bodies) assert (fr.expand() == fr_expected.expand()) assert (trigsimp(fr_star).expand() == fr_star_expected.expand()) def test_sub_qdot2(): # This test solves exercises 8.3 from Kane 1985 and defines # all velocities in terms of q, qdot. We check that the generalized active # forces are correctly computed if u terms are only defined in the # kinematic differential equations. # # This functionality was added in PR 8948. Without qdot/u substitution, the # KanesMethod constructor will fail during the constraint initialization as # the B matrix will be poorly formed and inversion of the dependent part # will fail. g, m, Px, Py, Pz, R, t = symbols('g m Px Py Pz R t') q = dynamicsymbols('q:5') qd = dynamicsymbols('q:5', level=1) u = dynamicsymbols('u:5') ## Define inertial, intermediate, and rigid body reference frames A = ReferenceFrame('A') B_prime = A.orientnew('B_prime', 'Axis', [q[0], A.z]) B = B_prime.orientnew('B', 'Axis', [pi/2 - q[1], B_prime.x]) C = B.orientnew('C', 'Axis', [q[2], B.z]) ## Define points of interest and their velocities pO = Point('O') pO.set_vel(A, 0) # R is the point in plane H that comes into contact with disk C. pR = pO.locatenew('R', q[3]*A.x + q[4]*A.y) pR.set_vel(A, pR.pos_from(pO).diff(t, A)) pR.set_vel(B, 0) # C^ is the point in disk C that comes into contact with plane H. pC_hat = pR.locatenew('C^', 0) pC_hat.set_vel(C, 0) # C* is the point at the center of disk C. pCs = pC_hat.locatenew('C*', R*B.y) pCs.set_vel(C, 0) pCs.set_vel(B, 0) # calculate velocites of points C* and C^ in frame A pCs.v2pt_theory(pR, A, B) # points C* and R are fixed in frame B pC_hat.v2pt_theory(pCs, A, C) # points C* and C^ are fixed in frame C ## Define forces on each point of the system R_C_hat = Px*A.x + Py*A.y + Pz*A.z R_Cs = -m*g*A.z forces = [(pC_hat, R_C_hat), (pCs, R_Cs)] ## Define kinematic differential equations # let ui = omega_C_A & bi (i = 1, 2, 3) # u4 = qd4, u5 = qd5 u_expr = [C.ang_vel_in(A) & uv for uv in B] u_expr += qd[3:] kde = [ui - e for ui, e in zip(u, u_expr)] km1 = KanesMethod(A, q, u, kde) fr1, _ = km1.kanes_equations(forces, []) ## Calculate generalized active forces if we impose the condition that the # disk C is rolling without slipping u_indep = u[:3] u_dep = list(set(u) - set(u_indep)) vc = [pC_hat.vel(A) & uv for uv in [A.x, A.y]] km2 = KanesMethod(A, q, u_indep, kde, u_dependent=u_dep, velocity_constraints=vc) fr2, _ = km2.kanes_equations(forces, []) fr1_expected = Matrix([ -R*g*m*sin(q[1]), -R*(Px*cos(q[0]) + Py*sin(q[0]))*tan(q[1]), R*(Px*cos(q[0]) + Py*sin(q[0])), Px, Py]) fr2_expected = Matrix([ -R*g*m*sin(q[1]), 0, 0]) assert (trigsimp(fr1.expand()) == trigsimp(fr1_expected.expand())) assert (trigsimp(fr2.expand()) == trigsimp(fr2_expected.expand()))
bsd-3-clause
nicolasconnault/mmrcwa-grav
user/plugins/admin/vendor/bacon/bacon-qr-code/src/BaconQrCode/Exception/ExceptionInterface.php
308
<?php /** * BaconQrCode * * @link http://github.com/Bacon/BaconQrCode For the canonical source repository * @copyright 2013 Ben 'DASPRiD' Scholzen * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace BaconQrCode\Exception; interface ExceptionInterface { }
mit
CodeZombieCH/DefinitelyTyped
loglevel/loglevel-tests.ts
587
/// <reference path="loglevel.d.ts" /> log.trace("Trace message"); log.debug("Debug message"); log.info("Info message"); log.warn("Warn message"); log.error("Error message"); log.debug(["Hello", "world", 42]); log.setLevel(0); log.setLevel(0, false); log.setLevel("error"); log.setLevel("error", false); log.setLevel(LogLevel.WARN); log.setLevel(LogLevel.WARN, false); var logLevel = log.getLevel(); var testLogger = log.getLogger("TestLogger"); testLogger.setLevel(logLevel); testLogger.warn("logging test"); var logging = log.noConflict(); logging.error("still pretty easy");
mit
jprante/elasticsearch
core/src/main/java/org/elasticsearch/action/bulk/BulkShardRequest.java
3964
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.bulk; import org.elasticsearch.action.support.replication.ReplicatedWriteRequest; import org.elasticsearch.action.support.replication.ReplicationRequest; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.index.shard.ShardId; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class BulkShardRequest extends ReplicatedWriteRequest<BulkShardRequest> { private BulkItemRequest[] items; public BulkShardRequest() { } public BulkShardRequest(ShardId shardId, RefreshPolicy refreshPolicy, BulkItemRequest[] items) { super(shardId); this.items = items; setRefreshPolicy(refreshPolicy); } public BulkItemRequest[] items() { return items; } @Override public String[] indices() { List<String> indices = new ArrayList<>(); for (BulkItemRequest item : items) { if (item != null) { indices.add(item.index()); } } return indices.toArray(new String[indices.size()]); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(items.length); for (BulkItemRequest item : items) { if (item != null) { out.writeBoolean(true); item.writeTo(out); } else { out.writeBoolean(false); } } } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); items = new BulkItemRequest[in.readVInt()]; for (int i = 0; i < items.length; i++) { if (in.readBoolean()) { items[i] = BulkItemRequest.readBulkItem(in); } } } @Override public String toString() { // This is included in error messages so we'll try to make it somewhat user friendly. StringBuilder b = new StringBuilder("BulkShardRequest ["); b.append(shardId).append("] containing ["); if (items.length > 1) { b.append(items.length).append("] requests"); } else { b.append(items[0].request()).append("]"); } switch (getRefreshPolicy()) { case IMMEDIATE: b.append(" and a refresh"); break; case WAIT_UNTIL: b.append(" blocking until refresh"); break; case NONE: break; } return b.toString(); } @Override public String getDescription() { return "requests[" + items.length + "], index[" + index + "]"; } @Override public void onRetry() { for (BulkItemRequest item : items) { if (item.request() instanceof ReplicationRequest) { // all replication requests need to be notified here as well to ie. make sure that internal optimizations are // disabled see IndexRequest#canHaveDuplicates() ((ReplicationRequest) item.request()).onRetry(); } } } }
apache-2.0
jleonhard/angular2-webpack-jquery-bootstrap
node_modules/source-map/lib/source-node.js
13796
/* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; var util = require('./util'); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are accessed by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); // The last line of a file might not have a newline. var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : undefined; } }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[remainingLinesIndex]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.splice(remainingLinesIndex).join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode;
mit
alexdresko/DefinitelyTyped
types/react-icons/lib/ti/document-delete.d.ts
182
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; declare class TiDocumentDelete extends React.Component<IconBaseProps> { } export = TiDocumentDelete;
mit
martinduparc/DefinitelyTyped
webspeechapi/index.d.ts
4460
// Type definitions for Web Speech API // Project: https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html // Definitions by: SaschaNaz <https://github.com/saschanaz> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Spec version: 19 October 2012 // Errata version: 6 June 2014 // Corrected unofficial spec version: 6 June 2014 interface SpeechRecognition extends EventTarget { grammars: SpeechGrammarList; lang: string; continuous: boolean; interimResults: boolean; maxAlternatives: number; serviceURI: string; start(): void; stop(): void; abort(): void; onaudiostart: (ev: Event) => any; onsoundstart: (ev: Event) => any; onspeechstart: (ev: Event) => any; onspeechend: (ev: Event) => any; onsoundend: (ev: Event) => any; onresult: (ev: SpeechRecognitionEvent) => any; onnomatch: (ev: SpeechRecognitionEvent) => any; onerror: (ev: SpeechRecognitionError) => any; onstart: (ev: Event) => any; onend: (ev: Event) => any; } interface SpeechRecognitionStatic { prototype: SpeechRecognition; new (): SpeechRecognition; } declare var SpeechRecognition: SpeechRecognitionStatic; declare var webkitSpeechRecognition: SpeechRecognitionStatic; interface SpeechRecognitionError extends Event { error: string; message: string; } interface SpeechRecognitionAlternative { transcript: string; confidence: number; } interface SpeechRecognitionResult { length: number; item(index: number): SpeechRecognitionAlternative; [index: number]: SpeechRecognitionAlternative; /* Errata 02 */ isFinal: boolean; } interface SpeechRecognitionResultList { length: number; item(index: number): SpeechRecognitionResult; [index: number]: SpeechRecognitionResult; } interface SpeechRecognitionEvent extends Event { resultIndex: number; results: SpeechRecognitionResultList; interpretation: any; emma: Document; } interface SpeechGrammar { src: string; weight: number; } interface SpeechGrammarStatic { prototype: SpeechGrammar; new (): SpeechGrammar; } declare var SpeechGrammar: SpeechGrammarStatic; declare var webkitSpeechGrammar: SpeechGrammarStatic; interface SpeechGrammarList { length: number; item(index: number): SpeechGrammar; [index: number]: SpeechGrammar; addFromURI(src: string, weight: number): void; addFromString(string: string, weight: number): void; } interface SpeechGrammarListStatic { prototype: SpeechGrammarList; new (): SpeechGrammarList; } declare var SpeechGrammarList: SpeechGrammarListStatic; declare var webkitSpeechGrammarList: SpeechGrammarListStatic; /* Errata 08 */ interface SpeechSynthesis extends EventTarget { pending: boolean; speaking: boolean; paused: boolean; /* Errata 11 */ onvoiceschanged: (ev: Event) => any; speak(utterance: SpeechSynthesisUtterance): void; cancel(): void; pause(): void; resume(): void; /* Errata 05 */ getVoices(): SpeechSynthesisVoice[]; } interface SpeechSynthesisGetter { speechSynthesis: SpeechSynthesis; } interface Window extends SpeechSynthesisGetter { } declare var speechSynthesis: SpeechSynthesis; interface SpeechSynthesisUtterance extends EventTarget { text: string; lang: string; /* Errata 07 */ voice: SpeechSynthesisVoice; volume: number; rate: number; pitch: number; onstart: (ev: SpeechSynthesisEvent) => any; onend: (ev: SpeechSynthesisEvent) => any; /* Errata 12 */ onerror: (ev: SpeechSynthesisErrorEvent) => any; onpause: (ev: SpeechSynthesisEvent) => any; onresume: (ev: SpeechSynthesisEvent) => any; onmark: (ev: SpeechSynthesisEvent) => any; onboundary: (ev: SpeechSynthesisEvent) => any; } interface SpeechSynthesisUtteranceStatic { prototype: SpeechSynthesisUtterance; new (): SpeechSynthesisUtterance; new (text: string): SpeechSynthesisUtterance; } declare var SpeechSynthesisUtterance: SpeechSynthesisUtteranceStatic; interface SpeechSynthesisEvent extends Event { /* Errata 08 */ utterance: SpeechSynthesisUtterance; charIndex: number; elapsedTime: number; name: string; } /* Errata 12 */ interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent { error: string; } interface SpeechSynthesisVoice { voiceURI: string; name: string; lang: string; localService: boolean; default: boolean; }
mit
alexdresko/DefinitelyTyped
types/react-icons/lib/fa/calendar-minus-o.d.ts
182
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; declare class FaCalendarMinusO extends React.Component<IconBaseProps> { } export = FaCalendarMinusO;
mit
rolandzwaga/DefinitelyTyped
types/react-icons/lib/md/assistant.d.ts
172
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; declare class MdAssistant extends React.Component<IconBaseProps> { } export = MdAssistant;
mit
Wangab/Jedis
src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java
3545
package redis.clients.jedis.tests; import java.util.ArrayList; import java.util.List; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Protocol; public class HostAndPortUtil { private static List<HostAndPort> redisHostAndPortList = new ArrayList<HostAndPort>(); private static List<HostAndPort> sentinelHostAndPortList = new ArrayList<HostAndPort>(); private static List<HostAndPort> clusterHostAndPortList = new ArrayList<HostAndPort>(); static { redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT)); redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 1)); redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 2)); redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 3)); redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 4)); redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 5)); redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 6)); sentinelHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT)); sentinelHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 1)); sentinelHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 2)); sentinelHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 3)); clusterHostAndPortList.add(new HostAndPort("localhost", 7379)); clusterHostAndPortList.add(new HostAndPort("localhost", 7380)); clusterHostAndPortList.add(new HostAndPort("localhost", 7381)); clusterHostAndPortList.add(new HostAndPort("localhost", 7382)); clusterHostAndPortList.add(new HostAndPort("localhost", 7383)); clusterHostAndPortList.add(new HostAndPort("localhost", 7384)); String envRedisHosts = System.getProperty("redis-hosts"); String envSentinelHosts = System.getProperty("sentinel-hosts"); String envClusterHosts = System.getProperty("cluster-hosts"); redisHostAndPortList = parseHosts(envRedisHosts, redisHostAndPortList); sentinelHostAndPortList = parseHosts(envSentinelHosts, sentinelHostAndPortList); clusterHostAndPortList = parseHosts(envClusterHosts, clusterHostAndPortList); } public static List<HostAndPort> parseHosts(String envHosts, List<HostAndPort> existingHostsAndPorts) { if (null != envHosts && 0 < envHosts.length()) { String[] hostDefs = envHosts.split(","); if (null != hostDefs && 2 <= hostDefs.length) { List<HostAndPort> envHostsAndPorts = new ArrayList<HostAndPort>(hostDefs.length); for (String hostDef : hostDefs) { String[] hostAndPort = hostDef.split(":"); if (null != hostAndPort && 2 == hostAndPort.length) { String host = hostAndPort[0]; int port = Protocol.DEFAULT_PORT; try { port = Integer.parseInt(hostAndPort[1]); } catch (final NumberFormatException nfe) { } envHostsAndPorts.add(new HostAndPort(host, port)); } } return envHostsAndPorts; } } return existingHostsAndPorts; } public static List<HostAndPort> getRedisServers() { return redisHostAndPortList; } public static List<HostAndPort> getSentinelServers() { return sentinelHostAndPortList; } public static List<HostAndPort> getClusterServers() { return clusterHostAndPortList; } }
mit
alexdresko/DefinitelyTyped
types/react-icons/lib/fa/umbrella.d.ts
170
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; declare class FaUmbrella extends React.Component<IconBaseProps> { } export = FaUmbrella;
mit
ruud-v-a/rust
src/test/codegen/small-dense-int-switch.cc
640
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #include <stdlib.h> extern "C" size_t test(size_t x, size_t y) { switch (x) { case 1: return y; case 2: return y*2; case 4: return y*3; default: return 11; } }
apache-2.0
s3u-group/QuanLyChiDao
vendor/phpoffice/phpexcel/Examples/33chartcreate-pie.php
6492
<?php /** Error reporting */ error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); date_default_timezone_set('Europe/London'); define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />'); date_default_timezone_set('Europe/London'); /** * PHPExcel * * Copyright (C) 2006 - 2014 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ /** PHPExcel */ require_once dirname(__FILE__) . '/../Classes/PHPExcel.php'; $objPHPExcel = new PHPExcel(); $objWorksheet = $objPHPExcel->getActiveSheet(); $objWorksheet->fromArray( array( array('', 2010, 2011, 2012), array('Q1', 12, 15, 21), array('Q2', 56, 73, 86), array('Q3', 52, 61, 69), array('Q4', 30, 32, 0), ) ); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataseriesLabels1 = array( new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011 ); // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues1 = array( new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$5', NULL, 4), // Q1 to Q4 ); // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues1 = array( new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$C$2:$C$5', NULL, 4), ); // Build the dataseries $series1 = new PHPExcel_Chart_DataSeries( PHPExcel_Chart_DataSeries::TYPE_PIECHART, // plotType PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping range(0, count($dataSeriesValues1)-1), // plotOrder $dataseriesLabels1, // plotLabel $xAxisTickValues1, // plotCategory $dataSeriesValues1 // plotValues ); // Set up a layout object for the Pie chart $layout1 = new PHPExcel_Chart_Layout(); $layout1->setShowVal(TRUE); $layout1->setShowPercent(TRUE); // Set the series in the plot area $plotarea1 = new PHPExcel_Chart_PlotArea($layout1, array($series1)); // Set the chart legend $legend1 = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false); $title1 = new PHPExcel_Chart_Title('Test Pie Chart'); // Create the chart $chart1 = new PHPExcel_Chart( 'chart1', // name $title1, // title $legend1, // legend $plotarea1, // plotArea true, // plotVisibleOnly 0, // displayBlanksAs NULL, // xAxisLabel NULL // yAxisLabel - Pie charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart1->setTopLeftPosition('A7'); $chart1->setBottomRightPosition('H20'); // Add the chart to the worksheet $objWorksheet->addChart($chart1); // Set the Labels for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataseriesLabels2 = array( new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1), // 2011 ); // Set the X-Axis Labels // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $xAxisTickValues2 = array( new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$5', NULL, 4), // Q1 to Q4 ); // Set the Data values for each data series we want to plot // Datatype // Cell reference for data // Format Code // Number of datapoints in series // Data values // Data Marker $dataSeriesValues2 = array( new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$C$2:$C$5', NULL, 4), ); // Build the dataseries $series2 = new PHPExcel_Chart_DataSeries( PHPExcel_Chart_DataSeries::TYPE_DONUTCHART, // plotType PHPExcel_Chart_DataSeries::GROUPING_STANDARD, // plotGrouping range(0, count($dataSeriesValues2)-1), // plotOrder $dataseriesLabels2, // plotLabel $xAxisTickValues2, // plotCategory $dataSeriesValues2 // plotValues ); // Set up a layout object for the Pie chart $layout2 = new PHPExcel_Chart_Layout(); $layout2->setShowVal(TRUE); $layout2->setShowCatName(TRUE); // Set the series in the plot area $plotarea2 = new PHPExcel_Chart_PlotArea($layout2, array($series2)); $title2 = new PHPExcel_Chart_Title('Test Donut Chart'); // Create the chart $chart2 = new PHPExcel_Chart( 'chart2', // name $title2, // title NULL, // legend $plotarea2, // plotArea true, // plotVisibleOnly 0, // displayBlanksAs NULL, // xAxisLabel NULL // yAxisLabel - Like Pie charts, Donut charts don't have a Y-Axis ); // Set the position where the chart should appear in the worksheet $chart2->setTopLeftPosition('I7'); $chart2->setBottomRightPosition('P20'); // Add the chart to the worksheet $objWorksheet->addChart($chart2); // Save Excel 2007 file echo date('H:i:s') , " Write to Excel2007 format" , EOL; $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->setIncludeCharts(TRUE); $objWriter->save(str_replace('.php', '.xlsx', __FILE__)); echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL; // Echo memory peak usage echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL; // Echo done echo date('H:i:s') , " Done writing file" , EOL; echo 'File has been created in ' , getcwd() , EOL;
bsd-3-clause
binarycrusader/go
test/fixedbugs/issue14164.dir/a.go
1127
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package a // F is an exported function, small enough to be inlined. // It defines a local interface with an unexported method // f, which will appear with a package-qualified method // name in the export data. func F(x interface{}) bool { _, ok := x.(interface { f() }) return ok } // Like F but with the unexported interface method f // defined via an embedded interface t. The compiler // always flattens embedded interfaces so there should // be no difference between F and G. Alas, currently // G is not inlineable (at least via export data), so // the issue is moot, here. func G(x interface{}) bool { type t0 interface { f() } _, ok := x.(interface { t0 }) return ok } // Like G but now the embedded interface is declared // at package level. This function is inlineable via // export data. The export data representation is like // for F. func H(x interface{}) bool { _, ok := x.(interface { t1 }) return ok } type t1 interface { f() }
bsd-3-clause
havran/Drupal.sk
docroot/drupal/core/modules/views/tests/modules/views_test_data/src/Plugin/views/style/MappingTest.php
1801
<?php /** * @file * Contains \Drupal\views_test_data\Plugin\views\style\MappingTest. */ namespace Drupal\views_test_data\Plugin\views\style; use Drupal\views\Plugin\views\style\Mapping; use Drupal\views\Plugin\views\field\NumericField; /** * Provides a test plugin for the mapping style. * * @ingroup views_style_plugins * * @ViewsStyle( * id = "mapping_test", * title = @Translation("Field mapping"), * help = @Translation("Maps specific fields to specific purposes."), * theme = "views_view_mapping_test", * display_types = {"normal", "test"} * ) */ class MappingTest extends Mapping { /** * Overrides Drupal\views\Plugin\views\style\Mapping::defineMapping(). */ protected function defineMapping() { return array( 'title_field' => array( '#title' => $this->t('Title field'), '#description' => $this->t('Choose the field with the custom title.'), '#toggle' => TRUE, '#required' => TRUE, ), 'name_field' => array( '#title' => $this->t('Name field'), '#description' => $this->t('Choose the field with the custom name.'), ), 'numeric_field' => array( '#title' => $this->t('Numeric field'), '#description' => $this->t('Select one or more numeric fields.'), '#multiple' => TRUE, '#toggle' => TRUE, '#filter' => 'filterNumericFields', '#required' => TRUE, ), ); } /** * Restricts the allowed fields to only numeric fields. * * @param array $fields * An array of field labels, keyed by the field ID. */ protected function filterNumericFields(&$fields) { foreach ($this->view->field as $id => $field) { if (!($field instanceof NumericField)) { unset($fields[$id]); } } } }
gpl-2.0
besutra/freeraum
core/lib/Drupal/Component/Transliteration/data/x38.php
2024
<?php /** * @file * Generic transliteration data for the PHPTransliteration class. */ $base = array( 0x00 => 'dao', NULL, 'ao', NULL, 'xi', 'fu', 'dan', 'jiu', 'run', 'tong', 'qu', 'e', 'qi', 'ji', 'ji', 'hua', 0x10 => 'jiao', 'zui', 'biao', 'meng', 'bai', 'wei', 'yi', 'ao', 'yu', 'hao', 'dui', 'wo', 'ni', 'cuan', NULL, 'li', 0x20 => 'lu', 'niao', 'huai', 'li', NULL, 'lu', 'feng', 'mi', 'yu', NULL, 'ju', NULL, NULL, 'zhan', 'peng', 'yi', 0x30 => NULL, 'ji', 'bi', NULL, 'ren', 'huang', 'fan', 'ge', 'ku', 'jie', 'sha', NULL, 'si', 'tong', 'yuan', 'zi', 0x40 => 'bi', 'kua', 'li', 'huang', 'xun', 'nuo', NULL, 'zhe', 'wen', 'xian', 'qia', 'ye', 'mao', NULL, NULL, 'shu', 0x50 => NULL, 'qiao', 'zhun', 'kun', 'wu', 'ying', 'chuang', 'ti', 'lian', 'bi', 'gou', 'mang', 'xie', 'feng', 'lou', 'zao', 0x60 => 'zheng', 'chu', 'man', 'long', NULL, 'yin', 'pin', 'zheng', 'jian', 'luan', 'nie', 'yi', NULL, 'ji', 'ji', 'zhai', 0x70 => 'yu', 'jiu', 'huan', 'zhi', 'la', 'ling', 'zhi', 'ben', 'zha', 'ju', 'dan', 'liao', 'yi', 'zhao', 'xian', 'chi', 0x80 => 'ci', 'chi', 'yan', 'lang', 'dou', 'long', 'chan', NULL, 'tui', 'cha', 'ai', 'chi', NULL, 'ying', 'zhe', 'tou', 0x90 => NULL, 'tui', 'cha', 'yao', 'zong', NULL, 'pan', 'qiao', 'lian', 'qin', 'lu', 'yan', 'kang', 'su', 'yi', 'chan', 0xA0 => 'jiong', 'jiang', NULL, 'jing', NULL, 'dong', NULL, 'juan', 'han', 'di', NULL, NULL, 'hong', NULL, 'chi', 'diao', 0xB0 => 'bi', NULL, 'xun', 'lu', NULL, 'xie', 'bi', NULL, 'bi', NULL, 'xian', 'rui', 'bie', 'er', 'juan', NULL, 0xC0 => 'zhen', 'bei', 'e', 'yu', 'qu', 'zan', 'mi', 'yi', 'si', NULL, NULL, NULL, 'shan', 'tai', 'mu', 'jing', 0xD0 => 'bian', 'rong', 'ceng', 'can', 'ding', NULL, NULL, NULL, NULL, 'di', 'tong', 'ta', 'xing', 'song', 'duo', 'xi', 0xE0 => 'tao', NULL, 'ti', 'shan', 'jian', 'zhi', 'wei', 'yin', NULL, NULL, 'huan', 'zhong', 'qi', 'zong', NULL, 'xie', 0xF0 => 'xie', 'ze', 'wei', NULL, NULL, 'ta', 'zhan', 'ning', NULL, NULL, NULL, 'yi', 'ren', 'shu', 'cha', 'zhuo', );
gpl-2.0
soovorov/d8intranet
drupal/core/modules/views/src/Plugin/views/sort/GroupByNumeric.php
1187
<?php /** * @file * Contains \Drupal\views\Plugin\views\sort\GroupByNumeric. */ namespace Drupal\views\Plugin\views\sort; use Drupal\views\Plugin\views\display\DisplayPluginBase; use Drupal\views\ViewExecutable; use Drupal\views\Views; /** * Handler for GROUP BY on simple numeric fields. * * @ViewsSort("groupby_numeric") */ class GroupByNumeric extends SortPluginBase { /** * Overrides \Drupal\views\Plugin\views\HandlerBase::init(). */ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) { parent::init($view, $display, $options); // Initialize the original handler. $this->handler = Views::handlerManager('sort')->getHandler($options); $this->handler->init($view, $display, $options); } /** * Called to add the field to a query. */ public function query() { $this->ensureMyTable(); $params = array( 'function' => $this->options['group_type'], ); $this->query->addOrderBy($this->tableAlias, $this->realField, $this->options['order'], NULL, $params); } public function adminLabel($short = FALSE) { return $this->getField(parent::adminLabel($short)); } }
gpl-2.0
cnsoft/kbengine-cocos2dx
kbe/src/lib/dependencies/boost/multiprecision/detail/functions/trig.hpp
21891
// Copyright Christopher Kormanyos 2002 - 2011. // Copyright 2011 John Maddock. Distributed under the Boost // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This work is based on an earlier work: // "Algorithm 910: A Portable C++ Multiple-Precision System for Special-Function Calculations", // in ACM TOMS, {VOL 37, ISSUE 4, (February 2011)} (C) ACM, 2011. http://doi.acm.org/10.1145/1916461.1916469 // // This file has no include guards or namespaces - it's expanded inline inside default_ops.hpp // template <class T> void hyp0F1(T& result, const T& b, const T& x) { typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type; typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type; // Compute the series representation of Hypergeometric0F1 taken from // http://functions.wolfram.com/HypergeometricFunctions/Hypergeometric0F1/06/01/01/ // There are no checks on input range or parameter boundaries. T x_pow_n_div_n_fact(x); T pochham_b (b); T bp (b); eval_divide(result, x_pow_n_div_n_fact, pochham_b); eval_add(result, ui_type(1)); si_type n; T tol; tol = ui_type(1); eval_ldexp(tol, tol, 1 - boost::multiprecision::detail::digits2<number<T, et_on> >::value); eval_multiply(tol, result); if(eval_get_sign(tol) < 0) tol.negate(); T term; static const unsigned series_limit = boost::multiprecision::detail::digits2<number<T, et_on> >::value < 100 ? 100 : boost::multiprecision::detail::digits2<number<T, et_on> >::value; // Series expansion of hyperg_0f1(; b; x). for(n = 2; n < series_limit; ++n) { eval_multiply(x_pow_n_div_n_fact, x); eval_divide(x_pow_n_div_n_fact, n); eval_increment(bp); eval_multiply(pochham_b, bp); eval_divide(term, x_pow_n_div_n_fact, pochham_b); eval_add(result, term); bool neg_term = eval_get_sign(term) < 0; if(neg_term) term.negate(); if(term.compare(tol) <= 0) break; } if(n >= series_limit) BOOST_THROW_EXCEPTION(std::runtime_error("H0F1 Failed to Converge")); } template <class T> void eval_sin(T& result, const T& x) { BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The sin function is only valid for floating point types."); if(&result == &x) { T temp; eval_sin(temp, x); result = temp; return; } typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type; typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type; typedef typename mpl::front<typename T::float_types>::type fp_type; switch(eval_fpclassify(x)) { case FP_INFINITE: case FP_NAN: if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN) result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend(); else BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type.")); return; case FP_ZERO: result = ui_type(0); return; default: ; } // Local copy of the argument T xx = x; // Analyze and prepare the phase of the argument. // Make a local, positive copy of the argument, xx. // The argument xx will be reduced to 0 <= xx <= pi/2. bool b_negate_sin = false; if(eval_get_sign(x) < 0) { xx.negate(); b_negate_sin = !b_negate_sin; } T n_pi, t; // Remove even multiples of pi. if(xx.compare(get_constant_pi<T>()) > 0) { eval_divide(n_pi, xx, get_constant_pi<T>()); eval_trunc(n_pi, n_pi); t = ui_type(2); eval_fmod(t, n_pi, t); const bool b_n_pi_is_even = eval_get_sign(t) == 0; eval_multiply(n_pi, get_constant_pi<T>()); eval_subtract(xx, n_pi); BOOST_MATH_INSTRUMENT_CODE(xx.str(0, std::ios_base::scientific)); BOOST_MATH_INSTRUMENT_CODE(n_pi.str(0, std::ios_base::scientific)); // Adjust signs if the multiple of pi is not even. if(!b_n_pi_is_even) { b_negate_sin = !b_negate_sin; } } // Reduce the argument to 0 <= xx <= pi/2. eval_ldexp(t, get_constant_pi<T>(), -1); if(xx.compare(t) > 0) { eval_subtract(xx, get_constant_pi<T>(), xx); BOOST_MATH_INSTRUMENT_CODE(xx.str(0, std::ios_base::scientific)); } eval_subtract(t, xx); const bool b_zero = eval_get_sign(xx) == 0; const bool b_pi_half = eval_get_sign(t) == 0; // Check if the reduced argument is very close to 0 or pi/2. const bool b_near_zero = xx.compare(fp_type(1e-1)) < 0; const bool b_near_pi_half = t.compare(fp_type(1e-1)) < 0;; if(b_zero) { result = ui_type(0); } else if(b_pi_half) { result = ui_type(1); } else if(b_near_zero) { eval_multiply(t, xx, xx); eval_divide(t, si_type(-4)); T t2; t2 = fp_type(1.5); hyp0F1(result, t2, t); BOOST_MATH_INSTRUMENT_CODE(result.str(0, std::ios_base::scientific)); eval_multiply(result, xx); } else if(b_near_pi_half) { eval_multiply(t, t); eval_divide(t, si_type(-4)); T t2; t2 = fp_type(0.5); hyp0F1(result, t2, t); BOOST_MATH_INSTRUMENT_CODE(result.str(0, std::ios_base::scientific)); } else { // Scale to a small argument for an efficient Taylor series, // implemented as a hypergeometric function. Use a standard // divide by three identity a certain number of times. // Here we use division by 3^9 --> (19683 = 3^9). static const si_type n_scale = 9; static const si_type n_three_pow_scale = static_cast<si_type>(19683L); eval_divide(xx, n_three_pow_scale); // Now with small arguments, we are ready for a series expansion. eval_multiply(t, xx, xx); eval_divide(t, si_type(-4)); T t2; t2 = fp_type(1.5); hyp0F1(result, t2, t); BOOST_MATH_INSTRUMENT_CODE(result.str(0, std::ios_base::scientific)); eval_multiply(result, xx); // Convert back using multiple angle identity. for(boost::int32_t k = static_cast<boost::int32_t>(0); k < n_scale; k++) { // Rescale the cosine value using the multiple angle identity. eval_multiply(t2, result, ui_type(3)); eval_multiply(t, result, result); eval_multiply(t, result); eval_multiply(t, ui_type(4)); eval_subtract(result, t2, t); } } if(b_negate_sin) result.negate(); } template <class T> void eval_cos(T& result, const T& x) { BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The cos function is only valid for floating point types."); if(&result == &x) { T temp; eval_cos(temp, x); result = temp; return; } typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type; typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type; typedef typename mpl::front<typename T::float_types>::type fp_type; switch(eval_fpclassify(x)) { case FP_INFINITE: case FP_NAN: if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN) result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend(); else BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type.")); return; case FP_ZERO: result = ui_type(1); return; default: ; } // Local copy of the argument T xx = x; // Analyze and prepare the phase of the argument. // Make a local, positive copy of the argument, xx. // The argument xx will be reduced to 0 <= xx <= pi/2. bool b_negate_cos = false; if(eval_get_sign(x) < 0) { xx.negate(); } T n_pi, t; // Remove even multiples of pi. if(xx.compare(get_constant_pi<T>()) > 0) { eval_divide(t, xx, get_constant_pi<T>()); eval_trunc(n_pi, t); BOOST_MATH_INSTRUMENT_CODE(n_pi.str(0, std::ios_base::scientific)); eval_multiply(t, n_pi, get_constant_pi<T>()); BOOST_MATH_INSTRUMENT_CODE(t.str(0, std::ios_base::scientific)); eval_subtract(xx, t); BOOST_MATH_INSTRUMENT_CODE(xx.str(0, std::ios_base::scientific)); // Adjust signs if the multiple of pi is not even. t = ui_type(2); eval_fmod(t, n_pi, t); const bool b_n_pi_is_even = eval_get_sign(t) == 0; if(!b_n_pi_is_even) { b_negate_cos = !b_negate_cos; } } // Reduce the argument to 0 <= xx <= pi/2. eval_ldexp(t, get_constant_pi<T>(), -1); int com = xx.compare(t); if(com > 0) { eval_subtract(xx, get_constant_pi<T>(), xx); b_negate_cos = !b_negate_cos; BOOST_MATH_INSTRUMENT_CODE(xx.str(0, std::ios_base::scientific)); } const bool b_zero = eval_get_sign(xx) == 0; const bool b_pi_half = com == 0; // Check if the reduced argument is very close to 0. const bool b_near_zero = xx.compare(fp_type(1e-1)) < 0; if(b_zero) { result = si_type(1); } else if(b_pi_half) { result = si_type(0); } else if(b_near_zero) { eval_multiply(t, xx, xx); eval_divide(t, si_type(-4)); n_pi = fp_type(0.5f); hyp0F1(result, n_pi, t); BOOST_MATH_INSTRUMENT_CODE(result.str(0, std::ios_base::scientific)); } else { eval_subtract(t, xx); eval_sin(result, t); } if(b_negate_cos) result.negate(); } template <class T> void eval_tan(T& result, const T& x) { BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The tan function is only valid for floating point types."); if(&result == &x) { T temp; eval_tan(temp, x); result = temp; return; } T t; eval_sin(result, x); eval_cos(t, x); eval_divide(result, t); } template <class T> void hyp2F1(T& result, const T& a, const T& b, const T& c, const T& x) { // Compute the series representation of hyperg_2f1 taken from // Abramowitz and Stegun 15.1.1. // There are no checks on input range or parameter boundaries. typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type; T x_pow_n_div_n_fact(x); T pochham_a (a); T pochham_b (b); T pochham_c (c); T ap (a); T bp (b); T cp (c); eval_multiply(result, pochham_a, pochham_b); eval_divide(result, pochham_c); eval_multiply(result, x_pow_n_div_n_fact); eval_add(result, ui_type(1)); T lim; eval_ldexp(lim, result, 1 - boost::multiprecision::detail::digits2<number<T, et_on> >::value); if(eval_get_sign(lim) < 0) lim.negate(); ui_type n; T term; static const unsigned series_limit = boost::multiprecision::detail::digits2<number<T, et_on> >::value < 100 ? 100 : boost::multiprecision::detail::digits2<number<T, et_on> >::value; // Series expansion of hyperg_2f1(a, b; c; x). for(n = 2; n < series_limit; ++n) { eval_multiply(x_pow_n_div_n_fact, x); eval_divide(x_pow_n_div_n_fact, n); eval_increment(ap); eval_multiply(pochham_a, ap); eval_increment(bp); eval_multiply(pochham_b, bp); eval_increment(cp); eval_multiply(pochham_c, cp); eval_multiply(term, pochham_a, pochham_b); eval_divide(term, pochham_c); eval_multiply(term, x_pow_n_div_n_fact); eval_add(result, term); if(eval_get_sign(term) < 0) term.negate(); if(lim.compare(term) >= 0) break; } if(n > series_limit) BOOST_THROW_EXCEPTION(std::runtime_error("H2F1 failed to converge.")); } template <class T> void eval_asin(T& result, const T& x) { BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The asin function is only valid for floating point types."); typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type; typedef typename mpl::front<typename T::float_types>::type fp_type; if(&result == &x) { T t(x); eval_asin(result, t); return; } switch(eval_fpclassify(x)) { case FP_NAN: case FP_INFINITE: if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN) result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend(); else BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type.")); return; case FP_ZERO: result = ui_type(0); return; default: ; } const bool b_neg = eval_get_sign(x) < 0; T xx(x); if(b_neg) xx.negate(); int c = xx.compare(ui_type(1)); if(c > 0) { if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN) result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend(); else BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type.")); return; } else if(c == 0) { result = get_constant_pi<T>(); eval_ldexp(result, result, -1); if(b_neg) result.negate(); return; } if(xx.compare(fp_type(1e-4)) < 0) { // http://functions.wolfram.com/ElementaryFunctions/ArcSin/26/01/01/ eval_multiply(xx, xx); T t1, t2; t1 = fp_type(0.5f); t2 = fp_type(1.5f); hyp2F1(result, t1, t1, t2, xx); eval_multiply(result, x); return; } else if(xx.compare(fp_type(1 - 1e-4f)) > 0) { T dx1; T t1, t2; eval_subtract(dx1, ui_type(1), xx); t1 = fp_type(0.5f); t2 = fp_type(1.5f); eval_ldexp(dx1, dx1, -1); hyp2F1(result, t1, t1, t2, dx1); eval_ldexp(dx1, dx1, 2); eval_sqrt(t1, dx1); eval_multiply(result, t1); eval_ldexp(t1, get_constant_pi<T>(), -1); result.negate(); eval_add(result, t1); if(b_neg) result.negate(); return; } // Get initial estimate using standard math function asin. double dd; eval_convert_to(&dd, xx); result = fp_type(std::asin(dd)); // Newton-Raphson iteration while(true) { T s, c; eval_sin(s, result); eval_cos(c, result); eval_subtract(s, xx); eval_divide(s, c); eval_subtract(result, s); T lim; eval_ldexp(lim, result, 1 - boost::multiprecision::detail::digits2<number<T, et_on> >::value); if(eval_get_sign(s) < 0) s.negate(); if(eval_get_sign(lim) < 0) lim.negate(); if(lim.compare(s) >= 0) break; } if(b_neg) result.negate(); } template <class T> inline void eval_acos(T& result, const T& x) { BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The acos function is only valid for floating point types."); typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type; switch(eval_fpclassify(x)) { case FP_NAN: case FP_INFINITE: if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN) result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend(); else BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type.")); return; case FP_ZERO: result = get_constant_pi<T>(); eval_ldexp(result, result, -1); // divide by two. return; } eval_abs(result, x); int c = result.compare(ui_type(1)); if(c > 0) { if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN) result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend(); else BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type.")); return; } else if(c == 0) { if(eval_get_sign(x) < 0) result = get_constant_pi<T>(); else result = ui_type(0); return; } eval_asin(result, x); T t; eval_ldexp(t, get_constant_pi<T>(), -1); eval_subtract(result, t); result.negate(); } template <class T> void eval_atan(T& result, const T& x) { BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The atan function is only valid for floating point types."); typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type; typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type; typedef typename mpl::front<typename T::float_types>::type fp_type; switch(eval_fpclassify(x)) { case FP_NAN: result = x; return; case FP_ZERO: result = ui_type(0); return; case FP_INFINITE: if(eval_get_sign(x) < 0) { eval_ldexp(result, get_constant_pi<T>(), -1); result.negate(); } else eval_ldexp(result, get_constant_pi<T>(), -1); return; default: ; } const bool b_neg = eval_get_sign(x) < 0; T xx(x); if(b_neg) xx.negate(); if(xx.compare(fp_type(0.1)) < 0) { T t1, t2, t3; t1 = ui_type(1); t2 = fp_type(0.5f); t3 = fp_type(1.5f); eval_multiply(xx, xx); xx.negate(); hyp2F1(result, t1, t2, t3, xx); eval_multiply(result, x); return; } if(xx.compare(fp_type(10)) > 0) { T t1, t2, t3; t1 = fp_type(0.5f); t2 = ui_type(1u); t3 = fp_type(1.5f); eval_multiply(xx, xx); eval_divide(xx, si_type(-1), xx); hyp2F1(result, t1, t2, t3, xx); eval_divide(result, x); if(!b_neg) result.negate(); eval_ldexp(t1, get_constant_pi<T>(), -1); eval_add(result, t1); if(b_neg) result.negate(); return; } // Get initial estimate using standard math function atan. fp_type d; eval_convert_to(&d, xx); result = fp_type(std::atan(d)); // Newton-Raphson iteration static const boost::int32_t double_digits10_minus_a_few = std::numeric_limits<double>::digits10 - 3; T s, c, t; for(boost::int32_t digits = double_digits10_minus_a_few; digits <= std::numeric_limits<number<T, et_on> >::digits10; digits *= 2) { eval_sin(s, result); eval_cos(c, result); eval_multiply(t, xx, c); eval_subtract(t, s); eval_multiply(s, t, c); eval_add(result, s); } if(b_neg) result.negate(); } template <class T> void eval_atan2(T& result, const T& y, const T& x) { BOOST_STATIC_ASSERT_MSG(number_category<T>::value == number_kind_floating_point, "The atan2 function is only valid for floating point types."); if(&result == &y) { T temp(y); eval_atan2(result, temp, x); return; } else if(&result == &x) { T temp(x); eval_atan2(result, y, temp); return; } typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type; switch(eval_fpclassify(y)) { case FP_NAN: result = y; return; case FP_ZERO: { int c = eval_get_sign(x); if(c < 0) result = get_constant_pi<T>(); else if(c >= 0) result = ui_type(0); // Note we allow atan2(0,0) to be zero, even though it's mathematically undefined return; } case FP_INFINITE: { if(eval_fpclassify(x) == FP_INFINITE) { if(std::numeric_limits<number<T, et_on> >::has_quiet_NaN) result = std::numeric_limits<number<T, et_on> >::quiet_NaN().backend(); else BOOST_THROW_EXCEPTION(std::domain_error("Result is undefined or complex and there is no NaN for this number type.")); } else { eval_ldexp(result, get_constant_pi<T>(), -1); if(eval_get_sign(y) < 0) result.negate(); } return; } } switch(eval_fpclassify(x)) { case FP_NAN: result = x; return; case FP_ZERO: { eval_ldexp(result, get_constant_pi<T>(), -1); if(eval_get_sign(y) < 0) result.negate(); return; } case FP_INFINITE: if(eval_get_sign(x) > 0) result = ui_type(0); else result = get_constant_pi<T>(); if(eval_get_sign(y) < 0) result.negate(); return; } T xx; eval_divide(xx, y, x); if(eval_get_sign(xx) < 0) xx.negate(); eval_atan(result, xx); // Determine quadrant (sign) based on signs of x, y const bool y_neg = eval_get_sign(y) < 0; const bool x_neg = eval_get_sign(x) < 0; if(y_neg != x_neg) result.negate(); if(x_neg) { if(y_neg) eval_subtract(result, get_constant_pi<T>()); else eval_add(result, get_constant_pi<T>()); } } template<class T, class A> inline typename enable_if<is_arithmetic<A>, void>::type eval_atan2(T& result, const T& x, const A& a) { typedef typename boost::multiprecision::detail::canonical<A, T>::type canonical_type; typedef typename mpl::if_<is_same<A, canonical_type>, T, canonical_type>::type cast_type; cast_type c; c = a; eval_atan2(result, x, c); } template<class T, class A> inline typename enable_if<is_arithmetic<A>, void>::type eval_atan2(T& result, const A& x, const T& a) { typedef typename boost::multiprecision::detail::canonical<A, T>::type canonical_type; typedef typename mpl::if_<is_same<A, canonical_type>, T, canonical_type>::type cast_type; cast_type c; c = x; eval_atan2(result, c, a); }
lgpl-3.0
portworx/docker
daemon/logger/journald/journald.go
3180
// +build linux // Package journald provides the log driver for forwarding server logs // to endpoints that receive the systemd format. package journald import ( "fmt" "sync" "unicode" "github.com/Sirupsen/logrus" "github.com/coreos/go-systemd/journal" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger/loggerutils" ) const name = "journald" type journald struct { vars map[string]string // additional variables and values to send to the journal along with the log message readers readerList } type readerList struct { mu sync.Mutex readers map[*logger.LogWatcher]*logger.LogWatcher } func init() { if err := logger.RegisterLogDriver(name, New); err != nil { logrus.Fatal(err) } if err := logger.RegisterLogOptValidator(name, validateLogOpt); err != nil { logrus.Fatal(err) } } // sanitizeKeyMode returns the sanitized string so that it could be used in journald. // In journald log, there are special requirements for fields. // Fields must be composed of uppercase letters, numbers, and underscores, but must // not start with an underscore. func sanitizeKeyMod(s string) string { n := "" for _, v := range s { if 'a' <= v && v <= 'z' { v = unicode.ToUpper(v) } else if ('Z' < v || v < 'A') && ('9' < v || v < '0') { v = '_' } // If (n == "" && v == '_'), then we will skip as this is the beginning with '_' if !(n == "" && v == '_') { n += string(v) } } return n } // New creates a journald logger using the configuration passed in on // the context. func New(ctx logger.Context) (logger.Logger, error) { if !journal.Enabled() { return nil, fmt.Errorf("journald is not enabled on this host") } // Strip a leading slash so that people can search for // CONTAINER_NAME=foo rather than CONTAINER_NAME=/foo. name := ctx.ContainerName if name[0] == '/' { name = name[1:] } // parse log tag tag, err := loggerutils.ParseLogTag(ctx, loggerutils.DefaultTemplate) if err != nil { return nil, err } vars := map[string]string{ "CONTAINER_ID": ctx.ContainerID[:12], "CONTAINER_ID_FULL": ctx.ContainerID, "CONTAINER_NAME": name, "CONTAINER_TAG": tag, } extraAttrs := ctx.ExtraAttributes(sanitizeKeyMod) for k, v := range extraAttrs { vars[k] = v } return &journald{vars: vars, readers: readerList{readers: make(map[*logger.LogWatcher]*logger.LogWatcher)}}, nil } // We don't actually accept any options, but we have to supply a callback for // the factory to pass the (probably empty) configuration map to. func validateLogOpt(cfg map[string]string) error { for key := range cfg { switch key { case "labels": case "env": case "tag": default: return fmt.Errorf("unknown log opt '%s' for journald log driver", key) } } return nil } func (s *journald) Log(msg *logger.Message) error { vars := map[string]string{} for k, v := range s.vars { vars[k] = v } if msg.Partial { vars["CONTAINER_PARTIAL_MESSAGE"] = "true" } if msg.Source == "stderr" { return journal.Send(string(msg.Line), journal.PriErr, vars) } return journal.Send(string(msg.Line), journal.PriInfo, vars) } func (s *journald) Name() string { return name }
apache-2.0
jhen0409/react-native
ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java
3984
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.uimanager; import java.util.List; import java.util.Map; import com.facebook.react.common.MapBuilder; /** * Helps generate constants map for {@link UIManagerModule} by collecting and merging constants from * registered view managers. */ /* package */ class UIManagerModuleConstantsHelper { private static final String CUSTOM_BUBBLING_EVENT_TYPES_KEY = "customBubblingEventTypes"; private static final String CUSTOM_DIRECT_EVENT_TYPES_KEY = "customDirectEventTypes"; /** * Generates map of constants that is then exposed by {@link UIManagerModule}. The constants map * contains the following predefined fields for 'customBubblingEventTypes' and * 'customDirectEventTypes'. Provided list of {@param viewManagers} is then used to populate * content of those predefined fields using * {@link ViewManager#getExportedCustomBubblingEventTypeConstants} and * {@link ViewManager#getExportedCustomDirectEventTypeConstants} respectively. Each view manager * is in addition allowed to expose viewmanager-specific constants that are placed under the key * that corresponds to the view manager's name (see {@link ViewManager#getName}). Constants are * merged into the map of {@link UIManagerModule} base constants that is stored in * {@link UIManagerModuleConstants}. * TODO(6845124): Create a test for this */ /* package */ static Map<String, Object> createConstants(List<ViewManager> viewManagers) { Map<String, Object> constants = UIManagerModuleConstants.getConstants(); Map bubblingEventTypesConstants = UIManagerModuleConstants.getBubblingEventTypeConstants(); Map directEventTypesConstants = UIManagerModuleConstants.getDirectEventTypeConstants(); for (ViewManager viewManager : viewManagers) { Map viewManagerBubblingEvents = viewManager.getExportedCustomBubblingEventTypeConstants(); if (viewManagerBubblingEvents != null) { recursiveMerge(bubblingEventTypesConstants, viewManagerBubblingEvents); } Map viewManagerDirectEvents = viewManager.getExportedCustomDirectEventTypeConstants(); if (viewManagerDirectEvents != null) { recursiveMerge(directEventTypesConstants, viewManagerDirectEvents); } Map viewManagerConstants = MapBuilder.newHashMap(); Map customViewConstants = viewManager.getExportedViewConstants(); if (customViewConstants != null) { viewManagerConstants.put("Constants", customViewConstants); } Map viewManagerCommands = viewManager.getCommandsMap(); if (viewManagerCommands != null) { viewManagerConstants.put("Commands", viewManagerCommands); } Map<String, String> viewManagerNativeProps = viewManager.getNativeProps(); if (!viewManagerNativeProps.isEmpty()) { viewManagerConstants.put("NativeProps", viewManagerNativeProps); } if (!viewManagerConstants.isEmpty()) { constants.put(viewManager.getName(), viewManagerConstants); } } constants.put(CUSTOM_BUBBLING_EVENT_TYPES_KEY, bubblingEventTypesConstants); constants.put(CUSTOM_DIRECT_EVENT_TYPES_KEY, directEventTypesConstants); return constants; } /** * Merges {@param source} map into {@param dest} map recursively */ private static void recursiveMerge(Map dest, Map source) { for (Object key : source.keySet()) { Object sourceValue = source.get(key); Object destValue = dest.get(key); if (destValue != null && (sourceValue instanceof Map) && (destValue instanceof Map)) { recursiveMerge((Map) destValue, (Map) sourceValue); } else { dest.put(key, sourceValue); } } } }
bsd-3-clause
houchj/selenium
java/server/src/org/openqa/selenium/remote/server/DefaultDriverFactory.java
2901
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.remote.server; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.VisibleForTesting; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; public class DefaultDriverFactory implements DriverFactory { private static final Logger LOG = Logger.getLogger(DefaultDriverFactory.class.getName()); private Map<Capabilities, DriverProvider> capabilitiesToDriverProvider = new ConcurrentHashMap<>(); public void registerDriverProvider(DriverProvider driverProvider) { if (driverProvider.canCreateDriverInstances()) { capabilitiesToDriverProvider.put(driverProvider.getProvidedCapabilities(), driverProvider); } else { LOG.info(String.format("Driver provider %s is not registered", driverProvider)); } } @VisibleForTesting DriverProvider getProviderMatching(Capabilities desired) { // We won't be able to make a match if no drivers have been registered. checkState(!capabilitiesToDriverProvider.isEmpty(), "No drivers have been registered, will be unable to match %s", desired); Capabilities bestMatchingCapabilities = CapabilitiesComparator.getBestMatch(desired, capabilitiesToDriverProvider.keySet()); return capabilitiesToDriverProvider.get(bestMatchingCapabilities); } public WebDriver newInstance(Capabilities capabilities) { DriverProvider provider = getProviderMatching(capabilities); if (provider.canCreateDriverInstanceFor(capabilities)) { return getProviderMatching(capabilities).newInstance(capabilities); } else { throw new WebDriverException(String.format( "The best matching driver provider %s can't create a new driver instance for %s", provider, capabilities)); } } public boolean hasMappingFor(Capabilities capabilities) { return capabilitiesToDriverProvider.containsKey(capabilities); } }
apache-2.0
revocoin/Revo
share/qt/make_spinner.py
1035
#!/usr/bin/env python # W.J. van der Laan, 2011 # Make spinning .mng animation from a .png # Requires imagemagick 6.7+ from __future__ import division from os import path from PIL import Image from subprocess import Popen SRC='img/reload_scaled.png' DST='../../src/qt/res/movies/update_spinner.mng' TMPDIR='/tmp' TMPNAME='tmp-%03i.png' NUMFRAMES=35 FRAMERATE=10.0 CONVERT='convert' CLOCKWISE=True DSIZE=(16,16) im_src = Image.open(SRC) if CLOCKWISE: im_src = im_src.transpose(Image.FLIP_LEFT_RIGHT) def frame_to_filename(frame): return path.join(TMPDIR, TMPNAME % frame) frame_files = [] for frame in xrange(NUMFRAMES): rotation = (frame + 0.5) / NUMFRAMES * 360.0 if CLOCKWISE: rotation = -rotation im_new = im_src.rotate(rotation, Image.BICUBIC) im_new.thumbnail(DSIZE, Image.ANTIALIAS) outfile = frame_to_filename(frame) im_new.save(outfile, 'png') frame_files.append(outfile) p = Popen([CONVERT, "-delay", str(FRAMERATE), "-dispose", "2"] + frame_files + [DST]) p.communicate()
mit
saurabhse/hybo
node_modules/babel-register/node_modules/core-js/library/fn/number/is-safe-integer.js
122
require('../../modules/es6.number.is-safe-integer'); module.exports = require('../../modules/_core').Number.isSafeInteger;
mit
jamesdraper5/angularapp
node_modules/mongoose/lib/query.js
78458
/*! * Module dependencies. */ var mquery = require('mquery'); var util = require('util'); var events = require('events'); var mongo = require('mongodb'); var utils = require('./utils'); var Promise = require('./promise'); var helpers = require('./queryhelpers'); var Types = require('./schema/index'); var Document = require('./document'); var QueryStream = require('./querystream'); /** * Query constructor used for building queries. * * ####Example: * * var query = new Query(); * query.setOptions({ lean : true }); * query.collection(model.collection); * query.where('age').gte(21).exec(callback); * * @param {Object} [options] * @param {Object} [model] * @param {Object} [conditions] * @param {Object} [collection] Mongoose collection * @api private */ function Query(conditions, options, model, collection) { // this stuff is for dealing with custom queries created by #toConstructor if (!this._mongooseOptions) { this._mongooseOptions = {}; } // this is the case where we have a CustomQuery, we need to check if we got // options passed in, and if we did, merge them in if (options) { var keys = Object.keys(options); for (var i=0; i < keys.length; i++) { var k = keys[i]; this._mongooseOptions[k] = options[k]; } } if (collection) { this.mongooseCollection = collection; } if (model) { this.model = model; } // this is needed because map reduce returns a model that can be queried, but // all of the queries on said model should be lean if (this.model && this.model._mapreduce) { this.lean(); } // inherit mquery mquery.call(this, this.mongooseCollection, options); if (conditions) { this.find(conditions); } } /*! * inherit mquery */ Query.prototype = new mquery; Query.prototype.constructor = Query; Query.base = mquery.prototype; /** * Flag to opt out of using `$geoWithin`. * * mongoose.Query.use$geoWithin = false; * * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. * * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ * @default true * @property use$geoWithin * @memberOf Query * @receiver Query * @api public */ Query.use$geoWithin = mquery.use$geoWithin; /** * Converts this query to a customized, reusable query constructor with all arguments and options retained. * * ####Example * * // Create a query for adventure movies and read from the primary * // node in the replica-set unless it is down, in which case we'll * // read from a secondary node. * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); * * // create a custom Query constructor based off these settings * var Adventure = query.toConstructor(); * * // Adventure is now a subclass of mongoose.Query and works the same way but with the * // default query parameters and options set. * Adventure().exec(callback) * * // further narrow down our query results while still using the previous settings * Adventure().where({ name: /^Life/ }).exec(callback); * * // since Adventure is a stand-alone constructor we can also add our own * // helper methods and getters without impacting global queries * Adventure.prototype.startsWith = function (prefix) { * this.where({ name: new RegExp('^' + prefix) }) * return this; * } * Object.defineProperty(Adventure.prototype, 'highlyRated', { * get: function () { * this.where({ rating: { $gt: 4.5 }}); * return this; * } * }) * Adventure().highlyRated.startsWith('Life').exec(callback) * * New in 3.7.3 * * @return {Query} subclass-of-Query * @api public */ Query.prototype.toConstructor = function toConstructor () { function CustomQuery (criteria, options) { if (!(this instanceof CustomQuery)) return new CustomQuery(criteria, options); Query.call(this, criteria, options || null); } util.inherits(CustomQuery, Query); // set inherited defaults var p = CustomQuery.prototype; p.options = {}; p.setOptions(this.options); p.op = this.op; p._conditions = utils.clone(this._conditions); p._fields = utils.clone(this._fields); p._update = utils.clone(this._update); p._path = this._path; p._distict = this._distinct; p._collection = this._collection; p.model = this.model; p.mongooseCollection = this.mongooseCollection; p._mongooseOptions = this._mongooseOptions; return CustomQuery; } /** * Specifies a javascript function or expression to pass to MongoDBs query system. * * ####Example * * query.$where('this.comments.length > 10 || this.name.length > 5') * * // or * * query.$where(function () { * return this.comments.length > 10 || this.name.length > 5; * }) * * ####NOTE: * * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** * * @see $where http://docs.mongodb.org/manual/reference/operator/where/ * @method $where * @param {String|Function} js javascript string or function * @return {Query} this * @memberOf Query * @method $where * @api public */ /** * Specifies a `path` for use with chaining. * * ####Example * * // instead of writing: * User.find({age: {$gte: 21, $lte: 65}}, callback); * * // we can instead write: * User.where('age').gte(21).lte(65); * * // passing query conditions is permitted * User.find().where({ name: 'vonderful' }) * * // chaining * User * .where('age').gte(21).lte(65) * .where('name', /^vonderful/i) * .where('friends').slice(10) * .exec(callback) * * @method where * @memberOf Query * @param {String|Object} [path] * @param {any} [val] * @return {Query} this * @api public */ /** * Specifies the complementary comparison value for paths specified with `where()` * * ####Example * * User.where('age').equals(49); * * // is the same as * * User.where('age', 49); * * @method equals * @memberOf Query * @param {Object} val * @return {Query} this * @api public */ /** * Specifies arguments for an `$or` condition. * * ####Example * * query.or([{ color: 'red' }, { status: 'emergency' }]) * * @see $or http://docs.mongodb.org/manual/reference/operator/or/ * @method or * @memberOf Query * @param {Array} array array of conditions * @return {Query} this * @api public */ /** * Specifies arguments for a `$nor` condition. * * ####Example * * query.nor([{ color: 'green' }, { status: 'ok' }]) * * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ * @method nor * @memberOf Query * @param {Array} array array of conditions * @return {Query} this * @api public */ /** * Specifies arguments for a `$and` condition. * * ####Example * * query.and([{ color: 'green' }, { status: 'ok' }]) * * @method and * @memberOf Query * @see $and http://docs.mongodb.org/manual/reference/operator/and/ * @param {Array} array array of conditions * @return {Query} this * @api public */ /** * Specifies a $gt query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * ####Example * * Thing.find().where('age').gt(21) * * // or * Thing.find().gt('age', 21) * * @method gt * @memberOf Query * @param {String} [path] * @param {Number} val * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ * @api public */ /** * Specifies a $gte query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method gte * @memberOf Query * @param {String} [path] * @param {Number} val * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ * @api public */ /** * Specifies a $lt query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method lt * @memberOf Query * @param {String} [path] * @param {Number} val * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ * @api public */ /** * Specifies a $lte query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method lte * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $ne query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ * @method ne * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies an $in query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @see $in http://docs.mongodb.org/manual/reference/operator/in/ * @method in * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies an $nin query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ * @method nin * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies an $all query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @see $all http://docs.mongodb.org/manual/reference/operator/all/ * @method all * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $size query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * ####Example * * MyModel.where('tags').size(0).exec(function (err, docs) { * if (err) return handleError(err); * * assert(Array.isArray(docs)); * console.log('documents with 0 tags', docs); * }) * * @see $size http://docs.mongodb.org/manual/reference/operator/size/ * @method size * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $regex query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ * @method regex * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $maxDistance query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ * @method maxDistance * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a `$mod` condition * * @method mod * @memberOf Query * @param {String} [path] * @param {Number} val * @return {Query} this * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ * @api public */ /** * Specifies an `$exists` condition * * ####Example * * // { name: { $exists: true }} * Thing.where('name').exists() * Thing.where('name').exists(true) * Thing.find().exists('name') * * // { name: { $exists: false }} * Thing.where('name').exists(false); * Thing.find().exists('name', false); * * @method exists * @memberOf Query * @param {String} [path] * @param {Number} val * @return {Query} this * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ * @api public */ /** * Specifies an `$elemMatch` condition * * ####Example * * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) * * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) * * query.elemMatch('comment', function (elem) { * elem.where('author').equals('autobot'); * elem.where('votes').gte(5); * }) * * query.where('comment').elemMatch(function (elem) { * elem.where({ author: 'autobot' }); * elem.where('votes').gte(5); * }) * * @method elemMatch * @memberOf Query * @param {String|Object|Function} path * @param {Object|Function} criteria * @return {Query} this * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ * @api public */ /** * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. * * ####Example * * query.where(path).within().box() * query.where(path).within().circle() * query.where(path).within().geometry() * * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); * query.where('loc').within({ polygon: [[],[],[],[]] }); * * query.where('loc').within([], [], []) // polygon * query.where('loc').within([], []) // box * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry * * **MUST** be used after `where()`. * * ####NOTE: * * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). * * ####NOTE: * * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). * * @method within * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ * @see $box http://docs.mongodb.org/manual/reference/operator/box/ * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ * @see $center http://docs.mongodb.org/manual/reference/operator/center/ * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ * @memberOf Query * @return {Query} this * @api public */ /** * Specifies a $slice projection for an array. * * ####Example * * query.slice('comments', 5) * query.slice('comments', -5) * query.slice('comments', [10, 5]) * query.where('comments').slice(5) * query.where('comments').slice([-10, 5]) * * @method slice * @memberOf Query * @param {String} [path] * @param {Number} val number/range of elements to slice * @return {Query} this * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice * @api public */ /** * Specifies the maximum number of documents the query will return. * * ####Example * * query.limit(20) * * ####Note * * Cannot be used with `distinct()` * * @method limit * @memberOf Query * @param {Number} val * @api public */ /** * Specifies the number of documents to skip. * * ####Example * * query.skip(100).limit(20) * * ####Note * * Cannot be used with `distinct()` * * @method skip * @memberOf Query * @param {Number} val * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ * @api public */ /** * Specifies the maxScan option. * * ####Example * * query.maxScan(100) * * ####Note * * Cannot be used with `distinct()` * * @method maxScan * @memberOf Query * @param {Number} val * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ * @api public */ /** * Specifies the batchSize option. * * ####Example * * query.batchSize(100) * * ####Note * * Cannot be used with `distinct()` * * @method batchSize * @memberOf Query * @param {Number} val * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ * @api public */ /** * Specifies the `comment` option. * * ####Example * * query.comment('login query') * * ####Note * * Cannot be used with `distinct()` * * @method comment * @memberOf Query * @param {Number} val * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ * @api public */ /** * Specifies this query as a `snapshot` query. * * ####Example * * query.snapshot() // true * query.snapshot(true) * query.snapshot(false) * * ####Note * * Cannot be used with `distinct()` * * @method snapshot * @memberOf Query * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ * @return {Query} this * @api public */ /** * Sets query hints. * * ####Example * * query.hint({ indexA: 1, indexB: -1}) * * ####Note * * Cannot be used with `distinct()` * * @method hint * @memberOf Query * @param {Object} val a hint object * @return {Query} this * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ * @api public */ /** * Specifies which document fields to include or exclude * * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). * * ####Example * * // include a and b, exclude c * query.select('a b -c'); * * // or you may use object notation, useful when * // you have keys already prefixed with a "-" * query.select({a: 1, b: 1, c: 0}); * * // force inclusion of field excluded at schema level * query.select('+path') * * ####NOTE: * * Cannot be used with `distinct()`. * * _v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3._ * * @method select * @memberOf Query * @param {Object|String} arg * @return {Query} this * @see SchemaType * @api public */ /** * _DEPRECATED_ Sets the slaveOk option. * * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). * * ####Example: * * query.slaveOk() // true * query.slaveOk(true) * query.slaveOk(false) * * @method slaveOk * @memberOf Query * @deprecated use read() preferences instead if on mongodb >= 2.2 * @param {Boolean} v defaults to true * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ * @see read() #query_Query-read * @return {Query} this * @api public */ /** * Determines the MongoDB nodes from which to read. * * ####Preferences: * * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. * secondary Read from secondary if available, otherwise error. * primaryPreferred Read from primary if available, otherwise a secondary. * secondaryPreferred Read from a secondary if available, otherwise read from the primary. * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. * * Aliases * * p primary * pp primaryPreferred * s secondary * sp secondaryPreferred * n nearest * * ####Example: * * new Query().read('primary') * new Query().read('p') // same as primary * * new Query().read('primaryPreferred') * new Query().read('pp') // same as primaryPreferred * * new Query().read('secondary') * new Query().read('s') // same as secondary * * new Query().read('secondaryPreferred') * new Query().read('sp') // same as secondaryPreferred * * new Query().read('nearest') * new Query().read('n') // same as nearest * * // read from secondaries with matching tags * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) * * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). * * @method read * @memberOf Query * @param {String} pref one of the listed preference options or aliases * @param {Array} [tags] optional tags for this query * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences * @return {Query} this * @api public */ Query.prototype.read = function read (pref, tags) { // first cast into a ReadPreference object to support tags var readPref = utils.readPref.apply(utils.readPref, arguments); return Query.base.read.call(this, readPref); } /** * Merges another Query or conditions object into this one. * * When a Query is passed, conditions, field selection and options are merged. * * New in 3.7.0 * * @method merge * @memberOf Query * @param {Query|Object} source * @return {Query} this */ /** * Sets query options. * * ####Options: * * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * * - [maxscan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * * - [lean](./api.html#query_Query-lean) * * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) * * _* denotes a query helper method is also available_ * * @param {Object} options * @api public */ Query.prototype.setOptions = function (options, overwrite) { // overwrite is only for internal use if (overwrite) { // ensure that _mongooseOptions & options are two different objects this._mongooseOptions = (options && utils.clone(options)) || {}; this.options = options || {}; if('populate' in options) { this.populate(this._mongooseOptions); } return this; } if (!(options && 'Object' == options.constructor.name)) { return this; } return Query.base.setOptions.call(this, options); } /** * Returns fields selection for this query. * * @method _fieldsForExec * @return {Object} * @api private */ /** * Return an update document with corrected $set operations. * * @method _updateForExec * @api private */ /** * Makes sure _path is set. * * @method _ensurePath * @param {String} method * @api private */ /** * Determines if `conds` can be merged using `mquery().merge()` * * @method canMerge * @memberOf Query * @param {Object} conds * @return {Boolean} * @api private */ /** * Returns default options for this query. * * @param {Model} model * @api private */ Query.prototype._optionsForExec = function (model) { var options = Query.base._optionsForExec.call(this); delete options.populate; model = model || this.model; if (!model) { return options; } else { if (!('safe' in options) && model.schema.options.safe) { options.safe = model.schema.options.safe; } if (!('readPreference' in options) && model.schema.options.read) { options.readPreference = model.schema.options.read; } return options; } }; /** * Sets the lean option. * * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied. * * ####Example: * * new Query().lean() // true * new Query().lean(true) * new Query().lean(false) * * Model.find().lean().exec(function (err, docs) { * docs[0] instanceof mongoose.Document // false * }); * * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream). * * @param {Boolean} bool defaults to true * @return {Query} this * @api public */ Query.prototype.lean = function (v) { this._mongooseOptions.lean = arguments.length ? !!v : true; return this; } /** * Finds documents. * * When no `callback` is passed, the query is not executed. * * ####Example * * query.find({ name: 'Los Pollos Hermanos' }).find(callback) * * @param {Object} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.find = function (conditions, callback) { if ('function' == typeof conditions) { callback = conditions; conditions = {}; } else if (conditions instanceof Document) { conditions = conditions.toObject(); } if (mquery.canMerge(conditions)) { this.merge(conditions); } prepareDiscriminatorCriteria(this); try { this.cast(this.model); this._castError = null; } catch (err) { this._castError = err; } // if we don't have a callback, then just return the query object if (!callback) { return Query.base.find.call(this); } var promise = new Promise(callback); if (this._castError) { promise.error(this._castError); return this; } this._applyPaths(); this._fields = this._castFields(this._fields); var fields = this._fieldsForExec(); var options = this._mongooseOptions; var self = this; return Query.base.find.call(this, {}, cb); function cb(err, docs) { if (err) return promise.error(err); if (0 === docs.length) { return promise.complete(docs); } if (!options.populate) { return true === options.lean ? promise.complete(docs) : completeMany(self.model, docs, fields, self, null, promise); } var pop = helpers.preparePopulationOptionsMQ(self, options); self.model.populate(docs, pop, function (err, docs) { if(err) return promise.error(err); return true === options.lean ? promise.complete(docs) : completeMany(self.model, docs, fields, self, pop, promise); }); } } /*! * hydrates many documents * * @param {Model} model * @param {Array} docs * @param {Object} fields * @param {Query} self * @param {Array} [pop] array of paths used in population * @param {Promise} promise */ function completeMany (model, docs, fields, self, pop, promise) { var arr = []; var count = docs.length; var len = count; var opts = pop ? { populated: pop } : undefined; for (var i=0; i < len; ++i) { arr[i] = helpers.createModel(model, docs[i], fields); arr[i].init(docs[i], opts, function (err) { if (err) return promise.error(err); --count || promise.complete(arr); }); } } /** * Declares the query a findOne operation. When executed, the first found document is passed to the callback. * * Passing a `callback` executes the query. * * ####Example * * var query = Kitten.where({ color: 'white' }); * query.findOne(function (err, kitten) { * if (err) return handleError(err); * if (kitten) { * // doc may be null if no document matched * } * }); * * @param {Object|Query} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ * @api public */ Query.prototype.findOne = function (conditions, fields, options, callback) { if ('function' == typeof conditions) { callback = conditions; conditions = null; fields = null; options = null; } if ('function' == typeof fields) { callback = fields; options = null; fields = null; } if ('function' == typeof options) { callback = options; options = null; } // make sure we don't send in the whole Document to merge() if (conditions instanceof Document) { conditions = conditions.toObject(); } if (options) { this.setOptions(options); } if (fields) { this.select(fields); } if (mquery.canMerge(conditions)) { this.merge(conditions); } prepareDiscriminatorCriteria(this); try { this.cast(this.model); this._castError = null; } catch (err) { this._castError = err; } if (!callback) { // already merged in the conditions, don't need to send them in. return Query.base.findOne.call(this); } var promise = new Promise(callback); if (this._castError) { promise.error(this._castError); return this; } this._applyPaths(); this._fields = this._castFields(this._fields); var options = this._mongooseOptions; var fields = this._fieldsForExec(); var self = this; // don't pass in the conditions because we already merged them in Query.base.findOne.call(this, {}, function cb (err, doc) { if (err) return promise.error(err); if (!doc) return promise.complete(null); if (!options.populate) { return true === options.lean ? promise.complete(doc) : completeOne(self.model, doc, fields, self, null, promise); } var pop = helpers.preparePopulationOptionsMQ(self, options); self.model.populate(doc, pop, function (err, doc) { if (err) return promise.error(err); return true === options.lean ? promise.complete(doc) : completeOne(self.model, doc, fields, self, pop, promise); }); }) return this; } /** * Specifying this query as a `count` query. * * Passing a `callback` executes the query. * * ####Example: * * var countQuery = model.where({ 'color': 'black' }).count(); * * query.count({ color: 'black' }).count(callback) * * query.count({ color: 'black' }, callback) * * query.where('color', 'black').count(function (err, count) { * if (err) return handleError(err); * console.log('there are %d kittens', count); * }) * * @param {Object} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ * @api public */ Query.prototype.count = function (conditions, callback) { if ('function' == typeof conditions) { callback = conditions; conditions = undefined; } if (mquery.canMerge(conditions)) { this.merge(conditions); } try { this.cast(this.model); } catch (err) { callback(err); return this; } return Query.base.count.call(this, {}, callback); } /** * Declares or executes a distict() operation. * * Passing a `callback` executes the query. * * ####Example * * distinct(criteria, field, fn) * distinct(criteria, field) * distinct(field, fn) * distinct(field) * distinct(fn) * distinct() * * @param {Object|Query} [criteria] * @param {String} [field] * @param {Function} [callback] * @return {Query} this * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ * @api public */ Query.prototype.distinct = function (conditions, field, callback) { if (!callback) { if('function' == typeof field) { callback = field; if ('string' == typeof conditions) { field = conditions; conditions = undefined; } } switch (typeof conditions) { case 'string': field = conditions; conditions = undefined; break; case 'function': callback = conditions; field = undefined; conditions = undefined; break; } } if (conditions instanceof Document) { conditions = conditions.toObject(); } if (mquery.canMerge(conditions)) { this.merge(conditions) } try { this.cast(this.model); } catch (err) { callback(err); return this; } return Query.base.distinct.call(this, {}, field, callback); } /** * Sets the sort order * * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. * * If a string is passed, it must be a space delimited list of path names. The * sort order of each path is ascending unless the path name is prefixed with `-` * which will be treated as descending. * * ####Example * * // sort by "field" ascending and "test" descending * query.sort({ field: 'asc', test: -1 }); * * // equivalent * query.sort('field -test'); * * ####Note * * Cannot be used with `distinct()` * * @param {Object|String} arg * @return {Query} this * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ * @api public */ Query.prototype.sort = function (arg) { var nArg = {}; if (arguments.length > 1) { throw new Error("sort() only takes 1 Argument"); } if (Array.isArray(arg)) { // time to deal with the terrible syntax for (var i=0; i < arg.length; i++) { if (!Array.isArray(arg[i])) throw new Error("Invalid sort() argument."); nArg[arg[i][0]] = arg[i][1]; } } else { nArg = arg; } return Query.base.sort.call(this, nArg); } /** * Declare and/or execute this query as a remove() operation. * * ####Example * * Model.remove({ artist: 'Anne Murray' }, callback) * * ####Note * * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. * * // not executed * var query = Model.find().remove({ name: 'Anne Murray' }) * * // executed * query.remove({ name: 'Anne Murray' }, callback) * query.remove({ name: 'Anne Murray' }).remove(callback) * * // executed without a callback (unsafe write) * query.exec() * * // summary * query.remove(conds, fn); // executes * query.remove(conds) * query.remove(fn) // executes * query.remove() * * @param {Object|Query} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/ * @api public */ Query.prototype.remove = function (cond, callback) { if ('function' == typeof cond) { callback = cond; cond = null; } var cb = 'function' == typeof callback; try { this.cast(this.model); } catch (err) { if (cb) return process.nextTick(callback.bind(null, err)); return this; } return Query.base.remove.call(this, cond, callback); } /*! * hydrates a document * * @param {Model} model * @param {Document} doc * @param {Object} fields * @param {Query} self * @param {Array} [pop] array of paths used in population * @param {Promise} promise */ function completeOne (model, doc, fields, self, pop, promise) { var opts = pop ? { populated: pop } : undefined; var casted = helpers.createModel(model, doc, fields) casted.init(doc, opts, function (err) { if (err) return promise.error(err); promise.complete(casted); }); } /*! * If the model is a discriminator type and not root, then add the key & value to the criteria. */ function prepareDiscriminatorCriteria(query) { if (!query || !query.model || !query.model.schema) { return; } var schema = query.model.schema; if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; } } /** * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. * * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. * * ####Available options * * - `new`: bool - true to return the modified document rather than the original. defaults to true * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * * ####Examples * * query.findOneAndUpdate(conditions, update, options, callback) // executes * query.findOneAndUpdate(conditions, update, options) // returns Query * query.findOneAndUpdate(conditions, update, callback) // executes * query.findOneAndUpdate(conditions, update) // returns Query * query.findOneAndUpdate(update, callback) // returns Query * query.findOneAndUpdate(update) // returns Query * query.findOneAndUpdate(callback) // executes * query.findOneAndUpdate() // returns Query * * @method findOneAndUpdate * @memberOf Query * @param {Object|Query} [query] * @param {Object} [doc] * @param {Object} [options] * @param {Function} [callback] * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @return {Query} this * @api public */ /** * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. * * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. * * ####Available options * * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * * ####Examples * * A.where().findOneAndRemove(conditions, options, callback) // executes * A.where().findOneAndRemove(conditions, options) // return Query * A.where().findOneAndRemove(conditions, callback) // executes * A.where().findOneAndRemove(conditions) // returns Query * A.where().findOneAndRemove(callback) // executes * A.where().findOneAndRemove() // returns Query * * @method findOneAndRemove * @memberOf Query * @param {Object} [conditions] * @param {Object} [options] * @param {Function} [callback] * @return {Query} this * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @api public */ /** * Override mquery.prototype._findAndModify to provide casting etc. * * @param {String} type - either "remove" or "update" * @param {Function} callback * @api private */ Query.prototype._findAndModify = function (type, callback) { if ('function' != typeof callback) { throw new Error("Expected callback in _findAndModify"); } var model = this.model , promise = new Promise(callback) , self = this , castedQuery , castedDoc , fields , opts; castedQuery = castQuery(this); if (castedQuery instanceof Error) { process.nextTick(promise.error.bind(promise, castedQuery)); return promise; } opts = this._optionsForExec(model); if ('remove' == type) { opts.remove = true; } else { if (!('new' in opts)) opts.new = true; if (!('upsert' in opts)) opts.upsert = false; castedDoc = castDoc(this, opts.overwrite); if (!castedDoc) { if (opts.upsert) { // still need to do the upsert to empty doc var doc = utils.clone(castedQuery); delete doc._id; castedDoc = { $set: doc }; } else { return this.findOne(callback); } } else if (castedDoc instanceof Error) { process.nextTick(promise.error.bind(promise, castedDoc)); return promise; } else { // In order to make MongoDB 2.6 happy (see // https://jira.mongodb.org/browse/SERVER-12266 and related issues) // if we have an actual update document but $set is empty, junk the $set. if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) { delete castedDoc.$set; } } } this._applyPaths(); var self = this; var options = this._mongooseOptions; if (this._fields) { fields = utils.clone(this._fields); opts.fields = this._castFields(fields); if (opts.fields instanceof Error) { process.nextTick(promise.error.bind(promise, opts.fields)); return promise; } } if (opts.sort) convertSortToArray(opts); this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(cb)); function cb (err, doc) { if (err) return promise.error(err); if (!doc || (utils.isObject(doc) && Object.keys(doc).length === 0)) { return promise.complete(null); } if (!options.populate) { return true === options.lean ? promise.complete(doc) : completeOne(self.model, doc, fields, self, null, promise); } var pop = helpers.preparePopulationOptionsMQ(self, options); self.model.populate(doc, pop, function (err, doc) { if (err) return promise.error(err); return true === options.lean ? promise.complete(doc) : completeOne(self.model, doc, fields, self, pop, promise); }); } return promise; } /*! * The mongodb driver 1.3.23 only supports the nested array sort * syntax. We must convert it or sorting findAndModify will not work. */ function convertSortToArray (opts) { if (Array.isArray(opts.sort)) return; if (!utils.isObject(opts.sort)) return; var sort = []; for (var key in opts.sort) if (utils.object.hasOwnProperty(opts.sort, key)) { sort.push([ key, opts.sort[key] ]); } opts.sort = sort; } /** * Declare and/or execute this query as an update() operation. * * _All paths passed that are not $atomic operations will become $set ops._ * * ####Example * * Model.where({ _id: id }).update({ title: 'words' }) * * // becomes * * Model.where({ _id: id }).update({ $set: { title: 'words' }}) * * ####Note * * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. * * ####Note * * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. * * var q = Model.where({ _id: id }); * q.update({ $set: { name: 'bob' }}).update(); // not executed * * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe * * // keys that are not $atomic ops become $set. * // this executes the same command as the previous example. * q.update({ name: 'bob' }).exec(); * * // overwriting with empty docs * var q = Model.where({ _id: id }).setOptions({ overwrite: true }) * q.update({ }, callback); // executes * * // multi update with overwrite to empty doc * var q = Model.where({ _id: id }); * q.setOptions({ multi: true, overwrite: true }) * q.update({ }); * q.update(callback); // executed * * // multi updates * Model.where() * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) * * // more multi updates * Model.where() * .setOptions({ multi: true }) * .update({ $set: { arr: [] }}, callback) * * // single update by default * Model.where({ email: '[email protected]' }) * .update({ $inc: { counter: 1 }}, callback) * * API summary * * update(criteria, doc, options, cb) // executes * update(criteria, doc, options) * update(criteria, doc, cb) // executes * update(criteria, doc) * update(doc, cb) // executes * update(doc) * update(cb) // executes * update(true) // executes (unsafe write) * update() * * @param {Object} [criteria] * @param {Object} [doc] the update command * @param {Object} [options] * @param {Function} [callback] * @return {Query} this * @see Model.update #model_Model.update * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ * @api public */ Query.prototype.update = function (conditions, doc, options, callback) { if ('function' === typeof options) { // Scenario: update(conditions, doc, callback) callback = options; options = null; } else if ('function' === typeof doc) { // Scenario: update(doc, callback); callback = doc; doc = conditions; conditions = {}; options = null; } else if ('function' === typeof conditions) { callback = conditions; conditions = undefined; doc = undefined; options = undefined; } // make sure we don't send in the whole Document to merge() if (conditions instanceof Document) { conditions = conditions.toObject(); } // strict is an option used in the update checking, make sure it gets set if (options) { if ('strict' in options) { this._mongooseOptions.strict = options.strict; } } // if doc is undefined at this point, this means this function is being // executed by exec(not always see below). Grab the update doc from here in // order to validate // This could also be somebody calling update() or update({}). Probably not a // common use case, check for _update to make sure we don't do anything bad if (!doc && this._update) { doc = this._updateForExec(); } if (mquery.canMerge(conditions)) { this.merge(conditions); } // validate the selector part of the query var castedQuery = castQuery(this); if (castedQuery instanceof Error) { if(callback) { callback(castedQuery); return this; } else { throw castedQuery; } } // validate the update part of the query var castedDoc; try { castedDoc = this._castUpdate(doc, options && options.overwrite); } catch (err) { if (callback) { callback(err); return this; } else { throw err; } } if (!castedDoc) { callback && callback(null, 0); return this; } return Query.base.update.call(this, castedQuery, castedDoc, options, callback); } /** * Executes the query * * ####Examples: * * var promise = query.exec(); * var promise = query.exec('update'); * * query.exec(callback); * query.exec('find', callback); * * @param {String|Function} [operation] * @param {Function} [callback] * @return {Promise} * @api public */ Query.prototype.exec = function exec (op, callback) { var promise = new Promise(); if ('function' == typeof op) { callback = op; op = null; } else if ('string' == typeof op) { this.op = op; } if (callback) promise.addBack(callback); if (!this.op) { promise.complete(); return promise; } Query.base.exec.call(this, op, promise.resolve.bind(promise)); return promise; } /** * Finds the schema for `path`. This is different than * calling `schema.path` as it also resolves paths with * positional selectors (something.$.another.$.path). * * @param {String} path * @api private */ Query.prototype._getSchema = function _getSchema (path) { return this.model._getSchema(path); } /*! * These operators require casting docs * to real Documents for Update operations. */ var castOps = { $push: 1 , $pushAll: 1 , $addToSet: 1 , $set: 1 }; /*! * These operators should be cast to numbers instead * of their path schema type. */ var numberOps = { $pop: 1 , $unset: 1 , $inc: 1 }; /** * Casts obj for an update command. * * @param {Object} obj * @return {Object} obj after casting its values * @api private */ Query.prototype._castUpdate = function _castUpdate (obj, overwrite) { if (!obj) return undefined; var ops = Object.keys(obj) , i = ops.length , ret = {} , hasKeys , val while (i--) { var op = ops[i]; // if overwrite is set, don't do any of the special $set stuff if ('$' !== op[0] && !overwrite) { // fix up $set sugar if (!ret.$set) { if (obj.$set) { ret.$set = obj.$set; } else { ret.$set = {}; } } ret.$set[op] = obj[op]; ops.splice(i, 1); if (!~ops.indexOf('$set')) ops.push('$set'); } else if ('$set' === op) { if (!ret.$set) { ret[op] = obj[op]; } } else { ret[op] = obj[op]; } } // cast each value i = ops.length; // if we get passed {} for the update, we still need to respect that when it // is an overwrite scenario if (overwrite) { hasKeys = true; } while (i--) { op = ops[i]; val = ret[op]; if (val && 'Object' === val.constructor.name && !overwrite) { hasKeys |= this._walkUpdatePath(val, op); } else if (overwrite && 'Object' === ret.constructor.name) { // if we are just using overwrite, cast the query and then we will // *always* return the value, even if it is an empty object. We need to // set hasKeys above because we need to account for the case where the // user passes {} and wants to clobber the whole document // Also, _walkUpdatePath expects an operation, so give it $set since that // is basically what we're doing this._walkUpdatePath(ret, '$set'); } else { var msg = 'Invalid atomic update value for ' + op + '. ' + 'Expected an object, received ' + typeof val; throw new Error(msg); } } return hasKeys && ret; } /** * Walk each path of obj and cast its values * according to its schema. * * @param {Object} obj - part of a query * @param {String} op - the atomic operator ($pull, $set, etc) * @param {String} pref - path prefix (internal only) * @return {Bool} true if this path has keys to update * @api private */ Query.prototype._walkUpdatePath = function _walkUpdatePath (obj, op, pref) { var prefix = pref ? pref + '.' : '' , keys = Object.keys(obj) , i = keys.length , hasKeys = false , schema , key , val var strict = 'strict' in this._mongooseOptions ? this._mongooseOptions.strict : this.model.schema.options.strict; while (i--) { key = keys[i]; val = obj[key]; if (val && 'Object' === val.constructor.name) { // watch for embedded doc schemas schema = this._getSchema(prefix + key); if (schema && schema.caster && op in castOps) { // embedded doc schema if (strict && !schema) { // path is not in our strict schema if ('throw' == strict) { throw new Error('Field `' + key + '` is not in schema.'); } else { // ignore paths not specified in schema delete obj[key]; } } else { hasKeys = true; if ('$each' in val) { obj[key] = { $each: this._castUpdateVal(schema, val.$each, op) } if (val.$slice) { obj[key].$slice = val.$slice | 0; } if (val.$sort) { obj[key].$sort = val.$sort; } if (!!val.$position || val.$position === 0) { obj[key].$position = val.$position; } } else { obj[key] = this._castUpdateVal(schema, val, op); } } } else if (op === '$currentDate') { // $currentDate can take an object obj[key] = this._castUpdateVal(schema, val, op); } else { hasKeys |= this._walkUpdatePath(val, op, prefix + key); } } else { schema = ('$each' === key || '$or' === key || '$and' === key) ? this._getSchema(pref) : this._getSchema(prefix + key); var skip = strict && !schema && !/real|nested/.test(this.model.schema.pathType(prefix + key)); if (skip) { if ('throw' == strict) { throw new Error('Field `' + prefix + key + '` is not in schema.'); } else { delete obj[key]; } } else { hasKeys = true; obj[key] = this._castUpdateVal(schema, val, op, key); } } } return hasKeys; } /** * Casts `val` according to `schema` and atomic `op`. * * @param {Schema} schema * @param {Object} val * @param {String} op - the atomic operator ($pull, $set, etc) * @param {String} [$conditional] * @api private */ Query.prototype._castUpdateVal = function _castUpdateVal (schema, val, op, $conditional) { if (!schema) { // non-existing schema path return op in numberOps ? Number(val) : val } var cond = schema.caster && op in castOps && (utils.isObject(val) || Array.isArray(val)); if (cond) { // Cast values for ops that add data to MongoDB. // Ensures embedded documents get ObjectIds etc. var tmp = schema.cast(val); if (Array.isArray(val)) { val = tmp; } else { val = tmp[0]; } } if (op in numberOps) { return Number(val); } if (op === '$currentDate') { if (typeof val === 'object') { return { $type: val.$type }; } return Boolean(val); } if (/^\$/.test($conditional)) { return schema.castForQuery($conditional, val); } return schema.castForQuery(val) } /*! * castQuery * @api private */ function castQuery (query) { try { return query.cast(query.model); } catch (err) { return err; } } /*! * castDoc * @api private */ function castDoc (query, overwrite) { try { return query._castUpdate(query._update, overwrite); } catch (err) { return err; } } /** * Specifies paths which should be populated with other documents. * * ####Example: * * Kitten.findOne().populate('owner').exec(function (err, kitten) { * console.log(kitten.owner.name) // Max * }) * * Kitten.find().populate({ * path: 'owner' * , select: 'name' * , match: { color: 'black' } * , options: { sort: { name: -1 }} * }).exec(function (err, kittens) { * console.log(kittens[0].owner.name) // Zoopa * }) * * // alternatively * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { * console.log(kittens[0].owner.name) // Zoopa * }) * * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback. * * @param {Object|String} path either the path to populate or an object specifying all parameters * @param {Object|String} [select] Field selection for the population query * @param {Model} [model] The name of the model you wish to use for population. If not specified, the name is looked up from the Schema ref. * @param {Object} [match] Conditions for the population query * @param {Object} [options] Options for the population query (sort, etc) * @see population ./populate.html * @see Query#select #query_Query-select * @see Model.populate #model_Model.populate * @return {Query} this * @api public */ Query.prototype.populate = function () { var res = utils.populate.apply(null, arguments); var opts = this._mongooseOptions; if (!utils.isObject(opts.populate)) { opts.populate = {}; } for (var i = 0; i < res.length; ++i) { opts.populate[res[i].path] = res[i]; } return this; } /** * Casts this query to the schema of `model` * * ####Note * * If `obj` is present, it is cast instead of this query. * * @param {Model} model * @param {Object} [obj] * @return {Object} * @api public */ Query.prototype.cast = function (model, obj) { obj || (obj = this._conditions); var schema = model.schema , paths = Object.keys(obj) , i = paths.length , any$conditionals , schematype , nested , path , type , val; while (i--) { path = paths[i]; val = obj[path]; if ('$or' === path || '$nor' === path || '$and' === path) { var k = val.length , orComponentQuery; while (k--) { orComponentQuery = new Query(val[k], {}, null, this.mongooseCollection); orComponentQuery.cast(model); val[k] = orComponentQuery._conditions; } } else if (path === '$where') { type = typeof val; if ('string' !== type && 'function' !== type) { throw new Error("Must have a string or function for $where"); } if ('function' === type) { obj[path] = val.toString(); } continue; } else { if (!schema) { // no casting for Mixed types continue; } schematype = schema.path(path); if (!schematype) { // Handle potential embedded array queries var split = path.split('.') , j = split.length , pathFirstHalf , pathLastHalf , remainingConds , castingQuery; // Find the part of the var path that is a path of the Schema while (j--) { pathFirstHalf = split.slice(0, j).join('.'); schematype = schema.path(pathFirstHalf); if (schematype) break; } // If a substring of the input path resolves to an actual real path... if (schematype) { // Apply the casting; similar code for $elemMatch in schema/array.js if (schematype.caster && schematype.caster.schema) { remainingConds = {}; pathLastHalf = split.slice(j).join('.'); remainingConds[pathLastHalf] = val; castingQuery = new Query(remainingConds, {}, null, this.mongooseCollection); castingQuery.cast(schematype.caster); obj[path] = castingQuery._conditions[pathLastHalf]; } else { obj[path] = val; } continue; } if (utils.isObject(val)) { // handle geo schemas that use object notation // { loc: { long: Number, lat: Number } var geo = val.$near ? '$near' : val.$nearSphere ? '$nearSphere' : val.$within ? '$within' : val.$geoIntersects ? '$geoIntersects' : ''; if (!geo) { continue; } var numbertype = new Types.Number('__QueryCasting__') var value = val[geo]; if (val.$maxDistance) { val.$maxDistance = numbertype.castForQuery(val.$maxDistance); } if ('$within' == geo) { var withinType = value.$center || value.$centerSphere || value.$box || value.$polygon; if (!withinType) { throw new Error('Bad $within paramater: ' + JSON.stringify(val)); } value = withinType; } else if ('$near' == geo && 'string' == typeof value.type && Array.isArray(value.coordinates)) { // geojson; cast the coordinates value = value.coordinates; } else if (('$near' == geo || '$nearSphere' == geo || '$geoIntersects' == geo) && value.$geometry && 'string' == typeof value.$geometry.type && Array.isArray(value.$geometry.coordinates)) { // geojson; cast the coordinates value = value.$geometry.coordinates; } ;(function _cast (val) { if (Array.isArray(val)) { val.forEach(function (item, i) { if (Array.isArray(item) || utils.isObject(item)) { return _cast(item); } val[i] = numbertype.castForQuery(item); }); } else { var nearKeys= Object.keys(val); var nearLen = nearKeys.length; while (nearLen--) { var nkey = nearKeys[nearLen]; var item = val[nkey]; if (Array.isArray(item) || utils.isObject(item)) { _cast(item); val[nkey] = item; } else { val[nkey] = numbertype.castForQuery(item); } } } })(value); } } else if (val === null || val === undefined) { continue; } else if ('Object' === val.constructor.name) { any$conditionals = Object.keys(val).some(function (k) { return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; }); if (!any$conditionals) { obj[path] = schematype.castForQuery(val); } else { var ks = Object.keys(val) , k = ks.length , $cond; while (k--) { $cond = ks[k]; nested = val[$cond]; if ('$exists' === $cond) { if ('boolean' !== typeof nested) { throw new Error("$exists parameter must be Boolean"); } continue; } if ('$type' === $cond) { if ('number' !== typeof nested) { throw new Error("$type parameter must be Number"); } continue; } if ('$not' === $cond) { this.cast(model, nested); } else { val[$cond] = schematype.castForQuery($cond, nested); } } } } else { obj[path] = schematype.castForQuery(val); } } } return obj; } /** * Casts selected field arguments for field selection with mongo 2.2 * * query.select({ ids: { $elemMatch: { $in: [hexString] }}) * * @param {Object} fields * @see https://github.com/LearnBoost/mongoose/issues/1091 * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ * @api private */ Query.prototype._castFields = function _castFields (fields) { var selected , elemMatchKeys , keys , key , out , i if (fields) { keys = Object.keys(fields); elemMatchKeys = []; i = keys.length; // collect $elemMatch args while (i--) { key = keys[i]; if (fields[key].$elemMatch) { selected || (selected = {}); selected[key] = fields[key]; elemMatchKeys.push(key); } } } if (selected) { // they passed $elemMatch, cast em try { out = this.cast(this.model, selected); } catch (err) { return err; } // apply the casted field args i = elemMatchKeys.length; while (i--) { key = elemMatchKeys[i]; fields[key] = out[key]; } } return fields; } /** * Applies schematype selected options to this query. * @api private */ Query.prototype._applyPaths = function applyPaths () { // determine if query is selecting or excluding fields var fields = this._fields , exclude , keys , ki if (fields) { keys = Object.keys(fields); ki = keys.length; while (ki--) { if ('+' == keys[ki][0]) continue; exclude = 0 === fields[keys[ki]]; break; } } // if selecting, apply default schematype select:true fields // if excluding, apply schematype select:false fields var selected = [] , excluded = [] , seen = []; analyzeSchema(this.model.schema); switch (exclude) { case true: excluded.length && this.select('-' + excluded.join(' -')); break; case false: selected.length && this.select(selected.join(' ')); break; case undefined: // user didn't specify fields, implies returning all fields. // only need to apply excluded fields excluded.length && this.select('-' + excluded.join(' -')); break; } return seen = excluded = selected = keys = fields = null; function analyzeSchema (schema, prefix) { prefix || (prefix = ''); // avoid recursion if (~seen.indexOf(schema)) return; seen.push(schema); schema.eachPath(function (path, type) { if (prefix) path = prefix + '.' + path; analyzePath(path, type); // array of subdocs? if (type.schema) { analyzeSchema(type.schema, path); } }); } function analyzePath (path, type) { if ('boolean' != typeof type.selected) return; var plusPath = '+' + path; if (fields && plusPath in fields) { // forced inclusion delete fields[plusPath]; // if there are other fields being included, add this one // if no other included fields, leave this out (implied inclusion) if (false === exclude && keys.length > 1 && !~keys.indexOf(path)) { fields[path] = 1; } return }; // check for parent exclusions var root = path.split('.')[0]; if (~excluded.indexOf(root)) return; ;(type.selected ? selected : excluded).push(path); } } /** * Casts selected field arguments for field selection with mongo 2.2 * * query.select({ ids: { $elemMatch: { $in: [hexString] }}) * * @param {Object} fields * @see https://github.com/LearnBoost/mongoose/issues/1091 * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ * @api private */ Query.prototype._castFields = function _castFields (fields) { var selected , elemMatchKeys , keys , key , out , i if (fields) { keys = Object.keys(fields); elemMatchKeys = []; i = keys.length; // collect $elemMatch args while (i--) { key = keys[i]; if (fields[key].$elemMatch) { selected || (selected = {}); selected[key] = fields[key]; elemMatchKeys.push(key); } } } if (selected) { // they passed $elemMatch, cast em try { out = this.cast(this.model, selected); } catch (err) { return err; } // apply the casted field args i = elemMatchKeys.length; while (i--) { key = elemMatchKeys[i]; fields[key] = out[key]; } } return fields; } /** * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface. * * ####Example * * // follows the nodejs 0.8 stream api * Thing.find({ name: /^hello/ }).stream().pipe(res) * * // manual streaming * var stream = Thing.find({ name: /^hello/ }).stream(); * * stream.on('data', function (doc) { * // do something with the mongoose document * }).on('error', function (err) { * // handle the error * }).on('close', function () { * // the stream is closed * }); * * ####Valid options * * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. * * ####Example * * // JSON.stringify all documents before emitting * var stream = Thing.find().stream({ transform: JSON.stringify }); * stream.pipe(writeStream); * * @return {QueryStream} * @param {Object} [options] * @see QueryStream * @api public */ Query.prototype.stream = function stream (opts) { this._applyPaths(); this._fields = this._castFields(this._fields); return new QueryStream(this, opts); } // the rest of these are basically to support older Mongoose syntax with mquery /** * _DEPRECATED_ Alias of `maxScan` * * @deprecated * @see maxScan #query_Query-maxScan * @method maxscan * @memberOf Query */ Query.prototype.maxscan = Query.base.maxScan; /** * Sets the tailable option (for use with capped collections). * * ####Example * * query.tailable() // true * query.tailable(true) * query.tailable(false) * * ####Note * * Cannot be used with `distinct()` * * @param {Boolean} bool defaults to true * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ * @api public */ Query.prototype.tailable = function (val, opts) { // we need to support the tailable({ awaitdata : true }) as well as the // tailable(true, {awaitdata :true}) syntax that mquery does not support if (val && val.constructor.name == 'Object') { opts = val; val = true; } if (val === undefined) { val = true; } if (opts && opts.awaitdata) this.options.awaitdata = true; return Query.base.tailable.call(this, val); } /** * Declares an intersects query for `geometry()`. * * ####Example * * query.where('path').intersects().geometry({ * type: 'LineString' * , coordinates: [[180.0, 11.0], [180, 9.0]] * }) * * query.where('path').intersects({ * type: 'LineString' * , coordinates: [[180.0, 11.0], [180, 9.0]] * }) * * ####NOTE: * * **MUST** be used after `where()`. * * ####NOTE: * * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). * * @method intersects * @memberOf Query * @param {Object} [arg] * @return {Query} this * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ * @api public */ /** * Specifies a `$geometry` condition * * ####Example * * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) * * // or * var polyB = [[ 0, 0 ], [ 1, 1 ]] * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) * * // or * var polyC = [ 0, 0 ] * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) * * // or * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) * * The argument is assigned to the most recent path passed to `where()`. * * ####NOTE: * * `geometry()` **must** come after either `intersects()` or `within()`. * * The `object` argument must contain `type` and `coordinates` properties. * - type {String} * - coordinates {Array} * * @method geometry * @memberOf Query * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. * @return {Query} this * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @api public */ /** * Specifies a `$near` or `$nearSphere` condition * * These operators return documents sorted by distance. * * ####Example * * query.where('loc').near({ center: [10, 10] }); * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); * query.near('loc', { center: [10, 10], maxDistance: 5 }); * * @method near * @memberOf Query * @param {String} [path] * @param {Object} val * @return {Query} this * @see $near http://docs.mongodb.org/manual/reference/operator/near/ * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @api public */ /*! * Overwriting mquery is needed to support a couple different near() forms found in older * versions of mongoose * near([1,1]) * near(1,1) * near(field, [1,2]) * near(field, 1, 2) * In addition to all of the normal forms supported by mquery */ Query.prototype.near = function () { var params = []; var sphere = this._mongooseOptions.nearSphere; // TODO refactor if (arguments.length === 1) { if (Array.isArray(arguments[0])) { params.push({ center: arguments[0], spherical: sphere }); } else if ('string' == typeof arguments[0]) { // just passing a path params.push(arguments[0]); } else if (utils.isObject(arguments[0])) { if ('boolean' != typeof arguments[0].spherical) { arguments[0].spherical = sphere; } params.push(arguments[0]); } else { throw new TypeError('invalid argument'); } } else if (arguments.length === 2) { if ('number' == typeof arguments[0] && 'number' == typeof arguments[1]) { params.push({ center: [arguments[0], arguments[1]], spherical: sphere}); } else if ('string' == typeof arguments[0] && Array.isArray(arguments[1])) { params.push(arguments[0]); params.push({ center: arguments[1], spherical: sphere }); } else if ('string' == typeof arguments[0] && utils.isObject(arguments[1])) { params.push(arguments[0]); if ('boolean' != typeof arguments[1].spherical) { arguments[1].spherical = sphere; } params.push(arguments[1]); } else { throw new TypeError('invalid argument'); } } else if (arguments.length === 3) { if ('string' == typeof arguments[0] && 'number' == typeof arguments[1] && 'number' == typeof arguments[2]) { params.push(arguments[0]); params.push({ center: [arguments[1], arguments[2]], spherical: sphere }); } else { throw new TypeError('invalid argument'); } } else { throw new TypeError('invalid argument'); } return Query.base.near.apply(this, params); } /** * _DEPRECATED_ Specifies a `$nearSphere` condition * * ####Example * * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); * * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. * * ####Example * * query.where('loc').near({ center: [10, 10], spherical: true }); * * @deprecated * @see near() #query_Query-near * @see $near http://docs.mongodb.org/manual/reference/operator/near/ * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ */ Query.prototype.nearSphere = function () { this._mongooseOptions.nearSphere = true; this.near.apply(this, arguments); return this; } /** * Specifies a $polygon condition * * ####Example * * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) * query.polygon('loc', [10,20], [13, 25], [7,15]) * * @method polygon * @memberOf Query * @param {String|Array} [path] * @param {Array|Object} [coordinatePairs...] * @return {Query} this * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @api public */ /** * Specifies a $box condition * * ####Example * * var lowerLeft = [40.73083, -73.99756] * var upperRight= [40.741404, -73.988135] * * query.where('loc').within().box(lowerLeft, upperRight) * query.box({ ll : lowerLeft, ur : upperRight }) * * @method box * @memberOf Query * @see $box http://docs.mongodb.org/manual/reference/operator/box/ * @see within() Query#within #query_Query-within * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @param {Object} val * @param [Array] Upper Right Coords * @return {Query} this * @api public */ /*! * this is needed to support the mongoose syntax of: * box(field, { ll : [x,y], ur : [x2,y2] }) * box({ ll : [x,y], ur : [x2,y2] }) */ Query.prototype.box = function (ll, ur) { if (!Array.isArray(ll) && utils.isObject(ll)) { ur = ll.ur; ll = ll.ll; } return Query.base.box.call(this, ll, ur); } /** * Specifies a $center or $centerSphere condition. * * ####Example * * var area = { center: [50, 50], radius: 10, unique: true } * query.where('loc').within().circle(area) * // alternatively * query.circle('loc', area); * * // spherical calculations * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } * query.where('loc').within().circle(area) * // alternatively * query.circle('loc', area); * * New in 3.7.0 * * @method circle * @memberOf Query * @param {String} [path] * @param {Object} area * @return {Query} this * @see $center http://docs.mongodb.org/manual/reference/operator/center/ * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/within/ * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @api public */ /** * _DEPRECATED_ Alias for [circle](#query_Query-circle) * * **Deprecated.** Use [circle](#query_Query-circle) instead. * * @deprecated * @method center * @memberOf Query * @api public */ Query.prototype.center = Query.base.circle; /** * _DEPRECATED_ Specifies a $centerSphere condition * * **Deprecated.** Use [circle](#query_Query-circle) instead. * * ####Example * * var area = { center: [50, 50], radius: 10 }; * query.where('loc').within().centerSphere(area); * * @deprecated * @param {String} [path] * @param {Object} val * @return {Query} this * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ * @api public */ Query.prototype.centerSphere = function () { if (arguments[0] && arguments[0].constructor.name == 'Object') { arguments[0].spherical = true; } if (arguments[1] && arguments[1].constructor.name == 'Object') { arguments[1].spherical = true; } Query.base.circle.apply(this, arguments); } /** * Determines if query fields are inclusive * * @return {Boolean} bool defaults to true * @api private */ Query.prototype._selectedInclusively = Query.prototype.selectedInclusively; /*! * Remove from public api for 3.8 */ Query.prototype.selected = Query.prototype.selectedInclusively = Query.prototype.selectedExclusively = undefined; /*! * Export */ module.exports = Query;
mit
summerpulse/openjdk7
jdk/test/sun/security/x509/AVA/BadName.java
1704
/* * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4184274 * @summary Make sure bad distinguished names (without keywords) don't * cause out-of-memory condition */ import java.io.IOException; import sun.security.x509.X500Name; public class BadName { public static void main(String args[]) throws Exception { try { // This used to throw java.lang.OutOfMemoryError, from which no // recovery is possible. // In the example below, the correct DN would be: "CN=John Doe" X500Name name = new X500Name("John Doe"); System.out.println(name.toString()); } catch (IOException ioe) { } } }
gpl-2.0
hyuni/homebrew
Library/Formula/eigen.rb
1455
class Eigen < Formula desc "C++ template library for linear algebra" homepage "http://eigen.tuxfamily.org/" url "https://bitbucket.org/eigen/eigen/get/3.2.6.tar.bz2" sha256 "8a3352f9a5361fe90e451a7305fb1896fc7f771dc16cc0edd8e6b157f52c343e" head "https://bitbucket.org/eigen/eigen", :using => :hg bottle do cellar :any_skip_relocation sha256 "10492e31aa6f9b9764aae344198b0e1f55e644510a67d11e73ccdc685c8e32b4" => :el_capitan sha256 "925c934e9215bfaa438d69723e0c785eb92761a70591b4c9038263ebf81afb90" => :yosemite sha256 "964552d6a1463744bbdf26de9be97836f84b4f6fcf007559f0cfd913c0873847" => :mavericks end option :universal depends_on "cmake" => :build def install ENV.universal_binary if build.universal? mkdir "eigen-build" do args = std_cmake_args args << "-Dpkg_config_libdir=#{lib}" << ".." system "cmake", *args system "make", "install" end (share/"cmake/Modules").install "cmake/FindEigen3.cmake" end test do (testpath/"test.cpp").write <<-EOS.undent #include <iostream> #include <Eigen/Dense> using Eigen::MatrixXd; int main() { MatrixXd m(2,2); m(0,0) = 3; m(1,0) = 2.5; m(0,1) = -1; m(1,1) = m(1,0) + m(0,1); std::cout << m << std::endl; } EOS system ENV.cxx, "test.cpp", "-I#{include}/eigen3", "-o", "test" assert_equal `./test`.split, %w[3 -1 2.5 1.5] end end
bsd-2-clause
shadedprofit/meteor
tools/tests/compiler-plugins.js
13246
var _ = require('underscore'); var selftest = require('../tool-testing/selftest.js'); var files = require('../fs/files.js'); import { getUrl } from '../utils/http-helpers.js'; import { sleepMs } from '../utils/utils.js'; var Sandbox = selftest.Sandbox; var MONGO_LISTENING = { stdout: " [initandlisten] waiting for connections on port" }; function startRun(sandbox) { var run = sandbox.run(); run.match("myapp"); run.match("proxy"); run.tellMongo(MONGO_LISTENING); run.match("MongoDB"); return run; }; // Tests the actual cache logic used by coffeescript. selftest.define("compiler plugin caching - coffee", () => { var s = new Sandbox({ fakeMongo: true }); s.createApp("myapp", "caching-coffee"); s.cd("myapp"); // Ask them to print out when they build a file (instead of using it from the // cache) as well as when they load cache from disk. s.set('METEOR_COFFEESCRIPT_CACHE_DEBUG', 't'); var run = startRun(s); // First program built (server or web.browser) compiles everything. run.match('CACHE(coffeescript): Ran (#1) on: ' + JSON.stringify( ['/f1.coffee', '/f2.coffee', '/f3.coffee', '/packages/local-pack/p.coffee'] )); // Second program doesn't need to compile anything because compilation works // the same on both programs. run.match("CACHE(coffeescript): Ran (#2) on: []"); // App prints this: run.match("Coffeescript X is 2 Y is 1 FromPackage is 4"); s.write("f2.coffee", "share.Y = 'Y is 3'\n"); // Only recompiles f2. run.match('CACHE(coffeescript): Ran (#3) on: ["/f2.coffee"]'); // And other program doesn't even need to do f2. run.match("CACHE(coffeescript): Ran (#4) on: []"); // Program prints this: run.match("Coffeescript X is 2 Y is 3 FromPackage is 4"); // Force a rebuild of the local package without actually changing the // coffeescript file in it. This should not require us to coffee.compile // anything (for either program). s.append("packages/local-pack/package.js", "\n// foo\n"); run.match("CACHE(coffeescript): Ran (#5) on: []"); run.match("CACHE(coffeescript): Ran (#6) on: []"); run.match("Coffeescript X is 2 Y is 3 FromPackage is 4"); // But writing to the actual source file in the local package should // recompile. s.write("packages/local-pack/p.coffee", "FromPackage = 'FromPackage is 5'"); run.match('CACHE(coffeescript): Ran (#7) on: ["/packages/local-pack/p.coffee"]'); run.match('CACHE(coffeescript): Ran (#8) on: []'); run.match("Coffeescript X is 2 Y is 3 FromPackage is 5"); // We never should have loaded cache from disk, since we only made // each compiler once and there were no cache files at this point. run.forbid('CACHE(coffeescript): Loaded'); // Kill the run. Change one coffee file and re-run. run.stop(); s.write("f2.coffee", "share.Y = 'Y is edited'\n"); run = startRun(s); // This time there's a cache to load! run.match('CACHE(coffeescript): Loaded /packages/local-pack/p.coffee'); run.match('CACHE(coffeescript): Loaded /f1.coffee'); run.match('CACHE(coffeescript): Loaded /f3.coffee'); // And we only need to re-compiler the changed file, even though we restarted. run.match('CACHE(coffeescript): Ran (#1) on: ["/f2.coffee"]'); run.match('CACHE(coffeescript): Ran (#2) on: []'); run.match('Coffeescript X is 2 Y is edited FromPackage is 5'); run.stop(); }); // Tests the actual cache logic used by less and stylus. ['less', 'stylus'].forEach((packageName) => { const extension = packageName === 'stylus' ? 'styl' : packageName; selftest.define("compiler plugin caching - " + packageName, () => { var s = new Sandbox({ fakeMongo: true }); s.createApp("myapp", "caching-" + packageName); s.cd("myapp"); // Ask them to print out when they build a file (instead of using it from // the cache) as well as when they load cache from disk. s.set(`METEOR_${ packageName.toUpperCase() }_CACHE_DEBUG`, "t"); var run = startRun(s); const cacheMatch = selftest.markStack((message) => { run.match(`CACHE(${ packageName }): ${ message }`); }); // First program built (web.browser) compiles everything. cacheMatch('Ran (#1) on: ' + JSON.stringify( ["/subdir/nested-root." + extension, "/top." + extension])); // There is no render execution in the server program, because it has // archMatching:'web'. We'll see this more clearly when the next call later // is "#2" --- we didn't miss a call! // App prints this: run.match("Hello world"); // Check that the CSS is what we expect. var checkCSS = selftest.markStack((borderStyleMap) => { var builtBrowserProgramDir = files.pathJoin( s.cwd, '.meteor', 'local', 'build', 'programs', 'web.browser'); var cssFile = _.find( files.readdir( files.pathJoin(s.cwd, '.meteor/local/build/programs/web.browser')), path => path.match(/\.css$/) ); selftest.expectTrue(cssFile); var actual = s.read( files.pathJoin('.meteor/local/build/programs/web.browser', cssFile)); actual = actual.replace(/\s+/g, ' '); // simplify whitespace var expected = _.map(borderStyleMap, (style, className) => { return '.' + className + " { border-style: " + style + "; }"; }).join(' '); selftest.expectEqual(actual, expected); }); var expectedBorderStyles = { el0: "dashed", el1: "dotted", el2: "solid", el3: "groove", el4: "ridge"}; checkCSS(expectedBorderStyles); // Force a rebuild of the local package without actually changing the // preprocessor file in it. This should not require us to render anything. s.append("packages/local-pack/package.js", "\n// foo\n"); cacheMatch('Ran (#2) on: []'); run.match("Hello world"); function setVariable(variableName, value) { switch (packageName) { case 'less': return `@${ variableName }: ${ value };\n`; case 'stylus': return `$${ variableName } = ${ value }\n`; } } function importLine(fileWithoutExtension) { switch (packageName) { case 'less': return `@import "${ fileWithoutExtension }.less";\n`; case 'stylus': return `@import "${ fileWithoutExtension }.styl"\n`; } } // Writing to a single file only re-renders the root that depends on it. s.write('packages/local-pack/p.' + extension, setVariable('el4-style', 'inset')); expectedBorderStyles.el4 = 'inset'; cacheMatch(`Ran (#3) on: ["/top.${ extension }"]`); run.match("Client modified -- refreshing"); checkCSS(expectedBorderStyles); // This works for changing a root too. s.write('subdir/nested-root.' + extension, '.el0 { border-style: double; }\n'); expectedBorderStyles.el0 = 'double'; cacheMatch(`Ran (#4) on: ["/subdir/nested-root.${ extension }"]`); run.match("Client modified -- refreshing"); checkCSS(expectedBorderStyles); // Adding a new root works too. s.write('yet-another-root.' + extension, '.el6 { border-style: solid; }\n'); expectedBorderStyles.el6 = 'solid'; cacheMatch(`Ran (#5) on: ["/yet-another-root.${ extension }"]`); run.match("Client modified -- refreshing"); checkCSS(expectedBorderStyles); // We never should have loaded cache from disk, since we only made // each compiler once and there were no cache files at this point. run.forbid('CACHE(${ packageName }): Loaded'); // Kill the run. Change one file and re-run. run.stop(); s.write('packages/local-pack/p.' + extension, setVariable('el4-style', 'double')); expectedBorderStyles.el4 = 'double'; run = startRun(s); // This time there's a cache to load! Note that for // MultiFileCachingCompiler we load all the cache entries, even for the // not-up-to-date file 'top', because we only key off of filename, not off // of cache key. cacheMatch('Loaded {}/subdir/nested-root.' + extension); cacheMatch('Loaded {}/top.' + extension); cacheMatch('Loaded {}/yet-another-root.' + extension); cacheMatch(`Ran (#1) on: ["/top.${ extension }"]`); run.match('Hello world'); checkCSS(expectedBorderStyles); s.write('bad-import.' + extension, importLine('/foo/bad')); run.match('Errors prevented startup'); switch (packageName) { case 'less': run.match('bad-import.less:1: Unknown import: /foo/bad.less'); break; case 'stylus': run.match('bad-import.styl: Stylus compiler error: bad-import.styl:1'); run.match('failed to locate @import file /foo/bad.styl'); break; } run.match('Waiting for file change'); run.stop(); }); }); // Tests that rebuilding a compiler plugin re-instantiates the source processor, // but other changes don't. selftest.define("compiler plugin caching - local plugin", function () { var s = new Sandbox({ fakeMongo: true }); s.createApp("myapp", "local-compiler-plugin"); s.cd("myapp"); var run = startRun(s); // The compiler gets used the first time... run.match("PrintmeCompiler invocation 1"); // ... and the program runs the generated code. run.match("PMC: Print out bar"); run.match("PMC: Print out foo"); s.write("quux.printme", "And print out quux"); // PrintmeCompiler gets reused. run.match("PrintmeCompiler invocation 2"); // And the right output prints out run.match("PMC: Print out bar"); run.match("PMC: Print out foo"); run.match("PMC: And print out quux"); // Restart meteor; see that the disk cache gets used. run.stop(); run = startRun(s); // Disk cache gets us up to 3. run.match("PrintmeCompiler invocation 3"); // And the right output prints out run.match("PMC: Print out bar"); run.match("PMC: Print out foo"); run.match("PMC: And print out quux"); // Edit the compiler itself. s.write('packages/local-plugin/plugin.js', s.read('packages/local-plugin/plugin.js').replace(/PMC/, 'pmc')); // New PrintmeCompiler object, and empty disk cache dir. run.match("PrintmeCompiler invocation 1"); // And the right output prints out (lower case now) run.match("pmc: Print out bar"); run.match("pmc: Print out foo"); run.match("pmc: And print out quux"); run.stop(); }); // Test error on duplicate compiler plugins. selftest.define("compiler plugins - duplicate extension", () => { const s = new Sandbox({ fakeMongo: true }); s.createApp("myapp", "duplicate-compiler-extensions"); s.cd("myapp"); let run = startRun(s); run.match('Errors prevented startup'); run.match('conflict: two packages'); run.match('trying to handle *.myext'); // Fix it by changing one extension. s.write('packages/local-plugin/plugin.js', s.read('packages/local-plugin/plugin.js').replace('myext', 'xext')); run.match('Modified -- restarting'); run.stop(); }); // Test error when a source file no longer has an active plugin. selftest.define("compiler plugins - inactive source", () => { const s = new Sandbox({ fakeMongo: true }); // This app depends on the published package 'glasser:uses-sourcish', and // contains a local package 'local-plugin'. // // glasser:uses-sourcish depends on local-plugin and contains a file // 'foo.sourcish'. When glasser:[email protected] was published, a local // copy of 'local-plugin' had a plugin which called registerCompiler for the // extension '*.sourcish', and so 'foo.sourcish' is in the published isopack // as a source file. However, the copy of 'local-plugin' currently in the test // app contains no plugins. So we hit this weird error. s.createApp('myapp', 'uses-published-package-with-inactive-source'); s.cd('myapp'); let run = startRun(s); run.match('Errors prevented startup'); run.match('no plugin found for foo.sourcish in glasser:use-sourcish'); run.match('none is now'); run.stop(); }); // Test error when the registerCompiler callback throws. selftest.define("compiler plugins - compiler throws", () => { const s = new Sandbox({ fakeMongo: true }); s.createApp('myapp', 'compiler-plugin-throws-on-instantiate'); s.cd('myapp'); const run = s.run('add', 'local-plugin'); run.matchErr('Errors while adding packages'); run.matchErr( 'While running registerCompiler callback in package local-plugin'); // XXX This is wrong! The path on disk is packages/local-plugin/plugin.js, but // at some point we switched to the servePath which is based on the *plugin*'s // "package" name. run.matchErr('packages/compilePrintme/plugin.js:5:1: Error in my ' + 'registerCompiler callback!'); run.expectExit(1); }); // Test that compiler plugins can add static assets. Also tests `filenames` // option to registerCompiler. selftest.define("compiler plugins - compiler addAsset", () => { const s = new Sandbox({ fakeMongo: true }); s.createApp('myapp', 'compiler-plugin-add-asset'); s.cd('myapp'); const run = startRun(s); // Test server-side asset. run.match("extension is null"); // test getExtension -> null run.match("Asset says Print out foo"); // Test client-side asset. const body = getUrl('http://localhost:3000/foo.printme'); selftest.expectEqual(body, 'Print out foo\n'); run.stop(); });
mit
faraazkhan/kops
vendor/github.com/aws/aws-sdk-go/service/devicefarm/service.go
3154
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. package devicefarm import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) // AWS Device Farm is a service that enables mobile app developers to test Android, // iOS, and Fire OS apps on physical phones, tablets, and other devices in the // cloud. // The service client's operations are safe to be used concurrently. // It is not safe to mutate any of the client's properties though. // Please also see https://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23 type DeviceFarm struct { *client.Client } // Used for custom client initialization logic var initClient func(*client.Client) // Used for custom request initialization logic var initRequest func(*request.Request) // Service information constants const ( ServiceName = "devicefarm" // Service endpoint prefix API calls made to. EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. ) // New creates a new instance of the DeviceFarm client with a session. // If additional configuration is needed for the client instance use the optional // aws.Config parameter to add your extra config. // // Example: // // Create a DeviceFarm client from just a session. // svc := devicefarm.New(mySession) // // // Create a DeviceFarm client with additional configuration // svc := devicefarm.New(mySession, aws.NewConfig().WithRegion("us-west-2")) func New(p client.ConfigProvider, cfgs ...*aws.Config) *DeviceFarm { c := p.ClientConfig(EndpointsID, cfgs...) return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) } // newClient creates, initializes and returns a new service client instance. func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *DeviceFarm { svc := &DeviceFarm{ Client: client.New( cfg, metadata.ClientInfo{ ServiceName: ServiceName, SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint, APIVersion: "2015-06-23", JSONVersion: "1.1", TargetPrefix: "DeviceFarm_20150623", }, handlers, ), } // Handlers svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) // Run custom client initialization if present if initClient != nil { initClient(svc.Client) } return svc } // newRequest creates a new request for a DeviceFarm operation and runs any // custom request initialization. func (c *DeviceFarm) newRequest(op *request.Operation, params, data interface{}) *request.Request { req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
apache-2.0
evocateur/npm
lib/install/realize-shrinkwrap-specifier.js
661
'use strict' var realizePackageSpecifier = require('realize-package-specifier') var isRegistrySpecifier = require('./is-registry-specifier.js') module.exports = function (name, sw, where, cb) { function lookup (ver, cb) { realizePackageSpecifier(name + '@' + ver, where, cb) } if (sw.resolved) { return lookup(sw.resolved, cb) } else if (sw.from) { return lookup(sw.from, function (err, spec) { if (err || isRegistrySpecifier(spec)) { return thenUseVersion() } else { return cb(null, spec) } }) } else { return thenUseVersion() } function thenUseVersion () { lookup(sw.version, cb) } }
artistic-2.0
TaurusTiger/binnavi
src/main/java/com/google/security/zynamics/binnavi/Gui/Debug/ToolbarPanel/Actions/CHaltAction.java
2269
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.security.zynamics.binnavi.Gui.Debug.ToolbarPanel.Actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.Gui.Debug.ToolbarPanel.Implementations.CDebuggerFunctions; import com.google.security.zynamics.binnavi.Gui.GraphWindows.Panels.IFrontEndDebuggerProvider; import com.google.security.zynamics.binnavi.debug.debugger.interfaces.IDebugger; /** * This action class can be used to halt the target process. */ public final class CHaltAction extends AbstractAction { /** * Used for serialization. */ private static final long serialVersionUID = -2514000165001424956L; /** * Parent window used for dialogs. */ private final JFrame m_parent; /** * Debugger that halts the target process. */ private final IFrontEndDebuggerProvider m_debugger; /** * Creates a new halt action. * * @param parent Parent window used for dialogs. * @param debugger Debugger that halts the target process. */ public CHaltAction(final JFrame parent, final IFrontEndDebuggerProvider debugger) { m_parent = Preconditions.checkNotNull(parent, "IE00296: Parent argument can not be null"); m_debugger = Preconditions.checkNotNull(debugger, "IE01534: Debugger argument can not be null"); putValue(Action.SHORT_DESCRIPTION, "Halt"); } @Override public void actionPerformed(final ActionEvent event) { final IDebugger debugger = m_debugger.getCurrentSelectedDebugger(); if (debugger != null) { CDebuggerFunctions.halt(m_parent, debugger); } } }
apache-2.0