code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
// ---------------------------------------------------------------------------
// <copyright file="PhoneEntityCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the PhoneEntityCollection class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
/// <summary>
/// Represents a collection of PhoneEntity objects.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class PhoneEntityCollection : ComplexPropertyCollection<PhoneEntity>
{
/// <summary>
/// Initializes a new instance of the <see cref="PhoneEntityCollection"/> class.
/// </summary>
internal PhoneEntityCollection()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PhoneEntityCollection"/> class.
/// </summary>
/// <param name="collection">The collection of objects to include.</param>
internal PhoneEntityCollection(IEnumerable<PhoneEntity> collection)
{
if (collection != null)
{
collection.ForEach(this.InternalAdd);
}
}
/// <summary>
/// Creates the complex property.
/// </summary>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>PhoneEntity.</returns>
internal override PhoneEntity CreateComplexProperty(string xmlElementName)
{
return new PhoneEntity();
}
/// <summary>
/// Creates the default complex property.
/// </summary>
/// <returns>PhoneEntity.</returns>
internal override PhoneEntity CreateDefaultComplexProperty()
{
return new PhoneEntity();
}
/// <summary>
/// Gets the name of the collection item XML element.
/// </summary>
/// <param name="complexProperty">The complex property.</param>
/// <returns>XML element name.</returns>
internal override string GetCollectionItemXmlElementName(PhoneEntity complexProperty)
{
return XmlElementNames.NlgPhone;
}
}
}
| dclaux/ews-managed-api | ComplexProperties/PhoneEntityCollection.cs | C# | mit | 2,624 |
class BreatheIn::Scraper
@@air_quality_info = {}
@@scraped = nil
def self.air_quality
@@air_quality_info
end
def self.scraped_pg
@@scraped
end
def self.scraped_page(zipcode)
begin
@@scraped = Nokogiri::HTML(open("https://airnow.gov/?action=airnow.local_city&zipcode=#{zipcode}&submit=Go"))
rescue OpenURI::HTTPError => e
if e.message == '404 Not Found'
puts "The website is currently down. Please try again later."
else
raise e
end
end
end
def self.city_air_quality
city_name
today_high
index_level
current_conditions_time
current_conditions_value
current_conditions_index
air_quality
end
def self.city_name
city = scraped_pg.css("#pageContent .ActiveCity")
#returns array of an object with attributes including city name
city.empty? ? nil : air_quality[:city_name] = city.text.strip
end
def self.today_high
data = scraped_pg.css(".AQDataContent tr td .TblInvisible tr td")
#returns array of data numbers (today's high, tomorrow's high, particles, etc.)
data.empty? ? nil : air_quality[:today_high] = data[0].text.strip.to_i
end
def self.index_level
quality = scraped_pg.css(".AQDataContent .AQILegendText")
#returns array of objects with attributes including quality
quality.empty? ? nil : air_quality[:today_index] = quality.first.text
end
def self.current_conditions_time
unformatted_info = scraped_pg.css(".AQData .AQDataSectionTitle .AQDataSectionTitle")
#returns array of objects with attributes of title and date information
current_info = unformatted_info.text.strip.split("\r\n \t")
# => returns array ["Air Quality Index (AQI)", "observed at 19:00 PST"]
unformatted_info.empty? ? nil : air_quality[:last_update_time] = current_info[1]
end
def self.current_conditions_value
current_value = scraped_pg.css(".AQDataSectionTitle .TblInvisible .TblInvisible td")
#returns array of an object with attributes including current condition value
current_value.empty? ? nil : air_quality[:last_update_value] = current_value.text.strip.to_i
end
def self.current_conditions_index
current_index = scraped_pg.css(".AQDataSectionTitle .TblInvisible .AQDataLg")
#returns array of an object with attributes including current condition index
current_index.empty? ? nil : air_quality[:last_update_index] = current_index.text.strip
end
def self.index_good
print "Air quality is considered satisfactory, and air pollution poses little or no risk."
end
def self.index_moderate
print "Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution."
end
def self.index_sensitive
print "Members of sensitive groups may experience health effects. The general public is not likely to be affected."
end
def self.index_unhealthy
print "Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects."
end
def self.index_very_unhealthy
print "Health warnings of emergency conditions. The entire population is more likely to be affected."
end
def self.index_hazardous
print "Health alert: everyone may experience more serious health effects."
end
def self.AQI_range_information
information = <<-Ruby
The Air Quality Index (AQI) translates air quality data into an easily understandable number to identify how clean or polluted the outdoor air is, along with possible health effects.
The U.S. Environmental Protection Agency, National Oceanic and Atmospheric Administration, National Park Service, tribal, state, and local agencies developed the AirNow system to provide the public with easy access to national air quality information.
"Good" AQI is 0 - 50.
Air quality is considered satisfactory, and air pollution poses little or no risk.
***************************
"Moderate" AQI is 51 - 100.
Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people. For example, people who are unusually sensitive to ozone may experience respiratory symptoms.
***************************
"Unhealthy for Sensitive Groups" AQI is 101 - 150.
Although general public is not likely to be affected at this AQI range, people with lung disease, older adults and children are at a greater risk from exposure to ozone, whereas persons with heart and lung disease, older adults and children are at greater risk from the presence of particles in the air.
***************************
"Unhealthy" AQI is 151 - 200.
Everyone may begin to experience some adverse health effects, and members of the sensitive groups may experience more serious effects.
***************************
"Very Unhealthy" AQI is 201 - 300.
This would trigger a health alert signifying that everyone may experience more serious health effects.
***************************
"Hazardous" AQI greater than 300.
This would trigger a health warnings of emergency conditions. The entire population is more likely to be affected.
***************************
All descriptions, information, and data are provided courtesy of AirNow.gov. Visit the website to learn more.
Ruby
puts information
end
def self.under_maintenance #returns true if under maintenance
scraped_pg.css("#pageContent .TblInvisibleFixed tr p[style*='color:#F00;']").text.include?("maintenance")
end
# def self.unavailable_data #returns true if data is unavailable
# phrase = scraped_pg.css(".TblInvisibleFixed .AQData tr td[valign*='top']").text
# phrase.include?("Data Not Available")
# end
end | eric-an/breathe-in | lib/breathe_in/scraper.rb | Ruby | mit | 5,930 |
/**
* Run the APP
*/
app.run();
| bordeux/GeekShare | src/Acme/GeekShareBundle/Angular/init/run.js | JavaScript | mit | 34 |
/*
* slush-ml-3t
* https://github.com/edmacabebe/slush-ml-3t
*
* Copyright (c) 2017, edmacabebe
* Licensed under the MIT license.
*/
'use strict';
var gulp = require('gulp'),
install = require('gulp-install'),
conflict = require('gulp-conflict'),
template = require('gulp-template'),
rename = require('gulp-rename'),
_ = require('underscore.string'),
inquirer = require('inquirer'),
path = require('path');
function format(string) {
var username = string.toLowerCase();
return username.replace(/\s/g, '');
}
var defaults = (function () {
var workingDirName = path.basename(process.cwd()),
homeDir, osUserName, configFile, user;
if (process.platform === 'win32') {
homeDir = process.env.USERPROFILE;
osUserName = process.env.USERNAME || path.basename(homeDir).toLowerCase();
}
else {
homeDir = process.env.HOME || process.env.HOMEPATH;
osUserName = homeDir && homeDir.split('/').pop() || 'root';
}
configFile = path.join(homeDir, '.gitconfig');
user = {};
if (require('fs').existsSync(configFile)) {
user = require('iniparser').parseSync(configFile).user;
}
return {
appName: workingDirName,
userName: osUserName || format(user.name || ''),
authorName: user.name || '',
authorEmail: user.email || ''
};
})();
gulp.task('default', function (done) {
var prompts = [{
name: 'appName',
message: 'What is the name of your project?',
default: defaults.appName
}, {
name: 'appDescription',
message: 'What is the description?'
}, {
name: 'appVersion',
message: 'What is the version of your project?',
default: '0.1.0'
}, {
name: 'authorName',
message: 'What is the author name?',
default: defaults.authorName
}, {
name: 'authorEmail',
message: 'What is the author email?',
default: defaults.authorEmail
}, {
name: 'userName',
message: 'What is the github username?',
default: defaults.userName
}, {
type: 'confirm',
name: 'moveon',
message: 'Continue?'
}];
//Ask
inquirer.prompt(prompts,
function (answers) {
if (!answers.moveon) {
return done();
}
answers.appNameSlug = _.slugify(answers.appName);
gulp.src(__dirname + '/templates/**')
.pipe(template(answers))
.pipe(rename(function (file) {
if (file.basename[0] === '_') {
file.basename = '.' + file.basename.slice(1);
}
}))
.pipe(conflict('./'))
.pipe(gulp.dest('./'))
.pipe(install())
.on('end', function () {
done();
});
});
});
| edmacabebe/ML-3T-Dev | slushfile.js | JavaScript | mit | 2,940 |
using System;
using Newtonsoft.Json;
namespace PayStack.Net
{
public class ChargeTokenize
{
public class Customer
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("customer_code")]
public string CustomerCode { get; set; }
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
}
public class Data
{
[JsonProperty("authorization_code")]
public string AuthorizationCode { get; set; }
[JsonProperty("card_type")]
public string CardType { get; set; }
[JsonProperty("last4")]
public string Last4 { get; set; }
[JsonProperty("exp_month")]
public string ExpMonth { get; set; }
[JsonProperty("exp_year")]
public string ExpYear { get; set; }
[JsonProperty("bin")]
public string Bin { get; set; }
[JsonProperty("bank")]
public string Bank { get; set; }
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("signature")]
public string Signature { get; set; }
[JsonProperty("reusable")]
public bool Reusable { get; set; }
[JsonProperty("country_code")]
public string CountryCode { get; set; }
[JsonProperty("customer")]
public Customer Customer { get; set; }
}
}
public class ChargeTokenizeResponse : HasRawResponse
{
[JsonProperty("status")]
public bool Status { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("data")]
public ChargeTokenize.Data Data { get; set; }
}
} | adebisi-fa/paystack-dotnet | src/main/Apis/Charge/Tokenize.cs | C# | mit | 2,023 |
angular.module('streama').controller('adminVideosCtrl', ['$scope', 'apiService', 'modalService', '$state', function ($scope, apiService, modalService, $state) {
$scope.loading = true;
apiService.genericVideo.list().then(function (response) {
$scope.videos = response.data;
$scope.loading = false;
});
$scope.openGenericVideoModal = function () {
modalService.genericVideoModal(null, function (data) {
$state.go('admin.video', {videoId: data.id});
});
};
$scope.addFromSuggested = function (movie, redirect) {
var tempMovie = angular.copy(movie);
var apiId = tempMovie.id;
delete tempMovie.id;
tempMovie.apiId = apiId;
apiService.movie.save(tempMovie).then(function (response) {
if(redirect){
$state.go('admin.movie', {movieId: response.data.id});
}else{
$scope.movies.push(response.data);
}
});
};
$scope.alreadyAdded = function (movie) {
console.log('%c movie', 'color: deeppink; font-weight: bold; text-shadow: 0 0 5px deeppink;', movie);
return movie.id && _.find($scope.movies, {apiId: movie.id.toString()});
};
}]);
| dularion/streama | grails-app/assets/javascripts/streama/controllers/admin-videos-ctrl.js | JavaScript | mit | 1,084 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "skus" collection of methods.
* Typical usage is:
* <code>
* $cloudbillingService = new Google_Service_Cloudbilling(...);
* $skus = $cloudbillingService->skus;
* </code>
*/
class Google_Service_Cloudbilling_Resource_ServicesSkus extends Google_Service_Resource
{
/**
* Lists all publicly available SKUs for a given cloud service.
* (skus.listServicesSkus)
*
* @param string $parent The name of the service. Example:
* "services/DA34-426B-A397"
* @param array $optParams Optional parameters.
*
* @opt_param string currencyCode The ISO 4217 currency code for the pricing
* info in the response proto. Will use the conversion rate as of start_time.
* Optional. If not specified USD will be used.
* @opt_param string endTime Optional exclusive end time of the time range for
* which the pricing versions will be returned. Timestamps in the future are not
* allowed. The time range has to be within a single calendar month in
* America/Los_Angeles timezone. Time range as a whole is optional. If not
* specified, the latest pricing will be returned (up to 12 hours old at most).
* @opt_param string startTime Optional inclusive start time of the time range
* for which the pricing versions will be returned. Timestamps in the future are
* not allowed. The time range has to be within a single calendar month in
* America/Los_Angeles timezone. Time range as a whole is optional. If not
* specified, the latest pricing will be returned (up to 12 hours old at most).
* @opt_param string pageToken A token identifying a page of results to return.
* This should be a `next_page_token` value returned from a previous `ListSkus`
* call. If unspecified, the first page of results is returned.
* @opt_param int pageSize Requested page size. Defaults to 5000.
* @return Google_Service_Cloudbilling_ListSkusResponse
*/
public function listServicesSkus($parent, $optParams = array())
{
$params = array('parent' => $parent);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Cloudbilling_ListSkusResponse");
}
}
| philnewman/scoutbook | includes/vendor/google/apiclient-services/src/Google/Service/Cloudbilling/Resource/ServicesSkus.php | PHP | mit | 2,766 |
var cookie = require('../index');
chai.should();
describe('cookie monster', function() {
it('sets a cookie', function (){
cookie.setItem('cookieKey', 'cookieVal');
document.cookie.should.contain('cookieKey=cookieVal');
});
it('gets a cookie', function (){
document.cookie = 'dumby=mcdumberson;';
cookie.getItem('dumby').should.equal('mcdumberson');
});
it('sets and gets cookie with `=` in value', function (){
cookie.setItem('key', 'val=ue');
cookie.getItem('key').should.equal('val=ue');
});
it('removes a cookie', function (){
document.cookie = 'dumby=mcdumberson;';
document.cookie.should.contain('dumby=mcdumberson');
cookie.removeItem('dumby');
document.cookie.should.not.contain('dumby=mcdumberson');
});
it('sets 30 cookies and clears all of them', function (){
for (var i = 0; i++; i < 30){ cookie.setItem('key' + i, 'value' + i); }
for (var i = 0; i++; i < 30){ cookie.getItem('key' + i).should.equal('value' + i); }
cookie.clear();
document.cookie.should.equal('');
});
});
| kahnjw/cookie-monster | test/cookie-monster-spec.js | JavaScript | mit | 1,068 |
/**
*
* Store transaction
*
* Programmer By Emay Komarudin.
* 2013
*
* Description Store transaction
*
*
**/
var data_gen = generate_transaction_list(30);
Ext.define('App.store.transaction.sListTrx',{
extend : 'Ext.data.Store',
// groupField: 'trx_no',
// model : 'App.model.transaction.mOrders',
fields : ['trx_no','user_name','status','count_orders','count_items','order_no'],
data : data_gen
});
| emayk/ics | public/frontend/app/store/transaction/sListTrx.js | JavaScript | mit | 405 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow_serving/resources/resources.proto
#include "tensorflow_serving/resources/resources.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace protobuf_google_2fprotobuf_2fwrappers_2eproto {
extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fwrappers_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_UInt32Value;
} // namespace protobuf_google_2fprotobuf_2fwrappers_2eproto
namespace protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto {
extern PROTOBUF_INTERNAL_EXPORT_protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Resource;
extern PROTOBUF_INTERNAL_EXPORT_protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ResourceAllocation_Entry;
} // namespace protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto
namespace tensorflow {
namespace serving {
class ResourceDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Resource>
_instance;
} _Resource_default_instance_;
class ResourceAllocation_EntryDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ResourceAllocation_Entry>
_instance;
} _ResourceAllocation_Entry_default_instance_;
class ResourceAllocationDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ResourceAllocation>
_instance;
} _ResourceAllocation_default_instance_;
} // namespace serving
} // namespace tensorflow
namespace protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto {
static void InitDefaultsResource() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::serving::_Resource_default_instance_;
new (ptr) ::tensorflow::serving::Resource();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::serving::Resource::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_Resource =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsResource}, {
&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base,}};
static void InitDefaultsResourceAllocation_Entry() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::serving::_ResourceAllocation_Entry_default_instance_;
new (ptr) ::tensorflow::serving::ResourceAllocation_Entry();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::serving::ResourceAllocation_Entry::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_ResourceAllocation_Entry =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsResourceAllocation_Entry}, {
&protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::scc_info_Resource.base,}};
static void InitDefaultsResourceAllocation() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::serving::_ResourceAllocation_default_instance_;
new (ptr) ::tensorflow::serving::ResourceAllocation();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::serving::ResourceAllocation::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_ResourceAllocation =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsResourceAllocation}, {
&protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::scc_info_ResourceAllocation_Entry.base,}};
void InitDefaults() {
::google::protobuf::internal::InitSCC(&scc_info_Resource.base);
::google::protobuf::internal::InitSCC(&scc_info_ResourceAllocation_Entry.base);
::google::protobuf::internal::InitSCC(&scc_info_ResourceAllocation.base);
}
::google::protobuf::Metadata file_level_metadata[3];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::Resource, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::Resource, device_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::Resource, device_instance_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::Resource, kind_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::ResourceAllocation_Entry, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::ResourceAllocation_Entry, resource_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::ResourceAllocation_Entry, quantity_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::ResourceAllocation, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::tensorflow::serving::ResourceAllocation, resource_quantities_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::tensorflow::serving::Resource)},
{ 8, -1, sizeof(::tensorflow::serving::ResourceAllocation_Entry)},
{ 15, -1, sizeof(::tensorflow::serving::ResourceAllocation)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::tensorflow::serving::_Resource_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::tensorflow::serving::_ResourceAllocation_Entry_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::tensorflow::serving::_ResourceAllocation_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
AssignDescriptors(
"tensorflow_serving/resources/resources.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n,tensorflow_serving/resources/resources"
".proto\022\022tensorflow.serving\032\036google/proto"
"buf/wrappers.proto\"_\n\010Resource\022\016\n\006device"
"\030\001 \001(\t\0225\n\017device_instance\030\002 \001(\0132\034.google"
".protobuf.UInt32Value\022\014\n\004kind\030\003 \001(\t\"\252\001\n\022"
"ResourceAllocation\022I\n\023resource_quantitie"
"s\030\001 \003(\0132,.tensorflow.serving.ResourceAll"
"ocation.Entry\032I\n\005Entry\022.\n\010resource\030\001 \001(\013"
"2\034.tensorflow.serving.Resource\022\020\n\010quanti"
"ty\030\002 \001(\004b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 376);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"tensorflow_serving/resources/resources.proto", &protobuf_RegisterTypes);
::protobuf_google_2fprotobuf_2fwrappers_2eproto::AddDescriptors();
}
void AddDescriptors() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto
namespace tensorflow {
namespace serving {
// ===================================================================
void Resource::InitAsDefaultInstance() {
::tensorflow::serving::_Resource_default_instance_._instance.get_mutable()->device_instance_ = const_cast< ::google::protobuf::UInt32Value*>(
::google::protobuf::UInt32Value::internal_default_instance());
}
void Resource::clear_device_instance() {
if (GetArenaNoVirtual() == NULL && device_instance_ != NULL) {
delete device_instance_;
}
device_instance_ = NULL;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Resource::kDeviceFieldNumber;
const int Resource::kDeviceInstanceFieldNumber;
const int Resource::kKindFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Resource::Resource()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::scc_info_Resource.base);
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.serving.Resource)
}
Resource::Resource(const Resource& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
device_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.device().size() > 0) {
device_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.device_);
}
kind_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.kind().size() > 0) {
kind_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.kind_);
}
if (from.has_device_instance()) {
device_instance_ = new ::google::protobuf::UInt32Value(*from.device_instance_);
} else {
device_instance_ = NULL;
}
// @@protoc_insertion_point(copy_constructor:tensorflow.serving.Resource)
}
void Resource::SharedCtor() {
device_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
kind_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
device_instance_ = NULL;
}
Resource::~Resource() {
// @@protoc_insertion_point(destructor:tensorflow.serving.Resource)
SharedDtor();
}
void Resource::SharedDtor() {
device_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
kind_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete device_instance_;
}
void Resource::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Resource::descriptor() {
::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Resource& Resource::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::scc_info_Resource.base);
return *internal_default_instance();
}
void Resource::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.serving.Resource)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
device_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
kind_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (GetArenaNoVirtual() == NULL && device_instance_ != NULL) {
delete device_instance_;
}
device_instance_ = NULL;
_internal_metadata_.Clear();
}
bool Resource::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.serving.Resource)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string device = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_device()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->device().data(), static_cast<int>(this->device().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.serving.Resource.device"));
} else {
goto handle_unusual;
}
break;
}
// .google.protobuf.UInt32Value device_instance = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_device_instance()));
} else {
goto handle_unusual;
}
break;
}
// string kind = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_kind()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->kind().data(), static_cast<int>(this->kind().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.serving.Resource.kind"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.serving.Resource)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.serving.Resource)
return false;
#undef DO_
}
void Resource::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.serving.Resource)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string device = 1;
if (this->device().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->device().data(), static_cast<int>(this->device().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.serving.Resource.device");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->device(), output);
}
// .google.protobuf.UInt32Value device_instance = 2;
if (this->has_device_instance()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->_internal_device_instance(), output);
}
// string kind = 3;
if (this->kind().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->kind().data(), static_cast<int>(this->kind().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.serving.Resource.kind");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
3, this->kind(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.serving.Resource)
}
::google::protobuf::uint8* Resource::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.serving.Resource)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string device = 1;
if (this->device().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->device().data(), static_cast<int>(this->device().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.serving.Resource.device");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->device(), target);
}
// .google.protobuf.UInt32Value device_instance = 2;
if (this->has_device_instance()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->_internal_device_instance(), deterministic, target);
}
// string kind = 3;
if (this->kind().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->kind().data(), static_cast<int>(this->kind().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.serving.Resource.kind");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
3, this->kind(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.serving.Resource)
return target;
}
size_t Resource::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.serving.Resource)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// string device = 1;
if (this->device().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->device());
}
// string kind = 3;
if (this->kind().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->kind());
}
// .google.protobuf.UInt32Value device_instance = 2;
if (this->has_device_instance()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*device_instance_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Resource::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.serving.Resource)
GOOGLE_DCHECK_NE(&from, this);
const Resource* source =
::google::protobuf::internal::DynamicCastToGenerated<const Resource>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.serving.Resource)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.serving.Resource)
MergeFrom(*source);
}
}
void Resource::MergeFrom(const Resource& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.serving.Resource)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.device().size() > 0) {
device_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.device_);
}
if (from.kind().size() > 0) {
kind_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.kind_);
}
if (from.has_device_instance()) {
mutable_device_instance()->::google::protobuf::UInt32Value::MergeFrom(from.device_instance());
}
}
void Resource::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.serving.Resource)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Resource::CopyFrom(const Resource& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.serving.Resource)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Resource::IsInitialized() const {
return true;
}
void Resource::Swap(Resource* other) {
if (other == this) return;
InternalSwap(other);
}
void Resource::InternalSwap(Resource* other) {
using std::swap;
device_.Swap(&other->device_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
kind_.Swap(&other->kind_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(device_instance_, other->device_instance_);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Resource::GetMetadata() const {
protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void ResourceAllocation_Entry::InitAsDefaultInstance() {
::tensorflow::serving::_ResourceAllocation_Entry_default_instance_._instance.get_mutable()->resource_ = const_cast< ::tensorflow::serving::Resource*>(
::tensorflow::serving::Resource::internal_default_instance());
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ResourceAllocation_Entry::kResourceFieldNumber;
const int ResourceAllocation_Entry::kQuantityFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ResourceAllocation_Entry::ResourceAllocation_Entry()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::scc_info_ResourceAllocation_Entry.base);
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.serving.ResourceAllocation.Entry)
}
ResourceAllocation_Entry::ResourceAllocation_Entry(const ResourceAllocation_Entry& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_resource()) {
resource_ = new ::tensorflow::serving::Resource(*from.resource_);
} else {
resource_ = NULL;
}
quantity_ = from.quantity_;
// @@protoc_insertion_point(copy_constructor:tensorflow.serving.ResourceAllocation.Entry)
}
void ResourceAllocation_Entry::SharedCtor() {
::memset(&resource_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&quantity_) -
reinterpret_cast<char*>(&resource_)) + sizeof(quantity_));
}
ResourceAllocation_Entry::~ResourceAllocation_Entry() {
// @@protoc_insertion_point(destructor:tensorflow.serving.ResourceAllocation.Entry)
SharedDtor();
}
void ResourceAllocation_Entry::SharedDtor() {
if (this != internal_default_instance()) delete resource_;
}
void ResourceAllocation_Entry::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* ResourceAllocation_Entry::descriptor() {
::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const ResourceAllocation_Entry& ResourceAllocation_Entry::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::scc_info_ResourceAllocation_Entry.base);
return *internal_default_instance();
}
void ResourceAllocation_Entry::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.serving.ResourceAllocation.Entry)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == NULL && resource_ != NULL) {
delete resource_;
}
resource_ = NULL;
quantity_ = GOOGLE_ULONGLONG(0);
_internal_metadata_.Clear();
}
bool ResourceAllocation_Entry::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.serving.ResourceAllocation.Entry)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .tensorflow.serving.Resource resource = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_resource()));
} else {
goto handle_unusual;
}
break;
}
// uint64 quantity = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &quantity_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.serving.ResourceAllocation.Entry)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.serving.ResourceAllocation.Entry)
return false;
#undef DO_
}
void ResourceAllocation_Entry::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.serving.ResourceAllocation.Entry)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .tensorflow.serving.Resource resource = 1;
if (this->has_resource()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->_internal_resource(), output);
}
// uint64 quantity = 2;
if (this->quantity() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(2, this->quantity(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.serving.ResourceAllocation.Entry)
}
::google::protobuf::uint8* ResourceAllocation_Entry::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.serving.ResourceAllocation.Entry)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .tensorflow.serving.Resource resource = 1;
if (this->has_resource()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->_internal_resource(), deterministic, target);
}
// uint64 quantity = 2;
if (this->quantity() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(2, this->quantity(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.serving.ResourceAllocation.Entry)
return target;
}
size_t ResourceAllocation_Entry::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.serving.ResourceAllocation.Entry)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// .tensorflow.serving.Resource resource = 1;
if (this->has_resource()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*resource_);
}
// uint64 quantity = 2;
if (this->quantity() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->quantity());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ResourceAllocation_Entry::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.serving.ResourceAllocation.Entry)
GOOGLE_DCHECK_NE(&from, this);
const ResourceAllocation_Entry* source =
::google::protobuf::internal::DynamicCastToGenerated<const ResourceAllocation_Entry>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.serving.ResourceAllocation.Entry)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.serving.ResourceAllocation.Entry)
MergeFrom(*source);
}
}
void ResourceAllocation_Entry::MergeFrom(const ResourceAllocation_Entry& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.serving.ResourceAllocation.Entry)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_resource()) {
mutable_resource()->::tensorflow::serving::Resource::MergeFrom(from.resource());
}
if (from.quantity() != 0) {
set_quantity(from.quantity());
}
}
void ResourceAllocation_Entry::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.serving.ResourceAllocation.Entry)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ResourceAllocation_Entry::CopyFrom(const ResourceAllocation_Entry& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.serving.ResourceAllocation.Entry)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ResourceAllocation_Entry::IsInitialized() const {
return true;
}
void ResourceAllocation_Entry::Swap(ResourceAllocation_Entry* other) {
if (other == this) return;
InternalSwap(other);
}
void ResourceAllocation_Entry::InternalSwap(ResourceAllocation_Entry* other) {
using std::swap;
swap(resource_, other->resource_);
swap(quantity_, other->quantity_);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata ResourceAllocation_Entry::GetMetadata() const {
protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void ResourceAllocation::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ResourceAllocation::kResourceQuantitiesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ResourceAllocation::ResourceAllocation()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::scc_info_ResourceAllocation.base);
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.serving.ResourceAllocation)
}
ResourceAllocation::ResourceAllocation(const ResourceAllocation& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
resource_quantities_(from.resource_quantities_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:tensorflow.serving.ResourceAllocation)
}
void ResourceAllocation::SharedCtor() {
}
ResourceAllocation::~ResourceAllocation() {
// @@protoc_insertion_point(destructor:tensorflow.serving.ResourceAllocation)
SharedDtor();
}
void ResourceAllocation::SharedDtor() {
}
void ResourceAllocation::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* ResourceAllocation::descriptor() {
::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const ResourceAllocation& ResourceAllocation::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::scc_info_ResourceAllocation.base);
return *internal_default_instance();
}
void ResourceAllocation::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.serving.ResourceAllocation)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
resource_quantities_.Clear();
_internal_metadata_.Clear();
}
bool ResourceAllocation::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.serving.ResourceAllocation)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .tensorflow.serving.ResourceAllocation.Entry resource_quantities = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_resource_quantities()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.serving.ResourceAllocation)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.serving.ResourceAllocation)
return false;
#undef DO_
}
void ResourceAllocation::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.serving.ResourceAllocation)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .tensorflow.serving.ResourceAllocation.Entry resource_quantities = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->resource_quantities_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1,
this->resource_quantities(static_cast<int>(i)),
output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.serving.ResourceAllocation)
}
::google::protobuf::uint8* ResourceAllocation::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.serving.ResourceAllocation)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .tensorflow.serving.ResourceAllocation.Entry resource_quantities = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->resource_quantities_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->resource_quantities(static_cast<int>(i)), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.serving.ResourceAllocation)
return target;
}
size_t ResourceAllocation::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.serving.ResourceAllocation)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// repeated .tensorflow.serving.ResourceAllocation.Entry resource_quantities = 1;
{
unsigned int count = static_cast<unsigned int>(this->resource_quantities_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->resource_quantities(static_cast<int>(i)));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ResourceAllocation::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.serving.ResourceAllocation)
GOOGLE_DCHECK_NE(&from, this);
const ResourceAllocation* source =
::google::protobuf::internal::DynamicCastToGenerated<const ResourceAllocation>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.serving.ResourceAllocation)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.serving.ResourceAllocation)
MergeFrom(*source);
}
}
void ResourceAllocation::MergeFrom(const ResourceAllocation& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.serving.ResourceAllocation)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
resource_quantities_.MergeFrom(from.resource_quantities_);
}
void ResourceAllocation::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.serving.ResourceAllocation)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ResourceAllocation::CopyFrom(const ResourceAllocation& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.serving.ResourceAllocation)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ResourceAllocation::IsInitialized() const {
return true;
}
void ResourceAllocation::Swap(ResourceAllocation* other) {
if (other == this) return;
InternalSwap(other);
}
void ResourceAllocation::InternalSwap(ResourceAllocation* other) {
using std::swap;
CastToBase(&resource_quantities_)->InternalSwap(CastToBase(&other->resource_quantities_));
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata ResourceAllocation::GetMetadata() const {
protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_tensorflow_5fserving_2fresources_2fresources_2eproto::file_level_metadata[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace serving
} // namespace tensorflow
namespace google {
namespace protobuf {
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::tensorflow::serving::Resource* Arena::CreateMaybeMessage< ::tensorflow::serving::Resource >(Arena* arena) {
return Arena::CreateInternal< ::tensorflow::serving::Resource >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::tensorflow::serving::ResourceAllocation_Entry* Arena::CreateMaybeMessage< ::tensorflow::serving::ResourceAllocation_Entry >(Arena* arena) {
return Arena::CreateInternal< ::tensorflow::serving::ResourceAllocation_Entry >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::tensorflow::serving::ResourceAllocation* Arena::CreateMaybeMessage< ::tensorflow::serving::ResourceAllocation >(Arena* arena) {
return Arena::CreateInternal< ::tensorflow::serving::ResourceAllocation >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
| diplomacy/research | diplomacy_research/proto/tensorflow_serving/resources/resources.pb.cc | C++ | mit | 43,981 |
// Description: C# Extension Methods | Enhance the .NET Framework and .NET Core with over 1000 extension methods.
// Website & Documentation: https://csharp-extension.com/
// Issues: https://github.com/zzzprojects/Z.ExtensionMethods/issues
// License (MIT): https://github.com/zzzprojects/Z.ExtensionMethods/blob/master/LICENSE
// More projects: https://zzzprojects.com/
// Copyright © ZZZ Projects Inc. All rights reserved.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
public static partial class Extensions
{
/// <summary>
/// Enumerates to entities in this collection.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an IEnumerable<T></returns>
public static IEnumerable<T> ToEntities<T>(this IDataReader @this) where T : new()
{
Type type = typeof (T);
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
var list = new List<T>();
var hash = new HashSet<string>(Enumerable.Range(0, @this.FieldCount)
.Select(@this.GetName));
while (@this.Read())
{
var entity = new T();
foreach (PropertyInfo property in properties)
{
if (hash.Contains(property.Name))
{
Type valueType = property.PropertyType;
property.SetValue(entity, @this[property.Name].To(valueType), null);
}
}
foreach (FieldInfo field in fields)
{
if (hash.Contains(field.Name))
{
Type valueType = field.FieldType;
field.SetValue(entity, @this[field.Name].To(valueType));
}
}
list.Add(entity);
}
return list;
}
} | zzzprojects/Z.ExtensionMethods | src/Z.Data/System.Data.IDataReader/IDataReader.ToEntities.cs | C# | mit | 2,073 |
'use strict'
const { Message: MessageModel } = require('../model')
module.exports = exports = {
sendAtMessage: (masterId, authorId, topicId, replyId) => {
return exports.sendMessage('at', masterId, authorId, topicId, replyId)
},
sendReplyMessage: (masterId, authorId, topicId, replyId) => {
return exports.sendMessage('reply', masterId, authorId, topicId, replyId)
},
sendMessage: (type, masterId, authorId, topicId, replyId) => {
return new MessageModel({
type: type,
master_id: masterId,
author_id: authorId,
topic_id: topicId,
reply_id: replyId
}).save()
}
}
| xiedacon/nodeclub-koa | app/common/message.js | JavaScript | mit | 622 |
export { default as Toolbar } from './Toolbar';
export { default as ToolbarSection } from './ToolbarSection';
export { default as ToolbarTitle } from './ToolbarTitle';
export { default as ToolbarRow } from './ToolbarRow';
export { default as ToolbarIcon } from './ToolbarIcon';
| kradio3/react-mdc-web | src/Toolbar/index.js | JavaScript | mit | 278 |
<table>
<tr>
<th>NIM</th>
<th>Nama</th>
</tr>
<tr>
<td>23511000</td>
<td>Alex Xandra Albert Sim</td>
</tr>
</table> | basroni/aplikasicekin | table.php | PHP | mit | 163 |
<?php
/**
* RedirectApi
*
* @category Class
* @package Pananames
*/
namespace Pananames\Api;
class RedirectApi extends ApiClient
{
private $settings;
public function __construct($signature, $url)
{
if (empty($signature)) {
throw new \InvalidArgumentException('Signature was not provided or was invalid.');
}
if (empty($url)) {
throw new \InvalidArgumentException('Url was not provided or was invalid.');
}
$this->settings['url'] = $url;
$this->settings['signature'] = $signature;
}
/**
* Function disable
*
* Disable redirect.
*
* @param string $domain The name of the domain. (required)
* @return \Pananames\Model\EmptyResponse
*/
public function disable($domain)
{
if (empty($domain)) {
throw new \InvalidArgumentException('Missing the required parameter $domain when calling disable');
}
if (strlen($domain) < 3) {
throw new \InvalidArgumentException('Invalid length for "$domain" when calling RedirectApi.disable, must be bigger than or equal to 3.');
}
$url = str_replace('{'.'domain'.'}', ObjectSerializer::toPathValue($domain), '/domains/{domain}/redirect');
$returnType = '\Pananames\Model\EmptyResponse';
return $this->sendRequest('DELETE', $url, [], $this->settings, $returnType);
}
/**
* Function enable
*
* Enable redirect.
*
* @param string $domain The name of the domain. (required)
* @param \Pananames\Model\DomainRedirectRequest $data (required)
* @return \Pananames\Model\DomainRedirectResponse
*/
public function enable($domain, $data)
{
if (empty($domain)) {
throw new \InvalidArgumentException('Missing the required parameter $domain when calling enable');
}
if (empty($data)) {
throw new \InvalidArgumentException('Missing the required parameter $data when calling enable');
}
if (strlen($domain) < 3) {
throw new \InvalidArgumentException('Invalid length for "$domain" when calling RedirectApi.enable, must be bigger than or equal to 3.');
}
$url = str_replace('{'.'domain'.'}', ObjectSerializer::toPathValue($domain), '/domains/{domain}/redirect');
$returnType = '\Pananames\Model\DomainRedirectResponse';
return $this->sendRequest('PUT', $url, $data, $this->settings, $returnType);
}
/**
* Function getRedirect
*
* Get current redirect URL.
*
* @param string $domain The name of the domain. (required)
* @return \Pananames\Model\DomainRedirectResponse
*/
public function getRedirect($domain)
{
if (empty($domain)) {
throw new \InvalidArgumentException('Missing the required parameter $domain when calling getRedirect');
}
if (strlen($domain) < 3) {
throw new \InvalidArgumentException('Invalid length for "$domain" when calling RedirectApi.getRedirect, must be bigger than or equal to 3.');
}
$url = str_replace('{'.'domain'.'}', ObjectSerializer::toPathValue($domain), '/domains/{domain}/redirect');
$returnType = '\Pananames\Model\DomainRedirectResponse';
return $this->sendRequest('GET', $url, [], $this->settings, $returnType);
}
}
| Pananames/php-api | lib/Api/RedirectApi.php | PHP | mit | 3,052 |
namespace DictionaryEdit
{
partial class DefinitionForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.defHeadBox = new System.Windows.Forms.TextBox();
this.defPOSBox = new System.Windows.Forms.ComboBox();
this.addIllBtn = new System.Windows.Forms.Button();
this.defSDefBox = new System.Windows.Forms.TextBox();
this.defDefBox = new System.Windows.Forms.TextBox();
this.okBtn = new System.Windows.Forms.Button();
this.cnclBtn = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 13);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(59, 13);
this.label1.TabIndex = 0;
this.label1.Text = "HeadWord";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(13, 48);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(29, 13);
this.label2.TabIndex = 1;
this.label2.Text = "POS";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(13, 83);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(79, 13);
this.label3.TabIndex = 2;
this.label3.Text = "Short Definition";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(13, 122);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(51, 13);
this.label4.TabIndex = 3;
this.label4.Text = "Definition";
//
// defHeadBox
//
this.defHeadBox.Location = new System.Drawing.Point(102, 15);
this.defHeadBox.Name = "defHeadBox";
this.defHeadBox.ReadOnly = true;
this.defHeadBox.Size = new System.Drawing.Size(383, 20);
this.defHeadBox.TabIndex = 4;
//
// defPOSBox
//
this.defPOSBox.FormattingEnabled = true;
this.defPOSBox.Items.AddRange(new object[] {
"adj.",
"adv.",
"conj.",
"ideo.",
"prep.",
"pro.",
"n.",
"v."});
this.defPOSBox.Location = new System.Drawing.Point(102, 48);
this.defPOSBox.Name = "defPOSBox";
this.defPOSBox.Size = new System.Drawing.Size(383, 21);
this.defPOSBox.TabIndex = 5;
//
// addIllBtn
//
this.addIllBtn.Location = new System.Drawing.Point(500, 15);
this.addIllBtn.Name = "addIllBtn";
this.addIllBtn.Size = new System.Drawing.Size(100, 23);
this.addIllBtn.TabIndex = 6;
this.addIllBtn.Text = "Add Illustrations";
this.addIllBtn.UseVisualStyleBackColor = true;
this.addIllBtn.Click += new System.EventHandler(this.addIllBtn_Click);
//
// defSDefBox
//
this.defSDefBox.Location = new System.Drawing.Point(102, 83);
this.defSDefBox.Name = "defSDefBox";
this.defSDefBox.Size = new System.Drawing.Size(573, 20);
this.defSDefBox.TabIndex = 7;
//
// defDefBox
//
this.defDefBox.Location = new System.Drawing.Point(102, 122);
this.defDefBox.Multiline = true;
this.defDefBox.Name = "defDefBox";
this.defDefBox.Size = new System.Drawing.Size(573, 89);
this.defDefBox.TabIndex = 8;
//
// okBtn
//
this.okBtn.Location = new System.Drawing.Point(705, 122);
this.okBtn.Name = "okBtn";
this.okBtn.Size = new System.Drawing.Size(75, 23);
this.okBtn.TabIndex = 9;
this.okBtn.Text = "OK";
this.okBtn.UseVisualStyleBackColor = true;
this.okBtn.Click += new System.EventHandler(this.okBtn_Click);
//
// cnclBtn
//
this.cnclBtn.Location = new System.Drawing.Point(705, 167);
this.cnclBtn.Name = "cnclBtn";
this.cnclBtn.Size = new System.Drawing.Size(75, 23);
this.cnclBtn.TabIndex = 10;
this.cnclBtn.Text = "Cancel";
this.cnclBtn.UseVisualStyleBackColor = true;
this.cnclBtn.Click += new System.EventHandler(this.cnclBtn_Click);
//
// DefinitionForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(798, 258);
this.Controls.Add(this.cnclBtn);
this.Controls.Add(this.okBtn);
this.Controls.Add(this.defDefBox);
this.Controls.Add(this.defSDefBox);
this.Controls.Add(this.addIllBtn);
this.Controls.Add(this.defPOSBox);
this.Controls.Add(this.defHeadBox);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "DefinitionForm";
this.Text = "Definition Form";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox defHeadBox;
private System.Windows.Forms.ComboBox defPOSBox;
private System.Windows.Forms.Button addIllBtn;
private System.Windows.Forms.TextBox defSDefBox;
private System.Windows.Forms.TextBox defDefBox;
private System.Windows.Forms.Button okBtn;
private System.Windows.Forms.Button cnclBtn;
}
} | joedanpar/Academic-Projects | CSCI 473/DictionaryEdit/DefinitionForm.Designer.cs | C# | mit | 7,506 |
package org.amityregion5.terragame;
public class GameLoop implements Runnable {
private void loop(double delta) {
}
@Override
public void run() {
long fpsTimer = System.currentTimeMillis();
int targetFPS = 30;
double nsPerUpdate = 1000000000.0 / targetFPS;
// last update
double then = System.nanoTime();
double unprocessed = 0;
boolean shouldLoop = false;
double lastUpdate = System.nanoTime();
while (true)
{
double now = System.nanoTime();
unprocessed += (now - then) / nsPerUpdate;
then = now;
// update
while (unprocessed >= 1)
{
// update++;
// update();
unprocessed--;
shouldLoop = true;
}
if (shouldLoop)
{
loop((now - lastUpdate) * targetFPS/1e9);
lastUpdate = now;
shouldLoop = false;
} else
{
try
{
Thread.sleep(1);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (System.currentTimeMillis() - fpsTimer > 1000)
{
// System.out.println("Update=" + update);
// System.out.println("FPS=" + fps);
// put code for processing fps data here!!!!
// update = 0;
fpsTimer = System.currentTimeMillis();
}
}
}
}
| AmityHighCSDevTeam/TerraGame | core/src/org/amityregion5/terragame/GameLoop.java | Java | mit | 1,242 |
package walnut
import (
"fmt"
"reflect"
"testing"
"time"
)
var splitTests = []struct {
in string
out []line
err error
}{
{"", []line{}, nil},
{"# comment", []line{}, nil},
{"\n\na=1\n\n", []line{{3, 0, "a=1"}}, nil},
{"a=1\nb=2", []line{{1, 0, "a=1"}, {2, 0, "b=2"}}, nil},
{"a=1\na=1", []line{{1, 0, "a=1"}, {2, 0, "a=1"}}, nil},
{"a=1\n b=2", []line{{1, 0, "a=1"}, {2, 1, "b=2"}}, nil},
{"a=1\n\tb=2", []line{{1, 0, "a=1"}, {2, 1, "b=2"}}, nil},
{"a=1\n\t \n\tb=2", []line{{1, 0, "a=1"}, {3, 1, "b=2"}}, nil},
{"\n\t\t\n\n ", []line{}, nil},
{" a=1", nil, fmt.Errorf(errIndent, 1)},
{"a=1\n b=2\n c=3", nil, fmt.Errorf(errIndent, 3)},
{"a=1\n b=2\n\tc=3", nil, fmt.Errorf(errIndent, 3)},
}
func TestSplit(t *testing.T) {
for _, test := range splitTests {
out, err := split([]byte(test.in))
if !eq(out, test.out) || !eq(err, test.err) {
t.Errorf("split(%q):", test.in)
t.Errorf(" got %+v, %v", out, err)
t.Errorf(" want %+v, %v", test.out, test.err)
}
}
}
var interpretTests = []struct {
in []line
out []assignment
err error
}{
{
[]line{{3, 0, "a=1"}},
[]assignment{{3, "a", "1", int64(1)}},
nil,
},
{
[]line{{1, 0, "b=2"}, {2, 0, "c=3"}},
[]assignment{{1, "b", "2", int64(2)}, {2, "c", "3", int64(3)}},
nil,
},
{
[]line{{1, 0, "d"}, {2, 1, "e=4"}},
[]assignment{
{2, "d.e", "4", int64(4)},
},
nil,
},
{
[]line{{1, 0, "foo"}, {2, 1, "bar=5"}, {3, 1, "baz=6"}},
[]assignment{
{2, "foo.bar", "5", int64(5)},
{3, "foo.baz", "6", int64(6)},
},
nil,
},
{
[]line{{1, 0, "group#snug"}, {3, 1, "key=\"test\"#snug"}},
[]assignment{
{3, "group.key", "\"test\"#snug", "test"},
},
nil,
},
{
[]line{{1, 0, "bool = true"}},
[]assignment{
{1, "bool", "true", true},
},
nil,
},
{
[]line{{1, 0, "int64 = 12345"}},
[]assignment{
{1, "int64", "12345", int64(12345)},
},
nil,
},
{
[]line{{1, 0, "float64 = 123.45"}},
[]assignment{
{1, "float64", "123.45", float64(123.45)},
},
nil,
},
{
[]line{{1, 0, "string = \"hello\""}},
[]assignment{
{1, "string", "\"hello\"", "hello"},
},
nil,
},
{
[]line{{1, 0, "time = 2012-01-02 15:30:28.000000000789 +0000"}},
func() []assignment {
raw := "2012-01-02 15:30:28.000000000789 +0000"
t, _ := time.Parse("2006-01-02 15:04:05 -0700", raw)
return []assignment{{1, "time", raw, t}}
}(),
nil,
},
{
[]line{{1, 0, "duration = 10m 20s"}},
[]assignment{
{1, "duration", "10m 20s", 10*time.Minute + 20*time.Second},
},
nil,
},
{
[]line{{1, 0, "♫ = 123"}},
[]assignment{
{1, "♫", "123", int64(123)},
},
nil,
},
{[]line{{1, 0, "=1"}}, nil, fmt.Errorf(errKey, 1)},
{[]line{{1, 0, " = 1"}}, nil, fmt.Errorf(errKey, 1)},
{[]line{{1, 0, "== 1"}}, nil, fmt.Errorf(errKey, 1)},
{[]line{{1, 0, "a b = 1"}}, nil, fmt.Errorf(errKey, 1)},
{[]line{{1, 0, "a\tb"}}, nil, fmt.Errorf(errKey, 1)},
{[]line{{1, 0, "a = 0 0"}}, nil, fmt.Errorf(errValue, 1, "0 0")},
{[]line{{1, 0, "a == 0"}}, nil, fmt.Errorf(errValue, 1, "= 0")},
}
func TestInterpret(t *testing.T) {
for _, test := range interpretTests {
out, err := interpret(test.in)
if !eq(out, test.out) || !eq(err, test.err) {
t.Errorf("interpret(%+v):", test.in)
t.Errorf(" got %+v, %v", out, err)
t.Errorf(" want %+v, %v", test.out, test.err)
}
}
}
var initializeTests = []struct {
in []assignment
out map[string]interface{}
err error
}{
{
[]assignment{{1, "a", "1", int64(1)}},
map[string]interface{}{
"a": int64(1),
},
nil,
},
{
[]assignment{{1, "foo.bar", "2", int64(2)}, {1, "foo.baz", "3", int64(3)}},
map[string]interface{}{
"foo.bar": int64(2),
"foo.baz": int64(3),
},
nil,
},
{
[]assignment{{1, "a", "1", int64(1)}, {2, "a.b", "2", int64(2)}},
nil,
fmt.Errorf(errConflict, "a.b", 2, "a", 1),
},
{
[]assignment{{1, "a", "1", int64(1)}, {2, "a", "1", int64(1)}},
nil,
fmt.Errorf(errConflict, "a", 2, "a", 1),
},
{
[]assignment{{1, "a.b.c", "1", int64(1)}, {2, "a.b", "2", int64(2)}},
nil,
fmt.Errorf(errConflict, "a.b", 2, "a.b.c", 1),
},
{
[]assignment{{1, "a.b", "1", int64(1)}, {2, "a.b.c", "2", int64(2)}},
nil,
fmt.Errorf(errConflict, "a.b.c", 2, "a.b", 1),
},
}
func TestInitialize(t *testing.T) {
for _, test := range initializeTests {
out, err := initialize(test.in)
if !eq(out, test.out) || !eq(err, test.err) {
t.Errorf("initialize(%+v):", test.in)
t.Errorf(" got %+v, %v", out, err)
t.Errorf(" want %+v, %v", test.out, test.err)
}
}
}
// shorthand for reflect.DeepEqual
func eq(a, b interface{}) bool {
return reflect.DeepEqual(a, b)
}
| erkl-old/walnut | parse_test.go | GO | mit | 4,629 |
/*
* stylie.treeview
* https://github.com/typesettin/stylie.treeview
*
* Copyright (c) 2015 Yaw Joseph Etse. All rights reserved.
*/
'use strict';
var extend = require('util-extend'),
CodeMirror = require('codemirror'),
StylieModals = require('stylie.modals'),
editorModals,
events = require('events'),
classie = require('classie'),
util = require('util');
require('../../node_modules/codemirror/addon/edit/matchbrackets');
require('../../node_modules/codemirror/addon/hint/css-hint');
require('../../node_modules/codemirror/addon/hint/html-hint');
require('../../node_modules/codemirror/addon/hint/javascript-hint');
require('../../node_modules/codemirror/addon/hint/show-hint');
require('../../node_modules/codemirror/addon/lint/css-lint');
require('../../node_modules/codemirror/addon/lint/javascript-lint');
// require('../../node_modules/codemirror/addon/lint/json-lint');
require('../../node_modules/codemirror/addon/lint/lint');
// require('../../node_modules/codemirror/addon/lint/html-lint');
require('../../node_modules/codemirror/addon/comment/comment');
require('../../node_modules/codemirror/addon/comment/continuecomment');
require('../../node_modules/codemirror/addon/fold/foldcode');
require('../../node_modules/codemirror/addon/fold/comment-fold');
require('../../node_modules/codemirror/addon/fold/indent-fold');
require('../../node_modules/codemirror/addon/fold/brace-fold');
require('../../node_modules/codemirror/addon/fold/foldgutter');
require('../../node_modules/codemirror/mode/css/css');
require('../../node_modules/codemirror/mode/htmlembedded/htmlembedded');
require('../../node_modules/codemirror/mode/htmlmixed/htmlmixed');
require('../../node_modules/codemirror/mode/javascript/javascript');
var saveSelection = function () {
if (window.getSelection) {
var sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
return sel.getRangeAt(0);
}
}
else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
};
var restoreSelection = function (range) {
if (range) {
if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
else if (document.selection && range.select) {
range.select();
}
}
};
var getInsertTextModal = function (orignialid, mtype) {
var returnDiv = document.createElement('div'),
modaltype = (mtype === 'image') ? 'image' : 'text',
// execcmd = (mtype === 'image') ? 'insertImage' : 'createLink',
samplelink = (mtype === 'image') ? 'https://developers.google.com/+/images/branding/g+138.png' : 'http://example.com',
linktype = (mtype === 'image') ? 'image' : 'link';
returnDiv.setAttribute('id', orignialid + '-insert' + modaltype + '-modal');
returnDiv.setAttribute('data-name', orignialid + '-insert' + modaltype + '-modal');
returnDiv.setAttribute('class', 'ts-modal ts-modal-effect-1 insert' + modaltype + '-modal');
var divInnerHTML = '<section class="ts-modal-content ts-bg-text-primary-color ts-no-heading-margin ts-padding-lg ts-shadow ">';
divInnerHTML += '<div class="ts-form">';
divInnerHTML += '<div class="ts-row">';
divInnerHTML += '<div class="ts-col-span12">';
divInnerHTML += '<h6>Insert a link</h6>';
divInnerHTML += '</div>';
divInnerHTML += '</div>';
// divInnerHTML += '<div class="ts-row">';
// divInnerHTML += '<div class="ts-col-span4">';
// divInnerHTML += '<label class="ts-label">text</label>';
// divInnerHTML += '</div>';
// divInnerHTML += '<div class="ts-col-span8">';
// divInnerHTML += '<input type="text" name="link_url" placeholder="some web link" value="some web link"/>';
// divInnerHTML += '</div>';
// divInnerHTML += '</div>';
divInnerHTML += '<div class="ts-row">';
divInnerHTML += '<div class="ts-col-span4">';
divInnerHTML += '<label class="ts-label">url</label>';
divInnerHTML += '</div>';
divInnerHTML += '<div class="ts-col-span8">';
divInnerHTML += '<input type="text" class="ts-input ts-' + linktype + '_url" name="' + linktype + '_url" placeholder="' + samplelink + '" value="' + samplelink + '"/>';
divInnerHTML += '</div>';
divInnerHTML += '</div>';
divInnerHTML += '<div class="ts-row ts-text-center">';
divInnerHTML += '<div class="ts-col-span6">';
// divInnerHTML += '<button type="button" class="ts-button ts-modal-close ts-button-primary-color" onclick="document.execCommand(\'insertImage\', false, \'http://lorempixel.com/40/20/sports/\');">insert link</button>';
divInnerHTML += '<button type="button" class="ts-button ts-modal-close ts-button-primary-color add-' + linktype + '-button" >insert ' + linktype + '</button>';
divInnerHTML += '</div>';
divInnerHTML += '<div class="ts-col-span6">';
divInnerHTML += '<a class="ts-button ts-modal-close">close</a>';
divInnerHTML += '</div>';
divInnerHTML += '</div>';
divInnerHTML += '</div>';
divInnerHTML += '</section>';
returnDiv.innerHTML = divInnerHTML;
return returnDiv;
};
/**
* A module that represents a StylieTextEditor object, a componentTab is a page composition tool.
* @{@link https://github.com/typesettin/stylie.treeview}
* @author Yaw Joseph Etse
* @copyright Copyright (c) 2015 Typesettin. All rights reserved.
* @license MIT
* @constructor StylieTextEditor
* @requires module:util-extent
* @requires module:util
* @requires module:events
* @param {object} el element of tab container
* @param {object} options configuration options
*/
var StylieTextEditor = function (options) {
events.EventEmitter.call(this);
var defaultOptions = {
type: 'html',
updateOnChange: true
};
this.options = extend(defaultOptions, options);
return this;
// this.getTreeHTML = this.getTreeHTML;
};
util.inherits(StylieTextEditor, events.EventEmitter);
var createButton = function (options) {
var buttonElement = document.createElement('button');
buttonElement.setAttribute('class', 'ts-button ts-text-xs ' + options.classes);
buttonElement.setAttribute('type', 'button');
buttonElement.innerHTML = options.innerHTML;
for (var key in options) {
if (key !== 'classes' && key !== 'innerHTML' && key !== 'innerhtml') {
buttonElement.setAttribute(key, options[key]);
}
}
return buttonElement;
};
StylieTextEditor.prototype.addMenuButtons = function () {
this.options.buttons.boldButton = createButton({
classes: ' flaticon-bold17 ',
title: 'Bold text',
innerHTML: ' ',
'data-attribute-action': 'bold'
});
this.options.buttons.italicButton = createButton({
classes: ' flaticon-italic9 ',
title: 'Italic text',
innerHTML: ' ',
'data-attribute-action': 'italic'
});
this.options.buttons.underlineButton = createButton({
classes: ' flaticon-underlined5 ',
title: 'Underline text',
innerHTML: ' ',
'data-attribute-action': 'underline'
});
this.options.buttons.unorderedLIButton = createButton({
classes: ' flaticon-list82 ',
innerHTML: ' ',
title: ' Insert unordered list ',
'data-attribute-action': 'unorderedLI'
});
this.options.buttons.orderedLIButton = createButton({
classes: ' flaticon-numbered8 ',
title: ' Insert ordered list ',
innerHTML: ' ',
'data-attribute-action': 'orderedLI'
});
this.options.buttons.lefttextalignButton = createButton({
classes: ' flaticon-text141 ',
innerHTML: ' ',
title: ' left align text ',
'data-attribute-action': 'left-textalign'
}); //flaticon-text141
this.options.buttons.centertextalignButton = createButton({
classes: ' flaticon-text136 ',
innerHTML: ' ',
title: ' center align text ',
'data-attribute-action': 'center-textalign'
}); //flaticon-text136
this.options.buttons.righttextalignButton = createButton({
classes: ' flaticon-text134 ',
innerHTML: ' ',
title: ' right align text ',
'data-attribute-action': 'right-textalign'
}); //flaticon-text134
this.options.buttons.justifytextalignButton = createButton({
classes: ' flaticon-text146 ',
innerHTML: ' ',
title: ' justify align text ',
'data-attribute-action': 'justify-textalign'
}); //flaticon-text146
//flaticon-characters - font
this.options.buttons.textcolorButton = createButton({
classes: ' flaticon-text137 ',
innerHTML: ' ',
title: ' change text color ',
'data-attribute-action': 'text-color'
}); //flaticon-text137 - text color
this.options.buttons.texthighlightButton = createButton({
classes: ' flaticon-paintbrush13 ',
innerHTML: ' ',
title: ' change text highlight ',
'data-attribute-action': 'text-highlight'
}); //flaticon-paintbrush13 - text background color(highlight)
this.options.buttons.linkButton = createButton({
classes: ' flaticon-link56 ',
title: ' Insert a link ',
innerHTML: ' ',
'data-attribute-action': 'link'
});
this.options.buttons.imageButton = createButton({
classes: ' flaticon-images25 ',
title: ' Insert image ',
innerHTML: ' ',
'data-attribute-action': 'image'
});
this.options.buttons.codeButton = createButton({
innerHTML: ' ',
classes: ' flaticon-code39 ',
title: 'Source code editor',
'data-attribute-action': 'code'
});
this.options.buttons.fullscreenButton = createButton({
title: 'Maximize and fullscreen editor',
classes: ' flaticon-logout18 ',
innerHTML: ' ',
'data-attribute-action': 'fullscreen'
});
this.options.buttons.outdentButton = createButton({
title: 'Outdent button',
classes: ' flaticon-paragraph19 ',
innerHTML: ' ',
'data-attribute-action': 'outdent'
});
this.options.buttons.indentButton = createButton({
title: 'Indent button',
classes: ' flaticon-right195 ',
innerHTML: ' ',
'data-attribute-action': 'indent'
});
};
var button_gobold = function () {
document.execCommand('bold', false, '');
};
var button_gounderline = function () {
document.execCommand('underline', false, '');
};
var button_goitalic = function () {
document.execCommand('italic', false, '');
};
var button_golink = function () {
document.execCommand('createLink', true, '');
};
var button_golist = function () {
document.execCommand('insertOrderedList', true, '');
};
var button_gobullet = function () {
document.execCommand('insertUnorderedList', true, '');
};
var button_goimg = function () {
// document.execCommand('insertImage', false, 'http://lorempixel.com/40/20/sports/');
this.saveSelection();
window.editorModals.show(this.options.elementContainer.getAttribute('data-original-id') + '-insertimage-modal');
};
var button_gotextlink = function () {
// console.log(this.options.elementContainer.getAttribute('data-original-id'));
this.saveSelection();
window.editorModals.show(this.options.elementContainer.getAttribute('data-original-id') + '-inserttext-modal');
};
var add_link_to_editor = function () {
this.restoreSelection();
document.execCommand('createLink', false, this.options.forms.add_link_form.querySelector('.ts-link_url').value);
};
var add_image_to_editor = function () {
this.restoreSelection();
document.execCommand('insertImage', false, this.options.forms.add_image_form.querySelector('.ts-image_url').value);
};
var button_gofullscreen = function () {
// console.log('button_gofullscreen this', this);
// if()
classie.toggle(this.options.elementContainer, 'ts-editor-fullscreen');
classie.toggle(this.options.buttons.fullscreenButton, 'ts-button-primary-text-color');
};
var button_togglecodeeditor = function () {
classie.toggle(this.options.codemirror.getWrapperElement(), 'ts-hidden');
classie.toggle(this.options.buttons.codeButton, 'ts-button-primary-text-color');
this.options.codemirror.refresh();
};
var button_gotext_left = function () {
document.execCommand('justifyLeft', true, '');
};
var button_gotext_center = function () {
document.execCommand('justifyCenter', true, '');
};
var button_gotext_right = function () {
document.execCommand('justifyRight', true, '');
};
var button_gotext_justifyfull = function () {
document.execCommand('justifyFull', true, '');
};
// var button_gotext_left = function () {
// document.execCommand('justifyLeft', true, '');
// };
var button_go_outdent = function () {
document.execCommand('outdent', true, '');
};
var button_go_indent = function () {
document.execCommand('indent', true, '');
};
StylieTextEditor.prototype.initButtonEvents = function () {
this.options.buttons.boldButton.addEventListener('click', button_gobold, false);
this.options.buttons.underlineButton.addEventListener('click', button_gounderline, false);
this.options.buttons.italicButton.addEventListener('click', button_goitalic, false);
this.options.buttons.linkButton.addEventListener('click', button_golink, false);
this.options.buttons.unorderedLIButton.addEventListener('click', button_gobullet, false);
this.options.buttons.orderedLIButton.addEventListener('click', button_golist, false);
this.options.buttons.imageButton.addEventListener('click', button_goimg.bind(this), false);
this.options.buttons.linkButton.addEventListener('click', button_gotextlink.bind(this), false);
this.options.buttons.lefttextalignButton.addEventListener('click', button_gotext_left, false);
this.options.buttons.centertextalignButton.addEventListener('click', button_gotext_center, false);
this.options.buttons.righttextalignButton.addEventListener('click', button_gotext_right, false);
this.options.buttons.justifytextalignButton.addEventListener('click', button_gotext_justifyfull, false);
this.options.buttons.outdentButton.addEventListener('click', button_go_outdent, false);
this.options.buttons.indentButton.addEventListener('click', button_go_indent, false);
this.options.buttons.fullscreenButton.addEventListener('click', button_gofullscreen.bind(this), false);
this.options.buttons.codeButton.addEventListener('click', button_togglecodeeditor.bind(this), false);
this.options.buttons.addlinkbutton.addEventListener('click', add_link_to_editor.bind(this), false);
this.options.buttons.addimagebutton.addEventListener('click', add_image_to_editor.bind(this), false);
};
StylieTextEditor.prototype.init = function () {
try {
var previewEditibleDiv = document.createElement('div'),
previewEditibleMenu = document.createElement('div'),
insertImageURLModal = getInsertTextModal(this.options.element.getAttribute('id'), 'image'),
insertTextLinkModal = getInsertTextModal(this.options.element.getAttribute('id'), 'text'),
previewEditibleContainer = document.createElement('div');
this.options.buttons = {};
this.addMenuButtons();
previewEditibleMenu.appendChild(this.options.buttons.boldButton);
previewEditibleMenu.appendChild(this.options.buttons.italicButton);
previewEditibleMenu.appendChild(this.options.buttons.underlineButton);
previewEditibleMenu.appendChild(this.options.buttons.unorderedLIButton);
previewEditibleMenu.appendChild(this.options.buttons.orderedLIButton);
previewEditibleMenu.appendChild(this.options.buttons.lefttextalignButton);
previewEditibleMenu.appendChild(this.options.buttons.centertextalignButton);
previewEditibleMenu.appendChild(this.options.buttons.righttextalignButton);
previewEditibleMenu.appendChild(this.options.buttons.justifytextalignButton);
// previewEditibleMenu.appendChild(this.options.buttons.textcolorButton);
// previewEditibleMenu.appendChild(this.options.buttons.texthighlightButton);
previewEditibleMenu.appendChild(this.options.buttons.outdentButton);
previewEditibleMenu.appendChild(this.options.buttons.indentButton);
previewEditibleMenu.appendChild(this.options.buttons.linkButton);
previewEditibleMenu.appendChild(this.options.buttons.imageButton);
previewEditibleMenu.appendChild(this.options.buttons.codeButton);
previewEditibleMenu.appendChild(this.options.buttons.fullscreenButton);
previewEditibleMenu.setAttribute('class', 'ts-input ts-editor-menu ts-padding-sm');
previewEditibleMenu.setAttribute('style', 'font-family: monospace, Arial,"Times New Roman";');
previewEditibleDiv.setAttribute('class', 'ts-input ts-texteditor');
previewEditibleDiv.setAttribute('contenteditable', 'true');
previewEditibleDiv.setAttribute('tabindex', '1');
previewEditibleContainer.setAttribute('id', this.options.element.getAttribute('id') + '_container');
previewEditibleContainer.setAttribute('data-original-id', this.options.element.getAttribute('id'));
previewEditibleContainer.setAttribute('class', 'ts-editor-container');
previewEditibleContainer.appendChild(previewEditibleMenu);
previewEditibleContainer.appendChild(previewEditibleDiv);
document.querySelector('.ts-modal-hidden-container').appendChild(insertTextLinkModal);
document.querySelector('.ts-modal-hidden-container').appendChild(insertImageURLModal);
this.options.element = this.options.element || document.querySelector(this.options.elementSelector);
previewEditibleDiv.innerHTML = this.options.element.innerText;
this.options.previewElement = previewEditibleDiv;
this.options.forms = {
add_link_form: document.querySelector('.inserttext-modal .ts-form'),
add_image_form: document.querySelector('.insertimage-modal .ts-form')
};
this.options.buttons.addlinkbutton = document.querySelector('.inserttext-modal').querySelector('.add-link-button');
this.options.buttons.addimagebutton = document.querySelector('.insertimage-modal').querySelector('.add-image-button');
//now add code mirror
this.options.elementContainer = previewEditibleContainer;
this.options.element.parentNode.appendChild(previewEditibleContainer);
previewEditibleContainer.appendChild(this.options.element);
this.options.codemirror = CodeMirror.fromTextArea(
this.options.element, {
lineNumbers: true,
lineWrapping: true,
matchBrackets: true,
autoCloseBrackets: true,
mode: (this.options.type === 'ejs') ? 'text/ejs' : 'text/html',
indentUnit: 2,
indentWithTabs: true,
'overflow-y': 'hidden',
'overflow-x': 'auto',
lint: true,
gutters: [
'CodeMirror-linenumbers',
'CodeMirror-foldgutter',
// 'CodeMirror-lint-markers'
],
foldGutter: true
}
);
// this.options.element.parentNode.insertBefore(previewEditibleDiv, this.options.element);
this.options.codemirror.on('blur', function (instance) {
// console.log('editor lost focuss', instance, change);
this.options.previewElement.innerHTML = instance.getValue();
}.bind(this));
this.options.previewElement.addEventListener('blur', function () {
this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML);
}.bind(this));
if (this.options.updateOnChange) {
this.options.codemirror.on('change', function (instance) {
// console.log('editor lost focuss', instance, change);
// console.log('document.activeElement === this.options.previewElement', document.activeElement === this.options.previewElement);
setTimeout(function () {
if (document.activeElement !== this.options.previewElement) {
this.options.previewElement.innerHTML = instance.getValue();
}
}.bind(this), 5000);
}.bind(this));
this.options.previewElement.addEventListener('change', function () {
this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML);
}.bind(this));
}
//set initial code mirror
this.options.codemirror.getDoc().setValue(this.options.previewElement.innerHTML);
this.options.codemirror.refresh();
classie.add(this.options.codemirror.getWrapperElement(), 'ts-hidden');
// setTimeout(this.options.codemirror.refresh, 1000);
this.initButtonEvents();
editorModals = new StylieModals({});
window.editorModals = editorModals;
return this;
}
catch (e) {
console.error(e);
}
};
StylieTextEditor.prototype.getValue = function () {
return this.options.previewElement.innerText || this.options.codemirror.getValue();
};
StylieTextEditor.prototype.saveSelection = function () {
this.options.selection = (saveSelection()) ? saveSelection() : null;
};
StylieTextEditor.prototype.restoreSelection = function () {
this.options.preview_selection = this.options.selection;
restoreSelection(this.options.selection);
};
module.exports = StylieTextEditor;
| typesettin/periodicjs.ext.asyncadmin | resources/js/stylieeditor.js | JavaScript | mit | 19,967 |
<?php
/**
* YAWIK
*
* @filesource
* @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
* @license MIT
*/
namespace Auth\Factory\Service;
use Auth\Repository;
use Auth\Service\Register;
use Interop\Container\ContainerInterface;
use Interop\Container\Exception\ContainerException;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Exception\ServiceNotFoundException;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class RegisterFactory implements FactoryInterface
{
/**
* Create a Register service
*
* @param ContainerInterface $container
* @param string $requestedName
* @param null|array $options
*
* @return Register
* @throws ServiceNotFoundException if unable to resolve the service.
* @throws ServiceNotCreatedException if an exception is raised when
* creating a service.
* @throws ContainerException if any other error occurs
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
/* @var Repository\User $userRepository */
$userRepository = $container->get('repositories')->get('Auth/User');
/* @var \Core\Mail\MailService $mailService */
$mailService = $container->get('Core/MailService');
/* @var \Core\Options\ModuleOptions $config */
$config = $container->get('Core/Options');
$service = new Register($userRepository, $mailService, $config);
$events = $container->get('Auth/Events');
$service->setEventManager($events);
return $service;
}
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
*
* @return Register
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $this($serviceLocator, Register::class);
}
}
| kilip/YAWIK | module/Auth/src/Auth/Factory/Service/RegisterFactory.php | PHP | mit | 1,972 |
import { Activity } from "./Activity";
export interface TimeEntry {
activity: Activity;
comments: string;
created_on: string;
hours: number;
id: number;
issue: any;
project: any;
spent_on: string;
updated_on: string;
user: any;
} | hectorrmz/test | src/models/TimeEntry.ts | TypeScript | mit | 270 |
// $Id: HTTP_Service_Handler.cpp 82739 2008-09-16 12:20:46Z johnnyw $
#define ACE_BUILD_SVC_DLL
#include "ace/OS.h"
#include "ace/Get_Opt.h"
#include "jaws3/Concurrency.h"
#include "HTTP_Service_Handler.h"
#include "HTTP_States.h"
#include "HTTP_Data.h"
JAWS_HTTP_Service_Handler::JAWS_HTTP_Service_Handler (void)
: JAWS_Protocol_Handler (JAWS_HTTP_Read_Request::instance (), & this->data_)
, data_ (this)
{
}
int
JAWS_HTTP_Service_Handler::open (void *)
{
int result = JAWS_Concurrency::instance ()->putq (this);
if (result < 0)
return -1;
return 0;
}
int
JAWS_HTTP_Service_Handler::close (unsigned long)
{
delete this;
return 0;
}
int
JAWS_HTTP_Acceptor::init (int argc, ACE_TCHAR *argv[])
{
ACE_Get_Opt opt (argc, argv, ACE_TEXT("p:"));
unsigned short p = 0;
int c;
while ((c = opt ()) != -1)
switch (c)
{
case 'p':
p = (unsigned short) ACE_OS::atoi (opt.optarg);
break;
default:
break;
}
if (p == 0)
p = 8000;
if (this->open (ACE_INET_Addr (p)) == -1)
{
ACE_DEBUG ((LM_DEBUG, "%p\n", "ACE_Acceptor::open"));
return -1;
}
return 0;
}
ACE_SVC_FACTORY_DEFINE (JAWS_HTTP_Acceptor)
| binghuo365/BaseLab | 3rd/ACE-5.7.0/ACE_wrappers/apps/JAWS3/http/HTTP_Service_Handler.cpp | C++ | mit | 1,204 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ShapeType_1 = require("../Enums/ShapeType");
var Updater_1 = require("./Particle/Updater");
var Utils_1 = require("../Utils/Utils");
var PolygonMaskType_1 = require("../Enums/PolygonMaskType");
var RotateDirection_1 = require("../Enums/RotateDirection");
var ColorUtils_1 = require("../Utils/ColorUtils");
var Particles_1 = require("../Options/Classes/Particles/Particles");
var SizeAnimationStatus_1 = require("../Enums/SizeAnimationStatus");
var OpacityAnimationStatus_1 = require("../Enums/OpacityAnimationStatus");
var Shape_1 = require("../Options/Classes/Particles/Shape/Shape");
var StartValueType_1 = require("../Enums/StartValueType");
var CanvasUtils_1 = require("../Utils/CanvasUtils");
var Particle = (function () {
function Particle(container, position, overrideOptions) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
this.container = container;
this.fill = true;
this.close = true;
this.links = [];
this.lastNoiseTime = 0;
this.destroyed = false;
var options = container.options;
var particlesOptions = new Particles_1.Particles();
particlesOptions.load(options.particles);
if ((overrideOptions === null || overrideOptions === void 0 ? void 0 : overrideOptions.shape) !== undefined) {
var shapeType = (_a = overrideOptions.shape.type) !== null && _a !== void 0 ? _a : particlesOptions.shape.type;
this.shape = shapeType instanceof Array ? Utils_1.Utils.itemFromArray(shapeType) : shapeType;
var shapeOptions = new Shape_1.Shape();
shapeOptions.load(overrideOptions.shape);
if (this.shape !== undefined) {
var shapeData = shapeOptions.options[this.shape];
if (shapeData !== undefined) {
this.shapeData = Utils_1.Utils.deepExtend({}, shapeData instanceof Array ?
Utils_1.Utils.itemFromArray(shapeData) :
shapeData);
this.fill = (_c = (_b = this.shapeData) === null || _b === void 0 ? void 0 : _b.fill) !== null && _c !== void 0 ? _c : this.fill;
this.close = (_e = (_d = this.shapeData) === null || _d === void 0 ? void 0 : _d.close) !== null && _e !== void 0 ? _e : this.close;
}
}
}
else {
var shapeType = particlesOptions.shape.type;
this.shape = shapeType instanceof Array ? Utils_1.Utils.itemFromArray(shapeType) : shapeType;
var shapeData = particlesOptions.shape.options[this.shape];
if (shapeData) {
this.shapeData = Utils_1.Utils.deepExtend({}, shapeData instanceof Array ?
Utils_1.Utils.itemFromArray(shapeData) :
shapeData);
this.fill = (_g = (_f = this.shapeData) === null || _f === void 0 ? void 0 : _f.fill) !== null && _g !== void 0 ? _g : this.fill;
this.close = (_j = (_h = this.shapeData) === null || _h === void 0 ? void 0 : _h.close) !== null && _j !== void 0 ? _j : this.close;
}
}
if (overrideOptions !== undefined) {
particlesOptions.load(overrideOptions);
}
this.particlesOptions = particlesOptions;
var noiseDelay = this.particlesOptions.move.noise.delay;
this.noiseDelay = (noiseDelay.random.enable ?
Utils_1.Utils.randomInRange(noiseDelay.random.minimumValue, noiseDelay.value) :
noiseDelay.value) * 1000;
container.retina.initParticle(this);
var color = this.particlesOptions.color;
var sizeValue = ((_k = this.sizeValue) !== null && _k !== void 0 ? _k : container.retina.sizeValue);
var randomSize = typeof this.particlesOptions.size.random === "boolean" ?
this.particlesOptions.size.random :
this.particlesOptions.size.random.enable;
this.size = {
value: randomSize && this.randomMinimumSize !== undefined ?
Utils_1.Utils.randomInRange(this.randomMinimumSize, sizeValue) :
sizeValue,
};
this.direction = this.particlesOptions.move.direction;
this.bubble = {};
this.angle = this.particlesOptions.rotate.random ? Math.random() * 360 : this.particlesOptions.rotate.value;
if (this.particlesOptions.rotate.direction == RotateDirection_1.RotateDirection.random) {
var index = Math.floor(Math.random() * 2);
if (index > 0) {
this.rotateDirection = RotateDirection_1.RotateDirection.counterClockwise;
}
else {
this.rotateDirection = RotateDirection_1.RotateDirection.clockwise;
}
}
else {
this.rotateDirection = this.particlesOptions.rotate.direction;
}
if (this.particlesOptions.size.animation.enable) {
switch (this.particlesOptions.size.animation.startValue) {
case StartValueType_1.StartValueType.min:
if (!randomSize) {
var pxRatio = container.retina.pixelRatio;
this.size.value = this.particlesOptions.size.animation.minimumValue * pxRatio;
}
break;
}
this.size.status = SizeAnimationStatus_1.SizeAnimationStatus.increasing;
this.size.velocity = ((_l = this.sizeAnimationSpeed) !== null && _l !== void 0 ? _l : container.retina.sizeAnimationSpeed) / 100;
if (!this.particlesOptions.size.animation.sync) {
this.size.velocity = this.size.velocity * Math.random();
}
}
if (this.particlesOptions.rotate.animation.enable) {
if (!this.particlesOptions.rotate.animation.sync) {
this.angle = Math.random() * 360;
}
}
this.position = this.calcPosition(this.container, position);
if (options.polygon.enable && options.polygon.type === PolygonMaskType_1.PolygonMaskType.inline) {
this.initialPosition = {
x: this.position.x,
y: this.position.y,
};
}
this.offset = {
x: 0,
y: 0,
};
if (this.particlesOptions.collisions.enable) {
this.checkOverlap(position);
}
if (color instanceof Array) {
this.color = ColorUtils_1.ColorUtils.colorToRgb(Utils_1.Utils.itemFromArray(color));
}
else {
this.color = ColorUtils_1.ColorUtils.colorToRgb(color);
}
var randomOpacity = this.particlesOptions.opacity.random;
var opacityValue = this.particlesOptions.opacity.value;
this.opacity = {
value: randomOpacity.enable ? Utils_1.Utils.randomInRange(randomOpacity.minimumValue, opacityValue) : opacityValue,
};
if (this.particlesOptions.opacity.animation.enable) {
this.opacity.status = OpacityAnimationStatus_1.OpacityAnimationStatus.increasing;
this.opacity.velocity = this.particlesOptions.opacity.animation.speed / 100;
if (!this.particlesOptions.opacity.animation.sync) {
this.opacity.velocity *= Math.random();
}
}
this.initialVelocity = this.calculateVelocity();
this.velocity = {
horizontal: this.initialVelocity.horizontal,
vertical: this.initialVelocity.vertical,
};
var drawer = container.drawers[this.shape];
if (!drawer) {
drawer = CanvasUtils_1.CanvasUtils.getShapeDrawer(this.shape);
container.drawers[this.shape] = drawer;
}
if (this.shape === ShapeType_1.ShapeType.image || this.shape === ShapeType_1.ShapeType.images) {
var shape = this.particlesOptions.shape;
var imageDrawer = drawer;
var imagesOptions = shape.options[this.shape];
var images = imageDrawer.getImages(container).images;
var index = Utils_1.Utils.arrayRandomIndex(images);
var image_1 = images[index];
var optionsImage = (imagesOptions instanceof Array ?
imagesOptions.filter(function (t) { return t.src === image_1.source; })[0] :
imagesOptions);
this.image = {
data: image_1,
ratio: optionsImage.width / optionsImage.height,
replaceColor: (_m = optionsImage.replaceColor) !== null && _m !== void 0 ? _m : optionsImage.replace_color,
source: optionsImage.src,
};
if (!this.image.ratio) {
this.image.ratio = 1;
}
this.fill = (_o = optionsImage.fill) !== null && _o !== void 0 ? _o : this.fill;
this.close = (_p = optionsImage.close) !== null && _p !== void 0 ? _p : this.close;
}
this.stroke = this.particlesOptions.stroke instanceof Array ?
Utils_1.Utils.itemFromArray(this.particlesOptions.stroke) :
this.particlesOptions.stroke;
this.strokeColor = typeof this.stroke.color === "string" ?
ColorUtils_1.ColorUtils.stringToRgb(this.stroke.color) :
ColorUtils_1.ColorUtils.colorToRgb(this.stroke.color);
this.shadowColor = typeof this.particlesOptions.shadow.color === "string" ?
ColorUtils_1.ColorUtils.stringToRgb(this.particlesOptions.shadow.color) :
ColorUtils_1.ColorUtils.colorToRgb(this.particlesOptions.shadow.color);
this.updater = new Updater_1.Updater(this.container, this);
}
Particle.prototype.update = function (index, delta) {
this.links = [];
this.updater.update(delta);
};
Particle.prototype.draw = function (delta) {
this.container.canvas.drawParticle(this, delta);
};
Particle.prototype.isOverlapping = function () {
var container = this.container;
var p = this;
var collisionFound = false;
var iterations = 0;
for (var _i = 0, _a = container.particles.array.filter(function (t) { return t != p; }); _i < _a.length; _i++) {
var p2 = _a[_i];
iterations++;
var pos1 = {
x: p.position.x + p.offset.x,
y: p.position.y + p.offset.y
};
var pos2 = {
x: p2.position.x + p2.offset.x,
y: p2.position.y + p2.offset.y
};
var dist = Utils_1.Utils.getDistanceBetweenCoordinates(pos1, pos2);
if (dist <= p.size.value + p2.size.value) {
collisionFound = true;
break;
}
}
return {
collisionFound: collisionFound,
iterations: iterations,
};
};
Particle.prototype.checkOverlap = function (position) {
var container = this.container;
var p = this;
var overlapResult = p.isOverlapping();
if (overlapResult.iterations >= container.particles.count) {
container.particles.remove(this);
}
else if (overlapResult.collisionFound) {
p.position.x = position ? position.x : Math.random() * container.canvas.size.width;
p.position.y = position ? position.y : Math.random() * container.canvas.size.height;
p.checkOverlap();
}
};
Particle.prototype.startInfection = function (stage) {
var container = this.container;
var options = container.options;
var stages = options.infection.stages;
var stagesCount = stages.length;
if (stage > stagesCount || stage < 0) {
return;
}
this.infectionDelay = 0;
this.infectionDelayStage = stage;
};
Particle.prototype.updateInfectionStage = function (stage) {
var container = this.container;
var options = container.options;
var stagesCount = options.infection.stages.length;
if (stage > stagesCount || stage < 0 || (this.infectionStage !== undefined && this.infectionStage > stage)) {
return;
}
if (this.infectionTimeout !== undefined) {
window.clearTimeout(this.infectionTimeout);
}
this.infectionStage = stage;
this.infectionTime = 0;
};
Particle.prototype.updateInfection = function (delta) {
var container = this.container;
var options = container.options;
var infection = options.infection;
var stages = options.infection.stages;
var stagesCount = stages.length;
if (this.infectionDelay !== undefined && this.infectionDelayStage !== undefined) {
var stage = this.infectionDelayStage;
if (stage > stagesCount || stage < 0) {
return;
}
if (this.infectionDelay > infection.delay * 1000) {
this.infectionStage = stage;
this.infectionTime = 0;
delete this.infectionDelay;
delete this.infectionDelayStage;
}
else {
this.infectionDelay += delta;
}
}
else {
delete this.infectionDelay;
delete this.infectionDelayStage;
}
if (this.infectionStage !== undefined && this.infectionTime !== undefined) {
var infectionStage = stages[this.infectionStage];
if (infectionStage.duration !== undefined && infectionStage.duration >= 0) {
if (this.infectionTime > infectionStage.duration * 1000) {
this.nextInfectionStage();
}
else {
this.infectionTime += delta;
}
}
else {
this.infectionTime += delta;
}
}
else {
delete this.infectionStage;
delete this.infectionTime;
}
};
Particle.prototype.nextInfectionStage = function () {
var container = this.container;
var options = container.options;
var stagesCount = options.infection.stages.length;
if (stagesCount <= 0 || this.infectionStage === undefined) {
return;
}
this.infectionTime = 0;
if (stagesCount <= ++this.infectionStage) {
if (options.infection.cure) {
delete this.infectionStage;
delete this.infectionTime;
return;
}
else {
this.infectionStage = 0;
this.infectionTime = 0;
}
}
};
Particle.prototype.destroy = function () {
this.destroyed = true;
};
Particle.prototype.calcPosition = function (container, position) {
for (var _i = 0, _a = container.plugins; _i < _a.length; _i++) {
var plugin = _a[_i];
var pluginPos = plugin.particlePosition !== undefined ? plugin.particlePosition(position) : undefined;
if (pluginPos !== undefined) {
return pluginPos;
}
}
var pos = { x: 0, y: 0 };
pos.x = position ? position.x : Math.random() * container.canvas.size.width;
pos.y = position ? position.y : Math.random() * container.canvas.size.height;
if (pos.x > container.canvas.size.width - this.size.value * 2) {
pos.x -= this.size.value;
}
else if (pos.x < this.size.value * 2) {
pos.x += this.size.value;
}
if (pos.y > container.canvas.size.height - this.size.value * 2) {
pos.y -= this.size.value;
}
else if (pos.y < this.size.value * 2) {
pos.y += this.size.value;
}
return pos;
};
Particle.prototype.calculateVelocity = function () {
var baseVelocity = Utils_1.Utils.getParticleBaseVelocity(this);
var res = {
horizontal: 0,
vertical: 0,
};
if (this.particlesOptions.move.straight) {
res.horizontal = baseVelocity.x;
res.vertical = baseVelocity.y;
if (this.particlesOptions.move.random) {
res.horizontal *= Math.random();
res.vertical *= Math.random();
}
}
else {
res.horizontal = baseVelocity.x + Math.random() - 0.5;
res.vertical = baseVelocity.y + Math.random() - 0.5;
}
return res;
};
return Particle;
}());
exports.Particle = Particle;
| cdnjs/cdnjs | ajax/libs/tsparticles/1.14.0-alpha.6/Core/Particle.js | JavaScript | mit | 16,661 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using MonoGame.Extended;
using MonoGame.Extended.Maps.Tiled;
namespace tb.GameClasses.Zones
{
abstract class Zone
{
public TiledMap map;
public abstract void LoadContent(ContentManager content);
public abstract void DrawBackground(SpriteBatch spriteBatch,Camera2D camera);
public abstract void DrawForeground(SpriteBatch spriteBatch,Camera2D camera);
public abstract void DrawTop(SpriteBatch spriteBatch,Camera2D camera);
public abstract void DrawEntities(SpriteBatch spriteBatch, Camera2D camera);
public abstract void UpdateEntityCollision(Player player, tb.Managers.GameManager manager, ContentManager content);
public abstract TiledTileLayer GetCollisionLayer();
public abstract Point GetSpawnPosition();
public abstract void SetSpawnPosition(Point pos);
public abstract TiledMap GetMap();
public Point SpawnPosition;
}
}
| Mr-Bones738/AllMyStuff | TurnBasedThing/tb/GameClasses/Zones/Zone.cs | C# | mit | 1,171 |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit6f62dc029fedfa7dbe26bed1593c624e::getLoader();
| nicerway/tongyong | vendor/autoload.php | PHP | mit | 178 |
def login_as(player)
puts "login as"
session[:player_id] = player.id
if @current_game
GameService.add_player(@current_game, player, false, true)
cookies[:current_game_id] = @current_game.id
end
end
| j-arp/tectonic | spec/support/helpers/session.rb | Ruby | mit | 215 |
<?php
namespace Pagedynamo\AdminBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\EntityRepository;
class SiteLanguageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'text', array('required' => true, 'label' => 'Name'));
$builder->add('urlCode', 'text', array('required' => false, 'label' => 'URL-Segment'));
$builder->add('isdefaultlang', 'checkbox', array('required' => false, 'label' => 'Standardsprache'));
$builder->add('flag', 'pd_image', array('required' => false, 'label' => 'Flagge'));
$builder->add('createdBy', 'text', array('disabled' => true, 'label' => 'Erstellt von'));
$builder->add('createdAt', 'datetime', array('disabled' => true, 'label' => 'Erstellt am', 'date_widget' => 'single_text', 'time_widget' => 'single_text'));
$builder->add('updatedBy', 'text', array('disabled' => true, 'label' => 'Bearbeitet von'));
$builder->add('updatedAt', 'datetime', array('disabled' => true, 'label' => 'Bearbeitet am', 'date_widget' => 'single_text', 'time_widget' => 'single_text'));
}
public function getName()
{
return 'sitelanguage';
}
} | pagedynamo-cms/PagedynamoAdminBundle | Form/Type/SiteLanguageType.php | PHP | mit | 1,303 |
module ObsFactory
# View decorator for a Project
class ObsProjectPresenter < BasePresenter
def build_and_failed_params
params = { project: self.name, defaults: 0 }
Buildresult.avail_status_values.each do |s|
next if %w(succeeded excluded disabled).include? s.to_s
params[s] = 1
end
self.repos.each do |r|
next if exclusive_repository && r != exclusive_repository
params["repo_#{r}"] = 1
end
# hard code the archs we care for
params['arch_i586'] = 1
params['arch_x86_64'] = 1
params['arch_local'] = 1
params
end
def summary
return @summary if @summary
building = false
failed = 0
final = 0
total = 0
# first calculate the building state - and filter the results
results = []
build_summary.elements('result') do |result|
next if exclusive_repository && result['repository'] != exclusive_repository
if !%w(published unpublished unknown).include?(result['state']) || result['dirty'] == 'true'
building = true
end
results << result
end
results.each do |result|
result['summary'].elements('statuscount') do |sc|
code = sc['code']
count = sc['count'].to_i
next if code == 'excluded' # plain ignore
total += count
if code == 'unresolvable'
unless building # only count if finished
failed += count
end
next
end
if %w(broken failed).include?(code)
failed += count
elsif %w(succeeded disabled).include?(code)
final += count
end
end
end
if failed > 0
failed = build_failures_count
end
if building
build_progress = (100 * (final + failed)) / total
build_progress = [99, build_progress].min
if failed > 0
@summary = [:building, "#{self.nickname}: #{build_progress}% (#{failed} errors)"]
else
@summary = [:building, "#{self.nickname}: #{build_progress}%"]
end
elsif failed > 0
# don't duplicate packages in archs, so redo
@summary = [:failed, "#{self.nickname}: #{failed} errors"]
else
@summary = [:succeeded, "#{self.nickname}: DONE"]
end
end
end
end
| ancorgs/obs_factory | app/presenters/obs_factory/obs_project_presenter.rb | Ruby | mit | 2,374 |
'use strict';
require('angular/angular');
angular.module('<%= name %>Module', [])
.directive('<%= name %>', [
function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'src/<%= name %>/<%= name %>.tpl.html',
scope: {},
link: function(scope, element, attrs) {
scope.directiveTitle = 'dummy';
}
};
}
]);
| hung-phan/generator-angular-with-browserify | directive/templates/directive-template.js | JavaScript | mit | 475 |
import Ember from 'ember';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
import InfinityRoute from "../../../../mixins/infinity-route";
export default Ember.Route.extend(InfinityRoute, AuthenticatedRouteMixin, {
_listName: 'model',
model: function() {
return this.infinityModel("report", { perPage: 10, startingPage: 1});
},
actions: {
remove: function(model) {
if(confirm('Are you sure?')) {
model.destroyRecord();
}
},
search: function () {
this.set('_listName', 'model.content');
var filter = { perPage: 10, startingPage: 1};
this.get('controller').set('model', this.infinityModel("report", filter))
}
}
});
| Goblab/observatorio-electoral | front/app/routes/data-entry/elections/reports/index.js | JavaScript | mit | 729 |
/**
* @file theme loader
*
* @desc 向每个.vue文件中注入样式相关的变量,不需要手动import
* @author echaoo(1299529160@qq.com)
*/
/* eslint-disable fecs-no-require, fecs-prefer-destructure */
'use strict';
const theme = require('../../config/theme');
const loaderUtils = require('loader-utils');
const STYLE_TAG_REG = /(\<style.*?lang="styl(?:us)?".*?\>)([\S\s]*?)(\<\/style\>)/g;
// 定义在vuetify中默认的两组stylus hash:主题色和material相关
let defaultVuetifyVariables = {
themeColor: {
primary: '$blue.darken-2',
accent: '$blue.accent-2',
secondary: '$grey.darken-3',
info: '$blue.base',
warning: '$amber.base',
error: '$red.accent-2',
success: '$green.base'
},
materialDesign: {
'bg-color': '#fff',
'fg-color': '#000',
'text-color': '#000',
'primary-text-percent': .87,
'secondary-text-percent': .54,
'disabledORhints-text-percent': .38,
'divider-percent': .12,
'active-icon-percent': .54,
'inactive-icon-percent': .38
}
};
// 使用用户定义在config/theme.js中的变量覆盖默认值
let themeColor = Object.assign(
{},
defaultVuetifyVariables.themeColor,
theme.theme.themeColor
);
// 最终输出的stylus hash(themeColor部分)
let themeColorTemplate = `
$theme := {
primary: ${themeColor.primary}
accent: ${themeColor.accent}
secondary: ${themeColor.secondary}
info: ${themeColor.info}
warning: ${themeColor.warning}
error: ${themeColor.error}
success: ${themeColor.success}
}
`;
let materialDesign = Object.assign(
{},
defaultVuetifyVariables.materialDesign,
theme.theme.materialDesign
);
let materialDesignTemplate = `
$material-custom := {
bg-color: ${materialDesign['bg-color']}
fg-color: ${materialDesign['fg-color']}
text-color: ${materialDesign['text-color']}
primary-text-percent: ${materialDesign['primary-text-percent']}
secondary-text-percent: ${materialDesign['secondary-text-percent']}
disabledORhints-text-percent: ${materialDesign['disabledORhints-text-percent']}
divider-percent: ${materialDesign['divider-percent']}
active-icon-percent: ${materialDesign['active-icon-percent']}
inactive-icon-percent: ${materialDesign['inactive-icon-percent']}
}
$material-theme := $material-custom
`;
// 引入项目变量和vuetify中使用的颜色变量
let importVariablesTemplate = `
@import '~@/assets/styles/variables';
@import '~vuetify/src/stylus/settings/_colors';
`;
let injectedTemplate = importVariablesTemplate
+ themeColorTemplate + materialDesignTemplate;
module.exports = function (source) {
this.cacheable();
let options = loaderUtils.getOptions(this);
if (options && options.injectInVueFile) {
// 向每一个.vue文件的<style>块中注入
return source.replace(STYLE_TAG_REG, `$1${injectedTemplate}$2$3`);
}
return injectedTemplate + source;
};
| echaoo/doubanMovie_PWA | build/loaders/theme-loader.js | JavaScript | mit | 3,098 |
/*
* Kendo UI v2014.2.1008 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["ms-BN"] = {
name: "ms-BN",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["($n)","$n"],
decimals: 0,
",": ".",
".": ",",
groupSize: [3],
symbol: "$"
}
},
calendars: {
standard: {
days: {
names: ["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"],
namesAbbr: ["Ahad","Isnin","Sel","Rabu","Khamis","Jumaat","Sabtu"],
namesShort: ["A","I","S","R","K","J","S"]
},
months: {
names: ["Januari","Februari","Mac","April","Mei","Jun","Julai","Ogos","September","Oktober","November","Disember",""],
namesAbbr: ["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ogos","Sept","Okt","Nov","Dis",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy H:mm:ss",
g: "dd/MM/yyyy H:mm",
G: "dd/MM/yyyy H:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | shriramdevanathan/FactoryOfTheFuture | vendor/kendoui-2014.2.1008/src/js/cultures/kendo.culture.ms-BN.js | JavaScript | mit | 2,615 |
class UnsetSchedulingInfrastructureMonitoringService
def initialize(infrastructure_id, user_id)
@infrastructure_id = infrastructure_id.to_s
@user_id = user_id.to_s
end
def run
return if @user_id.blank?
Scalarm::MongoLock.mutex("user-#{@user_id}-monitoring") do
Rails.logger.info("Unsetting infrastructure monitoring - #{@infrastructure_id} - #{@user_id}")
user = ScalarmUser.where(id: @user_id).first
user.unset_monitoring_schedule(@infrastructure_id)
user.save
end
end
end
| Scalarm/scalarm_experiment_manager | app/services/unset_scheduling_infrastructure_monitoring_service.rb | Ruby | mit | 530 |
<?php
/*
Safe sample
input : execute a ls command using the function system, and put the last result in $tainted
sanitize : settype (float)
construction : use of sprintf via a %u with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = system('ls', $retval);
if(settype($tainted, "float"))
$tainted = $tainted ;
else
$tainted = 0.0 ;
$query = sprintf("SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name, a.city, a.street & (' ' +a.housenum) AS address FROM Employees AS a WHERE a.supervisor='%u'", $tainted);
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_89/safe/CWE_89__system__CAST-func_settype_float__multiple_AS-sprintf_%u_simple_quote.php | PHP | mit | 1,754 |
"use strict";
var m = require("mithril"),
assign = require("lodash.assign"),
id = require("./lib/id"),
hide = require("./lib/hide"),
label = require("./lib/label"),
css = require("./textarea.css");
module.exports = {
controller : function(options) {
var ctrl = this;
ctrl.id = id(options);
ctrl.text = options.data || "";
ctrl.resize = function(opt, value) {
opt.update(opt.path, value);
ctrl.text = value;
};
},
view : function(ctrl, options) {
var field = options.field,
hidden = hide(options);
if(hidden) {
return hidden;
}
return m("div", { class : options.class },
label(ctrl, options),
m("div", { class : css.expander },
m("pre", { class : css.shadow }, m("span", ctrl.text), m("br")),
m("textarea", assign({
// attrs
id : ctrl.id,
class : css.textarea,
required : field.required ? "required" : null,
// events
oninput : m.withAttr("value", ctrl.resize.bind(null, options))
},
field.attrs || {}
), options.data || "")
)
);
}
};
| Ryan-McMillan/crucible | src/types/textarea.js | JavaScript | mit | 1,402 |
<?php
/*
Safe sample
input : get the UserData field of $_SESSION
sanitize : cast into int
construction : interpretation
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = $_SESSION['UserData'];
$tainted = (int) $tainted ;
$query = "//User[@id= $tainted ]";
$xml = simplexml_load_file("users.xml");//file load
echo "query : ". $query ."<br /><br />" ;
$res=$xml->xpath($query);//execution
print_r($res);
echo "<br />" ;
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_91/safe/CWE_91__SESSION__CAST-cast_int__ID_test-interpretation.php | PHP | mit | 1,301 |
import seaborn as sns
import matplotlib.pyplot as plt
def plot_corrmatrix(df, square=True, linewidths=0.1, annot=True,
size=None, figsize=(12, 9), *args, **kwargs):
"""
Plot correlation matrix of the dataset
see doc at https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html#seaborn.heatmap
"""
sns.set(context="paper", font="monospace")
f, ax = plt.subplots(figsize=figsize)
sns.heatmap(df.corr(), vmax=1, square=square, linewidths=linewidths,
annot=annot, annot_kws={"size": size}, *args, **kwargs)
| ericfourrier/auto-clean | autoc/utils/corrplot.py | Python | mit | 590 |
package com.yiibaiMVC;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
} | n5xm/testspring | src/com/yiibaiMVC/Student.java | Java | mit | 447 |
(function() {
"use strict";
angular
.module('app.users', [
'app.core'
]);
})(); | belicka/tia-rezervacny-system | client/app/users/users.module.js | JavaScript | mit | 117 |
<?php
namespace FSB\ASTT\CoreBundle\Repository;
use Doctrine\ORM\EntityRepository;
class TeamRepository extends EntityRepository
{
public function findAllDisplayedSorteredByDates()
{
$qb = $this->_em->createQueryBuilder();
$qb->select('t')
->from('FSB\ASTT\CoreBundle\Entity\Team', 't')
->where('t.deleted = :deleted')
->setParameter('deleted', false)
->orderBy('t.createdAt', 'DESC')
;
return $qb->getQuery()->getResult();
}
public function findAllDisplayedByCivility($civility, $queryBuilderOnly = false)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('t')
->from('FSB\ASTT\CoreBundle\Entity\Team', 't')
->where('t.deleted = :deleted')
->andWhere('t.civility = :civility')
->setParameter('deleted', false)
->setParameter('civility', $civility)
->orderBy('t.civility', 'DESC')
->addOrderBy('t.number', 'ASC');
;
if ($queryBuilderOnly) {
return $qb;
} else {
return $qb->getQuery()->getResult();
}
}
public function findAllDisplayed($queryBuilderOnly = false)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('t')
->from('FSB\ASTT\CoreBundle\Entity\Team', 't')
->where('t.deleted = :deleted')
->setParameter('deleted', false)
->orderBy('t.civility', 'DESC')
->addOrderBy('t.number', 'ASC')
;
if ($queryBuilderOnly) {
return $qb;
} else {
return $qb->getQuery()->getResult();
}
}
public function find($id)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('t')
->from('FSB\ASTT\CoreBundle\Entity\Team', 't')
->where('t.deleted = :deleted')
->andWhere('t.id = :id')
->setParameter('deleted', false)
->setParameter('id', $id)
;
try {
$result = $qb->getQuery()->getSingleResult();
}
catch (\Doctrine\Orm\NoResultException $NRE) {
$result = NULL;
}
return $result;
}
public function findOneById($id)
{
return $this->find($id);
}
public function findAll()
{
$qb = $this->_em->createQueryBuilder();
$qb->select('t')
->from('FSB\ASTT\CoreBundle\Entity\Team', 't')
->where('t.deleted = :deleted')
->setParameter('deleted', false)
;
return $qb->getQuery()->getResult();
}
} | Flo-Schield-Bobby/Amiens-Sport-Tennis-de-Table | src/FSB/ASTT/CoreBundle/Repository/TeamRepository.php | PHP | mit | 2,749 |
FactoryBot.define do
factory :source_repository do
url "MyString"
end
end
| diraulo/WebsiteOne | spec/factories/source_repositories.rb | Ruby | mit | 83 |
<?php
/**
* The template for displaying paged pages.
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage <%= NombreTema %>
* @since <%= VersionTema %>
*/
| xDae/generator-wptheme | app/templates/Base-Hierarchy/_paged.php | PHP | mit | 210 |
package protocols.NEC;
import protocols.ProtocolSpecification;
import protocols.frame.FrameBitImpl;
/**
* Created by piotrek on 06.02.17.
*/
public class NECProtocolSpecScaled extends ProtocolSpecification {
private static final ProtocolSpecification metric =
NecProtocolSpecification.getInstance();
public NECProtocolSpecScaled(int scale) {
super(
metric.getStateShortTime()/scale,
metric.getStateLongTime()/scale,
metric.getCommandLen(),
metric.getAddressLen(),
metric.getPrefixPauseTime()/scale,
metric.getSufixPauseTime()/scale,
FrameBitImpl.vectorScalarDiv(metric.getPreamble(), scale),
FrameBitImpl.vectorScalarDiv(metric.getPostamble(),scale),
metric.getProtocolType()
);
}
}
| pworkshop/Peesdrq | tools/src/protocols/NEC/NECProtocolSpecScaled.java | Java | mit | 838 |
package main
import (
"fmt"
"time"
"net/http"
"encoding/json"
"io/ioutil"
"github.com/gorilla/mux"
)
type Play struct {
Key string `json:"key" redis:"-"`
SeasonKey string `json:"season_key" redis:"season_key"`
QueenKey string `json:"queen_key" redis:"queen_key"`
PlayTypeKey string `json:"play_type_key" redis:"play_type_key"`
EpisodeKey string `json:"episode_key" redis:"episode_key"`
Timestamp int64 `json:"timestamp" redis:"timestamp"`
}
func PostPlay(w http.ResponseWriter, r *http.Request) {
fmt.Println("PostPlay")
var new_play Play
b, _ := ioutil.ReadAll(r.Body)
fmt.Println(string(b))
json.Unmarshal(b, &new_play)
season_key := mux.Vars(r)["season_id"]
new_play.SeasonKey = season_key
new_play.Timestamp = time.Now().Unix()
_, success := AddObject("play", new_play)
if success {
fmt.Fprintf(w, "201 Created")
} else {
// TODO set the response code correct
fmt.Fprintf(w, "ERR")
}
}
func DeletePlay(w http.ResponseWriter, r *http.Request) {
season_key := mux.Vars(r)["season_id"]
play_key := mux.Vars(r)["play_key"]
fmt.Println("DELTE play: ", play_key)
var del_play Play
del_play.Key = play_key
success := GetObject(play_key, &del_play)
fmt.Println("GOT QUEEN: ", del_play)
if (season_key != del_play.SeasonKey) {
fmt.Println("Hey, you are trying todelerte a play that doesn't belong here.")
success = false
}
if (success) {
success = DeleteObject("play", play_key, del_play)
}
if (success) {
fmt.Fprintf(w, "200 OK (deleted)")
} else {
fmt.Fprintf(w, "KEY DOES NOT EXIST")
}
}
| macrael/racetrack | play.go | GO | mit | 1,787 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EdmundsApi.Requests
{
public enum State
{
New,
Used,
Future,
}
public enum View
{
Basic,
Full,
}
public enum Category
{
Hatchback4Dr,
Coupe,
Convertible,
Sedan,
Hatchback2Dr,
Wagon,
RegularCabPickup,
ExtendedCabPickup,
CrewCabPickup,
Suv2Dr,
Suv4Dr,
SuvConvertible,
CargoVan,
PassengerVan,
CargoMinivan,
PassengerMinivan
}
}
| ghotiphud/EdmundsApi | EdmundsApi/Requests/Enums.cs | C# | mit | 662 |
var Plugin = require('./baseplugin'),
request = require('request-promise');
class Spotify extends Plugin {
init() {
this.httpRegex = /(?:https?:\/\/)?open\.spotify\.com\/(album|track|user\/[^\/]+\/playlist)\/([a-zA-Z0-9]+)/;
this.uriRegex = /^spotify:(album|track|user:[^:]+:playlist):([a-zA-Z0-9]+)$/;
}
canHandle(url) {
return this.httpRegex.test(url) || this.uriRegex.test(url);
}
run(url) {
var options = {
url: `https://embed.spotify.com/oembed/?url=${url}`,
headers: {'User-Agent': 'request'}
};
return request.get(options)
.then(body => JSON.parse(body).html)
.then(html => ({ type: 'spotify', html: html }));
}
}
module.exports = Spotify;
| d3estudio/d3-digest | src/prefetch/plugins/spotify.js | JavaScript | mit | 776 |
public interface Command {
void execute();
void undo();
}
| jellyice/Design-Patterns | Assets/Scripts/Command/Command.cs | C# | mit | 63 |
<?php
global $_MODULE;
$_MODULE = array();
$_MODULE['<{easycss}cars>easycss_15ea502c0c3df59ddd33334ae6a9420b'] = 'Fácil css';
$_MODULE['<{easycss}cars>easycss_d7c8c85bf79bbe1b7188497c32c3b0ca'] = 'Falha';
$_MODULE['<{easycss}cars>easycss_248336101b461380a4b2391a7625493d'] = 'Salvo';
$_MODULE['<{easycss}cars>easycss_12e1ce6966d38525bc96c0f558ee6df3'] = 'Por favor, escolha uma imagem válida';
$_MODULE['<{easycss}cars>easycss_729a51874fe901b092899e9e8b31c97a'] = 'Tem a certeza?';
$_MODULE['<{easycss}cars>easycss_e8081116db6145064c613944d82690e7'] = 'Por favor, preencha o campo do seletor';
$_MODULE['<{easycss}cars>easycss_41d3bba0af74d2624f6b309888a0309a'] = 'Nenhuma imagem para salvar';
$_MODULE['<{easycss}cars>easycss_1bc564651413b9c31c46314a88d1d6d3'] = 'Erro: a imagem não foi copiado';
$_MODULE['<{easycss}cars>configure_0c3cd33e7bf626da4897316a7158a7a4'] = 'Seletor de';
$_MODULE['<{easycss}cars>configure_be53a0541a6d36f6ecb879fa2c584b08'] = 'Imagem';
$_MODULE['<{easycss}cars>configure_03c2e7e41ffc181a4e84080b4710e81e'] = 'Novo';
| amicavi/grupo-ochoa | prestashop/themes/cars/modules/easycss/translations/pt.php | PHP | mit | 1,050 |
<?php
/**
* Generated by Protobuf protoc plugin.
*
* File descriptor : POGOProtos/Inventory/InventoryItemData.proto
*/
namespace POGOProtos\Inventory;
/**
* Protobuf message : POGOProtos.Inventory.InventoryItemData
*/
class InventoryItemData extends \Protobuf\AbstractMessage
{
/**
* @var \Protobuf\UnknownFieldSet
*/
protected $unknownFieldSet = null;
/**
* @var \Protobuf\Extension\ExtensionFieldMap
*/
protected $extensions = null;
/**
* pokemon_data optional message = 1
*
* @var \POGOProtos\Data\PokemonData
*/
protected $pokemon_data = null;
/**
* item optional message = 2
*
* @var \POGOProtos\Inventory\Item\ItemData
*/
protected $item = null;
/**
* pokedex_entry optional message = 3
*
* @var \POGOProtos\Data\PokedexEntry
*/
protected $pokedex_entry = null;
/**
* player_stats optional message = 4
*
* @var \POGOProtos\Data\Player\PlayerStats
*/
protected $player_stats = null;
/**
* player_currency optional message = 5
*
* @var \POGOProtos\Data\Player\PlayerCurrency
*/
protected $player_currency = null;
/**
* player_camera optional message = 6
*
* @var \POGOProtos\Data\Player\PlayerCamera
*/
protected $player_camera = null;
/**
* inventory_upgrades optional message = 7
*
* @var \POGOProtos\Inventory\InventoryUpgrades
*/
protected $inventory_upgrades = null;
/**
* applied_items optional message = 8
*
* @var \POGOProtos\Inventory\AppliedItems
*/
protected $applied_items = null;
/**
* egg_incubators optional message = 9
*
* @var \POGOProtos\Inventory\EggIncubators
*/
protected $egg_incubators = null;
/**
* candy optional message = 10
*
* @var \POGOProtos\Inventory\Candy
*/
protected $candy = null;
/**
* quest optional message = 11
*
* @var \POGOProtos\Data\Quests\Quest
*/
protected $quest = null;
/**
* avatar_item optional message = 12
*
* @var \POGOProtos\Data\Avatar\AvatarItem
*/
protected $avatar_item = null;
/**
* raid_tickets optional message = 13
*
* @var \POGOProtos\Inventory\RaidTickets
*/
protected $raid_tickets = null;
/**
* Check if 'pokemon_data' has a value
*
* @return bool
*/
public function hasPokemonData()
{
return $this->pokemon_data !== null;
}
/**
* Get 'pokemon_data' value
*
* @return \POGOProtos\Data\PokemonData
*/
public function getPokemonData()
{
return $this->pokemon_data;
}
/**
* Set 'pokemon_data' value
*
* @param \POGOProtos\Data\PokemonData $value
*/
public function setPokemonData(\POGOProtos\Data\PokemonData $value = null)
{
$this->pokemon_data = $value;
}
/**
* Check if 'item' has a value
*
* @return bool
*/
public function hasItem()
{
return $this->item !== null;
}
/**
* Get 'item' value
*
* @return \POGOProtos\Inventory\Item\ItemData
*/
public function getItem()
{
return $this->item;
}
/**
* Set 'item' value
*
* @param \POGOProtos\Inventory\Item\ItemData $value
*/
public function setItem(\POGOProtos\Inventory\Item\ItemData $value = null)
{
$this->item = $value;
}
/**
* Check if 'pokedex_entry' has a value
*
* @return bool
*/
public function hasPokedexEntry()
{
return $this->pokedex_entry !== null;
}
/**
* Get 'pokedex_entry' value
*
* @return \POGOProtos\Data\PokedexEntry
*/
public function getPokedexEntry()
{
return $this->pokedex_entry;
}
/**
* Set 'pokedex_entry' value
*
* @param \POGOProtos\Data\PokedexEntry $value
*/
public function setPokedexEntry(\POGOProtos\Data\PokedexEntry $value = null)
{
$this->pokedex_entry = $value;
}
/**
* Check if 'player_stats' has a value
*
* @return bool
*/
public function hasPlayerStats()
{
return $this->player_stats !== null;
}
/**
* Get 'player_stats' value
*
* @return \POGOProtos\Data\Player\PlayerStats
*/
public function getPlayerStats()
{
return $this->player_stats;
}
/**
* Set 'player_stats' value
*
* @param \POGOProtos\Data\Player\PlayerStats $value
*/
public function setPlayerStats(\POGOProtos\Data\Player\PlayerStats $value = null)
{
$this->player_stats = $value;
}
/**
* Check if 'player_currency' has a value
*
* @return bool
*/
public function hasPlayerCurrency()
{
return $this->player_currency !== null;
}
/**
* Get 'player_currency' value
*
* @return \POGOProtos\Data\Player\PlayerCurrency
*/
public function getPlayerCurrency()
{
return $this->player_currency;
}
/**
* Set 'player_currency' value
*
* @param \POGOProtos\Data\Player\PlayerCurrency $value
*/
public function setPlayerCurrency(\POGOProtos\Data\Player\PlayerCurrency $value = null)
{
$this->player_currency = $value;
}
/**
* Check if 'player_camera' has a value
*
* @return bool
*/
public function hasPlayerCamera()
{
return $this->player_camera !== null;
}
/**
* Get 'player_camera' value
*
* @return \POGOProtos\Data\Player\PlayerCamera
*/
public function getPlayerCamera()
{
return $this->player_camera;
}
/**
* Set 'player_camera' value
*
* @param \POGOProtos\Data\Player\PlayerCamera $value
*/
public function setPlayerCamera(\POGOProtos\Data\Player\PlayerCamera $value = null)
{
$this->player_camera = $value;
}
/**
* Check if 'inventory_upgrades' has a value
*
* @return bool
*/
public function hasInventoryUpgrades()
{
return $this->inventory_upgrades !== null;
}
/**
* Get 'inventory_upgrades' value
*
* @return \POGOProtos\Inventory\InventoryUpgrades
*/
public function getInventoryUpgrades()
{
return $this->inventory_upgrades;
}
/**
* Set 'inventory_upgrades' value
*
* @param \POGOProtos\Inventory\InventoryUpgrades $value
*/
public function setInventoryUpgrades(\POGOProtos\Inventory\InventoryUpgrades $value = null)
{
$this->inventory_upgrades = $value;
}
/**
* Check if 'applied_items' has a value
*
* @return bool
*/
public function hasAppliedItems()
{
return $this->applied_items !== null;
}
/**
* Get 'applied_items' value
*
* @return \POGOProtos\Inventory\AppliedItems
*/
public function getAppliedItems()
{
return $this->applied_items;
}
/**
* Set 'applied_items' value
*
* @param \POGOProtos\Inventory\AppliedItems $value
*/
public function setAppliedItems(\POGOProtos\Inventory\AppliedItems $value = null)
{
$this->applied_items = $value;
}
/**
* Check if 'egg_incubators' has a value
*
* @return bool
*/
public function hasEggIncubators()
{
return $this->egg_incubators !== null;
}
/**
* Get 'egg_incubators' value
*
* @return \POGOProtos\Inventory\EggIncubators
*/
public function getEggIncubators()
{
return $this->egg_incubators;
}
/**
* Set 'egg_incubators' value
*
* @param \POGOProtos\Inventory\EggIncubators $value
*/
public function setEggIncubators(\POGOProtos\Inventory\EggIncubators $value = null)
{
$this->egg_incubators = $value;
}
/**
* Check if 'candy' has a value
*
* @return bool
*/
public function hasCandy()
{
return $this->candy !== null;
}
/**
* Get 'candy' value
*
* @return \POGOProtos\Inventory\Candy
*/
public function getCandy()
{
return $this->candy;
}
/**
* Set 'candy' value
*
* @param \POGOProtos\Inventory\Candy $value
*/
public function setCandy(\POGOProtos\Inventory\Candy $value = null)
{
$this->candy = $value;
}
/**
* Check if 'quest' has a value
*
* @return bool
*/
public function hasQuest()
{
return $this->quest !== null;
}
/**
* Get 'quest' value
*
* @return \POGOProtos\Data\Quests\Quest
*/
public function getQuest()
{
return $this->quest;
}
/**
* Set 'quest' value
*
* @param \POGOProtos\Data\Quests\Quest $value
*/
public function setQuest(\POGOProtos\Data\Quests\Quest $value = null)
{
$this->quest = $value;
}
/**
* Check if 'avatar_item' has a value
*
* @return bool
*/
public function hasAvatarItem()
{
return $this->avatar_item !== null;
}
/**
* Get 'avatar_item' value
*
* @return \POGOProtos\Data\Avatar\AvatarItem
*/
public function getAvatarItem()
{
return $this->avatar_item;
}
/**
* Set 'avatar_item' value
*
* @param \POGOProtos\Data\Avatar\AvatarItem $value
*/
public function setAvatarItem(\POGOProtos\Data\Avatar\AvatarItem $value = null)
{
$this->avatar_item = $value;
}
/**
* Check if 'raid_tickets' has a value
*
* @return bool
*/
public function hasRaidTickets()
{
return $this->raid_tickets !== null;
}
/**
* Get 'raid_tickets' value
*
* @return \POGOProtos\Inventory\RaidTickets
*/
public function getRaidTickets()
{
return $this->raid_tickets;
}
/**
* Set 'raid_tickets' value
*
* @param \POGOProtos\Inventory\RaidTickets $value
*/
public function setRaidTickets(\POGOProtos\Inventory\RaidTickets $value = null)
{
$this->raid_tickets = $value;
}
/**
* {@inheritdoc}
*/
public function extensions()
{
if ( $this->extensions !== null) {
return $this->extensions;
}
return $this->extensions = new \Protobuf\Extension\ExtensionFieldMap(__CLASS__);
}
/**
* {@inheritdoc}
*/
public function unknownFieldSet()
{
return $this->unknownFieldSet;
}
/**
* {@inheritdoc}
*/
public static function fromStream($stream, \Protobuf\Configuration $configuration = null)
{
return new self($stream, $configuration);
}
/**
* {@inheritdoc}
*/
public static function fromArray(array $values)
{
$message = new self();
$values = array_merge([
'pokemon_data' => null,
'item' => null,
'pokedex_entry' => null,
'player_stats' => null,
'player_currency' => null,
'player_camera' => null,
'inventory_upgrades' => null,
'applied_items' => null,
'egg_incubators' => null,
'candy' => null,
'quest' => null,
'avatar_item' => null,
'raid_tickets' => null
], $values);
$message->setPokemonData($values['pokemon_data']);
$message->setItem($values['item']);
$message->setPokedexEntry($values['pokedex_entry']);
$message->setPlayerStats($values['player_stats']);
$message->setPlayerCurrency($values['player_currency']);
$message->setPlayerCamera($values['player_camera']);
$message->setInventoryUpgrades($values['inventory_upgrades']);
$message->setAppliedItems($values['applied_items']);
$message->setEggIncubators($values['egg_incubators']);
$message->setCandy($values['candy']);
$message->setQuest($values['quest']);
$message->setAvatarItem($values['avatar_item']);
$message->setRaidTickets($values['raid_tickets']);
return $message;
}
/**
* {@inheritdoc}
*/
public static function descriptor()
{
return \google\protobuf\DescriptorProto::fromArray([
'name' => 'InventoryItemData',
'field' => [
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 1,
'name' => 'pokemon_data',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Data.PokemonData'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 2,
'name' => 'item',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Inventory.Item.ItemData'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 3,
'name' => 'pokedex_entry',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Data.PokedexEntry'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 4,
'name' => 'player_stats',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Data.Player.PlayerStats'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 5,
'name' => 'player_currency',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Data.Player.PlayerCurrency'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 6,
'name' => 'player_camera',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Data.Player.PlayerCamera'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 7,
'name' => 'inventory_upgrades',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Inventory.InventoryUpgrades'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 8,
'name' => 'applied_items',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Inventory.AppliedItems'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 9,
'name' => 'egg_incubators',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Inventory.EggIncubators'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 10,
'name' => 'candy',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Inventory.Candy'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 11,
'name' => 'quest',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Data.Quests.Quest'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 12,
'name' => 'avatar_item',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Data.Avatar.AvatarItem'
]),
\google\protobuf\FieldDescriptorProto::fromArray([
'number' => 13,
'name' => 'raid_tickets',
'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
'type_name' => '.POGOProtos.Inventory.RaidTickets'
]),
],
]);
}
/**
* {@inheritdoc}
*/
public function toStream(\Protobuf\Configuration $configuration = null)
{
$config = $configuration ?: \Protobuf\Configuration::getInstance();
$context = $config->createWriteContext();
$stream = $context->getStream();
$this->writeTo($context);
$stream->seek(0);
return $stream;
}
/**
* {@inheritdoc}
*/
public function writeTo(\Protobuf\WriteContext $context)
{
$stream = $context->getStream();
$writer = $context->getWriter();
$sizeContext = $context->getComputeSizeContext();
if ($this->pokemon_data !== null) {
$writer->writeVarint($stream, 10);
$writer->writeVarint($stream, $this->pokemon_data->serializedSize($sizeContext));
$this->pokemon_data->writeTo($context);
}
if ($this->item !== null) {
$writer->writeVarint($stream, 18);
$writer->writeVarint($stream, $this->item->serializedSize($sizeContext));
$this->item->writeTo($context);
}
if ($this->pokedex_entry !== null) {
$writer->writeVarint($stream, 26);
$writer->writeVarint($stream, $this->pokedex_entry->serializedSize($sizeContext));
$this->pokedex_entry->writeTo($context);
}
if ($this->player_stats !== null) {
$writer->writeVarint($stream, 34);
$writer->writeVarint($stream, $this->player_stats->serializedSize($sizeContext));
$this->player_stats->writeTo($context);
}
if ($this->player_currency !== null) {
$writer->writeVarint($stream, 42);
$writer->writeVarint($stream, $this->player_currency->serializedSize($sizeContext));
$this->player_currency->writeTo($context);
}
if ($this->player_camera !== null) {
$writer->writeVarint($stream, 50);
$writer->writeVarint($stream, $this->player_camera->serializedSize($sizeContext));
$this->player_camera->writeTo($context);
}
if ($this->inventory_upgrades !== null) {
$writer->writeVarint($stream, 58);
$writer->writeVarint($stream, $this->inventory_upgrades->serializedSize($sizeContext));
$this->inventory_upgrades->writeTo($context);
}
if ($this->applied_items !== null) {
$writer->writeVarint($stream, 66);
$writer->writeVarint($stream, $this->applied_items->serializedSize($sizeContext));
$this->applied_items->writeTo($context);
}
if ($this->egg_incubators !== null) {
$writer->writeVarint($stream, 74);
$writer->writeVarint($stream, $this->egg_incubators->serializedSize($sizeContext));
$this->egg_incubators->writeTo($context);
}
if ($this->candy !== null) {
$writer->writeVarint($stream, 82);
$writer->writeVarint($stream, $this->candy->serializedSize($sizeContext));
$this->candy->writeTo($context);
}
if ($this->quest !== null) {
$writer->writeVarint($stream, 90);
$writer->writeVarint($stream, $this->quest->serializedSize($sizeContext));
$this->quest->writeTo($context);
}
if ($this->avatar_item !== null) {
$writer->writeVarint($stream, 98);
$writer->writeVarint($stream, $this->avatar_item->serializedSize($sizeContext));
$this->avatar_item->writeTo($context);
}
if ($this->raid_tickets !== null) {
$writer->writeVarint($stream, 106);
$writer->writeVarint($stream, $this->raid_tickets->serializedSize($sizeContext));
$this->raid_tickets->writeTo($context);
}
if ($this->extensions !== null) {
$this->extensions->writeTo($context);
}
return $stream;
}
/**
* {@inheritdoc}
*/
public function readFrom(\Protobuf\ReadContext $context)
{
$reader = $context->getReader();
$length = $context->getLength();
$stream = $context->getStream();
$limit = ($length !== null)
? ($stream->tell() + $length)
: null;
while ($limit === null || $stream->tell() < $limit) {
if ($stream->eof()) {
break;
}
$key = $reader->readVarint($stream);
$wire = \Protobuf\WireFormat::getTagWireType($key);
$tag = \Protobuf\WireFormat::getTagFieldNumber($key);
if ($stream->eof()) {
break;
}
if ($tag === 1) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Data\PokemonData();
$this->pokemon_data = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 2) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Inventory\Item\ItemData();
$this->item = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 3) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Data\PokedexEntry();
$this->pokedex_entry = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 4) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Data\Player\PlayerStats();
$this->player_stats = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 5) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Data\Player\PlayerCurrency();
$this->player_currency = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 6) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Data\Player\PlayerCamera();
$this->player_camera = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 7) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Inventory\InventoryUpgrades();
$this->inventory_upgrades = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 8) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Inventory\AppliedItems();
$this->applied_items = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 9) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Inventory\EggIncubators();
$this->egg_incubators = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 10) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Inventory\Candy();
$this->candy = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 11) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Data\Quests\Quest();
$this->quest = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 12) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Data\Avatar\AvatarItem();
$this->avatar_item = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
if ($tag === 13) {
\Protobuf\WireFormat::assertWireType($wire, 11);
$innerSize = $reader->readVarint($stream);
$innerMessage = new \POGOProtos\Inventory\RaidTickets();
$this->raid_tickets = $innerMessage;
$context->setLength($innerSize);
$innerMessage->readFrom($context);
$context->setLength($length);
continue;
}
$extensions = $context->getExtensionRegistry();
$extension = $extensions ? $extensions->findByNumber(__CLASS__, $tag) : null;
if ($extension !== null) {
$this->extensions()->add($extension, $extension->readFrom($context, $wire));
continue;
}
if ($this->unknownFieldSet === null) {
$this->unknownFieldSet = new \Protobuf\UnknownFieldSet();
}
$data = $reader->readUnknown($stream, $wire);
$unknown = new \Protobuf\Unknown($tag, $wire, $data);
$this->unknownFieldSet->add($unknown);
}
}
/**
* {@inheritdoc}
*/
public function serializedSize(\Protobuf\ComputeSizeContext $context)
{
$calculator = $context->getSizeCalculator();
$size = 0;
if ($this->pokemon_data !== null) {
$innerSize = $this->pokemon_data->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->item !== null) {
$innerSize = $this->item->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->pokedex_entry !== null) {
$innerSize = $this->pokedex_entry->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->player_stats !== null) {
$innerSize = $this->player_stats->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->player_currency !== null) {
$innerSize = $this->player_currency->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->player_camera !== null) {
$innerSize = $this->player_camera->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->inventory_upgrades !== null) {
$innerSize = $this->inventory_upgrades->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->applied_items !== null) {
$innerSize = $this->applied_items->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->egg_incubators !== null) {
$innerSize = $this->egg_incubators->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->candy !== null) {
$innerSize = $this->candy->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->quest !== null) {
$innerSize = $this->quest->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->avatar_item !== null) {
$innerSize = $this->avatar_item->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->raid_tickets !== null) {
$innerSize = $this->raid_tickets->serializedSize($context);
$size += 1;
$size += $innerSize;
$size += $calculator->computeVarintSize($innerSize);
}
if ($this->extensions !== null) {
$size += $this->extensions->serializedSize($context);
}
return $size;
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->pokemon_data = null;
$this->item = null;
$this->pokedex_entry = null;
$this->player_stats = null;
$this->player_currency = null;
$this->player_camera = null;
$this->inventory_upgrades = null;
$this->applied_items = null;
$this->egg_incubators = null;
$this->candy = null;
$this->quest = null;
$this->avatar_item = null;
$this->raid_tickets = null;
}
/**
* {@inheritdoc}
*/
public function merge(\Protobuf\Message $message)
{
if ( ! $message instanceof \POGOProtos\Inventory\InventoryItemData) {
throw new \InvalidArgumentException(sprintf('Argument 1 passed to %s must be a %s, %s given', __METHOD__, __CLASS__, get_class($message)));
}
$this->pokemon_data = ($message->pokemon_data !== null) ? $message->pokemon_data : $this->pokemon_data;
$this->item = ($message->item !== null) ? $message->item : $this->item;
$this->pokedex_entry = ($message->pokedex_entry !== null) ? $message->pokedex_entry : $this->pokedex_entry;
$this->player_stats = ($message->player_stats !== null) ? $message->player_stats : $this->player_stats;
$this->player_currency = ($message->player_currency !== null) ? $message->player_currency : $this->player_currency;
$this->player_camera = ($message->player_camera !== null) ? $message->player_camera : $this->player_camera;
$this->inventory_upgrades = ($message->inventory_upgrades !== null) ? $message->inventory_upgrades : $this->inventory_upgrades;
$this->applied_items = ($message->applied_items !== null) ? $message->applied_items : $this->applied_items;
$this->egg_incubators = ($message->egg_incubators !== null) ? $message->egg_incubators : $this->egg_incubators;
$this->candy = ($message->candy !== null) ? $message->candy : $this->candy;
$this->quest = ($message->quest !== null) ? $message->quest : $this->quest;
$this->avatar_item = ($message->avatar_item !== null) ? $message->avatar_item : $this->avatar_item;
$this->raid_tickets = ($message->raid_tickets !== null) ? $message->raid_tickets : $this->raid_tickets;
}
}
| jaspervdm/pogoprotos-php | src/POGOProtos/Inventory/InventoryItemData.php | PHP | mit | 35,478 |
/*
* The MIT License
*
* Copyright 2019 Azarias Boutin.
*
* 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.
*/
import { expect } from 'chai';
import 'mocha';
import * as chrome from 'sinon-chrome';
global['chrome'] = chrome;
import { join, is10fastFingersUrl, parseJsArray } from '../../src/common';
describe('Common methods', () => {
it('Should join elements togeter', () => {
const simpleJoin = join('a', 'b');
expect(simpleJoin).to.equal('a/b');
const moreJoins = join('x', 'mostElement', '', 'j');
expect(moreJoins).to.equal('x/mostElement//j');
});
it('Should be able to detect a valid 10fastfingers url', () => {
const validUrl = 'https://10fastfingers.com';
const valids = [ validUrl, validUrl + '/randomStuff', validUrl + '/' ];
const invalids = [ `a${validUrl}`, `${validUrl}c`, `http://google.fr`, 'http://10fastfingers.com' ];
valids.forEach((v) => expect(is10fastFingersUrl(v), `Valid url : ${v}`).to.be.true);
invalids.forEach((iv) => expect(is10fastFingersUrl(iv), `Invalid url ${iv}`).to.be.false);
});
it('Should correctly parse a js array', () => {
const testValues = [
'[]',
'["1"]',
'["2"]',
'["1", "123", "2", "3"]',
'["23", "45", "1", "1"]',
'["384443","384417"]',
"['384443', '384417', '384417', '384417', '384417']"
];
testValues.forEach((v) => {
const values = eval(v).map((x: string) => +x);
expect(parseJsArray(v)).to.deep.equal(values);
});
});
});
| AzariasB/10fastfingersCompetition | test/specs/common.spec.ts | TypeScript | mit | 2,471 |
namespace Shape
{
using System;
public abstract class Shape
{
private double width;
private double height;
//public Shape(double parameter)
//{
// this.Width = parameter;
// this.Height = parameter;
//}
public Shape(double width, double height)
{
this.Width = width;
this.Height = height;
}
public double Width
{
get
{
return this.width;
}
set
{
if (value <= 0)
{
throw new ArgumentException("The value of Width cannot be 0 or negative.");
}
this.width = value;
}
}
public double Height
{
get
{
return this.height;
}
set
{
if (value <= 0)
{
throw new ArgumentException("The value of Height cannot be 0 or negative.");
}
this.height = value;
}
}
public virtual double CalculateSurface()
{
return 0.0;
}
}
}
| Andro0/TelerikAcademy | OOP/05.HomeworkOOPPrinciplesPart2/Shape/Shape.cs | C# | mit | 1,273 |
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TraningToWeek extends Model
{
protected $table = 'training_OfWeeks';
protected $guarded = array('id');
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id_training_detail', 'numDay', 'start_time','end_time'
];
public function getTrainingDetail(){
return $this->hasOne('App\TraningDetails','id','id_training_detail');
}
}
| MILLKA3000/endorfine_dashboard | app/TraningToWeek.php | PHP | mit | 499 |
<?php
declare(strict_types=1);
namespace Symplify\MonorepoBuilder\ComposerJsonDecorator;
use Symplify\MonorepoBuilder\Composer\Section;
use Symplify\MonorepoBuilder\Contract\ComposerJsonDecoratorInterface;
final class RemoverComposerJsonDecorator implements ComposerJsonDecoratorInterface
{
/**
* @var mixed[]
*/
private $dataToRemove = [];
/**
* @param mixed[] $dataToRemove
*/
public function __construct(array $dataToRemove)
{
$this->dataToRemove = $dataToRemove;
}
/**
* @param mixed[] $composerJson
* @return mixed[]
*/
public function decorate(array $composerJson): array
{
foreach (array_keys($composerJson) as $key) {
if (! isset($this->dataToRemove[$key])) {
continue;
}
$composerJson = $this->processRequires($composerJson, $key);
$composerJson = $this->processAutoloads($composerJson, $key);
}
return $composerJson;
}
/**
* @param mixed[] $composerJson
* @return mixed[]
*/
private function processRequires(array $composerJson, string $key): array
{
if (! in_array($key, [Section::REQUIRE, Section::REQUIRE_DEV], true)) {
return $composerJson;
}
foreach (array_keys($this->dataToRemove[$key]) as $package) {
unset($composerJson[$key][$package]);
}
return $composerJson;
}
/**
* @param mixed[] $composerJson
* @return mixed[]
*/
private function processAutoloads(array $composerJson, string $key): array
{
if (! in_array($key, [Section::AUTOLOAD, Section::AUTOLOAD_DEV], true)) {
return $composerJson;
}
foreach ($this->dataToRemove[$key] as $type => $autoloadList) {
if (is_array($autoloadList)) {
foreach (array_keys($autoloadList) as $namespace) {
unset($composerJson[$key][$type][$namespace]);
}
}
}
return $composerJson;
}
}
| Symplify/Symplify | packages/MonorepoBuilder/src/ComposerJsonDecorator/RemoverComposerJsonDecorator.php | PHP | mit | 2,079 |
#include "Log.h"
#include "../PacketShare/PacketType.h"
#include "ClientSession.h"
#include "GameLiftManager.h"
//@{ Handler Helper
typedef std::shared_ptr<ClientSession> ClientSessionPtr;
typedef void(*HandlerFunc)(ClientSessionPtr session);
static HandlerFunc HandlerTable[PKT_MAX];
static void DefaultHandler(ClientSessionPtr session)
{
GConsoleLog->PrintOut(true, "Invalid packet handler");
session->Disconnect();
}
struct InitializeHandlers
{
InitializeHandlers()
{
for (int i = 0; i < PKT_MAX; ++i)
HandlerTable[i] = DefaultHandler;
}
} _init_handlers_;
struct RegisterHandler
{
RegisterHandler(int pktType, HandlerFunc handler)
{
HandlerTable[pktType] = handler;
}
};
#define REGISTER_HANDLER(PKT_TYPE) \
static void Handler_##PKT_TYPE(ClientSessionPtr session); \
static RegisterHandler _register_##PKT_TYPE(PKT_TYPE, Handler_##PKT_TYPE); \
static void Handler_##PKT_TYPE(ClientSessionPtr session)
//@}
///////////////////////////////////////////////////////////
void ClientSession::DispatchPacket()
{
/// packet parsing
while (true)
{
/// read packet header
PacketHeader header;
if (false == mRecvBuffer.Peek((char*)&header, sizeof(PacketHeader)))
return;
/// packet completed?
if (mRecvBuffer.GetStoredSize() < (size_t)header.mSize)
return;
if (header.mType >= PKT_MAX || header.mType <= PKT_NONE)
{
GConsoleLog->PrintOut(true, "Invalid packet type\n");
Disconnect();
return;
}
/// packet dispatch...
HandlerTable[header.mType](shared_from_this());
}
}
/////////////////////////////////////////////////////////
REGISTER_HANDLER(PKT_CS_LOGIN)
{
LoginRequest inPacket;
if (false == session->ParsePacket(inPacket))
{
GConsoleLog->PrintOut(true, "packet parsing error, Type: %d\n", inPacket.mType);
return;
}
session->PlayerLogin(std::string(inPacket.mPlayerId));
}
REGISTER_HANDLER(PKT_CS_EXIT)
{
ExitRequest inPacket;
if (false == session->ParsePacket(inPacket))
{
GConsoleLog->PrintOut(true, "packet parsing error: %d\n", inPacket.mType);
return;
}
session->PlayerLogout(std::string(inPacket.mPlayerId));
}
REGISTER_HANDLER(PKT_CS_CHAT)
{
ChatBroadcastRequest inPacket;
if (false == session->ParsePacket(inPacket))
{
GConsoleLog->PrintOut(true, "[DEBUG] packet parsing error, Type: %d\n", inPacket.mType);
return;
}
/// direct response in case of chatting
ChatBroadcastResult outPacket;
strcpy(outPacket.mPlayerId, inPacket.mPlayerId);
strcpy(outPacket.mChat, inPacket.mChat);
GGameLiftManager->BroadcastMessage(&outPacket);
}
REGISTER_HANDLER(PKT_CS_MOVE)
{
MoveRequest inPacket;
if (false == session->ParsePacket(inPacket))
{
GConsoleLog->PrintOut(true, "[DEBUG] packet parsing error, Type: %d\n", inPacket.mType);
return;
}
/// just broadcast for now
MoveBroadcastResult outPacket;
outPacket.mPlayerIdx = inPacket.mPlayerIdx;
outPacket.mPosX = inPacket.mPosX;
outPacket.mPosY = inPacket.mPosY;
GGameLiftManager->BroadcastMessage(&outPacket);
}
| zeliard/GameLift | GameLiftLinuxServer/PacketHandler.cpp | C++ | mit | 2,996 |
<?php
namespace Acme\StampBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Test
*/
class Test
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $imie;
/**
* @var \DateTime
*/
private $data;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set imie
*
* @param string $imie
* @return Test
*/
public function setImie($imie)
{
$this->imie = $imie;
return $this;
}
/**
* Get imie
*
* @return string
*/
public function getImie()
{
return $this->imie;
}
/**
* Set data
*
* @param \DateTime $data
* @return Test
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* @return \DateTime
*/
public function getData()
{
return $this->data;
}
}
| stampski/symf | src/Acme/StampBundle/Entity/Test.php | PHP | mit | 1,055 |
package mp
type MP struct {
*Server
*Client
CorpClient *Client
}
func New(id, appID, appSecret, token, aesKey string, urlPrefix ...string) *MP {
client := NewClient(appID, appSecret, true)
server := NewServer(token, aesKey, urlPrefix...)
server.SetClient(client)
server.SetID(id)
server.SetAppID(appID)
return &MP{
Server: server,
Client: client,
}
}
| ridewindx/wechat | mp/mp.go | GO | mit | 367 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Plugin.MapExtensions.WindowsStore")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Plugin.MapExtensions.WindowsStore")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | P3PPP/MapExtensions | MapExtensions/MapExtensions.Forms.Plugin.WindowsStore/Properties/AssemblyInfo.cs | C# | mit | 1,086 |
import now from './now.js';
/**
* This function transforms stored pixel values into a canvas image data buffer
* by using a LUT.
*
* @param {Image} image A Cornerstone Image Object
* @param {Array} lut Lookup table array
* @param {Uint8ClampedArray} canvasImageDataData canvasImageData.data buffer filled with white pixels
*
* @returns {void}
*/
export default function (image, lut, canvasImageDataData) {
let start = now();
const pixelData = image.getPixelData();
image.stats.lastGetPixelDataTime = now() - start;
const numPixels = pixelData.length;
const minPixelValue = image.minPixelValue;
let canvasImageDataIndex = 0;
let storedPixelDataIndex = 0;
let pixelValue;
// NOTE: As of Nov 2014, most javascript engines have lower performance when indexing negative indexes.
// We have a special code path for this case that improves performance. Thanks to @jpambrun for this enhancement
// Added two paths (Int16Array, Uint16Array) to avoid polymorphic deoptimization in chrome.
start = now();
if (pixelData instanceof Int16Array) {
if (minPixelValue < 0) {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++] + (-minPixelValue)];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
} else {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++]];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
}
} else if (pixelData instanceof Uint16Array) {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++]];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
} else if (minPixelValue < 0) {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++] + (-minPixelValue)];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
} else {
while (storedPixelDataIndex < numPixels) {
pixelValue = lut[pixelData[storedPixelDataIndex++]];
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = pixelValue;
canvasImageDataData[canvasImageDataIndex++] = 255; // Alpha
}
}
image.stats.lastStoredPixelDataToCanvasImageDataTime = now() - start;
}
| google/cornerstone | src/internal/storedPixelDataToCanvasImageDataRGBA.js | JavaScript | mit | 3,211 |
# encoding: utf-8
# frozen_string_literal: true
module RuboCop
module Cop
module Metrics
# This cop checks for methods with too many parameters.
# The maximum number of parameters in configurable.
# On Ruby 2.0+ keyword arguments can optionally
# be excluded from the total count.
class ParameterLists < Cop
include ConfigurableMax
MSG = 'Avoid parameter lists longer than %d parameters.'.freeze
def on_args(node)
count = args_count(node)
return unless count > max_params
add_offense(node, :expression, format(MSG, max_params)) do
self.max = count
end
end
private
def args_count(node)
if count_keyword_args?
node.children.size
else
node.children.count { |a| ![:kwoptarg, :kwarg].include?(a.type) }
end
end
def max_params
cop_config['Max']
end
def count_keyword_args?
cop_config['CountKeywordArgs']
end
end
end
end
end
| mrb/rubocop | lib/rubocop/cop/metrics/parameter_lists.rb | Ruby | mit | 1,088 |
from organise import app
app.run()
| msanatan/organise | run.py | Python | mit | 36 |
#include "export_node.hpp"
#include <sstream>
#include "constant_mappings.hpp"
namespace opossum {
ExportNode::ExportNode(const std::string& init_table_name, const std::string& init_file_name,
const FileType init_file_type)
: AbstractNonQueryNode(LQPNodeType::Export),
table_name(init_table_name),
file_name(init_file_name),
file_type(init_file_type) {}
std::string ExportNode::description(const DescriptionMode mode) const {
std::ostringstream stream;
stream << "[Export] Name: '" << table_name << "'";
return stream.str();
}
size_t ExportNode::_on_shallow_hash() const {
auto hash = boost::hash_value(table_name);
boost::hash_combine(hash, file_name);
boost::hash_combine(hash, file_type);
return hash;
}
std::shared_ptr<AbstractLQPNode> ExportNode::_on_shallow_copy(LQPNodeMapping& node_mapping) const {
return ExportNode::make(table_name, file_name, file_type);
}
bool ExportNode::_on_shallow_equals(const AbstractLQPNode& rhs, const LQPNodeMapping& node_mapping) const {
const auto& export_node = static_cast<const ExportNode&>(rhs);
return table_name == export_node.table_name && file_name == export_node.file_name &&
file_type == export_node.file_type;
}
} // namespace opossum
| hyrise/hyrise | src/lib/logical_query_plan/export_node.cpp | C++ | mit | 1,269 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.contrib.gis.geos import GeometryCollection
def change_line_to_multiline(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Poi = apps.get_model("webmap", "Poi")
for poi in Poi.objects.all():
if poi.geom:
poi.geom_multi = GeometryCollection([poi.geom, ])
poi.save()
class Migration(migrations.Migration):
dependencies = [
('webmap', '0011_auto_20160101_0521'),
]
operations = [
migrations.RunPython(change_line_to_multiline),
]
| auto-mat/django-webmap-corpus | webmap/migrations/0012_line_to_multiline.py | Python | mit | 736 |
from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_string(value):
return False
return len(remove_0x_prefix(value)) == 64 and is_hex(value)
def is_hex_encoded_block_number(value):
if not is_string(value):
return False
elif is_hex_encoded_block_hash(value):
return False
try:
value_as_int = int(value, 16)
except ValueError:
return False
return 0 <= value_as_int < 2**256
def select_method_for_block_identifier(value, if_hash, if_number, if_predefined):
if is_predefined_block_number(value):
return if_predefined
elif isinstance(value, bytes):
return if_hash
elif is_hex_encoded_block_hash(value):
return if_hash
elif is_integer(value) and (0 <= value < 2**256):
return if_number
elif is_hex_encoded_block_number(value):
return if_number
else:
raise ValueError(
"Value did not match any of the recognized block identifiers: {0}".format(value)
)
| pipermerriam/web3.py | web3/utils/blocks.py | Python | mit | 1,270 |
module ToppingsRails
VERSION = "0.0.1"
end
| toppings/toppings-rails | lib/toppings_rails/version.rb | Ruby | mit | 45 |
<?php
namespace OAuth2\ResponseType;
use OAuth2\Storage\AuthorizationCodeInterface as AuthorizationCodeStorageInterface;
/**
*
* @author Brent Shaffer <bshafs at gmail dot com>
*/
class AuthorizationCode implements AuthorizationCodeInterface
{
protected $storage;
protected $config;
public function __construct(AuthorizationCodeStorageInterface $storage, array $config = array())
{
$this->storage = $storage;
$this->config = array_merge(array(
'enforce_redirect' => false,
'auth_code_lifetime' => 30,
), $config);
}
public function getAuthorizeResponse($params, $user_id = null)
{
// build the URL to redirect to
// exit(print $_GET['user_id']);
//$user_id=$_GET['user_id'];
$result = array('query' => array());
$params += array('scope' => null, 'state' => null);
$result['query']['code'] = $this->createAuthorizationCode($params['client_id'], $user_id, $params['redirect_uri'], $params['scope']);
if (isset($params['state'])) {
$result['query']['state'] = $params['state'];
}
return array($params['redirect_uri'], $result);
}
/**
* Handle the creation of the authorization code.
*
* @param $client_id
* Client identifier related to the authorization code
* @param $user_id
* User ID associated with the authorization code
* @param $redirect_uri
* An absolute URI to which the authorization server will redirect the
* user-agent to when the end-user authorization step is completed.
* @param $scope
* (optional) Scopes to be stored in space-separated string.
*
* @see http://tools.ietf.org/html/rfc6749#section-4
* @ingroup oauth2_section_4
*/
public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null)
{
$code = $this->generateAuthorizationCode();
$this->storage->setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, time() + $this->config['auth_code_lifetime'], $scope);
return $code;
}
/**
* @return
* TRUE if the grant type requires a redirect_uri, FALSE if not
*/
public function enforceRedirect()
{
return $this->config['enforce_redirect'];
}
/**
* Generates an unique auth code.
*
* Implementing classes may want to override this function to implement
* other auth code generation schemes.
*
* @return
* An unique auth code.
*
* @ingroup oauth2_section_4
*/
protected function generateAuthorizationCode()
{
$tokenLen = 40;
if (function_exists('mcrypt_create_iv')) {
$randomData = mcrypt_create_iv(100, MCRYPT_DEV_URANDOM);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$randomData = openssl_random_pseudo_bytes(100);
} elseif (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
$randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
} else {
$randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
}
return substr(hash('sha512', $randomData), 0, $tokenLen);
}
}
| vthawat/oauth2_server | application/third_party/OAuth2/ResponseType/AuthorizationCode.php | PHP | mit | 3,335 |
module.exports = function() {
function CreditsCommand() {
return {
name: 'credits',
params: '[none]',
execute: function(data, sandbox) {
var msg = '\nCREDITS:\n';
msg += 'Hack Bot\n';
msg += 'version: v1\n';
msg += 'created by: R.M.C. (hacktastic)\n\n\n';
sandbox.sendChannelMessage(msg);
}
};
}
return new CreditsCommand();
}; | ryanmcoble/LiveCoding.tv-Chat-Bot | modules/commands/credits/credits.js | JavaScript | mit | 375 |
'use strict';
const Bluebird = require('bluebird');
const Book = require('./helpers/book');
const Counter = require('../lib/counter');
const Genre = require('./helpers/genre');
const Redis = require('./helpers/redis');
describe('counter', () => {
describe('count', () => {
it('returns the count for a model without a filter function', () => {
const request = {};
return Counter.count(Genre, request)
.then((count) => {
expect(count).to.eql(3);
});
});
it('returns the count for a model with a filter function', () => {
const request = { query: { filter: { year: 1984 } }, auth: { credentials: {} } };
return Counter.count(Book, request)
.then((count) => {
expect(count).to.eql(2);
});
});
it('saves the count to redis under the given key with a ttl when a redis client is given', () => {
const key = 'key';
const ttl = () => 10;
const request = { query: { filter: { year: 1984 } }, auth: { credentials: {} } };
return Counter.count(Book, request, Redis, key, ttl)
.then(() => {
return Bluebird.all([
Redis.getAsync(key),
Redis.ttlAsync(key)
]);
})
.spread((cachedCount, cachedTtl) => {
expect(cachedCount).to.eql('2');
expect(cachedTtl).to.eql(10);
});
});
});
});
| lob/hapi-bookshelf-total-count | test/counter.test.js | JavaScript | mit | 1,376 |
// Dependencies
let builder = require('focus').component.builder;
let React = require('react');
let checkIsNotNull = require('focus').util.object.checkIsNotNull;
let type = require('focus').component.types;
let find = require('lodash/collection/find');
// Mixins
let translationMixin = require('../../common/i18n').mixin;
let infiniteScrollMixin = require('../mixin/infinite-scroll').mixin;
let referenceMixin = require('../../common/mixin/reference-property');
// Components
let Button = require('../../common/button/action').component;
let listMixin = {
/**
* Display name.
*/
displayName: 'selection-list',
/**
* Mixin dependancies.
*/
mixins: [translationMixin, infiniteScrollMixin, referenceMixin],
/**
* Default properties for the list.
* @returns {{isSelection: boolean}} the default properties
*/
getDefaultProps: function getListDefaultProps(){
return {
data: [],
isSelection: true,
selectionStatus: 'partial',
selectionData: [],
isLoading: false,
operationList: [],
idField: 'id'
};
},
/**
* list property validation.
* @type {Object}
*/
propTypes: {
data: type('array'),
idField: type('string'),
isLoading: type('bool'),
isSelection: type('bool'),
lineComponent: type('func', true),
loader: type('func'),
onLineClick: type('func'),
onSelection: type('func'),
operationList: type('array'),
selectionData: type('array'),
selectionStatus: type('string')
},
/**
* called before component mount
*/
componentWillMount() {
checkIsNotNull('lineComponent', this.props.lineComponent);
},
/**
* Return selected items in the list.
* @return {Array} selected items
*/
getSelectedItems() {
let selected = [];
for(let i = 1; i < this.props.data.length + 1; i++){
let lineName = 'line' + i;
let lineValue = this.refs[lineName].getValue();
if(lineValue.isSelected){
selected.push(lineValue.item);
}
}
return selected;
},
/**
* Render lines of the list.
* @returns {*} DOM for lines
*/
_renderLines() {
let lineCount = 1;
let {data, lineComponent, selectionStatus, idField, isSelection, selectionData, onSelection, onLineClick, operationList} = this.props;
return data.map((line) => {
let isSelected;
let selection = find(selectionData, {[idField]: line[idField]});
if (selection) {
isSelected = selection.isSelected;
} else {
switch(selectionStatus){
case 'none':
isSelected = false;
break;
case 'selected':
isSelected = true;
break;
case 'partial':
isSelected = undefined;
break;
default:
isSelected = false;
}
}
return React.createElement(lineComponent, {
key: line[idField],
data: line,
ref: `line${lineCount++}`,
isSelection: isSelection,
isSelected: isSelected,
onSelection: onSelection,
onLineClick: onLineClick,
operationList: operationList,
reference: this._getReference()
});
});
},
_renderLoading() {
if(this.props.isLoading){
if(this.props.loader){
return this.props.loader();
}
return (
<li className='sl-loading'>{this.i18n('list.loading')} ...</li>
);
}
},
_renderManualFetch() {
if(this.props.isManualFetch && this.props.hasMoreData){
let style = {className: 'primary'};
return (
<li className='sl-button'>
<Button
handleOnClick={this.handleShowMore}
label='list.button.showMore'
style={style}
type='button'
/>
</li>
);
}
},
/**
* Render the list.
* @returns {XML} DOM of the component
*/
render() {
return (
<ul data-focus='selection-list'>
{this._renderLines()}
{this._renderLoading()}
{this._renderManualFetch()}
</ul>
);
}
};
module.exports = builder(listMixin);
| Jerom138/focus-components | src/list/selection/list.js | JavaScript | mit | 4,831 |
import { createAction } from 'redux-actions';
import axios from '../../../utils/APIHelper';
export const CATEGORY_FORM_UPDATE = 'CATEGORY_FORM_UPDATE';
export const CATEGORY_FORM_RESET = 'CATEGORY_FORM_RESET';
export const categoryFormUpdate = createAction(CATEGORY_FORM_UPDATE);
export const categoryFormReset = createAction(CATEGORY_FORM_RESET);
export function requestCreateCategory(attrs) {
return (dispatch) => {
dispatch(categoryFormUpdate());
return axios.post('/api/categories', { category: attrs })
.then(response => {
dispatch(categoryFormReset());
return response.data.category;
}, e => dispatch(categoryFormUpdate(e)));
};
}
| fdietz/whistler_news_reader | client/js/modules/categoryForm/actions/index.js | JavaScript | mit | 681 |
#include <cstdio>
#include <string>
#include <cerrno>
#include <cstring>
#include "toi.h"
using namespace std;
FileStack::FileStack() {
tlines = 0;
}
FileStack::~FileStack() {
while(!file_stack.empty())
file_close();
}
// returns true if the file is now open
// throws an exception upon failure
void FileStack::file_open(string name) {
Logging(DEBUG) << "opening file \"" << name << "\"";
struct file_entry* fe = new struct file_entry;
fe->fp = ifstream(name);
if(fe->fp.is_open()) {
fe->line_no = 1;
fe->name = string(name);
file_stack.push(fe);
}
else {
Logging(FATAL) << "cannot open input file: \"" << name << "\": " << strerror(errno);
}
}
int FileStack::read_character() {
int retv = 0;
if(!file_stack.empty()) {
retv = file_stack.top()->fp.get();
if(retv == EOF) {
// Note that if one reads the stack for a file and and a line
// number after this, it's the new file on the tos, not the
// one that matches the END_CONTEXT token. I don't think it's
// a problem, but I am dropping this comment to mark the
// occourance.
file_close();
retv = 0x01;
}
}
else {
retv = 0x00;
}
if(retv == '\n') {
file_stack.top()->line_no++;
tlines++;
}
return retv;
}
void FileStack::unread_character(int ch) {
if(!file_stack.empty()) {
if(ch != '\n')
file_stack.top()->fp.putback(ch);
}
}
string FileStack::file_name() {
if(!file_stack.empty())
return file_stack.top()->name;
else
return string("no file");
}
int FileStack::line_number() {
if(!file_stack.empty())
return file_stack.top()->line_no;
else
return -1;
}
int FileStack::total_lines() {
return tlines;
}
void FileStack::file_close() {
// close the file and pop the stack
if(!file_stack.empty()) {
Logging(DEBUG) << "closing file \"" << file_stack.top()->name << "\"";
struct file_entry* fe = file_stack.top();
fe->fp.close();
file_stack.pop();
delete fe;
}
else
Logging(DEBUG) << "no files to close";
}
| chucktilbury/toi | file_stack.cpp | C++ | mit | 2,268 |
'use strict';
/**
* Module dependencies
*/
var forumsPolicy = require('../policies/forums.server.policy'),
forums = require('../controllers/forums.server.controller');
module.exports = function (app) {
// Forums collection routes
app.route('/api/forums').all(forumsPolicy.isAllowed)
.get(forums.list)
.post(forums.create);
// Single forum routes
app.route('/api/forums/:forumId').all(forumsPolicy.isAllowed)
.get(forums.read)
.put(forums.update)
.delete(forums.delete);
// Finish by binding the forum middleware
app.param('forumId', forums.forumByID);
};
| jecp/mean | modules/forums/server/routes/forums.server.routes.js | JavaScript | mit | 595 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('ebets.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| pisskidney/dota | dota/urls.py | Python | mit | 222 |
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _index = _interopRequireDefault(require("../../index"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Custom =
/*#__PURE__*/
function (_Smooth) {
_inherits(Custom, _Smooth);
function Custom(opt) {
var _this;
_classCallCheck(this, Custom);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Custom).call(this, opt));
_this.perfs = {
now: null,
last: null
};
_this.dom.section = opt.section;
return _this;
}
_createClass(Custom, [{
key: "init",
value: function init() {
_get(_getPrototypeOf(Custom.prototype), "init", this).call(this);
}
}, {
key: "run",
value: function run() {
this.perfs.now = window.performance.now();
_get(_getPrototypeOf(Custom.prototype), "run", this).call(this);
this.dom.section.style[this.prefix] = this.getTransform(-this.vars.current.toFixed(2));
console.log(this.perfs.now - this.perfs.last);
this.perfs.last = this.perfs.now;
}
}, {
key: "resize",
value: function resize() {
this.vars.bounding = this.dom.section.getBoundingClientRect().height - this.vars.height;
_get(_getPrototypeOf(Custom.prototype), "resize", this).call(this);
}
}]);
return Custom;
}(_index["default"]);
var _default = Custom;
exports["default"] = _default;
},{"../../index":3}],2:[function(require,module,exports){
"use strict";
var _custom = _interopRequireDefault(require("./custom"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var scroll = new _custom["default"]({
"extends": true,
section: document.querySelector('.vs-section')
});
scroll.init();
},{"./custom":1}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _domClasses = _interopRequireDefault(require("dom-classes"));
var _domCreateElement = _interopRequireDefault(require("dom-create-element"));
var _prefix = _interopRequireDefault(require("prefix"));
var _virtualScroll = _interopRequireDefault(require("virtual-scroll"));
var _domEvents = _interopRequireDefault(require("dom-events"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var Smooth =
/*#__PURE__*/
function () {
function Smooth() {
var opt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Smooth);
this.createBound();
this.options = opt;
this.prefix = (0, _prefix["default"])('transform');
this.rAF = undefined; // It seems that under heavy load, Firefox will still call the RAF callback even though the RAF has been canceled
// To prevent that we set a flag to prevent any callback to be executed when RAF is removed
this.isRAFCanceled = false;
var constructorName = this.constructor.name ? this.constructor.name : 'Smooth';
this["extends"] = typeof opt["extends"] === 'undefined' ? this.constructor !== Smooth : opt["extends"];
this.callback = this.options.callback || null;
this.vars = {
direction: this.options.direction || 'vertical',
"native": this.options["native"] || false,
ease: this.options.ease || 0.075,
preload: this.options.preload || false,
current: 0,
last: 0,
target: 0,
height: window.innerHeight,
width: window.innerWidth,
bounding: 0,
timer: null,
ticking: false
};
this.vs = this.vars["native"] ? null : new _virtualScroll["default"]({
limitInertia: this.options.vs && this.options.vs.limitInertia || false,
mouseMultiplier: this.options.vs && this.options.vs.mouseMultiplier || 1,
touchMultiplier: this.options.vs && this.options.vs.touchMultiplier || 1.5,
firefoxMultiplier: this.options.vs && this.options.vs.firefoxMultiplier || 30,
preventTouch: this.options.vs && this.options.vs.preventTouch || true
});
this.dom = {
listener: this.options.listener || document.body,
section: this.options.section || document.querySelector('.vs-section') || null,
scrollbar: this.vars["native"] || this.options.noscrollbar ? null : {
state: {
clicked: false,
x: 0
},
el: (0, _domCreateElement["default"])({
selector: 'div',
styles: "vs-scrollbar vs-".concat(this.vars.direction, " vs-scrollbar-").concat(constructorName.toLowerCase())
}),
drag: {
el: (0, _domCreateElement["default"])({
selector: 'div',
styles: 'vs-scrolldrag'
}),
delta: 0,
height: 50
}
}
};
}
_createClass(Smooth, [{
key: "createBound",
value: function createBound() {
var _this = this;
['run', 'calc', 'debounce', 'resize', 'mouseUp', 'mouseDown', 'mouseMove', 'calcScroll', 'scrollTo'].forEach(function (fn) {
return _this[fn] = _this[fn].bind(_this);
});
}
}, {
key: "init",
value: function init() {
this.addClasses();
this.vars.preload && this.preloadImages();
this.vars["native"] ? this.addFakeScrollHeight() : !this.options.noscrollbar && this.addFakeScrollBar();
this.addEvents();
this.resize();
}
}, {
key: "addClasses",
value: function addClasses() {
var type = this.vars["native"] ? 'native' : 'virtual';
var direction = this.vars.direction === 'vertical' ? 'y' : 'x';
_domClasses["default"].add(this.dom.listener, "is-".concat(type, "-scroll"));
_domClasses["default"].add(this.dom.listener, "".concat(direction, "-scroll"));
}
}, {
key: "preloadImages",
value: function preloadImages() {
var _this2 = this;
var images = Array.prototype.slice.call(this.dom.listener.querySelectorAll('img'), 0);
images.forEach(function (image) {
var img = document.createElement('img');
_domEvents["default"].once(img, 'load', function () {
images.splice(images.indexOf(image), 1);
images.length === 0 && _this2.resize();
});
img.src = image.getAttribute('src');
});
}
}, {
key: "calc",
value: function calc(e) {
var delta = this.vars.direction == 'horizontal' ? e.deltaX : e.deltaY;
this.vars.target += delta * -1;
this.clampTarget();
}
}, {
key: "debounce",
value: function debounce() {
var _this3 = this;
var win = this.dom.listener === document.body;
this.vars.target = this.vars.direction === 'vertical' ? win ? window.scrollY || window.pageYOffset : this.dom.listener.scrollTop : win ? window.scrollX || window.pageXOffset : this.dom.listener.scrollLeft;
clearTimeout(this.vars.timer);
if (!this.vars.ticking) {
this.vars.ticking = true;
_domClasses["default"].add(this.dom.listener, 'is-scrolling');
}
this.vars.timer = setTimeout(function () {
_this3.vars.ticking = false;
_domClasses["default"].remove(_this3.dom.listener, 'is-scrolling');
}, 200);
}
}, {
key: "run",
value: function run() {
if (this.isRAFCanceled) return;
this.vars.current += (this.vars.target - this.vars.current) * this.vars.ease;
this.vars.current < .1 && (this.vars.current = 0);
this.requestAnimationFrame();
if (!this["extends"]) {
this.dom.section.style[this.prefix] = this.getTransform(-this.vars.current.toFixed(2));
}
if (!this.vars["native"] && !this.options.noscrollbar) {
var size = this.dom.scrollbar.drag.height;
var bounds = this.vars.direction === 'vertical' ? this.vars.height : this.vars.width;
var value = Math.abs(this.vars.current) / (this.vars.bounding / (bounds - size)) + size / .5 - size;
var clamp = Math.max(0, Math.min(value - size, value + size));
this.dom.scrollbar.drag.el.style[this.prefix] = this.getTransform(clamp.toFixed(2));
}
if (this.callback && this.vars.current !== this.vars.last) {
this.callback(this.vars.current);
}
this.vars.last = this.vars.current;
}
}, {
key: "getTransform",
value: function getTransform(value) {
return this.vars.direction === 'vertical' ? "translate3d(0,".concat(value, "px,0)") : "translate3d(".concat(value, "px,0,0)");
}
}, {
key: "on",
value: function on() {
var requestAnimationFrame = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
if (this.isRAFCanceled) {
this.isRAFCanceled = false;
}
var node = this.dom.listener === document.body ? window : this.dom.listener;
this.vars["native"] ? _domEvents["default"].on(node, 'scroll', this.debounce) : this.vs && this.vs.on(this.calc);
requestAnimationFrame && this.requestAnimationFrame();
}
}, {
key: "off",
value: function off() {
var cancelAnimationFrame = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var node = this.dom.listener === document.body ? window : this.dom.listener;
this.vars["native"] ? _domEvents["default"].off(node, 'scroll', this.debounce) : this.vs && this.vs.off(this.calc);
cancelAnimationFrame && this.cancelAnimationFrame();
}
}, {
key: "requestAnimationFrame",
value: function (_requestAnimationFrame) {
function requestAnimationFrame() {
return _requestAnimationFrame.apply(this, arguments);
}
requestAnimationFrame.toString = function () {
return _requestAnimationFrame.toString();
};
return requestAnimationFrame;
}(function () {
this.rAF = requestAnimationFrame(this.run);
})
}, {
key: "cancelAnimationFrame",
value: function (_cancelAnimationFrame) {
function cancelAnimationFrame() {
return _cancelAnimationFrame.apply(this, arguments);
}
cancelAnimationFrame.toString = function () {
return _cancelAnimationFrame.toString();
};
return cancelAnimationFrame;
}(function () {
this.isRAFCanceled = true;
cancelAnimationFrame(this.rAF);
})
}, {
key: "addEvents",
value: function addEvents() {
this.on();
_domEvents["default"].on(window, 'resize', this.resize);
}
}, {
key: "removeEvents",
value: function removeEvents() {
this.off();
_domEvents["default"].off(window, 'resize', this.resize);
}
}, {
key: "addFakeScrollBar",
value: function addFakeScrollBar() {
this.dom.listener.appendChild(this.dom.scrollbar.el);
this.dom.scrollbar.el.appendChild(this.dom.scrollbar.drag.el);
_domEvents["default"].on(this.dom.scrollbar.el, 'click', this.calcScroll);
_domEvents["default"].on(this.dom.scrollbar.el, 'mousedown', this.mouseDown);
_domEvents["default"].on(document, 'mousemove', this.mouseMove);
_domEvents["default"].on(document, 'mouseup', this.mouseUp);
}
}, {
key: "removeFakeScrollBar",
value: function removeFakeScrollBar() {
_domEvents["default"].off(this.dom.scrollbar.el, 'click', this.calcScroll);
_domEvents["default"].off(this.dom.scrollbar.el, 'mousedown', this.mouseDown);
_domEvents["default"].off(document, 'mousemove', this.mouseMove);
_domEvents["default"].off(document, 'mouseup', this.mouseUp);
this.dom.listener.removeChild(this.dom.scrollbar.el);
}
}, {
key: "mouseDown",
value: function mouseDown(e) {
e.preventDefault();
e.which == 1 && (this.dom.scrollbar.state.clicked = true);
}
}, {
key: "mouseUp",
value: function mouseUp(e) {
this.dom.scrollbar.state.clicked = false;
_domClasses["default"].remove(this.dom.listener, 'is-dragging');
}
}, {
key: "mouseMove",
value: function mouseMove(e) {
this.dom.scrollbar.state.clicked && this.calcScroll(e);
}
}, {
key: "addFakeScrollHeight",
value: function addFakeScrollHeight() {
this.dom.scroll = (0, _domCreateElement["default"])({
selector: 'div',
styles: 'vs-scroll-view'
});
this.dom.listener.appendChild(this.dom.scroll);
}
}, {
key: "removeFakeScrollHeight",
value: function removeFakeScrollHeight() {
this.dom.listener.removeChild(this.dom.scroll);
}
}, {
key: "calcScroll",
value: function calcScroll(e) {
var client = this.vars.direction == 'vertical' ? e.clientY : e.clientX;
var bounds = this.vars.direction == 'vertical' ? this.vars.height : this.vars.width;
var delta = client * (this.vars.bounding / bounds);
_domClasses["default"].add(this.dom.listener, 'is-dragging');
this.vars.target = delta;
this.clampTarget();
this.dom.scrollbar && (this.dom.scrollbar.drag.delta = this.vars.target);
}
}, {
key: "scrollTo",
value: function scrollTo(offset) {
if (this.vars["native"]) {
this.vars.direction == 'vertical' ? window.scrollTo(0, offset) : window.scrollTo(offset, 0);
} else {
this.vars.target = offset;
this.clampTarget();
}
}
}, {
key: "resize",
value: function resize() {
var prop = this.vars.direction === 'vertical' ? 'height' : 'width';
this.vars.height = window.innerHeight;
this.vars.width = window.innerWidth;
if (!this["extends"]) {
var bounding = this.dom.section.getBoundingClientRect();
this.vars.bounding = this.vars.direction === 'vertical' ? bounding.height - (this.vars["native"] ? 0 : this.vars.height) : bounding.right - (this.vars["native"] ? 0 : this.vars.width);
}
if (!this.vars["native"] && !this.options.noscrollbar) {
this.dom.scrollbar.drag.height = this.vars.height * (this.vars.height / (this.vars.bounding + this.vars.height));
this.dom.scrollbar.drag.el.style[prop] = "".concat(this.dom.scrollbar.drag.height, "px");
} else if (this.vars["native"]) {
this.dom.scroll.style[prop] = "".concat(this.vars.bounding, "px");
}
!this.vars["native"] && this.clampTarget();
}
}, {
key: "clampTarget",
value: function clampTarget() {
this.vars.target = Math.round(Math.max(0, Math.min(this.vars.target, this.vars.bounding)));
}
}, {
key: "destroy",
value: function destroy() {
if (this.vars["native"]) {
_domClasses["default"].remove(this.dom.listener, 'is-native-scroll');
this.removeFakeScrollHeight();
} else {
_domClasses["default"].remove(this.dom.listener, 'is-virtual-scroll');
!this.options.noscrollbar && this.removeFakeScrollBar();
}
this.vars.direction === 'vertical' ? _domClasses["default"].remove(this.dom.listener, 'y-scroll') : _domClasses["default"].remove(this.dom.listener, 'x-scroll');
this.vars.current = 0;
this.vs && (this.vs.destroy(), this.vs = null);
this.removeEvents();
}
}]);
return Smooth;
}();
exports["default"] = Smooth;
window.Smooth = Smooth;
},{"dom-classes":5,"dom-create-element":6,"dom-events":7,"prefix":11,"virtual-scroll":17}],4:[function(require,module,exports){
'use strict';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty;
module.exports = function(object) {
if(!object) return console.warn('bindAll requires at least one argument.');
var functions = Array.prototype.slice.call(arguments, 1);
if (functions.length === 0) {
for (var method in object) {
if(hasOwnProperty.call(object, method)) {
if(typeof object[method] == 'function' && toString.call(object[method]) == "[object Function]") {
functions.push(method);
}
}
}
}
for(var i = 0; i < functions.length; i++) {
var f = functions[i];
object[f] = bind(object[f], object);
}
};
/*
Faster bind without specific-case checking. (see https://coderwall.com/p/oi3j3w).
bindAll is only needed for events binding so no need to make slow fixes for constructor
or partial application.
*/
function bind(func, context) {
return function() {
return func.apply(context, arguments);
};
}
},{}],5:[function(require,module,exports){
/**
* Module dependencies.
*/
var index = require('indexof');
/**
* Whitespace regexp.
*/
var whitespaceRe = /\s+/;
/**
* toString reference.
*/
var toString = Object.prototype.toString;
module.exports = classes;
module.exports.add = add;
module.exports.contains = has;
module.exports.has = has;
module.exports.toggle = toggle;
module.exports.remove = remove;
module.exports.removeMatching = removeMatching;
function classes (el) {
if (el.classList) {
return el.classList;
}
var str = el.className.replace(/^\s+|\s+$/g, '');
var arr = str.split(whitespaceRe);
if ('' === arr[0]) arr.shift();
return arr;
}
function add (el, name) {
// classList
if (el.classList) {
el.classList.add(name);
return;
}
// fallback
var arr = classes(el);
var i = index(arr, name);
if (!~i) arr.push(name);
el.className = arr.join(' ');
}
function has (el, name) {
return el.classList
? el.classList.contains(name)
: !! ~index(classes(el), name);
}
function remove (el, name) {
if ('[object RegExp]' == toString.call(name)) {
return removeMatching(el, name);
}
// classList
if (el.classList) {
el.classList.remove(name);
return;
}
// fallback
var arr = classes(el);
var i = index(arr, name);
if (~i) arr.splice(i, 1);
el.className = arr.join(' ');
}
function removeMatching (el, re, ref) {
var arr = Array.prototype.slice.call(classes(el));
for (var i = 0; i < arr.length; i++) {
if (re.test(arr[i])) {
remove(el, arr[i]);
}
}
}
function toggle (el, name) {
// classList
if (el.classList) {
return el.classList.toggle(name);
}
// fallback
if (has(el, name)) {
remove(el, name);
} else {
add(el, name);
}
}
},{"indexof":8}],6:[function(require,module,exports){
/*
`dom-create-element`
var create = require('dom-create-element');
var el = create({
selector: 'div',
styles: 'preloader',
html: '<span>Text</span>'
});
*/
module.exports = create;
function create(opt) {
opt = opt || {};
var el = document.createElement(opt.selector);
if(opt.attr) for(var index in opt.attr)
opt.attr.hasOwnProperty(index) && el.setAttribute(index, opt.attr[index]);
"a" == opt.selector && opt.link && (
el.href = opt.link,
opt.target && el.setAttribute("target", opt.target)
);
"img" == opt.selector && opt.src && (
el.src = opt.src,
opt.lazyload && (
el.style.opacity = 0,
el.onload = function(){
el.style.opacity = 1;
}
)
);
opt.id && (el.id = opt.id);
opt.styles && (el.className = opt.styles);
opt.html && (el.innerHTML = opt.html);
opt.children && (el.appendChild(opt.children));
return el;
};
},{}],7:[function(require,module,exports){
var synth = require('synthetic-dom-events');
var on = function(element, name, fn, capture) {
return element.addEventListener(name, fn, capture || false);
};
var off = function(element, name, fn, capture) {
return element.removeEventListener(name, fn, capture || false);
};
var once = function (element, name, fn, capture) {
function tmp (ev) {
off(element, name, tmp, capture);
fn(ev);
}
on(element, name, tmp, capture);
};
var emit = function(element, name, opt) {
var ev = synth(name, opt);
element.dispatchEvent(ev);
};
if (!document.addEventListener) {
on = function(element, name, fn) {
return element.attachEvent('on' + name, fn);
};
}
if (!document.removeEventListener) {
off = function(element, name, fn) {
return element.detachEvent('on' + name, fn);
};
}
if (!document.dispatchEvent) {
emit = function(element, name, opt) {
var ev = synth(name, opt);
return element.fireEvent('on' + ev.type, ev);
};
}
module.exports = {
on: on,
off: off,
once: once,
emit: emit
};
},{"synthetic-dom-events":12}],8:[function(require,module,exports){
var indexOf = [].indexOf;
module.exports = function(arr, obj){
if (indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
},{}],9:[function(require,module,exports){
// Generated by CoffeeScript 1.9.2
(function() {
var root;
root = typeof exports !== "undefined" && exports !== null ? exports : this;
root.Lethargy = (function() {
function Lethargy(stability, sensitivity, tolerance, delay) {
this.stability = stability != null ? Math.abs(stability) : 8;
this.sensitivity = sensitivity != null ? 1 + Math.abs(sensitivity) : 100;
this.tolerance = tolerance != null ? 1 + Math.abs(tolerance) : 1.1;
this.delay = delay != null ? delay : 150;
this.lastUpDeltas = (function() {
var i, ref, results;
results = [];
for (i = 1, ref = this.stability * 2; 1 <= ref ? i <= ref : i >= ref; 1 <= ref ? i++ : i--) {
results.push(null);
}
return results;
}).call(this);
this.lastDownDeltas = (function() {
var i, ref, results;
results = [];
for (i = 1, ref = this.stability * 2; 1 <= ref ? i <= ref : i >= ref; 1 <= ref ? i++ : i--) {
results.push(null);
}
return results;
}).call(this);
this.deltasTimestamp = (function() {
var i, ref, results;
results = [];
for (i = 1, ref = this.stability * 2; 1 <= ref ? i <= ref : i >= ref; 1 <= ref ? i++ : i--) {
results.push(null);
}
return results;
}).call(this);
}
Lethargy.prototype.check = function(e) {
var lastDelta;
e = e.originalEvent || e;
if (e.wheelDelta != null) {
lastDelta = e.wheelDelta;
} else if (e.deltaY != null) {
lastDelta = e.deltaY * -40;
} else if ((e.detail != null) || e.detail === 0) {
lastDelta = e.detail * -40;
}
this.deltasTimestamp.push(Date.now());
this.deltasTimestamp.shift();
if (lastDelta > 0) {
this.lastUpDeltas.push(lastDelta);
this.lastUpDeltas.shift();
return this.isInertia(1);
} else {
this.lastDownDeltas.push(lastDelta);
this.lastDownDeltas.shift();
return this.isInertia(-1);
}
return false;
};
Lethargy.prototype.isInertia = function(direction) {
var lastDeltas, lastDeltasNew, lastDeltasOld, newAverage, newSum, oldAverage, oldSum;
lastDeltas = direction === -1 ? this.lastDownDeltas : this.lastUpDeltas;
if (lastDeltas[0] === null) {
return direction;
}
if (this.deltasTimestamp[(this.stability * 2) - 2] + this.delay > Date.now() && lastDeltas[0] === lastDeltas[(this.stability * 2) - 1]) {
return false;
}
lastDeltasOld = lastDeltas.slice(0, this.stability);
lastDeltasNew = lastDeltas.slice(this.stability, this.stability * 2);
oldSum = lastDeltasOld.reduce(function(t, s) {
return t + s;
});
newSum = lastDeltasNew.reduce(function(t, s) {
return t + s;
});
oldAverage = oldSum / lastDeltasOld.length;
newAverage = newSum / lastDeltasNew.length;
if (Math.abs(oldAverage) < Math.abs(newAverage * this.tolerance) && (this.sensitivity < Math.abs(newAverage))) {
return direction;
} else {
return false;
}
};
Lethargy.prototype.showLastUpDeltas = function() {
return this.lastUpDeltas;
};
Lethargy.prototype.showLastDownDeltas = function() {
return this.lastDownDeltas;
};
return Lethargy;
})();
}).call(this);
},{}],10:[function(require,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
},{}],11:[function(require,module,exports){
// check document first so it doesn't error in node.js
var style = typeof document != 'undefined'
? document.createElement('p').style
: {}
var prefixes = ['O', 'ms', 'Moz', 'Webkit']
var upper = /([A-Z])/g
var memo = {}
/**
* prefix `key`
*
* prefix('transform') // => WebkitTransform
*
* @param {String} key
* @return {String}
* @api public
*/
function prefix(key){
// Camel case
key = key.replace(/-([a-z])/g, function(_, char){
return char.toUpperCase()
})
// Without prefix
if (style[key] !== undefined) return key
// With prefix
var Key = key.charAt(0).toUpperCase() + key.slice(1)
var i = prefixes.length
while (i--) {
var name = prefixes[i] + Key
if (style[name] !== undefined) return name
}
return key
}
/**
* Memoized version of `prefix`
*
* @param {String} key
* @return {String}
* @api public
*/
function prefixMemozied(key){
return key in memo
? memo[key]
: memo[key] = prefix(key)
}
/**
* Create a dashed prefix
*
* @param {String} key
* @return {String}
* @api public
*/
function prefixDashed(key){
key = prefix(key)
if (upper.test(key)) {
key = '-' + key.replace(upper, '-$1')
upper.lastIndex = 0
}
return key.toLowerCase()
}
module.exports = prefixMemozied
module.exports.dash = prefixDashed
},{}],12:[function(require,module,exports){
// for compression
var win = window;
var doc = document || {};
var root = doc.documentElement || {};
// detect if we need to use firefox KeyEvents vs KeyboardEvents
var use_key_event = true;
try {
doc.createEvent('KeyEvents');
}
catch (err) {
use_key_event = false;
}
// Workaround for https://bugs.webkit.org/show_bug.cgi?id=16735
function check_kb(ev, opts) {
if (ev.ctrlKey != (opts.ctrlKey || false) ||
ev.altKey != (opts.altKey || false) ||
ev.shiftKey != (opts.shiftKey || false) ||
ev.metaKey != (opts.metaKey || false) ||
ev.keyCode != (opts.keyCode || 0) ||
ev.charCode != (opts.charCode || 0)) {
ev = document.createEvent('Event');
ev.initEvent(opts.type, opts.bubbles, opts.cancelable);
ev.ctrlKey = opts.ctrlKey || false;
ev.altKey = opts.altKey || false;
ev.shiftKey = opts.shiftKey || false;
ev.metaKey = opts.metaKey || false;
ev.keyCode = opts.keyCode || 0;
ev.charCode = opts.charCode || 0;
}
return ev;
}
// modern browsers, do a proper dispatchEvent()
var modern = function(type, opts) {
opts = opts || {};
// which init fn do we use
var family = typeOf(type);
var init_fam = family;
if (family === 'KeyboardEvent' && use_key_event) {
family = 'KeyEvents';
init_fam = 'KeyEvent';
}
var ev = doc.createEvent(family);
var init_fn = 'init' + init_fam;
var init = typeof ev[init_fn] === 'function' ? init_fn : 'initEvent';
var sig = initSignatures[init];
var args = [];
var used = {};
opts.type = type;
for (var i = 0; i < sig.length; ++i) {
var key = sig[i];
var val = opts[key];
// if no user specified value, then use event default
if (val === undefined) {
val = ev[key];
}
used[key] = true;
args.push(val);
}
ev[init].apply(ev, args);
// webkit key event issue workaround
if (family === 'KeyboardEvent') {
ev = check_kb(ev, opts);
}
// attach remaining unused options to the object
for (var key in opts) {
if (!used[key]) {
ev[key] = opts[key];
}
}
return ev;
};
var legacy = function (type, opts) {
opts = opts || {};
var ev = doc.createEventObject();
ev.type = type;
for (var key in opts) {
if (opts[key] !== undefined) {
ev[key] = opts[key];
}
}
return ev;
};
// expose either the modern version of event generation or legacy
// depending on what we support
// avoids if statements in the code later
module.exports = doc.createEvent ? modern : legacy;
var initSignatures = require('./init.json');
var types = require('./types.json');
var typeOf = (function () {
var typs = {};
for (var key in types) {
var ts = types[key];
for (var i = 0; i < ts.length; i++) {
typs[ts[i]] = key;
}
}
return function (name) {
return typs[name] || 'Event';
};
})();
},{"./init.json":13,"./types.json":14}],13:[function(require,module,exports){
module.exports={
"initEvent" : [
"type",
"bubbles",
"cancelable"
],
"initUIEvent" : [
"type",
"bubbles",
"cancelable",
"view",
"detail"
],
"initMouseEvent" : [
"type",
"bubbles",
"cancelable",
"view",
"detail",
"screenX",
"screenY",
"clientX",
"clientY",
"ctrlKey",
"altKey",
"shiftKey",
"metaKey",
"button",
"relatedTarget"
],
"initMutationEvent" : [
"type",
"bubbles",
"cancelable",
"relatedNode",
"prevValue",
"newValue",
"attrName",
"attrChange"
],
"initKeyboardEvent" : [
"type",
"bubbles",
"cancelable",
"view",
"ctrlKey",
"altKey",
"shiftKey",
"metaKey",
"keyCode",
"charCode"
],
"initKeyEvent" : [
"type",
"bubbles",
"cancelable",
"view",
"ctrlKey",
"altKey",
"shiftKey",
"metaKey",
"keyCode",
"charCode"
]
}
},{}],14:[function(require,module,exports){
module.exports={
"MouseEvent" : [
"click",
"mousedown",
"mouseup",
"mouseover",
"mousemove",
"mouseout"
],
"KeyboardEvent" : [
"keydown",
"keyup",
"keypress"
],
"MutationEvent" : [
"DOMSubtreeModified",
"DOMNodeInserted",
"DOMNodeRemoved",
"DOMNodeRemovedFromDocument",
"DOMNodeInsertedIntoDocument",
"DOMAttrModified",
"DOMCharacterDataModified"
],
"HTMLEvents" : [
"load",
"unload",
"abort",
"error",
"select",
"change",
"submit",
"reset",
"focus",
"blur",
"resize",
"scroll"
],
"UIEvent" : [
"DOMFocusIn",
"DOMFocusOut",
"DOMActivate"
]
}
},{}],15:[function(require,module,exports){
function E () {
// Keep this empty so it's easier to inherit from
// (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
}
E.prototype = {
on: function (name, callback, ctx) {
var e = this.e || (this.e = {});
(e[name] || (e[name] = [])).push({
fn: callback,
ctx: ctx
});
return this;
},
once: function (name, callback, ctx) {
var self = this;
function listener () {
self.off(name, listener);
callback.apply(ctx, arguments);
};
listener._ = callback
return this.on(name, listener, ctx);
},
emit: function (name) {
var data = [].slice.call(arguments, 1);
var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
var i = 0;
var len = evtArr.length;
for (i; i < len; i++) {
evtArr[i].fn.apply(evtArr[i].ctx, data);
}
return this;
},
off: function (name, callback) {
var e = this.e || (this.e = {});
var evts = e[name];
var liveEvents = [];
if (evts && callback) {
for (var i = 0, len = evts.length; i < len; i++) {
if (evts[i].fn !== callback && evts[i].fn._ !== callback)
liveEvents.push(evts[i]);
}
}
// Remove event from queue to prevent memory leak
// Suggested by https://github.com/lazd
// Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
(liveEvents.length)
? e[name] = liveEvents
: delete e[name];
return this;
}
};
module.exports = E;
},{}],16:[function(require,module,exports){
'use strict';
module.exports = function(source) {
return JSON.parse(JSON.stringify(source));
};
},{}],17:[function(require,module,exports){
'use strict';
var objectAssign = require('object-assign');
var Emitter = require('tiny-emitter');
var Lethargy = require('lethargy').Lethargy;
var support = require('./support');
var clone = require('./clone');
var bindAll = require('bindall-standalone');
var EVT_ID = 'virtualscroll';
module.exports = VirtualScroll;
var keyCodes = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
SPACE: 32
};
function VirtualScroll(options) {
bindAll(this, '_onWheel', '_onMouseWheel', '_onTouchStart', '_onTouchMove', '_onKeyDown');
this.el = window;
if (options && options.el) {
this.el = options.el;
delete options.el;
}
this.options = objectAssign({
mouseMultiplier: 1,
touchMultiplier: 2,
firefoxMultiplier: 15,
keyStep: 120,
preventTouch: false,
unpreventTouchClass: 'vs-touchmove-allowed',
limitInertia: false
}, options);
if (this.options.limitInertia) this._lethargy = new Lethargy();
this._emitter = new Emitter();
this._event = {
y: 0,
x: 0,
deltaX: 0,
deltaY: 0
};
this.touchStartX = null;
this.touchStartY = null;
this.bodyTouchAction = null;
if (this.options.passive !== undefined) {
this.listenerOptions = {passive: this.options.passive};
}
}
VirtualScroll.prototype._notify = function(e) {
var evt = this._event;
evt.x += evt.deltaX;
evt.y += evt.deltaY;
this._emitter.emit(EVT_ID, {
x: evt.x,
y: evt.y,
deltaX: evt.deltaX,
deltaY: evt.deltaY,
originalEvent: e
});
};
VirtualScroll.prototype._onWheel = function(e) {
var options = this.options;
if (this._lethargy && this._lethargy.check(e) === false) return;
var evt = this._event;
// In Chrome and in Firefox (at least the new one)
evt.deltaX = e.wheelDeltaX || e.deltaX * -1;
evt.deltaY = e.wheelDeltaY || e.deltaY * -1;
// for our purpose deltamode = 1 means user is on a wheel mouse, not touch pad
// real meaning: https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent#Delta_modes
if(support.isFirefox && e.deltaMode == 1) {
evt.deltaX *= options.firefoxMultiplier;
evt.deltaY *= options.firefoxMultiplier;
}
evt.deltaX *= options.mouseMultiplier;
evt.deltaY *= options.mouseMultiplier;
this._notify(e);
};
VirtualScroll.prototype._onMouseWheel = function(e) {
if (this.options.limitInertia && this._lethargy.check(e) === false) return;
var evt = this._event;
// In Safari, IE and in Chrome if 'wheel' isn't defined
evt.deltaX = (e.wheelDeltaX) ? e.wheelDeltaX : 0;
evt.deltaY = (e.wheelDeltaY) ? e.wheelDeltaY : e.wheelDelta;
this._notify(e);
};
VirtualScroll.prototype._onTouchStart = function(e) {
var t = (e.targetTouches) ? e.targetTouches[0] : e;
this.touchStartX = t.pageX;
this.touchStartY = t.pageY;
};
VirtualScroll.prototype._onTouchMove = function(e) {
var options = this.options;
if(options.preventTouch
&& !e.target.classList.contains(options.unpreventTouchClass)) {
e.preventDefault();
}
var evt = this._event;
var t = (e.targetTouches) ? e.targetTouches[0] : e;
evt.deltaX = (t.pageX - this.touchStartX) * options.touchMultiplier;
evt.deltaY = (t.pageY - this.touchStartY) * options.touchMultiplier;
this.touchStartX = t.pageX;
this.touchStartY = t.pageY;
this._notify(e);
};
VirtualScroll.prototype._onKeyDown = function(e) {
var evt = this._event;
evt.deltaX = evt.deltaY = 0;
var windowHeight = window.innerHeight - 40
switch(e.keyCode) {
case keyCodes.LEFT:
case keyCodes.UP:
evt.deltaY = this.options.keyStep;
break;
case keyCodes.RIGHT:
case keyCodes.DOWN:
evt.deltaY = - this.options.keyStep;
break;
case keyCodes.SPACE && e.shiftKey:
evt.deltaY = windowHeight;
break;
case keyCodes.SPACE:
evt.deltaY = - windowHeight;
break;
default:
return;
}
this._notify(e);
};
VirtualScroll.prototype._bind = function() {
if(support.hasWheelEvent) this.el.addEventListener('wheel', this._onWheel, this.listenerOptions);
if(support.hasMouseWheelEvent) this.el.addEventListener('mousewheel', this._onMouseWheel, this.listenerOptions);
if(support.hasTouch) {
this.el.addEventListener('touchstart', this._onTouchStart, this.listenerOptions);
this.el.addEventListener('touchmove', this._onTouchMove, this.listenerOptions);
}
if(support.hasPointer && support.hasTouchWin) {
this.bodyTouchAction = document.body.style.msTouchAction;
document.body.style.msTouchAction = 'none';
this.el.addEventListener('MSPointerDown', this._onTouchStart, true);
this.el.addEventListener('MSPointerMove', this._onTouchMove, true);
}
if(support.hasKeyDown) document.addEventListener('keydown', this._onKeyDown);
};
VirtualScroll.prototype._unbind = function() {
if(support.hasWheelEvent) this.el.removeEventListener('wheel', this._onWheel);
if(support.hasMouseWheelEvent) this.el.removeEventListener('mousewheel', this._onMouseWheel);
if(support.hasTouch) {
this.el.removeEventListener('touchstart', this._onTouchStart);
this.el.removeEventListener('touchmove', this._onTouchMove);
}
if(support.hasPointer && support.hasTouchWin) {
document.body.style.msTouchAction = this.bodyTouchAction;
this.el.removeEventListener('MSPointerDown', this._onTouchStart, true);
this.el.removeEventListener('MSPointerMove', this._onTouchMove, true);
}
if(support.hasKeyDown) document.removeEventListener('keydown', this._onKeyDown);
};
VirtualScroll.prototype.on = function(cb, ctx) {
this._emitter.on(EVT_ID, cb, ctx);
var events = this._emitter.e;
if (events && events[EVT_ID] && events[EVT_ID].length === 1) this._bind();
};
VirtualScroll.prototype.off = function(cb, ctx) {
this._emitter.off(EVT_ID, cb, ctx);
var events = this._emitter.e;
if (!events[EVT_ID] || events[EVT_ID].length <= 0) this._unbind();
};
VirtualScroll.prototype.reset = function() {
var evt = this._event;
evt.x = 0;
evt.y = 0;
};
VirtualScroll.prototype.destroy = function() {
this._emitter.off();
this._unbind();
};
},{"./clone":16,"./support":18,"bindall-standalone":4,"lethargy":9,"object-assign":10,"tiny-emitter":15}],18:[function(require,module,exports){
'use strict';
module.exports = (function getSupport() {
return {
hasWheelEvent: 'onwheel' in document,
hasMouseWheelEvent: 'onmousewheel' in document,
hasTouch: 'ontouchstart' in document,
hasTouchWin: navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1,
hasPointer: !!window.navigator.msPointerEnabled,
hasKeyDown: 'onkeydown' in document,
isFirefox: navigator.userAgent.indexOf('Firefox') > -1
};
})();
},{}]},{},[2]);
| baptistebriel/smooth-scrolling | demos/performances/build.js | JavaScript | mit | 45,174 |
<?php namespace App\Handlers\Events;
use App\Events\ContactRequest;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class SendContactSms {
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param ContactRequest $event
* @return void
*/
public function handle(ContactRequest $event)
{
//
}
}
| Grisou13/site | app/Handlers/Events/SendContactSms.php | PHP | mit | 436 |
var NAVTREEINDEX3 =
{
"d4/db5/array_8hpp.html":[3,0,1,11],
"d4/db5/array_8hpp.html#a0048463a9200ce90a34092d719fe9922":[3,0,1,11,1],
"d4/db5/array_8hpp.html#a311d0610601290b2bb98f1808fc56d24":[3,0,1,11,3],
"d4/db5/array_8hpp.html#a44c20174c4360e3d4ec9373839c493e2":[3,0,1,11,2],
"d4/db5/array_8hpp.html#a66c2e9bfacf2a266d988285089c50705":[3,0,1,11,5],
"d4/db5/array_8hpp.html#ae74917955a3fa69cd29c43493f75fef3":[3,0,1,11,4],
"d4/de8/classstd_1_1basic__string.html":[2,0,0,16],
"d4/de8/classstd_1_1basic__string.html#a048145b966ec41fbaa4714140308167a":[2,0,0,16,28],
"d4/de8/classstd_1_1basic__string.html#a11da29d044d50af12ad86730e077c349":[2,0,0,16,37],
"d4/de8/classstd_1_1basic__string.html#a155d2fa939e5c2c45b68db675a5fa86a":[2,0,0,16,6],
"d4/de8/classstd_1_1basic__string.html#a19700f17170ad1f72867c379b2d0d75e":[2,0,0,16,44],
"d4/de8/classstd_1_1basic__string.html#a1f4ccdd026fe166b90dd52cb7be634c9":[2,0,0,16,8],
"d4/de8/classstd_1_1basic__string.html#a26f9a2e19f6933f947bee0132e3aae81":[2,0,0,16,27],
"d4/de8/classstd_1_1basic__string.html#a366ac2380d95d352498c88278a7a9d8b":[2,0,0,16,24],
"d4/de8/classstd_1_1basic__string.html#a37d7594eca3b2c47b5f0bc2447a982c9":[2,0,0,16,34],
"d4/de8/classstd_1_1basic__string.html#a42961d0cef0f670eb1a2462a2b8f08c8":[2,0,0,16,15],
"d4/de8/classstd_1_1basic__string.html#a43bb85d9b8916f484babb7b92d10cb42":[2,0,0,16,42],
"d4/de8/classstd_1_1basic__string.html#a44aa7597b00eed7606f7952989ac6ed1":[2,0,0,16,21],
"d4/de8/classstd_1_1basic__string.html#a4a618a1d6343243652cc9123e6d26593":[2,0,0,16,4],
"d4/de8/classstd_1_1basic__string.html#a52b9d0b393063fdb59585f80ac803191":[2,0,0,16,5],
"d4/de8/classstd_1_1basic__string.html#a5339b8e4151978ad8f67fb23a1da93a7":[2,0,0,16,0],
"d4/de8/classstd_1_1basic__string.html#a55b6e4d56823c8de8ab5fbf9e33dfce5":[2,0,0,16,18],
"d4/de8/classstd_1_1basic__string.html#a56c4648661953fc5e9269b4a89ed7441":[2,0,0,16,33],
"d4/de8/classstd_1_1basic__string.html#a59f4cc8315d514e52ecdc743e0451e27":[2,0,0,16,41],
"d4/de8/classstd_1_1basic__string.html#a5f93368f7fb6a2874bf8da801aa526d1":[2,0,0,16,43],
"d4/de8/classstd_1_1basic__string.html#a617bd833ddf33273bb8049b83fc4b254":[2,0,0,16,1],
"d4/de8/classstd_1_1basic__string.html#a6d31b891369dbaa90962ecf4cddf078a":[2,0,0,16,40],
"d4/de8/classstd_1_1basic__string.html#a7ec81f393c688621e7857ace949111eb":[2,0,0,16,9],
"d4/de8/classstd_1_1basic__string.html#a8493d62f43e0ef6a8c18adc283618ee9":[2,0,0,16,36],
"d4/de8/classstd_1_1basic__string.html#a8db97eff295c3b6a6bf4631d6ec5dfdf":[2,0,0,16,23],
"d4/de8/classstd_1_1basic__string.html#a8e26341ef4a38db673b8a986d881824b":[2,0,0,16,31],
"d4/de8/classstd_1_1basic__string.html#a91a0362fdb3c542e2aa27c88d74370e3":[2,0,0,16,10],
"d4/de8/classstd_1_1basic__string.html#a9ae54e7e4d3f24e11e92bf28ab4e7555":[2,0,0,16,38],
"d4/de8/classstd_1_1basic__string.html#a9e4d69675aff6909e70935e4368ca859":[2,0,0,16,39],
"d4/de8/classstd_1_1basic__string.html#a9e89f6285c48714f17596dc9b5183def":[2,0,0,16,29],
"d4/de8/classstd_1_1basic__string.html#aa25030581cb9824576b8bee02eaba540":[2,0,0,16,17],
"d4/de8/classstd_1_1basic__string.html#aa40b7059ca42243c7bbb557bea09336c":[2,0,0,16,2],
"d4/de8/classstd_1_1basic__string.html#aa4b716dd9157b8dba708c56c89be5dc4":[2,0,0,16,26],
"d4/de8/classstd_1_1basic__string.html#aa5f40b761e880a93fd8c6c3db5c0df72":[2,0,0,16,35],
"d4/de8/classstd_1_1basic__string.html#aa97a7b633573d24a9944a57986800d71":[2,0,0,16,16],
"d4/de8/classstd_1_1basic__string.html#ab1b0a7a408203f0126955b874de27352":[2,0,0,16,7],
"d4/de8/classstd_1_1basic__string.html#ab2c981bafcfc423d2dd847c0e5fc35fd":[2,0,0,16,19],
"d4/de8/classstd_1_1basic__string.html#ab66e0321e01c4483cfbef4f845f0d35c":[2,0,0,16,32],
"d4/de8/classstd_1_1basic__string.html#ab8a99058684557be228b91b498e8a3e9":[2,0,0,16,12],
"d4/de8/classstd_1_1basic__string.html#ac04ce8c34135d3576f1f639c8917d138":[2,0,0,16,30],
"d4/de8/classstd_1_1basic__string.html#ac08e1b13601baa3477b970ebd35ebf99":[2,0,0,16,3],
"d4/de8/classstd_1_1basic__string.html#ac74c043d5388cc66d0f922526f4cd395":[2,0,0,16,22],
"d4/de8/classstd_1_1basic__string.html#ad0e792c2a8a518722c3e6fef0000e68f":[2,0,0,16,14],
"d4/de8/classstd_1_1basic__string.html#ad9e4f9545f7d760a0975a6c3c0a75a20":[2,0,0,16,13],
"d4/de8/classstd_1_1basic__string.html#ada7d4480f4f216b45818c2952042b3bd":[2,0,0,16,25],
"d4/de8/classstd_1_1basic__string.html#aebc27f736e76a55864f508077c3f56d8":[2,0,0,16,20],
"d4/de8/classstd_1_1basic__string.html#afec7916221582f548d4ed0656f871806":[2,0,0,16,11],
"d4/de8/classstd_1_1map.html":[2,0,0,111],
"d4/de8/classstd_1_1map.html#a2340c924a5187f1a63cfdf0687216763":[2,0,0,111,18],
"d4/de8/classstd_1_1map.html#a2c6eaa30025b6bbcbb0cfc5963ee237c":[2,0,0,111,8],
"d4/de8/classstd_1_1map.html#a3b6a55862b5d793f47b0023f53eab748":[2,0,0,111,6],
"d4/de8/classstd_1_1map.html#a4b6b2b79140050d718dc72d1f1c9f0ad":[2,0,0,111,5],
"d4/de8/classstd_1_1map.html#a58706f0166408a04c60bdba751d1a98d":[2,0,0,111,4],
"d4/de8/classstd_1_1map.html#a73ea071e7772e050444541652f732083":[2,0,0,111,1],
"d4/de8/classstd_1_1map.html#a873685a9110c9219265f1e3201282581":[2,0,0,111,3],
"d4/de8/classstd_1_1map.html#a8c523966f8bbd00039d0f2b5cc3c77e5":[2,0,0,111,19],
"d4/de8/classstd_1_1map.html#a8f93152ce41f03543187d01c98c034ff":[2,0,0,111,17],
"d4/de8/classstd_1_1map.html#a97bf18d62e8afe85c3739cbc62abbbc6":[2,0,0,111,14],
"d4/de8/classstd_1_1map.html#a9bcac17c36254c93e37f06d966d32773":[2,0,0,111,21],
"d4/de8/classstd_1_1map.html#aa77322ea3800895f483a5a863a2f9356":[2,0,0,111,10],
"d4/de8/classstd_1_1map.html#aa9af2db3e9feccee588c59852c389319":[2,0,0,111,0],
"d4/de8/classstd_1_1map.html#ab85e6b3f71a6cd66e4c7920f6b141423":[2,0,0,111,7],
"d4/de8/classstd_1_1map.html#ab8c8abbc1c9afb13828d3a04a46d9b4c":[2,0,0,111,11],
"d4/de8/classstd_1_1map.html#ac8005e666248dfa867980a0d2a7d433d":[2,0,0,111,12],
"d4/de8/classstd_1_1map.html#ac9e60107a51138e82a8a66d2c3bca0bf":[2,0,0,111,2],
"d4/de8/classstd_1_1map.html#ad4354abcb3f30dae394e199f1230d681":[2,0,0,111,16],
"d4/de8/classstd_1_1map.html#adf709df841b651865a6aa361ad6a9763":[2,0,0,111,15],
"d4/de8/classstd_1_1map.html#ae02b3d1d336a42ab76f5e187ae9ef5d4":[2,0,0,111,20],
"d4/de8/classstd_1_1map.html#ae82d0b4bd0fec70cc51778722e2d760a":[2,0,0,111,9],
"d4/de8/classstd_1_1map.html#ae9dcf18d95d45bef7b48ddf28503c60f":[2,0,0,111,13],
"d4/dfa/classstd_1_1fixed__sorted__vector.html":[2,0,0,40],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a2ce3d1d05f733abbbf1bf5b42707f51a":[2,0,0,40,4],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a3554132678255108808abcfb93cd9a6b":[2,0,0,40,14],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a3d1973321125b85937c51627cecf7526":[2,0,0,40,15],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a481527c0df696268826e6932ebce476e":[2,0,0,40,0],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a4d7c31d322d6b796ef3bc3a150d9e4b6":[2,0,0,40,3],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a5340ed31349b4ad6bc2010cece895c61":[2,0,0,40,8],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a5a3d349013a3a8b429c8c17d01fc3a73":[2,0,0,40,13],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a616d38b84b146a28959b47d3d3c457ca":[2,0,0,40,1],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a6a5879b6815b4d99155138bb46333a88":[2,0,0,40,6],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a71c9a896bf7d257a85c24d65789efa7d":[2,0,0,40,17],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a7827372b61d7a779057d11a2f2fc7287":[2,0,0,40,10],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a80357d89e033ef0e8213b3b14e675b61":[2,0,0,40,11],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a819e554776546c42857db0bb4fbc474c":[2,0,0,40,16],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#a8dd3ad604c8a45f3a514cedf70ed0c1d":[2,0,0,40,2],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#abab718a13944985143bc2a882aeea657":[2,0,0,40,7],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#ad3a09470b09ced0d1e9b2dfe4999dcb4":[2,0,0,40,9],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#ad55e670afba8c3b8a947c2007188ebe8":[2,0,0,40,12],
"d4/dfa/classstd_1_1fixed__sorted__vector.html#ad8536b6a839c0f97ed486f1e87871179":[2,0,0,40,5],
"d4/dff/classstd_1_1list.html":[2,0,0,106],
"d4/dff/classstd_1_1list.html#a012d703d9498bb5379aefab4cbd793fc":[2,0,0,106,10],
"d4/dff/classstd_1_1list.html#a068c5ba29eb4c5784417063041db9876":[2,0,0,106,26],
"d4/dff/classstd_1_1list.html#a11c4f88fd223f0d6f69e9812409148ac":[2,0,0,106,3],
"d4/dff/classstd_1_1list.html#a1b5cf608d0dfc92d253ad2b2c61ffe92":[2,0,0,106,4],
"d4/dff/classstd_1_1list.html#a25f54f28c1f8d88247acb96bdcea6816":[2,0,0,106,7],
"d4/dff/classstd_1_1list.html#a3131c7319678df9ca4a822a04cf7fb6c":[2,0,0,106,29],
"d4/dff/classstd_1_1list.html#a39dd6f17e8be7b52b109f62295528b5c":[2,0,0,106,2],
"d4/dff/classstd_1_1list.html#a3a37b706d3d0b2f13b2428e3ca1c699c":[2,0,0,106,1],
"d4/dff/classstd_1_1list.html#a3e9ec15c28ddebc1953662e58ec510ca":[2,0,0,106,19],
"d4/dff/classstd_1_1list.html#a3f6fac6aa256c5db949f84a0cd2efcac":[2,0,0,106,0],
"d4/dff/classstd_1_1list.html#a40e6feb7cf0b64094287e5827597da81":[2,0,0,106,8],
"d4/dff/classstd_1_1list.html#a41a418c3113d8c12fe012f774be80597":[2,0,0,106,24],
"d4/dff/classstd_1_1list.html#a4354c4728b382544e06fce4fc9bcc312":[2,0,0,106,20],
"d4/dff/classstd_1_1list.html#a551b830dafee1df29c1140d6f313a18b":[2,0,0,106,22],
"d4/dff/classstd_1_1list.html#a5ae1a58a6b82d43f7cd07e9109333d57":[2,0,0,106,14],
"d4/dff/classstd_1_1list.html#a5b9334ad92fc00e1e85ea89b0897abf1":[2,0,0,106,17],
"d4/dff/classstd_1_1list.html#a6ce0ffc7ab23dbf139a9cad3847cca65":[2,0,0,106,25],
"d4/dff/classstd_1_1list.html#a79d4760b4b044e86ccc18f418c2dfbd5":[2,0,0,106,18],
"d4/dff/classstd_1_1list.html#a7ea2991023c95d6082a982639d589122":[2,0,0,106,16],
"d4/dff/classstd_1_1list.html#a8309c19812be5d7699bae2cb74b23498":[2,0,0,106,6],
"d4/dff/classstd_1_1list.html#a845d0da013d055fa9d8a5fba3c83451f":[2,0,0,106,12],
"d4/dff/classstd_1_1list.html#a9016e842ec79a98cfbe4af8253025cda":[2,0,0,106,21],
"d4/dff/classstd_1_1list.html#a9e4100a74107d8bfdf64836fd395c428":[2,0,0,106,23],
"d4/dff/classstd_1_1list.html#aa2a48b9d9d42da5c02daeecaa24f1f6b":[2,0,0,106,11],
"d4/dff/classstd_1_1list.html#acad7862b982e5d322e4f43256e64094c":[2,0,0,106,27],
"d4/dff/classstd_1_1list.html#adce674f11895530210a08dd9feb8221f":[2,0,0,106,9],
"d4/dff/classstd_1_1list.html#adf28a3cd2d000c2e9dbb2f31d140189b":[2,0,0,106,28],
"d4/dff/classstd_1_1list.html#ae9e3042311db99b0ed187cf26bcedb09":[2,0,0,106,30],
"d4/dff/classstd_1_1list.html#aec0f8c316d3702cf37f24968429eec63":[2,0,0,106,15],
"d4/dff/classstd_1_1list.html#af24365dafd4b435765afc393959c72da":[2,0,0,106,5],
"d4/dff/classstd_1_1list.html#afd9bdd4dc99526ea4f79c9bf5cb9c006":[2,0,0,106,13],
"d5/d05/classstd_1_1ramakrishna.html":[2,0,0,127],
"d5/d05/classstd_1_1ramakrishna.html#a6441f28b4ef0e44eb62726b5c61ba8e0":[2,0,0,127,1],
"d5/d05/classstd_1_1ramakrishna.html#aa74c6cbb95ea33a3f5343a91f34004cb":[2,0,0,127,0],
"d5/d27/applications__events_8hpp.html":[3,0,1,9],
"d5/d2c/smath_8hpp.html":[3,0,1,62],
"d5/d38/classstd_1_1independent__bits__engine.html":[2,0,0,59],
"d5/d38/classstd_1_1independent__bits__engine.html#a1daa4f3fdd1c4a805931b678d3fae5fe":[2,0,0,59,3],
"d5/d38/classstd_1_1independent__bits__engine.html#a32f151de85e10db3c7818333e543d1cb":[2,0,0,59,5],
"d5/d38/classstd_1_1independent__bits__engine.html#a3f7b409af91a4364b2adca735cb6f34a":[2,0,0,59,4],
"d5/d38/classstd_1_1independent__bits__engine.html#a43d68292f4b0693e304146b9a32ddcb3":[2,0,0,59,2],
"d5/d38/classstd_1_1independent__bits__engine.html#a569ea2356722f0905ea3abb74bb2cd6b":[2,0,0,59,1],
"d5/d38/classstd_1_1independent__bits__engine.html#a5bf120f126dd5ca1964d01a4ce8d5bef":[2,0,0,59,6],
"d5/d38/classstd_1_1independent__bits__engine.html#a5d7b0d9168fd124a290e25ea93541c96":[2,0,0,59,8],
"d5/d38/classstd_1_1independent__bits__engine.html#a60306c9881c5ce4dc0d055d32571ac03":[2,0,0,59,9],
"d5/d38/classstd_1_1independent__bits__engine.html#a7ec88d4d053d1852f3fe16f5f8610365":[2,0,0,59,0],
"d5/d38/classstd_1_1independent__bits__engine.html#af31e73ded39f92a9a9c714092f6a6556":[2,0,0,59,7],
"d5/d40/structstd_1_1internal_1_1slist__base__node.html":[2,0,0,1,7],
"d5/d40/structstd_1_1internal_1_1slist__base__node.html#a0e1fe1f53aeebb7d860d8630a02d71ec":[2,0,0,1,7,0],
"d5/d40/structstd_1_1internal_1_1slist__base__node.html#a3ad27932e24383eba50bf6e8ddefb9d9":[2,0,0,1,7,4],
"d5/d40/structstd_1_1internal_1_1slist__base__node.html#a5059f904e47e8ee44777fd9f8026efb8":[2,0,0,1,7,2],
"d5/d40/structstd_1_1internal_1_1slist__base__node.html#a9c43ac315223c45502b3e85c040d4a12":[2,0,0,1,7,1],
"d5/d40/structstd_1_1internal_1_1slist__base__node.html#aad3c6a04ad23efc497a7a5a1b576b103":[2,0,0,1,7,3],
"d5/d40/structstd_1_1internal_1_1slist__base__node.html#ab51c452c73a63bded6db92d617ac441e":[2,0,0,1,7,5],
"d5/d46/classstd_1_1event.html":[2,0,0,31],
"d5/d46/classstd_1_1event.html#a2555ea55a19f7438c11b448a4da310be":[2,0,0,31,0],
"d5/d46/classstd_1_1event.html#a3127439e3b1ae53ff82ffbd6eb1cdb74":[2,0,0,31,1],
"d5/d46/classstd_1_1event.html#a60162e40f032fd335c8f63923b4ef002":[2,0,0,31,2],
"d5/d46/classstd_1_1event.html#a650674261758e63ccde58cd585caef81":[2,0,0,31,4],
"d5/d46/classstd_1_1event.html#ae5bc638a246c98040e8ecfa64836f029":[2,0,0,31,5],
"d5/d46/classstd_1_1event.html#ae9459294918a688d5b389ed80b54cd58":[2,0,0,31,3],
"d5/d4b/classstd_1_1property.html":[2,0,0,125],
"d5/d4b/classstd_1_1property.html#a098f2afe0df9c5ce4506b335611ef53e":[2,0,0,125,3],
"d5/d4b/classstd_1_1property.html#a2b7254e0060ade9f44e65f3a4d71dd54":[2,0,0,125,1],
"d5/d4b/classstd_1_1property.html#a556273c46a8a9cbd32b5a05375c844cd":[2,0,0,125,0],
"d5/d4b/classstd_1_1property.html#aa2728918617e3d879fb41e58d7e53c24":[2,0,0,125,4],
"d5/d4b/classstd_1_1property.html#ae5ddf88013535b71302ec90518934549":[2,0,0,125,5],
"d5/d4b/classstd_1_1property.html#af5962d92265befccc38f8a426d11d58a":[2,0,0,125,2],
"d5/d51/buffer__allocator_8hpp.html":[3,0,1,15],
"d5/d61/allocator_8hpp.html":[3,0,1,7],
"d5/d61/allocator_8hpp.html#a3b4c7dfb17db51bb2753517543ccd37c":[3,0,1,7,2],
"d5/d61/allocator_8hpp.html#a9a2e8249bedcfb932780df5723e4ad9e":[3,0,1,7,1],
"d5/d64/classstd_1_1slist.html":[2,0,0,141],
"d5/d64/classstd_1_1slist.html#a04a69afc6847311533818dddfcdee97e":[2,0,0,141,4],
"d5/d64/classstd_1_1slist.html#a0b6782d4bcd7dc6971e8fbb42a6ad5ce":[2,0,0,141,12],
"d5/d64/classstd_1_1slist.html#a111d34dd3475c3d5b9247a70a85a30b2":[2,0,0,141,22],
"d5/d64/classstd_1_1slist.html#a140815ea1f9e91fe058f933f1ae8ed55":[2,0,0,141,6],
"d5/d64/classstd_1_1slist.html#a14776d9cb4de5a6ab72e848ecd996a67":[2,0,0,141,10],
"d5/d64/classstd_1_1slist.html#a24c00ed63a3cd52377a77de14fe82652":[2,0,0,141,0],
"d5/d64/classstd_1_1slist.html#a2977308e228e97004773dee54c91b8b5":[2,0,0,141,13],
"d5/d64/classstd_1_1slist.html#a2bdb4b58fb7bdd268323735f0b33bbe6":[2,0,0,141,11],
"d5/d64/classstd_1_1slist.html#a3660e14a008464ecc897c731968ecd81":[2,0,0,141,19],
"d5/d64/classstd_1_1slist.html#a47166c64c1ddb6b559610a6c5f739c35":[2,0,0,141,17],
"d5/d64/classstd_1_1slist.html#a495f2218b4c1e39bda6258ee9dcb9db1":[2,0,0,141,20],
"d5/d64/classstd_1_1slist.html#a55470629e45e49d744d6eeab82331138":[2,0,0,141,7],
"d5/d64/classstd_1_1slist.html#a5fa39130f5ef432af64b224e50d99e72":[2,0,0,141,16],
"d5/d64/classstd_1_1slist.html#a61f6570d0e7572ac7d68e6e8967dd098":[2,0,0,141,5],
"d5/d64/classstd_1_1slist.html#a6ae4ca7dfc3e0bd5080033904ae10c71":[2,0,0,141,9],
"d5/d64/classstd_1_1slist.html#a7f3ce2758b964158f7b413bbe0e2c699":[2,0,0,141,21],
"d5/d64/classstd_1_1slist.html#a8f3d02d796e1b94127a8f9ec622e7f3a":[2,0,0,141,14],
"d5/d64/classstd_1_1slist.html#a9dc76627cfe746336df1102798406f04":[2,0,0,141,3],
"d5/d64/classstd_1_1slist.html#aae0f045e80a1691a8dc0daa4a64d7c53":[2,0,0,141,8],
"d5/d64/classstd_1_1slist.html#ab6b6cc8d2f6529076150d4b9d25421c1":[2,0,0,141,15],
"d5/d64/classstd_1_1slist.html#aca19a21368914a9c7d6ba9bfd2ca7e6e":[2,0,0,141,2],
"d5/d64/classstd_1_1slist.html#ace6af22ddd9ca105272f3a7e6c8dd90c":[2,0,0,141,18],
"d5/d64/classstd_1_1slist.html#af578a53dfee381d366b7a881720a07d4":[2,0,0,141,1],
"d5/d68/structstd_1_1is__polymorphic.html":[2,0,0,91],
"d5/d6c/atomic_8hpp.html":[3,0,1,12],
"d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3f":[3,0,1,12,1],
"d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa1b67b1f58b6dfe544dc067460fc47332":[3,0,1,12,1,5],
"d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa713961552f49e86e76c18d31568396d8":[3,0,1,12,1,1],
"d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa71556f1ad3429c75eb63c783a8c4390e":[3,0,1,12,1,0],
"d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa8b17a31dea30fef995ad75d19e1d85ee":[3,0,1,12,1,3],
"d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fad4338b1beb516c55566a43f41ad98560":[3,0,1,12,1,4],
"d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3faf4ba3803d19d0df46da5f0ae092ec08d":[3,0,1,12,1,2],
"d5/d78/structstd_1_1has__trivial__assign.html":[2,0,0,50],
"d5/d7a/classstd_1_1spinlock.html":[2,0,0,143],
"d5/d7a/classstd_1_1spinlock.html#a01429c40f6b8a27bc844f2e7073b5262":[2,0,0,143,0],
"d5/d7a/classstd_1_1spinlock.html#a1c0cb294f8af28dee9a63807a982b0ed":[2,0,0,143,6],
"d5/d7a/classstd_1_1spinlock.html#a48029fe3844ce4614875c893d20a970e":[2,0,0,143,8],
"d5/d7a/classstd_1_1spinlock.html#a6d010c79795532eac8503d24b5c14312":[2,0,0,143,1],
"d5/d7a/classstd_1_1spinlock.html#aa4caf15c25859ff4c23fcf4d978023d2":[2,0,0,143,3],
"d5/d7a/classstd_1_1spinlock.html#aa7b292b211c18e54849550385c9686cd":[2,0,0,143,2],
"d5/d7a/classstd_1_1spinlock.html#abb56d76aad9b5ab8d865d2a1691ebf03":[2,0,0,143,4],
"d5/d7a/classstd_1_1spinlock.html#aca18d2985a115a9f01ecd5aab1d6e12f":[2,0,0,143,7],
"d5/d7a/classstd_1_1spinlock.html#ae958fb96bc80bb084032600a3834bee4":[2,0,0,143,5],
"d5/d7e/structstd_1_1_sys_1_1mutex__struct.html":[2,0,0,151,0],
"d5/d88/structstd_1_1string__rep.html":[2,0,0,149],
"d5/d88/structstd_1_1string__rep.html#a2b07a0e88e164ee6406b2d1b9c6112c5":[2,0,0,149,0],
"d5/d88/structstd_1_1string__rep.html#a811ba699f524a07fca87451ec9b7bd9a":[2,0,0,149,5],
"d5/d88/structstd_1_1string__rep.html#a8c75d5341c4689f99f5357e4c7686edd":[2,0,0,149,6],
"d5/d88/structstd_1_1string__rep.html#a9703e294128a2ee943237571af5bedf0":[2,0,0,149,3],
"d5/d88/structstd_1_1string__rep.html#a976c3e095976d5098eafa69b61abc016":[2,0,0,149,1],
"d5/d88/structstd_1_1string__rep.html#abf1f5949512a20b084a87b276f65307c":[2,0,0,149,4],
"d5/d88/structstd_1_1string__rep.html#ad9d46356d507f4750b7f66b84d741bd2":[2,0,0,149,2],
"d5/da8/classstd_1_1lock__base.html":[2,0,0,107],
"d5/da8/classstd_1_1lock__base.html#a11a6fcfe95e53fcf7fa9ea1899795399":[2,0,0,107,2],
"d5/da8/classstd_1_1lock__base.html#a40542bbcdbabc587b03363ba1e6291c6":[2,0,0,107,0],
"d5/da8/classstd_1_1lock__base.html#a493cd8e3d4e08f82d1d64014153a032b":[2,0,0,107,3],
"d5/da8/classstd_1_1lock__base.html#ad2292c7877a72b49f0b59e08a7392c61":[2,0,0,107,1],
"d5/da8/classstd_1_1lock__base.html#ad5ab453523394a1c4b083b82766f555e":[2,0,0,107,4],
"d5/da8/ext_8hpp.html":[3,0,1,2,3],
"d5/da8/ext_8hpp.html#a75ea34a9c5a358814dc101008e25da63":[3,0,1,2,3,3],
"d5/da8/ext_8hpp.html#af2e3a1605007b6c1c31a698b0036a4af":[3,0,1,2,3,1],
"d5/da8/ext_8hpp.html#af627b3eb00e62d3b51160e17590d7cf8":[3,0,1,2,3,0],
"d5/da8/ext_8hpp.html#afedf386ab72c194c06eaeb3d5c7c650a":[3,0,1,2,3,2],
"d5/db6/structstd_1_1random__access__iterator__tag.html":[2,0,0,128],
"d5/dcf/classstd_1_1net_1_1socket.html":[2,0,0,3,8],
"d5/dcf/classstd_1_1net_1_1socket.html#a037eb0329c110f9978e504a2e9c6b850":[2,0,0,3,8,1],
"d5/dcf/classstd_1_1net_1_1socket.html#a057063eaf2e2ae7e3e2a68d36aea64fe":[2,0,0,3,8,18],
"d5/dcf/classstd_1_1net_1_1socket.html#a1145bdb7d5e964fd525f0635dcfd043f":[2,0,0,3,8,2],
"d5/dcf/classstd_1_1net_1_1socket.html#a2adbebe226bb20438587b8cd802a74a8":[2,0,0,3,8,7],
"d5/dcf/classstd_1_1net_1_1socket.html#a2c9643d14e3b5ff465bbc77391ae2bef":[2,0,0,3,8,3],
"d5/dcf/classstd_1_1net_1_1socket.html#a2e846460d29b2e9e9c15201245cf0ddb":[2,0,0,3,8,25],
"d5/dcf/classstd_1_1net_1_1socket.html#a3ce264c4d03e7d066e68ca59cd173baf":[2,0,0,3,8,17],
"d5/dcf/classstd_1_1net_1_1socket.html#a45060a1f5a96f3fc0b579b6a12e59686":[2,0,0,3,8,5],
"d5/dcf/classstd_1_1net_1_1socket.html#a49263efe677b0ed0b0db906d9b300835":[2,0,0,3,8,24],
"d5/dcf/classstd_1_1net_1_1socket.html#a4dee92e90c25b542d7a5dfd2777565c1":[2,0,0,3,8,16],
"d5/dcf/classstd_1_1net_1_1socket.html#a5138f6fa3c53e3b9c7acfd668fbe8080":[2,0,0,3,8,27],
"d5/dcf/classstd_1_1net_1_1socket.html#a514b503b24b99d2d281ca8ea6f062c35":[2,0,0,3,8,35],
"d5/dcf/classstd_1_1net_1_1socket.html#a545a96e10df6b5750fd7c5c525bc42ac":[2,0,0,3,8,21],
"d5/dcf/classstd_1_1net_1_1socket.html#a5a951a5a6482ed9ebff2b61092a045ff":[2,0,0,3,8,10],
"d5/dcf/classstd_1_1net_1_1socket.html#a6bb39f226ba79d033a9881ed2ab64fea":[2,0,0,3,8,36],
"d5/dcf/classstd_1_1net_1_1socket.html#a6fd737591a798c982ab10d1171863b11":[2,0,0,3,8,26],
"d5/dcf/classstd_1_1net_1_1socket.html#a799f9d5c22e3f0b1b9e9142b71dc548b":[2,0,0,3,8,22]
};
| RoseLeBlood/aSTL | docs/html/navtreeindex3.js | JavaScript | mit | 20,797 |
<?php
$msg['controller.annotation.var.missingclosebracket.title'] = "Une erreur a été détectée dans une annotation @Var.";
$msg['controller.annotation.var.missingclosebracket.text']="<p class=\"small\" style=\"color: red;\">Une erreur a été détectée dans une annotation @Var. Un crochet fermant (]) est manquant: '{0}'.</p>";
$msg['controller.annotation.var.unabletofindvalidator.title'] = "Une erreur a été détectée dans une annotation @Var.";
$msg['controller.annotation.var.unabletofindvalidator.text']="<p class=\"small\" style=\"color: red;\">Une erreur a été détectée dans une annotation @Var. Impossible de trouver le Validator '{0}'. Vérifier que cette classe existe et qu'elle est bien inclue dans le projet.</p>";
$msg['controller.annotation.var.urlorigintakesanint.title'] = "Une erreur a été détectée dans une annotation @Var.";
$msg['controller.annotation.var.urlorigintakesanint.text']="<p class=\"small\" style=\"color: red;\">Une erreur a été détectée dans une annotation @Var. Dans le paramètre 'origin', 'url' a été spécifié. Le paramètre pour 'url' Doit être un entier. 'origin' specifiée: {0}</p>";
$msg['controller.annotation.var.incorrectcommand.title'] = "Une erreur a été détectée dans une annotation @Var.";
$msg['controller.annotation.var.incorrectcommand.text'] = "<p class=\"small\" style=\"color: red;\">Une erreur a été détectée dans une annotation @Var. Dans le paramètre 'origin', seules les commandes request / session ou url sont acceptées. '{0}' a été passé en commande.</p>";
$msg['controller.annotation.var.validationexception.title'] = "Une erreur a été détectée.";
$msg['controller.annotation.var.validationexception.text'] = "Une erreur a été détectée lors de la validation d'un champ.";
$msg['controller.annotation.var.validationexception.debug.title'] = "Une erreur de validation a été détectée.";
$msg['controller.annotation.var.validationexception.debug.text'] = "Une erreur de validation a été détectée dans le validateur \"<i>{0}</i>\" pour l'argument \"<i>{1}</i>\" avec la valeur \"<i>{2}</i>\".";
$msg['error.500.title']="Une erreur s'est produite dans l'application.";
$msg['error.500.text']="Veuillez nous excuser pour la gène occasionée. Cliquez sur <a href='".ROOT_URL."'>ce lien</a> pour revenir à la page d'accueil.";
$msg['controller.incorrect.parameter.title'] = "Un paramètre n'a pas de valeur {0}->{1} /paramètre : {2}";
$msg['controller.incorrect.parameter.text'] = "Un paramètre n'a pas de valeur et n'a pas de valeur par défaut : {0}->{1} /paramètre : {2}";
$msg['404.back.on.tracks']="Rendez-vous sur la <a href='".ROOT_URL."'>page d'accueil</a> pour revenir sur le site!";
$msg['404.wrong.class']="L'URL semble contenir une erreur. ";
$msg['404.wrong.file']="L'URL semble contenir une erreur.";
$msg['404.wrong.method']="L'URL semble contenir une erreur.";
$msg['404.wrong.url']="L'URL semble contenir une erreur.";
$msg['controller.404.no.action'] = "Note pour les développeurs: le controlleur '{0}' a été trouvé, et la fonction '{1}' existe. Cependant, la fonction '{1}' ne possède pas d'annotation @Action. Elle ne peut donc pas être accédée par URL.";
$msg['controller.incorrect.parameter.title'] = "Les paramètres passés dans l'URL sont incorrects.";
$msg['controller.incorrect.parameter.text'] = "Les paramètres passés dans l'URL sont incorrects: L'URL correspond à l'action '{0}->{1}'. Cette action nécessite que le paramètre '{2}' soit spécifié.";
$msg['controller.annotation.var.validation.error'] = "Les paramètres passés dans l'URL sont incorrects: Le paramètre {1} devrait passer le validateur {0}, mais ce n'est pas le cas. Valeur passée: '{2}'.";
$msg['controller.annotation.var.validation.error.title'] = "Les paramètres passés dans l'URL sont incorrects";
?> | xhuberty/mvc.splash-common | resources/message_fr.php | PHP | mit | 3,850 |
#include <iostream>
using namespace std;
int n;
void print(int* s);
int* lastNode(int s, int *c);
int eval(int i, int k, int *c, int *t);
int main() {
cin >> n;
int *c = new int[2 * n]; // saving each node childs in two index like 1:{6,5}, 2:{0,0}...6:{4,0}
fill_n(c, 2 * n, 0);
int q = 0;
for (int i = 0; i < n - 1; i++) {
cin >> q;
if (c[(q - 1) * 2 + 1]) {
c[(q - 1) * 2] = i + 2;
} else {
c[(q - 1) * 2 + 1] = i + 2;
}
}
int *t = new int[n];
fill_n(t, n + 1, 0);
t[0] = 1;
eval(0, 0, c, t);
print(t);
int p;
for (int i = 0; i < n; i++) {
p = lastNode(i, c)[0] + 1;
int start = 0, end = 0;
for (int k = 0; k < n; k++) {
if (t[k] == i + 1) {
start = k + 1;
}
if (t[k] == p) {
end = k + 1;
break;
}
}
cout << i + 1 << ": " << start << " " << end << endl;
}
cin.get();
cin.ignore();
return 0;
}
int* lastNode(int s, int *c) {
int ln[2] = { s,1 };
if (!c[2 * s + 1]) return ln;
int k = 0; // key
int d = 1; // depth
int rk, rd, lk, ld;
int *w = lastNode(c[2 * s + 1] - 1, c);
rk = w[0];
rd = w[1];
if (c[2 * s]) {
w = lastNode(c[2 * s] - 1, c);
lk = w[0];
ld = w[1];
k = rd >= ld ? rk : lk;
d += rd + ld;
} else {
k = rk;
d += rd;
}
ln[0] = k;
ln[1] = d;
return ln;
}
int eval(int i, int k, int *c, int *t) {
if (i >= n) return 0;
int lc = 0; // number of sub tree nodes
if (c[2 * k]) {
t[i + 1] = c[k];
lc = eval(i + 1, c[2 * k] - 1, c, t);
}
if (c[2 * k + 1]) {
i += lc;
t[i + 1] = c[2 * k + 1];
lc += eval(i + 1, c[2 * k + 1] - 1, c, t);
} else {
t[i] = k + 1;
}
return lc + 1;
}
void print(int* s) {
for (int i = 0; s[i]; i++) {
cout << s[i] << " ";
}
cout << endl;
} | AminAliari/DS-Playground | HW4/5.cpp | C++ | mit | 1,714 |
<?php
declare(strict_types=1);
/*
* This file is part of Laravel Countries.
*
* (c) Brian Faust <hello@basecode.sh>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Artisanry\Tests\Countries;
use GrahamCampbell\TestBench\AbstractPackageTestCase;
abstract class AbstractTestCase extends AbstractPackageTestCase
{
/**
* Setup the application environment.
*
* @param \Illuminate\Contracts\Foundation\Application $app
*/
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
$this->setUpDatabase($this->app);
}
/**
* Get the service provider class.
*
* @param \Illuminate\Contracts\Foundation\Application $app
*
* @return string
*/
protected function getServiceProviderClass($app): string
{
return \Artisanry\Countries\ServiceProvider::class;
}
/**
* Set up the database.
*
* @param \Illuminate\Foundation\Application $app
*/
protected function setUpDatabase($app)
{
include_once __DIR__.'/../resources/migrations/create_countries_table.php';
(new \CreateCountriesTable())->up();
}
}
| DraperStudio/Laravel-Countries | tests/AbstractTestCase.php | PHP | mit | 1,273 |
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createMount, describeConformanceV5, act, createClientRender } from 'test/utils';
import FormControl, { formControlClasses as classes } from '@material-ui/core/FormControl';
import Input from '@material-ui/core/Input';
import Select from '@material-ui/core/Select';
import useFormControl from './useFormControl';
describe('<FormControl />', () => {
const render = createClientRender();
const mount = createMount();
function TestComponent(props) {
const context = useFormControl();
React.useEffect(() => {
props.contextCallback(context);
});
return null;
}
describeConformanceV5(<FormControl />, () => ({
classes,
inheritComponent: 'div',
render,
mount,
refInstanceof: window.HTMLDivElement,
testComponentPropWith: 'fieldset',
muiName: 'MuiFormControl',
testVariantProps: { margin: 'dense' },
skip: ['componentsProp'],
}));
describe('initial state', () => {
it('should have no margin', () => {
const { container } = render(<FormControl />);
const root = container.firstChild;
expect(root).not.to.have.class(classes.marginNormal);
expect(root).not.to.have.class(classes.sizeSmall);
});
it('can have the margin normal class', () => {
const { container } = render(<FormControl margin="normal" />);
const root = container.firstChild;
expect(root).to.have.class(classes.marginNormal);
expect(root).not.to.have.class(classes.sizeSmall);
});
it('can have the margin dense class', () => {
const { container } = render(<FormControl margin="dense" />);
const root = container.firstChild;
expect(root).to.have.class(classes.marginDense);
expect(root).not.to.have.class(classes.marginNormal);
});
it('should not be filled initially', () => {
const readContext = spy();
render(
<FormControl>
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('filled', false);
});
it('should not be focused initially', () => {
const readContext = spy();
render(
<FormControl>
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('focused', false);
});
});
describe('prop: required', () => {
it('should not apply it to the DOM', () => {
const { container } = render(<FormControl required />);
expect(container.firstChild).not.to.have.attribute('required');
});
});
describe('prop: disabled', () => {
it('will be unfocused if it gets disabled', () => {
const readContext = spy();
const { container, setProps } = render(
<FormControl>
<Input />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('focused', false);
act(() => {
container.querySelector('input').focus();
});
expect(readContext.args[1][0]).to.have.property('focused', true);
setProps({ disabled: true });
expect(readContext.args[2][0]).to.have.property('focused', false);
});
});
describe('prop: focused', () => {
it('should display input in focused state', () => {
const readContext = spy();
const { container } = render(
<FormControl focused>
<Input />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('focused', true);
container.querySelector('input').blur();
expect(readContext.args[0][0]).to.have.property('focused', true);
});
it('ignores focused when disabled', () => {
const readContext = spy();
render(
<FormControl focused disabled>
<Input />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.include({ disabled: true, focused: false });
});
});
describe('input', () => {
it('should be filled when a value is set', () => {
const readContext = spy();
render(
<FormControl>
<Input value="bar" />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('filled', true);
});
it('should be filled when a defaultValue is set', () => {
const readContext = spy();
render(
<FormControl>
<Input defaultValue="bar" />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('filled', true);
});
it('should not be adornedStart with an endAdornment', () => {
const readContext = spy();
render(
<FormControl>
<Input endAdornment={<div />} />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('adornedStart', false);
});
it('should be adornedStar with a startAdornment', () => {
const readContext = spy();
render(
<FormControl>
<Input startAdornment={<div />} />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('adornedStart', true);
});
});
describe('select', () => {
it('should not be adorned without a startAdornment', () => {
const readContext = spy();
render(
<FormControl>
<Select value="" />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0]).to.have.property('adornedStart', false);
});
it('should be adorned with a startAdornment', () => {
const readContext = spy();
render(
<FormControl>
<Select value="" input={<Input startAdornment={<div />} />} />
<TestComponent contextCallback={readContext} />
</FormControl>,
);
expect(readContext.args[0][0].adornedStart, true);
});
});
describe('useFormControl', () => {
const FormController = React.forwardRef((_, ref) => {
const formControl = useFormControl();
React.useImperativeHandle(ref, () => formControl, [formControl]);
return null;
});
const FormControlled = React.forwardRef(function FormControlled(props, ref) {
return (
<FormControl {...props}>
<FormController ref={ref} />
</FormControl>
);
});
describe('from props', () => {
it('should have the required prop from the instance', () => {
const formControlRef = React.createRef();
const { setProps } = render(<FormControlled ref={formControlRef} />);
expect(formControlRef.current).to.have.property('required', false);
setProps({ required: true });
expect(formControlRef.current).to.have.property('required', true);
});
it('should have the error prop from the instance', () => {
const formControlRef = React.createRef();
const { setProps } = render(<FormControlled ref={formControlRef} />);
expect(formControlRef.current).to.have.property('error', false);
setProps({ error: true });
expect(formControlRef.current).to.have.property('error', true);
});
it('should have the margin prop from the instance', () => {
const formControlRef = React.createRef();
const { setProps } = render(<FormControlled ref={formControlRef} />);
expect(formControlRef.current).to.have.property('size', 'medium');
setProps({ size: 'small' });
expect(formControlRef.current).to.have.property('size', 'small');
});
it('should have the fullWidth prop from the instance', () => {
const formControlRef = React.createRef();
const { setProps } = render(<FormControlled ref={formControlRef} />);
expect(formControlRef.current).to.have.property('fullWidth', false);
setProps({ fullWidth: true });
expect(formControlRef.current).to.have.property('fullWidth', true);
});
});
describe('callbacks', () => {
describe('onFilled', () => {
it('should set the filled state', () => {
const formControlRef = React.createRef();
render(<FormControlled ref={formControlRef} />);
expect(formControlRef.current).to.have.property('filled', false);
act(() => {
formControlRef.current.onFilled();
});
expect(formControlRef.current).to.have.property('filled', true);
act(() => {
formControlRef.current.onFilled();
});
expect(formControlRef.current).to.have.property('filled', true);
});
});
describe('onEmpty', () => {
it('should clean the filled state', () => {
const formControlRef = React.createRef();
render(<FormControlled ref={formControlRef} />);
act(() => {
formControlRef.current.onFilled();
});
expect(formControlRef.current).to.have.property('filled', true);
act(() => {
formControlRef.current.onEmpty();
});
expect(formControlRef.current).to.have.property('filled', false);
act(() => {
formControlRef.current.onEmpty();
});
expect(formControlRef.current).to.have.property('filled', false);
});
});
describe('handleFocus', () => {
it('should set the focused state', () => {
const formControlRef = React.createRef();
render(<FormControlled ref={formControlRef} />);
expect(formControlRef.current).to.have.property('focused', false);
act(() => {
formControlRef.current.onFocus();
});
expect(formControlRef.current).to.have.property('focused', true);
act(() => {
formControlRef.current.onFocus();
});
expect(formControlRef.current).to.have.property('focused', true);
});
});
describe('handleBlur', () => {
it('should clear the focused state', () => {
const formControlRef = React.createRef();
render(<FormControlled ref={formControlRef} />);
expect(formControlRef.current).to.have.property('focused', false);
act(() => {
formControlRef.current.onFocus();
});
expect(formControlRef.current).to.have.property('focused', true);
act(() => {
formControlRef.current.onBlur();
});
expect(formControlRef.current).to.have.property('focused', false);
act(() => {
formControlRef.current.onBlur();
});
expect(formControlRef.current).to.have.property('focused', false);
});
});
});
});
});
| callemall/material-ui | packages/material-ui/src/FormControl/FormControl.test.js | JavaScript | mit | 11,169 |
using Treefrog.Windows;
namespace Treefrog.Plugins.Tiles.UI
{
partial class DynamicBrushForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent ()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DynamicBrushForm));
this._buttonCancel = new System.Windows.Forms.Button();
this._buttonOk = new System.Windows.Forms.Button();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this._tilePanel = new Treefrog.Plugins.Tiles.UI.TilePoolPane();
this._toggleErase = new System.Windows.Forms.CheckBox();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this._toggleDraw = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this._tileSizeList = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this._prototypeList = new System.Windows.Forms.ComboBox();
this._nameField = new System.Windows.Forms.TextBox();
this._layerControl = new Treefrog.Windows.Controls.LayerGraphicsControl();
this._ViewportControl = new Treefrog.Windows.Controls.ViewportControl();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// _buttonCancel
//
this._buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this._buttonCancel.Location = new System.Drawing.Point(444, 430);
this._buttonCancel.Name = "_buttonCancel";
this._buttonCancel.Size = new System.Drawing.Size(75, 23);
this._buttonCancel.TabIndex = 1;
this._buttonCancel.Text = "Cancel";
this._buttonCancel.UseVisualStyleBackColor = true;
this._buttonCancel.Click += new System.EventHandler(this._buttonCancel_Click);
//
// _buttonOk
//
this._buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this._buttonOk.Enabled = false;
this._buttonOk.Location = new System.Drawing.Point(363, 430);
this._buttonOk.Name = "_buttonOk";
this._buttonOk.Size = new System.Drawing.Size(75, 23);
this._buttonOk.TabIndex = 2;
this._buttonOk.Text = "OK";
this._buttonOk.UseVisualStyleBackColor = true;
this._buttonOk.Click += new System.EventHandler(this._buttonOk_Click);
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this._tilePanel);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this._toggleErase);
this.splitContainer1.Panel2.Controls.Add(this._toggleDraw);
this.splitContainer1.Panel2.Controls.Add(this.groupBox1);
this.splitContainer1.Panel2.Controls.Add(this._buttonOk);
this.splitContainer1.Panel2.Controls.Add(this._buttonCancel);
this.splitContainer1.Size = new System.Drawing.Size(771, 465);
this.splitContainer1.SplitterDistance = 236;
this.splitContainer1.TabIndex = 0;
//
// _tilePanel
//
this._tilePanel.Dock = System.Windows.Forms.DockStyle.Fill;
this._tilePanel.Location = new System.Drawing.Point(0, 0);
this._tilePanel.Name = "_tilePanel";
this._tilePanel.Size = new System.Drawing.Size(236, 465);
this._tilePanel.TabIndex = 0;
//
// _toggleErase
//
this._toggleErase.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this._toggleErase.Appearance = System.Windows.Forms.Appearance.Button;
this._toggleErase.AutoCheck = false;
this._toggleErase.AutoSize = true;
this._toggleErase.FlatAppearance.BorderColor = System.Drawing.SystemColors.ControlDark;
this._toggleErase.FlatAppearance.CheckedBackColor = System.Drawing.SystemColors.GradientActiveCaption;
this._toggleErase.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._toggleErase.ImageIndex = 1;
this._toggleErase.ImageList = this.imageList1;
this._toggleErase.Location = new System.Drawing.Point(31, 430);
this._toggleErase.Name = "_toggleErase";
this._toggleErase.Size = new System.Drawing.Size(22, 22);
this._toggleErase.TabIndex = 8;
this._toggleErase.UseVisualStyleBackColor = true;
this._toggleErase.Click += new System.EventHandler(this._toggleErase_Click);
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "paint-brush16.png");
this.imageList1.Images.SetKeyName(1, "eraser16.png");
//
// _toggleDraw
//
this._toggleDraw.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this._toggleDraw.Appearance = System.Windows.Forms.Appearance.Button;
this._toggleDraw.AutoCheck = false;
this._toggleDraw.AutoSize = true;
this._toggleDraw.Checked = true;
this._toggleDraw.CheckState = System.Windows.Forms.CheckState.Checked;
this._toggleDraw.FlatAppearance.BorderColor = System.Drawing.SystemColors.ControlDark;
this._toggleDraw.FlatAppearance.CheckedBackColor = System.Drawing.SystemColors.GradientActiveCaption;
this._toggleDraw.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._toggleDraw.ImageIndex = 0;
this._toggleDraw.ImageList = this.imageList1;
this._toggleDraw.Location = new System.Drawing.Point(3, 430);
this._toggleDraw.Name = "_toggleDraw";
this._toggleDraw.Size = new System.Drawing.Size(22, 22);
this._toggleDraw.TabIndex = 7;
this._toggleDraw.UseVisualStyleBackColor = true;
this._toggleDraw.Click += new System.EventHandler(this._toggleDraw_Click);
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this._ViewportControl);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this._tileSizeList);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this._prototypeList);
this.groupBox1.Controls.Add(this._nameField);
this.groupBox1.Location = new System.Drawing.Point(3, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(516, 412);
this.groupBox1.TabIndex = 4;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Brush Detail";
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(288, 49);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(50, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Tile Size:";
//
// _tileSizeList
//
this._tileSizeList.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._tileSizeList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._tileSizeList.FormattingEnabled = true;
this._tileSizeList.Location = new System.Drawing.Point(379, 46);
this._tileSizeList.Name = "_tileSizeList";
this._tileSizeList.Size = new System.Drawing.Size(131, 21);
this._tileSizeList.TabIndex = 7;
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(288, 22);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(85, 13);
this.label2.TabIndex = 6;
this.label2.Text = "Brush Prototype:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 22);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(38, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Name:";
//
// _prototypeList
//
this._prototypeList.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._prototypeList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._prototypeList.FormattingEnabled = true;
this._prototypeList.Location = new System.Drawing.Point(379, 19);
this._prototypeList.Name = "_prototypeList";
this._prototypeList.Size = new System.Drawing.Size(131, 21);
this._prototypeList.TabIndex = 4;
//
// _nameField
//
this._nameField.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._nameField.Location = new System.Drawing.Point(80, 19);
this._nameField.Name = "_nameField";
this._nameField.Size = new System.Drawing.Size(177, 20);
this._nameField.TabIndex = 3;
//
// _layerControl
//
this._layerControl.CanvasAlignment = Treefrog.Presentation.CanvasAlignment.Center;
this._layerControl.Dock = System.Windows.Forms.DockStyle.Fill;
this._layerControl.HeightSynced = false;
this._layerControl.Location = new System.Drawing.Point(0, 0);
this._layerControl.Name = "_layerControl";
this._layerControl.Size = new System.Drawing.Size(487, 316);
this._layerControl.TabIndex = 0;
this._layerControl.Text = "layerControl1";
this._layerControl.WidthSynced = false;
//
// _ViewportControl
//
this._ViewportControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._ViewportControl.Control = this._layerControl;
this._ViewportControl.Location = new System.Drawing.Point(6, 73);
this._ViewportControl.Name = "_ViewportControl";
this._ViewportControl.Size = new System.Drawing.Size(504, 333);
this._ViewportControl.TabIndex = 9;
//
// DynamicBrushForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(771, 465);
this.Controls.Add(this.splitContainer1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "DynamicBrushForm";
this.Text = "Edit Dynamic Tile Brush";
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private Treefrog.Windows.Controls.LayerGraphicsControl _layerControl;
private System.Windows.Forms.Button _buttonCancel;
private System.Windows.Forms.Button _buttonOk;
private System.Windows.Forms.SplitContainer splitContainer1;
private TilePoolPane _tilePanel;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox _tileSizeList;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox _prototypeList;
private System.Windows.Forms.TextBox _nameField;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.CheckBox _toggleErase;
private System.Windows.Forms.CheckBox _toggleDraw;
private Treefrog.Windows.Controls.ViewportControl _ViewportControl;
}
} | jaquadro/Treefrog | Treefrog/Plugins/Tile/UI/DynamicBrushForm.Designer.cs | C# | mit | 15,313 |
const EventEmitter = require('events');
class MomentumEventEmitter extends EventEmitter {}
module.exports = MomentumEventEmitter;
| kylekatarnls/momentum | src/event/emitter.js | JavaScript | mit | 132 |
package com.xcysoft.framework.core.model.dbmeta;
/**
* 错误处理接口
*
* @author huangxin
*/
public interface IErrorHandler {
public abstract void onError(String s, Throwable throwable);
}
| 3203317/ppp | framework-core/src/main/java/com/xcysoft/framework/core/model/dbmeta/IErrorHandler.java | Java | mit | 201 |
<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Mall\Controller;
use OT\DataDictionary;
use Mall\Model;
/**
* 前台首页控制器
* 主要获取首页聚合数据
*/
class GoodsController extends HomeController {
//系统首页
public function index(){
$id = I('id') ? I('id') : 0;
$goods_detail = M("b_goods_info")->where(array('goods_id' => $id,'goods_status' => 1))->find();
if($goods_detail){
$goods_detail['details'] = htmlspecialchars_decode($goods_detail['details']);
$f = $this->getGoodsImg($id,800,800);
$this->assign('good_imgs',$f);
//地址联动
$this->assign('_address',getRegion());
//类目列表
$category = D('CategoryMall');
$goods_detail['category_name'] = $category->getLastCategory($goods_detail['category_id']);
$goods_detail['brandName'] = $this->getBrandName($goods_detail['brand_id']);
$this->assign('_goods_list',$category->getSameLevel($goods_detail['category_id']));
$this->assign('_goodsdetail',$goods_detail);
$this->assign('is_short_menu',1);
$this->display('index');
}else{
$this->error('此商品已下架!!!');
}
}
public function getregions(){
$parent_id = I("parent_id");
echo getRegion($parent_id,true);exit;
}
} | leekin666/yihengyun | Application/Mall/Controller/GoodsController.class.php | PHP | mit | 1,860 |
#include "Other.h"
namespace PluggableBot
{
namespace Other
{
std::string ReadFromPipe(HANDLE hPipe)
{
static const int BufferSize = 4096;
std::string content;
DWORD read;
CHAR buffer[BufferSize + 1];
BOOL success;
do
{
success = ReadFile(hPipe, buffer, BufferSize, &read, nullptr);
buffer[read] = 0;
content += buffer;
} while (success && read == BufferSize);
return content;
}
std::string CallSystemCommand(const std::string& command, const std::string& workingDirectory)
{
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
HANDLE hChildOutRead = nullptr, hChildOutWrite = nullptr;
if (!CreatePipe(&hChildOutRead, &hChildOutWrite, &saAttr, 0))
{
throw std::system_error(std::error_code(GetLastError(), std::system_category()), "Cannot create pipe.");
}
PROCESS_INFORMATION procInfo;
STARTUPINFOA startInfo;
ZeroMemory(&procInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory(&startInfo, sizeof(STARTUPINFO));
startInfo.cb = sizeof(STARTUPINFO);
startInfo.hStdOutput = hChildOutWrite;
startInfo.hStdError = hChildOutWrite;
startInfo.dwFlags |= STARTF_USESTDHANDLES;
auto success = CreateProcessA(nullptr, (char*)command.c_str(), nullptr, nullptr, TRUE, 0, nullptr,
workingDirectory.empty() ? nullptr : workingDirectory.c_str(),
&startInfo, &procInfo);
if (!success)
{
CloseHandle(hChildOutRead);
CloseHandle(hChildOutWrite);
throw std::system_error(std::error_code(GetLastError(), std::system_category()), "Cannot start process.");
}
WaitForSingleObject(procInfo.hProcess, INFINITE);
CloseHandle(procInfo.hProcess);
CloseHandle(procInfo.hThread);
std::string message = ReadFromPipe(hChildOutRead);
CloseHandle(hChildOutRead);
CloseHandle(hChildOutWrite);
return message;
}
std::string FormatError(DWORD code)
{
WCHAR* wideMessage;
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
code,
MAKELANGID(LANG_POLISH, SUBLANG_POLISH_POLAND),
(LPWSTR)&wideMessage,
0, nullptr);
std::string converted = WideCharToUTF8(wideMessage);
LocalFree(wideMessage);
return converted;
}
std::string WideCharToUTF8(const wchar_t* str)
{
int length = WideCharToMultiByte(CP_UTF8, 0, str, -1, nullptr, 0, nullptr, nullptr);
char* message = new char[length + 1];
message[length] = 0;
WideCharToMultiByte(CP_UTF8, 0, str, -1, message, length, nullptr, nullptr);
std::string converted = message;
delete[] message;
return converted;
}
std::shared_ptr<wchar_t> UTF8ToWideString(const std::string& str)
{
wchar_t* message = new wchar_t[str.length() + 1];
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), message, str.length());
message[len] = 0;
return std::shared_ptr<wchar_t>(message, std::default_delete<wchar_t[]>());
}
}
} | jakubfijalkowski/pluggablebot | PluggableBot/Other.cpp | C++ | mit | 3,040 |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
inspected_dict = {}
for i, num in enumerate(nums):
try:
j = inspected_dict[num]
return j+1, i+1
except KeyError:
inspected_dict[target-num] = i | chenjiancan/LeetCodeSolutions | src/two_sum/two_sum.py | Python | mit | 414 |
/*
* Copyright 2002-2016 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.springframework.aop.framework.autoproxy;
import java.util.ArrayList;
import java.util.List;
import org.springframework.aop.TargetSource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.Assert;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;
/**
* Auto proxy creator that identifies beans to proxy via a list of names.
* Checks for direct, "xxx*", and "*xxx" matches.
*
* <p>For configuration details, see the javadoc of the parent class
* AbstractAutoProxyCreator. Typically, you will specify a list of
* interceptor names to apply to all identified beans, via the
* "interceptorNames" property.
*
* @author Juergen Hoeller
* @since 10.10.2003
* @see #setBeanNames
* @see #isMatch
* @see #setInterceptorNames
* @see AbstractAutoProxyCreator
*/
@SuppressWarnings("serial")
public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {
private List<String> beanNames;
/**
* Set the names of the beans that should automatically get wrapped with proxies.
* A name can specify a prefix to match by ending with "*", e.g. "myBean,tx*"
* will match the bean named "myBean" and all beans whose name start with "tx".
* <p><b>NOTE:</b> In case of a FactoryBean, only the objects created by the
* FactoryBean will get proxied. This default behavior applies as of Spring 2.0.
* If you intend to proxy a FactoryBean instance itself (a rare use case, but
* Spring 1.2's default behavior), specify the bean name of the FactoryBean
* including the factory-bean prefix "&": e.g. "&myFactoryBean".
* @see org.springframework.beans.factory.FactoryBean
* @see org.springframework.beans.factory.BeanFactory#FACTORY_BEAN_PREFIX
*/
public void setBeanNames(String... beanNames) {
Assert.notEmpty(beanNames, "'beanNames' must not be empty");
this.beanNames = new ArrayList<>(beanNames.length);
for (String mappedName : beanNames) {
this.beanNames.add(StringUtils.trimWhitespace(mappedName));
}
}
/**
* Identify as bean to proxy if the bean name is in the configured list of names.
*/
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
if (this.beanNames != null) {
for (String mappedName : this.beanNames) {
if (FactoryBean.class.isAssignableFrom(beanClass)) {
if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
continue;
}
mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
if (isMatch(beanName, mappedName)) {
return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
}
BeanFactory beanFactory = getBeanFactory();
if (beanFactory != null) {
String[] aliases = beanFactory.getAliases(beanName);
for (String alias : aliases) {
if (isMatch(alias, mappedName)) {
return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
}
}
}
}
}
return DO_NOT_PROXY;
}
/**
* Return if the given bean name matches the mapped name.
* <p>The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches,
* as well as direct equality. Can be overridden in subclasses.
* @param beanName the bean name to check
* @param mappedName the name in the configured list of names
* @return if the names match
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*/
protected boolean isMatch(String beanName, String mappedName) {
return PatternMatchUtils.simpleMatch(mappedName, beanName);
}
}
| boggad/jdk9-sample | sample-catalog/spring-jdk9/src/spring.aop/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java | Java | mit | 4,235 |
package generator.model;
import generator.ParserEngine;
import generator.model.profile.Stereotype;
import generator.model.profile.UIClass;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class FMClass extends FMType {
private String visibility;
private List<FMProperty> properties = new ArrayList<FMProperty>();
private List<String> importedPackages = new ArrayList<String>();
private List<FMMethod> methods = new ArrayList<FMMethod>();
private List<FMConstraint> constraints = new ArrayList<FMConstraint>();
private String parentId = null;
private ArrayList<String> interfaceIds = new ArrayList<>();
private UIClass uIClass;
public FMClass(String name, String classPackage, String visibility) {
super(name, classPackage);
this.visibility = visibility;
}
public List<FMProperty> getProperties() {
return properties;
}
public Iterator<FMProperty> getPropertyIterator() {
return properties.iterator();
}
public void addProperty(FMProperty property) {
properties.add(property);
}
public int getPropertyCount() {
return properties.size();
}
public List<String> getImportedPackages() {
return importedPackages;
}
public Iterator<String> getImportedIterator() {
return importedPackages.iterator();
}
public void addImportedPackage(String importedPackage) {
importedPackages.add(importedPackage);
}
public int getImportedCount() {
return properties.size();
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public List<FMMethod> getMethods() {
return methods;
}
public void addMethod(FMMethod method) {
methods.add(method);
}
public String getParent() {
return ParserEngine.getType(parentId);
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getLowerName() {
String s = this.getName();
return s.substring(0, 1).toLowerCase() + s.substring(1);
}
public UIClass getUIClass() {
return uIClass;
}
public void addConstraint(FMConstraint constraint)
{
constraints.add(constraint);
}
public List<FMConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<FMConstraint> constraints) {
this.constraints = constraints;
}
public void addInterfaceId(String interfaceId) {
interfaceIds.add(interfaceId);
}
public ArrayList<String> getInterfaceIds() {
return interfaceIds;
}
public ArrayList<String> getInterfaces() {
ArrayList<String> interfaces = new ArrayList<String>();
for (String interfaceId : interfaceIds) {
interfaces.add(ParserEngine.getType(interfaceId));
}
return interfaces;
}
@Override
public void addStereotype(Stereotype st) {
super.addStereotype(st);
if (st instanceof UIClass) {
uIClass = (UIClass) st;
}
}
public List<FMProperty> getLookupProperties() {
ArrayList<FMProperty> lookups = new ArrayList<FMProperty>();
for (FMProperty p : properties) {
if (p.getLookup() != null) {
lookups.add(p);
}
}
return lookups;
}
}
| vladimirivkovic/MBRS17 | XMI2NG/src/generator/model/FMClass.java | Java | mit | 3,157 |
package org.workcraft.plugins.circuit;
import org.workcraft.annotations.VisualClass;
import org.workcraft.dom.math.MathGroup;
import org.workcraft.dom.references.FileReference;
import org.workcraft.observation.PropertyChangedEvent;
import org.workcraft.utils.Hierarchy;
import java.util.ArrayList;
import java.util.Collection;
@VisualClass(VisualCircuitComponent.class)
public class CircuitComponent extends MathGroup {
public static final String PROPERTY_MODULE = "Module";
public static final String PROPERTY_IS_ENVIRONMENT = "Treat as environment";
public static final String PROPERTY_REFINEMENT = "Refinement";
private String module = "";
private boolean isEnvironment = false;
private FileReference refinement = null;
public void setModule(String value) {
if (value == null) value = "";
if (!value.equals(module)) {
module = value;
sendNotification(new PropertyChangedEvent(this, PROPERTY_MODULE));
}
}
public String getModule() {
return module;
}
public boolean isMapped() {
return (module != null) && !module.isEmpty();
}
public void setIsEnvironment(boolean value) {
if (isEnvironment != value) {
isEnvironment = value;
sendNotification(new PropertyChangedEvent(this, PROPERTY_IS_ENVIRONMENT));
}
}
public FileReference getRefinement() {
return refinement;
}
public void setRefinement(FileReference value) {
if (refinement != value) {
refinement = value;
sendNotification(new PropertyChangedEvent(this, PROPERTY_REFINEMENT));
}
}
public boolean hasRefinement() {
return (refinement != null) && (refinement.getFile() != null);
}
public boolean getIsEnvironment() {
return isEnvironment;
}
public Collection<Contact> getContacts() {
return Hierarchy.filterNodesByType(getChildren(), Contact.class);
}
public Collection<Contact> getInputs() {
ArrayList<Contact> result = new ArrayList<>();
for (Contact contact: getContacts()) {
if (contact.isInput()) {
result.add(contact);
}
}
return result;
}
public Collection<Contact> getOutputs() {
ArrayList<Contact> result = new ArrayList<>();
for (Contact contact: getContacts()) {
if (contact.isOutput()) {
result.add(contact);
}
}
return result;
}
public Contact getFirstInput() {
Contact result = null;
for (Contact contact: getContacts()) {
if (contact.isInput()) {
result = contact;
break;
}
}
return result;
}
public Contact getFirstOutput() {
Contact result = null;
for (Contact contact: getContacts()) {
if (contact.isOutput()) {
result = contact;
break;
}
}
return result;
}
public boolean isSingleInputSingleOutput() {
return (getContacts().size() == 2) && (getFirstInput() != null) && (getFirstOutput() != null);
}
}
| tuura/workcraft | workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitComponent.java | Java | mit | 3,235 |
////////////////////////////////////////////////////////////////////////////////
//
// secp256k1.cc
//
// Copyright (c) 2013 Eric Lombrozo
//
// 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.
//
// Some portions taken from bitcoin/bitcoin,
// Copyright (c) 2009-2013 Satoshi Nakamoto, the Bitcoin developers
#include "secp256k1.h"
bool EC_KEY_regenerate_key(EC_KEY* eckey, BIGNUM* priv_key) {
if (!eckey) return false;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
bool rval = false;
EC_POINT* pub_key = NULL;
BN_CTX* ctx = BN_CTX_new();
if (!ctx) goto finish;
pub_key = EC_POINT_new(group);
if (!pub_key) goto finish;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) goto finish;
EC_KEY_set_private_key(eckey, priv_key);
EC_KEY_set_public_key(eckey, pub_key);
rval = true;
finish:
if (pub_key) EC_POINT_free(pub_key);
if (ctx) BN_CTX_free(ctx);
return rval;
}
secp256k1_key::secp256k1_key() {
pKey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (!pKey) {
throw std::runtime_error("secp256k1_key::secp256k1_key() : EC_KEY_new_by_curve_name failed.");
}
EC_KEY_set_conv_form(pKey, POINT_CONVERSION_COMPRESSED);
bSet = false;
}
secp256k1_key::~secp256k1_key() {
EC_KEY_free(pKey);
}
EC_KEY* secp256k1_key::newKey() {
if (!EC_KEY_generate_key(pKey)) {
throw std::runtime_error("secp256k1_key::newKey() : EC_KEY_generate_key failed.");
}
EC_KEY_set_conv_form(pKey, POINT_CONVERSION_COMPRESSED);
bSet = true;
return pKey;
}
bytes_t secp256k1_key::getPrivKey() const {
if (!bSet) {
throw std::runtime_error("secp256k1_key::getPrivKey() : key is not set.");
}
const BIGNUM* bn = EC_KEY_get0_private_key(pKey);
if (!bn) {
throw std::runtime_error("secp256k1_key::getPrivKey() : EC_KEY_get0_private_key failed.");
}
unsigned char privKey[32];
assert(BN_num_bytes(bn) <= 32);
BN_bn2bin(bn, privKey);
return bytes_t(privKey, privKey + 32);
}
EC_KEY* secp256k1_key::setPrivKey(const bytes_t& key)
{
BIGNUM* bn = BN_bin2bn(&key[0], key.size(), NULL);
if (!bn) {
throw std::runtime_error("secp256k1_key::setPrivKey() : BN_bin2bn failed.");
}
bool bFail = !EC_KEY_regenerate_key(pKey, bn);
BN_clear_free(bn);
if (bFail) {
throw std::runtime_error("secp256k1_key::setPrivKey() : EC_KEY_set_private_key failed.");
}
bSet = true;
return pKey;
}
bytes_t secp256k1_key::getPubKey() const
{
if (!bSet) {
throw std::runtime_error("secp256k1_key::getPubKey() : key is not set.");
}
int nSize = i2o_ECPublicKey(pKey, NULL);
if (nSize == 0) {
throw std::runtime_error("secp256k1_key::getPubKey() : i2o_ECPublicKey failed.");
}
bytes_t pubKey(nSize, 0);
unsigned char* pBegin = &pubKey[0];
if (i2o_ECPublicKey(pKey, &pBegin) != nSize) {
throw std::runtime_error("secp256k1_key::getPubKey() : i2o_ECPublicKey returned unexpected size.");
}
return pubKey;
}
bytes_t secp256k1_sign(const secp256k1_key& key, const bytes_t& data)
{
unsigned char signature[1024];
unsigned int nSize = 0;
if (!ECDSA_sign(0, (const unsigned char*)&data[0], data.size(), signature, &nSize, key.getKey())) {
throw std::runtime_error("secp256k1_sign(): ECDSA_sign failed.");
}
return bytes_t(signature, signature + nSize);
}
secp256k1_point::secp256k1_point()
{
init();
}
secp256k1_point::secp256k1_point(const secp256k1_point& source)
{
init();
if (!EC_GROUP_copy(group, source.group)) throw std::runtime_error("secp256k1_point::secp256k1_point(const secp256k1_point&) - EC_GROUP_copy failed.");
if (!EC_POINT_copy(point, source.point)) throw std::runtime_error("secp256k1_point::secp256k1_point(const secp256k1_point&) - EC_POINT_copy failed.");
}
secp256k1_point::secp256k1_point(const bytes_t& bytes)
{
init();
this->bytes(bytes);
}
secp256k1_point::~secp256k1_point()
{
if (point) EC_POINT_free(point);
if (group) EC_GROUP_free(group);
if (ctx) BN_CTX_free(ctx);
}
secp256k1_point& secp256k1_point::operator=(const secp256k1_point& rhs) {
if (!EC_GROUP_copy(group, rhs.group)) throw std::runtime_error("secp256k1_point::operator= - EC_GROUP_copy failed.");
if (!EC_POINT_copy(point, rhs.point)) throw std::runtime_error("secp256k1_point::operator= - EC_POINT_copy failed.");
return *this; // TODO(miket)
}
void secp256k1_point::bytes(const bytes_t& bytes)
{
std::string err;
EC_POINT* rval;
BIGNUM* bn = BN_bin2bn(&bytes[0], bytes.size(), NULL);
if (!bn) {
err = "BN_bin2bn failed.";
goto finish;
}
rval = EC_POINT_bn2point(group, bn, point, ctx);
if (!rval) {
err = "EC_POINT_bn2point failed.";
goto finish;
}
finish:
if (bn) BN_clear_free(bn);
if (!err.empty()) {
throw std::runtime_error(std::string("secp256k1_point::set() - ") + err);
}
}
bytes_t secp256k1_point::bytes() const
{
bytes_t bytes(33);
std::string err;
BIGNUM* rval;
BIGNUM* bn = BN_new();
if (!bn) {
err = "BN_new failed.";
goto finish;
}
rval = EC_POINT_point2bn(group, point, POINT_CONVERSION_COMPRESSED, bn, ctx);
if (!rval) {
err = "EC_POINT_point2bn failed.";
goto finish;
}
assert(BN_num_bytes(bn) == 33);
BN_bn2bin(bn, &bytes[0]);
finish:
if (bn) BN_clear_free(bn);
if (!err.empty()) {
throw std::runtime_error(std::string("secp256k1_point::get() - ") + err);
}
return bytes;
}
secp256k1_point& secp256k1_point::operator+=(const secp256k1_point& rhs)
{
if (!EC_POINT_add(group, point, point, rhs.point, ctx)) {
throw std::runtime_error("secp256k1_point::operator+= - EC_POINT_add failed.");
}
return *this; // TODO(miket)
}
secp256k1_point& secp256k1_point::operator*=(const bytes_t& rhs)
{
BIGNUM* bn = BN_bin2bn(&rhs[0], rhs.size(), NULL);
if (!bn) {
throw std::runtime_error("secp256k1_point::operator*= - BN_bin2bn failed.");
}
int rval = EC_POINT_mul(group, point, NULL, point, bn, ctx);
BN_clear_free(bn);
if (rval == 0) {
throw std::runtime_error("secp256k1_point::operator*= - EC_POINT_mul failed.");
}
return *this; // TODO(miket)
}
// Computes n*G + K where K is this and G is the group generator
void secp256k1_point::generator_mul(const bytes_t& n)
{
BIGNUM* bn = BN_bin2bn(&n[0], n.size(), NULL);
if (!bn) throw std::runtime_error("secp256k1_point::generator_mul - BN_bin2bn failed.");
int rval = EC_POINT_mul(group, point, bn, point, BN_value_one(), ctx);
BN_clear_free(bn);
if (rval == 0) throw std::runtime_error("secp256k1_point::generator_mul - EC_POINT_mul failed.");
}
void secp256k1_point::init()
{
std::string err;
group = NULL;
point = NULL;
ctx = NULL;
group = EC_GROUP_new_by_curve_name(NID_secp256k1);
if (!group) {
err = "EC_KEY_new_by_curve_name failed.";
goto finish;
}
point = EC_POINT_new(group);
if (!point) {
err = "EC_POINT_new failed.";
goto finish;
}
ctx = BN_CTX_new();
if (!ctx) {
err = "BN_CTX_new failed.";
goto finish;
}
return;
finish:
if (group) EC_GROUP_free(group);
if (point) EC_POINT_free(point);
throw std::runtime_error(std::string("secp256k1_point::init() - ") + err);
}
| sowbug/happynine | nacl_module/secp256k1.cc | C++ | mit | 8,140 |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Graphics.Animations
{
/// <summary>
/// Represents a generic, frame-based animation.
/// </summary>
public interface IAnimation
{
/// <summary>
/// The number of frames this animation has.
/// </summary>
int FrameCount { get; }
/// <summary>
/// True if the animation is playing, false otherwise.
/// </summary>
bool IsPlaying { get; set; }
/// <summary>
/// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing.
/// </summary>
bool Repeat { get; set; }
/// <summary>
/// Displays the frame with the given zero-based frame index.
/// </summary>
/// <param name="frameIndex">The zero-based index of the frame to display.</param>
void GotoFrame(int frameIndex);
}
}
| DrabWeb/osu-framework | osu.Framework/Graphics/Animations/IAnimation.cs | C# | mit | 1,111 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { ITextModel } from 'vs/editor/common/model';
import { URI } from 'vs/base/common/uri';
import { TextResourceEditorInput } from 'vs/workbench/common/editor/textResourceEditorInput';
import { TextResourceEditorModel } from 'vs/workbench/common/editor/textResourceEditorModel';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { workbenchInstantiationService, TestServiceAccessor, TestTextFileEditorModelManager } from 'vs/workbench/test/browser/workbenchTestServices';
import { toResource } from 'vs/base/test/common/utils';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { snapshotToString } from 'vs/workbench/services/textfile/common/textfiles';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { Event } from 'vs/base/common/event';
import { timeout } from 'vs/base/common/async';
import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput';
import { createTextBufferFactory } from 'vs/editor/common/model/textModel';
suite('Workbench - TextModelResolverService', () => {
let instantiationService: IInstantiationService;
let accessor: TestServiceAccessor;
let model: TextFileEditorModel;
setup(() => {
instantiationService = workbenchInstantiationService();
accessor = instantiationService.createInstance(TestServiceAccessor);
});
teardown(() => {
model?.dispose();
(<TextFileEditorModelManager>accessor.textFileService.files).dispose();
});
test('resolve resource', async () => {
const disposable = accessor.textModelResolverService.registerTextModelContentProvider('test', {
provideTextContent: async function (resource: URI): Promise<ITextModel | null> {
if (resource.scheme === 'test') {
let modelContent = 'Hello Test';
let languageSelection = accessor.modeService.create('json');
return accessor.modelService.createModel(modelContent, languageSelection, resource);
}
return null;
}
});
let resource = URI.from({ scheme: 'test', authority: null!, path: 'thePath' });
let input = instantiationService.createInstance(TextResourceEditorInput, resource, 'The Name', 'The Description', undefined, undefined);
const model = await input.resolve();
assert.ok(model);
assert.strictEqual(snapshotToString(((model as TextResourceEditorModel).createSnapshot()!)), 'Hello Test');
let disposed = false;
let disposedPromise = new Promise<void>(resolve => {
Event.once(model.onWillDispose)(() => {
disposed = true;
resolve();
});
});
input.dispose();
await disposedPromise;
assert.strictEqual(disposed, true);
disposable.dispose();
});
test('resolve file', async function () {
const textModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_resolver.txt'), 'utf8', undefined);
(<TestTextFileEditorModelManager>accessor.textFileService.files).add(textModel.resource, textModel);
await textModel.resolve();
const ref = await accessor.textModelResolverService.createModelReference(textModel.resource);
const model = ref.object;
const editorModel = model.textEditorModel;
assert.ok(editorModel);
assert.strictEqual(editorModel.getValue(), 'Hello Html');
let disposed = false;
Event.once(model.onWillDispose)(() => {
disposed = true;
});
ref.dispose();
await timeout(0); // due to the reference resolving the model first which is async
assert.strictEqual(disposed, true);
});
test('resolved dirty file eventually disposes', async function () {
const textModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_resolver.txt'), 'utf8', undefined);
(<TestTextFileEditorModelManager>accessor.textFileService.files).add(textModel.resource, textModel);
await textModel.resolve();
textModel.updateTextEditorModel(createTextBufferFactory('make dirty'));
const ref = await accessor.textModelResolverService.createModelReference(textModel.resource);
let disposed = false;
Event.once(textModel.onWillDispose)(() => {
disposed = true;
});
ref.dispose();
await timeout(0);
assert.strictEqual(disposed, false); // not disposed because model still dirty
textModel.revert();
await timeout(0);
assert.strictEqual(disposed, true); // now disposed because model got reverted
});
test('resolved dirty file does not dispose when new reference created', async function () {
const textModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_resolver.txt'), 'utf8', undefined);
(<TestTextFileEditorModelManager>accessor.textFileService.files).add(textModel.resource, textModel);
await textModel.resolve();
textModel.updateTextEditorModel(createTextBufferFactory('make dirty'));
const ref1 = await accessor.textModelResolverService.createModelReference(textModel.resource);
let disposed = false;
Event.once(textModel.onWillDispose)(() => {
disposed = true;
});
ref1.dispose();
await timeout(0);
assert.strictEqual(disposed, false); // not disposed because model still dirty
const ref2 = await accessor.textModelResolverService.createModelReference(textModel.resource);
textModel.revert();
await timeout(0);
assert.strictEqual(disposed, false); // not disposed because we got another ref meanwhile
ref2.dispose();
await timeout(0);
assert.strictEqual(disposed, true); // now disposed because last ref got disposed
});
test('resolve untitled', async () => {
const service = accessor.untitledTextEditorService;
const untitledModel = service.create();
const input = instantiationService.createInstance(UntitledTextEditorInput, untitledModel);
await input.resolve();
const ref = await accessor.textModelResolverService.createModelReference(input.resource);
const model = ref.object;
assert.strictEqual(untitledModel, model);
const editorModel = model.textEditorModel;
assert.ok(editorModel);
ref.dispose();
input.dispose();
model.dispose();
});
test('even loading documents should be refcounted', async () => {
let resolveModel!: Function;
let waitForIt = new Promise(resolve => resolveModel = resolve);
const disposable = accessor.textModelResolverService.registerTextModelContentProvider('test', {
provideTextContent: async (resource: URI): Promise<ITextModel> => {
await waitForIt;
let modelContent = 'Hello Test';
let languageSelection = accessor.modeService.create('json');
return accessor.modelService.createModel(modelContent, languageSelection, resource);
}
});
const uri = URI.from({ scheme: 'test', authority: null!, path: 'thePath' });
const modelRefPromise1 = accessor.textModelResolverService.createModelReference(uri);
const modelRefPromise2 = accessor.textModelResolverService.createModelReference(uri);
resolveModel();
const modelRef1 = await modelRefPromise1;
const model1 = modelRef1.object;
const modelRef2 = await modelRefPromise2;
const model2 = modelRef2.object;
const textModel = model1.textEditorModel;
assert.strictEqual(model1, model2, 'they are the same model');
assert(!textModel.isDisposed(), 'the text model should not be disposed');
modelRef1.dispose();
assert(!textModel.isDisposed(), 'the text model should still not be disposed');
let p1 = new Promise<void>(resolve => textModel.onWillDispose(resolve));
modelRef2.dispose();
await p1;
assert(textModel.isDisposed(), 'the text model should finally be disposed');
disposable.dispose();
});
});
| Microsoft/vscode | src/vs/workbench/services/textmodelResolver/test/browser/textModelResolverService.test.ts | TypeScript | mit | 8,018 |
#
# Copyright (c) 2009-2011 RightScale Inc
#
# 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.
#
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'lib', 'right_agent', 'core_payload_types'))
module RightScale
describe DevRepository do
it 'should serialize 9 parameters' do
DevRepository.new.serialized_members.count.should == 9
end
end
end
| rightscale/right_agent | spec/core_payload_types/dev_repository_spec.rb | Ruby | mit | 1,470 |
var http = require("http");
var path = require('path');
var fs = require('fs');
var mkdirp = require('mkdirp');
var pg = require('pg');
var exec = require('child_process').exec;
var sh = require("execSync")
var util = require('util');
var info = {"good_load":0,"bad_load":0,"no_data":0};
var password="transit";
var options = {
host: 'www.gtfs-data-exchange.com',
path: '/api/agencies'
};
http.get(options, function (http_res) {
//console.log(http_res);
var data = "";
http_res.on("data", function (chunk) {
data += chunk;
});
http_res.on("end", function () {
parseAgencies(JSON.parse(data).data);
});
})
.on('error', function(e) {
console.log(e);
console.log("Got error: " + e);
});
var parseAgencies = function(agencyList){
var validAgencyCount = 0;
var conString = "postgres://postgres:"+password+"@localhost:5432/gtfs";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('Could not connect to database', err);
}
//console.log(result.rows[0].theTime);
//output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
agencyList.forEach(function(agency){
if(agency['is_official'] && agency['country'] == 'United States'){
//console.log( agency['dataexchange_id']);
validAgencyCount++
var options = {
host: 'www.gtfs-data-exchange.com',
path: '/api/agency?agency='+agency['dataexchange_id']
};
http.get(options, function (http_res) {
//console.log(http_res);
var data = "";
http_res.on("data", function (chunk) {
data += chunk;
});
http_res.on("end", function () {
mkdirp(path.resolve(__dirname,"../gtfs/")+"/"+agency['dataexchange_id'], function(err){
if (err) console.error(err)
//else console.log('created dir '+agency['dataexchange_id']);
});
if(agency["is_official"] && agency['country'] === 'United States'){
//console.log( "Agency id: " + agency['dataexchange_id'],"File URL: " + "")
}
parseAgent(JSON.parse(data).data,agency,client);
});
})
.on('error', function(e) {
console.log(e);
console.log("Got error: " + e);
});
}
})//end for each agency;
//client.end();
});
console.log("Num Agencies:"+validAgencyCount);
console.log("done");
}
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close();
cb();
});
});
}
var gtfsdbLoad = function(schemaName,destinationStream){
var result = sh.exec("gtfsdb-load --database_url postgresql://postgres:"+password+"@localhost/gtfs --schema="+schemaName+" --is_geospatial "+destinationStream);
console.log('return code ' + result.code);
console.log('stdout + stderr ' + result.stdout);
}
var createSchema = function(client,schemaName){
var query = 'CREATE SCHEMA "'+schemaName+'" ';
client.query(query, function(err, result) { if(err) { return console.error('error running query:',query, err); }})
}
var writeAgency = function(agency){
var body = JSON.stringify(agency);
var post_options = {
hostname: "localhost",
port: 1337,
path: "/agency/create/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": body.length // Often this part is optional
}
}
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
post_req.write(body);
post_req.end();
}
var inAPI = function(dataexchange_id,cb){
var options = {
host: 'localhost',
port: 1337,
path: '/agency/?dataexchange_id='+dataexchange_id
};
http.get(options, function (http_res) {
//console.log(http_res);
var data = "";
http_res.on("data", function (chunk) {
data += chunk;
});
http_res.on("end", function () {
output =JSON.parse(data)
if(output.length > 0){
cb(true);
}else{
cb(false);
}
});
})
.on('error', function(e) {
console.log(e);
console.log("Got error: " + e);
});
}
var testQuery = function(client,schemaName,agency,destinationStream){
var query = 'select ST_AsGeoJSON(geom) as geo,route_id from "'+schemaName+'".routes where geom is not null';
client.query(query, function(err, result) {
if(err) {
//return console.error('error running query:',query, err);
info.no_data++;
console.log(util.inspect(info,false,null));
//client.query('DROP SCHEMA "'+schemaName+'"');
return console.log(schemaName+":No Table");
}
if(result.rows && result.rows.length > 0){
//console.log('error check '+util.inspect(result,false,null)+' '+schemaName);
if(JSON.parse(result.rows[0].geo) !== null){
agency['current_datafile'] = schemaName;
agency.is_official = 1;
//console.log('Writing '+agency.dataexchange_id)
//console.log(util.inspect(agency,false,null));
//writeAgency(agency);
inAPI(agency.dataexchange_id,function(exists){
if(exists){
console.log(agency.dataexchange_id+" exists.")
}else{
console.log(agency.dataexchange_id+" doesn't exist.")
writeAgency(agency);
}
});
//console.log(schemaName+": "+JSON.parse(result.rows[0].geo).coordinates[0][0]);
info.good_load++;
}else{
//client.query('DROP SCHEMA "'+schemaName+'"');
//console.log(schemaName+": No Geometry");
info.bad_load++;
//gtfsdbLoad(schemaName,destinationStream)
}
}else{
//client.query('DROP SCHEMA "'+schemaName+'"');
//console.log(schemaName+": No Rows");
info.bad_load++;
//gtfsdbLoad(schemaName,destinationStream)
}
//console.log(util.inspect(info,false,null));
})
}
var parseAgent = function(agent,agency, client){
var i = 0;
var house = agency.dataexchange_id;
agent.datafiles.forEach(function(datafile){
if(i == 0){
var fileNameOrig = agent["datafiles"][0].file_url;
var nameSplit = fileNameOrig.substr(29);
var schemaName = fileNameOrig.substr(29).split(".")[0];
var destinationStream = path.resolve(__dirname,"../gtfs/" + house + "/" + nameSplit);
testQuery(client,schemaName,agency,destinationStream);
//createSchema(client,schemaName);
//gtfsdbLoad(schemaName,destinationStream)
//download(agent["datafiles"][0].file_url,destinationStream,function(){});
}
i++;
})
//console.log("agent")
return agent["datafiles"][0].file_url;
}
| availabs/njtdm | admin/gtfs-update.js | JavaScript | mit | 7,667 |
<?php
namespace Subbly\Presenter\V1;
use Illuminate\Database\Eloquent\Collection;
use Subbly\Model\Order;
use Subbly\Presenter\Presenter;
use Subbly\Presenter\Entries;
use Subbly\Presenter\Entry;
use Subbly\Subbly;
class OrderPresenter extends Presenter
{
/**
* Get formated datas for a single entry.
*
* @param \Subbly\Model\Order $order
*
* @return array
*/
public function single($order)
{
$entry = new Entry($order);
$entry
->conditionalField('id', function () {
return Subbly::api('subbly.user')->hasAccess('subbly.backend.auth');
})
->field('uid')
->field('status')
->field('gateway')
->decimal('total_price', $order->total_price)
->integer('total_items', $order->total_items)
->decimal('shipping_cost', $order->shipping_cost)
->relationshipField('user', 'Subbly\\Presenter\\V1\\UserPresenter')
->relationshipField('billing_address', 'Subbly\\Presenter\\V1\\OrderAddressPresenter')
->relationshipField('shipping_address', 'Subbly\\Presenter\\V1\\OrderAddressPresenter')
->relationshipField('products', 'Subbly\\Presenter\\V1\\OrderProductPresenter')
->dateField('created_at')
->dateField('updated_at')
;
return $entry->toArray();
}
/**
* Get formated datas for a collection.
*
* @param \Subbly\Model\Collection $collection
*
* @return \Illuminate\Support\Collection
*/
public function collection(Collection $collection)
{
$entries = new Entries();
foreach ($collection as $order) {
$entry = new Entry($order);
$entry
->conditionalField('id', function () {
return Subbly::api('subbly.user')->hasAccess('subbly.backend.auth');
})
->field('uid')
->field('status')
->decimal('total_price', (float) $order->total_price)
->integer('total_items', (int) $order->total_items)
->decimal('shipping_cost', (float) $order->shipping_cost)
->relationshipField('user', 'Subbly\\Presenter\\V1\\UserPresenter')
->relationshipField('billing_address', 'Subbly\\Presenter\\V1\\OrderAddressPresenter')
->relationshipField('shipping_address', 'Subbly\\Presenter\\V1\\OrderAddressPresenter')
->relationshipField('products', 'Subbly\\Presenter\\V1\\OrderProductPresenter')
->dateField('created_at')
->dateField('updated_at')
;
$entries->addEntry($entry);
}
return $entries->toArray();
}
}
| subbly/framework | src/Subbly/Presenter/V1/OrderPresenter.php | PHP | mit | 2,802 |
<?php
namespace Petramas\MainBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Petramas\MainBundle\DataFixtures\ORM\LoadPetramasData;
use Petramas\MainBundle\Entity\Cliente as Cliente;
class LoadClienteData extends LoadPetramasData implements OrderedFixtureInterface
{
/**
* Main load function.
*
* @param Doctrine\Common\Persistence\ObjectManager $manager
*/
function load(ObjectManager $manager)
{
$clientes = $this->getModelFixtures();
// Now iterate thought all fixtures
foreach ($clientes['Cliente'] as $reference => $columns)
{
$cliente = new Cliente();
$cliente->setEstado($manager->merge($this->getReference('Estado_' . $columns['estado'])));
$cliente->setUsuario($manager->merge($this->getReference('Usuario_' . $columns['usuario'])));
$cliente->setRazonSocial($columns['razon_social']);
$cliente->setRuc($columns['ruc']);
$cliente->setDireccion($columns['direccion']);
$manager->persist($cliente);
// Add a reference to be able to use this object in others entities loaders
$this->addReference('Cliente_'. $reference, $cliente);
}
$manager->flush();
}
/**
* The main fixtures file for this loader.
*/
public function getModelFile()
{
return 'clientes';
}
/**
* The order in which these fixtures will be loaded.
*/
public function getOrder()
{
return 3;
}
} | CollDev/petramas | src/Petramas/MainBundle/DataFixtures/ORM/LoadClienteData.php | PHP | mit | 1,618 |
/*
* Copyright (C) 2014 Carlos González.
* All rights reserved.
*
* The software in this package is published under the terms of the MIT
* license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on Jul 17, 2014 by Carlos González
*/
package com.github.chuckbuckethead.cypher.keys;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
/**
* Asymmetric cryptography implementation of the <code>CryptoKey</code>
* interface using the RSA encryption algorithm.
*
* @author Carlos González
*/
public class RSAKey extends AbstractCryptoKey implements CryptoKey
{
private String publicKey;
private String privateKey;
// Ciphers
private transient AsymmetricBlockCipher encodeCipher;
private transient AsymmetricBlockCipher decodeCipher;
public static final int MINIMUM_KEY_SIZE = 512;
/**
* Default
*/
public RSAKey()
{
}
/**
* @param publicKey
* @param privateKey
*/
public RSAKey(String publicKey, String privateKey)
{
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* @return the privateKey
*/
public String getPrivateKey()
{
return privateKey;
}
/**
* @param privateKey
* the privateKey to set
*/
public void setPrivateKey(String privateKey)
{
this.privateKey = privateKey;
}
/**
* @return the publicKey
*/
public String getPublicKey()
{
return publicKey;
}
/**
* @param publicKey
* the publicKey to set
*/
public void setPublicKey(String publicKey)
{
this.publicKey = publicKey;
}
/*
* (non-Javadoc)
*
* @see com.github.chuckbuckethead.cypher.keys.CryptoKey#getAlgorithmName()
*/
public String getAlgorithmName()
{
return CryptoKey.RSA_ALGORITHM;
}
/*
* (non-Javadoc)
*
* @see com.github.chuckbuckethead.cypher.keys.AbstractCryptoKey#getEncryptCipher()
*/
@Override
protected Cipher getEncryptCipher()
{
throw new UnsupportedOperationException("This method should never be called.");
}
/*
* (non-Javadoc)
*
* @see com.github.chuckbuckethead.cypher.keys.AbstractCryptoKey#getDecryptCipher()
*/
@Override
protected Cipher getDecryptCipher()
{
throw new UnsupportedOperationException("This method should never be called.");
}
/*
* (non-Javadoc)
*
* @see
* com.github.chuckbuckethead.cypher.keys.AbstractCryptoKey#decryptBytes(java.lang
* .String)
*/
@Override
public synchronized byte[] decryptBytes(String base64Str)
{
byte[] bytes = null;
try
{
byte[] dec = getEncoder().decode(base64Str);
// Decrypt
bytes = getRSADecryptCipher().processBlock(dec, 0, dec.length);
}
catch (InvalidCipherTextException e)
{
e.printStackTrace();
}
return bytes;
}
/*
* (non-Javadoc)
*
* @see
* com.github.chuckbuckethead.cypher.keys.AbstractCryptoKey#encryptBytes(byte[])
*/
@Override
public synchronized String encryptBytes(byte[] bytes)
{
String encryptedStr = null;
try
{
// Encrypt
byte[] enc = getRSAEncryptCipher().processBlock(bytes, 0,
bytes.length);
// Encode bytes to base64 to get a string
encryptedStr = getEncoder().encode(enc);
}
catch (InvalidCipherTextException e)
{
e.printStackTrace();
}
return encryptedStr;
}
/**
* @return an RSA decryption cipher
*/
protected synchronized AsymmetricBlockCipher getRSADecryptCipher()
{
if (decodeCipher == null)
{
try
{
byte[] bytes = getEncoder().decode(privateKey);
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PrivateKey key = keyFactory.generatePrivate(privateKeySpec);
this.decodeCipher = new PKCS1Encoding(new RSABlindedEngine());
decodeCipher.init(false, generatePrivateKeyParameter((RSAPrivateKey) key));
}
catch (Exception e)
{
throw new RuntimeException("Error constructing Cipher: ", e);
}
}
return decodeCipher;
}
/**
* @param key
* @return
*/
private static RSAKeyParameters generatePrivateKeyParameter(
RSAPrivateKey key)
{
RSAKeyParameters parameters = null;
if (key instanceof RSAPrivateCrtKey)
{
RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) key;
parameters = new RSAPrivateCrtKeyParameters(crtKey.getModulus(),
crtKey.getPublicExponent(), crtKey.getPrivateExponent(),
crtKey.getPrimeP(), crtKey.getPrimeQ(),
crtKey.getPrimeExponentP(), crtKey.getPrimeExponentQ(),
crtKey.getCrtCoefficient());
}
else
{
parameters = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());
}
return parameters;
}
/**
* @return
*/
protected synchronized AsymmetricBlockCipher getRSAEncryptCipher()
{
if (encodeCipher == null)
{
try
{
byte[] bytes = getEncoder().decode(publicKey);
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PublicKey key = keyFactory.generatePublic(publicKeySpec);
this.encodeCipher = new PKCS1Encoding(new RSABlindedEngine());
encodeCipher.init(true, generatePublicKeyParameter((RSAPublicKey) key));
}
catch (Exception e)
{
throw new RuntimeException("Error constructing Cipher: ", e);
}
}
return encodeCipher;
}
/**
* @param key
* @return
*/
private static RSAKeyParameters generatePublicKeyParameter(RSAPublicKey key)
{
return new RSAKeyParameters(false, key.getModulus(), key.getPublicExponent());
}
} | chuckbuckethead/cypher | src/main/java/com/github/chuckbuckethead/cypher/keys/RSAKey.java | Java | mit | 6,215 |
// Copyright (c) 2015 SharpYaml - Alexandre Mutel
//
// 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.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Runtime.Serialization;
namespace SharpYaml
{
/// <summary>
/// Exception that is thrown when a semantic error is detected on a YAML stream.
/// </summary>
public class SemanticErrorException : YamlException
{
/// <summary>
/// Initializes a new instance of the <see cref="SemanticErrorException"/> class.
/// </summary>
public SemanticErrorException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SemanticErrorException"/> class.
/// </summary>
/// <param name="message">The message.</param>
public SemanticErrorException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SemanticErrorException"/> class.
/// </summary>
public SemanticErrorException(Mark start, Mark end, string message)
: base(start, end, message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SemanticErrorException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
public SemanticErrorException(string message, Exception inner)
: base(message, inner)
{
}
}
}
| SiliconStudio/SharpYaml | SharpYaml/SemanticErrorException.cs | C# | mit | 3,830 |
# frozen_string_literal: true
require "active_support/core_ext/enumerable"
require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/string/filters"
require "active_support/parameter_filter"
require "concurrent/map"
module ActiveRecord
module Core
extend ActiveSupport::Concern
included do
##
# :singleton-method:
#
# Accepts a logger conforming to the interface of Log4r which is then
# passed on to any new database connections made and which can be
# retrieved on both a class and instance level by calling +logger+.
class_attribute :logger, instance_writer: false
##
# :singleton-method:
#
# Specifies the job used to destroy associations in the background
class_attribute :destroy_association_async_job, instance_writer: false, instance_predicate: false, default: false
##
# Contains the database configuration - as is typically stored in config/database.yml -
# as an ActiveRecord::DatabaseConfigurations object.
#
# For example, the following database.yml...
#
# development:
# adapter: sqlite3
# database: db/development.sqlite3
#
# production:
# adapter: sqlite3
# database: db/production.sqlite3
#
# ...would result in ActiveRecord::Base.configurations to look like this:
#
# #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
# @name="primary", @config={adapter: "sqlite3", database: "db/development.sqlite3"}>,
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="production",
# @name="primary", @config={adapter: "sqlite3", database: "db/production.sqlite3"}>
# ]>
def self.configurations=(config)
@@configurations = ActiveRecord::DatabaseConfigurations.new(config)
end
self.configurations = {}
# Returns fully resolved ActiveRecord::DatabaseConfigurations object
def self.configurations
@@configurations
end
##
# :singleton-method:
# Force enumeration of all columns in SELECT statements.
# e.g. `SELECT first_name, last_name FROM ...` instead of `SELECT * FROM ...`
# This avoids +PreparedStatementCacheExpired+ errors when a column is added
# to the database while the app is running.
class_attribute :enumerate_columns_in_select_statements, instance_accessor: false, default: false
class_attribute :belongs_to_required_by_default, instance_accessor: false
class_attribute :strict_loading_by_default, instance_accessor: false, default: false
class_attribute :has_many_inversing, instance_accessor: false, default: false
class_attribute :default_connection_handler, instance_writer: false
class_attribute :default_role, instance_writer: false
class_attribute :default_shard, instance_writer: false
def self.application_record_class? # :nodoc:
if ActiveRecord.application_record_class
self == ActiveRecord.application_record_class
else
if defined?(ApplicationRecord) && self == ApplicationRecord
true
end
end
end
self.filter_attributes = []
def self.connection_handler
Thread.current.thread_variable_get(:ar_connection_handler) || default_connection_handler
end
def self.connection_handler=(handler)
Thread.current.thread_variable_set(:ar_connection_handler, handler)
end
def self.connection_handlers
if ActiveRecord.legacy_connection_handling
else
raise NotImplementedError, "The new connection handling does not support accessing multiple connection handlers."
end
@@connection_handlers ||= {}
end
def self.connection_handlers=(handlers)
if ActiveRecord.legacy_connection_handling
ActiveSupport::Deprecation.warn(<<~MSG)
Using legacy connection handling is deprecated. Please set
`legacy_connection_handling` to `false` in your application.
The new connection handling does not support `connection_handlers`
getter and setter.
Read more about how to migrate at: https://guides.rubyonrails.org/active_record_multiple_databases.html#migrate-to-the-new-connection-handling
MSG
else
raise NotImplementedError, "The new connection handling does not support multiple connection handlers."
end
@@connection_handlers = handlers
end
def self.asynchronous_queries_session # :nodoc:
asynchronous_queries_tracker.current_session
end
def self.asynchronous_queries_tracker # :nodoc:
Thread.current.thread_variable_get(:ar_asynchronous_queries_tracker) ||
Thread.current.thread_variable_set(:ar_asynchronous_queries_tracker, AsynchronousQueriesTracker.new)
end
# Returns the symbol representing the current connected role.
#
# ActiveRecord::Base.connected_to(role: :writing) do
# ActiveRecord::Base.current_role #=> :writing
# end
#
# ActiveRecord::Base.connected_to(role: :reading) do
# ActiveRecord::Base.current_role #=> :reading
# end
def self.current_role
if ActiveRecord.legacy_connection_handling
connection_handlers.key(connection_handler) || default_role
else
connected_to_stack.reverse_each do |hash|
return hash[:role] if hash[:role] && hash[:klasses].include?(Base)
return hash[:role] if hash[:role] && hash[:klasses].include?(connection_classes)
end
default_role
end
end
# Returns the symbol representing the current connected shard.
#
# ActiveRecord::Base.connected_to(role: :reading) do
# ActiveRecord::Base.current_shard #=> :default
# end
#
# ActiveRecord::Base.connected_to(role: :writing, shard: :one) do
# ActiveRecord::Base.current_shard #=> :one
# end
def self.current_shard
connected_to_stack.reverse_each do |hash|
return hash[:shard] if hash[:shard] && hash[:klasses].include?(Base)
return hash[:shard] if hash[:shard] && hash[:klasses].include?(connection_classes)
end
default_shard
end
# Returns the symbol representing the current setting for
# preventing writes.
#
# ActiveRecord::Base.connected_to(role: :reading) do
# ActiveRecord::Base.current_preventing_writes #=> true
# end
#
# ActiveRecord::Base.connected_to(role: :writing) do
# ActiveRecord::Base.current_preventing_writes #=> false
# end
def self.current_preventing_writes
if ActiveRecord.legacy_connection_handling
connection_handler.prevent_writes
else
connected_to_stack.reverse_each do |hash|
return hash[:prevent_writes] if !hash[:prevent_writes].nil? && hash[:klasses].include?(Base)
return hash[:prevent_writes] if !hash[:prevent_writes].nil? && hash[:klasses].include?(connection_classes)
end
false
end
end
def self.connected_to_stack # :nodoc:
if connected_to_stack = Thread.current.thread_variable_get(:ar_connected_to_stack)
connected_to_stack
else
connected_to_stack = Concurrent::Array.new
Thread.current.thread_variable_set(:ar_connected_to_stack, connected_to_stack)
connected_to_stack
end
end
def self.connection_class=(b) # :nodoc:
@connection_class = b
end
def self.connection_class # :nodoc
@connection_class ||= false
end
def self.connection_class? # :nodoc:
self.connection_class
end
def self.connection_classes # :nodoc:
klass = self
until klass == Base
break if klass.connection_class?
klass = klass.superclass
end
klass
end
def self.allow_unsafe_raw_sql # :nodoc:
ActiveSupport::Deprecation.warn("ActiveRecord::Base.allow_unsafe_raw_sql is deprecated and will be removed in Rails 7.0")
end
def self.allow_unsafe_raw_sql=(value) # :nodoc:
ActiveSupport::Deprecation.warn("ActiveRecord::Base.allow_unsafe_raw_sql= is deprecated and will be removed in Rails 7.0")
end
self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new
self.default_role = ActiveRecord.writing_role
self.default_shard = :default
def self.strict_loading_violation!(owner:, reflection:) # :nodoc:
case ActiveRecord.action_on_strict_loading_violation
when :raise
message = "`#{owner}` is marked for strict_loading. The `#{reflection.klass}` association named `:#{reflection.name}` cannot be lazily loaded."
raise ActiveRecord::StrictLoadingViolationError.new(message)
when :log
name = "strict_loading_violation.active_record"
ActiveSupport::Notifications.instrument(name, owner: owner, reflection: reflection)
end
end
end
module ClassMethods
def initialize_find_by_cache # :nodoc:
@find_by_statement_cache = { true => Concurrent::Map.new, false => Concurrent::Map.new }
end
def inherited(child_class) # :nodoc:
# initialize cache at class definition for thread safety
child_class.initialize_find_by_cache
unless child_class.base_class?
klass = self
until klass.base_class?
klass.initialize_find_by_cache
klass = klass.superclass
end
end
super
end
def find(*ids) # :nodoc:
# We don't have cache keys for this stuff yet
return super unless ids.length == 1
return super if block_given? || primary_key.nil? || scope_attributes?
id = ids.first
return super if StatementCache.unsupported_value?(id)
key = primary_key
statement = cached_find_by_statement(key) { |params|
where(key => params.bind).limit(1)
}
statement.execute([id], connection).first ||
raise(RecordNotFound.new("Couldn't find #{name} with '#{key}'=#{id}", name, key, id))
end
def find_by(*args) # :nodoc:
return super if scope_attributes?
hash = args.first
return super unless Hash === hash
hash = hash.each_with_object({}) do |(key, value), h|
key = key.to_s
key = attribute_aliases[key] || key
return super if reflect_on_aggregation(key)
reflection = _reflect_on_association(key)
if !reflection
value = value.id if value.respond_to?(:id)
elsif reflection.belongs_to? && !reflection.polymorphic?
key = reflection.join_foreign_key
pkey = reflection.join_primary_key
value = value.public_send(pkey) if value.respond_to?(pkey)
end
if !columns_hash.key?(key) || StatementCache.unsupported_value?(value)
return super
end
h[key] = value
end
keys = hash.keys
statement = cached_find_by_statement(keys) { |params|
wheres = keys.index_with { params.bind }
where(wheres).limit(1)
}
begin
statement.execute(hash.values, connection).first
rescue TypeError
raise ActiveRecord::StatementInvalid
end
end
def find_by!(*args) # :nodoc:
find_by(*args) || where(*args).raise_record_not_found_exception!
end
%w(
reading_role writing_role legacy_connection_handling default_timezone index_nested_attribute_errors
verbose_query_logs queues warn_on_records_fetched_greater_than maintain_test_schema
application_record_class action_on_strict_loading_violation schema_format error_on_ignored_order
timestamped_migrations dump_schema_after_migration dump_schemas suppress_multiple_database_warning
).each do |attr|
module_eval(<<~RUBY, __FILE__, __LINE__ + 1)
def #{attr}
ActiveSupport::Deprecation.warn(<<~MSG)
ActiveRecord::Base.#{attr} is deprecated and will be removed in Rails 7.1.
Use `ActiveRecord.#{attr}` instead.
MSG
ActiveRecord.#{attr}
end
def #{attr}=(value)
ActiveSupport::Deprecation.warn(<<~MSG)
ActiveRecord::Base.#{attr}= is deprecated and will be removed in Rails 7.1.
Use `ActiveRecord.#{attr}=` instead.
MSG
ActiveRecord.#{attr} = value
end
RUBY
end
def initialize_generated_modules # :nodoc:
generated_association_methods
end
def generated_association_methods # :nodoc:
@generated_association_methods ||= begin
mod = const_set(:GeneratedAssociationMethods, Module.new)
private_constant :GeneratedAssociationMethods
include mod
mod
end
end
# Returns columns which shouldn't be exposed while calling +#inspect+.
def filter_attributes
if defined?(@filter_attributes)
@filter_attributes
else
superclass.filter_attributes
end
end
# Specifies columns which shouldn't be exposed while calling +#inspect+.
def filter_attributes=(filter_attributes)
@inspection_filter = nil
@filter_attributes = filter_attributes
end
def inspection_filter # :nodoc:
if defined?(@filter_attributes)
@inspection_filter ||= begin
mask = InspectionMask.new(ActiveSupport::ParameterFilter::FILTERED)
ActiveSupport::ParameterFilter.new(@filter_attributes, mask: mask)
end
else
superclass.inspection_filter
end
end
# Returns a string like 'Post(id:integer, title:string, body:text)'
def inspect # :nodoc:
if self == Base
super
elsif abstract_class?
"#{super}(abstract)"
elsif !connected?
"#{super} (call '#{super}.connection' to establish a connection)"
elsif table_exists?
attr_list = attribute_types.map { |name, type| "#{name}: #{type.type}" } * ", "
"#{super}(#{attr_list})"
else
"#{super}(Table doesn't exist)"
end
end
# Overwrite the default class equality method to provide support for decorated models.
def ===(object) # :nodoc:
object.is_a?(self)
end
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
def arel_table # :nodoc:
@arel_table ||= Arel::Table.new(table_name, klass: self)
end
def arel_attribute(name, table = arel_table) # :nodoc:
table[name]
end
deprecate :arel_attribute
def predicate_builder # :nodoc:
@predicate_builder ||= PredicateBuilder.new(table_metadata)
end
def type_caster # :nodoc:
TypeCaster::Map.new(self)
end
def cached_find_by_statement(key, &block) # :nodoc:
cache = @find_by_statement_cache[connection.prepared_statements]
cache.compute_if_absent(key) { StatementCache.create(connection, &block) }
end
private
def relation
relation = Relation.create(self)
if finder_needs_type_condition? && !ignore_default_scope?
relation.where!(type_condition)
else
relation
end
end
def table_metadata
TableMetadata.new(self, arel_table)
end
end
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
# In both instances, valid attribute keys are determined by the column names of the associated table --
# hence you can't have attributes that aren't part of the table columns.
#
# ==== Example:
# # Instantiates a single new object
# User.new(first_name: 'Jamie')
def initialize(attributes = nil)
@new_record = true
@attributes = self.class._default_attributes.deep_dup
init_internals
initialize_internals_callback
assign_attributes(attributes) if attributes
yield self if block_given?
_run_initialize_callbacks
end
# Initialize an empty model object from +coder+. +coder+ should be
# the result of previously encoding an Active Record model, using
# #encode_with.
#
# class Post < ActiveRecord::Base
# end
#
# old_post = Post.new(title: "hello world")
# coder = {}
# old_post.encode_with(coder)
#
# post = Post.allocate
# post.init_with(coder)
# post.title # => 'hello world'
def init_with(coder, &block)
coder = LegacyYamlAdapter.convert(self.class, coder)
attributes = self.class.yaml_encoder.decode(coder)
init_with_attributes(attributes, coder["new_record"], &block)
end
##
# Initialize an empty model object from +attributes+.
# +attributes+ should be an attributes object, and unlike the
# `initialize` method, no assignment calls are made per attribute.
def init_with_attributes(attributes, new_record = false) # :nodoc:
@new_record = new_record
@attributes = attributes
init_internals
yield self if block_given?
_run_find_callbacks
_run_initialize_callbacks
self
end
##
# :method: clone
# Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
# That means that modifying attributes of the clone will modify the original, since they will both point to the
# same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
#
# user = User.first
# new_user = user.clone
# user.name # => "Bob"
# new_user.name = "Joe"
# user.name # => "Joe"
#
# user.object_id == new_user.object_id # => false
# user.name.object_id == new_user.name.object_id # => true
#
# user.name.object_id == user.dup.name.object_id # => false
##
# :method: dup
# Duped objects have no id assigned and are treated as new records. Note
# that this is a "shallow" copy as it copies the object's attributes
# only, not its associations. The extent of a "deep" copy is application
# specific and is therefore left to the application to implement according
# to its need.
# The dup method does not preserve the timestamps (created|updated)_(at|on).
##
def initialize_dup(other) # :nodoc:
@attributes = @attributes.deep_dup
@attributes.reset(@primary_key)
_run_initialize_callbacks
@new_record = true
@previously_new_record = false
@destroyed = false
@_start_transaction_state = nil
super
end
# Populate +coder+ with attributes about this record that should be
# serialized. The structure of +coder+ defined in this method is
# guaranteed to match the structure of +coder+ passed to the #init_with
# method.
#
# Example:
#
# class Post < ActiveRecord::Base
# end
# coder = {}
# Post.new.encode_with(coder)
# coder # => {"attributes" => {"id" => nil, ... }}
def encode_with(coder)
self.class.yaml_encoder.encode(@attributes, coder)
coder["new_record"] = new_record?
coder["active_record_yaml_version"] = 2
end
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
#
# Note that new records are different from any other record by definition, unless the
# other record is the receiver itself. Besides, if you fetch existing records with
# +select+ and leave the ID out, you're on your own, this predicate will return false.
#
# Note also that destroying a record preserves its ID in the model instance, so deleted
# models are still comparable.
def ==(comparison_object)
super ||
comparison_object.instance_of?(self.class) &&
!id.nil? &&
comparison_object.id == id
end
alias :eql? :==
# Delegates to id in order to allow two records of the same type and id to work with something like:
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
def hash
id = self.id
if id
self.class.hash ^ id.hash
else
super
end
end
# Clone and freeze the attributes hash such that associations are still
# accessible, even on destroyed records, but cloned models will not be
# frozen.
def freeze
@attributes = @attributes.clone.freeze
self
end
# Returns +true+ if the attributes hash has been frozen.
def frozen?
@attributes.frozen?
end
# Allows sort on objects
def <=>(other_object)
if other_object.is_a?(self.class)
to_key <=> other_object.to_key
else
super
end
end
def present? # :nodoc:
true
end
def blank? # :nodoc:
false
end
# Returns +true+ if the record is read only.
def readonly?
@readonly
end
# Returns +true+ if the record is in strict_loading mode.
def strict_loading?
@strict_loading
end
# Sets the record to strict_loading mode. This will raise an error
# if the record tries to lazily load an association.
#
# user = User.first
# user.strict_loading! # => true
# user.comments
# => ActiveRecord::StrictLoadingViolationError
#
# === Parameters:
#
# * value - Boolean specifying whether to enable or disable strict loading.
# * mode - Symbol specifying strict loading mode. Defaults to :all. Using
# :n_plus_one_only mode will only raise an error if an association
# that will lead to an n plus one query is lazily loaded.
#
# === Example:
#
# user = User.first
# user.strict_loading!(false) # => false
# user.comments
# => #<ActiveRecord::Associations::CollectionProxy>
def strict_loading!(value = true, mode: :all)
unless [:all, :n_plus_one_only].include?(mode)
raise ArgumentError, "The :mode option must be one of [:all, :n_plus_one_only]."
end
@strict_loading_mode = mode
@strict_loading = value
end
attr_reader :strict_loading_mode
# Returns +true+ if the record uses strict_loading with +:n_plus_one_only+ mode enabled.
def strict_loading_n_plus_one_only?
@strict_loading_mode == :n_plus_one_only
end
# Marks this record as read only.
def readonly!
@readonly = true
end
def connection_handler
self.class.connection_handler
end
# Returns the contents of the record as a nicely formatted string.
def inspect
# We check defined?(@attributes) not to issue warnings if the object is
# allocated but not initialized.
inspection = if defined?(@attributes) && @attributes
self.class.attribute_names.filter_map do |name|
if _has_attribute?(name)
"#{name}: #{attribute_for_inspect(name)}"
end
end.join(", ")
else
"not initialized"
end
"#<#{self.class} #{inspection}>"
end
# Takes a PP and prettily prints this record to it, allowing you to get a nice result from <tt>pp record</tt>
# when pp is required.
def pretty_print(pp)
return super if custom_inspect_method_defined?
pp.object_address_group(self) do
if defined?(@attributes) && @attributes
attr_names = self.class.attribute_names.select { |name| _has_attribute?(name) }
pp.seplist(attr_names, proc { pp.text "," }) do |attr_name|
pp.breakable " "
pp.group(1) do
pp.text attr_name
pp.text ":"
pp.breakable
value = _read_attribute(attr_name)
value = inspection_filter.filter_param(attr_name, value) unless value.nil?
pp.pp value
end
end
else
pp.breakable " "
pp.text "not initialized"
end
end
end
# Returns a hash of the given methods with their names as keys and returned values as values.
def slice(*methods)
methods.flatten.index_with { |method| public_send(method) }.with_indifferent_access
end
# Returns an array of the values returned by the given methods.
def values_at(*methods)
methods.flatten.map! { |method| public_send(method) }
end
private
# +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of
# the array, and then rescues from the possible +NoMethodError+. If those elements are
# +ActiveRecord::Base+'s, then this triggers the various +method_missing+'s that we have,
# which significantly impacts upon performance.
#
# So we can avoid the +method_missing+ hit by explicitly defining +#to_ary+ as +nil+ here.
#
# See also https://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
def to_ary
nil
end
def init_internals
@readonly = false
@previously_new_record = false
@destroyed = false
@marked_for_destruction = false
@destroyed_by_association = nil
@_start_transaction_state = nil
klass = self.class
@primary_key = klass.primary_key
@strict_loading = klass.strict_loading_by_default
@strict_loading_mode = :all
klass.define_attribute_methods
end
def initialize_internals_callback
end
def custom_inspect_method_defined?
self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner
end
class InspectionMask < DelegateClass(::String)
def pretty_print(pp)
pp.text __getobj__
end
end
private_constant :InspectionMask
def inspection_filter
self.class.inspection_filter
end
end
end
| georgeclaghorn/rails | activerecord/lib/active_record/core.rb | Ruby | mit | 26,884 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AssemblyToProcessExternal")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AssemblyToProcessExternal")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("70f0c636-cf7f-4f07-8e94-fc8cd7b5427d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| qkub/ExpandoIntelligizer | AssemblyToProcessExternal/Properties/AssemblyInfo.cs | C# | mit | 1,426 |
# -*- coding: utf-8 -*-
r"""
.. _SoftiMAX:
SoftiMAX at MAX IV
------------------
The images below are produced by scripts in
``\examples\withRaycing\14_SoftiMAX``.
The beamline will have two branches:
- STXM (Scanning Transmission X-ray Microscopy) and
- CXI (Coherent X-ray Imaging),
see the scheme provided by K. Thånell.
.. imagezoom:: _images/softiMAX_layout.*
STXM branch
~~~~~~~~~~~
.. rubric:: Rays vs. hybrid
The propagation through the first optical elements – from undulator to front
end (FE) slit, to M1, to M2 and to plane grating (PG) – is done with rays:
+------------+------------+------------+------------+
| FE | M1 | M2 | PG |
+============+============+============+============+
| |st_rFE| | |st_rM1| | |st_rM2| | |st_rPG| |
+------------+------------+------------+------------+
.. |st_rFE| imagezoom:: _images/stxm-2D-1-rays-0emit-0enSpread-monoE-00-FE.*
.. |st_rM1| imagezoom:: _images/stxm-2D-1-rays-0emit-0enSpread-monoE-01-M1local.*
.. |st_rM2| imagezoom:: _images/stxm-2D-1-rays-0emit-0enSpread-monoE-02-M2local.*
.. |st_rPG| imagezoom:: _images/stxm-2D-1-rays-0emit-0enSpread-monoE-02a-PGlocal.*
:loc: upper-right-corner
Starting from PG – to M3, to exit slit, to Fresnel zone plate (FZP) and to
variously positioned sample screen – the propagation is done by rays or waves,
as compared below. Despite the M3 footprint looks not perfect (not black at
periphery), the field at normal surfaces (exit slit, FZP (not shown) and sample
screen) is of perfect quality. At the best focus, rays and waves result in a
similar image. Notice a micron-sized depth of focus.
+-----------+---------------------+---------------------+
| | rays | wave |
+===========+=====================+=====================+
| M3 | |st_rM3| | |st_hM3| |
+-----------+---------------------+---------------------+
| exit slit | |st_rES| | |st_hES| |
+-----------+---------------------+---------------------+
| sample | |st_rS| | |st_hS| |
+-----------+---------------------+---------------------+
.. |st_rM3| imagezoom:: _images/stxm-2D-1-rays-0emit-0enSpread-monoE-03-M3local.*
.. |st_hM3| imagezoom:: _images/stxm-2D-2-hybr-0emit-0enSpread-monoE-03-M3local.*
:loc: upper-right-corner
.. |st_rES| imagezoom:: _images/stxm-2D-1-rays-0emit-0enSpread-monoE-04-ExitSlit.*
.. |st_hES| imagezoom:: _images/stxm-2D-2-hybr-0emit-0enSpread-monoE-04-ExitSlit.*
:loc: upper-right-corner
.. |st_rS| animation:: _images/stxm-2D-1-rays-0emit-0enSpread-monoE-06i-ExpFocus-Is
.. |st_hS| imagezoom:: _images/stxm-2D-2-hybr-0emit-0enSpread-monoE-06i-ExpFocus-Is
:loc: upper-right-corner
.. rubric:: Influence of emittance
Non-zero emittance radiation is treated in xrt by incoherent addition of single
electron intensities. The single electron (filament) fields are considered as
fully coherent and are resulted from filament trajectories (one per repeat)
that attain positional and angular shifts within the given emittance
distribution. The following images are calculated for the exit slit and the
focus screen for zero and non-zero emittance
(for MAX IV 3 GeV ring: ε\ :sub:`x`\ =263 pm·rad,
β\ :sub:`x`\ =9 m, ε\ :sub:`z`\ =8 pm·rad, β\ :sub:`z`\ =2 m). At the real
emittance, the horizontal focal size increases by ~75%. A finite energy band,
as determined by vertical size of the exit slit, results in somewhat bigger
broadening due to a chromatic dependence of the focal length.
+-----------+---------------------+---------------------+---------------------+
| | 0 emittance | real emittance | |refeb| |
+===========+=====================+=====================+=====================+
| exit slit | |st_hESb| | |st_hES2| | |st_hES3| |
+-----------+---------------------+---------------------+---------------------+
| sample | |st_hSb| | |st_hS2| | |st_hS3| |
+-----------+---------------------+---------------------+---------------------+
.. |refeb| replace:: real emittance, finite energy band
.. |st_hESb| imagezoom:: _images/stxm-2D-2-hybr-0emit-0enSpread-monoE-04-ExitSlit.*
.. |st_hES2| imagezoom:: _images/stxm-2D-2-hybr-non0e-0enSpread-monoE-04-ExitSlit.*
.. |st_hS2| animation:: _images/stxm-2D-2-hybr-non0e-0enSpread-monoE-06i-ExpFocus-Is
.. |st_hES3| imagezoom:: _images/stxm-2D-2-hybr-non0e-0enSpread-wideE-04-ExitSlit.*
:loc: upper-right-corner
.. |st_hSb| imagezoom:: _images/stxm-2D-2-hybr-0emit-0enSpread-monoE-06i-ExpFocus-Is
.. |st_hS3| animation:: _images/stxm-2D-2-hybr-non0e-0enSpread-wideE-06i-ExpFocus-Is
:loc: upper-right-corner
.. rubric:: Correction of emittance effects
The increased focal size can be amended by closing the exit slit. With flux
loss of about 2/3, the focal size is almost restored.
+-----------+--------------------+--------------------+
| | 80 µm exit slit | 20 µm exit slit |
+===========+====================+====================+
| exit slit | |st_hES2b| | |st_hES4| |
+-----------+--------------------+--------------------+
| sample | |st_hS2b| | |st_hS4| |
+-----------+--------------------+--------------------+
.. |st_hES2b| imagezoom:: _images/stxm-2D-2-hybr-non0e-0enSpread-monoE-04-ExitSlit.*
.. |st_hES4| imagezoom:: _images/stxm-2D-2-hybr-non0e-0enSpread-monoE-025H-04-ExitSlit.*
:loc: upper-right-corner
.. |st_hS2b| animation:: _images/stxm-2D-2-hybr-non0e-0enSpread-monoE-06i-ExpFocus-Is
.. |st_hS4| animation:: _images/stxm-2D-2-hybr-non0e-0enSpread-monoE-025H-06i-ExpFocus-Is
:loc: upper-right-corner
.. rubric:: Coherence signatures
The beam improvement can also be viewed via the coherence properties by the
four available methods (see :ref:`coh_signs`). As the horizontal exit slit
becomes smaller, one can observe the increase of the coherent fraction ζ and
the increase of the primary (coherent) mode weight. The width of degree of
coherence (DoC) relative to the width of the intensity distribution determines
the coherent beam fraction. Both widths vary with varying screen position
around the focal point such that their ratio is not invariant, so that the
coherent fraction also varies, which is counter-intuitive. An important
advantage of the eigen-mode or PCA methods is a simple definition of the
coherent fraction as the eigenvalue of the zeroth mode (component); this
eigenvalue appears to be invariant around the focal point, see below. Note that
the methods 2 and 3 give equal results. The method 4 that gives the degree of
transverse coherence (DoTC) is also invariant around the focal point, see DoTC
values on the pictures of Principal Components.
+-----------+--------------------------+--------------------------+
| | 80 µm exit slit | 20 µm exit slit |
+===========+==========================+==========================+
| method 1 | |st_hS80m1| | |st_hS20m1| |
+-----------+--------------------------+--------------------------+
| method 2 | |st_hS80m3| | |st_hS20m3| |
+-----------+--------------------------+--------------------------+
| method 3, | |st_hS80m4| | |st_hS20m4| |
| method 4b | | |
+-----------+--------------------------+--------------------------+
.. |st_hS80m1| animation:: _images/stxm-IDOC-2D-2-hybr-non0e-0enSpread-monoE
.. |st_hS20m1| animation:: _images/stxm-IDOC-2D-2-hybr-non0e-0enSpread-monoE-025H
:loc: upper-right-corner
.. |st_hS80m3| animation:: _images/stxm-Modes-2D-2-hybr-non0e-0enSpread-monoE
.. |st_hS20m3| animation:: _images/stxm-Modes-2D-2-hybr-non0e-0enSpread-monoE-025H
:loc: upper-right-corner
.. |st_hS80m4| animation:: _images/stxm-PCA-2D-2-hybr-non0e-0enSpread-monoE
.. |st_hS20m4| animation:: _images/stxm-PCA-2D-2-hybr-non0e-0enSpread-monoE-025H
:loc: upper-right-corner
CXI branch
~~~~~~~~~~
.. rubric:: 2D vs 1D
Although the sample screen images are of good quality (the dark field is almost
black), the mirror footprints may be noisy and not well convergent in the
periphery. Compare the M3 footprint with that in the previous section (STXM
branch) where the difference is in the mirror area and thus in the sample
density. The used 10\ :sup:`6` wave samples (i.e. 10\ :sup:`12` possible paths)
are not enough for the slightly enlarged area in the present example. The
propagation is therefore performed in separated horizontal and vertical
directions, which dramatically improves the quality of the footprints.
Disadvantages of the cuts are losses in visual representation and incorrect
evaluation of the flux.
+------+----------------------+-----------------------+-----------------------+
| | 2D | 1D horizontal cut | 1D vertical cut |
+======+======================+=======================+=======================+
| |M3| | |cxiM32D| | |cxiM31Dh| | |cxiM31Dv| |
+------+----------------------+-----------------------+-----------------------+
| |SS| | |cxiS2D| | |cxiS1Dh| | |cxiS1Dv| |
+------+----------------------+-----------------------+-----------------------+
.. |M3| replace:: M3 footprint
.. |SS| replace:: sample screen
.. |cxiM32D| imagezoom:: _images/cxi_2D-2-hybr-0emit-0enSpread-monoE-03-M3local.*
.. |cxiM31Dh| imagezoom:: _images/cxi_1D-2-hybr-1e6hor-0emit-0enSpread-monoE-03-M3local.*
.. |cxiM31Dv| imagezoom:: _images/cxi_1D-2-hybr-1e6ver-0emit-0enSpread-monoE-03-M3local.*
:loc: upper-right-corner
.. |cxiS2D| animation:: _images/cxi_S2D
.. |cxiS1Dh| animation:: _images/cxi_S1Dh
.. |cxiS1Dv| animation:: _images/cxi_S1Dv
:loc: upper-right-corner
.. _wavefronts:
.. rubric:: Flat screen vs normal-to-k screen (wave front)
The following images demonstrate the correctness of the directional
Kirchhoff-like integral (see :ref:`seq_prop`). Five diffraction integrals are
calculated on flat screens around the focus position: for two polarizations and
for three directional components. The latter ones define the wave fronts at
every flat screen position; these wave fronts are further used as new curved
screens. The calculated diffraction fields on these curved screens have narrow
phase distributions, as shown by the color histograms, which is indeed expected
for a wave front by its definition. In contrast, the *flat* screens at the same
positions have rapid phase variation over several Fresnel zones.
.. note::
In the process of wave propagation, wave fronts -- surfaces of
constant phase -- are not used in any way. We therefore call it “wave
propagation”, not “wave *front* propagation” as frequently called by
others. The wave fronts in this example were calculated to solely
demonstrate the correctness of the local propagation directions after
having calculated the diffracted field.
+------------------------------+------------------------------+
| flat screen | curved screen (wave front) |
+==============================+==============================+
| |cxiFlat| | |cxiFront| |
+------------------------------+------------------------------+
.. |cxiFlat| animation:: _images/cxi-S1DhFlat
.. |cxiFront| animation:: _images/cxi-S1DhFront
:loc: upper-right-corner
The curvature of the calculated wave fronts varies across the focus position.
The wave fronts become more flat as one approaches the focus, see the figure
below. This is in contrast to *ray* propagation, where the angular ray
distribution is invariant at any position between two optical elements.
.. imagezoom:: _images/cxi_waveFronts.*
.. rubric:: Rays, waves and hybrid
The following images are horizontal cuts at the footprints and sample screens
calculated by
- rays,
- rays + waves hybrid (rays up to PG and wave from PG) and
- purely by waves.
+-----------------+-------------------+-------------------+-------------------+
| | rays | hybrid | waves |
+=================+===================+===================+===================+
| front end slit | |cxi-hFE| | same as rays | |cxi-wFE| |
+-----------------+-------------------+-------------------+-------------------+
| footprint on M1 | |cxi-hM1| | same as rays | |cxi-wM1| |
+-----------------+-------------------+-------------------+-------------------+
| footprint on M2 | |cxi-hM2| | same as rays | |cxi-wM2| |
+-----------------+-------------------+-------------------+-------------------+
| footprint on PG | |cxi-hPG| | same as rays | |cxi-wPG| |
+-----------------+-------------------+-------------------+-------------------+
| footprint on M3 | |cxi-rM3| | |cxi-hM3| | |cxi-wM3| |
+-----------------+-------------------+-------------------+-------------------+
| exit slit | |cxi-rES| | |cxi-hES| | |cxi-wES| |
+-----------------+-------------------+-------------------+-------------------+
| footprint on M4 | |cxi-rM4| | |cxi-hM4| | |cxi-wM4| |
+-----------------+-------------------+-------------------+-------------------+
| footprint on M5 | |cxi-rM5| | |cxi-hM5| | |cxi-wM5| |
+-----------------+-------------------+-------------------+-------------------+
| sample screen | |cxi-rS| | |cxi-hS| | |cxi-wS| |
+-----------------+-------------------+-------------------+-------------------+
.. |cxi-hFE| imagezoom:: _images/cxi_1D-1-rays-hor-0emit-0enSpread-monoE-00-FE.*
.. |cxi-wFE| imagezoom:: _images/cxi_1D-3-wave-hor-0emit-0enSpread-monoE-00-FE.*
:loc: upper-right-corner
.. |cxi-hM1| imagezoom:: _images/cxi_1D-1-rays-hor-0emit-0enSpread-monoE-01-M1local.*
.. |cxi-wM1| imagezoom:: _images/cxi_1D-3-wave-hor-0emit-0enSpread-monoE-01-M1local.*
:loc: upper-right-corner
.. |cxi-hM2| imagezoom:: _images/cxi_1D-1-rays-hor-0emit-0enSpread-monoE-02-M2local.*
.. |cxi-wM2| imagezoom:: _images/cxi_1D-3-wave-hor-0emit-0enSpread-monoE-02-M2local.*
:loc: upper-right-corner
.. |cxi-hPG| imagezoom:: _images/cxi_1D-1-rays-hor-0emit-0enSpread-monoE-02-PGlocal.*
.. |cxi-wPG| imagezoom:: _images/cxi_1D-3-wave-hor-0emit-0enSpread-monoE-02-PGlocal.*
:loc: upper-right-corner
.. |cxi-rM3| imagezoom:: _images/cxi_1D-1-rays-hor-0emit-0enSpread-monoE-03-M3local.*
.. |cxi-hM3| imagezoom:: _images/cxi_1D-2-hybr-hor-0emit-0enSpread-monoE-03-M3local.*
.. |cxi-wM3| imagezoom:: _images/cxi_1D-3-wave-hor-0emit-0enSpread-monoE-03-M3local.*
:loc: upper-right-corner
.. |cxi-rES| imagezoom:: _images/cxi_1D-1-rays-hor-0emit-0enSpread-monoE-04-ExitSlit.*
.. |cxi-hES| imagezoom:: _images/cxi_1D-2-hybr-hor-0emit-0enSpread-monoE-04-ExitSlit.*
.. |cxi-wES| imagezoom:: _images/cxi_1D-3-wave-hor-0emit-0enSpread-monoE-04-ExitSlit.*
:loc: upper-right-corner
.. |cxi-rM4| imagezoom:: _images/cxi_1D-1-rays-hor-0emit-0enSpread-monoE-05-M4local.*
.. |cxi-hM4| imagezoom:: _images/cxi_1D-2-hybr-hor-0emit-0enSpread-monoE-05-M4local.*
.. |cxi-wM4| imagezoom:: _images/cxi_1D-3-wave-hor-0emit-0enSpread-monoE-05-M4local.*
:loc: upper-right-corner
.. |cxi-rM5| imagezoom:: _images/cxi_1D-1-rays-hor-0emit-0enSpread-monoE-06-M5local.*
.. |cxi-hM5| imagezoom:: _images/cxi_1D-2-hybr-hor-0emit-0enSpread-monoE-06-M5local.*
.. |cxi-wM5| imagezoom:: _images/cxi_1D-3-wave-hor-0emit-0enSpread-monoE-06-M5local.*
:loc: upper-right-corner
.. |cxi-rS| animation:: _images/cxi-rS
.. |cxi-hS| animation:: _images/cxi-hS
.. |cxi-wS| animation:: _images/cxi-wS
:loc: upper-right-corner
.. rubric:: Coherence signatures
This section demonstrates the methods 1 and 3 from :ref:`coh_signs`. Notice
again the difficulty in determining the width of DoC owing to its complex shape
(at real emittance) or the restricted field of view (the 0 emittance case). In
contrast, the eigen mode analysis yields an almost invariant well defined
coherent fraction.
+-----------+--------------------------+--------------------------+
| | 0 emittance | real emittance |
+===========+==========================+==========================+
| method 1 | |cxi-coh1-0emit| | |cxi-coh1-non0e| |
+-----------+--------------------------+--------------------------+
| method 3 | |cxi-coh3-0emit| | |cxi-coh3-non0e| |
+-----------+--------------------------+--------------------------+
.. |cxi-coh1-0emit| animation:: _images/cxi-coh1-0emit
.. |cxi-coh1-non0e| animation:: _images/cxi-coh1-non0e
.. |cxi-coh3-0emit| animation:: _images/cxi-coh3-0emit
.. |cxi-coh3-non0e| animation:: _images/cxi-coh3-non0e
:loc: upper-right-corner
"""
pass
| kklmn/xrt | examples/withRaycing/14_SoftiMAX/__init__.py | Python | mit | 16,930 |