code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
2
1.05M
//--------------------------------------------------------------------- // <copyright file="CustomizeNamingTest.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.Test.OData.Tests.Client.CodeGenerationTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Microsoft.OData.Core; using Microsoft.OData.Edm; using Microsoft.Spatial; using Microsoft.Test.OData.Services.TestServices; using Microsoft.Test.OData.Services.TestServices.ODataWCFServiceReferencePlus; using Microsoft.Test.OData.Tests.Client.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using ODataClient = Microsoft.OData.Client; /// <summary> /// T4 code generation for operations test cases. /// </summary> [TestClass] public class CustomizeNamingTest : ODataWCFServiceTestsBase<Microsoft.Test.OData.Services.TestServices.ODataWCFServiceReferencePlus.InMemoryEntitiesPlus> { private const string ServerSideNameSpacePrefix = "Microsoft.Test.OData.Services.ODataWCFService."; public CustomizeNamingTest() : base(ServiceDescriptors.ODataWCFServiceDescriptor) { } [TestMethod] public void BasicQuery() { TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges; // Query a entity set var products1 = TestClientContext.ProductsPlus.ToList(); Assert.AreEqual(5, products1.Count); // Query with expand (Linq) var products2 = TestClientContext.ProductsPlus.Expand(p => p.DetailsPlus).ToList(); Assert.AreEqual(5, products2.Single(p => p.ProductIDPlus == 5).DetailsPlus.Count); // Query with expand (PropertyName) var products3 = TestClientContext.ProductsPlus.Expand("Details").ToList(); Assert.AreEqual(5, products3.Single(p => p.ProductIDPlus == 5).DetailsPlus.Count); // Query a individual primitive property var product4 = TestClientContext.ProductsPlus.Where(p => p.ProductIDPlus == 5).Single(); Assert.AreEqual("Cheetos", product4.NamePlus); // Query an Navigation Property TestClientContext.LoadProperty(product4, "Details"); Assert.AreEqual(5, product4.DetailsPlus.Count); // Query a Derived entity. var people5 = TestClientContext.PeoplePlus.Where(p => p.PersonIDPlus == 1).Single(); // Check the property from the derived type. Assert.AreEqual("Tokyo", people5.HomeAddressPlus.CityPlus); // Check the derived complex property. Assert.AreEqual("Cats", ((HomeAddressPlus)(people5.HomeAddressPlus)).FamilyNamePlus); // Check collection of PrimitiveTypes Assert.AreEqual(1, people5.EmailsPlus.Count); // Query with $select & $expand var accounts6 = TestClientContext.AccountsPlus .Where(a => a.AccountIDPlus == 103) .Select(a => new AccountPlus() { AccountIDPlus = a.AccountIDPlus, MyGiftCardPlus = a.MyGiftCardPlus, CountryRegionPlus = a.CountryRegionPlus }); var account6 = accounts6.Single(); Assert.IsNotNull(account6.MyGiftCardPlus); Assert.AreEqual(103, account6.AccountIDPlus); Assert.IsNull(account6.AccountInfoPlus); // Query with $filter by non-key property. var accounts7 = TestClientContext.AccountsPlus.Where(a => a.CountryRegionPlus == "CN").ToList(); Assert.AreEqual(3, accounts7.Count); // Query with OrderBy var people8 = TestClientContext.PeoplePlus.OrderBy((p) => p.LastNamePlus).First(); Assert.AreEqual(5, people8.PersonIDPlus); // Query with $count var count = TestClientContext.AccountsPlus.Count(); Assert.AreEqual(count, 7); // Query with MultiKeys var productReview10 = TestClientContext.ProductReviewsPlus.Where(pd => pd.ProductDetailIDPlus == 2 && pd.ProductIDPlus == 5 && pd.ReviewTitlePlus == "Special" && pd.RevisionIDPlus == 1).First(); Assert.AreEqual("Andy", productReview10.AuthorPlus); } [TestMethod] public void BasicModify() { TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges; TestClientContext.IgnoreMissingProperties = true; // AddRelatedObject AccountPlus newAccount1 = new AccountPlus() { AccountIDPlus = 110, CountryRegionPlus = "CN", AccountInfoPlus = new AccountInfoPlus() { FirstNamePlus = "New", LastNamePlus = "Boy" } }; PaymentInstrumentPlus newPI = new PaymentInstrumentPlus() { PaymentInstrumentIDPlus = 110901, FriendlyNamePlus = "110's first PI", CreatedDatePlus = new DateTimeOffset(new DateTime(2012, 12, 10)) }; TestClientContext.AddToAccountsPlus(newAccount1); TestClientContext.AddRelatedObject(newAccount1, "MyPaymentInstruments", newPI); TestClientContext.SaveChanges(); var r1 = TestClientContext.AccountsPlus.Where(account => account.AccountIDPlus == 110).Single(); Assert.AreEqual("Boy", r1.AccountInfoPlus.LastNamePlus); var r2 = TestClientContext.CreateQuery<PaymentInstrumentPlus>("Accounts(110)/MyPaymentInstruments") .Where(pi => pi.PaymentInstrumentIDPlus == 110901).Single(); Assert.AreEqual("110's first PI", r2.FriendlyNamePlus); //UpdateObject newAccount1.CountryRegionPlus = "US"; TestClientContext.UpdateObject(newAccount1); TestClientContext.SaveChanges(); r1 = TestClientContext.AccountsPlus.Where(account => account.AccountIDPlus == 110).Single(); Assert.AreEqual("US", r1.CountryRegionPlus); //UpdateRelatedObject var myGiftCard = new GiftCardPlus() { GiftCardIDPlus = 11111, GiftCardNOPlus = "11111", AmountPlus = 20, ExperationDatePlus = new DateTimeOffset(2015, 12, 1, 0, 0, 0, new TimeSpan(0)) }; TestClientContext.UpdateRelatedObject(newAccount1, "MyGiftCard", myGiftCard); TestClientContext.SaveChanges(); r1 = TestClientContext.AccountsPlus.Expand(account => account.MyGiftCardPlus).Where(account => account.AccountIDPlus == 110).Single(); Assert.AreEqual(11111, r1.MyGiftCardPlus.GiftCardIDPlus); //Add Derived Object CustomerPlus customerPlus = new CustomerPlus() { FirstNamePlus = "Nelson", MiddleNamePlus = "S.", LastNamePlus = "Black", NumbersPlus = new ObservableCollection<string> { "111-111-1111" }, EmailsPlus = new ObservableCollection<string> { "abc@abc.com" }, PersonIDPlus = 10001, BirthdayPlus = new DateTimeOffset(new DateTime(1957, 4, 3)), CityPlus = "London", HomePlus = GeographyPoint.Create(32.1, 23.1), TimeBetweenLastTwoOrdersPlus = new TimeSpan(1), HomeAddressPlus = new HomeAddressPlus() { CityPlus = "London", PostalCodePlus = "98052", StreetPlus = "1 Microsoft Way", FamilyNamePlus = "Black's Family" }, }; var ordersPlus = new ODataClient.DataServiceCollection<OrderPlus>(TestClientContext) { new OrderPlus() { OrderIDPlus = 11111111, OrderDatePlus = new DateTimeOffset(new DateTime(2011, 5, 29, 14, 21, 12)), ShelfLifePlus = new TimeSpan(1), OrderShelfLifesPlus = new ObservableCollection<TimeSpan>(){new TimeSpan(1)} } }; TestClientContext.AddToPeoplePlus(customerPlus); TestClientContext.SaveChanges(); var customer1 = TestClientContext.CustomersPlus.Where(c => c.PersonIDPlus == 10001).Single(); TestClientContext.AddLink(customer1, "Orders", ordersPlus[0]); TestClientContext.SaveChanges(); TestClientContext.Detach(customerPlus); TestClientContext.SaveChanges(); var customer = TestClientContext.CustomersPlus.Expand(p => (p as CustomerPlus).OrdersPlus).Where(p => p.PersonIDPlus == 10001).SingleOrDefault(); Assert.AreEqual(((CustomerPlus)customer).CityPlus, "London"); Assert.AreEqual(((HomeAddressPlus)(customer.HomeAddressPlus)).FamilyNamePlus, "Black's Family"); Assert.AreEqual(((CustomerPlus)customer).OrdersPlus.Count, 1); var order = TestClientContext.OrdersPlus.Where(p => p.OrderIDPlus == 11111111).SingleOrDefault(); Assert.AreEqual(order.OrderShelfLifesPlus.Count, 1); // DeleteObject TestClientContext.DeleteObject(newAccount1); TestClientContext.SaveChanges(); var accounts = TestClientContext.AccountsPlus.ToList(); Assert.IsTrue(!accounts.Any(ac => ac.AccountIDPlus == 110)); // SetLink var person1 = TestClientContext.PeoplePlus.Where((p) => p.PersonIDPlus == 1).Single(); var person2 = TestClientContext.PeoplePlus.Where((p) => p.PersonIDPlus == 2).Single(); TestClientContext.SetLink(person1, "Parent", person2); TestClientContext.SaveChanges(); person1 = TestClientContext.PeoplePlus.Expand(d => d.ParentPlus).Where((p) => p.PersonIDPlus == 1).Single(); Assert.IsNotNull(person1.ParentPlus); Assert.IsNotNull(person1.ParentPlus.PersonIDPlus == 2); // SetLink : Bug, SetLink to Null will not update the client object. TestClientContext.SetLink(person1, "Parent", null); TestClientContext.SaveChanges(); person1.ParentPlus = null; var person3 = TestClientContext.PeoplePlus.Expand(d => d.ParentPlus).Where((p) => p.PersonIDPlus == 1).Single(); Assert.IsNull(person3.ParentPlus); //AddLink var companyPlus = TestClientContext.CompanyPlus.GetValue(); DepartmentPlus department = new DepartmentPlus() { DepartmentIDPlus = 100001, NamePlus = "ID" + 100001, }; TestClientContext.AddToDepartmentsPlus(department); TestClientContext.AddLink(companyPlus, "Departments", department); TestClientContext.SaveChanges(); TestClientContext.LoadProperty(companyPlus, "Departments"); Assert.IsTrue(companyPlus.DepartmentsPlus.Any(d => d.DepartmentIDPlus == department.DepartmentIDPlus)); //Delete Link TestClientContext.DeleteLink(companyPlus, "Departments", department); TestClientContext.SaveChanges(); TestClientContext.LoadProperty(companyPlus, "Departments"); Assert.IsTrue(!companyPlus.DepartmentsPlus.Any(d => d.DepartmentIDPlus == department.DepartmentIDPlus)); } [TestMethod] public void OpenComplexType() { //Update entity with open complex type AccountPlus account = new AccountPlus() { AccountIDPlus = 1000000, CountryRegionPlus = "CN", AccountInfoPlus = new AccountInfoPlus() { FirstNamePlus = "Peter", MiddleNamePlus = "White", LastNamePlus = "Andy", IsActivePlus = true } }; TestClientContext.AddToAccountsPlus(account); TestClientContext.SaveChanges(); //Check account can be correctly desirialized. account = TestClientContext.AccountsPlus.Where(a => a.AccountIDPlus == 1000000).Single(); Assert.IsNotNull(account); Assert.AreEqual(account.AccountInfoPlus.MiddleNamePlus, "White"); Assert.IsTrue(account.AccountInfoPlus.IsActivePlus); //Update entity with open complex type var entry = new ODataEntry() { TypeName = ServerSideNameSpacePrefix + "Account" }; entry.Properties = new[] { new ODataProperty { Name = "AccountID", Value = 1000000 }, new ODataProperty { Name = "AccountInfo", Value = new ODataComplexValue { TypeName = ServerSideNameSpacePrefix + "AccountInfo", Properties = new[] { new ODataProperty { Name = "FirstName", Value = "Peter" }, new ODataProperty { Name = "LastName", Value = "Andy" }, //Property that exists in Customer-Defined client code. new ODataProperty { Name = "MiddleName", Value = "White2" }, new ODataProperty { Name = "IsActive", Value = false, }, //Property that doesn't exist in Customer-Defined client code. new ODataProperty { Name = "ShippingAddress", Value = "#999, ZiXing Road" } } } } }; var settings = new ODataMessageWriterSettings(); settings.PayloadBaseUri = ServiceBaseUri; var accountType = Model.FindDeclaredType(ServerSideNameSpacePrefix + "Account") as IEdmEntityType; var accountSet = Model.EntityContainer.FindEntitySet("Accounts"); var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + "Accounts(1000000)")); requestMessage.SetHeader("Content-Type", MimeTypes.ApplicationJson); requestMessage.SetHeader("Accept", MimeTypes.ApplicationJson); requestMessage.Method = "PATCH"; using (var messageWriter = new ODataMessageWriter(requestMessage, settings)) { var odataWriter = messageWriter.CreateODataEntryWriter(accountSet, accountType); odataWriter.WriteStart(entry); odataWriter.WriteEnd(); } var responseMessage = requestMessage.GetResponse(); TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges; //Check account can be correctly desirialized. account = TestClientContext.AccountsPlus.Where(a => a.AccountIDPlus == 1000000).Single(); Assert.IsNotNull(account); Assert.AreEqual(account.AccountInfoPlus.MiddleNamePlus, "White2"); Assert.IsTrue(!account.AccountInfoPlus.IsActivePlus); } [TestMethod] public void OpenEntityType() { //UpdateOpenTypeSingleton var entry = new ODataEntry() { TypeName = ServerSideNameSpacePrefix + "PublicCompany" }; entry.Properties = new[] { new ODataProperty { Name = "FullName", Value = "MS Ltd." }, new ODataProperty { Name = "PhoneNumber", Value = "123-45678" }, new ODataProperty { Name = "TotalAssets", Value = 500000L, } }; var settings = new ODataMessageWriterSettings(); settings.PayloadBaseUri = ServiceBaseUri; settings.AutoComputePayloadMetadataInJson = true; var companyType = Model.FindDeclaredType(ServerSideNameSpacePrefix + "PublicCompany") as IEdmEntityType; var companySingleton = Model.EntityContainer.FindSingleton("PublicCompany"); var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + "PublicCompany")); requestMessage.SetHeader("Content-Type", MimeTypes.ApplicationJson); requestMessage.SetHeader("Accept", MimeTypes.ApplicationJson); requestMessage.Method = "PATCH"; using (var messageWriter = new ODataMessageWriter(requestMessage, settings)) { var odataWriter = messageWriter.CreateODataEntryWriter(companySingleton, companyType); odataWriter.WriteStart(entry); odataWriter.WriteEnd(); } var responseMessage = requestMessage.GetResponse(); Assert.AreEqual(204, responseMessage.StatusCode); //Check account can be correctly desirialized. var company = TestClientContext.PublicCompanyPlus.GetValue(); Assert.IsNotNull(company); Assert.AreEqual("MS Ltd.", company.FullNamePlus); Assert.AreEqual(500000, company.TotalAssetsPlus); TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges; company.FullNamePlus = "MS2 Ltd."; company.TotalAssetsPlus = 1000000; TestClientContext.UpdateObject(company); TestClientContext.SaveChanges(); company.FullNamePlus = null; company.TotalAssetsPlus = 0; company = TestClientContext.PublicCompanyPlus.GetValue(); Assert.IsNotNull(company); Assert.AreEqual("MS2 Ltd.", company.FullNamePlus); Assert.AreEqual(1000000, company.TotalAssetsPlus); } [TestMethod] public void InvokeOperations() { TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges; // Invoke Unbounded Action var color1 = TestClientContext.GetDefaultColorPlus().GetValue(); Assert.AreEqual(color1, ColorPlus.RedPlus); // Invoke Bounded Function on single entity var account = TestClientContext.AccountsPlus.Where(a => a.AccountIDPlus == 101).Single(); var r2 = account.GetDefaultPIPlus().GetValue(); Assert.AreEqual(101901, r2.PaymentInstrumentIDPlus); // Invoke bounded Function on Navigation Property var account3 = TestClientContext.AccountsPlus.Expand(c => c.MyGiftCardPlus).Where(a => a.AccountIDPlus == 101).Single(); var result3 = account3.MyGiftCardPlus.GetActualAmountPlus(1).GetValue(); Assert.AreEqual(39.8, result3); // Invoke bounded Action on single entity set var product4 = TestClientContext.ProductsPlus.Where(p => p.ProductIDPlus == 7).Single(); var result = product4.AddAccessRightPlus(AccessLevelPlus.WritePlus).GetValue(); Assert.AreEqual(AccessLevelPlus.ReadWritePlus, result); // Invoke bounded Action on Navigation Property var account5 = TestClientContext.AccountsPlus.Where(ac => ac.AccountIDPlus == 101).Single(); var result5 = account5.RefreshDefaultPIPlus(DateTimeOffset.Now).GetValue(); Assert.AreEqual(101901, result5.PaymentInstrumentIDPlus); } [TestMethod] public void ContainedEntityQuery() { TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges; // Query a single contained entity var q1 = TestClientContext.CreateQuery<PaymentInstrumentPlus>("Accounts(103)/MyPaymentInstruments(103902)"); Assert.IsTrue(q1.RequestUri.OriginalString.EndsWith("Accounts(103)/MyPaymentInstruments(103902)", StringComparison.Ordinal)); List<PaymentInstrumentPlus> r1 = q1.ToList(); Assert.AreEqual(1, r1.Count); Assert.AreEqual(103902, r1[0].PaymentInstrumentIDPlus); Assert.AreEqual("103 second PI", r1[0].FriendlyNamePlus); // Query a contained entity set with query option var q2 = TestClientContext.CreateQuery<PaymentInstrumentPlus>("Accounts(103)/MyPaymentInstruments").Expand(pi => pi.BillingStatementsPlus).Where(pi => pi.PaymentInstrumentIDPlus == 103901); PaymentInstrumentPlus r2 = q2.Single(); Assert.IsNotNull(r2.BillingStatementsPlus); // Invoke a bounded Function. double result = TestClientContext.Execute<double>(new Uri(ServiceBaseUri.AbsoluteUri + "Accounts(101)/MyGiftCard/Microsoft.Test.OData.Services.ODataWCFService.GetActualAmount(bonusRate=0.2)", UriKind.Absolute), "GET", true).Single(); Assert.AreEqual(23.88, result); } [TestMethod] public void SingltonQuery() { TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges; // Invoke a bounded Function var company1 = TestClientContext.CompanyPlus.GetValue(); var result1 = company1.GetEmployeesCountPlus().GetValue(); Assert.AreEqual(2, result1); // Invoke a bounded Action var company2 = TestClientContext.CompanyPlus.GetValue(); var result2 = company2.IncreaseRevenuePlus(1).GetValue(); Assert.AreEqual(100001, result2); // Invoke a bounded Action on derived type TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges; var publicCompany = TestClientContext.PublicCompanyPlus.GetValue(); var originalRevenue = publicCompany.RevenuePlus; var revenue = publicCompany.IncreaseRevenuePlus(10).GetValue(); Assert.IsTrue(originalRevenue + 10 == revenue); publicCompany = TestClientContext.PublicCompanyPlus.GetValue(); Assert.IsTrue(revenue == publicCompany.RevenuePlus); // Invoke Unbound Action TestClientContext.ResetBossAddressPlus( new HomeAddressPlus() { CityPlus = "Shanghai", StreetPlus = "ZiXing Road", PostalCodePlus = "200100", FamilyNamePlus = "White's Family" }).GetValue(); TestClientContext.SaveChanges(); var boss = TestClientContext.BossPlus.GetValue(); Assert.AreEqual(boss.HomeAddressPlus.PostalCodePlus, "200100"); Assert.AreEqual(((HomeAddressPlus)boss.HomeAddressPlus).FamilyNamePlus, "White's Family"); } } }
abkmr/odata.net
test/EndToEndTests/Tests/Client/Build.Desktop/CodeGenerationTests/CustomizeNamingTest.cs
C#
mit
24,396
#ifndef NUMEXPR_OBJECT_HPP #define NUMEXPR_OBJECT_HPP /********************************************************************* Numexpr - Fast numerical array expression evaluator for NumPy. License: MIT Author: See AUTHORS.txt See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ struct NumExprObject { PyObject_HEAD PyObject *signature; /* a python string */ PyObject *tempsig; PyObject *constsig; PyObject *fullsig; PyObject *program; /* a python string */ PyObject *constants; /* a tuple of int/float/complex */ PyObject *input_names; /* tuple of strings */ char **mem; /* pointers to registers */ char *rawmem; /* a chunks of raw memory for storing registers */ npy_intp *memsteps; npy_intp *memsizes; int rawmemsize; int n_inputs; int n_constants; int n_temps; }; extern PyTypeObject NumExprType; #endif // NUMEXPR_OBJECT_HPP
Alwnikrotikz/numexpr
numexpr/numexpr_object.hpp
C++
mit
1,069
var kunstmaanbundles = kunstmaanbundles || {}; kunstmaanbundles.datepicker = (function($, window, undefined) { var init, reInit, _setDefaultDate, _initDatepicker; var _today = window.moment(), _tomorrow = window.moment(_today).add(1, 'days'); var defaultFormat = 'DD-MM-YYYY', defaultCollapse = true, defaultKeepOpen = false, defaultMinDate = false, defaultShowDefaultDate = false, defaultStepping = 1; init = function() { $('.js-datepicker').each(function() { _initDatepicker($(this)); }); }; reInit = function(el) { if (el) { _initDatepicker($(el)); } else { $('.js-datepicker').each(function() { if (!$(this).hasClass('datepicker--enabled')) { _initDatepicker($(this)); } }); } }; _setDefaultDate = function(elMinDate) { if(elMinDate === 'tomorrow') { return _tomorrow; } else { return _today; } }; _initDatepicker = function($el) { // Get Settings var elFormat = $el.data('format'), elCollapse = $el.data('collapse'), elKeepOpen = $el.data('keep-open'), elMinDate = $el.data('min-date'), elShowDefaultDate = $el.data('default-date'), elStepping = $el.data('stepping'); // Set Settings var format = (elFormat !== undefined) ? elFormat : defaultFormat, collapse = (elCollapse !== undefined) ? elCollapse : defaultCollapse, keepOpen = (elKeepOpen !== undefined) ? elKeepOpen : defaultKeepOpen, minDate = (elMinDate === 'tomorrow') ? _tomorrow : (elMinDate === 'today') ? _today : defaultMinDate, defaultDate = (elShowDefaultDate) ? _setDefaultDate(elMinDate) : defaultShowDefaultDate, stepping = (elStepping !== undefined) ? elStepping : defaultStepping; // Setup var $input = $el.find('input'), $addon = $el.find('.input-group-addon'), linkedDatepickerID = $el.data('linked-datepicker') || false; if (format.indexOf('HH:mm') === -1) { // Drop time if not necessary if (minDate) { minDate = minDate.clone().startOf('day'); // clone() because otherwise .startOf() mutates the original moment object } if (defaultDate) { defaultDate = defaultDate.clone().startOf('day'); } } $input.datetimepicker({ format: format, collapse: collapse, keepOpen: keepOpen, minDate: minDate, defaultDate: defaultDate, widgetPositioning: { horizontal: 'left', vertical: 'auto' }, widgetParent: $el, icons: { time: 'fa fa-clock', date: 'fa fa-calendar', up: 'fa fa-chevron-up', down: 'fa fa-chevron-down', previous: 'fa fa-arrow-left', next: 'fa fa-arrow-right', today: 'fa fa-crosshairs', clear: 'fa fa-trash' }, stepping: stepping }); $el.addClass('datepicker--enabled'); $addon.on('click', function() { $input.focus(); }); // Linked datepickers - allow future datetime only - (un)publish modal if (linkedDatepickerID) { // set min time only if selected date = today $(document).on('dp.change', linkedDatepickerID, function(e) { if (e.target.value === _today.format('DD-MM-YYYY')) { var selectedTime = window.moment($input.val(), 'HH:mm'); // Force user to select new time, if current time isn't valid anymore selectedTime.isBefore(_today) && $input.data('DateTimePicker').show(); $input.data('DateTimePicker').minDate(_today); } else { $input.data('DateTimePicker').minDate(false); } }); } }; return { init: init, reInit: reInit }; })(jQuery, window);
mwoynarski/KunstmaanBundlesCMS
src/Kunstmaan/AdminBundle/Resources/ui/js/_datepicker.js
JavaScript
mit
4,312
// { dg-do compile { target c++11 } } #include "../abi/mangle55.C"
Gurgel100/gcc
gcc/testsuite/g++.dg/analyzer/pr93899.C
C++
gpl-2.0
67
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for AD_WF_Responsible * @author Adempiere (generated) * @version Release 3.8.0 */ public interface I_AD_WF_Responsible { /** TableName=AD_WF_Responsible */ public static final String Table_Name = "AD_WF_Responsible"; /** AD_Table_ID=646 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 6 - System - Client */ BigDecimal accessLevel = BigDecimal.valueOf(6); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Role_ID */ public static final String COLUMNNAME_AD_Role_ID = "AD_Role_ID"; /** Set Role. * Responsibility Role */ public void setAD_Role_ID (int AD_Role_ID); /** Get Role. * Responsibility Role */ public int getAD_Role_ID(); public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException; /** Column name AD_User_ID */ public static final String COLUMNNAME_AD_User_ID = "AD_User_ID"; /** Set User/Contact. * User within the system - Internal or Business Partner Contact */ public void setAD_User_ID (int AD_User_ID); /** Get User/Contact. * User within the system - Internal or Business Partner Contact */ public int getAD_User_ID(); public org.compiere.model.I_AD_User getAD_User() throws RuntimeException; /** Column name AD_WF_Responsible_ID */ public static final String COLUMNNAME_AD_WF_Responsible_ID = "AD_WF_Responsible_ID"; /** Set Workflow Responsible. * Responsible for Workflow Execution */ public void setAD_WF_Responsible_ID (int AD_WF_Responsible_ID); /** Get Workflow Responsible. * Responsible for Workflow Execution */ public int getAD_WF_Responsible_ID(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name EntityType */ public static final String COLUMNNAME_EntityType = "EntityType"; /** Set Entity Type. * Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType); /** Get Entity Type. * Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name ResponsibleType */ public static final String COLUMNNAME_ResponsibleType = "ResponsibleType"; /** Set Responsible Type. * Type of the Responsibility for a workflow */ public void setResponsibleType (String ResponsibleType); /** Get Responsible Type. * Type of the Responsibility for a workflow */ public String getResponsibleType(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); }
armenrz/adempiere
base/src/org/compiere/model/I_AD_WF_Responsible.java
Java
gpl-2.0
6,101
####################################################################### # # Author: Malte Helmert (helmert@informatik.uni-freiburg.de) # (C) Copyright 2003-2004 Malte Helmert # # This file is part of LAMA. # # LAMA 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. # # LAMA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. # ####################################################################### import cStringIO import textwrap __all__ = ["print_nested_list"] def tokenize_list(obj): if isinstance(obj, list): yield "(" for item in obj: for elem in tokenize_list(item): yield elem yield ")" else: yield obj def wrap_lines(lines): for line in lines: indent = " " * (len(line) - len(line.lstrip()) + 4) line = line.replace("-", "_") # textwrap breaks on "-", but not "_" line = textwrap.fill(line, subsequent_indent=indent, break_long_words=False) yield line.replace("_", "-") def print_nested_list(nested_list): stream = cStringIO.StringIO() indent = 0 startofline = True pendingspace = False for token in tokenize_list(nested_list): if token == "(": if not startofline: stream.write("\n") stream.write("%s(" % (" " * indent)) indent += 2 startofline = False pendingspace = False elif token == ")": indent -= 2 stream.write(")") startofline = False pendingspace = False else: if startofline: stream.write(" " * indent) if pendingspace: stream.write(" ") stream.write(token) startofline = False pendingspace = True for line in wrap_lines(stream.getvalue().splitlines()): print line
PlanTool/plantool
wrappingPlanners/Deterministic/LAMA/seq-sat-lama/lama/translate/pddl/pretty_print.py
Python
gpl-2.0
2,178
<?php namespace Drupal\KernelTests\Core\Extension; use Drupal\KernelTests\KernelTestBase; /** * @coversDefaultClass \Drupal\Core\Extension\ThemeExtensionList * @group Extension */ class ThemeExtensionListTest extends KernelTestBase { /** * @covers ::getList */ public function testGetlist() { \Drupal::configFactory()->getEditable('core.extension') ->set('module.testing', 1000) ->set('theme.test_theme', 0) ->save(); // The installation profile is provided by a container parameter. // Saving the configuration doesn't automatically trigger invalidation $this->container->get('kernel')->rebuildContainer(); /** @var \Drupal\Core\Extension\ThemeExtensionList $theme_extension_list */ $theme_extension_list = \Drupal::service('extension.list.theme'); $extensions = $theme_extension_list->getList(); $this->assertArrayHasKey('test_theme', $extensions); } /** * Tests that themes have an empty default version set. */ public function testThemeWithoutVersion() { $theme = \Drupal::service('extension.list.theme')->get('test_theme_settings_features'); $this->assertNull($theme->info['version']); } }
tobiasbuhrer/tobiasb
web/core/tests/Drupal/KernelTests/Core/Extension/ThemeExtensionListTest.php
PHP
gpl-2.0
1,189
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): objs = orm.ProjectApplication.objects apps = objs.filter(chain__chained_project=None).order_by( 'chain', '-id') checked_chain = None projs = [] for app in apps: chain = app.chain if chain.pk != checked_chain: checked_chain = chain.pk projs.append(orm.Project(id=chain, application=app, state=1)) orm.Project.objects.bulk_create(projs) def backwards(self, orm): "Write your backwards methods here." models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'im.additionalmail': { 'Meta': {'object_name': 'AdditionalMail'}, 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"}) }, 'im.approvalterms': { 'Meta': {'object_name': 'ApprovalTerms'}, 'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'im.astakosuser': { 'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']}, 'accepted_email': ('django.db.models.fields.EmailField', [], {'default': 'None', 'max_length': '75', 'null': 'True', 'blank': 'True'}), 'accepted_policy': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'activation_sent': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'deactivated_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'deactivated_reason': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True'}), 'disturbed_quota': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True', 'blank': 'True'}), 'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'invitations': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'is_rejected': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'level': ('django.db.models.fields.IntegerField', [], {'default': '4'}), 'moderated': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'moderated_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'moderated_data': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'policy': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['im.Resource']", 'null': 'True', 'through': "orm['im.AstakosUserQuota']", 'symmetrical': 'False'}), 'rejected_reason': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'updated': ('django.db.models.fields.DateTimeField', [], {}), 'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}), 'uuid': ('django.db.models.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True'}), 'verification_code': ('django.db.models.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True'}), 'verified_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'im.astakosuserauthprovider': { 'Meta': {'unique_together': "(('identifier', 'module', 'user'),)", 'object_name': 'AstakosUserAuthProvider'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'affiliation': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'auth_backend': ('django.db.models.fields.CharField', [], {'default': "'astakos'", 'max_length': '255'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'info_data': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}), 'module': ('django.db.models.fields.CharField', [], {'default': "'local'", 'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'auth_providers'", 'to': "orm['im.AstakosUser']"}) }, 'im.astakosuserquota': { 'Meta': {'unique_together': "(('resource', 'user'),)", 'object_name': 'AstakosUserQuota'}, 'capacity': ('snf_django.lib.db.fields.IntDecimalField', [], {'max_digits': '38', 'decimal_places': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Resource']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"}) }, 'im.authproviderpolicyprofile': { 'Meta': {'object_name': 'AuthProviderPolicyProfile'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'authpolicy_profiles'", 'symmetrical': 'False', 'to': "orm['auth.Group']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_exclusive': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'policy_add': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'policy_automoderate': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'policy_create': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'policy_limit': ('django.db.models.fields.IntegerField', [], {'default': 'None', 'null': 'True'}), 'policy_login': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'policy_remove': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'policy_required': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'policy_switch': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'priority': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'provider': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'authpolicy_profiles'", 'symmetrical': 'False', 'to': "orm['im.AstakosUser']"}) }, 'im.chain': { 'Meta': {'object_name': 'Chain'}, 'chain': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'im.component': { 'Meta': {'object_name': 'Component'}, 'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}), 'url': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True'}) }, 'im.emailchange': { 'Meta': {'object_name': 'EmailChange'}, 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'requested_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'emailchanges'", 'unique': 'True', 'to': "orm['im.AstakosUser']"}) }, 'im.endpoint': { 'Meta': {'object_name': 'Endpoint'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'service': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'endpoints'", 'to': "orm['im.Service']"}) }, 'im.endpointdata': { 'Meta': {'unique_together': "(('endpoint', 'key'),)", 'object_name': 'EndpointData'}, 'endpoint': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'data'", 'to': "orm['im.Endpoint']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '1024'}) }, 'im.invitation': { 'Meta': {'object_name': 'Invitation'}, 'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}), 'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}), 'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, 'im.pendingthirdpartyuser': { 'Meta': {'unique_together': "(('provider', 'third_party_identifier'),)", 'object_name': 'PendingThirdPartyUser'}, 'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'info': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'token': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'im.project': { 'Meta': {'object_name': 'Project'}, 'application': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'project'", 'unique': 'True', 'to': "orm['im.ProjectApplication']"}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'deactivation_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'deactivation_reason': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'chained_project'", 'unique': 'True', 'primary_key': 'True', 'db_column': "'id'", 'to': "orm['im.Chain']"}), 'last_approval_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['im.AstakosUser']", 'through': "orm['im.ProjectMembership']", 'symmetrical': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'unique': 'True', 'null': 'True', 'db_index': 'True'}), 'state': ('django.db.models.fields.IntegerField', [], {'default': '1', 'db_index': 'True'}) }, 'im.projectapplication': { 'Meta': {'unique_together': "(('chain', 'id'),)", 'object_name': 'ProjectApplication'}, 'applicant': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projects_applied'", 'to': "orm['im.AstakosUser']"}), 'chain': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'chained_apps'", 'db_column': "'chain'", 'to': "orm['im.Chain']"}), 'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateTimeField', [], {}), 'homepage': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issue_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'limit_on_members_number': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}), 'member_join_policy': ('django.db.models.fields.IntegerField', [], {}), 'member_leave_policy': ('django.db.models.fields.IntegerField', [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projects_owned'", 'to': "orm['im.AstakosUser']"}), 'precursor_application': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.ProjectApplication']", 'null': 'True', 'blank': 'True'}), 'resource_grants': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['im.Resource']", 'null': 'True', 'through': "orm['im.ProjectResourceGrant']", 'blank': 'True'}), 'response': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'response_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'}) }, 'im.projectmembership': { 'Meta': {'unique_together': "(('person', 'project'),)", 'object_name': 'ProjectMembership'}, 'acceptance_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'leave_request_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Project']"}), 'request_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'}) }, 'im.projectmembershiphistory': { 'Meta': {'object_name': 'ProjectMembershipHistory'}, 'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'person': ('django.db.models.fields.BigIntegerField', [], {}), 'project': ('django.db.models.fields.BigIntegerField', [], {}), 'reason': ('django.db.models.fields.IntegerField', [], {}), 'serial': ('django.db.models.fields.BigIntegerField', [], {}) }, 'im.projectresourcegrant': { 'Meta': {'unique_together': "(('resource', 'project_application'),)", 'object_name': 'ProjectResourceGrant'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'member_capacity': ('snf_django.lib.db.fields.IntDecimalField', [], {'default': '0', 'max_digits': '38', 'decimal_places': '0'}), 'project_application': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.ProjectApplication']", 'null': 'True'}), 'project_capacity': ('snf_django.lib.db.fields.IntDecimalField', [], {'null': 'True', 'max_digits': '38', 'decimal_places': '0'}), 'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Resource']"}) }, 'im.resource': { 'Meta': {'object_name': 'Resource'}, 'allow_in_projects': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'desc': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'service_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'service_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'unit': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'uplimit': ('snf_django.lib.db.fields.IntDecimalField', [], {'default': '0', 'max_digits': '38', 'decimal_places': '0'}) }, 'im.serial': { 'Meta': {'object_name': 'Serial'}, 'serial': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'im.service': { 'Meta': {'object_name': 'Service'}, 'component': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.Component']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'im.sessioncatalog': { 'Meta': {'object_name': 'SessionCatalog'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sessions'", 'null': 'True', 'to': "orm['im.AstakosUser']"}) }, 'im.usersetting': { 'Meta': {'unique_together': "(('user', 'setting'),)", 'object_name': 'UserSetting'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'setting': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"}), 'value': ('django.db.models.fields.IntegerField', [], {}) } } complete_apps = ['im']
grnet/synnefo
snf-astakos-app/astakos/im/migrations/old/0043_uninitialized_projects.py
Python
gpl-3.0
25,194
// ReSharper disable All using System; using System.Diagnostics; using System.Linq; using MixERP.Net.Api.Transactions.Fakes; using MixERP.Net.ApplicationState.Cache; using Xunit; namespace MixERP.Net.Api.Transactions.Tests { public class GetPurchaseTests { public static GetPurchaseController Fixture() { GetPurchaseController controller = new GetPurchaseController(new GetPurchaseRepository(), "", new LoginView()); return controller; } [Fact] [Conditional("Debug")] public void Execute() { var actual = Fixture().Execute(new GetPurchaseController.Annotation()); Assert.Equal(1, actual); } } }
gguruss/mixerp
src/Libraries/Web API/Transactions/Tests/GetPurchaseTests.cs
C#
gpl-3.0
720
using System; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using MixERP.Net.Common; using MixERP.Net.Core.Modules.Sales.Data.Data; using MixERP.Net.DbFactory; using MixERP.Net.Entities.Core; using MixERP.Net.Entities.Transactions.Models; using Npgsql; namespace MixERP.Net.Core.Modules.Sales.Data.Transactions { internal static class GlTransaction { public static long Add(string catalog, string bookName, DateTime valueDate, int officeId, int userId, long loginId, int costCenterId, string referenceNumber, string statementReference, StockMaster stockMaster, Collection<StockDetail> details, Collection<Attachment> attachments, bool nonTaxable, Collection<long> tranIds) { if (stockMaster == null) { return 0; } if (details == null) { return 0; } if (details.Count.Equals(0)) { return 0; } string detail = StockMasterDetailHelper.CreateStockMasterDetailParameter(details); string attachment = AttachmentHelper.CreateAttachmentModelParameter(attachments); string ids = "NULL::bigint"; if (tranIds != null && tranIds.Count > 0) { ids = string.Join(",", tranIds); } string sql = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM transactions.post_sales(@BookName::national character varying(48), @OfficeId::integer, @UserId::integer, @LoginId::bigint, @ValueDate::date, @CostCenterId::integer, @ReferenceNumber::national character varying(24), @StatementReference::text, @IsCredit::boolean, @PaymentTermId::integer, @PartyCode::national character varying(12), @PriceTypeId::integer, @SalespersonId::integer, @ShipperId::integer, @ShippingAddressCode::national character varying(12), @StoreId::integer, @NonTaxable::boolean, ARRAY[{0}], ARRAY[{1}], ARRAY[{2}])", detail, attachment, ids); using (NpgsqlCommand command = new NpgsqlCommand(sql)) { command.Parameters.AddWithValue("@BookName", bookName); command.Parameters.AddWithValue("@OfficeId", officeId); command.Parameters.AddWithValue("@UserId", userId); command.Parameters.AddWithValue("@LoginId", loginId); command.Parameters.AddWithValue("@ValueDate", valueDate); command.Parameters.AddWithValue("@CostCenterId", costCenterId); command.Parameters.AddWithValue("@ReferenceNumber", referenceNumber); command.Parameters.AddWithValue("@StatementReference", statementReference); command.Parameters.AddWithValue("@IsCredit", stockMaster.IsCredit); if (stockMaster.PaymentTermId.Equals(0)) { command.Parameters.AddWithValue("@PaymentTermId", DBNull.Value); } else { command.Parameters.AddWithValue("@PaymentTermId", stockMaster.PaymentTermId); } command.Parameters.AddWithValue("@PartyCode", stockMaster.PartyCode); command.Parameters.AddWithValue("@PriceTypeId", stockMaster.PriceTypeId); command.Parameters.AddWithValue("@SalespersonId", stockMaster.SalespersonId); command.Parameters.AddWithValue("@ShipperId", stockMaster.ShipperId); command.Parameters.AddWithValue("@ShippingAddressCode", stockMaster.ShippingAddressCode); command.Parameters.AddWithValue("@StoreId", stockMaster.StoreId); command.Parameters.AddWithValue("@NonTaxable", nonTaxable); command.Parameters.AddRange(StockMasterDetailHelper.AddStockMasterDetailParameter(details).ToArray()); command.Parameters.AddRange(AttachmentHelper.AddAttachmentParameter(attachments).ToArray()); long tranId = Conversion.TryCastLong(DbOperation.GetScalarValue(catalog, command)); return tranId; } } } }
mixerp/mixerp
src/FrontEnd/Modules/Sales.Data/Transactions/GlTransaction.cs
C#
gpl-3.0
4,220
package org.thoughtcrime.securesms.push; import android.content.Context; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.signalservice.api.SignalServiceAccountManager; public class TextSecureCommunicationFactory { public static SignalServiceAccountManager createManager(Context context) { return new SignalServiceAccountManager(BuildConfig.TEXTSECURE_URL, new TextSecurePushTrustStore(context), TextSecurePreferences.getLocalNumber(context), TextSecurePreferences.getPushServerPassword(context), BuildConfig.USER_AGENT); } public static SignalServiceAccountManager createManager(Context context, String number, String password) { return new SignalServiceAccountManager(BuildConfig.TEXTSECURE_URL, new TextSecurePushTrustStore(context), number, password, BuildConfig.USER_AGENT); } }
IBobko/signal
src/org/thoughtcrime/securesms/push/TextSecureCommunicationFactory.java
Java
gpl-3.0
1,107
<?php return array( 'about_asset_depreciations' => 'Over afschrijving van materiaal', 'about_depreciations' => 'U kan de materiaalafschrijving instellen om materiaal af te schrijven op basis van lineaire afschrijving.', 'asset_depreciations' => 'Materiaalafschrijvingen', 'create' => 'Afschrijving aanmaken', 'depreciation_name' => 'Afschrijvingsnaam', 'number_of_months' => 'Aantal maanden', 'update' => 'Afschrijving bijwerken', );
madd15/snipe-it
resources/lang/nl/admin/depreciations/general.php
PHP
agpl-3.0
528
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.nbio.structure.io.mmcif.model; /** A bean for the PDBX_NONPOLY_SCHEME category, which provides residue level nomenclature * mapping for non-polymer entities. * @author Andreas Prlic * @since 1.7 */ public class PdbxNonPolyScheme { String asym_id; String entity_id; String seq_id; String mon_id; String ndb_seq_num; String pdb_seq_num ; String auth_seq_num ; String pdb_mon_id; String auth_mon_id; String pdb_strand_id; String pdb_ins_code; public String getAsym_id() { return asym_id; } public void setAsym_id(String asym_id) { this.asym_id = asym_id; } public String getEntity_id() { return entity_id; } public void setEntity_id(String entity_id) { this.entity_id = entity_id; } public String getSeq_id() { return seq_id; } public void setSeq_id(String seq_id) { this.seq_id = seq_id; } public String getMon_id() { return mon_id; } public void setMon_id(String mon_id) { this.mon_id = mon_id; } public String getNdb_seq_num() { return ndb_seq_num; } public void setNdb_seq_num(String ndb_seq_num) { this.ndb_seq_num = ndb_seq_num; } public String getPdb_seq_num() { return pdb_seq_num; } public void setPdb_seq_num(String pdb_seq_num) { this.pdb_seq_num = pdb_seq_num; } public String getAuth_seq_num() { return auth_seq_num; } public void setAuth_seq_num(String auth_seq_num) { this.auth_seq_num = auth_seq_num; } public String getPdb_mon_id() { return pdb_mon_id; } public void setPdb_mon_id(String pdb_mon_id) { this.pdb_mon_id = pdb_mon_id; } public String getAuth_mon_id() { return auth_mon_id; } public void setAuth_mon_id(String auth_mon_id) { this.auth_mon_id = auth_mon_id; } public String getPdb_strand_id() { return pdb_strand_id; } public void setPdb_strand_id(String pdb_strand_id) { this.pdb_strand_id = pdb_strand_id; } public String getPdb_ins_code() { return pdb_ins_code; } public void setPdb_ins_code(String pdb_ins_code) { this.pdb_ins_code = pdb_ins_code; } }
fionakim/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/PdbxNonPolyScheme.java
Java
lgpl-2.1
2,607
package health; import com.comcast.cdn.traffic_control.traffic_monitor.config.Cache; import com.comcast.cdn.traffic_control.traffic_monitor.health.CacheStateUpdater; import com.comcast.cdn.traffic_control.traffic_monitor.health.CacheStatisticsClient; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.ListenableFuture; import com.ning.http.client.ProxyServer; import com.ning.http.client.Request; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; @PrepareForTest({CacheStatisticsClient.class, AsyncHttpClient.class, ProxyServer.class}) @RunWith(PowerMockRunner.class) public class CacheStatisticsClientTest { @Test public void itExecutesAsynchronousRequest() throws Exception { ListenableFuture listenableFuture = mock(ListenableFuture.class); AsyncHttpClient asyncHttpClient = spy(new AsyncHttpClient()); doReturn(listenableFuture).when(asyncHttpClient).executeRequest(any(Request.class), any(CacheStateUpdater.class)); whenNew(AsyncHttpClient.class).withNoArguments().thenReturn(asyncHttpClient); Cache cache = mock(Cache.class); when(cache.getQueryIp()).thenReturn("192.168.99.100"); when(cache.getQueryPort()).thenReturn(0); when(cache.getStatisticsUrl()).thenReturn("http://cache1.example.com/astats"); CacheStateUpdater cacheStateUpdater = mock(CacheStateUpdater.class); CacheStatisticsClient cacheStatisticsClient = new CacheStatisticsClient(); cacheStatisticsClient.fetchCacheStatistics(cache, cacheStateUpdater); verify(cacheStateUpdater).setFuture(listenableFuture); } }
dneuman64/traffic_control
traffic_monitor/src/test/java/health/CacheStatisticsClientTest.java
Java
apache-2.0
1,971
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Validation; using System.Diagnostics; using System.Xml; namespace DocumentFormat.OpenXml.Internal.SemanticValidation { internal class RelationshipExistConstraint : SemanticConstraint { private byte _rIdAttribute; public RelationshipExistConstraint(byte rIdAttribute) : base(SemanticValidationLevel.Part) { _rIdAttribute = rIdAttribute; } public override ValidationErrorInfo Validate(ValidationContext context) { OpenXmlSimpleType attributeValue = context.Element.Attributes[_rIdAttribute]; //if the attribute is omited, semantic validation will do nothing if (attributeValue == null || string.IsNullOrEmpty(attributeValue.InnerText)) { return null; } if (context.Part.PackagePart.RelationshipExists(attributeValue.InnerText)) { return null; } else { string errorDescription = string.Format(System.Globalization.CultureInfo.CurrentUICulture, ValidationResources.Sem_InvalidRelationshipId, attributeValue, GetAttributeQualifiedName(context.Element, _rIdAttribute)); return new ValidationErrorInfo() { Id = "Sem_InvalidRelationshipId", ErrorType = ValidationErrorType.Semantic, Node = context.Element, Description = errorDescription }; } } } }
JesseQin/Open-XML-SDK
src/ofapi/Validation/SemanticValidation/SemanticConstraint/RelationshipExistConstraint.cs
C#
apache-2.0
1,905
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH 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 com.graphhopper.jsprit.io.algorithm; import org.apache.commons.configuration.XMLConfiguration; public class AlgorithmConfig { private XMLConfiguration xmlConfig; public AlgorithmConfig() { xmlConfig = new XMLConfiguration(); } public XMLConfiguration getXMLConfiguration() { return xmlConfig; } }
terryturner/VRPinGMapFx
jsprit-master/jsprit-io/src/main/java/com/graphhopper/jsprit/io/algorithm/AlgorithmConfig.java
Java
apache-2.0
1,141
/* * 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.beam.runners.flink.translation.wrappers.streaming.stableinput; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkNotNull; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.flink.api.common.state.ListState; /** A non-keyed implementation of a {@link BufferingElementsHandler}. */ public class NonKeyedBufferingElementsHandler<T> implements BufferingElementsHandler { static <T> NonKeyedBufferingElementsHandler<T> create(ListState<BufferedElement> elementState) { return new NonKeyedBufferingElementsHandler<>(elementState); } private final ListState<BufferedElement> elementState; private NonKeyedBufferingElementsHandler(ListState<BufferedElement> elementState) { this.elementState = checkNotNull(elementState); } @Override public Stream<BufferedElement> getElements() { try { return StreamSupport.stream(elementState.get().spliterator(), false); } catch (Exception e) { throw new RuntimeException("Failed to retrieve buffered element from state backend.", e); } } @Override public void buffer(BufferedElement element) { try { elementState.add(element); } catch (Exception e) { throw new RuntimeException("Failed to buffer element in state backend.", e); } } @Override public void clear() { elementState.clear(); } }
lukecwik/incubator-beam
runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/stableinput/NonKeyedBufferingElementsHandler.java
Java
apache-2.0
2,224
cask "operadriver" do version "96.0.4664.45" sha256 "fe712310d8577056442bf7146cde2b1db69181873ff3cb2311335b784829cac6" url "https://github.com/operasoftware/operachromiumdriver/releases/download/v.#{version}/operadriver_mac64.zip" name "OperaChromiumDriver" desc "Driver for Chromium-based Opera releases" homepage "https://github.com/operasoftware/operachromiumdriver" livecheck do url :url regex(/^v?\.?(\d+(?:\.\d+)+)$/i) end binary "operadriver_mac64/operadriver" end
malob/homebrew-cask
Casks/operadriver.rb
Ruby
bsd-2-clause
501
cask 'arduino' do version '1.8.7' sha256 'bc5fae3e0b54f000d335d93f2e6da66fc8549def015e3b136d34a10e171c1501' url "https://downloads.arduino.cc/arduino-#{version}-macosx.zip" appcast 'https://www.arduino.cc/en/Main/ReleaseNotes' name 'Arduino' homepage 'https://www.arduino.cc/' app 'Arduino.app' binary "#{appdir}/Arduino.app/Contents/Java/arduino-builder" caveats do depends_on_java end end
bosr/homebrew-cask
Casks/arduino.rb
Ruby
bsd-2-clause
418
# Copyright 2019 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. import io import unittest from json5.host import Host class HostTest(unittest.TestCase): maxDiff = None def test_directory_and_file_operations(self): h = Host() orig_cwd = h.getcwd() try: d = h.mkdtemp() h.chdir(d) h.write_text_file('foo', 'bar') contents = h.read_text_file('foo') self.assertEqual(contents, 'bar') h.chdir('..') h.rmtree(d) finally: h.chdir(orig_cwd) def test_print(self): s = io.StringIO() h = Host() h.print_('hello, world', stream=s) self.assertEqual('hello, world\n', s.getvalue()) if __name__ == '__main__': # pragma: no cover unittest.main()
scheib/chromium
third_party/pyjson5/src/tests/host_test.py
Python
bsd-3-clause
1,346
//-------------------------------------------------------------------------- // // Environment: // This software is part of the EvtGen package developed jointly // for the BaBar and CLEO collaborations. If you use all or part // of it, please give an appropriate acknowledgement. // // Copyright Information: See EvtGen/COPYRIGHT // Copyright (C) 1998 Caltech, UCSB // // Module: EvtGen/EvtVector3R.hh // // Description: Class to describe real 3 vectors // // Modification history: // // RYD Sept. 5, 1997 Module created // //------------------------------------------------------------------------ #ifndef EVTVECTOR3R_HH #define EVTVECTOR3R_HH #include <iosfwd> class EvtVector3R { friend EvtVector3R rotateEuler(const EvtVector3R& v, double phi,double theta,double ksi); inline friend EvtVector3R operator*(double c,const EvtVector3R& v2); inline friend double operator*(const EvtVector3R& v1,const EvtVector3R& v2); inline friend EvtVector3R operator+(const EvtVector3R& v1,const EvtVector3R& v2); inline friend EvtVector3R operator-(const EvtVector3R& v1,const EvtVector3R& v2); inline friend EvtVector3R operator*(const EvtVector3R& v1,double c); inline friend EvtVector3R operator/(const EvtVector3R& v1,double c); friend EvtVector3R cross(const EvtVector3R& v1,const EvtVector3R& v2); public: EvtVector3R(); EvtVector3R(double x,double y ,double z); virtual ~EvtVector3R(); inline EvtVector3R& operator*=(const double c); inline EvtVector3R& operator/=(const double c); inline EvtVector3R& operator+=(const EvtVector3R& v2); inline EvtVector3R& operator-=(const EvtVector3R& v2); inline void set(int i,double d); inline void set(double x,double y ,double z); void applyRotateEuler(double phi,double theta,double ksi); inline double get(int i) const; friend std::ostream& operator<<(std::ostream& s,const EvtVector3R& v); double dot(const EvtVector3R& v2); double d3mag() const; private: double v[3]; }; inline EvtVector3R& EvtVector3R::operator*=(const double c){ v[0]*=c; v[1]*=c; v[2]*=c; return *this; } inline EvtVector3R& EvtVector3R::operator/=(const double c){ v[0]/=c; v[1]/=c; v[2]/=c; return *this; } inline EvtVector3R& EvtVector3R::operator+=(const EvtVector3R& v2){ v[0]+=v2.v[0]; v[1]+=v2.v[1]; v[2]+=v2.v[2]; return *this; } inline EvtVector3R& EvtVector3R::operator-=(const EvtVector3R& v2){ v[0]-=v2.v[0]; v[1]-=v2.v[1]; v[2]-=v2.v[2]; return *this; } inline EvtVector3R operator*(double c,const EvtVector3R& v2){ return EvtVector3R(v2)*=c; } inline EvtVector3R operator*(const EvtVector3R& v1,double c){ return EvtVector3R(v1)*=c; } inline EvtVector3R operator/(const EvtVector3R& v1,double c){ return EvtVector3R(v1)/=c; } inline double operator*(const EvtVector3R& v1,const EvtVector3R& v2){ return v1.v[0]*v2.v[0]+v1.v[1]*v2.v[1]+v1.v[2]*v2.v[2]; } inline EvtVector3R operator+(const EvtVector3R& v1,const EvtVector3R& v2) { return EvtVector3R(v1)+=v2; } inline EvtVector3R operator-(const EvtVector3R& v1,const EvtVector3R& v2) { return EvtVector3R(v1)-=v2; } inline double EvtVector3R::get(int i) const { return v[i]; } inline void EvtVector3R::set(int i,double d){ v[i]=d; } inline void EvtVector3R::set(double x,double y, double z){ v[0]=x; v[1]=y; v[2]=z; } #endif
miranov25/AliRoot
TEvtGen/EvtGen/EvtGenBase/EvtVector3R.hh
C++
bsd-3-clause
3,395
//=================================================================================== // // (C) COPYRIGHT International Business Machines Corp., 2002 All Rights Reserved // Licensed Materials - Property of IBM // US Government Users Restricted Rights - Use, duplication or // disclosure restricted by GSA ADP Schedule Contract with IBM Corp. // // IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING // ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR // CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF // USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE // OR PERFORMANCE OF THIS SOFTWARE. // // The program may be used, executed, copied, modified, and distributed // without royalty for the purpose of developing, using, marketing, or distributing. // //======================================================================================= // gSOAP v2 Interop test round 2 base //#include "interoptA.h" #include "soapH.h" extern "C" void displayText(char *text); extern "C" int interopA(const char *url); struct Namespace namespacesA[] = { {"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"}, {"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"}, {"xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance"}, {"xsd", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/*/XMLSchema"}, {"ns", "http://soapinterop.org/"}, {"s", "http://soapinterop.org/xsd"}, {"a", "http://xml.apache.org/xml-soap"}, {"h", "http://soapinterop.org/echoheader/"}, {NULL, NULL} }; int interopA(const char *url) { struct soap *soap; int i, g; xsd__string so, si = "Hello World! <>&"; struct ArrayOfstring Asi, Aso; xsd__int no, ni = 1234567890; xsd__int n = 2147483647; struct ArrayOfint Ani, Ano; // xsd__float f1 = 3.40282e+38; xsd__float f1 = 123.5678; xsd__float f2 = 3.14; xsd__float fo, fi = 123.456; // xsd__float fo, fi = 3e2; //#ifdef SYMBIAN // const struct soap_double_nan { unsigned int n1, n2; } soap_double_nan; //#endif xsd__float nan = FLT_NAN, inf = FLT_PINFTY, ninf = FLT_NINFTY; struct ArrayOffloat Afi, Afo; struct s__SOAPStruct sti, *p; struct ns__echoStructResponse sto; struct ArrayOfSOAPStruct Asti, Asto; struct ns__echoVoidResponse Rv; struct xsd__base64Binary b64i, b64o; xsd__dateTime dto, dti = "1967-12-29T01:02:03"; struct xsd__hexBinary hbi, hbo; xsd__decimal Do, Di = "1234567890.123456789"; xsd__boolean bo, bi = true; //struct a__Map mi, mo; //struct ArrayOfMap Ami, Amo; // char buff[100]; displayText("running test A on"); displayText((char*)url); soap = soap_new(); soap->namespaces = (struct Namespace *)namespacesA; // soap.send_timeout = 30; // soap.recv_timeout = 30; Asi.__size = 8; Asi.__offset = 0; Asi.__ptr = (xsd__string*)malloc(Asi.__size*sizeof(xsd__string)); Asi.__ptr[0] = NULL; Asi.__ptr[1] = " Hello\tWorld"; Asi.__ptr[2] = NULL; Asi.__ptr[3] = "! "; Asi.__ptr[4] = NULL; Asi.__ptr[5] = si; Asi.__ptr[6] = NULL; Asi.__ptr[7] = si; Ani.__size = 0; Ani.__offset = 0; Ani.__ptr = NULL; // (xsd__int*)malloc(Ani.__size*sizeof(xsd__int)); Afi.__size = 5; Afi.__offset = 0; Afi.__ptr = (xsd__float**)malloc(Afi.__size*sizeof(xsd__float*)); Afi.__ptr[0] = &f1; Afi.__ptr[1] = &nan; // FLT_NAN; Afi.__ptr[2] = &inf; // FLT_PINFTY; Afi.__ptr[3] = &ninf; // FLT_NINFTY; Afi.__ptr[4] = &f2; sti.varString = "Hello"; sti.varInt = &n; sti.varFloat = &f1; Asti.__size = 3; Asti.__offset = 2; Asti.__ptr = (struct s__SOAPStruct**)malloc((Asti.__size+1)*sizeof(struct s__SOAPStruct*)); p = (struct s__SOAPStruct*)malloc(Asti.__size*sizeof(struct s__SOAPStruct)); Asti.__ptr[0] = p; Asti.__ptr[1] = p+1; Asti.__ptr[2] = p+2; Asti.__ptr[3] = p; Asti.__ptr[0]->varString = "Hello"; Asti.__ptr[0]->varInt = &n; Asti.__ptr[0]->varFloat = &f1; Asti.__ptr[1]->varString = "World"; Asti.__ptr[1]->varInt = &n; Asti.__ptr[1]->varFloat = &f2; Asti.__ptr[2]->varString = "!"; Asti.__ptr[2]->varInt = &n; Asti.__ptr[2]->varFloat = &f2; // b64i.__ptr = (unsigned char*)"This is an example Base64 encoded string"; // b64i.__size = strlen((char*)b64i.__ptr)+1; unsigned char b64data[4]={0x80, 0x81, 0x82, 0x83}; b64i.__ptr = b64data; b64i.__size = 4; hbi.__ptr = (unsigned char*)"This is an example HexBinary encoded string"; hbi.__size = strlen((char*)hbi.__ptr)+1; /* mi.__size = 2; mi.__ptr = (struct _item*)malloc(mi.__size*sizeof(struct _item)); mi.__ptr[0].key = new xsd__string_("hello"); mi.__ptr[0].value = new xsd__string_("world"); mi.__ptr[1].key = new xsd__int_(2); mi.__ptr[1].value = new xsd__boolean_(true); Ami.__size = 2; Ami.__ptr = (struct a__Map**)malloc(Ami.__size*sizeof(struct a__Map*)); Ami.__ptr[0] = &mi; Ami.__ptr[1] = &mi; */ char *site=(char*)url; // char* site ="http://websrv.cs.fsu.edu/~engelen/interop2.cgi"; // char* site = "http://nagoya.apache.org:5049/axis/services/echo "; char* action = "http://soapinterop.org/"; bool ok=true; if (soap_call_ns__echoString(soap, site, action, si, so)) { displayText("echoString fail"); ok=false; } else if (!so || strcmp(si, so)) { ok=false; displayText("echoString mismatched"); } else displayText("echoString pass"); if (soap_call_ns__echoInteger(soap, site, "http://soapinterop.org/", ni, no)) { ok=false; displayText("echoInteger fail"); } else if (ni != no) { ok=false; displayText("echoInteger mismatched"); } else displayText("echoInteger pass"); if (soap_call_ns__echoFloat(soap, site, "http://soapinterop.org/", fi, fo)) { ok=false; displayText("echoFloat fail"); } else if (fi != fo) { ok=false; displayText("echoFloat mismatched"); } else displayText("echoFloat pass"); if (soap_call_ns__echoStruct(soap, site, "http://soapinterop.org/", sti, sto)) { ok=false; displayText("echoStruct fail"); } else if (!sto._return.varString || strcmp(sti.varString, sto._return.varString) || !sto._return.varInt || *sti.varInt != *sto._return.varInt || !sto._return.varFloat || *sti.varFloat != *sto._return.varFloat) { ok=false; displayText("echoStruct mismatch"); } else displayText("echoStruct pass"); if (soap_call_ns__echoStringArray(soap, site, "http://soapinterop.org/", Asi, Aso)) { soap_set_fault(soap); soap_faultdetail(soap); ok=false; displayText("echoStringArray fail"); } else { g = 0; if (Asi.__size != Aso.__size) g = 1; else for (i = 0; i < Asi.__size; i++) if (Asi.__ptr[i] && Aso.__ptr[i] && strcmp(Asi.__ptr[i], Aso.__ptr[i])) g = 1; else if (!Asi.__ptr[i]) ; else if (Asi.__ptr[i] && !Aso.__ptr[i]) g = 1; if (g) { ok=false; displayText("echoStringArray mismatch"); } else displayText("echoStringArray pass"); } if (soap_call_ns__echoIntegerArray(soap, site, "http://soapinterop.org/", Ani, Ano)) { displayText("echoIntegerArray fail"); ok=false; } else { g = 0; if (Ani.__size != Ano.__size) g = 1; else for (i = 0; i < Ani.__size; i++) if (Ani.__ptr[i] && (!Ano.__ptr[i] || *Ani.__ptr[i] != *Ano.__ptr[i])) g = 1; if (g) { displayText("echoIntegerArray mismatch"); ok=false; } else displayText("echoIntegerArray pass"); } if (soap_call_ns__echoFloatArray(soap, site, "http://soapinterop.org/", Afi, Afo)) { displayText("echoFloatArray fail"); ok=false; } else { g = 0; if (Afi.__size != Afo.__size) g = 1; else for (i = 0; i < Afi.__size; i++) if (Afi.__ptr[i] && Afo.__ptr[i] && soap_isnan(*Afi.__ptr[i]) && soap_isnan(*Afo.__ptr[i])) ; else if (Afi.__ptr[i] && (!Afo.__ptr[i] || *Afi.__ptr[i] != *Afo.__ptr[i])) g = 1; if (g) { displayText("echoFloatArray mismatch"); ok=false; } else displayText("echoFloatArray pass"); } if (soap_call_ns__echoStructArray(soap, site, "http://soapinterop.org/", Asti, Asto)) { displayText("echoStructArray fail"); ok=false; } else { g = 0; if (Asti.__size+Asti.__offset != Asto.__size+Asto.__offset) g = 1; else for (i = Asti.__offset; i < Asti.__size+Asti.__offset; i++) if (!Asto.__ptr[i-Asto.__offset] || !Asto.__ptr[i-Asto.__offset]->varString || strcmp(Asti.__ptr[i-Asti.__offset]->varString, Asto.__ptr[i-Asto.__offset]->varString) || !Asto.__ptr[i-Asto.__offset]->varInt || *Asti.__ptr[i-Asti.__offset]->varInt != *Asto.__ptr[i-Asto.__offset]->varInt || !Asto.__ptr[i-Asto.__offset]->varFloat || *Asti.__ptr[i-Asti.__offset]->varFloat != *Asto.__ptr[i-Asto.__offset]->varFloat) g = 1; if (g) { displayText("echoStructArray mismatch"); ok=false; } else displayText("echoStructArray pass"); } if (soap_call_ns__echoVoid(soap, site, "http://soapinterop.org/", Rv)) { displayText("echoVoid fail"); ok=false; } else displayText("echoVoid pass"); if (soap_call_ns__echoBase64(soap, site, "http://soapinterop.org/", b64i, b64o)) { displayText("echoBase64 fail"); ok=false; } else if ((b64i.__size+2)/3 != (b64o.__size+2)/3 || strncmp((char*)b64i.__ptr, (char*)b64o.__ptr,b64i.__size)) { displayText("echoBase64 mismatch"); ok=false; } else displayText("echoBase64 pass"); if (soap_call_ns__echoDate(soap, site, "http://soapinterop.org/", dti, dto)) { displayText("echoDate fail"); ok=false; } else if (!dto || strncmp(dti, dto, 19)) { displayText("echoDate mismatch"); ok=false; } else displayText("echoDate pass"); if (soap_call_ns__echoHexBinary(soap, site, "http://soapinterop.org/", hbi, hbo)) { ok=false; displayText("echoHexBinary fail"); } else if (hbi.__size != hbo.__size || strcmp((char*)hbi.__ptr, (char*)hbo.__ptr)) { ok=false; displayText("echoHexBinary mismatch"); } else displayText("echoHexBinary pass"); if (soap_call_ns__echoDecimal(soap, site, "http://soapinterop.org/", Di, Do)) { ok=false; displayText("echoDecimal pass"); } else if (strcmp(Di, Do)) { ok=false; displayText("echoDecimal mismatch"); } else displayText("echoDecimal pass"); if (soap_call_ns__echoBoolean(soap, site, "http://soapinterop.org/", bi, bo)) { ok=false; displayText("echoBoolean fail"); } else if (bi != bo) { ok=false; displayText("echoBoolean mismatch"); } else displayText("echoBoolean pass"); if (ok) displayText("ALL PASS"); else displayText("FAILURES"); return 0; end: return 1; }
cory-ko/KBWS
gsoap/Symbian/interop2test.cpp
C++
gpl-2.0
11,395
/* * * Copyright 2003, 2004 Blur Studio Inc. * * This file is part of the Resin software package. * * Resin is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin 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 Resin; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef COMMIT_CODE #include <qdir.h> #include <stdlib.h> #include "shotgroup.h" int ShotGroup::frameStart() const { return shots()[shots().count()-1].frameStart(); } int ShotGroup::frameEnd() const { return shots()[0].frameEnd(); } int ShotGroup::frameStartEDL() const { return shots()[shots().count()-1].frameStartEDL(); } int ShotGroup::frameEndEDL() const { return shots()[0].frameEndEDL(); } ShotList ShotGroup::shots() const { ShotList shots = children( Shot::type(), true ); return shots; } #endif
perryjrandall/arsenalsuite
cpp/lib/classes/base/shotgroupbase.cpp
C++
gpl-2.0
1,325
/* Copyright (C) 2011-2012 de4dot@gmail.com This file is part of de4dot. de4dot 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. de4dot 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 de4dot. If not, see <http://www.gnu.org/licenses/>. */ using de4dot.PE; namespace de4dot.code.deobfuscators.MaxtoCode { class DecrypterInfo { public readonly MainType mainType; public readonly PeImage peImage; public readonly PeHeader peHeader; public readonly McKey mcKey; public readonly byte[] fileData; public DecrypterInfo(MainType mainType, byte[] fileData) { this.mainType = mainType; this.peImage = new PeImage(fileData); this.peHeader = new PeHeader(mainType, peImage); this.mcKey = new McKey(peImage, peHeader); this.fileData = fileData; } } }
hjlfmy/de4dot
de4dot.code/deobfuscators/MaxtoCode/DecrypterInfo.cs
C#
gpl-3.0
1,256
#!/usr/bin/env python # Copyright (c) 2006-2007 XenSource, Inc. # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Simple example using the asynchronous version of the VM start method # Assumes the presence of a VM called 'new' import pprint, time, sys import XenAPI def main(session): print "Listing all VM references:" vms = session.xenapi.VM.get_all() pprint.pprint(vms) print "Dumping all VM records:" for vm in vms: pprint.pprint(session.xenapi.VM.get_record(vm)) print "Attempting to start a VM called 'new' (if it doesn't exist this will throw an exception)" vm = session.xenapi.VM.get_by_name_label('new')[0] session.xenapi.VM.start(vm, False, True) print "Attempting to start the VM asynchronously" task = session.xenapi.Async.VM.start(vm, False, True) task_record = session.xenapi.task.get_record(task) print "The initial contents of the task record:" pprint.pprint(task_record) print "Waiting for the task to complete" while session.xenapi.task.get_status(task) == "pending": time.sleep(1) task_record = session.xenapi.task.get_record(task) print "The final contents of the task record:" pprint.pprint(task_record) if __name__ == "__main__": if len(sys.argv) <> 4: print "Usage:" print sys.argv[0], " <url> <username> <password>" sys.exit(1) url = sys.argv[1] username = sys.argv[2] password = sys.argv[3] # First acquire a valid session by logging in: session = XenAPI.Session(url) session.xenapi.login_with_password(username, password, "1.0", "xen-api-scripts-vm-start-async.py") main(session)
anoobs/xen-api
scripts/examples/python/vm_start_async.py
Python
lgpl-2.1
2,335
package version // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // Number contains the semantic version of this SDK. const Number = "v40.2.0"
sethpollack/kubernetes
vendor/github.com/Azure/azure-sdk-for-go/version/version.go
GO
apache-2.0
865
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal static class TestTypeExtensions { public static string GetTypeName(this Type type, bool escapeKeywordIdentifiers = false) { return CSharpFormatter.Instance.GetTypeName((TypeImpl)type, escapeKeywordIdentifiers); } } }
ManishJayaswal/roslyn
src/ExpressionEvaluator/CSharp/Test/ResultProvider/Helpers/TestTypeExtensions.cs
C#
apache-2.0
563
// Copyright 2013 The Go Circuit Project // Use of this source code is governed by the license for // The Go Circuit Project, found in the LICENSE file. // // Authors: // 2013 Petar Maymounkov <p@gocircuit.org> package tele import ( "github.com/gocircuit/circuit/kit/tele/blend" "github.com/gocircuit/circuit/use/n" ) type Conn struct { addr *Addr sub *blend.Conn } func NewConn(sub *blend.Conn, addr *Addr) *Conn { return &Conn{addr: addr, sub: sub} } func (c *Conn) Read() (v interface{}, err error) { if v, err = c.sub.Read(); err != nil { return nil, err } return } func (c *Conn) Write(v interface{}) (err error) { if err = c.sub.Write(v); err != nil { return err } return nil } func (c *Conn) Close() error { return c.sub.Close() } func (c *Conn) Abort(reason error) { c.sub.Abort(reason) } func (c *Conn) Addr() n.Addr { return c.addr }
bzz/circuit
sys/tele/conn.go
GO
apache-2.0
874
/* * Copyright (C) 2010 The Android Open Source Project * * 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.android.internal.telephony; /** * WapPushManager constant value definitions */ public class WapPushManagerParams { /** * Application type activity */ public static final int APP_TYPE_ACTIVITY = 0; /** * Application type service */ public static final int APP_TYPE_SERVICE = 1; /** * Process Message return value * Message is handled */ public static final int MESSAGE_HANDLED = 0x1; /** * Process Message return value * Application ID or content type was not found in the application ID table */ public static final int APP_QUERY_FAILED = 0x2; /** * Process Message return value * Receiver application signature check failed */ public static final int SIGNATURE_NO_MATCH = 0x4; /** * Process Message return value * Receiver application was not found */ public static final int INVALID_RECEIVER_NAME = 0x8; /** * Process Message return value * Unknown exception */ public static final int EXCEPTION_CAUGHT = 0x10; /** * Process Message return value * Need further processing after WapPushManager message processing */ public static final int FURTHER_PROCESSING = 0x8000; }
JSDemos/android-sdk-20
src/com/android/internal/telephony/WapPushManagerParams.java
Java
apache-2.0
1,891
require 'test_helper' class TraceSummariesHelperTest < ActionView::TestCase end
rodzyn0688/zipkin
zipkin-web/test/unit/helpers/trace_summaries_helper_test.rb
Ruby
apache-2.0
81
require "formula" class Libpng < Formula homepage "http://www.libpng.org/pub/png/libpng.html" url "https://downloads.sf.net/project/libpng/libpng16/1.6.13/libpng-1.6.13.tar.xz" sha1 "5ae32b6b99cef6c5c85feab8edf9d619e1773b15" bottle do cellar :any sha1 "c4c5f94b771ea53620d9b6c508b382b3a40d6c80" => :yosemite sha1 "09af92d209c67dd0719d16866dc26c05bbbef77b" => :mavericks sha1 "23812e76bf0e3f98603c6d22ab69258b219918ca" => :mountain_lion sha1 "af1fe6844a0614652bbc9b60fd84c57e24da93ee" => :lion end keg_only :provided_pre_mountain_lion option :universal def install ENV.universal_binary if build.universal? system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make install" end end
0xbb/homebrew
Library/Formula/libpng.rb
Ruby
bsd-2-clause
844
/*global app: true, env: true */ /** Define tags that are known in JSDoc. @module jsdoc/tag/dictionary/definitions @author Michael Mathews <micmath@gmail.com> @license Apache License 2.0 - See file 'LICENSE.md' in this project. */ 'use strict'; var logger = require('jsdoc/util/logger'); var path = require('jsdoc/path'); var Syntax = require('jsdoc/src/syntax').Syntax; function getSourcePaths() { var sourcePaths = env.sourceFiles.slice(0) || []; if (env.opts._) { env.opts._.forEach(function(sourcePath) { var resolved = path.resolve(env.pwd, sourcePath); if (sourcePaths.indexOf(resolved) === -1) { sourcePaths.push(resolved); } }); } return sourcePaths; } function filepathMinusPrefix(filepath) { var sourcePaths = getSourcePaths(); var commonPrefix = path.commonPrefix(sourcePaths); var result = ''; if (filepath) { // always use forward slashes result = (filepath + path.sep).replace(commonPrefix, '') .replace(/\\/g, '/'); } if (result.length > 0 && result[result.length - 1] !== '/') { result += '/'; } return result; } /** @private */ function setDocletKindToTitle(doclet, tag) { doclet.addTag( 'kind', tag.title ); } function setDocletScopeToTitle(doclet, tag) { try { doclet.setScope(tag.title); } catch(e) { logger.error(e.message); } } function setDocletNameToValue(doclet, tag) { if (tag.value && tag.value.description) { // as in a long tag doclet.addTag( 'name', tag.value.description); } else if (tag.text) { // or a short tag doclet.addTag('name', tag.text); } } function setDocletNameToValueName(doclet, tag) { if (tag.value && tag.value.name) { doclet.addTag('name', tag.value.name); } } function setDocletDescriptionToValue(doclet, tag) { if (tag.value) { doclet.addTag( 'description', tag.value ); } } function setDocletTypeToValueType(doclet, tag) { if (tag.value && tag.value.type) { doclet.type = tag.value.type; } } function setNameToFile(doclet, tag) { var name; if (doclet.meta.filename) { name = filepathMinusPrefix(doclet.meta.path) + doclet.meta.filename; doclet.addTag('name', name); } } function setDocletMemberof(doclet, tag) { if (tag.value && tag.value !== '<global>') { doclet.setMemberof(tag.value); } } function applyNamespace(docletOrNs, tag) { if (typeof docletOrNs === 'string') { // ns tag.value = app.jsdoc.name.applyNamespace(tag.value, docletOrNs); } else { // doclet if (!docletOrNs.name) { return; // error? } //doclet.displayname = doclet.name; docletOrNs.longname = app.jsdoc.name.applyNamespace(docletOrNs.name, tag.title); } } function setDocletNameToFilename(doclet, tag) { var name = ''; if (doclet.meta.path) { name = filepathMinusPrefix(doclet.meta.path); } name += doclet.meta.filename.replace(/\.js$/i, ''); doclet.name = name; } function parseBorrows(doclet, tag) { var m = /^(\S+)(?:\s+as\s+(\S+))?$/.exec(tag.text); if (m) { if (m[1] && m[2]) { return { target: m[1], source: m[2] }; } else if (m[1]) { return { target: m[1] }; } } else { return {}; } } function firstWordOf(string) { var m = /^(\S+)/.exec(string); if (m) { return m[1]; } else { return ''; } } /** Populate the given dictionary with all known JSDoc tag definitions. @param {module:jsdoc/tag/dictionary} dictionary */ exports.defineTags = function(dictionary) { dictionary.defineTag('abstract', { mustNotHaveValue: true, onTagged: function(doclet, tag) { // since "abstract" is reserved word in JavaScript let's use "virtual" in code doclet.virtual = true; } }) .synonym('virtual'); dictionary.defineTag('access', { mustHaveValue: true, onTagged: function(doclet, tag) { // only valid values are private and protected, public is default if ( /^(private|protected)$/i.test(tag.value) ) { doclet.access = tag.value.toLowerCase(); } else { delete doclet.access; } } }); dictionary.defineTag('alias', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.alias = tag.value; } }); // Special separator tag indicating that multiple doclets should be generated for the same // comment. Used internally (and by some JSDoc users, although it's not officially supported). // // In the following example, the parser will replace `//**` with an `@also` tag: // // /** // * Foo. // *//** // * Foo with a param. // * @param {string} bar // */ // function foo(bar) {} dictionary.defineTag('also', { onTagged: function(doclet, tag) { // let the parser handle it; we define the tag here to avoid "not a known tag" errors } }); // this symbol inherits from the specified symbol dictionary.defineTag('augments', { mustHaveValue: true, // Allow augments value to be specified as a normal type, e.g. {Type} onTagText: function(text) { var type = require('jsdoc/tag/type'), tagType = type.parse(text, false, true); return tagType.typeExpression || text; }, onTagged: function(doclet, tag) { doclet.augment( firstWordOf(tag.value) ); } }) .synonym('extends'); dictionary.defineTag('author', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.author) { doclet.author = []; } doclet.author.push(tag.value); } }); // this symbol has a member that should use the same docs as another symbol dictionary.defineTag('borrows', { mustHaveValue: true, onTagged: function(doclet, tag) { var borrows = parseBorrows(doclet, tag); doclet.borrow(borrows.target, borrows.source); } }); dictionary.defineTag('class', { onTagged: function(doclet, tag) { doclet.addTag('kind', 'class'); // handle special case where both @class and @constructor tags exist in same doclet if (tag.originalTitle === 'class') { var looksLikeDesc = (tag.value || '').match(/\S+\s+\S+/); // multiple words after @class? if ( looksLikeDesc || /@construct(s|or)\b/i.test(doclet.comment) ) { doclet.classdesc = tag.value; // treat the @class tag as a @classdesc tag instead return; } } setDocletNameToValue(doclet, tag); } }) .synonym('constructor'); dictionary.defineTag('classdesc', { onTagged: function(doclet, tag) { doclet.classdesc = tag.value; } }); dictionary.defineTag('constant', { canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValueName(doclet, tag); setDocletTypeToValueType(doclet, tag); } }) .synonym('const'); dictionary.defineTag('constructs', { onTagged: function(doclet, tag) { var ownerClassName; if (!tag.value) { ownerClassName = '{@thisClass}'; // this can be resolved later in the handlers } else { ownerClassName = firstWordOf(tag.value); } doclet.addTag('alias', ownerClassName); doclet.addTag('kind', 'class'); } }); dictionary.defineTag('copyright', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.copyright = tag.value; } }); dictionary.defineTag('default', { onTagged: function(doclet, tag) { var type; var value; if (tag.value) { doclet.defaultvalue = tag.value; } else if (doclet.meta && doclet.meta.code && doclet.meta.code.value) { type = doclet.meta.code.type; value = doclet.meta.code.value; if (type === Syntax.Literal) { doclet.defaultvalue = String(value); } // TODO: reenable the changes for https://github.com/jsdoc3/jsdoc/pull/419 /* else if (doclet.meta.code.type === 'OBJECTLIT') { doclet.defaultvalue = String(doclet.meta.code.node.toSource()); doclet.defaultvaluetype = 'object'; } */ } } }) .synonym('defaultvalue'); dictionary.defineTag('deprecated', { // value is optional onTagged: function(doclet, tag) { doclet.deprecated = tag.value || true; } }); dictionary.defineTag('description', { mustHaveValue: true }) .synonym('desc'); dictionary.defineTag('enum', { canHaveType: true, onTagged: function(doclet, tag) { doclet.kind = 'member'; doclet.isEnum = true; setDocletTypeToValueType(doclet, tag); } }); dictionary.defineTag('event', { isNamespace: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); } }); dictionary.defineTag('example', { keepsWhitespace: true, removesIndent: true, mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.examples) { doclet.examples = []; } doclet.examples.push(tag.value); } }); dictionary.defineTag('exception', { mustHaveValue: true, canHaveType: true, onTagged: function(doclet, tag) { if (!doclet.exceptions) { doclet.exceptions = []; } doclet.exceptions.push(tag.value); setDocletTypeToValueType(doclet, tag); } }) .synonym('throws'); dictionary.defineTag('exports', { mustHaveValue: true, onTagged: function(doclet, tag) { var modName = firstWordOf(tag.value); doclet.addTag('alias', modName); doclet.addTag('kind', 'module'); } }); dictionary.defineTag('external', { canHaveType: true, isNamespace: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); if (tag.value && tag.value.type) { setDocletTypeToValueType(doclet, tag); doclet.addTag('name', doclet.type.names[0]); } } }) .synonym('host'); dictionary.defineTag('file', { onTagged: function(doclet, tag) { setNameToFile(doclet, tag); setDocletKindToTitle(doclet, tag); setDocletDescriptionToValue(doclet, tag); doclet.preserveName = true; } }) .synonym('fileoverview') .synonym('overview'); dictionary.defineTag('fires', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.fires) { doclet.fires = []; } applyNamespace('event', tag); doclet.fires.push(tag.value); } }) .synonym('emits'); dictionary.defineTag('function', { onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); } }) .synonym('func') .synonym('method'); dictionary.defineTag('global', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.scope = 'global'; delete doclet.memberof; } }); dictionary.defineTag('ignore', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.ignore = true; } }); dictionary.defineTag('inner', { onTagged: function(doclet, tag) { setDocletScopeToTitle(doclet, tag); } }); dictionary.defineTag('instance', { onTagged: function(doclet, tag) { setDocletScopeToTitle(doclet, tag); } }); dictionary.defineTag('kind', { mustHaveValue: true }); dictionary.defineTag('lends', { onTagged: function(doclet, tag) { var GLOBAL_LONGNAME = require('jsdoc/doclet').GLOBAL_LONGNAME; doclet.alias = tag.value || GLOBAL_LONGNAME; doclet.addTag('undocumented'); } }); dictionary.defineTag('license', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.license = tag.value; } }); dictionary.defineTag('listens', { mustHaveValue: true, onTagged: function (doclet, tag) { if (!doclet.listens) { doclet.listens = []; } applyNamespace('event', tag); doclet.listens.push(tag.value); // TODO: verify that parameters match the event parameters? } }); dictionary.defineTag('member', { canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValueName(doclet, tag); setDocletTypeToValueType(doclet, tag); } }) .synonym('var'); dictionary.defineTag('memberof', { mustHaveValue: true, onTagged: function(doclet, tag) { var GLOBAL_LONGNAME = require('jsdoc/doclet').GLOBAL_LONGNAME; if (tag.originalTitle === 'memberof!') { doclet.forceMemberof = true; if (tag.value === GLOBAL_LONGNAME) { doclet.addTag('global'); delete doclet.memberof; } } setDocletMemberof(doclet, tag); } }) .synonym('memberof!'); // this symbol mixes in all of the specified object's members dictionary.defineTag('mixes', { mustHaveValue: true, onTagged: function(doclet, tag) { var source = firstWordOf(tag.value); doclet.mix(source); } }); dictionary.defineTag('mixin', { onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); } }); dictionary.defineTag('module', { canHaveType: true, isNamespace: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); if (!doclet.name) { setDocletNameToFilename(doclet, tag); } setDocletTypeToValueType(doclet, tag); } }); dictionary.defineTag('name', { mustHaveValue: true }); dictionary.defineTag('namespace', { canHaveType: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); setDocletTypeToValueType(doclet, tag); } }); dictionary.defineTag('param', { //mustHaveValue: true, // param name can be found in the source code if not provided canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { if (!doclet.params) { doclet.params = []; } doclet.params.push(tag.value||{}); } }) .synonym('argument') .synonym('arg'); dictionary.defineTag('private', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.access = 'private'; } }); dictionary.defineTag('property', { mustHaveValue: true, canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { if (!doclet.properties) { doclet.properties = []; } doclet.properties.push(tag.value); } }) .synonym('prop'); dictionary.defineTag('protected', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.access = 'protected'; } }); dictionary.defineTag('public', { mustNotHaveValue: true, onTagged: function(doclet, tag) { delete doclet.access; // public is default } }); // use this instead of old deprecated @final tag dictionary.defineTag('readonly', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.readonly = true; } }); dictionary.defineTag('requires', { mustHaveValue: true, onTagged: function(doclet, tag) { var requiresName; var MODULE_PREFIX = require('jsdoc/name').MODULE_PREFIX; // inline link tags are passed through as-is so that `@requires {@link foo}` works if ( require('jsdoc/tag/inline').isInlineTag(tag.value, 'link\\S*') ) { requiresName = tag.value; } // otherwise, assume it's a module else { requiresName = firstWordOf(tag.value); if (requiresName.indexOf(MODULE_PREFIX) !== 0) { requiresName = MODULE_PREFIX + requiresName; } } if (!doclet.requires) { doclet.requires = []; } doclet.requires.push(requiresName); } }); dictionary.defineTag('returns', { mustHaveValue: true, canHaveType: true, onTagged: function(doclet, tag) { if (!doclet.returns) { doclet.returns = []; } doclet.returns.push(tag.value); } }) .synonym('return'); dictionary.defineTag('see', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.see) { doclet.see = []; } doclet.see.push(tag.value); } }); dictionary.defineTag('since', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.since = tag.value; } }); dictionary.defineTag('static', { onTagged: function(doclet, tag) { setDocletScopeToTitle(doclet, tag); } }); dictionary.defineTag('summary', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.summary = tag.value; } }); dictionary.defineTag('this', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet['this'] = firstWordOf(tag.value); } }); dictionary.defineTag('todo', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.todo) { doclet.todo = []; } doclet.todo.push(tag.value); } }); dictionary.defineTag('tutorial', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.tutorials) { doclet.tutorials = []; } doclet.tutorials.push(tag.value); } }); dictionary.defineTag('type', { mustHaveValue: true, canHaveType: true, onTagText: function(text) { // remove line breaks so we can parse the type expression correctly text = text.replace(/[\n\r]/g, ''); // any text must be formatted as a type, but for back compat braces are optional if ( !/^\{[\s\S]+\}$/.test(text) ) { text = '{' + text + '}'; } return text; }, onTagged: function(doclet, tag) { if (tag.value && tag.value.type) { setDocletTypeToValueType(doclet, tag); // for backwards compatibility, we allow @type for functions to imply return type if (doclet.kind === 'function') { doclet.addTag('returns', tag.text); } } } }); dictionary.defineTag('typedef', { canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); if (tag.value) { setDocletNameToValueName(doclet, tag); // callbacks are always type {function} if (tag.originalTitle === 'callback') { doclet.type = { names: [ 'function' ] }; } else { setDocletTypeToValueType(doclet, tag); } } } }) .synonym('callback'); dictionary.defineTag('undocumented', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.undocumented = true; doclet.comment = ''; } }); dictionary.defineTag('variation', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.variation = tag.value; } }); dictionary.defineTag('version', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.version = tag.value; } }); };
ad-l/djcl
tools/jsdoc/lib/jsdoc/tag/dictionary/definitions.js
JavaScript
bsd-2-clause
21,625
"""Testing the pytest fixtures themselves which are declared in conftest.py.""" import pytest import responses import requests from requests.exceptions import ConnectionError from olympia.access.models import Group def test_admin_group(admin_group): assert Group.objects.count() == 1 admin_group = Group.objects.get() assert admin_group.name == 'Admins' assert admin_group.rules == '*:*' def test_mozilla_user(mozilla_user): admin_group = mozilla_user.groups.get() assert admin_group.name == 'Admins' assert admin_group.rules == '*:*' @pytest.mark.allow_external_http_requests def test_external_requests_enabled(): with pytest.raises(ConnectionError): requests.get('http://example.invalid') assert len(responses.calls) == 0 def test_external_requests_disabled_by_default(): with pytest.raises(ConnectionError): requests.get('http://example.invalid') assert len(responses.calls) == 1
aviarypl/mozilla-l10n-addons-server
src/olympia/amo/tests/test_pytest_fixtures.py
Python
bsd-3-clause
955
--TEST-- Bug #43483 (get_class_methods() does not list all visible methods) --FILE-- <?php class C { public static function test() { D::prot(); print_r(get_class_methods("D")); } } class D extends C { protected static function prot() { echo "Successfully called D::prot().\n"; } } D::test(); ?> --EXPECT-- Successfully called D::prot(). Array ( [0] => prot [1] => test )
glayzzle/tests
zend/bug43483.phpt
PHP
bsd-3-clause
389
package org.motechproject.odk.domain; import org.motechproject.mds.annotations.Entity; import org.motechproject.mds.annotations.Field; /** * Domain object relating to a form receipt failure event */ @Entity public class FormFailure { @Field private String configName; @Field private String formTitle; @Field private String message; @Field private String exception; @Field(type = "TEXT") private String jsonContent; public FormFailure(String configName, String formTitle, String message, String exception, String jsonContent) { this.configName = configName; this.formTitle = formTitle; this.message = message; this.exception = exception; this.jsonContent = jsonContent; } public String getConfigName() { return configName; } public void setConfigName(String configName) { this.configName = configName; } public String getFormTitle() { return formTitle; } public void setFormTitle(String formTitle) { this.formTitle = formTitle; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getException() { return exception; } public void setException(String exception) { this.exception = exception; } public String getJsonContent() { return jsonContent; } public void setJsonContent(String jsonContent) { this.jsonContent = jsonContent; } }
koshalt/modules
odk/src/main/java/org/motechproject/odk/domain/FormFailure.java
Java
bsd-3-clause
1,577
/** * @license * Copyright The Closure Library Authors. * SPDX-License-Identifier: Apache-2.0 */ goog.module('goog.dom.SavedCaretRangeTest'); goog.setTestOnly(); const Range = goog.require('goog.dom.Range'); const SavedCaretRange = goog.require('goog.dom.SavedCaretRange'); const dom = goog.require('goog.dom'); const testSuite = goog.require('goog.testing.testSuite'); const testingDom = goog.require('goog.testing.dom'); const userAgent = goog.require('goog.userAgent'); /* TODO(user): Look into why removeCarets test doesn't pass. function testRemoveCarets() { var def = goog.dom.getElement('def'); var jkl = goog.dom.getElement('jkl'); var range = goog.dom.Range.createFromNodes( def.firstChild, 1, jkl.firstChild, 2); range.select(); var saved = range.saveUsingCarets(); assertHTMLEquals( "d<span id="" + saved.startCaretId_ + ""></span>ef", def.innerHTML); assertHTMLEquals( "jk<span id="" + saved.endCaretId_ + ""></span>l", jkl.innerHTML); saved.removeCarets(); assertHTMLEquals("def", def.innerHTML); assertHTMLEquals("jkl", jkl.innerHTML); var selection = goog.dom.Range.createFromWindow(window); assertEquals('Wrong start node', def.firstChild, selection.getStartNode()); assertEquals('Wrong end node', jkl.firstChild, selection.getEndNode()); assertEquals('Wrong start offset', 1, selection.getStartOffset()); assertEquals('Wrong end offset', 2, selection.getEndOffset()); } */ /** * Clear the selection by re-parsing the DOM. Then restore the saved * selection. * @param {Node} parent The node containing the current selection. * @param {dom.SavedRange} saved The saved range. * @return {dom.AbstractRange} Restored range. */ function clearSelectionAndRestoreSaved(parent, saved) { Range.clearSelection(); assertFalse(Range.hasSelection(window)); const range = saved.restore(); assertTrue(Range.hasSelection(window)); return range; } testSuite({ setUp() { document.body.normalize(); }, /** @bug 1480638 */ testSavedCaretRangeDoesntChangeSelection() { // NOTE(nicksantos): We cannot detect this bug programatically. The only // way to detect it is to run this test manually and look at the selection // when it ends. const div = dom.getElement('bug1480638'); const range = Range.createFromNodes(div.firstChild, 0, div.lastChild, 1); range.select(); // Observe visible selection. Then move to next line and see it change. // If the bug exists, it starts with "foo" selected and ends with // it not selected. // debugger; const saved = range.saveUsingCarets(); }, /** @suppress {strictMissingProperties} suppression added to enable type checking */ testSavedCaretRange() { if (userAgent.IE && !userAgent.isDocumentModeOrHigher(8)) { // testSavedCaretRange fails in IE7 unless the source files are loaded in // a certain order. Adding goog.require('goog.dom.classes') to dom.js or // goog.require('goog.array') to savedcaretrange_test.js after the // goog.require('goog.dom') line fixes the test, but it's better to not // rely on such hacks without understanding the reason of the failure. return; } const parent = dom.getElement('caretRangeTest'); let def = dom.getElement('def'); let jkl = dom.getElement('jkl'); const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2); assertFalse(range.isReversed()); range.select(); const saved = range.saveUsingCarets(); assertHTMLEquals( 'd<span id="' + saved.startCaretId_ + '"></span>ef', def.innerHTML); assertHTMLEquals( 'jk<span id="' + saved.endCaretId_ + '"></span>l', jkl.innerHTML); testingDom.assertRangeEquals( def.childNodes[1], 0, jkl.childNodes[1], 0, saved.toAbstractRange()); def = dom.getElement('def'); jkl = dom.getElement('jkl'); const restoredRange = clearSelectionAndRestoreSaved(parent, saved); assertFalse(restoredRange.isReversed()); testingDom.assertRangeEquals(def, 1, jkl, 1, restoredRange); const selection = Range.createFromWindow(window); assertHTMLEquals('def', def.innerHTML); assertHTMLEquals('jkl', jkl.innerHTML); // def and jkl now contain fragmented text nodes. const endNode = selection.getEndNode(); if (endNode == jkl.childNodes[0]) { // Webkit (up to Chrome 57) and IE < 9. testingDom.assertRangeEquals( def.childNodes[1], 0, jkl.childNodes[0], 2, selection); } else if (endNode == jkl.childNodes[1]) { // Opera testingDom.assertRangeEquals( def.childNodes[1], 0, jkl.childNodes[1], 0, selection); } else { // Gecko, newer Chromes testingDom.assertRangeEquals(def, 1, jkl, 1, selection); } }, testReversedSavedCaretRange() { const parent = dom.getElement('caretRangeTest'); const def = dom.getElement('def-5'); const jkl = dom.getElement('jkl-5'); const range = Range.createFromNodes(jkl.firstChild, 1, def.firstChild, 2); assertTrue(range.isReversed()); range.select(); const saved = range.saveUsingCarets(); const restoredRange = clearSelectionAndRestoreSaved(parent, saved); assertTrue(restoredRange.isReversed()); testingDom.assertRangeEquals(def, 1, jkl, 1, restoredRange); }, testRemoveContents() { const def = dom.getElement('def-4'); const jkl = dom.getElement('jkl-4'); // Sanity check. const container = dom.getElement('removeContentsTest'); assertEquals(7, container.childNodes.length); assertEquals('def', def.innerHTML); assertEquals('jkl', jkl.innerHTML); const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2); range.select(); const saved = range.saveUsingCarets(); const restored = saved.restore(); restored.removeContents(); assertEquals(6, container.childNodes.length); assertEquals('d', def.innerHTML); assertEquals('l', jkl.innerHTML); }, testHtmlEqual() { const parent = dom.getElement('caretRangeTest-2'); const def = dom.getElement('def-2'); const jkl = dom.getElement('jkl-2'); const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2); range.select(); const saved = range.saveUsingCarets(); const html1 = parent.innerHTML; saved.removeCarets(); const saved2 = range.saveUsingCarets(); const html2 = parent.innerHTML; saved2.removeCarets(); assertNotEquals( 'Same selection with different saved caret range carets ' + 'must have different html.', html1, html2); assertTrue( 'Same selection with different saved caret range carets must ' + 'be considered equal by htmlEqual', SavedCaretRange.htmlEqual(html1, html2)); saved.dispose(); saved2.dispose(); }, testStartCaretIsAtEndOfParent() { const parent = dom.getElement('caretRangeTest-3'); const def = dom.getElement('def-3'); const jkl = dom.getElement('jkl-3'); let range = Range.createFromNodes(def, 1, jkl, 1); range.select(); const saved = range.saveUsingCarets(); clearSelectionAndRestoreSaved(parent, saved); range = Range.createFromWindow(); assertEquals('ghijkl', range.getText().replace(/\s/g, '')); }, });
nwjs/chromium.src
third_party/google-closure-library/closure/goog/dom/savedcaretrange_test.js
JavaScript
bsd-3-clause
7,324
// 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. package org.chromium.media; import android.content.Context; import android.graphics.ImageFormat; import android.hardware.display.DisplayManager; import android.view.Display; import android.view.Surface; import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Video Capture Device base class, defines a set of methods that native code * needs to use to configure, start capture, and to be reached by callbacks and * provides some necessary data type(s) with accessors. **/ @JNINamespace("media") public abstract class VideoCapture { /** * Common class for storing a framerate range. Values should be multiplied by 1000. */ protected static class FramerateRange { public int min; public int max; public FramerateRange(int min, int max) { this.min = min; this.max = max; } } // The angle (0, 90, 180, 270) that the image needs to be rotated to show in // the display's native orientation. protected int mCameraNativeOrientation; // In some occasions we need to invert the device rotation readings, see the // individual implementations. protected boolean mInvertDeviceOrientationReadings; protected VideoCaptureFormat mCaptureFormat; protected final int mId; // Native callback context variable. protected final long mNativeVideoCaptureDeviceAndroid; protected boolean mUseBackgroundThreadForTesting; VideoCapture(int id, long nativeVideoCaptureDeviceAndroid) { mId = id; mNativeVideoCaptureDeviceAndroid = nativeVideoCaptureDeviceAndroid; } // Allocate necessary resources for capture. @CalledByNative public abstract boolean allocate( int width, int height, int frameRate, boolean enableFaceDetection); // Success is indicated by returning true and a callback to // VideoCaptureJni.get().onStarted(, VideoCapture.this), which may occur synchronously or // asynchronously. Failure can be indicated by one of the following: // * Returning false. In this case no callback to VideoCaptureJni.get().onStarted() is made. // * Returning true, and asynchronously invoking VideoCaptureJni.get().onError. In this case // also no callback to VideoCaptureJni.get().onStarted() is made. @CalledByNative public abstract boolean startCaptureMaybeAsync(); // Blocks until it is guaranteed that no more frames are sent. @CalledByNative public abstract boolean stopCaptureAndBlockUntilStopped(); // Replies by calling VideoCaptureJni.get().onGetPhotoCapabilitiesReply(). Will pass |null| // for parameter |result| to indicate failure. @CalledByNative public abstract void getPhotoCapabilitiesAsync(long callbackId); /** * @param zoom Zoom level, should be ignored if 0. * @param focusMode Focus mode following AndroidMeteringMode enum. * @param focusDistance Desired distance to plane of sharpest focus. * @param exposureMode Exposure mode following AndroidMeteringMode enum. * @param pointsOfInterest2D 2D normalized points of interest, marshalled with * x coordinate first followed by the y coordinate. * @param hasExposureCompensation Indicates if |exposureCompensation| is set. * @param exposureCompensation Adjustment to auto exposure. 0 means not adjusted. * @param exposureTime Duration each pixel is exposed to light (in nanoseconds). * @param whiteBalanceMode White Balance mode following AndroidMeteringMode enum. * @param iso Sensitivity to light. 0, which would be invalid, means ignore. * @param hasRedEyeReduction Indicates if |redEyeReduction| is set. * @param redEyeReduction Value of red eye reduction for the auto flash setting. * @param fillLightMode Flash setting, following AndroidFillLightMode enum. * @param colorTemperature White Balance reference temperature, valid if whiteBalanceMode is * manual, and its value is larger than 0. * @param torch Torch setting, true meaning on. */ @CalledByNative public abstract void setPhotoOptions(double zoom, int focusMode, double focusDistance, int exposureMode, double width, double height, double[] pointsOfInterest2D, boolean hasExposureCompensation, double exposureCompensation, double exposureTime, int whiteBalanceMode, double iso, boolean hasRedEyeReduction, boolean redEyeReduction, int fillLightMode, boolean hasTorch, boolean torch, double colorTemperature); // Replies by calling VideoCaptureJni.get().onPhotoTaken(). @CalledByNative public abstract void takePhotoAsync(long callbackId); @CalledByNative public abstract void deallocate(); @CalledByNative public final int queryWidth() { return mCaptureFormat.mWidth; } @CalledByNative public final int queryHeight() { return mCaptureFormat.mHeight; } @CalledByNative public final int queryFrameRate() { return mCaptureFormat.mFramerate; } @CalledByNative public final int getColorspace() { switch (mCaptureFormat.mPixelFormat) { case ImageFormat.YV12: return AndroidImageFormat.YV12; case ImageFormat.YUV_420_888: return AndroidImageFormat.YUV_420_888; case ImageFormat.NV21: return AndroidImageFormat.NV21; case ImageFormat.UNKNOWN: default: return AndroidImageFormat.UNKNOWN; } } @CalledByNative public final void setTestMode() { mUseBackgroundThreadForTesting = true; } protected final int getCameraRotation() { int rotation = mInvertDeviceOrientationReadings ? (360 - getDeviceRotation()) : getDeviceRotation(); return (mCameraNativeOrientation + rotation) % 360; } protected final int getDeviceRotation() { final int orientation; DisplayManager dm = (DisplayManager) ContextUtils.getApplicationContext().getSystemService( Context.DISPLAY_SERVICE); switch (dm.getDisplay(Display.DEFAULT_DISPLAY).getRotation()) { case Surface.ROTATION_90: orientation = 90; break; case Surface.ROTATION_180: orientation = 180; break; case Surface.ROTATION_270: orientation = 270; break; case Surface.ROTATION_0: default: orientation = 0; break; } return orientation; } // {@link VideoCaptureJni.get().onPhotoTaken()} needs to be called back if there's any // problem after {@link takePhotoAsync()} has returned true. protected void notifyTakePhotoError(long callbackId) { VideoCaptureJni.get().onPhotoTaken( mNativeVideoCaptureDeviceAndroid, VideoCapture.this, callbackId, null); } /** * Finds the framerate range matching |targetFramerate|. Tries to find a range with as low of a * minimum value as possible to allow the camera adjust based on the lighting conditions. * Assumes that all framerate values are multiplied by 1000. * * This code is mostly copied from WebRTC: * CameraEnumerationAndroid.getClosestSupportedFramerateRange * in webrtc/api/android/java/src/org/webrtc/CameraEnumerationAndroid.java */ protected static FramerateRange getClosestFramerateRange( final List<FramerateRange> framerateRanges, final int targetFramerate) { return Collections.min(framerateRanges, new Comparator<FramerateRange>() { // Threshold and penalty weights if the upper bound is further away than // |MAX_FPS_DIFF_THRESHOLD| from requested. private static final int MAX_FPS_DIFF_THRESHOLD = 5000; private static final int MAX_FPS_LOW_DIFF_WEIGHT = 1; private static final int MAX_FPS_HIGH_DIFF_WEIGHT = 3; // Threshold and penalty weights if the lower bound is bigger than |MIN_FPS_THRESHOLD|. private static final int MIN_FPS_THRESHOLD = 8000; private static final int MIN_FPS_LOW_VALUE_WEIGHT = 1; private static final int MIN_FPS_HIGH_VALUE_WEIGHT = 4; // Use one weight for small |value| less than |threshold|, and another weight above. private int progressivePenalty( int value, int threshold, int lowWeight, int highWeight) { return (value < threshold) ? value * lowWeight : threshold * lowWeight + (value - threshold) * highWeight; } int diff(FramerateRange range) { final int minFpsError = progressivePenalty(range.min, MIN_FPS_THRESHOLD, MIN_FPS_LOW_VALUE_WEIGHT, MIN_FPS_HIGH_VALUE_WEIGHT); final int maxFpsError = progressivePenalty(Math.abs(targetFramerate - range.max), MAX_FPS_DIFF_THRESHOLD, MAX_FPS_LOW_DIFF_WEIGHT, MAX_FPS_HIGH_DIFF_WEIGHT); return minFpsError + maxFpsError; } @Override public int compare(FramerateRange range1, FramerateRange range2) { return diff(range1) - diff(range2); } }); } protected static int[] integerArrayListToArray(ArrayList<Integer> intArrayList) { int[] intArray = new int[intArrayList.size()]; for (int i = 0; i < intArrayList.size(); i++) { intArray[i] = intArrayList.get(i).intValue(); } return intArray; } @NativeMethods interface Natives { // Method for VideoCapture implementations to call back native code. void onFrameAvailable(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, byte[] data, int length, int rotation); void onI420FrameAvailable(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, ByteBuffer yBuffer, int yStride, ByteBuffer uBuffer, ByteBuffer vBuffer, int uvRowStride, int uvPixelStride, int width, int height, int rotation, long timestamp); // Method for VideoCapture implementations to signal an asynchronous error. void onError(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, int androidVideoCaptureError, String message); // Method for VideoCapture implementations to signal that a frame was dropped. void onFrameDropped(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, int androidVideoCaptureFrameDropReason); void onGetPhotoCapabilitiesReply(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, long callbackId, PhotoCapabilities result); // Callback for calls to takePhoto(). This can indicate both success and // failure. Failure is indicated by |data| being null. void onPhotoTaken(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, long callbackId, byte[] data); // Method for VideoCapture implementations to report device started event. void onStarted(long nativeVideoCaptureDeviceAndroid, VideoCapture caller); void dCheckCurrentlyOnIncomingTaskRunner( long nativeVideoCaptureDeviceAndroid, VideoCapture caller); } }
youtube/cobalt
third_party/chromium/media/capture/video/android/java/src/org/chromium/media/VideoCapture.java
Java
bsd-3-clause
11,938
// This file was generated by the _js_query_arg_file Skylark rule defined in // maps/vectortown/performance/script/build_defs.bzl. var testConfig = "overridePixelRatio=1&title=chrome_smoothness_performancetest_config&nobudget=false&nodraw=false&noprefetch=true&viewport=basic&wait=true";
scheib/chromium
tools/perf/page_sets/maps_perf_test/config.js
JavaScript
bsd-3-clause
289
testTransport = function(transports) { var prefix = "socketio - " + transports + ": "; connect = function(transports) { // Force transport io.transports = transports; deepEqual(io.transports, transports, "Force transports"); var options = { 'force new connection': true } return io.connect('/test', options); } asyncTest(prefix + "Connect", function() { expect(4); test = connect(transports); test.on('connect', function () { ok( true, "Connected with transport: " + test.socket.transport.name ); test.disconnect(); }); test.on('disconnect', function (reason) { ok( true, "Disconnected - " + reason ); test.socket.disconnect(); start(); }); test.on('connect_failed', function () { ok( false, "Connection failed"); start(); }); }); asyncTest(prefix + "Emit with ack", function() { expect(3); test = connect(transports); test.emit('requestack', 1, function (val1, val2) { equal(val1, 1); equal(val2, "ack"); test.disconnect(); test.socket.disconnect(); start(); }); }); asyncTest(prefix + "Emit with ack one return value", function() { expect(2); test = connect(transports); test.emit('requestackonevalue', 1, function (val1) { equal(val1, 1); test.disconnect(); test.socket.disconnect(); start(); }); }); } transports = [io.transports]; // Validate individual transports for(t in io.transports) { if(io.Transport[io.transports[t]].check()) { transports.push([io.transports[t]]); } } for(t in transports) { testTransport(transports[t]) }
grokcore/dev.lexycross
wordsmithed/src/gevent-socketio/tests/jstests/tests/suite.js
JavaScript
mit
1,679
<?php namespace SMW\Tests\DataValues; use SMW\DataValues\ImportValue; /** * @covers \SMW\DataValues\ImportValue * * @group semantic-mediawiki * * @license GNU GPL v2+ * @since 2.2 * * @author mwjames */ class ImportValueTest extends \PHPUnit_Framework_TestCase { public function testCanConstruct() { $this->assertInstanceOf( '\SMW\DataValues\ImportValue', new ImportValue( '__imp' ) ); // FIXME Legacy naming remove in 3.x $this->assertInstanceOf( '\SMWImportValue', new ImportValue( '__imp' ) ); } public function testErrorForInvalidUserValue() { $instance = new ImportValue( '__imp' ); $instance->setUserValue( 'FooBar' ); $this->assertEquals( 'FooBar', $instance->getWikiValue() ); $this->assertNotEmpty( $instance->getErrors() ); } }
owen-kellie-smith/mediawiki
wiki/extensions/SemanticMediaWiki/tests/phpunit/includes/DataValues/ImportValueTest.php
PHP
mit
805
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Security.Policy.Hash.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Security.Policy { sealed public partial class Hash : EvidenceBase, System.Runtime.Serialization.ISerializable { #region Methods and constructors public override EvidenceBase Clone() { return default(EvidenceBase); } public static System.Security.Policy.Hash CreateMD5(byte[] md5) { Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null); return default(System.Security.Policy.Hash); } public static System.Security.Policy.Hash CreateSHA1(byte[] sha1) { Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null); return default(System.Security.Policy.Hash); } public static System.Security.Policy.Hash CreateSHA256(byte[] sha256) { Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null); return default(System.Security.Policy.Hash); } public byte[] GenerateHash(System.Security.Cryptography.HashAlgorithm hashAlg) { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public Hash(System.Reflection.Assembly assembly) { Contract.Ensures(!assembly.IsDynamic); } public override string ToString() { return default(string); } #endregion #region Properties and indexers public byte[] MD5 { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } public byte[] SHA1 { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } public byte[] SHA256 { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } #endregion } }
ndykman/CodeContracts
Microsoft.Research/Contracts/MsCorlib/Sources/System.Security.Policy.Hash.cs
C#
mit
3,951
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Product\Resolver; use Doctrine\Common\Collections\Collection; use Sylius\Component\Product\Model\ProductInterface; use Sylius\Component\Product\Model\ProductOptionInterface; use Sylius\Component\Product\Model\ProductOptionValueInterface; final class AvailableProductOptionValuesResolver implements AvailableProductOptionValuesResolverInterface { public function resolve(ProductInterface $product, ProductOptionInterface $productOption): Collection { if (!$product->hasOption($productOption)) { throw new \InvalidArgumentException( sprintf( 'Cannot resolve available product option values. Option "%s" does not belong to product "%s".', $product->getCode(), $productOption->getCode() ) ); } return $productOption->getValues()->filter( static function (ProductOptionValueInterface $productOptionValue) use ($product) { foreach ($product->getEnabledVariants() as $productVariant) { if ($productVariant->hasOptionValue($productOptionValue)) { return true; } } return false; } ); } }
loic425/Sylius
src/Sylius/Component/Product/Resolver/AvailableProductOptionValuesResolver.php
PHP
mit
1,552
/*************************************************************************** * Copyright (C) 2007 by Tarek Saidi * * tarek.saidi@arcor.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; version 2 of the License. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <QTreeWidget> #include <QPainter> #include <QPaintEvent> #include <QResizeEvent> #include "main.h" #include "TrashCanDlg.h" TrashCanDialog::TrashCanDialog(QWidget* parent,IDatabase* database,const QList<IEntryHandle*>& TrashItems):QDialog(parent){ setupUi(this); Entries=TrashItems; for(int i=0;i<Entries.size();i++){ QTreeWidgetItem* item=new QTreeWidgetItem(treeWidget); item->setData(0,Qt::UserRole,i); item->setText(0,Entries[i]->group()->title()); item->setText(1,Entries[i]->title()); item->setText(2,Entries[i]->username()); item->setText(3,Entries[i]->expire().dateToString(Qt::LocalDate)); item->setIcon(0,database->icon(Entries[i]->group()->image())); item->setIcon(1,database->icon(Entries[i]->image())); } connect(treeWidget,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(OnItemDoubleClicked(QTreeWidgetItem*))); connect(treeWidget,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(OnContextMenu(const QPoint&))); ContextMenu=new QMenu(this); ContextMenu->addAction(getIcon("restore"),"Restore"); ContextMenu->addAction(getIcon("deleteentry"),"Delete"); } void TrashCanDialog::paintEvent(QPaintEvent* event){ QDialog::paintEvent(event); QPainter painter(this); painter.setClipRegion(event->region()); painter.drawPixmap(QPoint(0,0),BannerPixmap); } void TrashCanDialog::resizeEvent(QResizeEvent* event){ createBanner(&BannerPixmap,getPixmap("trashcan"),tr("Recycle Bin"),width()); QDialog::resizeEvent(event); } void TrashCanDialog::OnItemDoubleClicked(QTreeWidgetItem* item){ SelectedEntry=Entries[item->data(0,Qt::UserRole).toInt()]; accept(); } void TrashCanDialog::OnContextMenu(const QPoint& pos){ if(treeWidget->itemAt(pos)){ QTreeWidgetItem* item=treeWidget->itemAt(pos); if(treeWidget->selectedItems().size()==0){ treeWidget->setItemSelected(item,true); } else{ if(!treeWidget->isItemSelected(item)){ while(treeWidget->selectedItems().size()){ treeWidget->setItemSelected(treeWidget->selectedItems()[0],false); } treeWidget->setItemSelected(item,true); } } } else { while(treeWidget->selectedItems().size()) treeWidget->setItemSelected(treeWidget->selectedItems()[0],false); } ContextMenu->popup(treeWidget->viewport()->mapToGlobal(pos)); } ///TODO 0.2.3 locale aware string/date compare for correct sorting
dwihn0r/keepassx
src/dialogs/TrashCanDlg.cpp
C++
gpl-2.0
3,752
// 2005-12-01 Paolo Carlini <pcarlini@suse.de> // Copyright (C) 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/>. // { dg-do compile } #include <vector> namespace N { struct X { }; template<typename T> X operator+(T, std::size_t) { return X(); } template<typename T> X operator-(T, T) { return X(); } } int main() { std::vector<N::X> v(5); const std::vector<N::X> w(1); v[0]; w[0]; v.size(); v.capacity(); v.resize(1); v.insert(v.begin(), N::X()); v.insert(v.begin(), 1, N::X()); v.insert(v.begin(), w.begin(), w.end()); v = w; return 0; }
embecosm/avr32-gcc
libstdc++-v3/testsuite/23_containers/vector/types/1.cc
C++
gpl-2.0
1,294
/* * This file is part of the cSploit. * * Copyleft of Massimo Dragano aka tux_mind <tux_mind@csploit.org> * * cSploit 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. * * cSploit 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 cSploit. If not, see <http://www.gnu.org/licenses/>. */ package org.csploit.android.tools; import org.csploit.android.core.ChildManager; import org.csploit.android.core.System; import org.csploit.android.core.Child; import org.csploit.android.core.Logger; import org.csploit.android.events.Event; import org.csploit.android.events.Host; import org.csploit.android.events.HostLost; import java.net.InetAddress; public class NetworkRadar extends Tool { public NetworkRadar() { mHandler = "network-radar"; mCmdPrefix = null; } public static abstract class HostReceiver extends Child.EventReceiver { public abstract void onHostFound(byte[] macAddress, InetAddress ipAddress, String name); public abstract void onHostLost(InetAddress ipAddress); public void onEvent(Event e) { if ( e instanceof Host ) { Host h = (Host)e; onHostFound(h.ethAddress, h.ipAddress, h.name); } else if ( e instanceof HostLost ) { onHostLost(((HostLost)e).ipAddress); } else { Logger.error("Unknown event: " + e); } } } public Child start(HostReceiver receiver) throws ChildManager.ChildNotStartedException { String ifName; ifName = System.getNetwork().getInterface().getDisplayName(); return async(ifName, receiver); } }
odin1314/android
cSploit/src/org/csploit/android/tools/NetworkRadar.java
Java
gpl-3.0
2,001
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.function.pattern; import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BaseBlock; import static com.google.common.base.Preconditions.checkNotNull; /** * A pattern that returns the same {@link BaseBlock} each time. */ public class BlockPattern extends AbstractPattern { private BaseBlock block; /** * Create a new pattern with the given block. * * @param block the block */ public BlockPattern(BaseBlock block) { setBlock(block); } /** * Get the block. * * @return the block that is always returned */ public BaseBlock getBlock() { return block; } /** * Set the block that is returned. * * @param block the block */ public void setBlock(BaseBlock block) { checkNotNull(block); this.block = block; } @Override public BaseBlock apply(Vector position) { return block; } }
UnlimitedFreedom/UF-WorldEdit
worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java
Java
gpl-3.0
1,799
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_sql_user_info description: - Gather info for GCP User short_description: Gather info for GCP User version_added: '2.8' author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: instance: description: - The name of the Cloud SQL instance. This does not include the project ID. - 'This field represents a link to a Instance resource in GCP. It can be specified in two ways. First, you can place a dictionary with key ''name'' and value of your resource''s name Alternatively, you can add `register: name-of-resource` to a gcp_sql_instance task and then set this instance field to "{{ name-of-resource }}"' required: true type: dict project: description: - The Google Cloud Platform project to use. type: str auth_kind: description: - The type of credential used. type: str required: true choices: - application - machineaccount - serviceaccount service_account_contents: description: - The contents of a Service Account JSON file, either in a dictionary or as a JSON string that represents it. type: jsonarg service_account_file: description: - The path of a Service Account JSON file if serviceaccount is selected as type. type: path service_account_email: description: - An optional service account email address if machineaccount is selected and the user does not wish to use the default email. type: str scopes: description: - Array of scopes to be used type: list env_type: description: - Specifies which Ansible environment you're running this module within. - This should not be set unless you know what you're doing. - This only alters the User Agent string for any API requests. type: str notes: - for authentication, you can set service_account_file using the C(gcp_service_account_file) env variable. - for authentication, you can set service_account_contents using the C(GCP_SERVICE_ACCOUNT_CONTENTS) env variable. - For authentication, you can set service_account_email using the C(GCP_SERVICE_ACCOUNT_EMAIL) env variable. - For authentication, you can set auth_kind using the C(GCP_AUTH_KIND) env variable. - For authentication, you can set scopes using the C(GCP_SCOPES) env variable. - Environment variables values will only be used if the playbook values are not set. - The I(service_account_email) and I(service_account_file) options are mutually exclusive. ''' EXAMPLES = ''' - name: get info on a user gcp_sql_user_info: instance: "{{ instance }}" project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" ''' RETURN = ''' resources: description: List of resources returned: always type: complex contains: host: description: - The host name from which the user can connect. For insert operations, host defaults to an empty string. For update operations, host is specified as part of the request URL. The host name cannot be updated after insertion. returned: success type: str name: description: - The name of the user in the Cloud SQL instance. returned: success type: str instance: description: - The name of the Cloud SQL instance. This does not include the project ID. returned: success type: dict password: description: - The password for the user. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, replace_resource_dict import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule(argument_spec=dict(instance=dict(required=True, type='dict'))) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/sqlservice.admin'] return_value = {'resources': fetch_list(module, collection(module))} module.exit_json(**return_value) def collection(module): res = {'project': module.params['project'], 'instance': replace_resource_dict(module.params['instance'], 'name')} return "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/users".format(**res) def fetch_list(module, link): auth = GcpSession(module, 'sql') return auth.list(link, return_if_object, array_name='items') def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main()
anryko/ansible
lib/ansible/modules/cloud/google/gcp_sql_user_info.py
Python
gpl-3.0
6,527
var searchData= [ ['print',['PRINT',['../_m_d___parola__lib_8h.html#a1696fc35fb931f8c876786fbc1078ac4',1,'MD_Parola_lib.h']]], ['print_5fstate',['PRINT_STATE',['../_m_d___parola__lib_8h.html#a3fda4e1a5122a16a21bd96ae5217402c',1,'MD_Parola_lib.h']]], ['prints',['PRINTS',['../_m_d___parola__lib_8h.html#ad68f35c3cfe67be8d09d1cea8e788e13',1,'MD_Parola_lib.h']]], ['printx',['PRINTX',['../_m_d___parola__lib_8h.html#abf55b44e8497cbc3addccdeb294138cc',1,'MD_Parola_lib.h']]] ];
javastraat/arduino
libraries/MD_Parola/doc/html/search/defines_70.js
JavaScript
gpl-3.0
482
/* * Copyright 2008, 2009 Google Inc. * Copyright 2006, 2007 Nintendo Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include <es/any.h> #include <es/endian.h> #include <es/formatter.h> #include <es/interfaceData.h> #include <es/object.h> #include <es/base/IProcess.h> #include <es/hashtable.h> #include <es/reflect.h> // TODO use proper name prefix or namespace namespace es { Reflect::Interface& getInterface(const char* iid); Object* getConstructor(const char* iid); extern unsigned char* defaultInterfaceInfo[]; extern size_t defaultInterfaceCount; } // namespace es #ifndef VERBOSE #define PRINTF(...) (__VA_ARGS__) #else #define PRINTF(...) report(__VA_ARGS__) #endif class ObjectValue; #include "interface.h" extern es::CurrentProcess* System(); namespace { const int GuidStringLength = 37; // Including terminating zero } // // invoke // typedef long long (*InterfaceMethod)(void* self, ...); static char heap[64*1024]; static Value* invoke(const char* iid, int number, InterfaceMethod** self, ListValue* list) { if (!self) { throw getErrorInstance("TypeError"); } Reflect::Interface interface = es::getInterface(iid); Reflect::Method method(interface.getMethod(number)); PRINTF("invoke %s.%s(%p)\n", interface.getName().c_str(), method.getName().c_str(), self); // Set up parameters Any argv[9]; Any* argp = argv; int ext = 0; // extra parameter count // Set this *argp++ = Any(reinterpret_cast<intptr_t>(self)); // In the following implementation, we assume no out nor inout attribute is // used for parameters. Reflect::Type returnType = method.getReturnType(); switch (returnType.getType()) { case Reflect::kAny: // Any op(void* buf, int len, ...); // FALL THROUGH case Reflect::kString: // const char* op(xxx* buf, int len, ...); *argp++ = Any(reinterpret_cast<intptr_t>(heap)); *argp++ = Any(sizeof(heap)); break; case Reflect::kSequence: // int op(xxx* buf, int len, ...); *argp++ = Any(reinterpret_cast<intptr_t>(heap)); ++ext; *argp++ = Any(static_cast<int32_t>(((*list)[0])->toNumber())); break; case Reflect::kArray: // void op(xxx[x] buf, ...); *argp++ = Any(reinterpret_cast<intptr_t>(heap)); break; } Reflect::Parameter param = method.listParameter(); for (int i = ext; param.next(); ++i, ++argp) { Reflect::Type type(param.getType()); Value* value = (*list)[i]; switch (type.getType()) { case Reflect::kAny: // Any variant, ... switch (value->getType()) { case Value::BoolType: *argp = Any(static_cast<bool>(value->toBoolean())); break; case Value::StringType: *argp = Any(value->toString().c_str()); break; case Value::NumberType: *argp = Any(static_cast<double>(value->toNumber())); break; case Value::ObjectType: if (InterfacePointerValue* unknown = dynamic_cast<InterfacePointerValue*>(value)) { *argp = Any(unknown->getObject()); } else { // XXX expose ECMAScript object *argp = Any(static_cast<Object*>(0)); } break; default: *argp = Any(); break; } argp->makeVariant(); break; case Reflect::kSequence: // xxx* buf, int len, ... // XXX Assume sequence<octet> now... *argp++ = Any(reinterpret_cast<intptr_t>(value->toString().c_str())); value = (*list)[++i]; *argp = Any(static_cast<int32_t>(value->toNumber())); break; case Reflect::kString: *argp = Any(value->toString().c_str()); break; case Reflect::kArray: // void op(xxx[x] buf, ...); // XXX expand data break; case Reflect::kObject: if (InterfacePointerValue* unknown = dynamic_cast<InterfacePointerValue*>(value)) { *argp = Any(unknown->getObject()); } else { *argp = Any(static_cast<Object*>(0)); } break; case Reflect::kBoolean: *argp = Any(static_cast<bool>(value->toBoolean())); break; case Reflect::kPointer: *argp = Any(static_cast<intptr_t>(value->toNumber())); break; case Reflect::kShort: *argp = Any(static_cast<int16_t>(value->toNumber())); break; case Reflect::kLong: *argp = Any(static_cast<int32_t>(value->toNumber())); break; case Reflect::kOctet: *argp = Any(static_cast<uint8_t>(value->toNumber())); break; case Reflect::kUnsignedShort: *argp = Any(static_cast<uint16_t>(value->toNumber())); break; case Reflect::kUnsignedLong: *argp = Any(static_cast<uint32_t>(value->toNumber())); break; case Reflect::kLongLong: *argp = Any(static_cast<int64_t>(value->toNumber())); break; case Reflect::kUnsignedLongLong: *argp = Any(static_cast<uint64_t>(value->toNumber())); break; case Reflect::kFloat: *argp = Any(static_cast<float>(value->toNumber())); break; case Reflect::kDouble: *argp = Any(static_cast<double>(value->toNumber())); break; default: break; } } // Invoke method Register<Value> value; unsigned methodNumber = interface.getInheritedMethodCount() + number; int argc = argp - argv; switch (returnType.getType()) { case Reflect::kAny: { Any result = apply(argc, argv, (Any (*)()) ((*self)[methodNumber])); switch (result.getType()) { case Any::TypeVoid: value = NullValue::getInstance(); break; case Any::TypeBool: value = BoolValue::getInstance(static_cast<bool>(result)); break; case Any::TypeOctet: value = new NumberValue(static_cast<uint8_t>(result)); break; case Any::TypeShort: value = new NumberValue(static_cast<int16_t>(result)); break; case Any::TypeUnsignedShort: value = new NumberValue(static_cast<uint16_t>(result)); break; case Any::TypeLong: value = new NumberValue(static_cast<int32_t>(result)); break; case Any::TypeUnsignedLong: value = new NumberValue(static_cast<uint32_t>(result)); break; case Any::TypeLongLong: value = new NumberValue(static_cast<int64_t>(result)); break; case Any::TypeUnsignedLongLong: value = new NumberValue(static_cast<uint64_t>(result)); break; case Any::TypeFloat: value = new NumberValue(static_cast<float>(result)); break; case Any::TypeDouble: value = new NumberValue(static_cast<double>(result)); break; case Any::TypeString: if (const char* string = static_cast<const char*>(result)) { value = new StringValue(string); } else { value = NullValue::getInstance(); } break; case Any::TypeObject: if (Object* unknown = static_cast<Object*>(result)) { ObjectValue* instance = new InterfacePointerValue(unknown); instance->setPrototype(getGlobal()->get(es::getInterface(Object::iid()).getName())->get("prototype")); // XXX Should use IID value = instance; } else { value = NullValue::getInstance(); } break; default: value = NullValue::getInstance(); break; } } break; case Reflect::kBoolean: value = BoolValue::getInstance(static_cast<bool>(apply(argc, argv, (bool (*)()) ((*self)[methodNumber])))); break; case Reflect::kOctet: value = new NumberValue(static_cast<uint8_t>(apply(argc, argv, (uint8_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kShort: value = new NumberValue(static_cast<int16_t>(apply(argc, argv, (int16_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kUnsignedShort: value = new NumberValue(static_cast<uint16_t>(apply(argc, argv, (uint16_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kLong: value = new NumberValue(static_cast<int32_t>(apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kUnsignedLong: value = new NumberValue(static_cast<uint32_t>(apply(argc, argv, (uint32_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kLongLong: value = new NumberValue(static_cast<int64_t>(apply(argc, argv, (int64_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kUnsignedLongLong: value = new NumberValue(static_cast<uint64_t>(apply(argc, argv, (uint64_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kFloat: value = new NumberValue(static_cast<float>(apply(argc, argv, (float (*)()) ((*self)[methodNumber])))); break; case Reflect::kDouble: value = new NumberValue(apply(argc, argv, (double (*)()) ((*self)[methodNumber]))); break; case Reflect::kPointer: value = new NumberValue(static_cast<intptr_t>(apply(argc, argv, (intptr_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kString: { heap[0] = '\0'; Any result = apply(argc, argv, (const char* (*)()) ((*self)[methodNumber])); if (const char* string = static_cast<const char*>(result)) { value = new StringValue(string); } else { value = NullValue::getInstance(); } } break; case Reflect::kSequence: { // XXX Assume sequence<octet> now... int32_t count = apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber])); if (count < 0) { count = 0; } heap[count] = '\0'; value = new StringValue(heap); } break; case Reflect::kObject: if (Object* unknown = apply(argc, argv, (Object* (*)()) ((*self)[methodNumber]))) { ObjectValue* instance = new InterfacePointerValue(unknown); // TODO: check Object and others instance->setPrototype(getGlobal()->get(es::getInterface(returnType.getQualifiedName().c_str()).getName())->get("prototype")); // XXX Should use IID value = instance; } else { value = NullValue::getInstance(); } break; case Reflect::kVoid: apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber])); value = NullValue::getInstance(); break; } return value; } static Value* invoke(const char* iid, int number, InterfacePointerValue* object, ListValue* list) { InterfaceMethod** self = reinterpret_cast<InterfaceMethod**>(object->getObject()); if (!self) { throw getErrorInstance("TypeError"); } Value* value = invoke(iid, number, self, list); if (strcmp(iid, Object::iid()) == 0 && number == 2) // Object::release() { object->clearObject(); } return value; } // // AttributeValue // class AttributeValue : public ObjectValue { bool readOnly; const char* iid; int getter; // Method number int setter; // Method number public: AttributeValue(const char* iid) : readOnly(true), iid(iid), getter(0), setter(0) { } ~AttributeValue() { } void addSetter(int number) { readOnly = false; setter = number; } void addGetter(int number) { getter = number; } // Getter virtual Value* get(Value* self) { if (dynamic_cast<InterfacePointerValue*>(self)) { Register<ListValue> list = new ListValue; return invoke(iid, getter, static_cast<InterfacePointerValue*>(self), list); } else { return this; } } // Setter virtual bool put(Value* self, Value* value) { if (dynamic_cast<InterfacePointerValue*>(self) && !readOnly) { Register<ListValue> list = new ListValue; list->push(value); invoke(iid, setter, static_cast<InterfacePointerValue*>(self), list); } return true; } }; // // InterfaceMethodCode // class InterfaceMethodCode : public Code { FormalParameterList* arguments; ObjectValue* prototype; const char* iid; int number; // Method number public: InterfaceMethodCode(ObjectValue* object, const char* iid, int number) : arguments(new FormalParameterList), prototype(new ObjectValue), iid(iid), number(number) { Reflect::Interface interface = es::getInterface(iid); Reflect::Method method(interface.getMethod(number)); #if 0 // Add as many arguments as required. for (int i = 0; i < method.getParameterCount(); ++i) { Reflect::Parameter param(method.getParameter(i)); if (param.isInput()) { // Note the name "arguments" is reserved in a ECMAScript function. ASSERT(strcmp(param.getName(), "arguments") != 0); arguments->add(new Identifier(param.getName())); } } #endif object->setParameterList(arguments); object->setScope(getGlobal()); // Create Interface.prototype prototype->put("constructor", object); object->put("prototype", prototype); } ~InterfaceMethodCode() { delete arguments; } CompletionType evaluate() { InterfacePointerValue* object = dynamic_cast<InterfacePointerValue*>(getThis()); if (!object) { throw getErrorInstance("TypeError"); } ListValue* list = static_cast<ListValue*>(getScopeChain()->get("arguments")); Register<Value> value = invoke(iid, number, object, list); return CompletionType(CompletionType::Return, value, ""); } }; // // AttributeSetterValue // class AttributeSetterValue : public ObjectValue { const char* iid; int number; // Method number public: AttributeSetterValue(const char* iid, int number) : iid(iid), number(number) { } ~AttributeSetterValue() { } void put(Value* self, const std::string& name, Value* value) { Register<ListValue> list = new ListValue; Register<StringValue> ident = new StringValue(name); list->push(ident); list->push(value); invoke(iid, number, static_cast<InterfacePointerValue*>(self), list); return; } }; // // AttributeGetterValue // class AttributeGetterValue : public ObjectValue { const char* iid; int number; // Method number public: AttributeGetterValue(const char* iid, int number) : iid(iid), number(number) { } ~AttributeGetterValue() { } Value* get(Value* self, const std::string& name) { Register<ListValue> list = new ListValue; Register<StringValue> ident = new StringValue(name); list->push(ident); return invoke(iid, number, static_cast<InterfacePointerValue*>(self), list); } }; // // InterfacePrototypeValue // class InterfacePrototypeValue : public ObjectValue { enum OpObject { IndexGetter, IndexSetter, NameGetter, NameSetter, ObjectCount }; ObjectValue* opObjects[ObjectCount]; public: InterfacePrototypeValue() { for (int i = 0; i < ObjectCount; ++i) { opObjects[i] = 0; } } ~InterfacePrototypeValue() { } void setOpObject(int op, ObjectValue* object) { ASSERT(op >= 0 && op < ObjectCount); opObjects[op] = object; } ObjectValue* getOpObject(int op) { ASSERT(op >= 0 && op < ObjectCount); return opObjects[op]; } friend class InterfaceConstructor; friend class InterfacePointerValue; }; // // InterfaceConstructor // class InterfaceConstructor : public Code { ObjectValue* constructor; FormalParameterList* arguments; InterfacePrototypeValue* prototype; std::string iid; public: InterfaceConstructor(ObjectValue* object, std::string iid) : constructor(object), arguments(new FormalParameterList), prototype(new InterfacePrototypeValue), iid(iid) { arguments->add(new Identifier("object")); object->setParameterList(arguments); object->setScope(getGlobal()); Reflect::Interface interface = es::getInterface(iid.c_str()); // PRINTF("interface: %s\n", interface.getName().c_str()); for (int i = 0; i < interface.getMethodCount(); ++i) { // Construct Method object Reflect::Method method(interface.getMethod(i)); if (prototype->hasProperty(method.getName())) { if (method.isOperation()) { // XXX Currently overloaded functions are just ignored. } else { AttributeValue* attribute = static_cast<AttributeValue*>(prototype->get(method.getName())); if (method.isGetter()) { attribute->addGetter(i); } else { attribute->addSetter(i); } } } else { if (method.isOperation()) { ObjectValue* function = new ObjectValue; function->setCode(new InterfaceMethodCode(function, iid.c_str(), i)); prototype->put(method.getName(), function); #if 0 if (method.isIndexGetter()) { AttributeGetterValue* getter = new AttributeGetterValue(iid, i); prototype->setOpObject(InterfacePrototypeValue::IndexGetter, getter); } else if (method.isIndexSetter()) { AttributeSetterValue* setter = new AttributeSetterValue(iid, i); prototype->setOpObject(InterfacePrototypeValue::IndexSetter, setter); } else if (method.isNameGetter()) { AttributeGetterValue* getter = new AttributeGetterValue(iid, i); prototype->setOpObject(InterfacePrototypeValue::NameGetter, getter); } else if (method.isNameSetter()) { AttributeSetterValue* setter = new AttributeSetterValue(iid, i); prototype->setOpObject(InterfacePrototypeValue::NameSetter, setter); } #endif } else { // method is an attribute AttributeValue* attribute = new AttributeValue(iid.c_str()); if (method.isGetter()) { attribute->addGetter(i); } else { attribute->addSetter(i); } prototype->put(method.getName(), attribute); } } } if (interface.getQualifiedSuperName() == "") { prototype->setPrototype(getGlobal()->get("InterfaceStore")->getPrototype()->getPrototype()); } else { Reflect::Interface super = es::getInterface(interface.getQualifiedSuperName().c_str()); prototype->setPrototype(getGlobal()->get(super.getName())->get("prototype")); } // Create Interface.prototype prototype->put("constructor", object); object->put("prototype", prototype); } ~InterfaceConstructor() { delete arguments; } // Query interface for this interface. CompletionType evaluate() { if (constructor->hasInstance(getThis())) { // Constructor Object* constructor = es::getConstructor(iid.c_str()); if (!constructor) { throw getErrorInstance("TypeError"); } // TODO: Currently only the default constructor is supported std::string ciid = iid; ciid += "::Constructor"; Value* value = invoke(ciid.c_str(), 0, reinterpret_cast<InterfaceMethod**>(constructor), 0); return CompletionType(CompletionType::Return, value, ""); } else { // Cast InterfacePointerValue* self = dynamic_cast<InterfacePointerValue*>(getScopeChain()->get("object")); if (!self) { throw getErrorInstance("TypeError"); } Object* object; object = self->getObject(); if (!object || !(object = reinterpret_cast<Object*>(object->queryInterface(iid.c_str())))) { // We should throw an error in case called by a new expression. throw getErrorInstance("TypeError"); } ObjectValue* value = new InterfacePointerValue(object); value->setPrototype(prototype); return CompletionType(CompletionType::Return, value, ""); } } }; // // InterfaceStoreConstructor // class InterfaceStoreConstructor : public Code { FormalParameterList* arguments; ObjectValue* prototype; // Interface.prototype public: InterfaceStoreConstructor(ObjectValue* object) : arguments(new FormalParameterList), prototype(new ObjectValue) { ObjectValue* function = static_cast<ObjectValue*>(getGlobal()->get("Function")); arguments->add(new Identifier("iid")); object->setParameterList(arguments); object->setScope(getGlobal()); // Create Interface.prototype prototype->setPrototype(function->getPrototype()->getPrototype()); prototype->put("constructor", object); object->put("prototype", prototype); object->setPrototype(function->getPrototype()); } ~InterfaceStoreConstructor() { delete arguments; } CompletionType evaluate() { Value* value = getScopeChain()->get("iid"); if (!value->isString()) { throw getErrorInstance("TypeError"); } const char* iid = value->toString().c_str(); Reflect::Interface interface; try { interface = es::getInterface(iid); } catch (...) { throw getErrorInstance("TypeError"); } // Construct Interface Object ObjectValue* object = new ObjectValue; object->setCode(new InterfaceConstructor(object, iid)); object->setPrototype(prototype); return CompletionType(CompletionType::Return, object, ""); } }; static bool isIndexAccessor(const std::string& name) { const char* ptr = name.c_str(); bool hex = false; if (strncasecmp(ptr, "0x", 2) == 0) { ptr += 2; hex = true; } while(*ptr) { if (hex) { if (!isxdigit(*ptr)) { return false; } } else { if (!isdigit(*ptr)) { return false; } } ptr++; } return true; } Value* InterfacePointerValue::get(const std::string& name) { InterfacePrototypeValue* proto = static_cast<InterfacePrototypeValue*>(prototype); AttributeGetterValue* getter; if (hasProperty(name)) { return ObjectValue::get(name); } else if ((getter = static_cast<AttributeGetterValue*>(proto->getOpObject(InterfacePrototypeValue::IndexGetter))) && isIndexAccessor(name)) { return getter->get(this, name); } else if ((getter = static_cast<AttributeGetterValue*>(proto->getOpObject(InterfacePrototypeValue::NameGetter)))) { return getter->get(this, name); } else { return ObjectValue::get(name); } } void InterfacePointerValue::put(const std::string& name, Value* value, int attributes) { InterfacePrototypeValue* proto = static_cast<InterfacePrototypeValue*>(prototype); AttributeSetterValue* setter; if (!canPut(name)) { return; } if (hasProperty(name)) { ObjectValue::put(name, value, attributes); } else if ((setter = static_cast<AttributeSetterValue*>(proto->getOpObject(InterfacePrototypeValue::IndexSetter))) && isIndexAccessor(name)) { setter->put(this, name, value); } else if ((setter = static_cast<AttributeSetterValue*>(proto->getOpObject(InterfacePrototypeValue::NameSetter)))) { setter->put(this, name, value); } else { ObjectValue::put(name, value, attributes); } } ObjectValue* constructInterfaceObject() { ObjectValue* object = new ObjectValue; object->setCode(new InterfaceStoreConstructor(object)); return object; } ObjectValue* constructSystemObject(void* system) { for (es::InterfaceData* data = es::interfaceData; data->iid; ++data) { // Construct Default Interface Object Reflect::Interface interface = es::getInterface(data->iid()); PRINTF("%s\n", interface.getName().c_str()); ObjectValue* object = new ObjectValue; object->setCode(new InterfaceConstructor(object, interface.getQualifiedName())); object->setPrototype(getGlobal()->get("InterfaceStore")->getPrototype()); getGlobal()->put(interface.getName(), object); } System()->addRef(); ObjectValue* object = new InterfacePointerValue(System()); object->setPrototype(getGlobal()->get("CurrentProcess")->get("prototype")); return object; }
LambdaLord/es-operating-system
esjs/src/interface.cpp
C++
apache-2.0
28,073
/** * Copyright 2009-2015 the original author or 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 org.apache.ibatis.domain.misc.generics; public abstract class GenericSubclass extends GenericAbstract<Long> { @Override public abstract Long getId(); }
macs524/mybatis_learn
src/test/java/org/apache/ibatis/domain/misc/generics/GenericSubclass.java
Java
apache-2.0
819
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" using namespace cv; using namespace cv::cuda; #if !defined (HAVE_CUDA) || defined (CUDA_DISABLER) Ptr<cv::cuda::DescriptorMatcher> cv::cuda::DescriptorMatcher::createBFMatcher(int) { throw_no_cuda(); return Ptr<cv::cuda::DescriptorMatcher>(); } #else /* !defined (HAVE_CUDA) */ namespace cv { namespace cuda { namespace device { namespace bf_match { template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, cudaStream_t stream); } namespace bf_knnmatch { template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask, const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask, const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask, const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist, cudaStream_t stream); template <typename T> void match2L1_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance, cudaStream_t stream); template <typename T> void match2L2_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance, cudaStream_t stream); template <typename T> void match2Hamming_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance, cudaStream_t stream); } namespace bf_radius_match { template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); } }}} namespace { static void makeGpuCollection(const std::vector<GpuMat>& trainDescCollection, const std::vector<GpuMat>& masks, GpuMat& trainCollection, GpuMat& maskCollection) { if (trainDescCollection.empty()) return; if (masks.empty()) { Mat trainCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepSzb))); PtrStepSzb* trainCollectionCPU_ptr = trainCollectionCPU.ptr<PtrStepSzb>(); for (size_t i = 0, size = trainDescCollection.size(); i < size; ++i, ++trainCollectionCPU_ptr) *trainCollectionCPU_ptr = trainDescCollection[i]; trainCollection.upload(trainCollectionCPU); maskCollection.release(); } else { CV_Assert( masks.size() == trainDescCollection.size() ); Mat trainCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepSzb))); Mat maskCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepb))); PtrStepSzb* trainCollectionCPU_ptr = trainCollectionCPU.ptr<PtrStepSzb>(); PtrStepb* maskCollectionCPU_ptr = maskCollectionCPU.ptr<PtrStepb>(); for (size_t i = 0, size = trainDescCollection.size(); i < size; ++i, ++trainCollectionCPU_ptr, ++maskCollectionCPU_ptr) { const GpuMat& train = trainDescCollection[i]; const GpuMat& mask = masks[i]; CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.cols == train.rows) ); *trainCollectionCPU_ptr = train; *maskCollectionCPU_ptr = mask; } trainCollection.upload(trainCollectionCPU); maskCollection.upload(maskCollectionCPU); } } class BFMatcher_Impl : public cv::cuda::DescriptorMatcher { public: explicit BFMatcher_Impl(int norm) : norm_(norm) { CV_Assert( norm == NORM_L1 || norm == NORM_L2 || norm == NORM_HAMMING ); } virtual bool isMaskSupported() const { return true; } virtual void add(const std::vector<GpuMat>& descriptors) { trainDescCollection_.insert(trainDescCollection_.end(), descriptors.begin(), descriptors.end()); } virtual const std::vector<GpuMat>& getTrainDescriptors() const { return trainDescCollection_; } virtual void clear() { trainDescCollection_.clear(); } virtual bool empty() const { return trainDescCollection_.empty(); } virtual void train() { } virtual void match(InputArray queryDescriptors, InputArray trainDescriptors, std::vector<DMatch>& matches, InputArray mask = noArray()); virtual void match(InputArray queryDescriptors, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>()); virtual void matchAsync(InputArray queryDescriptors, InputArray trainDescriptors, OutputArray matches, InputArray mask = noArray(), Stream& stream = Stream::Null()); virtual void matchAsync(InputArray queryDescriptors, OutputArray matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null()); virtual void matchConvert(InputArray gpu_matches, std::vector<DMatch>& matches); virtual void knnMatch(InputArray queryDescriptors, InputArray trainDescriptors, std::vector<std::vector<DMatch> >& matches, int k, InputArray mask = noArray(), bool compactResult = false); virtual void knnMatch(InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); virtual void knnMatchAsync(InputArray queryDescriptors, InputArray trainDescriptors, OutputArray matches, int k, InputArray mask = noArray(), Stream& stream = Stream::Null()); virtual void knnMatchAsync(InputArray queryDescriptors, OutputArray matches, int k, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null()); virtual void knnMatchConvert(InputArray gpu_matches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); virtual void radiusMatch(InputArray queryDescriptors, InputArray trainDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance, InputArray mask = noArray(), bool compactResult = false); virtual void radiusMatch(InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); virtual void radiusMatchAsync(InputArray queryDescriptors, InputArray trainDescriptors, OutputArray matches, float maxDistance, InputArray mask = noArray(), Stream& stream = Stream::Null()); virtual void radiusMatchAsync(InputArray queryDescriptors, OutputArray matches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null()); virtual void radiusMatchConvert(InputArray gpu_matches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); private: int norm_; std::vector<GpuMat> trainDescCollection_; }; // // 1 to 1 match // void BFMatcher_Impl::match(InputArray _queryDescriptors, InputArray _trainDescriptors, std::vector<DMatch>& matches, InputArray _mask) { GpuMat d_matches; matchAsync(_queryDescriptors, _trainDescriptors, d_matches, _mask); matchConvert(d_matches, matches); } void BFMatcher_Impl::match(InputArray _queryDescriptors, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks) { GpuMat d_matches; matchAsync(_queryDescriptors, d_matches, masks); matchConvert(d_matches, matches); } void BFMatcher_Impl::matchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors, OutputArray _matches, InputArray _mask, Stream& stream) { using namespace cv::cuda::device::bf_match; const GpuMat query = _queryDescriptors.getGpuMat(); const GpuMat train = _trainDescriptors.getGpuMat(); const GpuMat mask = _mask.getGpuMat(); if (query.empty() || train.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); CV_Assert( train.cols == query.cols && train.type() == query.type() ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) ); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; _matches.create(2, nQuery, CV_32SC1); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(1, nQuery, CV_32SC1, matches.ptr(0)); GpuMat distance(1, nQuery, CV_32FC1, matches.ptr(1)); func(query, train, mask, trainIdx, distance, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::matchAsync(InputArray _queryDescriptors, OutputArray _matches, const std::vector<GpuMat>& masks, Stream& stream) { using namespace cv::cuda::device::bf_match; const GpuMat query = _queryDescriptors.getGpuMat(); if (query.empty() || trainDescCollection_.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); GpuMat trainCollection, maskCollection; makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; _matches.create(3, nQuery, CV_32SC1); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(1, nQuery, CV_32SC1, matches.ptr(0)); GpuMat imgIdx(1, nQuery, CV_32SC1, matches.ptr(1)); GpuMat distance(1, nQuery, CV_32FC1, matches.ptr(2)); func(query, trainCollection, maskCollection, trainIdx, imgIdx, distance, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::matchConvert(InputArray _gpu_matches, std::vector<DMatch>& matches) { Mat gpu_matches; if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT) { _gpu_matches.getGpuMat().download(gpu_matches); } else { gpu_matches = _gpu_matches.getMat(); } if (gpu_matches.empty()) { matches.clear(); return; } CV_Assert( (gpu_matches.type() == CV_32SC1) && (gpu_matches.rows == 2 || gpu_matches.rows == 3) ); const int nQuery = gpu_matches.cols; matches.clear(); matches.reserve(nQuery); const int* trainIdxPtr = NULL; const int* imgIdxPtr = NULL; const float* distancePtr = NULL; if (gpu_matches.rows == 2) { trainIdxPtr = gpu_matches.ptr<int>(0); distancePtr = gpu_matches.ptr<float>(1); } else { trainIdxPtr = gpu_matches.ptr<int>(0); imgIdxPtr = gpu_matches.ptr<int>(1); distancePtr = gpu_matches.ptr<float>(2); } for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx) { const int trainIdx = trainIdxPtr[queryIdx]; if (trainIdx == -1) continue; const int imgIdx = imgIdxPtr ? imgIdxPtr[queryIdx] : 0; const float distance = distancePtr[queryIdx]; DMatch m(queryIdx, trainIdx, imgIdx, distance); matches.push_back(m); } } // // knn match // void BFMatcher_Impl::knnMatch(InputArray _queryDescriptors, InputArray _trainDescriptors, std::vector<std::vector<DMatch> >& matches, int k, InputArray _mask, bool compactResult) { GpuMat d_matches; knnMatchAsync(_queryDescriptors, _trainDescriptors, d_matches, k, _mask); knnMatchConvert(d_matches, matches, compactResult); } void BFMatcher_Impl::knnMatch(InputArray _queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k, const std::vector<GpuMat>& masks, bool compactResult) { if (k == 2) { GpuMat d_matches; knnMatchAsync(_queryDescriptors, d_matches, k, masks); knnMatchConvert(d_matches, matches, compactResult); } else { const GpuMat query = _queryDescriptors.getGpuMat(); if (query.empty() || trainDescCollection_.empty()) { matches.clear(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); std::vector< std::vector<DMatch> > curMatches; std::vector<DMatch> temp; temp.reserve(2 * k); matches.resize(query.rows); for (size_t i = 0; i < matches.size(); ++i) matches[i].reserve(k); for (size_t imgIdx = 0; imgIdx < trainDescCollection_.size(); ++imgIdx) { knnMatch(query, trainDescCollection_[imgIdx], curMatches, k, masks.empty() ? GpuMat() : masks[imgIdx]); for (int queryIdx = 0; queryIdx < query.rows; ++queryIdx) { std::vector<DMatch>& localMatch = curMatches[queryIdx]; std::vector<DMatch>& globalMatch = matches[queryIdx]; for (size_t i = 0; i < localMatch.size(); ++i) localMatch[i].imgIdx = imgIdx; temp.clear(); std::merge(globalMatch.begin(), globalMatch.end(), localMatch.begin(), localMatch.end(), std::back_inserter(temp)); globalMatch.clear(); const size_t count = std::min(static_cast<size_t>(k), temp.size()); std::copy(temp.begin(), temp.begin() + count, std::back_inserter(globalMatch)); } } if (compactResult) { std::vector< std::vector<DMatch> >::iterator new_end = std::remove_if(matches.begin(), matches.end(), std::mem_fun_ref(&std::vector<DMatch>::empty)); matches.erase(new_end, matches.end()); } } } void BFMatcher_Impl::knnMatchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors, OutputArray _matches, int k, InputArray _mask, Stream& stream) { using namespace cv::cuda::device::bf_knnmatch; const GpuMat query = _queryDescriptors.getGpuMat(); const GpuMat train = _trainDescriptors.getGpuMat(); const GpuMat mask = _mask.getGpuMat(); if (query.empty() || train.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); CV_Assert( train.cols == query.cols && train.type() == query.type() ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) ); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask, const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; const int nTrain = train.rows; GpuMat trainIdx, distance, allDist; if (k == 2) { _matches.create(2, nQuery, CV_32SC2); GpuMat matches = _matches.getGpuMat(); trainIdx = GpuMat(1, nQuery, CV_32SC2, matches.ptr(0)); distance = GpuMat(1, nQuery, CV_32FC2, matches.ptr(1)); } else { _matches.create(2 * nQuery, k, CV_32SC1); GpuMat matches = _matches.getGpuMat(); trainIdx = GpuMat(nQuery, k, CV_32SC1, matches.ptr(0), matches.step); distance = GpuMat(nQuery, k, CV_32FC1, matches.ptr(nQuery), matches.step); BufferPool pool(stream); allDist = pool.getBuffer(nQuery, nTrain, CV_32FC1); } trainIdx.setTo(Scalar::all(-1), stream); func(query, train, k, mask, trainIdx, distance, allDist, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::knnMatchAsync(InputArray _queryDescriptors, OutputArray _matches, int k, const std::vector<GpuMat>& masks, Stream& stream) { using namespace cv::cuda::device::bf_knnmatch; if (k != 2) { CV_Error(Error::StsNotImplemented, "only k=2 mode is supported for now"); } const GpuMat query = _queryDescriptors.getGpuMat(); if (query.empty() || trainDescCollection_.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); GpuMat trainCollection, maskCollection; makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance, cudaStream_t stream); static const caller_t callersL1[] = { match2L1_gpu<unsigned char>, 0/*match2L1_gpu<signed char>*/, match2L1_gpu<unsigned short>, match2L1_gpu<short>, match2L1_gpu<int>, match2L1_gpu<float> }; static const caller_t callersL2[] = { 0/*match2L2_gpu<unsigned char>*/, 0/*match2L2_gpu<signed char>*/, 0/*match2L2_gpu<unsigned short>*/, 0/*match2L2_gpu<short>*/, 0/*match2L2_gpu<int>*/, match2L2_gpu<float> }; static const caller_t callersHamming[] = { match2Hamming_gpu<unsigned char>, 0/*match2Hamming_gpu<signed char>*/, match2Hamming_gpu<unsigned short>, 0/*match2Hamming_gpu<short>*/, match2Hamming_gpu<int>, 0/*match2Hamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; _matches.create(3, nQuery, CV_32SC2); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(1, nQuery, CV_32SC2, matches.ptr(0)); GpuMat imgIdx(1, nQuery, CV_32SC2, matches.ptr(1)); GpuMat distance(1, nQuery, CV_32FC2, matches.ptr(2)); trainIdx.setTo(Scalar::all(-1), stream); func(query, trainCollection, maskCollection, trainIdx, imgIdx, distance, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::knnMatchConvert(InputArray _gpu_matches, std::vector< std::vector<DMatch> >& matches, bool compactResult) { Mat gpu_matches; if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT) { _gpu_matches.getGpuMat().download(gpu_matches); } else { gpu_matches = _gpu_matches.getMat(); } if (gpu_matches.empty()) { matches.clear(); return; } CV_Assert( ((gpu_matches.type() == CV_32SC2) && (gpu_matches.rows == 2 || gpu_matches.rows == 3)) || (gpu_matches.type() == CV_32SC1) ); int nQuery = -1, k = -1; const int* trainIdxPtr = NULL; const int* imgIdxPtr = NULL; const float* distancePtr = NULL; if (gpu_matches.type() == CV_32SC2) { nQuery = gpu_matches.cols; k = 2; if (gpu_matches.rows == 2) { trainIdxPtr = gpu_matches.ptr<int>(0); distancePtr = gpu_matches.ptr<float>(1); } else { trainIdxPtr = gpu_matches.ptr<int>(0); imgIdxPtr = gpu_matches.ptr<int>(1); distancePtr = gpu_matches.ptr<float>(2); } } else { nQuery = gpu_matches.rows / 2; k = gpu_matches.cols; trainIdxPtr = gpu_matches.ptr<int>(0); distancePtr = gpu_matches.ptr<float>(nQuery); } matches.clear(); matches.reserve(nQuery); for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx) { matches.push_back(std::vector<DMatch>()); std::vector<DMatch>& curMatches = matches.back(); curMatches.reserve(k); for (int i = 0; i < k; ++i) { const int trainIdx = *trainIdxPtr; if (trainIdx == -1) continue; const int imgIdx = imgIdxPtr ? *imgIdxPtr : 0; const float distance = *distancePtr; DMatch m(queryIdx, trainIdx, imgIdx, distance); curMatches.push_back(m); ++trainIdxPtr; ++distancePtr; if (imgIdxPtr) ++imgIdxPtr; } if (compactResult && curMatches.empty()) { matches.pop_back(); } } } // // radius match // void BFMatcher_Impl::radiusMatch(InputArray _queryDescriptors, InputArray _trainDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance, InputArray _mask, bool compactResult) { GpuMat d_matches; radiusMatchAsync(_queryDescriptors, _trainDescriptors, d_matches, maxDistance, _mask); radiusMatchConvert(d_matches, matches, compactResult); } void BFMatcher_Impl::radiusMatch(InputArray _queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance, const std::vector<GpuMat>& masks, bool compactResult) { GpuMat d_matches; radiusMatchAsync(_queryDescriptors, d_matches, maxDistance, masks); radiusMatchConvert(d_matches, matches, compactResult); } void BFMatcher_Impl::radiusMatchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors, OutputArray _matches, float maxDistance, InputArray _mask, Stream& stream) { using namespace cv::cuda::device::bf_radius_match; const GpuMat query = _queryDescriptors.getGpuMat(); const GpuMat train = _trainDescriptors.getGpuMat(); const GpuMat mask = _mask.getGpuMat(); if (query.empty() || train.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); CV_Assert( train.cols == query.cols && train.type() == query.type() ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) ); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; const int nTrain = train.rows; const int cols = std::max((nTrain / 100), nQuery); _matches.create(2 * nQuery + 1, cols, CV_32SC1); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(nQuery, cols, CV_32SC1, matches.ptr(0), matches.step); GpuMat distance(nQuery, cols, CV_32FC1, matches.ptr(nQuery), matches.step); GpuMat nMatches(1, nQuery, CV_32SC1, matches.ptr(2 * nQuery)); nMatches.setTo(Scalar::all(0), stream); func(query, train, maxDistance, mask, trainIdx, distance, nMatches, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::radiusMatchAsync(InputArray _queryDescriptors, OutputArray _matches, float maxDistance, const std::vector<GpuMat>& masks, Stream& stream) { using namespace cv::cuda::device::bf_radius_match; const GpuMat query = _queryDescriptors.getGpuMat(); if (query.empty() || trainDescCollection_.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); GpuMat trainCollection, maskCollection; makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; _matches.create(3 * nQuery + 1, nQuery, CV_32FC1); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(nQuery, nQuery, CV_32SC1, matches.ptr(0), matches.step); GpuMat imgIdx(nQuery, nQuery, CV_32SC1, matches.ptr(nQuery), matches.step); GpuMat distance(nQuery, nQuery, CV_32FC1, matches.ptr(2 * nQuery), matches.step); GpuMat nMatches(1, nQuery, CV_32SC1, matches.ptr(3 * nQuery)); nMatches.setTo(Scalar::all(0), stream); std::vector<PtrStepSzb> trains_(trainDescCollection_.begin(), trainDescCollection_.end()); std::vector<PtrStepSzb> masks_(masks.begin(), masks.end()); func(query, &trains_[0], static_cast<int>(trains_.size()), maxDistance, masks_.size() == 0 ? 0 : &masks_[0], trainIdx, imgIdx, distance, nMatches, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::radiusMatchConvert(InputArray _gpu_matches, std::vector< std::vector<DMatch> >& matches, bool compactResult) { Mat gpu_matches; if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT) { _gpu_matches.getGpuMat().download(gpu_matches); } else { gpu_matches = _gpu_matches.getMat(); } if (gpu_matches.empty()) { matches.clear(); return; } CV_Assert( gpu_matches.type() == CV_32SC1 || gpu_matches.type() == CV_32FC1 ); int nQuery = -1; const int* trainIdxPtr = NULL; const int* imgIdxPtr = NULL; const float* distancePtr = NULL; const int* nMatchesPtr = NULL; if (gpu_matches.type() == CV_32SC1) { nQuery = (gpu_matches.rows - 1) / 2; trainIdxPtr = gpu_matches.ptr<int>(0); distancePtr = gpu_matches.ptr<float>(nQuery); nMatchesPtr = gpu_matches.ptr<int>(2 * nQuery); } else { nQuery = (gpu_matches.rows - 1) / 3; trainIdxPtr = gpu_matches.ptr<int>(0); imgIdxPtr = gpu_matches.ptr<int>(nQuery); distancePtr = gpu_matches.ptr<float>(2 * nQuery); nMatchesPtr = gpu_matches.ptr<int>(3 * nQuery); } matches.clear(); matches.reserve(nQuery); for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx) { const int nMatched = std::min(nMatchesPtr[queryIdx], gpu_matches.cols); if (nMatched == 0) { if (!compactResult) { matches.push_back(std::vector<DMatch>()); } } else { matches.push_back(std::vector<DMatch>(nMatched)); std::vector<DMatch>& curMatches = matches.back(); for (int i = 0; i < nMatched; ++i) { const int trainIdx = trainIdxPtr[i]; const int imgIdx = imgIdxPtr ? imgIdxPtr[i] : 0; const float distance = distancePtr[i]; DMatch m(queryIdx, trainIdx, imgIdx, distance); curMatches[i] = m; } std::sort(curMatches.begin(), curMatches.end()); } trainIdxPtr += gpu_matches.cols; distancePtr += gpu_matches.cols; if (imgIdxPtr) imgIdxPtr += gpu_matches.cols; } } } Ptr<cv::cuda::DescriptorMatcher> cv::cuda::DescriptorMatcher::createBFMatcher(int norm) { return makePtr<BFMatcher_Impl>(norm); } #endif /* !defined (HAVE_CUDA) */
DamianPilot382/Rubiks-Cube-Solver
opencv/sources/modules/cudafeatures2d/src/brute_force_matcher.cpp
C++
apache-2.0
43,804
import { __platform_browser_private__ as r } from '@angular/platform-browser'; export var getDOM = r.getDOM; //# sourceMappingURL=platform_browser_private.js.map
evandor/skysail-webconsole
webconsole.client/client/dist/lib/@angular/platform-browser-dynamic/esm/platform_browser_private.js
JavaScript
apache-2.0
161
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // Copyright 2018 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glog/logging.h" #include "NvInferPlugin.h" #include "logger.h" #include "test_settings.h" #include "loadgen.h" #include "numpy.hpp" #include "qsl.hpp" #include "dlrm_server.h" #include "dlrm_qsl.hpp" #include "utils.hpp" #include "cuda_profiler_api.h" #include <dlfcn.h> DEFINE_string(gpu_engines, "", "Engine"); DEFINE_string(plugins, "", "Comma-separated list of shared objects for plugins"); DEFINE_string(scenario, "Offline", "Scenario to run for Loadgen (Offline, SingleStream, Server)"); DEFINE_string(test_mode, "PerformanceOnly", "Testing mode for Loadgen"); DEFINE_string(model, "dlrm", "Model name"); DEFINE_uint32(gpu_batch_size, 16384, "Max Batch size to use for all devices and engines"); DEFINE_bool(use_graphs, false, "Enable cudaGraphs for TensorRT engines"); // TODO: Enable support for Cuda Graphs DEFINE_bool(verbose, false, "Use verbose logging"); DEFINE_uint32(gpu_copy_streams, 1, "[CURRENTLY NOT USED] Number of copy streams"); DEFINE_uint32(gpu_num_bundles, 2, "Number of event-buffer bundles per GPU"); DEFINE_uint32(complete_threads, 1, "Number of threads per device for sending responses"); DEFINE_uint32(gpu_inference_streams, 1, "Number of inference streams"); DEFINE_double(warmup_duration, 1.0, "Minimum duration to run warmup for"); // configuration files DEFINE_string(mlperf_conf_path, "", "Path to mlperf.conf"); DEFINE_string(user_conf_path, "", "Path to user.conf"); DEFINE_uint64(single_stream_expected_latency_ns, 100000, "Inverse of desired target QPS"); // Loadgen logging settings DEFINE_string(logfile_outdir, "", "Specify the existing output directory for the LoadGen logs"); DEFINE_string(logfile_prefix, "", "Specify the filename prefix for the LoadGen log files"); DEFINE_string(logfile_suffix, "", "Specify the filename suffix for the LoadGen log files"); DEFINE_bool(logfile_prefix_with_datetime, false, "Prefix filenames for LoadGen log files"); DEFINE_bool(log_copy_detail_to_stdout, false, "Copy LoadGen detailed logging to stdout"); DEFINE_bool(disable_log_copy_summary_to_stdout, false, "Disable copy LoadGen summary logging to stdout"); DEFINE_string(log_mode, "AsyncPoll", "Logging mode for Loadgen"); DEFINE_uint64(log_mode_async_poll_interval_ms, 1000, "Specify the poll interval for asynchrounous logging"); DEFINE_bool(log_enable_trace, false, "Enable trace logging"); // QSL arguments DEFINE_string(map_path, "", "Path to map file for samples"); DEFINE_string(sample_partition_path, "", "Path to sample partition file in npy format."); DEFINE_string(tensor_path, "", "Path to preprocessed samples in npy format (<full_image_name>.npy). Comma-separated list if there are more than one input."); DEFINE_uint64(performance_sample_count, 0, "Number of samples to load in performance set. 0=use default"); DEFINE_bool(start_from_device, false, "Assuming that inputs start from device memory in QSL"); // Dataset arguments DEFINE_uint32(min_sample_size, 100, "Minimum number of pairs a sample can contain."); DEFINE_uint32(max_sample_size, 700, "Maximum number of pairs a sample can contain."); // BatchMaker arguments DEFINE_uint32(num_staging_threads, 8, "Number of staging threads in DLRM BatchMaker"); DEFINE_uint32(num_staging_batches, 4, "Number of staging batches in DLRM BatchMaker"); DEFINE_uint32(max_pairs_per_staging_thread, 0, "Maximum pairs to copy in one BatchMaker staging thread (0 = use default"); DEFINE_bool(check_contiguity, false, "Whether to use contiguity checking in BatchMaker (default: false, recommended: true for Offline)"); DEFINE_string(numa_config, "", "NUMA settings: cpu cores for each GPU, assuming each GPU corresponds to one NUMA node"); /* Define a map to convert test mode input string into its corresponding enum value */ std::map<std::string, mlperf::TestScenario> scenarioMap = { {"Offline", mlperf::TestScenario::Offline}, {"SingleStream", mlperf::TestScenario::SingleStream}, {"Server", mlperf::TestScenario::Server}, }; /* Define a map to convert test mode input string into its corresponding enum value */ std::map<std::string, mlperf::TestMode> testModeMap = { {"SubmissionRun", mlperf::TestMode::SubmissionRun}, {"AccuracyOnly", mlperf::TestMode::AccuracyOnly}, {"PerformanceOnly", mlperf::TestMode::PerformanceOnly} }; /* Define a map to convert logging mode input string into its corresponding enum value */ std::map<std::string, mlperf::LoggingMode> logModeMap = { {"AsyncPoll", mlperf::LoggingMode::AsyncPoll}, {"EndOfTestOnly", mlperf::LoggingMode::EndOfTestOnly}, {"Synchronous", mlperf::LoggingMode::Synchronous} }; // Example of the format: "0-63,64-127" for 2 GPUs (one per NUMA node). NumaConfig parseNumaConfig(const std::string& s) { NumaConfig config; if (!s.empty()) { auto nodes = splitString(s, ","); for (const auto& node : nodes) { auto cpuRange = splitString(node, "-"); CHECK(cpuRange.size() == 2) << "Invalid numa_config setting."; int start = std::stoi(cpuRange[0]); int last = std::stoi(cpuRange[1]); CHECK(start <= last) << "Invalid numa_config setting."; std::vector<int> cpus(last - start + 1); for (int i = start; i <= last; ++i) { cpus[i - start] = i; } config.emplace_back(cpus); } } return config; } int main(int argc, char* argv[]) { FLAGS_alsologtostderr = 1; // Log to console ::google::InitGoogleLogging("TensorRT mlperf"); ::google::ParseCommandLineFlags(&argc, &argv, true); const std::string gSampleName = "DLRM_HARNESS"; auto sampleTest = gLogger.defineTest(gSampleName, argc, const_cast<const char**>(argv)); if (FLAGS_verbose) { setReportableSeverity(Severity::kVERBOSE); } gLogger.reportTestStart(sampleTest); initLibNvInferPlugins(&gLogger.getTRTLogger(), ""); // Load all the needed shared objects for plugins. std::vector<std::string> plugin_files = splitString(FLAGS_plugins, ","); for (auto& s : plugin_files) { void* dlh = dlopen(s.c_str(), RTLD_LAZY); if (nullptr == dlh) { gLogError << "Error loading plugin library " << s << std::endl; return 1; } } // Scope to force all smart objects destruction before CUDA context resets { int num_gpu; cudaGetDeviceCount(&num_gpu); LOG(INFO) << "Found " << num_gpu << " GPUs"; // Configure the test settings mlperf::TestSettings testSettings; testSettings.scenario = scenarioMap[FLAGS_scenario]; testSettings.mode = testModeMap[FLAGS_test_mode]; testSettings.FromConfig(FLAGS_mlperf_conf_path, FLAGS_model, FLAGS_scenario); testSettings.FromConfig(FLAGS_user_conf_path, FLAGS_model, FLAGS_scenario); testSettings.single_stream_expected_latency_ns = FLAGS_single_stream_expected_latency_ns; testSettings.server_coalesce_queries = true; // Configure the logging settings mlperf::LogSettings logSettings; logSettings.log_output.outdir = FLAGS_logfile_outdir; logSettings.log_output.prefix = FLAGS_logfile_prefix; logSettings.log_output.suffix = FLAGS_logfile_suffix; logSettings.log_output.prefix_with_datetime = FLAGS_logfile_prefix_with_datetime; logSettings.log_output.copy_detail_to_stdout = FLAGS_log_copy_detail_to_stdout; logSettings.log_output.copy_summary_to_stdout = !FLAGS_disable_log_copy_summary_to_stdout; logSettings.log_mode = logModeMap[FLAGS_log_mode]; logSettings.log_mode_async_poll_interval_ms = FLAGS_log_mode_async_poll_interval_ms; logSettings.enable_trace = FLAGS_log_enable_trace; std::vector<int> gpus(num_gpu); std::iota(gpus.begin(), gpus.end(), 0); // Load the sample partition. We do this here to calculate the performance sample count of the underlying // LWIS QSL, since the super constructor must be in the constructor initialization list. std::vector<int> originalPartition; // Scope to automatically close the file { npy::NpyFile samplePartitionFile(FLAGS_sample_partition_path); CHECK_EQ(samplePartitionFile.getDims().size(), 1); // For now we do not allow numPartitions == FLAGS_performance_sample_count, since the TotalSampleCount // is determined at runtime in the underlying LWIS QSL. size_t numPartitions = samplePartitionFile.getDims()[0]; CHECK_EQ(numPartitions > FLAGS_performance_sample_count, true); std::vector<char> tmp(samplePartitionFile.getTensorSize()); samplePartitionFile.loadAll(tmp); originalPartition.resize(numPartitions); memcpy(originalPartition.data(), tmp.data(), tmp.size()); LOG(INFO) << "Loaded " << originalPartition.size() - 1 << " sample partitions. (" << tmp.size() << ") bytes."; } // Force underlying QSL to load all samples, since we want to be able to grab any partition given the sample // index. size_t perfPairCount = originalPartition.back(); auto qsl = std::make_shared<DLRMSampleLibrary>( "DLRM QSL", FLAGS_map_path, splitString(FLAGS_tensor_path, ","), originalPartition, FLAGS_performance_sample_count, perfPairCount, 0, true, FLAGS_start_from_device); auto dlrm_server = std::make_shared<DLRMServer>( "DLRM SERVER", FLAGS_gpu_engines, qsl, gpus, FLAGS_gpu_batch_size, FLAGS_gpu_num_bundles, FLAGS_complete_threads, FLAGS_gpu_inference_streams, FLAGS_warmup_duration, FLAGS_num_staging_threads, FLAGS_num_staging_batches, FLAGS_max_pairs_per_staging_thread, FLAGS_check_contiguity, FLAGS_start_from_device, parseNumaConfig(FLAGS_numa_config)); LOG(INFO) << "Starting running actual test."; cudaProfilerStart(); StartTest(dlrm_server.get(), qsl.get(), testSettings, logSettings); cudaProfilerStop(); LOG(INFO) << "Finished running actual test."; } return 0; }
mlperf/inference_results_v0.7
open/Inspur/code/harness/harness_dlrm/main_dlrm.cc
C++
apache-2.0
11,024
cask :v1 => 'font-lohit-tamil-classical' do version '2.5.3' sha256 '325ea1496bb2ae4f77552c268190251a5155717dccda64d497da4388d17c2432' url "https://fedorahosted.org/releases/l/o/lohit/lohit-tamil-classical-ttf-#{version}.tar.gz" homepage 'https://fedorahosted.org/lohit/' license :unknown font "lohit-tamil-classical-ttf-#{version}/Lohit-Tamil-Classical.ttf" end
elmariofredo/homebrew-fonts
Casks/font-lohit-tamil-classical.rb
Ruby
bsd-2-clause
376
class AddPlaneIdToNodes < ActiveRecord::Migration def change add_column :nodes, :plane_id, :integer add_index :nodes, :plane_id end end
irubi/rabel
db/migrate/20111209080432_add_plane_id_to_nodes.rb
Ruby
bsd-3-clause
148
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; /** * * Command for archers. * */ public class ArcherCommand implements Command { @Override public void process() { new ArcherView().display(); } }
WeRockStar/java-design-patterns
front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java
Java
mit
1,344
exports.x = "d";
g0ddish/webpack
test/cases/parsing/harmony-duplicate-export/d.js
JavaScript
mit
17
var test = require("tap").test var server = require("./lib/server.js") var common = require("./lib/common.js") var client = common.freshClient() var cache = require("./fixtures/underscore/cache.json") function nop () {} var URI = "https://npm.registry:8043/rewrite" var STARRED = true var USERNAME = "username" var PASSWORD = "%1234@asdf%" var EMAIL = "i@izs.me" var AUTH = { username : USERNAME, password : PASSWORD, email : EMAIL } var PARAMS = { starred : STARRED, auth : AUTH } test("star call contract", function (t) { t.throws(function () { client.star(undefined, PARAMS, nop) }, "requires a URI") t.throws(function () { client.star([], PARAMS, nop) }, "requires URI to be a string") t.throws(function () { client.star(URI, undefined, nop) }, "requires params object") t.throws(function () { client.star(URI, "", nop) }, "params must be object") t.throws(function () { client.star(URI, PARAMS, undefined) }, "requires callback") t.throws(function () { client.star(URI, PARAMS, "callback") }, "callback must be function") t.throws( function () { var params = { starred : STARRED } client.star(URI, params, nop) }, { name : "AssertionError", message : "must pass auth to star" }, "params must include auth" ) t.test("token auth disallowed in star", function (t) { var params = { auth : { token : "lol" } } client.star(URI, params, function (err) { t.equal( err && err.message, "This operation is unsupported for token-based auth", "star doesn't support token-based auth" ) t.end() }) }) t.end() }) test("star a package", function (t) { server.expect("GET", "/underscore?write=true", function (req, res) { t.equal(req.method, "GET") res.json(cache) }) server.expect("PUT", "/underscore", function (req, res) { t.equal(req.method, "PUT") var b = "" req.setEncoding("utf8") req.on("data", function (d) { b += d }) req.on("end", function () { var updated = JSON.parse(b) var already = [ "vesln", "mvolkmann", "lancehunt", "mikl", "linus", "vasc", "bat", "dmalam", "mbrevoort", "danielr", "rsimoes", "thlorenz" ] for (var i = 0; i < already.length; i++) { var current = already[i] t.ok( updated.users[current], current + " still likes this package" ) } t.ok(updated.users[USERNAME], "user is in the starred list") res.statusCode = 201 res.json({starred:true}) }) }) var params = { starred : STARRED, auth : AUTH } client.star("http://localhost:1337/underscore", params, function (error, data) { t.ifError(error, "no errors") t.ok(data.starred, "was starred") t.end() }) })
lwthatcher/Compass
web/node_modules/npm/node_modules/npm-registry-client/test/star.js
JavaScript
mit
2,885
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Validator\Constraints; class Url extends \Symfony\Component\Validator\Constraint { public $message = 'This value is not a valid URL'; public $protocols = array('http', 'https'); /** * {@inheritDoc} */ public function getTargets() { return self::PROPERTY_CONSTRAINT; } }
radzikowski/alf
vendor/symfony/src/Symfony/Component/Validator/Constraints/Url.php
PHP
mit
579
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Shared.LanguageParser; using Microsoft.Build.Tasks.Hosting; using Microsoft.Build.Tasks.InteropUtilities; using Microsoft.Build.Utilities; #if (!STANDALONEBUILD) using Microsoft.Internal.Performance; #endif namespace Microsoft.Build.Tasks { /// <summary> /// This class defines the "Csc" XMake task, which enables building assemblies from C# /// source files by invoking the C# compiler. This is the new Roslyn XMake task, /// meaning that the code is compiled by using the Roslyn compiler server, rather /// than csc.exe. The two should be functionally identical, but the compiler server /// should be significantly faster with larger projects and have a smaller memory /// footprint. /// </summary> public class Csc : ManagedCompiler { private bool _useHostCompilerIfAvailable = false; #region Properties // Please keep these alphabetized. These are the parameters specific to Csc. The // ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is // the base class. public bool AllowUnsafeBlocks { set { Bag["AllowUnsafeBlocks"] = value; } get { return GetBoolParameterWithDefault("AllowUnsafeBlocks", false); } } public string ApplicationConfiguration { set { Bag["ApplicationConfiguration"] = value; } get { return (string)Bag["ApplicationConfiguration"]; } } public string BaseAddress { set { Bag["BaseAddress"] = value; } get { return (string)Bag["BaseAddress"]; } } public bool CheckForOverflowUnderflow { set { Bag["CheckForOverflowUnderflow"] = value; } get { return GetBoolParameterWithDefault("CheckForOverflowUnderflow", false); } } public string DocumentationFile { set { Bag["DocumentationFile"] = value; } get { return (string)Bag["DocumentationFile"]; } } public string DisabledWarnings { set { Bag["DisabledWarnings"] = value; } get { return (string)Bag["DisabledWarnings"]; } } public bool ErrorEndLocation { set { Bag["ErrorEndLocation"] = value; } get { return GetBoolParameterWithDefault("ErrorEndLocation", false); } } public string ErrorReport { set { Bag["ErrorReport"] = value; } get { return (string)Bag["ErrorReport"]; } } public bool GenerateFullPaths { set { Bag["GenerateFullPaths"] = value; } get { return GetBoolParameterWithDefault("GenerateFullPaths", false); } } public string LangVersion { set { Bag["LangVersion"] = value; } get { return (string)Bag["LangVersion"]; } } public string ModuleAssemblyName { set { Bag["ModuleAssemblyName"] = value; } get { return (string)Bag["ModuleAssemblyName"]; } } public bool NoStandardLib { set { Bag["NoStandardLib"] = value; } get { return GetBoolParameterWithDefault("NoStandardLib", false); } } public string PdbFile { set { Bag["PdbFile"] = value; } get { return (string)Bag["PdbFile"]; } } /// <summary> /// Name of the language passed to "/preferreduilang" compiler option. /// </summary> /// <remarks> /// If set to null, "/preferreduilang" option is omitted, and csc.exe uses its default setting. /// Otherwise, the value is passed to "/preferreduilang" as is. /// </remarks> public string PreferredUILang { set { Bag["PreferredUILang"] = value; } get { return (string)Bag["PreferredUILang"]; } } public string VsSessionGuid { set { Bag["VsSessionGuid"] = value; } get { return (string)Bag["VsSessionGuid"]; } } public bool UseHostCompilerIfAvailable { set { _useHostCompilerIfAvailable = value; } get { return _useHostCompilerIfAvailable; } } public int WarningLevel { set { Bag["WarningLevel"] = value; } get { return GetIntParameterWithDefault("WarningLevel", 4); } } public string WarningsAsErrors { set { Bag["WarningsAsErrors"] = value; } get { return (string)Bag["WarningsAsErrors"]; } } public string WarningsNotAsErrors { set { Bag["WarningsNotAsErrors"] = value; } get { return (string)Bag["WarningsNotAsErrors"]; } } #endregion #region Tool Members /// <summary> /// Return the name of the tool to execute. /// </summary> override protected string ToolName { get { return "csc2.exe"; } } /// <summary> /// Return the path to the tool to execute. /// </summary> override protected string GenerateFullPathToTool() { string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion); if (null == pathToTool) { pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest); if (null == pathToTool) { Log.LogErrorWithCodeFromResources("General.FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest)); } } return pathToTool; } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> override protected internal void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitchIfNotNull("/lib:", this.AdditionalLibPaths, ","); commandLine.AppendPlusOrMinusSwitch("/unsafe", this.Bag, "AllowUnsafeBlocks"); commandLine.AppendPlusOrMinusSwitch("/checked", this.Bag, "CheckForOverflowUnderflow"); commandLine.AppendSwitchWithSplitting("/nowarn:", this.DisabledWarnings, ",", ';', ','); commandLine.AppendWhenTrue("/fullpaths", this.Bag, "GenerateFullPaths"); commandLine.AppendSwitchIfNotNull("/langversion:", this.LangVersion); commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", this.ModuleAssemblyName); commandLine.AppendSwitchIfNotNull("/pdb:", this.PdbFile); commandLine.AppendPlusOrMinusSwitch("/nostdlib", this.Bag, "NoStandardLib"); commandLine.AppendSwitchIfNotNull("/platform:", this.PlatformWith32BitPreference); commandLine.AppendSwitchIfNotNull("/errorreport:", this.ErrorReport); commandLine.AppendSwitchWithInteger("/warn:", this.Bag, "WarningLevel"); commandLine.AppendSwitchIfNotNull("/doc:", this.DocumentationFile); commandLine.AppendSwitchIfNotNull("/baseaddress:", this.BaseAddress); commandLine.AppendSwitchUnquotedIfNotNull("/define:", this.GetDefineConstantsSwitch(this.DefineConstants)); commandLine.AppendSwitchIfNotNull("/win32res:", this.Win32Resource); commandLine.AppendSwitchIfNotNull("/main:", this.MainEntryPoint); commandLine.AppendSwitchIfNotNull("/appconfig:", this.ApplicationConfiguration); commandLine.AppendWhenTrue("/errorendlocation", this.Bag, "ErrorEndLocation"); commandLine.AppendSwitchIfNotNull("/preferreduilang:", this.PreferredUILang); commandLine.AppendPlusOrMinusSwitch("/highentropyva", this.Bag, "HighEntropyVA"); // If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid> bool designTime = false; if (this.HostObject != null) { var csHost = this.HostObject as ICscHostObject; designTime = csHost.IsDesignTime(); } if (!designTime) { if (!string.IsNullOrWhiteSpace(this.VsSessionGuid)) { commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", this.VsSessionGuid); } } this.AddReferencesToCommandLine(commandLine); base.AddResponseFileCommands(commandLine); // This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs). // Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line, // and then any specific warnings that should be treated as errors should be specified with // /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line // does matter. // // Note that // /warnaserror+ // is just shorthand for: // /warnaserror+:<all possible warnings> // // Similarly, // /warnaserror- // is just shorthand for: // /warnaserror-:<all possible warnings> commandLine.AppendSwitchWithSplitting("/warnaserror+:", this.WarningsAsErrors, ",", ';', ','); commandLine.AppendSwitchWithSplitting("/warnaserror-:", this.WarningsNotAsErrors, ",", ';', ','); // It's a good idea for the response file to be the very last switch passed, just // from a predictability perspective. if (this.ResponseFiles != null) { foreach (ITaskItem response in this.ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } } #endregion /// <summary> /// The C# compiler (starting with Whidbey) supports assembly aliasing for references. /// See spec at http://devdiv/spectool/Documents/Whidbey/VCSharp/Design%20Time/M3%20DCRs/DCR%20Assembly%20aliases.doc. /// This method handles the necessary work of looking at the "Aliases" attribute on /// the incoming "References" items, and making sure to generate the correct /// command-line on csc.exe. The syntax for aliasing a reference is: /// csc.exe /reference:Foo=System.Xml.dll /// /// The "Aliases" attribute on the "References" items is actually a comma-separated /// list of aliases, and if any of the aliases specified is the string "global", /// then we add that reference to the command-line without an alias. /// </summary> /// <param name="commandLine"></param> private void AddReferencesToCommandLine ( CommandLineBuilderExtension commandLine ) { // If there were no references passed in, don't add any /reference: switches // on the command-line. if ((this.References == null) || (this.References.Length == 0)) { return; } // Loop through all the references passed in. We'll be adding separate // /reference: switches for each reference, and in some cases even multiple // /reference: switches per reference. foreach (ITaskItem reference in this.References) { // See if there was an "Alias" attribute on the reference. string aliasString = reference.GetMetadata(ItemMetadataNames.aliases); string switchName = "/reference:"; bool embed = MetadataConversionUtilities.TryConvertItemMetadataToBool ( reference, ItemMetadataNames.embedInteropTypes ); if (embed == true) { switchName = "/link:"; } if ((aliasString == null) || (aliasString.Length == 0)) { // If there was no "Alias" attribute, just add this as a global reference. commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec); } else { // If there was an "Alias" attribute, it contains a comma-separated list // of aliases to use for this reference. For each one of those aliases, // we're going to add a separate /reference: switch to the csc.exe // command-line string[] aliases = aliasString.Split(','); foreach (string alias in aliases) { // Trim whitespace. string trimmedAlias = alias.Trim(); if (alias.Length == 0) { continue; } // The alias should be a valid C# identifier. Therefore it cannot // contain comma, space, semicolon, or double-quote. Let's check for // the existence of those characters right here, and bail immediately // if any are present. There are a whole bunch of other characters // that are not allowed in a C# identifier, but we'll just let csc.exe // error out on those. The ones we're checking for here are the ones // that could seriously interfere with the command-line parsing or could // allow parameter injection. if (trimmedAlias.IndexOfAny(new char[] { ',', ' ', ';', '"' }) != -1) { ErrorUtilities.VerifyThrowArgument ( false, "Csc.AssemblyAliasContainsIllegalCharacters", reference.ItemSpec, trimmedAlias ); } // The alias called "global" is special. It means that we don't // give it an alias on the command-line. if (String.Compare("global", trimmedAlias, StringComparison.OrdinalIgnoreCase) == 0) { commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec); } else { // We have a valid (and explicit) alias for this reference. Add // it to the command-line using the syntax: // /reference:Foo=System.Xml.dll commandLine.AppendSwitchAliased(switchName, trimmedAlias, reference.ItemSpec); } } } } } /// <summary> /// Determines whether a particular string is a valid C# identifier. Legal /// identifiers must start with a letter, and all the characters must be /// letters or numbers. Underscore is considered a letter. /// </summary> private static bool IsLegalIdentifier ( string identifier ) { // Must be non-empty. if (identifier.Length == 0) { return false; } // First character must be a letter. // From 2.4.2 of the C# Language Specification // identifier-start-letter-character: if ( !TokenChar.IsLetter(identifier[0]) && (identifier[0] != '_') ) { return false; } // All the other characters must be letters or numbers. // From 2.4.2 of the C# Language Specification // identifier-part-letter-character: for (int i = 1; i < identifier.Length; i++) { char currentChar = identifier[i]; if ( !TokenChar.IsLetter(currentChar) && !TokenChar.IsDecimalDigit(currentChar) && !TokenChar.IsConnecting(currentChar) && !TokenChar.IsCombining(currentChar) && !TokenChar.IsFormatting(currentChar) ) { return false; } } return true; } /// <summary> /// Old VS projects had some pretty messed-up looking values for the /// "DefineConstants" property. It worked fine in the IDE, because it /// effectively munged up the string so that it ended up being valid for /// the compiler. We do the equivalent munging here now. /// /// Basically, we take the incoming string, and split it on comma/semicolon/space. /// Then we look at the resulting list of strings, and remove any that are /// illegal identifiers, and pass the remaining ones through to the compiler. /// /// Note that CSharp does support assigning a value to the constants ... in /// other words, a constant is either defined or not defined ... it can't have /// an actual value. /// </summary> internal string GetDefineConstantsSwitch ( string originalDefineConstants ) { if (originalDefineConstants == null) { return null; } StringBuilder finalDefineConstants = new StringBuilder(); // Split the incoming string on comma/semicolon/space. string[] allIdentifiers = originalDefineConstants.Split(new char[] { ',', ';', ' ' }); // Loop through all the parts, and for the ones that are legal C# identifiers, // add them to the outgoing string. foreach (string singleIdentifier in allIdentifiers) { if (Csc.IsLegalIdentifier(singleIdentifier)) { // Separate them with a semicolon if there's something already in // the outgoing string. if (finalDefineConstants.Length > 0) { finalDefineConstants.Append(";"); } finalDefineConstants.Append(singleIdentifier); } else if (singleIdentifier.Length > 0) { Log.LogWarningWithCodeFromResources("Csc.InvalidParameterWarning", "/define:", singleIdentifier); } } if (finalDefineConstants.Length > 0) { return finalDefineConstants.ToString(); } else { // We wouldn't want to pass in an empty /define: switch on the csc.exe command-line. return null; } } /// <summary> /// This method will initialize the host compiler object with all the switches, /// parameters, resources, references, sources, etc. /// /// It returns true if everything went according to plan. It returns false if the /// host compiler had a problem with one of the parameters that was passed in. /// /// This method also sets the "this.HostCompilerSupportsAllParameters" property /// accordingly. /// /// Example: /// If we attempted to pass in WarningLevel="9876", then this method would /// set HostCompilerSupportsAllParameters=true, but it would give a /// return value of "false". This is because the host compiler fully supports /// the WarningLevel parameter, but 9876 happens to be an illegal value. /// /// Example: /// If we attempted to pass in NoConfig=false, then this method would set /// HostCompilerSupportsAllParameters=false, because while this is a legal /// thing for csc.exe, the IDE compiler cannot support it. In this situation /// the return value will also be false. /// </summary> private bool InitializeHostCompiler ( // NOTE: For compat reasons this must remain ICscHostObject // we can dynamically test for smarter interfaces later.. ICscHostObject cscHostObject ) { bool success; this.HostCompilerSupportsAllParameters = this.UseHostCompilerIfAvailable; string param = "Unknown"; try { // Need to set these separately, because they don't require a CommitChanges to the C# compiler in the IDE. param = "LinkResources"; this.CheckHostObjectSupport(param, cscHostObject.SetLinkResources(this.LinkResources)); param = "References"; this.CheckHostObjectSupport(param, cscHostObject.SetReferences(this.References)); param = "Resources"; this.CheckHostObjectSupport(param, cscHostObject.SetResources(this.Resources)); param = "Sources"; this.CheckHostObjectSupport(param, cscHostObject.SetSources(this.Sources)); // For host objects which support it, pass the list of analyzers. IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject; if (analyzerHostObject != null) { param = "Analyzers"; this.CheckHostObjectSupport(param, analyzerHostObject.SetAnalyzers(this.Analyzers)); } } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } if (this.HostCompilerSupportsAllParameters) { // If the host compiler doesn't support everything we need, we're going to end up // shelling out to the command-line compiler anyway. That means the command-line // compiler will log the error. So here, we only log the error if we would've // tried to use the host compiler. Log.LogErrorWithCodeFromResources("General.CouldNotSetHostObjectParameter", param, e.Message); } return false; } try { param = "BeginInitialization"; cscHostObject.BeginInitialization(); param = "AdditionalLibPaths"; this.CheckHostObjectSupport(param, cscHostObject.SetAdditionalLibPaths(this.AdditionalLibPaths)); param = "AddModules"; this.CheckHostObjectSupport(param, cscHostObject.SetAddModules(this.AddModules)); param = "AllowUnsafeBlocks"; this.CheckHostObjectSupport(param, cscHostObject.SetAllowUnsafeBlocks(this.AllowUnsafeBlocks)); param = "BaseAddress"; this.CheckHostObjectSupport(param, cscHostObject.SetBaseAddress(this.BaseAddress)); param = "CheckForOverflowUnderflow"; this.CheckHostObjectSupport(param, cscHostObject.SetCheckForOverflowUnderflow(this.CheckForOverflowUnderflow)); param = "CodePage"; this.CheckHostObjectSupport(param, cscHostObject.SetCodePage(this.CodePage)); // These two -- EmitDebugInformation and DebugType -- must go together, with DebugType // getting set last, because it is more specific. param = "EmitDebugInformation"; this.CheckHostObjectSupport(param, cscHostObject.SetEmitDebugInformation(this.EmitDebugInformation)); param = "DebugType"; this.CheckHostObjectSupport(param, cscHostObject.SetDebugType(this.DebugType)); param = "DefineConstants"; this.CheckHostObjectSupport(param, cscHostObject.SetDefineConstants(this.GetDefineConstantsSwitch(this.DefineConstants))); param = "DelaySign"; this.CheckHostObjectSupport(param, cscHostObject.SetDelaySign((this.Bag["DelaySign"] != null), this.DelaySign)); param = "DisabledWarnings"; this.CheckHostObjectSupport(param, cscHostObject.SetDisabledWarnings(this.DisabledWarnings)); param = "DocumentationFile"; this.CheckHostObjectSupport(param, cscHostObject.SetDocumentationFile(this.DocumentationFile)); param = "ErrorReport"; this.CheckHostObjectSupport(param, cscHostObject.SetErrorReport(this.ErrorReport)); param = "FileAlignment"; this.CheckHostObjectSupport(param, cscHostObject.SetFileAlignment(this.FileAlignment)); param = "GenerateFullPaths"; this.CheckHostObjectSupport(param, cscHostObject.SetGenerateFullPaths(this.GenerateFullPaths)); param = "KeyContainer"; this.CheckHostObjectSupport(param, cscHostObject.SetKeyContainer(this.KeyContainer)); param = "KeyFile"; this.CheckHostObjectSupport(param, cscHostObject.SetKeyFile(this.KeyFile)); param = "LangVersion"; this.CheckHostObjectSupport(param, cscHostObject.SetLangVersion(this.LangVersion)); param = "MainEntryPoint"; this.CheckHostObjectSupport(param, cscHostObject.SetMainEntryPoint(this.TargetType, this.MainEntryPoint)); param = "ModuleAssemblyName"; this.CheckHostObjectSupport(param, cscHostObject.SetModuleAssemblyName(this.ModuleAssemblyName)); param = "NoConfig"; this.CheckHostObjectSupport(param, cscHostObject.SetNoConfig(this.NoConfig)); param = "NoStandardLib"; this.CheckHostObjectSupport(param, cscHostObject.SetNoStandardLib(this.NoStandardLib)); param = "Optimize"; this.CheckHostObjectSupport(param, cscHostObject.SetOptimize(this.Optimize)); param = "OutputAssembly"; this.CheckHostObjectSupport(param, cscHostObject.SetOutputAssembly(this.OutputAssembly.ItemSpec)); param = "PdbFile"; this.CheckHostObjectSupport(param, cscHostObject.SetPdbFile(this.PdbFile)); // For host objects which support it, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion ICscHostObject4 cscHostObject4 = cscHostObject as ICscHostObject4; if (cscHostObject4 != null) { param = "PlatformWith32BitPreference"; this.CheckHostObjectSupport(param, cscHostObject4.SetPlatformWith32BitPreference(this.PlatformWith32BitPreference)); param = "HighEntropyVA"; this.CheckHostObjectSupport(param, cscHostObject4.SetHighEntropyVA(this.HighEntropyVA)); param = "SubsystemVersion"; this.CheckHostObjectSupport(param, cscHostObject4.SetSubsystemVersion(this.SubsystemVersion)); } else { param = "Platform"; this.CheckHostObjectSupport(param, cscHostObject.SetPlatform(this.Platform)); } // For host objects which support it, set the analyzer ruleset and additional files. IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject; if (analyzerHostObject != null) { param = "CodeAnalysisRuleSet"; this.CheckHostObjectSupport(param, analyzerHostObject.SetRuleSet(this.CodeAnalysisRuleSet)); param = "AdditionalFiles"; this.CheckHostObjectSupport(param, analyzerHostObject.SetAdditionalFiles(this.AdditionalFiles)); } param = "ResponseFiles"; this.CheckHostObjectSupport(param, cscHostObject.SetResponseFiles(this.ResponseFiles)); param = "TargetType"; this.CheckHostObjectSupport(param, cscHostObject.SetTargetType(this.TargetType)); param = "TreatWarningsAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetTreatWarningsAsErrors(this.TreatWarningsAsErrors)); param = "WarningLevel"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningLevel(this.WarningLevel)); // This must come after TreatWarningsAsErrors. param = "WarningsAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningsAsErrors(this.WarningsAsErrors)); // This must come after TreatWarningsAsErrors. param = "WarningsNotAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningsNotAsErrors(this.WarningsNotAsErrors)); param = "Win32Icon"; this.CheckHostObjectSupport(param, cscHostObject.SetWin32Icon(this.Win32Icon)); // In order to maintain compatibility with previous host compilers, we must // light-up for ICscHostObject2/ICscHostObject3 if (cscHostObject is ICscHostObject2) { ICscHostObject2 cscHostObject2 = (ICscHostObject2)cscHostObject; param = "Win32Manifest"; this.CheckHostObjectSupport(param, cscHostObject2.SetWin32Manifest(this.GetWin32ManifestSwitch(this.NoWin32Manifest, this.Win32Manifest))); } else { // If we have been given a property that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler if (!String.IsNullOrEmpty(Win32Manifest)) { this.CheckHostObjectSupport("Win32Manifest", false); } } // This must come after Win32Manifest param = "Win32Resource"; this.CheckHostObjectSupport(param, cscHostObject.SetWin32Resource(this.Win32Resource)); if (cscHostObject is ICscHostObject3) { ICscHostObject3 cscHostObject3 = (ICscHostObject3)cscHostObject; param = "ApplicationConfiguration"; this.CheckHostObjectSupport(param, cscHostObject3.SetApplicationConfiguration(this.ApplicationConfiguration)); } else { // If we have been given a property that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler if (!String.IsNullOrEmpty(ApplicationConfiguration)) { this.CheckHostObjectSupport("ApplicationConfiguration", false); } } // If we have been given a property value that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler. // Null is supported because it means that option should be omitted, and compiler default used - obviously always valid. // Explicitly specified name of current locale is also supported, since it is effectively a no-op. // Other options are not supported since in-proc compiler always uses current locale. if (!String.IsNullOrEmpty(PreferredUILang) && !String.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase)) { this.CheckHostObjectSupport("PreferredUILang", false); } } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } if (this.HostCompilerSupportsAllParameters) { // If the host compiler doesn't support everything we need, we're going to end up // shelling out to the command-line compiler anyway. That means the command-line // compiler will log the error. So here, we only log the error if we would've // tried to use the host compiler. Log.LogErrorWithCodeFromResources("General.CouldNotSetHostObjectParameter", param, e.Message); } return false; } finally { int errorCode; string errorMessage; success = cscHostObject.EndInitialization(out errorMessage, out errorCode); if (this.HostCompilerSupportsAllParameters) { // If the host compiler doesn't support everything we need, we're going to end up // shelling out to the command-line compiler anyway. That means the command-line // compiler will log the error. So here, we only log the error if we would've // tried to use the host compiler. // If EndInitialization returns false, then there was an error. If EndInitialization was // successful, but there is a valid 'errorMessage,' interpret it as a warning. if (!success) { Log.LogError(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage); } else if (errorMessage != null && errorMessage.Length > 0) { Log.LogWarning(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage); } } } return (success); } /// <summary> /// This method will get called during Execute() if a host object has been passed into the Csc /// task. Returns one of the following values to indicate what the next action should be: /// UseHostObjectToExecute Host compiler exists and was initialized. /// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate. /// NoActionReturnSuccess Host compiler was already up-to-date, and we're done. /// NoActionReturnFailure Bad parameters were passed into the task. /// </summary> override protected HostObjectInitializationStatus InitializeHostObject() { if (this.HostObject != null) { // When the host object was passed into the task, it was passed in as a generic // "Object" (because ITask interface obviously can't have any Csc-specific stuff // in it, and each task is going to want to communicate with its host in a unique // way). Now we cast it to the specific type that the Csc task expects. If the // host object does not match this type, the host passed in an invalid host object // to Csc, and we error out. // NOTE: For compat reasons this must remain ICscHostObject // we can dynamically test for smarter interfaces later.. using (RCWForCurrentContext<ICscHostObject> hostObject = new RCWForCurrentContext<ICscHostObject>(this.HostObject as ICscHostObject)) { ICscHostObject cscHostObject = hostObject.RCW; if (cscHostObject != null) { bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(cscHostObject); // If we're currently only in design-time (as opposed to build-time), // then we're done. We've initialized the host compiler as best we // can, and we certainly don't want to actually do the final compile. // So return true, saying we're done and successful. if (cscHostObject.IsDesignTime()) { // If we are design-time then we do not want to continue the build at // this time. return hostObjectSuccessfullyInitialized ? HostObjectInitializationStatus.NoActionReturnSuccess : HostObjectInitializationStatus.NoActionReturnFailure; } if (!this.HostCompilerSupportsAllParameters || UseAlternateCommandLineToolToExecute()) { // Since the host compiler has refused to take on the responsibility for this compilation, // we're about to shell out to the command-line compiler to handle it. If some of the // references don't exist on disk, we know the command-line compiler will fail, so save // the trouble, and just throw a consistent error ourselves. This allows us to give // more information than the compiler would, and also make things consistent across // Vbc / Csc / etc. // This suite behaves differently in localized builds than on English builds because // VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it. if (!CheckAllReferencesExistOnDisk()) { return HostObjectInitializationStatus.NoActionReturnFailure; } // The host compiler doesn't support some of the switches/parameters // being passed to it. Therefore, we resort to using the command-line compiler // in this case. UsedCommandLineTool = true; return HostObjectInitializationStatus.UseAlternateToolToExecute; } // Ok, by now we validated that the host object supports the necessary switches // and parameters. Last thing to check is whether the host object is up to date, // and in that case, we will inform the caller that no further action is necessary. if (hostObjectSuccessfullyInitialized) { return cscHostObject.IsUpToDate() ? HostObjectInitializationStatus.NoActionReturnSuccess : HostObjectInitializationStatus.UseHostObjectToExecute; } else { return HostObjectInitializationStatus.NoActionReturnFailure; } } else { Log.LogErrorWithCodeFromResources("General.IncorrectHostObject", "Csc", "ICscHostObject"); } } } // No appropriate host object was found. UsedCommandLineTool = true; return HostObjectInitializationStatus.UseAlternateToolToExecute; } /// <summary> /// This method will get called during Execute() if a host object has been passed into the Csc /// task. Returns true if the compilation succeeded, otherwise false. /// </summary> override protected bool CallHostObjectToExecute() { Debug.Assert(this.HostObject != null, "We should not be here if the host object has not been set."); ICscHostObject cscHostObject = this.HostObject as ICscHostObject; Debug.Assert(cscHostObject != null, "Wrong kind of host object passed in!"); try { #if (!STANDALONEBUILD) CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfMSBuildHostCompileBegin); #endif return cscHostObject.Compile(); } finally { #if (!STANDALONEBUILD) CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfMSBuildHostCompileEnd); #endif } } } }
MetSystem/msbuild
src/XMakeTasks/Csc.cs
C#
mit
41,306
require 'active_support/core_ext/array' require 'active_support/core_ext/hash/except' require 'active_support/core_ext/kernel/singleton_class' require 'active_support/core_ext/object/blank' module ActiveRecord # = Active Record Named \Scopes module NamedScope extend ActiveSupport::Concern module ClassMethods # Returns an anonymous \scope. # # posts = Post.scoped # posts.size # Fires "select count(*) from posts" and returns the count # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects # # fruits = Fruit.scoped # fruits = fruits.where(:colour => 'red') if options[:red_only] # fruits = fruits.limit(10) if limited? # # Anonymous \scopes tend to be useful when procedurally generating complex # queries, where passing intermediate values (\scopes) around as first-class # objects is convenient. # # You can define a \scope that applies to all finders using # ActiveRecord::Base.default_scope. def scoped(options = nil) if options scoped.apply_finder_options(options) else current_scoped_methods ? relation.merge(current_scoped_methods) : relation.clone end end def scopes read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {}) end # Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query, # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>. # # class Shirt < ActiveRecord::Base # scope :red, where(:color => 'red') # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) # end # # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>. # # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance, # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>. # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable; # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> # all behave as if Shirt.red really was an Array. # # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce # all shirts that are both red and dry clean only. # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> # returns the number of garments for which these criteria obtain. Similarly with # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. # # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If, # # class Person < ActiveRecord::Base # has_many :shirts # end # # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean # only shirts. # # Named \scopes can also be procedural: # # class Shirt < ActiveRecord::Base # scope :colored, lambda {|color| where(:color => color) } # end # # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. # # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: # # class Shirt < ActiveRecord::Base # scope :red, where(:color => 'red') do # def dom_id # 'red_shirts' # end # end # end # # Scopes can also be used while creating/building a record. # # class Article < ActiveRecord::Base # scope :published, where(:published => true) # end # # Article.published.new.published # => true # Article.published.create.published # => true def scope(name, scope_options = {}, &block) name = name.to_sym valid_scope_name?(name) extension = Module.new(&block) if block_given? scopes[name] = lambda do |*args| options = scope_options.is_a?(Proc) ? scope_options.call(*args) : scope_options relation = if options.is_a?(Hash) scoped.apply_finder_options(options) elsif options scoped.merge(options) else scoped end extension ? relation.extending(extension) : relation end singleton_class.send(:redefine_method, name, &scopes[name]) end def named_scope(*args, &block) ActiveSupport::Deprecation.warn("Base.named_scope has been deprecated, please use Base.scope instead", caller) scope(*args, &block) end protected def valid_scope_name?(name) if !scopes[name] && respond_to?(name, true) logger.warn "Creating scope :#{name}. " \ "Overwriting existing method #{self.name}.#{name}." end end end end end
mzemel/kpsu.org
vendor/gems/ruby/1.8/gems/activerecord-3.0.3/lib/active_record/named_scope.rb
Ruby
gpl-3.0
5,522
import java.util.*; class Test { private Set<String> foo; void test(Test t1, String s) { t1.foo = new HashSet<>(); t1.foo.add(s); } }
siosio/intellij-community
plugins/IntentionPowerPak/test/com/siyeh/ipp/collections/to_mutable_collection/FieldAssignment_after.java
Java
apache-2.0
151
/// <reference path='fourslash.ts' /> ////function functionOverload(); ////function functionOverload(test: string); ////function functionOverload(test?: string) { } ////functionOverload(/*functionOverload1*/); ////functionOverload(""/*functionOverload2*/); verify.signatureHelp( { marker: "functionOverload1", overloadsCount: 2, text: "functionOverload(): any", parameterCount: 0, }, { marker: "functionOverload2", overloadsCount: 2, text: "functionOverload(test: string): any", parameterName: "test", parameterSpan: "test: string", }, );
domchen/typescript-plus
tests/cases/fourslash/signatureHelpFunctionOverload.ts
TypeScript
apache-2.0
652
/* * Copyright 2010 the original author or 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 org.spockframework.runtime.condition; public interface IObjectRendererService extends IObjectRenderer<Object> { <T> void addRenderer(Class<T> type, IObjectRenderer<? super T> renderer); }
spockframework/spock
spock-core/src/main/java/org/spockframework/runtime/condition/IObjectRendererService.java
Java
apache-2.0
809
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectView.impl.nodes; import com.intellij.ide.IdeBundle; import com.intellij.ide.projectView.PresentationData; import com.intellij.ide.projectView.ProjectViewNode; import com.intellij.ide.projectView.ViewSettings; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.libraries.LibraryEx; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryType; import com.intellij.openapi.roots.libraries.PersistentLibraryKind; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class LibraryGroupNode extends ProjectViewNode<LibraryGroupElement> { public LibraryGroupNode(Project project, @NotNull LibraryGroupElement value, ViewSettings viewSettings) { super(project, value, viewSettings); } @Override @NotNull public Collection<AbstractTreeNode<?>> getChildren() { Module module = getValue().getModule(); ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); List<AbstractTreeNode<?>> children = new ArrayList<>(); OrderEntry[] orderEntries = moduleRootManager.getOrderEntries(); for (final OrderEntry orderEntry : orderEntries) { if (orderEntry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)orderEntry; final Library library = libraryOrderEntry.getLibrary(); if (library == null) { continue; } final String libraryName = library.getName(); if (libraryName == null || libraryName.length() == 0) { addLibraryChildren(libraryOrderEntry, children, getProject(), this); } else { children.add(new NamedLibraryElementNode(getProject(), new NamedLibraryElement(module, libraryOrderEntry), getSettings())); } } else if (orderEntry instanceof JdkOrderEntry) { final JdkOrderEntry jdkOrderEntry = (JdkOrderEntry)orderEntry; final Sdk jdk = jdkOrderEntry.getJdk(); if (jdk != null) { children.add(new NamedLibraryElementNode(getProject(), new NamedLibraryElement(module, jdkOrderEntry), getSettings())); } } } return children; } public static void addLibraryChildren(LibraryOrSdkOrderEntry entry, List<? super AbstractTreeNode<?>> children, Project project, ProjectViewNode node) { final PsiManager psiManager = PsiManager.getInstance(project); VirtualFile[] files = entry instanceof LibraryOrderEntry ? getLibraryRoots((LibraryOrderEntry)entry) : entry.getRootFiles(OrderRootType.CLASSES); for (final VirtualFile file : files) { if (!file.isValid()) continue; if (file.isDirectory()) { final PsiDirectory psiDir = psiManager.findDirectory(file); if (psiDir == null) { continue; } children.add(new PsiDirectoryNode(project, psiDir, node.getSettings())); } else { final PsiFile psiFile = psiManager.findFile(file); if (psiFile == null) continue; children.add(new PsiFileNode(project, psiFile, node.getSettings())); } } } @Override public String getTestPresentation() { return "Libraries"; } @Override public boolean contains(@NotNull VirtualFile file) { final ProjectFileIndex index = ProjectRootManager.getInstance(getProject()).getFileIndex(); if (!index.isInLibrary(file)) { return false; } return someChildContainsFile(file, false); } @Override public void update(@NotNull PresentationData presentation) { presentation.setPresentableText(IdeBundle.message("node.projectview.libraries")); presentation.setIcon(PlatformIcons.LIBRARY_ICON); } @Override public boolean canNavigate() { return ProjectSettingsService.getInstance(myProject).canOpenModuleLibrarySettings(); } @Override public void navigate(final boolean requestFocus) { Module module = getValue().getModule(); ProjectSettingsService.getInstance(myProject).openModuleLibrarySettings(module); } public static VirtualFile @NotNull [] getLibraryRoots(@NotNull LibraryOrderEntry orderEntry) { Library library = orderEntry.getLibrary(); if (library == null) return VirtualFile.EMPTY_ARRAY; OrderRootType[] rootTypes = LibraryType.DEFAULT_EXTERNAL_ROOT_TYPES; if (library instanceof LibraryEx) { if (((LibraryEx)library).isDisposed()) return VirtualFile.EMPTY_ARRAY; PersistentLibraryKind<?> libKind = ((LibraryEx)library).getKind(); if (libKind != null) { rootTypes = LibraryType.findByKind(libKind).getExternalRootTypes(); } } final ArrayList<VirtualFile> files = new ArrayList<>(); for (OrderRootType rootType : rootTypes) { files.addAll(Arrays.asList(library.getFiles(rootType))); } return VfsUtilCore.toVirtualFileArray(files); } }
siosio/intellij-community
platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/LibraryGroupNode.java
Java
apache-2.0
5,590
/** * @fileoverview Rule to enforce spacing around embedded expressions of template strings * @author Toru Nagashima */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const OPEN_PAREN = /\$\{$/u; const CLOSE_PAREN = /^\}/u; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "layout", docs: { description: "require or disallow spacing around embedded expressions of template strings", category: "ECMAScript 6", recommended: false, url: "https://eslint.org/docs/rules/template-curly-spacing" }, fixable: "whitespace", schema: [ { enum: ["always", "never"] } ], messages: { expectedBefore: "Expected space(s) before '}'.", expectedAfter: "Expected space(s) after '${'.", unexpectedBefore: "Unexpected space(s) before '}'.", unexpectedAfter: "Unexpected space(s) after '${'." } }, create(context) { const sourceCode = context.getSourceCode(); const always = context.options[0] === "always"; const prefix = always ? "expected" : "unexpected"; /** * Checks spacing before `}` of a given token. * @param {Token} token A token to check. This is a Template token. * @returns {void} */ function checkSpacingBefore(token) { const prevToken = sourceCode.getTokenBefore(token); if (prevToken && CLOSE_PAREN.test(token.value) && astUtils.isTokenOnSameLine(prevToken, token) && sourceCode.isSpaceBetweenTokens(prevToken, token) !== always ) { context.report({ loc: token.loc.start, messageId: `${prefix}Before`, fix(fixer) { if (always) { return fixer.insertTextBefore(token, " "); } return fixer.removeRange([ prevToken.range[1], token.range[0] ]); } }); } } /** * Checks spacing after `${` of a given token. * @param {Token} token A token to check. This is a Template token. * @returns {void} */ function checkSpacingAfter(token) { const nextToken = sourceCode.getTokenAfter(token); if (nextToken && OPEN_PAREN.test(token.value) && astUtils.isTokenOnSameLine(token, nextToken) && sourceCode.isSpaceBetweenTokens(token, nextToken) !== always ) { context.report({ loc: { line: token.loc.end.line, column: token.loc.end.column - 2 }, messageId: `${prefix}After`, fix(fixer) { if (always) { return fixer.insertTextAfter(token, " "); } return fixer.removeRange([ token.range[1], nextToken.range[0] ]); } }); } } return { TemplateElement(node) { const token = sourceCode.getFirstToken(node); checkSpacingBefore(token); checkSpacingAfter(token); } }; } };
BigBoss424/portfolio
v8/development/node_modules/gatsby/node_modules/eslint/lib/rules/template-curly-spacing.js
JavaScript
apache-2.0
4,149
# Copyright (c) 2017 Keith Ito """ from https://github.com/keithito/tacotron """ ''' Defines the set of symbols used in text input to the model. The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. ''' from . import cmudict _pad = '_' _punctuation = '!\'(),.:;? ' _special = '-' _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' # Prepend "@" to ARPAbet symbols to ensure uniqueness (some are the same as uppercase letters): _arpabet = ['@' + s for s in cmudict.valid_symbols] # Export all symbols: symbols = [_pad] + list(_special) + list(_punctuation) + list(_letters) + _arpabet
mlperf/inference_results_v0.7
open/Inspur/code/rnnt/tensorrt/preprocessing/parts/text/symbols.py
Python
apache-2.0
749
/* * * 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. * */ var server = {}; (function (server) { var USER = 'server.user'; var log = new Log(); /** * Returns the currently logged in user */ server.current = function (session, user) { if (arguments.length > 1) { session.put(USER, user); return user; } return session.get(USER); }; }(server));
hsbhathiya/stratos
components/org.apache.stratos.manager.console/modules/console/scripts/server.js
JavaScript
apache-2.0
1,188
# 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. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_espn_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(5) class SkiaEspnDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaEspnDesktopPageSet, self).__init__( archive_data_file='data/skia_espn_desktop.json') urls_list = [ # Why: #1 sports. 'http://espn.go.com', ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self))
HalCanary/skia-hc
tools/skp/page_sets/skia_espn_desktop.py
Python
bsd-3-clause
1,170
var get = Ember.get; Ember._ResolvedState = Ember.Object.extend({ manager: null, state: null, match: null, object: Ember.computed(function(key) { if (this._object) { return this._object; } else { var state = get(this, 'state'), match = get(this, 'match'), manager = get(this, 'manager'); return state.deserialize(manager, match.hash); } }), hasPromise: Ember.computed(function() { return Ember.canInvoke(get(this, 'object'), 'then'); }).property('object'), promise: Ember.computed(function() { var object = get(this, 'object'); if (Ember.canInvoke(object, 'then')) { return object; } else { return { then: function(success) { success(object); } }; } }).property('object'), transition: function() { var manager = get(this, 'manager'), path = get(this, 'state.path'), object = get(this, 'object'); manager.transitionTo(path, object); } });
teddyzeenny/ember.js
packages/ember-old-router/lib/resolved_state.js
JavaScript
mit
985
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using Orleans; using Orleans.Concurrency; using System.Threading.Tasks; namespace TwitterGrainInterfaces { /// <summary> /// A grain to act as the API into Orleans, and fan out read/writes to multiple hashtag grains /// </summary> public interface ITweetDispatcherGrain : IGrainWithIntegerKey { Task AddScore(int score, string[] hashtags, string tweet); Task<Totals[]> GetTotals(string[] hashtags); } }
TedDBarr/orleans
Samples/TwitterSentiment/TwitterGrainInterfaces/ITweetGrain.cs
C#
mit
1,600
require('mocha'); require('should'); var assert = require('assert'); var support = require('./support'); var App = support.resolve(); var app; describe('app.option', function() { beforeEach(function() { app = new App(); }); it('should set a key-value pair on options:', function() { app.option('a', 'b'); assert(app.options.a === 'b'); }); it('should set an object on options:', function() { app.option({c: 'd'}); assert(app.options.c === 'd'); }); it('should set an option.', function() { app.option('a', 'b'); app.options.should.have.property('a'); }); it('should get an option.', function() { app.option('a', 'b'); app.option('a').should.equal('b'); }); it('should extend the `options` object.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.option('x').should.equal('xxx'); app.option('y').should.equal('yyy'); app.option('z').should.equal('zzz'); }); it('options should be on the `options` object.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.options.x.should.equal('xxx'); app.options.y.should.equal('yyy'); app.options.z.should.equal('zzz'); }); it('should be chainable.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.option({a: 'aaa', b: 'bbb', c: 'ccc'}); app.option('x').should.equal('xxx'); app.option('a').should.equal('aaa'); }); it('should extend the `options` object when the first param is a string.', function() { app.option('foo', {x: 'xxx', y: 'yyy', z: 'zzz'}); app.option('bar', {a: 'aaa', b: 'bbb', c: 'ccc'}); app.option('foo').should.have.property('x'); app.option('bar').should.have.property('a'); app.options.foo.should.have.property('x'); app.options.bar.should.have.property('a'); }); it('should set an option.', function() { app.option('a', 'b'); app.options.should.have.property('a'); }); it('should get an option.', function() { app.option('a', 'b'); app.option('a').should.equal('b'); }); it('should extend the `options` object.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.option('x').should.equal('xxx'); app.option('y').should.equal('yyy'); app.option('z').should.equal('zzz'); }); it('options should be on the `options` object.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.options.x.should.equal('xxx'); app.options.y.should.equal('yyy'); app.options.z.should.equal('zzz'); }); it('should be chainable.', function() { app .option({x: 'xxx', y: 'yyy', z: 'zzz'}) .option({a: 'aaa', b: 'bbb', c: 'ccc'}); app.option('x').should.equal('xxx'); app.option('a').should.equal('aaa'); }); });
Gargitier5/tier5portal
vendors/update/test/app.option.js
JavaScript
mit
2,760
<?php class Foo extends Bar { public function bar($foobar = array(parent::FOOBAR)) {} } ?>
sowbiba/senegal-front
vendor/pdepend/pdepend/src/test/resources/files/Parser/testParserHandlesParentKeywordInMethodParameterDefaultValue.php
PHP
mit
95
<?php /** * Settings screen sidebar for free plugins with a pro version. Display the reasons to upgrade * and the mailing list. */ ?> <!-- Keep Updated --> <div class="postbox"> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span><?php _e('Keep Updated', $this->plugin->name); ?></span></h3> <div class="option"> <p class="description"><?php _e('Subscribe to the newsletter and receive updates on our WordPress Plugins', $this->plugin->name); ?>.</p> </div> <form action="http://n7studios.createsend.com/t/r/s/jdutdyj/" method="post"> <div class="option"> <p> <strong><?php _e('Email', $this->plugin->name); ?></strong> <input id="fieldEmail" name="cm-jdutdyj-jdutdyj" type="email" required /> </p> </div> <div class="option"> <p> <input type="submit" name="submit" value="<?php _e('Subscribe', $this->plugin->name); ?>" class="button button-primary" /> </p> </div> </form> </div>
TheOrchardSolutions/WordPress
wp-content/plugins/wp-to-buffer/_modules/dashboard/views/sidebar-upgrade.php
PHP
gpl-2.0
1,049
// SPDX-License-Identifier: GPL-2.0-or-later package org.dolphinemu.dolphinemu.adapters; import android.content.res.Resources; import android.view.ViewGroup; import androidx.leanback.widget.ImageCardView; import androidx.leanback.widget.Presenter; import org.dolphinemu.dolphinemu.model.TvSettingsItem; import org.dolphinemu.dolphinemu.viewholders.TvSettingsViewHolder; public final class SettingsRowPresenter extends Presenter { public Presenter.ViewHolder onCreateViewHolder(ViewGroup parent) { // Create a new view. ImageCardView settingsCard = new ImageCardView(parent.getContext()); settingsCard.setMainImageAdjustViewBounds(true); settingsCard.setMainImageDimensions(192, 160); settingsCard.setFocusable(true); settingsCard.setFocusableInTouchMode(true); // Use that view to create a ViewHolder. return new TvSettingsViewHolder(settingsCard); } public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) { TvSettingsViewHolder holder = (TvSettingsViewHolder) viewHolder; TvSettingsItem settingsItem = (TvSettingsItem) item; Resources resources = holder.cardParent.getResources(); holder.itemId = settingsItem.getItemId(); holder.cardParent.setTitleText(resources.getString(settingsItem.getLabelId())); holder.cardParent.setMainImage(resources.getDrawable(settingsItem.getIconId(), null)); } public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) { // no op } }
ZephyrSurfer/dolphin
Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/adapters/SettingsRowPresenter.java
Java
gpl-2.0
1,484
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ /* * This file is based on WME Lite. * http://dead-code.org/redir.php?target=wmelite * Copyright (c) 2011 Jan Nedoma */ #include "engines/wintermute/base/base_game.h" #include "engines/wintermute/base/base_scriptable.h" #include "engines/wintermute/base/scriptables/script.h" #include "engines/wintermute/base/scriptables/script_value.h" #include "engines/wintermute/base/scriptables/script_stack.h" namespace Wintermute { bool EmulateHTTPConnectExternalCalls(BaseGame *inGame, ScStack *stack, ScStack *thisStack, ScScript::TExternalFunction *function) { ////////////////////////////////////////////////////////////////////////// // Register // Used to register license key online at Pizza Morgana: Episode 1 - Monsters and Manipulations in the Magical Forest // Specification: external "httpconnect.dll" cdecl long Register(string, long, string, long) // Known usage: Register(<productId>, 65535, <productKey>, 65535) // Known product ID values are: "357868", "353058" and "353006" // Known action: HTTP GET http://keygen.corbomitegames.com/keygen/validateKey.php?action=REGISTER&productId=productId&key=productKey // Returns 1 on success // Returns 0 on firewall error // Returns -1 on invalid product key // Returns -2 on invalid product ID // Returns -3 on expired product key // Returns -4 on invalid machine ID // Returns -5 on number of installations exceeded // Returns -6 on socket error // Returns -7 on no internet connection // Returns -8 on connection reset // Returns -11 on validation temporary unavaliable // Returns -12 on validation error // For some reason always returns -7 for me in a test game ////////////////////////////////////////////////////////////////////////// if (strcmp(function->name, "Register") == 0) { stack->correctParams(4); const char *productId = stack->pop()->getString(); int productIdMaxLen = stack->pop()->getInt(); const char *productKey = stack->pop()->getString(); int productKeyMaxLen = stack->pop()->getInt(); warning("Register(\"%s\",%d,\"%s\",%d) is not implemented", productId , productIdMaxLen, productKey, productKeyMaxLen); stack->pushInt(-7); // "no internet connection" error return STATUS_OK; } ////////////////////////////////////////////////////////////////////////// // Validate // Used to validate something at Pizza Morgana: Episode 1 - Monsters and Manipulations in the Magical Forest // Specification: external "httpconnect.dll" cdecl long Validate() // Known usage: Validate() // Known action: HTTP GET http://keygen.corbomitegames.com/keygen/validateKey.php?action=VALIDATE&productId=Ar&key=Ar // Used only when Debug mode is active or game is started with "INVALID" cmdline parameter // For some reason always returns 1 for me in a test game ////////////////////////////////////////////////////////////////////////// else if (strcmp(function->name, "Validate") == 0) { stack->correctParams(0); // do nothing stack->pushInt(1); return STATUS_OK; } ////////////////////////////////////////////////////////////////////////// // SendHTTPAsync // Used to send game progress events to server at Pizza Morgana: Episode 1 - Monsters and Manipulations in the Magical Forest // Specification: external "httpconnect.dll" cdecl long SendHTTPAsync(string, long, string, long, string, long) // Known usage: SendHTTPAsync("backend.pizzamorgana.com", 65535, <FullURL>, 65535, <Buffer?!>, 65535) // FullURL is formed as "http://backend.pizzamorgana.com/event.php?Event=<EventName>&player=<PlayerName>&extraParams=<ExtraParams>&SN=<ProductKey>&Episode=1&GameTime=<CurrentTime>&UniqueID=<UniqueId>" // Known EventName values are: "GameStart", "ChangeGoal", "EndGame" and "QuitGame" // Known ExtraParams values are: "ACT0", "ACT1", "ACT2", "ACT3", "ACT4", "Ep0FindFood", "Ep0FindCellMenu", "Ep0BroRoom", "Ep0FindKey", "Ep0FindCellMenuKey", "Ep0FindMenuKey", "Ep0FindCell", "Ep0FindMenu", "Ep0OrderPizza", "Ep0GetRidOfVamp", "Ep0GetVampAttention", "Ep0License" // Return value is never used ////////////////////////////////////////////////////////////////////////// else if (strcmp(function->name, "SendHTTPAsync") == 0) { stack->correctParams(6); const char *server = stack->pop()->getString(); int serverMaxLen = stack->pop()->getInt(); const char *fullUrl = stack->pop()->getString(); int fullUrlMaxLen = stack->pop()->getInt(); const char *param5 = stack->pop()->getString(); int param5MaxLen = stack->pop()->getInt(); // TODO: Maybe parse URL and call some Achievements API using ExtraParams values in some late future warning("SendHTTPAsync(\"%s\",%d,\"%s\",%d,\"%s\",%d) is not implemented", server, serverMaxLen, fullUrl, fullUrlMaxLen, param5, param5MaxLen); stack->pushInt(0); return STATUS_OK; } ////////////////////////////////////////////////////////////////////////// // SendRecvHTTP (6 params variant) // Declared at Pizza Morgana: Episode 1 - Monsters and Manipulations in the Magical Forest // Seems to be unused, probably SendRecvHTTP was initially used instead of SendHTTPAsync // Specification: external "httpconnect.dll" cdecl long SendRecvHTTP(string, long, string, long, string, long) // Always returns -7 for me in a test game, probably returns the same network errors as Register() ////////////////////////////////////////////////////////////////////////// else if (strcmp(function->name, "SendRecvHTTP") == 0 && function->nu_params == 6) { stack->correctParams(6); const char *server = stack->pop()->getString(); int serverMaxLen = stack->pop()->getInt(); const char *fullUrl = stack->pop()->getString(); int fullUrlMaxLen = stack->pop()->getInt(); const char *param5 = stack->pop()->getString(); int param5MaxLen = stack->pop()->getInt(); warning("SendRecvHTTP(\"%s\",%d,\"%s\",%d,\"%s\",%d) is not implemented", server, serverMaxLen, fullUrl, fullUrlMaxLen, param5, param5MaxLen); stack->pushInt(-7); // "no internet connection" error return STATUS_OK; } ////////////////////////////////////////////////////////////////////////// // SendRecvHTTP (4 params variant) // Used to call HTTP methods at Zbang! The Game // Specification: external "httpconnect.dll" cdecl long SendRecvHTTP(string, long, string, long) // Known usage: SendRecvHTTP("scoresshort.php?player=<PlayerName>", 65535, <Buffer>, 65535) // Known usage: SendRecvHTTP("/update.php?player=<PlayerName>&difficulty=<Difficulty>&items=<CommaSeparatedItemList>", 65535, <Buffer>, 65535) // My Zbang demo does not have this dll, so there is no way to actually test it with a test game // Return value is never used in Zbang scripts ////////////////////////////////////////////////////////////////////////// else if (strcmp(function->name, "SendRecvHTTP") == 0 && function->nu_params == 4) { stack->correctParams(4); const char *dirUrl = stack->pop()->getString(); int dirUrlMaxLen = stack->pop()->getInt(); /*ScValue *buf =*/ stack->pop(); int bufMaxLen = stack->pop()->getInt(); //TODO: Count items and give scores, persist those values warning("SendRecvHTTP(\"%s\",%d,buf,%d) is not implemented", dirUrl, dirUrlMaxLen, bufMaxLen); stack->pushInt(0); return STATUS_OK; } return STATUS_FAILED; } } // End of namespace Wintermute
somaen/scummvm
engines/wintermute/ext/dll_httpconnect.cpp
C++
gpl-2.0
8,196
<?php // $Id: panels-dashboard-link.tpl.php,v 1.3 2010/10/11 22:56:02 sdboyer Exp $ ?> <div class="dashboard-entry clearfix"> <div class="dashboard-text"> <div class="dashboard-link"> <?php print $link['title']; ?> </div> <div class="description"> <?php print $link['description']; ?> </div> </div> </div>
TransmissionStudios/Transmission
sites/default/modules/panels/templates/panels-dashboard-link.tpl.php
PHP
gpl-2.0
338
tinyMCE.addI18n('ka.wordcount',{words:"Words: "});
freaxmind/miage-l3
web/blog Tim Burton/tim_burton/protected/extensions/tinymce/assets/tiny_mce/plugins/wordc/langs/ka_dlg.js
JavaScript
gpl-3.0
50
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; namespace ICSharpCode.ILSpy.Debugger.Services { /// <summary> /// Very naive parser. /// </summary> static class ParserService { static HashSet<string> mySet = new HashSet<string>(); static ParserService() { mySet.AddRange((new string [] { ".", "{", "}", "(", ")", "[", "]", " ", "=", "+", "-", "/", "%", "*", "&", Environment.NewLine, ";", ",", "~", "!", "?", @"\n", @"\t", @"\r", "|" })); } static void AddRange<T>(this ICollection<T> list, IEnumerable<T> items) { foreach (T item in items) if (!list.Contains(item)) list.Add(item); } /// <summary> /// Returns the variable name /// </summary> /// <param name="fullText"></param> /// <param name="offset"></param> /// <returns></returns> public static string SimpleParseAt(string fullText, int offset) { if (string.IsNullOrEmpty(fullText)) return string.Empty; if (offset <= 0 || offset >= fullText.Length) return string.Empty; string currentValue = fullText[offset].ToString(); if (mySet.Contains(currentValue)) return string.Empty; int left = offset, right = offset; //search left while((!mySet.Contains(currentValue) || currentValue == ".") && left > 0) currentValue = fullText[--left].ToString(); currentValue = fullText[offset].ToString(); // searh right while(!mySet.Contains(currentValue) && right < fullText.Length - 2) currentValue = fullText[++right].ToString(); return fullText.Substring(left + 1, right - 1 - left).Trim(); } } }
damnya/dnSpy
ILSpy/Services/ParserService.cs
C#
gpl-3.0
2,300
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * 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.linkedin.pinot.routing.builder; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.helix.model.InstanceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linkedin.pinot.common.utils.CommonConstants; public class RoutingTableInstancePruner { private static final Logger LOGGER = LoggerFactory.getLogger(RoutingTableInstancePruner.class); private Map<String, InstanceConfig> instanceConfigMap; public RoutingTableInstancePruner(List<InstanceConfig> instanceConfigList) { instanceConfigMap = new HashMap<String, InstanceConfig>(); for (InstanceConfig config : instanceConfigList) { instanceConfigMap.put(config.getInstanceName(), config); } } public boolean isShuttingDown(String instanceName) { if (!instanceConfigMap.containsKey(instanceName)) { return false; } boolean status = false; if (instanceConfigMap.get(instanceName).getRecord().getSimpleField(CommonConstants.Helix.IS_SHUTDOWN_IN_PROGRESS) != null) { try { if (instanceConfigMap.get(instanceName).getRecord() == null) { return false; } if (instanceConfigMap.get(instanceName).getRecord() .getSimpleField(CommonConstants.Helix.IS_SHUTDOWN_IN_PROGRESS) != null) { status = Boolean.valueOf(instanceConfigMap.get(instanceName).getRecord() .getSimpleField(CommonConstants.Helix.IS_SHUTDOWN_IN_PROGRESS)); if (status == true) { LOGGER.info("found an instance : {} in shutting down state", instanceName); } } } catch (Exception e) { LOGGER.error("unknown value found while parsing boolean isShuttingDownField ", e); } } return status; } }
izzizz/pinot
pinot-transport/src/main/java/com/linkedin/pinot/routing/builder/RoutingTableInstancePruner.java
Java
apache-2.0
2,428
/* * Copyright 2011 gitblit.com. * * 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.gitblit.utils; import static org.eclipse.jgit.lib.Constants.encode; import static org.eclipse.jgit.lib.Constants.encodeASCII; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.MessageFormat; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.RawText; import org.eclipse.jgit.util.RawParseUtils; import com.gitblit.models.PathModel.PathChangeModel; import com.gitblit.utils.DiffUtils.DiffStat; /** * Generates an html snippet of a diff in Gitblit's style, tracks changed paths, * and calculates diff stats. * * @author James Moger * */ public class GitBlitDiffFormatter extends DiffFormatter { private final OutputStream os; private final DiffStat diffStat; private PathChangeModel currentPath; private int left, right; public GitBlitDiffFormatter(OutputStream os, String commitId) { super(os); this.os = os; this.diffStat = new DiffStat(commitId); } @Override public void format(DiffEntry ent) throws IOException { currentPath = diffStat.addPath(ent); super.format(ent); } /** * Output a hunk header * * @param aStartLine * within first source * @param aEndLine * within first source * @param bStartLine * within second source * @param bEndLine * within second source * @throws IOException */ @Override protected void writeHunkHeader(int aStartLine, int aEndLine, int bStartLine, int bEndLine) throws IOException { os.write("<tr><th>..</th><th>..</th><td class='hunk_header'>".getBytes()); os.write('@'); os.write('@'); writeRange('-', aStartLine + 1, aEndLine - aStartLine); writeRange('+', bStartLine + 1, bEndLine - bStartLine); os.write(' '); os.write('@'); os.write('@'); os.write("</td></tr>\n".getBytes()); left = aStartLine + 1; right = bStartLine + 1; } protected void writeRange(final char prefix, final int begin, final int cnt) throws IOException { os.write(' '); os.write(prefix); switch (cnt) { case 0: // If the range is empty, its beginning number must // be the // line just before the range, or 0 if the range is // at the // start of the file stream. Here, begin is always 1 // based, // so an empty file would produce "0,0". // os.write(encodeASCII(begin - 1)); os.write(','); os.write('0'); break; case 1: // If the range is exactly one line, produce only // the number. // os.write(encodeASCII(begin)); break; default: os.write(encodeASCII(begin)); os.write(','); os.write(encodeASCII(cnt)); break; } } @Override protected void writeLine(final char prefix, final RawText text, final int cur) throws IOException { // update entry diffstat currentPath.update(prefix); // output diff os.write("<tr>".getBytes()); switch (prefix) { case '+': os.write(("<th></th><th>" + (right++) + "</th>").getBytes()); os.write("<td><div class=\"diff add2\">".getBytes()); break; case '-': os.write(("<th>" + (left++) + "</th><th></th>").getBytes()); os.write("<td><div class=\"diff remove2\">".getBytes()); break; default: os.write(("<th>" + (left++) + "</th><th>" + (right++) + "</th>").getBytes()); os.write("<td>".getBytes()); break; } os.write(prefix); String line = text.getString(cur); line = StringUtils.escapeForHtml(line, false); os.write(encode(line)); switch (prefix) { case '+': case '-': os.write("</div>".getBytes()); break; default: os.write("</td>".getBytes()); } os.write("</tr>\n".getBytes()); } /** * Workaround function for complex private methods in DiffFormatter. This * sets the html for the diff headers. * * @return */ public String getHtml() { ByteArrayOutputStream bos = (ByteArrayOutputStream) os; String html = RawParseUtils.decode(bos.toByteArray()); String[] lines = html.split("\n"); StringBuilder sb = new StringBuilder(); boolean inFile = false; String oldnull = "a/dev/null"; for (String line : lines) { if (line.startsWith("index")) { // skip index lines } else if (line.startsWith("new file")) { // skip new file lines } else if (line.startsWith("\\ No newline")) { // skip no new line } else if (line.startsWith("---") || line.startsWith("+++")) { // skip --- +++ lines } else if (line.startsWith("diff")) { line = StringUtils.convertOctal(line); if (line.indexOf(oldnull) > -1) { // a is null, use b line = line.substring(("diff --git " + oldnull).length()).trim(); // trim b/ line = line.substring(2).trim(); } else { // use a line = line.substring("diff --git ".length()).trim(); line = line.substring(line.startsWith("\"a/") ? 3 : 2); line = line.substring(0, line.indexOf(" b/") > -1 ? line.indexOf(" b/") : line.indexOf("\"b/")).trim(); } if (line.charAt(0) == '"') { line = line.substring(1); } if (line.charAt(line.length() - 1) == '"') { line = line.substring(0, line.length() - 1); } if (inFile) { sb.append("</tbody></table></div>\n"); inFile = false; } sb.append(MessageFormat.format("<div class='header'><div class=\"diffHeader\" id=\"{0}\"><i class=\"icon-file\"></i> ", line)).append(line).append("</div></div>"); sb.append("<div class=\"diff\">"); sb.append("<table><tbody>"); inFile = true; } else { boolean gitLinkDiff = line.length() > 0 && line.substring(1).startsWith("Subproject commit"); if (gitLinkDiff) { sb.append("<tr><th></th><th></th>"); if (line.charAt(0) == '+') { sb.append("<td><div class=\"diff add2\">"); } else { sb.append("<td><div class=\"diff remove2\">"); } } sb.append(line); if (gitLinkDiff) { sb.append("</div></td></tr>"); } } } sb.append("</table></div>"); return sb.toString(); } public DiffStat getDiffStat() { return diffStat; } }
culmat/gitblit
src/main/java/com/gitblit/utils/GitBlitDiffFormatter.java
Java
apache-2.0
6,842
/** * 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.docker.headers; import java.util.Map; import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.core.command.WaitContainerResultCallback; import org.apache.camel.component.docker.DockerConstants; import org.apache.camel.component.docker.DockerOperation; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; /** * Validates Wait Container Request headers are applied properly */ public class WaitContainerCmdHeaderTest extends BaseDockerHeaderTest<WaitContainerCmd> { @Mock private WaitContainerCmd mockObject; @Mock private WaitContainerResultCallback callback; @Test public void waitContainerHeaderTest() { String containerId = "9c09acd48a25"; Map<String, Object> headers = getDefaultParameters(); headers.put(DockerConstants.DOCKER_CONTAINER_ID, containerId); template.sendBodyAndHeaders("direct:in", "", headers); Mockito.verify(dockerClient, Mockito.times(1)).waitContainerCmd(containerId); } @Override protected void setupMocks() { Mockito.when(dockerClient.waitContainerCmd(anyString())).thenReturn(mockObject); Mockito.when(mockObject.exec(any())).thenReturn(callback); Mockito.when(callback.awaitStatusCode()).thenReturn(anyInt()); } @Override protected DockerOperation getOperation() { return DockerOperation.WAIT_CONTAINER; } }
punkhorn/camel-upstream
components/camel-docker/src/test/java/org/apache/camel/component/docker/headers/WaitContainerCmdHeaderTest.java
Java
apache-2.0
2,429
/* * 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.cassandra.utils; import java.io.DataInputStream; import java.io.IOException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.AbstractSerializationsTester; import org.apache.cassandra.Util; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.marshal.Int32Type; import org.apache.cassandra.io.util.DataInputPlus.DataInputStreamPlus; import org.apache.cassandra.io.util.DataOutputStreamPlus; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.Murmur3Partitioner; import java.io.File; import java.io.FileInputStream; public class SerializationsTest extends AbstractSerializationsTester { @BeforeClass public static void initDD() { DatabaseDescriptor.daemonInitialization(); } private static void testBloomFilterWrite(boolean offheap) throws IOException { IPartitioner partitioner = Util.testPartitioner(); try (IFilter bf = FilterFactory.getFilter(1000000, 0.0001, offheap)) { for (int i = 0; i < 100; i++) bf.add(partitioner.decorateKey(partitioner.getTokenFactory().toByteArray(partitioner.getRandomToken()))); try (DataOutputStreamPlus out = getOutput("3.0", "utils.BloomFilter.bin")) { FilterFactory.serialize(bf, out); } } } private static void testBloomFilterWrite1000(boolean offheap) throws IOException { try (IFilter bf = FilterFactory.getFilter(1000000, 0.0001, offheap)) { for (int i = 0; i < 1000; i++) bf.add(Util.dk(Int32Type.instance.decompose(i))); try (DataOutputStreamPlus out = getOutput("3.0", "utils.BloomFilter1000.bin")) { FilterFactory.serialize(bf, out); } } } @Test public void testBloomFilterRead1000() throws IOException { if (EXECUTE_WRITES) testBloomFilterWrite1000(true); try (DataInputStream in = getInput("3.0", "utils.BloomFilter1000.bin"); IFilter filter = FilterFactory.deserialize(in, true)) { boolean present; for (int i = 0 ; i < 1000 ; i++) { present = filter.isPresent(Util.dk(Int32Type.instance.decompose(i))); Assert.assertTrue(present); } for (int i = 1000 ; i < 2000 ; i++) { present = filter.isPresent(Util.dk(Int32Type.instance.decompose(i))); Assert.assertFalse(present); } } } @Test public void testBloomFilterTable() throws Exception { testBloomFilterTable("test/data/bloom-filter/la/foo/la-1-big-Filter.db"); } private static void testBloomFilterTable(String file) throws Exception { Murmur3Partitioner partitioner = new Murmur3Partitioner(); try (DataInputStream in = new DataInputStream(new FileInputStream(new File(file))); IFilter filter = FilterFactory.deserialize(in, true)) { for (int i = 1; i <= 10; i++) { DecoratedKey decoratedKey = partitioner.decorateKey(Int32Type.instance.decompose(i)); boolean present = filter.isPresent(decoratedKey); Assert.assertTrue(present); } int positives = 0; for (int i = 11; i <= 1000010; i++) { DecoratedKey decoratedKey = partitioner.decorateKey(Int32Type.instance.decompose(i)); boolean present = filter.isPresent(decoratedKey); if (present) positives++; } double fpr = positives; fpr /= 1000000; Assert.assertTrue(fpr <= 0.011d); } } private static void testEstimatedHistogramWrite() throws IOException { EstimatedHistogram hist0 = new EstimatedHistogram(); EstimatedHistogram hist1 = new EstimatedHistogram(5000); long[] offsets = new long[1000]; long[] data = new long[offsets.length + 1]; for (int i = 0; i < offsets.length; i++) { offsets[i] = i; data[i] = 10 * i; } data[offsets.length] = 100000; EstimatedHistogram hist2 = new EstimatedHistogram(offsets, data); try (DataOutputStreamPlus out = getOutput("utils.EstimatedHistogram.bin")) { EstimatedHistogram.serializer.serialize(hist0, out); EstimatedHistogram.serializer.serialize(hist1, out); EstimatedHistogram.serializer.serialize(hist2, out); } } @Test public void testEstimatedHistogramRead() throws IOException { if (EXECUTE_WRITES) testEstimatedHistogramWrite(); try (DataInputStreamPlus in = getInput("utils.EstimatedHistogram.bin")) { Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in)); Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in)); Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in)); } } }
hengxin/cassandra
test/unit/org/apache/cassandra/utils/SerializationsTest.java
Java
apache-2.0
6,082
// Copyright Louis Dionne 2013-2016 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/and.hpp> #include <boost/hana/assert.hpp> #include <boost/hana/bool.hpp> namespace hana = boost::hana; BOOST_HANA_CONSTANT_CHECK(hana::and_(hana::true_c, hana::true_c, hana::true_c, hana::true_c)); static_assert(!hana::and_(hana::true_c, false, hana::true_c, hana::true_c), ""); int main() { }
bureau14/qdb-benchmark
thirdparty/boost/libs/hana/example/and.cpp
C++
bsd-2-clause
499
// No generics for getters and setters ({ set foo<T>(newFoo) {} })
facebook/flow
src/parser/test/flow/invalid_syntax/migrated_0012.js
JavaScript
mit
67
export const tinyNDArray: any;
markogresak/DefinitelyTyped
types/poisson-disk-sampling/src/tiny-ndarray.d.ts
TypeScript
mit
31
//------------------------------------------------------------------------------ // <copyright file="ValueOfAction.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Xsl.XsltOld { using Res = System.Xml.Utils.Res; using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; internal class ValueOfAction : CompiledAction { private const int ResultStored = 2; private int selectKey = Compiler.InvalidQueryKey; private bool disableOutputEscaping; private static Action s_BuiltInRule = new BuiltInRuleTextAction(); internal static Action BuiltInRule() { Debug.Assert(s_BuiltInRule != null); return s_BuiltInRule; } internal override void Compile(Compiler compiler) { CompileAttributes(compiler); CheckRequiredAttribute(compiler, selectKey != Compiler.InvalidQueryKey, "select"); CheckEmpty(compiler); } internal override bool CompileAttribute(Compiler compiler) { string name = compiler.Input.LocalName; string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Select)) { this.selectKey = compiler.AddQuery(value); } else if (Ref.Equal(name, compiler.Atoms.DisableOutputEscaping)) { this.disableOutputEscaping = compiler.GetYesNo(value); } else { return false; } return true; } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); switch (frame.State) { case Initialized: Debug.Assert(frame != null); Debug.Assert(frame.NodeSet != null); string value = processor.ValueOf(frame, this.selectKey); if (processor.TextEvent(value, disableOutputEscaping)) { frame.Finished(); } else { frame.StoredOutput = value; frame.State = ResultStored; } break; case ResultStored: Debug.Assert(frame.StoredOutput != null); processor.TextEvent(frame.StoredOutput); frame.Finished(); break; default: Debug.Fail("Invalid ValueOfAction execution state"); break; } } } internal class BuiltInRuleTextAction : Action { private const int ResultStored = 2; internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); switch (frame.State) { case Initialized: Debug.Assert(frame != null); Debug.Assert(frame.NodeSet != null); string value = processor.ValueOf(frame.NodeSet.Current); if (processor.TextEvent(value, /*disableOutputEscaping:*/false)) { frame.Finished(); } else { frame.StoredOutput = value; frame.State = ResultStored; } break; case ResultStored: Debug.Assert(frame.StoredOutput != null); processor.TextEvent(frame.StoredOutput); frame.Finished(); break; default: Debug.Fail("Invalid BuiltInRuleTextAction execution state"); break; } } } }
sekcheong/referencesource
System.Data.SqlXml/System/Xml/Xsl/XsltOld/ValueOfAction.cs
C#
mit
3,999
/* * Copyright (c) 2010, 2013, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. */ package jdk.nashorn.internal.objects.annotations; import static jdk.nashorn.internal.objects.annotations.Attribute.DEFAULT_ATTRIBUTES; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to specify the getter method for a JavaScript "data" property. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Getter { /** * Name of the property. If empty, the name is inferred. */ public String name() default ""; /** * Attribute flags for this setter. */ public int attributes() default DEFAULT_ATTRIBUTES; /** * Where this getter lives? */ public Where where() default Where.INSTANCE; }
rokn/Count_Words_2015
testing/openjdk2/nashorn/src/jdk/nashorn/internal/objects/annotations/Getter.java
Java
mit
2,016
/* * eXist Open Source Native XML Database * Copyright (C) 2009-2011 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.debuggee.dbgp.packets; import org.apache.mina.core.session.IoSession; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class StepInto extends AbstractCommandContinuation { public StepInto(IoSession session, String args) { super(session, args); } /* (non-Javadoc) * @see org.exist.debuggee.dgbp.packets.Command#exec() */ @Override public synchronized void exec() { getJoint().continuation(this); } public synchronized byte[] responseBytes() { String responce = xml_declaration + "<response " + namespaces + "command=\"step_into\" " + "status=\""+getStatus()+"\" " + "reason=\"ok\" " + "transaction_id=\""+transactionID+"\"/>"; return responce.getBytes(); } public byte[] commandBytes() { String command = "step_into -i "+transactionID; return command.getBytes(); } public int getType() { return STEP_INTO; } public boolean is(int type) { return (type == STEP_INTO); } public String toString() { return "step_into ["+transactionID+"]"; } }
MjAbuz/exist
extensions/debuggee/src/org/exist/debuggee/dbgp/packets/StepInto.java
Java
lgpl-2.1
1,942
package bootstrappolicy import ( rbacrest "k8s.io/kubernetes/pkg/registry/rbac/rest" ) func Policy() *rbacrest.PolicyData { return &rbacrest.PolicyData{ ClusterRoles: GetBootstrapClusterRoles(), ClusterRoleBindings: GetBootstrapClusterRoleBindings(), Roles: GetBootstrapNamespaceRoles(), RoleBindings: GetBootstrapNamespaceRoleBindings(), } }
kedgeproject/kedge
vendor/github.com/openshift/origin/pkg/cmd/server/bootstrappolicy/all.go
GO
apache-2.0
384
/* * 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.jclouds.aws.ec2.features; import static org.jclouds.aws.reference.FormParameters.ACTION; import java.util.Set; import javax.inject.Named; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404; import org.jclouds.aws.ec2.domain.AWSRunningInstance; import org.jclouds.aws.ec2.xml.AWSDescribeInstancesResponseHandler; import org.jclouds.aws.ec2.xml.AWSRunInstancesResponseHandler; import org.jclouds.aws.filters.FormSigner; import org.jclouds.ec2.binders.BindFiltersToIndexedFormParams; import org.jclouds.ec2.binders.BindInstanceIdsToIndexedFormParams; import org.jclouds.ec2.binders.IfNotNullBindAvailabilityZoneToFormParam; import org.jclouds.ec2.domain.Reservation; import org.jclouds.ec2.features.InstanceApi; import org.jclouds.ec2.options.RunInstancesOptions; import org.jclouds.javax.annotation.Nullable; import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.EndpointParam; import org.jclouds.rest.annotations.Fallback; import org.jclouds.rest.annotations.FormParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.XMLResponseParser; import com.google.common.collect.Multimap; /** * Provides access to EC2 Instance Services via their REST API. * <p/> */ @RequestFilters(FormSigner.class) @VirtualHost public interface AWSInstanceApi extends InstanceApi { @Named("DescribeInstances") @Override @POST @Path("/") @FormParams(keys = ACTION, values = "DescribeInstances") @XMLResponseParser(AWSDescribeInstancesResponseHandler.class) @Fallback(EmptySetOnNotFoundOr404.class) Set<? extends Reservation<? extends AWSRunningInstance>> describeInstancesInRegion( @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds); @Named("DescribeInstances") @POST @Path("/") @FormParams(keys = ACTION, values = "DescribeInstances") @XMLResponseParser(AWSDescribeInstancesResponseHandler.class) @Fallback(EmptySetOnNotFoundOr404.class) Set<? extends Reservation<? extends AWSRunningInstance>> describeInstancesInRegionWithFilter( @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter); @Named("RunInstances") @Override @POST @Path("/") @FormParams(keys = ACTION, values = "RunInstances") @XMLResponseParser(AWSRunInstancesResponseHandler.class) Reservation<? extends AWSRunningInstance> runInstancesInRegion( @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @Nullable @BinderParam(IfNotNullBindAvailabilityZoneToFormParam.class) String nullableAvailabilityZone, @FormParam("ImageId") String imageId, @FormParam("MinCount") int minCount, @FormParam("MaxCount") int maxCount, RunInstancesOptions... options); }
yanzhijun/jclouds-aliyun
providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/AWSInstanceApi.java
Java
apache-2.0
4,022
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * 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.linkedin.pinot.core.realtime; public class RealtimeIntegrationTest { public void endToEndTest(){ //start zk server //setup cluster //setup realtime resource //start controller //start participants } }
pinotlytics/pinot
pinot-core/src/test/java/com/linkedin/pinot/core/realtime/RealtimeIntegrationTest.java
Java
apache-2.0
877
/* * 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.ignite.internal.processors.query.oom; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * Test suite for queries produces OOME in some cases. */ @RunWith(Suite.class) @Suite.SuiteClasses({ //Query history. QueryOOMWithoutQueryParallelismTest.class, QueryOOMWithQueryParallelismTest.class, }) public class IgniteQueryOOMTestSuite { }
NSAmelchev/ignite
modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/oom/IgniteQueryOOMTestSuite.java
Java
apache-2.0
1,192
/* * Copyright 2016 Rethink Robotics * * Copyright 2016 Chris Smith * * 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. */ 'use strict'; let fs = require('fs'); let path = require('path'); let cmakePath = process.env.CMAKE_PREFIX_PATH; let cmakePaths = cmakePath.split(':'); let jsMsgPath = 'share/gennodejs/ros'; let packagePaths = {}; module.exports = function (messagePackage) { if (packagePaths.hasOwnProperty(messagePackage)) { return packagePaths[messagePackage]; } // else const found = cmakePaths.some((cmakePath) => { let path_ = path.join(cmakePath, jsMsgPath, messagePackage, '_index.js'); if (fs.existsSync(path_)) { packagePaths[messagePackage] = require(path_); return true; } return false; }); if (found) { return packagePaths[messagePackage]; } // else throw new Error('Unable to find message package ' + messagePackage + ' from CMAKE_PREFIX_PATH'); };
tarquasso/softroboticfish6
fish/pi/ros/catkin_ws/src/rosserial/devel/share/gennodejs/ros/rosserial_msgs/find.js
JavaScript
mit
1,464
// Package api provides a generic, low-level WebDriver API client for Go. // All methods map directly to endpoints of the WebDriver Wire Protocol: // https://code.google.com/p/selenium/wiki/JsonWireProtocol // // This package was previously internal to the agouti package. It currently // does not have a fixed API, but this will change in the near future // (with the addition of adequate documentation). package api
johanbrandhorst/protobuf
vendor/github.com/sclevine/agouti/api/api.go
GO
mit
418
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "AreaPostprocessor.h" registerMooseObject("MooseApp", AreaPostprocessor); defineLegacyParams(AreaPostprocessor); InputParameters AreaPostprocessor::validParams() { InputParameters params = SideIntegralPostprocessor::validParams(); params.addClassDescription("Computes the \"area\" or dimension - 1 \"volume\" of a given " "boundary or boundaries in your mesh."); return params; } AreaPostprocessor::AreaPostprocessor(const InputParameters & parameters) : SideIntegralPostprocessor(parameters) { } void AreaPostprocessor::threadJoin(const UserObject & y) { const AreaPostprocessor & pps = static_cast<const AreaPostprocessor &>(y); _integral_value += pps._integral_value; } Real AreaPostprocessor::computeQpIntegral() { return 1.0; }
nuclear-wizard/moose
framework/src/postprocessors/AreaPostprocessor.C
C++
lgpl-2.1
1,109
// ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.net; import java.io.IOException; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Functions; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ListenableFutureTask; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.twitter.common.base.ExceptionalFunction; import com.twitter.common.net.UrlResolver.ResolvedUrl.EndState; import com.twitter.common.quantity.Amount; import com.twitter.common.quantity.Time; import com.twitter.common.stats.PrintableHistogram; import com.twitter.common.util.BackoffStrategy; import com.twitter.common.util.Clock; import com.twitter.common.util.TruncatedBinaryBackoff; import com.twitter.common.util.caching.Cache; import com.twitter.common.util.caching.LRUCache; /** * Class to aid in resolving URLs by following redirects, which can optionally be performed * asynchronously using a thread pool. * * @author William Farner */ public class UrlResolver { private static final Logger LOG = Logger.getLogger(UrlResolver.class.getName()); private static final String TWITTER_UA = "Twitterbot/0.1"; private static final UrlResolverUtil URL_RESOLVER = new UrlResolverUtil(Functions.constant(TWITTER_UA)); private static final ExceptionalFunction<String, String, IOException> RESOLVER = new ExceptionalFunction<String, String, IOException>() { @Override public String apply(String url) throws IOException { return URL_RESOLVER.getEffectiveUrl(url, null); } }; private static ExceptionalFunction<String, String, IOException> getUrlResolver(final @Nullable ProxyConfig proxyConfig) { if (proxyConfig != null) { return new ExceptionalFunction<String, String, IOException>() { @Override public String apply(String url) throws IOException { return URL_RESOLVER.getEffectiveUrl(url, proxyConfig); } }; } else { return RESOLVER; } } private final ExceptionalFunction<String, String, IOException> resolver; private final int maxRedirects; // Tracks the number of active tasks (threads in use). private final Semaphore poolEntrySemaphore; private final Integer threadPoolSize; // Helps with signaling the handler. private final Executor handlerExecutor; // Manages the thread pool and task execution. private ExecutorService executor; // Cache to store resolved URLs. private final Cache<String, String> urlCache = LRUCache.<String, String>builder() .maxSize(10000) .makeSynchronized(true) .build(); // Variables to track connection/request stats. private AtomicInteger requestCount = new AtomicInteger(0); private AtomicInteger cacheHits = new AtomicInteger(0); private AtomicInteger failureCount = new AtomicInteger(0); // Tracks the time (in milliseconds) required to resolve URLs. private final PrintableHistogram urlResolutionTimesMs = new PrintableHistogram( 1, 5, 10, 25, 50, 75, 100, 150, 200, 250, 300, 500, 750, 1000, 1500, 2000); private final Clock clock; private final BackoffStrategy backoffStrategy; @VisibleForTesting UrlResolver(Clock clock, BackoffStrategy backoffStrategy, ExceptionalFunction<String, String, IOException> resolver, int maxRedirects) { this(clock, backoffStrategy, resolver, maxRedirects, null); } /** * Creates a new asynchronous URL resolver. A thread pool will be used to resolve URLs, and * resolved URLs will be announced via {@code handler}. * * @param maxRedirects The maximum number of HTTP redirects to follow. * @param threadPoolSize The number of threads to use for resolving URLs. * @param proxyConfig The proxy settings with which to make the HTTP request, or null for the * default configured proxy. */ public UrlResolver(int maxRedirects, int threadPoolSize, @Nullable ProxyConfig proxyConfig) { this(Clock.SYSTEM_CLOCK, new TruncatedBinaryBackoff(Amount.of(100L, Time.MILLISECONDS), Amount.of(1L, Time.SECONDS)), getUrlResolver(proxyConfig), maxRedirects, threadPoolSize); } public UrlResolver(int maxRedirects, int threadPoolSize) { this(maxRedirects, threadPoolSize, null); } private UrlResolver(Clock clock, BackoffStrategy backoffStrategy, ExceptionalFunction<String, String, IOException> resolver, int maxRedirects, @Nullable Integer threadPoolSize) { this.clock = clock; this.backoffStrategy = backoffStrategy; this.resolver = resolver; this.maxRedirects = maxRedirects; if (threadPoolSize != null) { this.threadPoolSize = threadPoolSize; Preconditions.checkState(threadPoolSize > 0); poolEntrySemaphore = new Semaphore(threadPoolSize); // Start up the thread pool. reset(); // Executor to send notifications back to the handler. This also needs to be // a daemon thread. handlerExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).build()); } else { this.threadPoolSize = null; poolEntrySemaphore = null; handlerExecutor = null; } } public Future<ResolvedUrl> resolveUrlAsync(final String url, final ResolvedUrlHandler handler) { Preconditions.checkNotNull( "Asynchronous URL resolution cannot be performed without a valid handler.", handler); try { poolEntrySemaphore.acquire(); } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Interrupted while waiting for thread to resolve URL: " + url, e); return null; } final ListenableFutureTask<ResolvedUrl> future = ListenableFutureTask.create( new Callable<ResolvedUrl>() { @Override public ResolvedUrl call() { return resolveUrl(url); } }); future.addListener(new Runnable() { @Override public void run() { try { handler.resolved(future); } finally { poolEntrySemaphore.release(); } } }, handlerExecutor); executor.execute(future); return future; } private void logThreadpoolInfo() { LOG.info("Shutting down thread pool, available permits: " + poolEntrySemaphore.availablePermits()); LOG.info("Queued threads? " + poolEntrySemaphore.hasQueuedThreads()); LOG.info("Queue length: " + poolEntrySemaphore.getQueueLength()); } public void reset() { Preconditions.checkState(threadPoolSize != null); if (executor != null) { Preconditions.checkState(executor.isShutdown(), "The thread pool must be shut down before resetting."); Preconditions.checkState(executor.isTerminated(), "There may still be pending async tasks."); } // Create a thread pool with daemon threads, so that they may be terminated when no // application threads are running. executor = Executors.newFixedThreadPool(threadPoolSize, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("UrlResolver[%d]").build()); } /** * Terminates the thread pool, waiting at most {@code waitSeconds} for active threads to complete. * After this method is called, no more URLs may be submitted for resolution. * * @param waitSeconds The number of seconds to wait for active threads to complete. */ public void clearAsyncTasks(int waitSeconds) { Preconditions.checkState(threadPoolSize != null, "finish() should not be called on a synchronous URL resolver."); logThreadpoolInfo(); executor.shutdown(); // Disable new tasks from being submitted. try { // Wait a while for existing tasks to terminate if (!executor.awaitTermination(waitSeconds, TimeUnit.SECONDS)) { LOG.info("Pool did not terminate, forcing shutdown."); logThreadpoolInfo(); List<Runnable> remaining = executor.shutdownNow(); LOG.info("Tasks still running: " + remaining); // Wait a while for tasks to respond to being cancelled if (!executor.awaitTermination(waitSeconds, TimeUnit.SECONDS)) { LOG.warning("Pool did not terminate."); logThreadpoolInfo(); } } } catch (InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while waiting for threadpool to finish.", e); // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } /** * Resolves a URL synchronously. * * @param url The URL to resolve. * @return The resolved URL. */ public ResolvedUrl resolveUrl(String url) { ResolvedUrl resolvedUrl = new ResolvedUrl(); resolvedUrl.setStartUrl(url); String cached = urlCache.get(url); if (cached != null) { cacheHits.incrementAndGet(); resolvedUrl.setNextResolve(cached); resolvedUrl.setEndState(EndState.CACHED); return resolvedUrl; } String currentUrl = url; long backoffMs = 0L; String next = null; for (int i = 0; i < maxRedirects; i++) { try { next = resolveOnce(currentUrl); // If there was a 4xx or a 5xx, we''ll get a null back, so we pretend like we never advanced // to allow for a retry within the redirect limit. // TODO(John Sirois): we really need access to the return code here to do the right thing; ie: // retry for internal server errors but probably not for unauthorized if (next == null) { if (i < maxRedirects - 1) { // don't wait if we're about to exit the loop backoffMs = backoffStrategy.calculateBackoffMs(backoffMs); try { clock.waitFor(backoffMs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException( "Interrupted waiting to retry a failed resolution for: " + currentUrl, e); } } continue; } backoffMs = 0L; if (next.equals(currentUrl)) { // We've reached the end of the redirect chain. resolvedUrl.setEndState(EndState.REACHED_LANDING); urlCache.put(url, currentUrl); for (String intermediateUrl : resolvedUrl.getIntermediateUrls()) { urlCache.put(intermediateUrl, currentUrl); } return resolvedUrl; } else if (!url.equals(next)) { resolvedUrl.setNextResolve(next); } currentUrl = next; } catch (IOException e) { LOG.log(Level.INFO, "Failed to resolve url: " + url, e); resolvedUrl.setEndState(EndState.ERROR); return resolvedUrl; } } resolvedUrl.setEndState(next == null || url.equals(currentUrl) ? EndState.ERROR : EndState.REDIRECT_LIMIT); return resolvedUrl; } /** * Resolves a url, following at most one redirect. Thread-safe. * * @param url The URL to resolve. * @return The result of following the URL through at most one redirect or null if the url could * not be followed * @throws IOException If an error occurs while resolving the URL. */ private String resolveOnce(String url) throws IOException { requestCount.incrementAndGet(); String resolvedUrl = urlCache.get(url); if (resolvedUrl != null) { cacheHits.incrementAndGet(); return resolvedUrl; } try { long startTimeMs = System.currentTimeMillis(); resolvedUrl = resolver.apply(url); if (resolvedUrl == null) { return null; } urlCache.put(url, resolvedUrl); synchronized (urlResolutionTimesMs) { urlResolutionTimesMs.addValue(System.currentTimeMillis() - startTimeMs); } return resolvedUrl; } catch (IOException e) { failureCount.incrementAndGet(); throw e; } } @Override public String toString() { return String.format("Cache: %s\nFailed requests: %d,\nResolution Times: %s", urlCache, failureCount.get(), urlResolutionTimesMs.toString()); } /** * Class to wrap the result of a URL resolution. */ public static class ResolvedUrl { public enum EndState { REACHED_LANDING, ERROR, CACHED, REDIRECT_LIMIT } private String startUrl; private final List<String> resolveChain; private EndState endState; public ResolvedUrl() { resolveChain = Lists.newArrayList(); } @VisibleForTesting public ResolvedUrl(EndState endState, String startUrl, String... resolveChain) { this.endState = endState; this.startUrl = startUrl; this.resolveChain = Lists.newArrayList(resolveChain); } public String getStartUrl() { return startUrl; } void setStartUrl(String startUrl) { this.startUrl = startUrl; } /** * Returns the last URL resolved following a redirect chain, or null if the startUrl is a * landing URL. */ public String getEndUrl() { return resolveChain.isEmpty() ? null : Iterables.getLast(resolveChain); } void setNextResolve(String endUrl) { this.resolveChain.add(endUrl); } /** * Returns any immediate URLs encountered on the resolution chain. If the startUrl redirects * directly to the endUrl or they are the same the imtermediate URLs will be empty. */ public Iterable<String> getIntermediateUrls() { return resolveChain.size() <= 1 ? ImmutableList.<String>of() : resolveChain.subList(0, resolveChain.size() - 1); } public EndState getEndState() { return endState; } void setEndState(EndState endState) { this.endState = endState; } public String toString() { return String.format("%s -> %s [%s, %d redirects]", startUrl, Joiner.on(" -> ").join(resolveChain), endState, resolveChain.size()); } } /** * Interface to use for notifying the caller of resolved URLs. */ public interface ResolvedUrlHandler { /** * Signals that a URL has been resolved to its target. The implementation of this method must * be thread safe. * * @param future The future that has finished resolving a URL. */ public void resolved(Future<ResolvedUrl> future); } }
abel-von/commons
src/java/com/twitter/common/net/UrlResolver.java
Java
apache-2.0
15,827
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. 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.wso2.appserver.ui.integration.test.webapp.spring; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.appserver.integration.common.ui.page.LoginPage; import org.wso2.appserver.integration.common.ui.page.main.WebAppListPage; import org.wso2.appserver.integration.common.ui.page.main.WebAppUploadingPage; import org.wso2.appserver.integration.common.utils.ASIntegrationUITest; import org.wso2.carbon.automation.extensions.selenium.BrowserManager; import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider; import java.io.File; import java.io.IOException; import java.util.Calendar; import static org.testng.AssertJUnit.assertTrue; /** * This class tests the deployment and accessibility of a web application which use spring framework */ public class SpringWebApplicationDeploymentTestCase extends ASIntegrationUITest { private WebDriver driver; private final String context = "/booking-faces"; @BeforeClass(alwaysRun = true, enabled = false) public void setUp() throws Exception { super.init(); driver = BrowserManager.getWebDriver(); driver.get(getLoginURL()); LoginPage test = new LoginPage(driver); test.loginAs(userInfo.getUserName(), userInfo.getPassword()); } @Test(groups = "wso2.as", description = "Uploading the web app which use spring", enabled = false) public void uploadSpringWebApplicationTest() throws Exception { String filePath = TestConfigurationProvider.getResourceLocation("AS") + File.separator + "war" + File.separator + "spring" + File.separator + "booking-faces.war"; WebAppUploadingPage uploadPage = new WebAppUploadingPage(driver); Assert.assertTrue(uploadPage.uploadWebApp(filePath), "Web Application uploading failed"); } @Test(groups = "wso2.as", description = "Verifying Deployment the web app which use spring" , dependsOnMethods = "uploadSpringWebApplicationTest", enabled = false) public void webApplicationDeploymentTest() throws Exception { WebAppListPage webAppListPage = new WebAppListPage(driver); assertTrue("Web Application Deployment Failed. Web Application /booking-faces not found in Web application List" , isWebAppDeployed(webAppListPage, context)); driver.findElement(By.id("webappsTable")).findElement(By.linkText("/booking-faces")).click(); } @Test(groups = "wso2.as", description = "Access the spring application" , dependsOnMethods = "webApplicationDeploymentTest", enabled = false) public void invokeSpringApplicationTest() throws Exception { WebDriver driverForApp = null; try { driverForApp = BrowserManager.getWebDriver(); //Go to application driverForApp.get(webAppURL + "/booking-faces/spring/intro"); driverForApp.findElement(By.linkText("Start your Spring Travel experience")).click(); //searching hotels to reserve driverForApp.findElement(By.xpath("//*[@id=\"j_idt13:searchString\"]")).sendKeys("Con"); driverForApp.findElement(By.xpath("//*[@id=\"j_idt13:findHotels\"]")).click(); //view hotel information driverForApp.findElement(By.xpath("//*[@id=\"j_idt12:hotels:0:viewHotelLink\"]")).click(); //go to book hotel driverForApp.findElement(By.xpath("//*[@id=\"hotel:book\"]")).click(); //providing user name and password driverForApp.findElement(By.xpath("/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[1]/input")) .sendKeys("keith"); driverForApp.findElement(By.xpath("/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[2]/input")) .sendKeys("melbourne"); //authenticating driverForApp.findElement(By.xpath("/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[4]/input")) .click(); //booking hotel driverForApp.findElement(By.xpath("//*[@id=\"hotel:book\"]")).click(); //providing payments information driverForApp.findElement(By.xpath("//*[@id=\"bookingForm:creditCard\"]")).sendKeys("1234567890123456"); driverForApp.findElement(By.xpath("//*[@id=\"bookingForm:creditCardName\"]")).sendKeys("xyz"); //proceed transaction driverForApp.findElement(By.xpath("//*[@id=\"bookingForm:proceed\"]")).click(); //confirm booking driverForApp.findElement(By.xpath("//*[@id=\"j_idt13:confirm\"]")).click(); //verify whether the hotel booked is in the booked hotel tabled Assert.assertEquals(driverForApp.findElement(By.xpath("//*[@id=\"bookings_header\"]")).getText() , "Your Hotel Bookings", "Booked Hotel table Not Found"); //verify the hotel name is exist in the booked hotel table Assert.assertEquals(driverForApp.findElement(By.xpath("//*[@id=\"j_idt23:j_idt24_data\"]/tr/td[1]")) .getText(), "Conrad Miami\n" + "1395 Brickell Ave\n" + "Miami, FL", "Hotel Name mismatch"); } finally { if (driverForApp != null) { driverForApp.quit(); } } } @AfterClass(alwaysRun = true, enabled = false) public void deleteWebApplication() throws Exception { try { WebAppListPage webAppListPage = new WebAppListPage(driver); if (webAppListPage.findWebApp(context)) { Assert.assertTrue(webAppListPage.deleteWebApp(context), "Web Application Deletion failed"); Assert.assertTrue(isWebAppUnDeployed(webAppListPage, context)); } } finally { driver.quit(); } } private boolean isWebAppDeployed(WebAppListPage listPage, String webAppContext) throws IOException { boolean isServiceDeployed = false; Calendar startTime = Calendar.getInstance(); long time; while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < 1000 * 60 * 2) { listPage = new WebAppListPage(driver); if (listPage.findWebApp(webAppContext)) { isServiceDeployed = true; break; } try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } return isServiceDeployed; } private boolean isWebAppUnDeployed(WebAppListPage listPage, String webAppContext) throws IOException { boolean isServiceUnDeployed = false; Calendar startTime = Calendar.getInstance(); long time; while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < 1000 * 60 * 2) { listPage = new WebAppListPage(driver); if (!listPage.findWebApp(webAppContext)) { isServiceUnDeployed = true; break; } try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } return isServiceUnDeployed; } }
kasungayan/product-as
modules/integration/tests-ui-integration/tests-ui/src/test/java/org/wso2/appserver/ui/integration/test/webapp/spring/SpringWebApplicationDeploymentTestCase.java
Java
apache-2.0
8,185
goog.module('javascript.protobuf.conformance'); const ConformanceRequest = goog.require('proto.conformance.ConformanceRequest'); const ConformanceResponse = goog.require('proto.conformance.ConformanceResponse'); const TestAllTypesProto2 = goog.require('proto.conformance.TestAllTypesProto2'); const TestAllTypesProto3 = goog.require('proto.conformance.TestAllTypesProto3'); const WireFormat = goog.require('proto.conformance.WireFormat'); const base64 = goog.require('goog.crypt.base64'); /** * Creates a `proto.conformance.ConformanceResponse` response according to the * `proto.conformance.ConformanceRequest` request. * @param {!ConformanceRequest} request * @return {!ConformanceResponse} response */ function doTest(request) { const response = ConformanceResponse.createEmpty(); if(request.getPayloadCase() === ConformanceRequest.PayloadCase.JSON_PAYLOAD) { response.setSkipped('Json is not supported as input format.'); return response; } if(request.getPayloadCase() === ConformanceRequest.PayloadCase.TEXT_PAYLOAD) { response.setSkipped('Text format is not supported as input format.'); return response; } if(request.getPayloadCase() === ConformanceRequest.PayloadCase.PAYLOAD_NOT_SET) { response.setRuntimeError('Request didn\'t have payload.'); return response; } if(request.getPayloadCase() !== ConformanceRequest.PayloadCase.PROTOBUF_PAYLOAD) { throw new Error('Request didn\'t have accepted input format.'); } if (request.getRequestedOutputFormat() === WireFormat.JSON) { response.setSkipped('Json is not supported as output format.'); return response; } if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) { response.setSkipped('Text format is not supported as output format.'); return response; } if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) { response.setRuntimeError('Unspecified output format'); return response; } if (request.getRequestedOutputFormat() !== WireFormat.PROTOBUF) { throw new Error('Request didn\'t have accepted output format.'); } if (request.getMessageType() === 'conformance.FailureSet') { response.setProtobufPayload(new ArrayBuffer(0)); } else if ( request.getMessageType() === 'protobuf_test_messages.proto2.TestAllTypesProto2') { try { const testMessage = TestAllTypesProto2.deserialize(request.getProtobufPayload()); response.setProtobufPayload(testMessage.serialize()); } catch (err) { response.setParseError(err.toString()); } } else if ( request.getMessageType() === 'protobuf_test_messages.proto3.TestAllTypesProto3') { try { const testMessage = TestAllTypesProto3.deserialize(request.getProtobufPayload()); response.setProtobufPayload(testMessage.serialize()); } catch (err) { response.setParseError(err.toString()); } } else { throw new Error( `Payload message not supported: ${request.getMessageType()}.`); } return response; } /** * Same as doTest, but both request and response are in base64. * @param {string} base64Request * @return {string} response */ function runConformanceTest(base64Request) { const request = ConformanceRequest.deserialize( base64.decodeStringToUint8Array(base64Request).buffer); const response = doTest(request); return base64.encodeByteArray(new Uint8Array(response.serialize())); } // Needed for node test exports.doTest = doTest; // Needed for browser test goog.exportSymbol('runConformanceTest', runConformanceTest);
nwjs/chromium.src
third_party/protobuf/js/experimental/runtime/kernel/conformance/conformance_testee.js
JavaScript
bsd-3-clause
3,602
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ArithmeticException ** ** ** Purpose: Exception class for bad arithmetic conditions! ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; // The ArithmeticException is thrown when overflow or underflow // occurs. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class ArithmeticException : SystemException { // Creates a new ArithmeticException with its message string set to // the empty string, its HRESULT set to COR_E_ARITHMETIC, // and its ExceptionInfo reference set to null. public ArithmeticException() : base(Environment.GetResourceString("Arg_ArithmeticException")) { SetErrorCode(__HResults.COR_E_ARITHMETIC); } // Creates a new ArithmeticException with its message string set to // message, its HRESULT set to COR_E_ARITHMETIC, // and its ExceptionInfo reference set to null. // public ArithmeticException(String message) : base(message) { SetErrorCode(__HResults.COR_E_ARITHMETIC); } public ArithmeticException(String message, Exception innerException) : base(message, innerException) { SetErrorCode(__HResults.COR_E_ARITHMETIC); } protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
sekcheong/referencesource
mscorlib/system/arithmeticexception.cs
C#
mit
1,736