repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
kt3k/class-component-initializer | spec.js | 3290 |
before(function () {
$.defineRole('foo', function (pt, parent) {
pt.constructor = function (elem) {
parent.constructor.call(this, elem);
elem.attr('is_foo', 'true');
};
});
$.defineRole('bar', function (pt, parent) {
pt.constructor = function (elem) {
parent.constructor.call(this, elem);
elem.attr('is_bar', 'true');
};
pt.__init = function () {
return new Promise(function (resolve) {
setTimeout(resolve, 500);
});
};
});
});
describe('$.CC.init', function () {
'use strict';
it('initializes the class component of the given name', function (done) {
var foo = $('<div class="foo" />').appendTo(document.body);
$.CC.init('foo');
setTimeout(function () {
expect(foo.attr('is_foo')).to.equal('true');
foo.remove();
done();
});
});
it('returns promise which resolves when the init process of each elem resolves', function (done) {
var bar = $('<div class="bar" />').appendTo('body');
$.CC.init('bar').then(function () {
expect(bar.attr('is_bar')).to.equal('true');
expect(a100).to.be.true;
expect(a200).to.be.true;
expect(a300).to.be.true;
expect(a400).to.be.true;
expect(a600).to.be.false;
expect(a700).to.be.false;
bar.remove();
done();
}).catch(done);
var a100 = false;
var a200 = false;
var a300 = false;
var a400 = false;
var a600 = false;
var a700 = false;
setTimeout(function () { a100 = true; }, 100);
setTimeout(function () { a200 = true; }, 200);
setTimeout(function () { a300 = true; }, 300);
setTimeout(function () { a400 = true; }, 400);
setTimeout(function () { a600 = true; }, 600);
setTimeout(function () { a700 = true; }, 700);
});
it('initializes multiple class components', function () {
var foo = $('<div class="foo" />').appendTo('body');
var bar = $('<div class="bar" />').appendTo('body');
$.CC.init(['foo', 'bar']).then(function () {
expect(foo.attr('is_foo')).to.equal('true');
expect(bar.attr('is_bar')).to.equal('true');
foo.remove();
bar.remove();
});
});
});
describe('$.fn.spawn', function () {
it('loads the contents from the url and place them in the element (interpreted as html) and initializes them as class-component', function () {
var elem = $('<div />').appendTo('body');
elem.spawn('/base/fixture.html', 'foo bar').then(function () {
expect(elem.children().length).to.equal(3);
});
});
it('resolves with initialized class components', function () {
var elem = $('<div />').appendTo('body');
return elem.spawn('/base/fixture.html', 'foo bar').then(function (elements) {
expect(elements).to.have.length(3);
elements.forEach(function (elem) {
expect(elem).to.be.instanceof(HTMLElement);
});
});
});
});
| mit |
thfabian/sequoia | sequoia-engine/src/sequoia-engine/Render/UniformVariable.cpp | 4942 | //===--------------------------------------------------------------------------------*- C++ -*-===//
// _____ _
// / ____| (_)
// | (___ ___ __ _ _ _ ___ _ __ _
// \___ \ / _ \/ _` | | | |/ _ \| |/ _` |
// ____) | __/ (_| | |_| | (_) | | (_| |
// |_____/ \___|\__, |\__,_|\___/|_|\__,_| - Game Engine (2016-2017)
// | |
// |_|
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "sequoia-engine/Core/Format.h"
#include "sequoia-engine/Core/StringUtil.h"
#include "sequoia-engine/Core/Unreachable.h"
#include "sequoia-engine/Render/UniformVariable.h"
#include <boost/preprocessor/stringize.hpp>
#include <ostream>
#include <sstream>
namespace sequoia {
namespace render {
namespace {
static std::string variantToString(const UniformVariable::DataType& data, UniformType type) {
std::stringstream ss;
switch(type) {
#define UNIFORM_VARIABLE_TYPE(Type, Name) \
case UniformType::Name: \
ss << boost::get<Type>(data); \
break; \
case UniformType::VectorOf##Name: \
ss << core::RangeToString(", ", "{", "}")(boost::get<std::vector<Type>>(data), \
[](const Type& value) { \
std::stringstream sout; \
sout << value; \
return sout.str(); \
}); \
break;
#include "sequoia-engine/Render/UniformVariable.inc"
#undef UNIFORM_VARIABLE_TYPE
case UniformType::Invalid:
ss << "<invalid>";
break;
default:
sequoia_unreachable("invalid type");
}
return ss.str();
}
} // anonymous namespace
std::ostream& operator<<(std::ostream& os, UniformType type) {
switch(type) {
#define UNIFORM_VARIABLE_TYPE(Type, Name) \
case UniformType::Name: \
os << #Name; \
break; \
case UniformType::VectorOf##Name: \
os << BOOST_PP_STRINGIZE(VectorOf##Name); \
break;
#include "sequoia-engine/Render/UniformVariable.inc"
#undef UNIFORM_VARIABLE_TYPE
case UniformType::Invalid:
os << "Invalid";
break;
case UniformType::Struct:
os << "Struct";
break;
default:
sequoia_unreachable("invalid type");
}
return os;
}
bool UniformVariable::operator==(const UniformVariable& other) const noexcept {
if(type_ != other.type_)
return false;
switch(type_) {
#define UNIFORM_VARIABLE_TYPE(Type, Name) \
case UniformType::Name: \
return boost::get<Type>(data_) == boost::get<Type>(other.data_); \
case UniformType::VectorOf##Name: \
return boost::get<std::vector<Type>>(data_) == boost::get<std::vector<Type>>(other.data_);
#include "sequoia-engine/Render/UniformVariable.inc"
#undef UNIFORM_VARIABLE_TYPE
case UniformType::Invalid:
return boost::get<internal::InvalidData>(data_) ==
boost::get<internal::InvalidData>(other.data_);
default:
sequoia_unreachable("invalid type");
}
}
std::string UniformVariable::toString() const {
return core::format("UniformVariable[\n"
" type = {},\n"
" data = {}\n"
"]",
type_, core::indent(variantToString(data_, type_), 4));
}
std::ostream& operator<<(std::ostream& os, const UniformVariable& var) {
return (os << var.toString());
}
} // namespace render
} // namespace sequoia
| mit |
space-wizards/space-station-14 | Content.Shared/Ghost/SharedGhostComponent.cs | 2303 | using System;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.Players;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Shared.Ghost
{
[NetworkedComponent()]
public class SharedGhostComponent : Component
{
[ViewVariables(VVAccess.ReadWrite)]
public bool CanGhostInteract
{
get => _canGhostInteract;
set
{
if (_canGhostInteract == value) return;
_canGhostInteract = value;
Dirty();
}
}
[DataField("canInteract")]
private bool _canGhostInteract;
/// <summary>
/// Changed by <see cref="SharedGhostSystem.SetCanReturnToBody"/>
/// </summary>
// TODO MIRROR change this to use friend classes when thats merged
[ViewVariables(VVAccess.ReadWrite)]
public bool CanReturnToBody
{
get => _canReturnToBody;
set
{
if (_canReturnToBody == value) return;
_canReturnToBody = value;
Dirty();
}
}
[DataField("canReturnToBody")]
private bool _canReturnToBody;
public override ComponentState GetComponentState()
{
return new GhostComponentState(CanReturnToBody, CanGhostInteract);
}
public override void HandleComponentState(ComponentState? curState, ComponentState? nextState)
{
base.HandleComponentState(curState, nextState);
if (curState is not GhostComponentState state)
{
return;
}
CanReturnToBody = state.CanReturnToBody;
CanGhostInteract = state.CanGhostInteract;
}
}
[Serializable, NetSerializable]
public class GhostComponentState : ComponentState
{
public bool CanReturnToBody { get; }
public bool CanGhostInteract { get; }
public GhostComponentState(
bool canReturnToBody,
bool canGhostInteract)
{
CanReturnToBody = canReturnToBody;
CanGhostInteract = canGhostInteract;
}
}
}
| mit |
salsify/ember-css-modules | packages/ember-css-modules/tests/integration/splattributes-test.js | 928 | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import setupStyles from '../helpers/render-with-styles';
import styles from 'dummy/components/component-with-splattributes/styles';
module('Integration | Components with splattributes', function (hooks) {
setupRenderingTest(hooks);
test('inner and outer local and global classes are all present', async function (assert) {
const hbs = setupStyles({
'local-outer': '--local-outer',
});
await render(
hbs`<ComponentWithSplattributes local-class="local-outer" class="global-outer" />`
);
assert.dom('[data-test-element]').hasClass('global-outer');
assert.dom('[data-test-element]').hasClass('--local-outer');
assert.dom('[data-test-element]').hasClass('global-inner');
assert.dom('[data-test-element]').hasClass(styles['local-inner']);
});
});
| mit |
guiwoda/fluent | src/FluentDriver.php | 3669 | <?php
namespace LaravelDoctrine\Fluent;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver;
use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder;
use Doctrine\ORM\Mapping\MappingException;
use InvalidArgumentException;
use LaravelDoctrine\Fluent\Builders\Builder;
use LaravelDoctrine\Fluent\Mappers\MapperSet;
class FluentDriver implements MappingDriver
{
/**
* @var MapperSet
*/
protected $mappers;
/**
* @type callable
*/
protected $fluentFactory;
/**
* Initializes a new FileDriver that looks in the given path(s) for mapping
* documents and operates in the specified operating mode.
*
* @param string[] $mappings
*/
public function __construct(array $mappings = [])
{
$this->fluentFactory = function (ClassMetadata $metadata) {
return new Builder(new ClassMetadataBuilder($metadata));
};
$this->mappers = new MapperSet();
$this->addMappings($mappings);
}
/**
* Loads the metadata for the specified class into the provided container.
*
* @param string $className
* @param ClassMetadata $metadata
*/
public function loadMetadataForClass($className, ClassMetadata $metadata)
{
$this->mappers->getMapperFor($className)->map(
$this->getFluent($metadata)
);
}
/**
* Gets the names of all mapped classes known to this driver.
*
* @throws MappingException
* @return string[] The names of all mapped classes known to this driver.
*/
public function getAllClassNames()
{
return $this->mappers->getClassNames();
}
/**
* Returns whether the class with the specified name should have its metadata loaded.
* This is only the case if it is either mapped as an Entity or a MappedSuperclass.
*
* @param string $className
*
* @return bool
*/
public function isTransient($className)
{
return
! $this->mappers->hasMapperFor($className) ||
$this->mappers->getMapperFor($className)->isTransient();
}
/**
* @param string[] $mappings
*/
public function addMappings(array $mappings = [])
{
foreach ($mappings as $class) {
if (!class_exists($class)) {
throw new InvalidArgumentException("Mapping class [{$class}] does not exist");
}
$mapping = new $class;
if (!$mapping instanceof Mapping) {
throw new InvalidArgumentException("Mapping class [{$class}] should implement " . Mapping::class);
}
$this->addMapping($mapping);
}
}
/**
* @param Mapping $mapping
*
* @throws MappingException
* @return void
*/
public function addMapping(Mapping $mapping)
{
$this->mappers->add($mapping);
}
/**
* @return MapperSet
*/
public function getMappers()
{
return $this->mappers;
}
/**
* Override the default Fluent factory method with a custom one.
* Use this to implement your own Fluent builder.
* The method will receive a ClassMetadata object as its only argument.
*
* @param callable $factory
*/
public function setFluentFactory(callable $factory)
{
$this->fluentFactory = $factory;
}
/**
* @param ClassMetadata $metadata
* @return Fluent
*/
protected function getFluent(ClassMetadata $metadata)
{
return call_user_func($this->fluentFactory, $metadata);
}
}
| mit |
aponsin/basic-online-mail-merge | config/environments/production.rb | 2982 | BasicOnlineMailMerge::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
config.action_mailer.smtp_settings = {
:address => "in.mailjet.com",
:port => 587,
:domain => 'something.com',
:user_name => ENV['MAIL_JET_USERNAME'],
:password => ENV['MAIL_JET_PASSWORD'],
:authentication => 'plain',
:enable_starttls_auto => true }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default :charset => "utf-8"
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
| mit |
jinaveiras/Qt-basic-interpreter | doc/Documentación doxygen/search/functions_69.js | 3239 | var searchData=
[
['inicializa',['inicializa',['../class_parser.html#a94b1efb497d47ea53d6699c5ad164b3d',1,'Parser::inicializa()'],['../class_scanner.html#a8dbdd837a88b1eee5f064a5467d8d404',1,'Scanner::inicializa()']]],
['input',['Input',['../class_input.html#abae3f379d3f157cf42dc857309832dba',1,'Input::Input()'],['../class_input.html#a071ba1844b4d34c7e9592395dd5d91b4',1,'Input::Input(QWidget *prnt)']]],
['instrgoto',['InstrGOTO',['../class_instr_g_o_t_o.html#a52ee7e23b44fc5fe5adf81a3f16e8ee7',1,'InstrGOTO::InstrGOTO()'],['../class_instr_g_o_t_o.html#a61358ad8782c16a2f0a04b13d164eb69',1,'InstrGOTO::InstrGOTO(const string nEtiq, Parser *p)']]],
['instrif',['InstrIF',['../class_instr_i_f.html#a9bc5356e0ebb3348e483de2d2e2d1717',1,'InstrIF::InstrIF()'],['../class_instr_i_f.html#ae62e2f65966b26c2c97ee10f8295ca3e',1,'InstrIF::InstrIF(Operando *a, Operando *b, Operador *opr, std::string jmp, Parser *p)'],['../class_instr_i_f.html#a6e66a610c22bb625abf2047dbc720e2e',1,'InstrIF::InstrIF(Operando *a, std::string jmp, Parser *p)']]],
['instrinput',['InstrINPUT',['../class_instr_i_n_p_u_t.html#a11f69b5b28a7a847cefb16dd269de5bb',1,'InstrINPUT::InstrINPUT()'],['../class_instr_i_n_p_u_t.html#a02df7507150e4ab3a5bdf6a34fafab53',1,'InstrINPUT::InstrINPUT(Operando *txt, Operando *dest, Input *i)']]],
['instrlet',['InstrLET',['../class_instr_l_e_t.html#a4daf72b203b61c8522821aee617b8545',1,'InstrLET::InstrLET()'],['../class_instr_l_e_t.html#a8770bd8195bdb021f11db95f61ffbbe7',1,'InstrLET::InstrLET(Operando *dest, Operando *a, Operando *b, Operador *op)'],['../class_instr_l_e_t.html#ab09e5208ab3e87247c268d013746bba3',1,'InstrLET::InstrLET(Operando *dest, Operando *a)']]],
['instrprint',['InstrPRINT',['../class_instr_p_r_i_n_t.html#a3dbcb9eafa0e593bcb6fc3a832ec6f5f',1,'InstrPRINT::InstrPRINT()'],['../class_instr_p_r_i_n_t.html#a277c48882c510ce48a71ecad3029ad8f',1,'InstrPRINT::InstrPRINT(vector< Operando * > txt, Output *o)']]],
['inttostr',['intToStr',['../class_op_entero.html#a982e60e4d69a7668b3136f24dea68b04',1,'OpEntero']]],
['isbooleano',['isBooleano',['../class_parser.html#a6dec252a0e7fde37f06ff2c606268e70',1,'Parser']]],
['iscadena',['isCadena',['../class_parser.html#a53545c74d30a5cfb28165564a0885de6',1,'Parser']]],
['isentero',['isEntero',['../class_parser.html#a3a806912dc29a7b95f06a5c3d93a1e8b',1,'Parser']]],
['isflotante',['isFlotante',['../class_parser.html#a78aaaa601dceb187be42207ec322adc1',1,'Parser']]],
['isnumber',['isNumber',['../class_parser.html#a8d4b60a41b3c02bde877838be718add0',1,'Parser']]],
['ist',['isT',['../class_operando.html#a0988fe21c600ab4d17bb61f7338bff3d',1,'Operando']]],
['istype',['isType',['../class_op_booleano.html#a4b72045faf35ee9c01ed94a5a000039f',1,'OpBooleano::isType()'],['../class_op_cadena.html#ac0bdaa2c7fee0c988f0c7acb9f9242a1',1,'OpCadena::isType()'],['../class_op_entero.html#abd83153baae2a921eec722191f73f662',1,'OpEntero::isType()'],['../class_op_flotante.html#ad94348c56212ead3bc361198ce37d09b',1,'OpFlotante::isType()']]],
['isvalidinstr',['isValidInstr',['../class_parser.html#a4b7bea979a014ec3df04b149248e1446',1,'Parser']]],
['isvarname',['isVarName',['../class_parser.html#a35d5a54e1c64d6e72e657fda5eab9f46',1,'Parser']]]
];
| mit |
giacomelli/Escrutinador | src/Escrutinador.UnitTests/DataAnnotationsMetadataProviderTest.cs | 3345 | using NUnit.Framework;
namespace Escrutinador.UnitTests
{
[TestFixture]
public class DataAnnotationsMetadataProviderTest
{
[Test]
public void Property_StringProperty_Metadata()
{
var target = new DataAnnotationsMetadataProvider();
var actual = target.Property<DataStub>(d => d.Name);
Assert.IsNotNull(actual);
Assert.AreEqual(10, actual.MinLength);
Assert.AreEqual(50, actual.MaxLength);
Assert.AreEqual(2, actual.Order);
Assert.IsTrue(actual.Required);
actual = target.Property<DataStub>(d => d.Description);
Assert.IsNotNull(actual);
Assert.AreEqual(0, actual.MinLength);
Assert.AreEqual(int.MaxValue, actual.MaxLength);
Assert.AreEqual(1, actual.Order);
Assert.IsFalse(actual.Required);
actual = target.Property<DataStub>(d => d.Text);
Assert.IsNotNull(actual);
Assert.AreEqual(1, actual.MinLength);
Assert.AreEqual(2, actual.MaxLength);
Assert.AreEqual(int.MaxValue, actual.Order);
Assert.IsTrue(actual.Required);
}
[Test]
public void Property_IntProperty_Metadata()
{
var target = new DataAnnotationsMetadataProvider();
var actual = target.Property<DataStub>(d => d.OtherId);
Assert.IsNotNull(actual);
Assert.AreEqual(0, actual.MinLength);
Assert.AreEqual(10, actual.MaxLength);
Assert.AreEqual(int.MaxValue, actual.Order);
Assert.IsFalse(actual.Required);
}
[Test]
public void Property_UrlProperty_Metadata()
{
var target = new DataAnnotationsMetadataProvider();
var actual = target.Property<DataStub>(d => d.Url);
Assert.IsNotNull(actual);
Assert.AreEqual(0, actual.MinLength);
Assert.AreEqual(int.MaxValue, actual.MaxLength);
Assert.IsFalse(actual.Required);
Assert.IsTrue(actual.IsUrl);
}
[Test]
public void Property_EnumProperty_Metadata()
{
var target = new DataAnnotationsMetadataProvider();
var actual = target.Property<DataStub>(d => d.DateKind);
Assert.IsNotNull(actual);
Assert.AreEqual(0, actual.MinLength);
Assert.AreEqual(int.MaxValue, actual.MaxLength);
Assert.IsTrue(actual.Required);
Assert.IsFalse(actual.IsUrl);
}
[Test]
public void Property_IListProperty_Metadata()
{
var target = new DataAnnotationsMetadataProvider();
var actual = target.Property<DataStub>(d => d.Lines);
Assert.IsNotNull(actual);
Assert.AreEqual(2, actual.MinLength);
Assert.AreEqual(int.MaxValue, actual.MaxLength);
Assert.AreEqual(int.MaxValue, actual.Order);
Assert.True(actual.Required);
}
[Test]
public void Properties_NoArgs_AllPropertiesMetadata()
{
var target = new DataAnnotationsMetadataProvider();
var actual = target.Properties<DataStub>();
Assert.IsNotNull(actual);
Assert.AreEqual(7, actual.Count);
}
}
}
| mit |
yangjm/winlet | winlet/src/main/java/com/aggrepoint/winlet/jsp/taglib/IncludeParamTag.java | 574 | package com.aggrepoint.winlet.jsp.taglib;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class IncludeParamTag extends TagSupport {
private static final long serialVersionUID = 1L;
String name;
String value;
public void setName(String str) {
name = str;
}
public void setValue(String str) {
value = str;
}
public int doStartTag() throws JspException {
IncludeTag include = (IncludeTag) TagSupport.findAncestorWithClass(
this, IncludeTag.class);
include.m_params.put(name, value);
return SKIP_BODY;
}
}
| mit |
arafattehsin/CognitiveRocket | Cognitive-Library/CustomVision/Properties/AssemblyInfo.cs | 1368 | 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("CognitiveLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CognitiveLibrary")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("5197e68a-cc01-4048-ad8a-ebf806507633")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
mind0n/hive | History/Website/3js/editor/js/ui/Sidebar.Renderer.js | 1768 | Sidebar.Renderer = function ( signals ) {
var rendererClasses = {
'CanvasRenderer': THREE.CanvasRenderer,
'SoftwareRenderer': THREE.SoftwareRenderer,
'SVGRenderer': THREE.SVGRenderer,
'WebGLRenderer': THREE.WebGLRenderer
};
var container = new UI.Panel();
container.setPadding( '10px' );
container.setBorderTop( '1px solid #ccc' );
container.add( new UI.Text( 'RENDERER' ).setColor( '#666' ) );
container.add( new UI.Break(), new UI.Break() );
// class
var rendererClassRow = new UI.Panel();
var rendererClass = new UI.Select().setOptions( {
'WebGLRenderer': 'WebGLRenderer',
'CanvasRenderer': 'CanvasRenderer',
'SoftwareRenderer': 'SoftwareRenderer',
'SVGRenderer': 'SVGRenderer',
} ).setWidth( '150px' ).setColor( '#444' ).setFontSize( '12px' ).onChange( updateRenderer );
rendererClassRow.add( new UI.Text( 'Class' ).setWidth( '90px' ).setColor( '#666' ) );
rendererClassRow.add( rendererClass );
container.add( rendererClassRow );
// clear color
var clearColorRow = new UI.Panel();
var clearColor = new UI.Color().setValue( '#aaaaaa' ).onChange( updateClearColor );
clearColorRow.add( new UI.Text( 'Clear color' ).setWidth( '90px' ).setColor( '#666' ) );
clearColorRow.add( clearColor );
container.add( clearColorRow );
//
function updateRenderer() {
var renderer = new rendererClasses[ rendererClass.getValue() ]( {
antialias: true,
alpha: false,
clearColor: clearColor.getHexValue(),
clearAlpha: 1
} );
signals.rendererChanged.dispatch( renderer );
}
function updateClearColor() {
signals.clearColorChanged.dispatch( clearColor.getHexValue() );
}
// events
signals.clearColorChanged.add( function ( color ) {
clearColor.setHexValue( color );
} );
return container;
}
| mit |
crazyhitty/Capstone-Project | app/src/main/java/com/crazyhitty/chdev/ks/predator/ui/adapters/recycler/PostsRecyclerAdapter.java | 14419 | /*
* MIT License
*
* Copyright (c) 2016 Kartik Sharma
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.crazyhitty.chdev.ks.predator.ui.adapters.recycler;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.crazyhitty.chdev.ks.predator.R;
import com.crazyhitty.chdev.ks.predator.models.Post;
import com.crazyhitty.chdev.ks.predator.utils.Logger;
import com.crazyhitty.chdev.ks.predator.utils.ScreenUtils;
import com.crazyhitty.chdev.ks.producthunt_wrapper.utils.ImageUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Author: Kartik Sharma
* Email Id: cr42yh17m4n@gmail.com
* Created: 1/9/2017 10:06 AM
* Description: Unavailable
*/
public class PostsRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = "PostsRecyclerAdapter";
private static final int VIEW_TYPE_LIST = 1;
private static final int VIEW_TYPE_SMALL_CARDS = 2;
private static final int VIEW_TYPE_LARGE_CARDS = 3;
private static final int VIEW_TYPE_LOAD_MORE = 98;
private List<Post> mPosts;
private TYPE mType;
private OnPostsLoadMoreRetryListener mOnPostsLoadMoreRetryListener;
private OnItemClickListener mOnItemClickListener;
private HashMap<Integer, String> mDateHashMap = new HashMap<>();
private int mLastPosition = -1;
private boolean mNetworkAvailable;
private String mErrorMessage;
private boolean mLoadMoreNotRequired = false;
/**
* Initialize using this constructor if load more and dates functionalities are not required.
*
* @param posts List containing posts
* @param type Type of data to be displayed
*/
public PostsRecyclerAdapter(List<Post> posts, TYPE type) {
mPosts = posts;
mType = type;
mLoadMoreNotRequired = true;
}
/**
* Constructor used to create a PostRecyclerAdapter with already defined dates. General use case
* is when user want to see offline posts which doesn't support date wise pagination.
*
* @param posts List containing posts
* @param type Type of data to be displayed
* @param dateHashMap Hashmap containing where to show appropriate dates
* @param onPostsLoadMoreRetryListener listener that will notify when to load more posts
*/
public PostsRecyclerAdapter(List<Post> posts,
TYPE type,
HashMap<Integer, String> dateHashMap,
OnPostsLoadMoreRetryListener onPostsLoadMoreRetryListener) {
mPosts = posts;
mType = type;
mDateHashMap = dateHashMap;
mOnPostsLoadMoreRetryListener = onPostsLoadMoreRetryListener;
mLoadMoreNotRequired = false;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
public void setOnPostsLoadMoreRetryListener(OnPostsLoadMoreRetryListener onPostsLoadMoreRetryListener) {
mOnPostsLoadMoreRetryListener = onPostsLoadMoreRetryListener;
mLoadMoreNotRequired = false;
}
public void setLoadMore(boolean canLoadMore) {
mLoadMoreNotRequired = !canLoadMore;
}
public boolean canLoadMore() {
return !mLoadMoreNotRequired;
}
public void setType(TYPE type) {
mType = type;
}
/**
* Update current dataset.
*
* @param posts
* @param dateHashMap
* @param forceReplace
*/
public void updateDataset(List<Post> posts, HashMap<Integer, String> dateHashMap, boolean forceReplace) {
mDateHashMap = dateHashMap;
mPosts = posts;
if (forceReplace) {
mLastPosition = -1;
notifyDataSetChanged();
} else {
int oldCount = mPosts.size();
notifyItemRangeInserted(oldCount, mPosts.size() - oldCount);
}
}
/**
* Update current dataset.
*
* @param posts
* @param forceReplace
*/
public void updateDataset(List<Post> posts, boolean forceReplace) {
mPosts = posts;
if (forceReplace) {
mLastPosition = -1;
}
notifyDataSetChanged();
}
public void addDataset(@NonNull List<Post> posts) {
if (mPosts != null) {
int oldCount = mPosts.size();
mPosts.addAll(posts);
notifyItemRangeInserted(oldCount, mPosts.size() - oldCount);
}
}
public void setNetworkStatus(boolean status, String message) {
mNetworkAvailable = status;
mErrorMessage = message;
if (!isEmpty() && canLoadMore()) {
notifyItemChanged(getItemCount() - 1);
}
}
public void removeLoadingView() {
notifyItemRemoved(getItemCount() - 1);
}
public void clear() {
mPosts = null;
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RecyclerView.ViewHolder viewHolder = null;
switch (viewType) {
case VIEW_TYPE_LIST:
View viewListType = layoutInflater.inflate(R.layout.item_list_post, parent, false);
viewHolder = new ListItemViewHolder(viewListType);
break;
case VIEW_TYPE_LOAD_MORE:
View viewLoadMore = layoutInflater.inflate(R.layout.item_load_more_posts, parent, false);
viewHolder = new LoadMoreViewHolder(viewLoadMore);
break;
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_LIST:
onBindListItemViewHolder((ListItemViewHolder) holder, position);
break;
case VIEW_TYPE_LOAD_MORE:
onBindLoadMoreViewHolder((LoadMoreViewHolder) holder, position);
break;
}
manageAnimation(holder.itemView, position);
}
private void onBindListItemViewHolder(final ListItemViewHolder listItemViewHolder, int position) {
String title = mPosts.get(position).getName();
String shortDesc = mPosts.get(position).getTagline();
Spannable titleSpannable = mPosts.get(position).getNameSpannable();
Spannable shortDescSpannable = mPosts.get(position).getTaglineSpannable();
Logger.d(TAG, "titleSpannable: " + titleSpannable);
Logger.d(TAG, "shortDescSpannable: " + shortDescSpannable);
String postImageUrl = mPosts.get(position).getThumbnailImageUrl();
postImageUrl = ImageUtils.getCustomPostThumbnailImageUrl(postImageUrl,
ScreenUtils.dpToPxInt(listItemViewHolder.itemView.getContext(), 44),
ScreenUtils.dpToPxInt(listItemViewHolder.itemView.getContext(), 44));
String date = mDateHashMap.get(position);
boolean showDate = (date != null);
listItemViewHolder.txtPostTitle.setText(titleSpannable != null ? titleSpannable : title);
listItemViewHolder.txtShortDesc.setText(shortDescSpannable != null ? shortDescSpannable : shortDesc);
listItemViewHolder.txtDate.setText(date);
listItemViewHolder.txtDate.setVisibility(showDate ? View.VISIBLE : View.GONE);
listItemViewHolder.imageViewPost.setImageURI(postImageUrl);
listItemViewHolder.relativeLayoutPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(listItemViewHolder.getAdapterPosition());
}
}
});
}
private void onBindLoadMoreViewHolder(LoadMoreViewHolder loadMoreViewHolder, int position) {
// All elements except progress bar will be visible if network is available, and vice versa.
loadMoreViewHolder.imgViewError.setVisibility(mNetworkAvailable ? View.GONE : View.VISIBLE);
loadMoreViewHolder.txtErrorTitle.setVisibility(mNetworkAvailable ? View.GONE : View.VISIBLE);
loadMoreViewHolder.txtErrorDesc.setVisibility(mNetworkAvailable ? View.GONE : View.VISIBLE);
loadMoreViewHolder.btnRetry.setVisibility(mNetworkAvailable ? View.GONE : View.VISIBLE);
loadMoreViewHolder.progressBarLoading.setVisibility(mNetworkAvailable ? View.VISIBLE : View.GONE);
loadMoreViewHolder.txtErrorDesc.setText(mErrorMessage);
loadMoreViewHolder.btnRetry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnPostsLoadMoreRetryListener.onLoadMore();
}
});
}
private void manageAnimation(View view, int position) {
if (position > mLastPosition) {
Animation animation = AnimationUtils.loadAnimation(view.getContext(),
R.anim.anim_bottom_top_fade_in);
view.startAnimation(animation);
mLastPosition = position;
}
}
@Override
public int getItemCount() {
if (mLoadMoreNotRequired) {
return mPosts != null ?
mPosts.size() : 0;
} else {
// Add extra item, that will be shown in case of load more scenario.
return mPosts != null ?
mPosts.size() + 1 : 0;
}
}
public boolean isEmpty() {
return mPosts == null || mPosts.isEmpty();
}
/**
* @param position Current position of the element.
* @return Returns the unique id associated with the item at available position.
*/
public int getId(int position) {
return mPosts.get(position).getId();
}
/**
* @param position Current position of the element.
* @return Returns the unique post id associated with the item at available position.
*/
public int getPostId(int position) {
return mPosts.get(position).getPostId();
}
public Post getPost(int position) {
return mPosts.get(position);
}
@Override
public int getItemViewType(int position) {
// If last position, then show "load more" view to the user.
if (position == getItemCount() - 1 && !mLoadMoreNotRequired) {
return VIEW_TYPE_LOAD_MORE;
}
switch (mType) {
case LIST:
return VIEW_TYPE_LIST;
case SMALL_CARDS:
return VIEW_TYPE_SMALL_CARDS;
case LARGE_CARDS:
return VIEW_TYPE_LARGE_CARDS;
default:
return VIEW_TYPE_LIST;
}
}
@Override
public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
super.onViewDetachedFromWindow(holder);
((RootViewHolder) holder).clearAnimation();
}
public enum TYPE {
LIST,
SMALL_CARDS,
LARGE_CARDS
}
public interface OnPostsLoadMoreRetryListener {
void onLoadMore();
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public static class ListItemViewHolder extends RootViewHolder {
@BindView(R.id.text_view_date)
TextView txtDate;
@BindView(R.id.image_view_post)
SimpleDraweeView imageViewPost;
@BindView(R.id.text_view_post_title)
TextView txtPostTitle;
@BindView(R.id.text_view_post_short_desc)
TextView txtShortDesc;
@BindView(R.id.checkbox_bookmark)
CheckBox checkBoxBookmark;
@BindView(R.id.relative_layout_post)
RelativeLayout relativeLayoutPost;
public ListItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public static class LoadMoreViewHolder extends RootViewHolder {
@BindView(R.id.image_view_error_icon)
SimpleDraweeView imgViewError;
@BindView(R.id.text_view_error_title)
TextView txtErrorTitle;
@BindView(R.id.text_view_error_desc)
TextView txtErrorDesc;
@BindView(R.id.button_retry)
Button btnRetry;
@BindView(R.id.progress_bar_loading)
ProgressBar progressBarLoading;
public LoadMoreViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
private static class RootViewHolder extends RecyclerView.ViewHolder {
public RootViewHolder(View itemView) {
super(itemView);
}
protected void clearAnimation() {
itemView.clearAnimation();
}
}
}
| mit |
lopezdp/JavaPracticeProblems | ResControl.java | 6194 | /**
* David P. Lopez
* COP2800 Test-2
* Programming Assignment
*/
package oysterBar;
import java.util.Scanner;
/**
* 305.467.5719
* @author david.lopez016@mymdc.net
*/
public class ResControl {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
boolean closed = false;
boolean t1 = true;
int menuSelect;
int numGuest;
Scanner userInput;
userInput = new Scanner(System.in);
GroupSeating reservationSys = new GroupSeating();
while(t1)
{
menuSelect = reservationSys.programMenu(closed);
if(menuSelect == 1)
{
boolean t = true;
while(t)
{
System.out.print ("Enter # of Guests in Group: ");
if(userInput.hasNextInt())
{
numGuest = userInput.nextInt();
if(numGuest > 0)
{
reservationSys.setGrSiz(numGuest);
if((reservationSys.getGrSiz() + reservationSys.getBarSiz()) == 100)
{
System.out.println("You are at Max Capacity!!! ");
System.out.println("The amount of people seated "
+ "in the Oyster Bar is: "
+ (reservationSys.getBarSiz()+reservationSys.getGrSiz()));
System.out.print ("Enter Q to QUIT the Program & Close: ");
while(!userInput.hasNext("[Qq]"))
{
System.out.print("PLEASE ENTER Q TO QUIT!!!");
userInput.next();
}
String exit = userInput.next();
System.out.println("Thank you. The program is shutting down..." + exit);
System.exit(0);
break;
}
while((reservationSys.getGrSiz() + reservationSys.getBarSiz()) > 100)
{
System.out.println("There is not enough seating "
+ "available for your party. Please enter a party "
+ "with guest amount less than or equal to: "
+ (100 - reservationSys.getBarSiz()));
reservationSys.setGrSiz(0);
System.out.print ("Enter # of Guests in the next Group: ");
numGuest = userInput.nextInt();
reservationSys.setGrSiz(numGuest);
}
reservationSys.setBarStd(numGuest);
t = false;
}
else
{
System.out.println("Error!!! This is not a valid input!!!"
+ "For security purposes we have recorded your IP address."
+ "Please enter a valid input.");
}
}
else
{
System.out.println("Error!!! This is not a valid input!!!"
+ "For security purposes we have recorded your IP address."
+ "Please enter a valid input.");
t = false;
}
reservationSys.setGrSiz(0);
}
}
if(menuSelect == 2)
{
boolean t = true;
while(t)
{
System.out.print ("Enter # of Guests leaving Bar: ");
if(userInput.hasNextInt())
{
numGuest = userInput.nextInt();
if(numGuest > 0)
{
reservationSys.setGrSiz(-(numGuest));
reservationSys.setBarStd(numGuest);
reservationSys.setClosed();
t = false;
}
else
{
System.out.println("Error!!! This is not a valid input!!!"
+ "For security purposes we have recorded your IP address."
+ "Please enter a valid input.");
}
}
else
{
System.out.println("Error!!! This is not a valid input!!!"
+ "For security purposes we have recorded your IP address."
+ "Please enter a valid input.");
}
}
}
System.out.println("Available Seating is: " + (100 - reservationSys.getBarSiz()));
reservationSys.setGrSiz(0);
if(reservationSys.getBarSiz() == 100)
{
System.out.println("You are at Max Capacity!!! "
+ "The Program has TERMINATED & the BAR IS NOW CLOSED");
t1 = false;
System.exit(0);
}
}
}
}
| mit |
buzzler/titan | Assets/Packages/Vortex Game Studios/Editor/UEditor.cs | 2117 | using UnityEditor;
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
namespace UT.UEditor {
public class UEditor {
#region Inspector Box Component
public static void BeginBox( string title, Color color ) {
// Actions list
GUI.backgroundColor = color;
GUILayout.BeginVertical( "AS TextArea", GUILayout.Height( 5 ) );
GUI.backgroundColor = Color.white;
if ( title != "" ) {
GUILayout.Space( 2 );
GUILayout.Label( title );
}
}
public static void EndBox() {
GUILayout.EndVertical();
}
#endregion
#region Inspector Group Component
public static bool BeginGroup( Texture2D icon, string title, bool fooldout, Color color ) {
bool returnValue = false;
GUI.backgroundColor = color;
GUILayout.BeginVertical( "AS TextArea", GUILayout.Height( 5 ) );
GUI.backgroundColor = Color.white;
GUILayout.Space( 2 );
GUILayout.BeginHorizontal();
if ( icon != null ) {
GUIContent content = new GUIContent( title, icon );
returnValue = EditorGUILayout.Foldout( fooldout, content );
} else {
returnValue = EditorGUILayout.Foldout( fooldout, title );
}
/*
if( list == null ) {
GUILayout.FlexibleSpace();
GUILayout.Button( "▲", GUILayout.Width(32) );
GUILayout.Button( "▼", GUILayout.Width(32) );
GUI.backgroundColor = Color.red;
GUILayout.Button( "×", GUILayout.Width(32) );
GUI.backgroundColor = Color.white;
}
*/
GUILayout.EndHorizontal();
return returnValue;
}
public static void EndGroup() {
GUILayout.EndVertical();
GUILayout.Space( 2 );
}
#endregion
}
} | mit |
grncdr/node-any-db | packages/any-db-adapter-spec/interfaces/connection.js | 484 | var Queryable = require('./queryable')
exports.testProperties = function(connection, adapter, assert) {
Queryable.testProperties(connection, adapter, assert, 'connection')
assert.equal(typeof connection.end, 'function')
}
exports.testEvents = function(connection, assert) {
connection.on('open', function() {
assert.ok(1, 'connection.emit("open")')
Queryable.testEvents(connection, assert, 'connection')
})
}
exports.testEvents.plan = 1 + Queryable.testEvents.plan
| mit |
mmazilu/FullStackStarter | NodeJS/routes/routes.js | 3657 | var express = require('express');
var router = express.Router();
var UserController = require('./userController');
var BoardController = require('./boardController');
// Authentication and Authorization Middleware
var auth = function(req, res, next) {
if (req.session && req.session.loggedIn === true)
return next();
else
return res.sendStatus(401);
};
router.get('/login', function (req, res) {
if (!req.query.username || !req.query.password) {
res.sendStatus(400);
} else {
UserController.getUser(req.query.username)
.then((users) => {
console.log(users);
if (users.length > 0) {
if(users[0].username === req.query.username && req.query.password === users[0].password) {
req.session.loggedIn = true;
req.session.username = req.query.username;
res.sendStatus(200);
}
} else {
res.send(401);
}
})
.catch((err) => {
console.log(err);
res.sendStatus(500);
});
}
});
router.get('/private/profile', auth, function (req, res) {
UserController.getUser(req.session.username)
.then((users) => {
if (users.length > 0) {
var obj = {name:users[0].name};
res.send(obj);
} else {
res.send(401);
}
})
.catch((err) => {
console.log(err);
res.sendStatus(500);
});
});
router.post('/signup', function (req, res) {
if (!req.body.username || !req.body.password || !req.body.name) {
res.sendStatus(400);
} else {
UserController.getUser(req.body.username)
.then(function(users){
if (users.length > 0) {
res.sendStatus(403);
} else {
var newUser = {
username: req.body.username,
password: req.body.password,
name: req.body.name
};
UserController.saveUser(newUser)
.then(function() {
res.sendStatus(200);
})
.catch(function() {
res.sendStatus(500);
});
}
})
.catch(function(err){
console.log(err);
res.sendStatus(500);
});
}
});
router.post('/private/postmessage', auth, function (req, res) {
if (!req.body.message) {
res.sendStatus(400);
} else {
var message = {
username: req.session.username,
message: req.body.message,
board: "main",
date: new Date()
};
BoardController.saveMessage(message)
.then(function() {
res.sendStatus(200);
})
.catch(function() {
res.sendStatus(500);
});
}
});
router.get('/private/messages', auth, function(req, res) {
BoardController.getMessages(
(code)=>{
res.sendStatus(status);
},
(users)=>{
res.send(users);
});
});
router.get('/private/users', auth, function(req, res) {
UserController.getUsers(
(code)=>{
res.sendStatus(status);
},
(users)=>{
res.send(users);
});
});
module.exports = router;
| mit |
davidhuynh/ludi.graphics | Test/Psuedocode.cpp | 884 |
int main(int argc, char** argv) {
Program* program = Program::Create(<config>);
program->Shader<Shader::kVertex>()->type();
Shader* tempShader = program->Shader<Shader::kVertex>();
program->Attach(Shader);
Shader* vertexShader;
//vertexShader->introspection();
Pipeline* pipeline;
//pipeline->Stage<kVertex>()->BindShader(vertexShader);
pipeline->Stage<Stage::kVertex>()->BindShader(vertexShader);
pipeline->Stage<Stage::kInputAssembler>()->BindVertexBuffer(someVertexBuffer);
pipeline->Stage<Stage::kInputAssembler>()->BindIndexBuffer(someIndexBuffer);
pipeline->Stage<Stage::kVertex>()->BindShader(vertexShader);
pipeline->Stage<Stage::kPixel>()->BindShader(pixelShader);
pipeline->Stage<Stage::kGeometry>()->BindShader(pixelShader);
// more stuff
pipeline->Draw(vertexCount);
return 0;
}
| mit |
lozjackson/ember-time-tools | tests/integration/components/tt-picker-item-test.js | 540 | import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('tt-picker-item', 'Integration | Component | tt picker item', {
integration: true
});
test('it renders', function(assert) {
this.render(hbs`{{tt-picker-item}}`);
assert.equal(this.$().text().trim(), '');
assert.equal(this.$('td').length, 1);
this.render(hbs`
{{#tt-picker-item}}
template block text
{{/tt-picker-item}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
| mit |
herpec-j/BehaviorTree | BehaviorTree/Includes/BehaviorTree/Details/DecimalCondition.hpp | 3313 | #pragma once
#include <functional>
#include <limits>
#include <cmath>
#include <cassert>
#include "BehaviorTree/Details/ConditionNode.hpp"
#include "BehaviorTree/Details/ConditionTest.hpp"
#include "BehaviorTree/Details/Private/DecimalConditionEnabler.hpp"
namespace AO
{
namespace BehaviorTree
{
inline namespace Version_1
{
namespace Details
{
template < typename DecimalType, class Entity, typename... Args >
class DecimalCondition final : public ConditionNode<Entity, Args...>, public Private::DecimalConditionEnabler < DecimalType >
{
private:
using EntityType = typename ConditionNode<Entity, Args...>::EntityType;
using EntityPtr = typename ConditionNode<Entity, Args...>::EntityPtr;
using Parent = typename ConditionNode<Entity, Args...>::Parent;
using ParentPtr = typename ConditionNode<Entity, Args...>::ParentPtr;
using Function = std::function < DecimalType(EntityPtr, Args...) > ;
// Attributes
Function function;
ConditionTest condition;
DecimalType target;
DecimalType epsilon;
// Static Methods
static bool Equals(DecimalType lhs, DecimalType rhs, DecimalType epsilon)
{
return std::abs(lhs - rhs) <= epsilon;
}
// Inherited Methods
void initialize(EntityPtr) override final
{
return;
}
Status decide(EntityPtr entity, Args... args) override final
{
DecimalType const result = function(entity, args...);
switch (condition)
{
case ConditionTest::LessThan:
return result < target && !DecimalCondition::Equals(result, target, epsilon) ? Status::Success : Status::Failure;
case ConditionTest::GreaterThan:
return result > target && !DecimalCondition::Equals(result, target, epsilon) ? Status::Success : Status::Failure;
case ConditionTest::LessOrEqualThan:
return result < target || DecimalCondition::Equals(result, target, epsilon) ? Status::Success : Status::Failure;
case ConditionTest::GreaterOrEqualThan:
return result > target || DecimalCondition::Equals(result, target, epsilon) ? Status::Success : Status::Failure;
case ConditionTest::Equal:
return DecimalCondition::Equals(result, target, epsilon) ? Status::Success : Status::Failure;
case ConditionTest::NotEqual:
return !DecimalCondition::Equals(result, target, epsilon) ? Status::Success : Status::Failure;
default:
return Status::Failure;
}
}
public:
// Constructors
DecimalCondition(void) = delete;
DecimalCondition(Function const &function, ConditionTest condition, DecimalType target, DecimalType epsilon = std::numeric_limits<DecimalType>::epsilon())
: ConditionNode<Entity, Args...>(), Private::DecimalConditionEnabler<DecimalType>(), function(function), condition(condition), target(target), epsilon(epsilon)
{
assert(function && "Invalid function");
}
DecimalCondition(DecimalCondition const &) = default;
DecimalCondition(DecimalCondition &&) = default;
// Assignment Operators
DecimalCondition &operator=(DecimalCondition const &) = default;
DecimalCondition &operator=(DecimalCondition &&) = default;
// Destructor
~DecimalCondition(void) = default;
};
}
}
}
}
| mit |
nicoagostini/sistemademandas | classes/bd.class.php | 840 | <?php
class bd{
public $conexao;
public $id;
public function __construct(){
$this->conexao = new mysqli("localhost", "root", "", "sistemaif");
}
public function consulta($select){
$this->conexao->query($select);
$retorno = array();
$dados = array();
$result = $this->conexao->query($select);
while($retorno = $result->fetch_array(MYSQLI_NUM)) {
$dados[] = $retorno;
}
return $dados;
}
public function executa($sql){
/*
Pq só essa variável começa com maiúscula?
*/
$RetornoExecucao = $this->conexao->query($sql);
$this->id = $this->conexao->insert_id;
return $RetornoExecucao;
}
public function insereID($sql){
$this->conexao->query($sql);
return $this->conexao->insert_id;
}
public function __destruct(){
$this->conexao->close();
}
}
?> | mit |
khowrurk/MSA | application/views/pages/dashboard/expenseAndWeight/index.php | 8343 | <?php
if(isset($_SESSION["MSA"]["right"])){
$right=$_SESSION["MSA"]["right"];
}
$loggedIn=$_SESSION["MSA"]["loggedIn"];
?>
<script src="assets/js/Highcharts-5.0.6/code/highcharts.js" type="text/javascript"></script>
<script src="assets/js/Highcharts-5.0.6/code/modules/drilldown.js" type="text/javascript"></script>
<section id="content" style="padding-bottom: 50px;">
<!--breadcrumbs start-->
<div id="breadcrumbs-wrapper">
<!-- Search for small screen -->
<div class="header-search-wrapper grey hide-on-large-only">
<i class="mdi-action-search active"></i>
<input type="text" name="Search" class="header-search-input z-depth-2" placeholder="Explore Materialize">
</div>
<div class="container">
<div class="row">
<div class="col s3">
<h5 class="breadcrumbs-title">Dashboard</h5>
<ol class="breadcrumbs">
<li class='active'>Dashboard</li>
</ol>
</div>
<div class="col s9" style="padding-top: 10px;">
<div class="col s4 input-field">
<select name="monNum" id="monNum">
<option value="">ทุกเดือน</option>
<?php
for($i=1;$i<=12;$i++){
?>
<option value="<?=$i?>"><?=$monName[$i]?></option>
<?php
}
?>
</select>
<label for="monNum">เดือน</label>
</div>
<div class="col s4 input-field">
<select name="yearNum" id="yearNum">
<?php
for($i=2016;$i<=date("Y");$i++){
?>
<option value="<?=$i?>"><?=$i+543?></option>
<?php
}
?>
</select>
<label for="yearNum">ปี</label>
</div>
<div class="col s4 input-field">
<select name="branchID" id="branchID">
<?php
if(isset($right["view-allBranch"])){
?>
<option value="">ทุกสาขา</option>
<?php
foreach ($branchName as $key => $value) {
?>
<option value="<?=$key?>"><?=$value?></option>
<?php
}
?>
<?php
}else{
?>
<option value="<?=$loggedIn["branchID"]?>"><?=$branchName[$loggedIn["branchID"]]?></option>
<?php
}
?>
</select>
<label for="branchID">สาขา</label>
</div>
</div>
</div>
</div>
</div>
<div class="row" style="position: relative;">
<div id="loading-container" style="position: fixed;top: 50%;left: 50%;z-index:3000">
<div class="windows8">
<div class="wBall" id="wBall_1">
<div class="wInnerBall"></div>
</div>
<div class="wBall" id="wBall_2">
<div class="wInnerBall"></div>
</div>
<div class="wBall" id="wBall_3">
<div class="wInnerBall"></div>
</div>
<div class="wBall" id="wBall_4">
<div class="wInnerBall"></div>
</div>
<div class="wBall" id="wBall_5">
<div class="wInnerBall"></div>
</div>
</div>
<br>
กรุณารอสักครู่
</div>
<div class="fixed-action-btn">
<button id="button-refresh" type="button" class="btn-floating btn-large red waves-effect waves-light">
<i class="fa fa-refresh" aria-hidden="true"></i>
</button>
</div>
<div class="col s12" style="padding-top: 20px;">
<div id="graph-container" style="height: 520px;width: 100%;"></div>
</div>
</div>
</section>
<?php
require_once dirname(__FILE__)."/allMonthAllBranch.php";
require_once dirname(__FILE__)."/allMonthBranch.php";
require_once dirname(__FILE__)."/monthAllBranch.php";
require_once dirname(__FILE__)."/monthBranch.php";
require_once dirname(__FILE__)."/../daObj.php";
?>
<script type="text/javascript">
var filter={};
var dashObj={
init: function(){
this.showLoading();
$('#branchID').change(function(){
dashObj.showGraph();
});
$('#yearNum').change(function(){
dashObj.showGraph();
});
$('#monNum').change(function(){
dashObj.showGraph();
});
$('#button-refresh').click(function(){
dashObj.showGraph();
});
},
showLoading: function(){
$('#loading-container').fadeIn();
},
hideLoading: function(){
$('#loading-container').fadeOut();
},
showGraph: function(){
var branchID=$('#branchID').val();
var yearNum=$('#yearNum').val();
var monNum=$('#monNum').val();
if(monNum=='' & branchID==''){
dashObj.getAllMonthAllBranch();
}else if(monNum=='' && branchID!=''){
dashObj.getAllMonthBranch();
}else if(monNum!='' && branchID==''){
dashObj.getMonthAllBranch();
}else if(monNum!='' && branchID!=''){
dashObj.getMonthBranch();
}
},
getAllMonthAllBranch: function(){
dashObj.showLoading();
filter.yearNum=$('#yearNum').val();
filter.monNum=$('#monNum').val();
filter.branchID=$('#branchID').val();
filter.weightAndExpense=true;
allMonthAllBranch(function(){
// console.log(daObj.graph21);
$('#graph-container').highcharts(daObj.graph31);
dashObj.hideLoading();
});
},
getMonthAllBranch: function(){
dashObj.showLoading();
filter.yearNum=$('#yearNum').val();
filter.monNum=$('#monNum').val();
filter.branchID=$('#branchID').val();
filter.weightAndExpense=true;
monthAllBranch(function(){
// console.log(daObj.graph21);
$('#graph-container').highcharts(daObj.graph31);
dashObj.hideLoading();
});
},
getMonthBranch: function(){
dashObj.showLoading();
filter.yearNum=$('#yearNum').val();
filter.monNum=$('#monNum').val();
filter.branchID=$('#branchID').val();
filter.weightAndExpense=true;
monthBranch(function(){
// console.log(daObj.graph21);
$('#graph-container').highcharts(daObj.graph32);
dashObj.hideLoading();
});
},
getAllMonthBranch: function(){
dashObj.showLoading();
filter.yearNum=$('#yearNum').val();
filter.monNum=$('#monNum').val();
filter.branchID=$('#branchID').val();
filter.weightAndExpense=true;
allMonthBranch(function(){
// console.log(daObj.graph21);
$('#graph-container').highcharts(daObj.graph32);
dashObj.hideLoading();
});
}
}
dashObj.init();
dashObj.getAllMonthAllBranch();
</script>
| mit |
Yasushi/oxidized_silver_bird | lib/popup/theme_manager.js | 6043 | var ThemeManager = {
init: function () {
$("link.theme").remove();
var theme = OptionsBackend.get('theme');
$(theme.split(",")).each(function(i, p) {
$("<link rel='stylesheet' type='text/css' class='theme' href='" + p + "'>").appendTo(document.head);
});
var baseStyle = $("#base_stylesheet")[0];
if(baseStyle.sheet && baseStyle.sheet.cssRules) {
var baseRules = baseStyle.sheet.cssRules;
var fontFamily = OptionsBackend.get('font_family');
var fontSize = OptionsBackend.get('font_size');
for(var i = 0, len = baseRules.length; i < len; ++i) {
var rule = baseRules[i];
if(rule.selectorText == ".tweet") {
rule.style.fontFamily = fontFamily;
rule.style.fontSize = fontSize;
break;
}
}
}
ThemeManager.isPopup = location.search == '?popup';
ThemeManager.isDetached = location.search == '?detached';
if(!ThemeManager.isPopup) {
$('<base target="_blank">').appendTo(document.head);
}
var persistedPosition = Persistence.windowPosition();
ThemeManager.detachedPos = persistedPosition.val();
if(!ThemeManager.detachedPos) {
// Setting default values
ThemeManager.detachedPos = {
left: 100,
top: 100,
height: null,
width: null
};
persistedPosition.save(ThemeManager.detachedPos);
}
if(ThemeManager.isDetached) {
$("#detach_img").hide();
// Listening to resize and move events
$(window).resize(function() {
ThemeManager.detachedPos.height = window.innerHeight;
ThemeManager.detachedPos.width = window.innerWidth;
persistedPosition.save(ThemeManager.detachedPos);
});
setInterval(function() {
if(ThemeManager.detachedPos.left != window.screenLeft || ThemeManager.detachedPos.top != window.screenTop) {
ThemeManager.detachedPos.left = window.screenLeft;
ThemeManager.detachedPos.top = window.screenTop;
persistedPosition.save(ThemeManager.detachedPos);
}
}, 1000);
}
},
setPopupSize: function(width, height, autoFitWidth) {
if(!ThemeManager.isPopup) {
return;
}
/* HACK: Magic numbers */
var hackBordersWidth = 14;
var hackTabsAdditionalWidth = 40;
var hackMinValidHeight = 400;
width = width || 490;
height = height || 400;
var minWidth = 450;
var maxWidth = 800 - hackBordersWidth;
if(width > maxWidth) {
width = maxWidth;
}
if(width < minWidth) {
width = minWidth;
}
if(autoFitWidth) {
setTimeout(function() {
var tabsBarWidth = 0;
$("li.timeline_tab").each(function() {
tabsBarWidth += $(this).outerWidth();
});
tabsBarWidth += hackTabsAdditionalWidth;
if(tabsBarWidth > width) {
ThemeManager.setPopupSize(tabsBarWidth, height);
}
}, 300);
}
$(".timeline").width(width + 'px');
$(".inner_timeline,.timeline").height(height + 'px');
var hackHeaderHeight = $(".timeline")[0].getBoundingClientRect().top || 74;
setTimeout(function() {
if(window.innerHeight < hackMinValidHeight) { return; }
if(window.innerHeight < ($(".timeline").height() + hackHeaderHeight)) {
var height = window.innerHeight - hackHeaderHeight;
ThemeManager.setPopupSize(width, height, autoFitWidth);
}
}, 100);
},
popupSizeData: Persistence.popupSize(),
initWindowResizing: function() {
ThemeManager.handleWindowResizing();
if(!ThemeManager.isPopup) {
var resizeFunc = function() {
var timelineHeight = window.innerHeight - 79;
$('.inner_timeline,.timeline').css('maxHeight', timelineHeight + 'px');
};
$(window).resize(resizeFunc);
resizeFunc();
return;
}
$(".timeline").resizable({
handles: 'e, s, se',
minWidth: 450,
resize: function(e, ui) {
var $this = $(this);
ThemeManager.setPopupSize($this.width(), $this.height());
},
stop: function(e, ui) {
var $this = $(this);
ThemeManager.popupSizeData.save($this.width() + 'x' + $this.height());
}
});
$(".ui-resizable-handle").attr('title', chrome.i18n.getMessage("resetSize"));
$(".ui-resizable-handle").dblclick(function(e) {
ThemeManager.popupSizeData.remove();
ThemeManager.setPopupSize(null, null, true);
});
},
handleWindowResizing: function() {
var sizeArray = ThemeManager.popupSizeData.val();
if(sizeArray) {
sizeArray = sizeArray.split('x');
ThemeManager.setPopupSize(sizeArray[0], sizeArray[1], true);
} else {
ThemeManager.setPopupSize(null, null, true);
}
},
sortableEl: null,
uiTabs: null,
handleSortableTabs: function() {
this.uiTabs = $("#tabs");
this.sortableEl = this.uiTabs.find(".ui-tabs-nav");
this.sortableEl.sortable({
stop: function(event, ui) {
ThemeManager.updateTabsOrder();
}
});
},
reOrderPanels: function(sortedTimelines) {
var panels = $("#tabs .ui-tabs-panel");
for(var i = 0, len = sortedTimelines.length; i < len; ++i) {
var correctTimeline = sortedTimelines[i];
var correctPanel = $("#timeline-" + correctTimeline);
var positionPanel = panels.eq(i);
if(correctPanel[0].id != positionPanel[0].id) {
var currentScroll = $('.inner_timeline', correctPanel).scrollTop();
correctPanel.detach();
positionPanel.before(correctPanel);
$('.inner_timeline', correctPanel).scrollTop(currentScroll);
panels = $("#tabs .ui-tabs-panel");
}
}
},
updateTabsOrder: function() {
var sortedTabs = this.sortableEl.sortable('toArray');
var sortedTimelines = [];
for(var i = 0; i < sortedTabs.length; ++i) {
sortedTimelines[i] = sortedTabs[i].split('-')[1];
}
tweetManager.setTimelineOrder(sortedTimelines);
this.reOrderPanels(sortedTimelines);
this.uiTabs.tabs('refreshPositions');
}
};
| mit |
kh3dr0n/projetphp | src/site/adminBundle/Controller/PassagerController.php | 5322 | <?php
/**
* Created by PhpStorm.
* User: kh3dr0n
* Date: 19/04/2014
* Time: 20:27
*/
namespace site\adminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use site\adminBundle\Entity\Passager;
class PassagerController extends Controller {
function listerAction(){
$em = $this->container->get('doctrine')->getEntityManager();
$passagers = $em->getRepository('siteadminBundle:passager')->FindAll();
return $this->render('siteadminBundle:passager:lister.html.twig',array(
'passagers'=>$passagers,
'msg'=>''
));
}
function supprimerAction($id = null){
$em = $this->container->get('doctrine')->getEntityManager();
$passager = $em->find('siteadminBundle:passager',$id);
if(!$passager){
throw new NotFoundHttpException("Vol non trouvé");
}
$user = $em->find('siteadminBundle:user',$id);
$rrepo = $em->getRepository('siteadminBundle:reservation');
$reservations = $rrepo->findby(array('passager'=>$passager));
foreach($reservations as $r ){
$em->remove($r);
}
$em->remove($passager);
$em->remove($user);
$em->flush();
return $this->redirect($this->generateUrl('siteadmin_passager_lister'));
}
function modifierAction($id = null){
$request = $this->container->get('request');
$em = $this->container->get('doctrine')->getEntityManager();
$user = $em->find('siteadminBundle:user',$id);
$username = $user->getUsername();
$discriminator = $this->container->get('pugx_user.manager.user_discriminator');
$discriminator->setClass('site\adminBundle\Entity\Passager');
$userManager = $this->container->get('pugx_user_manager');
$userOne = $userManager->findUserByUsername($username);
$nomvalue = $userOne->getNom();
$prenomvalue = $userOne->getPrenom();
$sexevalue = $userOne->getSexe();
$dnvalue = $userOne->getDateNaissance()->format('m/d/Y');
$request = $this->container->get('request');
if($request->getMethod() == "POST"){
$nom = $request->request->get('nom');
$prenom = $request->request->get('prenom');
$sexe = $request->request->get('sexe');
$dn = $request->request->get('dateNaissance');
$password = $request->request->get('password');
$userOne->setNom($nom);
$userOne->setPrenom($prenom);
$userOne->setSexe($sexe);
$userOne->setDateNaissance(new \DateTime($dn));
if($password != '')
$userOne->setPlainPassword($password);
//$userOne->setEnabled(true);
//$userOne->addRole('ROLE_PASSAGER');
$userManager->updateUser($userOne, true);
return $this->redirect($this->generateUrl('siteadmin_passager_lister'));
}
return $this->render('siteadminBundle:passager:modifier.html.twig',array(
'nom'=>$nomvalue,
'prenom'=>$prenomvalue,
'dn'=>$dnvalue,
'sexe'=>$sexevalue
));
}
function ajouterAction(){
$request = $this->container->get('request');
if($request->getMethod() == "POST"){
$nom = $request->request->get('nom');
$prenom = $request->request->get('prenom');
$sexe = $request->request->get('sexe');
$dn = $request->request->get('dateNaissance');
$username = $request->request->get('username');
$email = $request->request->get('email');
$password = $request->request->get('password');
$discriminator = $this->container->get('pugx_user.manager.user_discriminator');
$discriminator->setClass('site\adminBundle\Entity\Passager');
$userManager = $this->container->get('pugx_user_manager');
if($userManager->findUserByUsername($username))
return $this->render('siteadminBundle:passager:ajouter.html.twig',array(
'msg'=>'Nom utilisateur existe'
));
if($userManager->findUserByEmail($email))
return $this->render('siteadminBundle:passager:ajouter.html.twig',array(
'msg'=>'Email existe'
));
$userOne = $userManager->createUser();
$userOne->setUsername($username);
$userOne->setEmail($email);
$userOne->setNom($nom);
$userOne->setPrenom($prenom);
$userOne->setSexe($sexe);
$userOne->setDateNaissance(new \DateTime($dn));
$userOne->setPlainPassword($password);
$userOne->setEnabled(true);
$userOne->addRole('ROLE_PASSAGER');
$userManager->updateUser($userOne, true);
return $this->redirect($this->generateUrl('siteadmin_personnel_lister'));
}
return $this->render('siteadminBundle:passager:ajouter.html.twig',array(
'msg'=>''
));
}
} | mit |
brucevsked/vskeddemolist | vskeddemos/mavenproject/vskedtool/src/main/java/com/vsked/common/IdWorkerSnowflake.java | 6625 | package com.vsked.common;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
/**
* <p>名称:IdWorker.java</p>
* <p>描述:分布式自增长ID</p>
* <pre>
* Twitter的 Snowflake JAVA实现方案
* </pre>
* 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用:
* 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
* 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间,
* 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识),
* 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。
* 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分),
* 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。
* <p>
* 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
*
* @author Polim
*/
public class IdWorkerSnowflake {
// 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
private final static long twepoch = 1288834974657L;
// 机器标识位数
private final static long workerIdBits = 5L;
// 数据中心标识位数
private final static long datacenterIdBits = 5L;
// 机器ID最大值
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private final static long sequenceBits = 12L;
// 机器ID偏左移12位
private final static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private final static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
/* 上次生产id时间戳 */
private static long lastTimestamp = -1L;
// 0,并发控制
private long sequence = 0L;
private final long workerId;
// 数据标识id部分
private final long datacenterId;
public IdWorkerSnowflake(){
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
}
/**
* @param workerId
* 工作机器ID
* @param datacenterId
* 序列号
*/
public IdWorkerSnowflake(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
/**
* 获取下一个ID
*
* @return
*/
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
// 当前毫秒内,则+1
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 当前毫秒内计数满了,则等待下一秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
// ID偏移组合生成最终的ID,并返回ID
long nextId = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
return nextId;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
/**
* <p>
* 获取 maxWorkerId
* </p>
*/
protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
StringBuffer mpid = new StringBuffer();
mpid.append(datacenterId);
String name = ManagementFactory.getRuntimeMXBean().getName();
if (!name.isEmpty()) {
/*
* GET jvmPid
*/
mpid.append(name.split("@")[0]);
}
/*
* MAC + PID 的 hashcode 获取16个低位
*/
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
/**
* <p>
* 数据标识id部分
* </p>
*/
protected static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
} catch (Exception e) {
System.out.println(" getDatacenterId: " + e.getMessage());
}
return id;
}
public static void main(String[] args) {
// IdWorkerSnowflake idWorker = new IdWorkerSnowflake(31,31);
IdWorkerSnowflake idWorker = new IdWorkerSnowflake();
System.out.println("idWorker="+idWorker.nextId());
IdWorkerSnowflake id = new IdWorkerSnowflake();
System.out.println("id="+id.nextId());
System.out.println(id.datacenterId);
System.out.println(id.workerId);
}
}
| mit |
dutu/cryptox | test/bitxIntegrationTests.js | 1004 | 'use strict';
const chai = require('chai');
const sharedTests = require('./shared/integrationTest.js');
// configure Integration tests variables below this line
const slug = 'bitx';
const apiHost = {
private: 'https://api.mybitx.com',
public: 'https://api.mybitx.com'
};
const publicMethodsToTest = ['getRate', 'getTicker', 'getOrderBook'];
const privateMethodsToTest = ['getOpenOrders', ];
const writeMockResponseFileForMethod = '';
const nativeCalls = [
['getTicker']
];
// don't change below this line; only configure above this line
describe('Integration Test ' + slug + ':', function () {
let contextIT = { // set context for Integration Testing
slug: slug,
apiHost: apiHost,
publicMethodsToTest: publicMethodsToTest,
privateMethodsToTest: privateMethodsToTest,
writeMockResponseFileForMethod: writeMockResponseFileForMethod,
nativeCalls: nativeCalls,
};
sharedTests.integrationTest(contextIT);
});
| mit |
jkpenner/RPGSystemTutorial | Assets/RPGSystems/Scripts/Stats/Interfaces/IStatLinkable.cs | 324 | using UnityEngine;
using System.Collections;
/// <summary>
/// Allows the stat to use stat linkers
/// </summary>
public interface IStatLinkable {
int StatLinkerValue { get; }
void AddLinker(RPGStatLinker linker);
void RemoveLinker(RPGStatLinker linker);
void ClearLinkers();
void UpdateLinkers();
} | mit |
horst-naujoks/vollibro | src/Controllers/Settings/ConfigurePinController.ts | 5475 | module Naujoks.Vollibro.Controllers {
export class ConfigurePinController extends BaseController<ViewModels.ConfigurePinViewModel> {
//#region Injection
public static ID = "ConfigurePinController";
public static get $inject(): string[] {
return [
"$scope",
Services.Plugins.ID,
Services.UiHelper.ID,
Services.Preferences.ID
];
}
constructor(
$scope: ng.IScope,
private Plugins: Services.Plugins,
private UiHelper: Services.UiHelper,
private Preferences: Services.Preferences) {
super($scope, ViewModels.ConfigurePinViewModel);
}
//#endregion
//#region BaseController Overrides
protected view_beforeEnter(event?: ng.IAngularEvent, eventArgs?: Ionic.IViewEventArguments): void {
super.view_beforeEnter(event, eventArgs);
this.viewModel.isPinSet = this.Preferences.pin !== null;
}
//#endregion
//#region Controller Methods
protected setPin_click() {
var options: Models.DialogOptions,
model: Models.PinEntryDialogModel;
model = new Models.PinEntryDialogModel("Enter a value for your new PIN", null, true);
options = new Models.DialogOptions(model);
// Show the PIN entry dialog.
this.UiHelper.showDialog(PinEntryController.ID, options).then((result1: Models.PinEntryDialogResultModel) => {
// If there was a PIN returned, they didn't cancel.
if (result1 && result1.pin) {
// Show a second prompt to make sure they enter the same PIN twice.
// We pass in the first PIN value because we want them to be able to match it.
model.promptText = "Confirm your new PIN";
model.pinToMatch = result1.pin;
options.dialogData = model;
this.UiHelper.showDialog(PinEntryController.ID, options).then((result2: Models.PinEntryDialogResultModel) => {
// If the second PIN entered matched the first one, then use it.
if (result2 && result2.matches) {
this.Preferences.pin = result2.pin;
this.viewModel.isPinSet = true;
this.Plugins.toast.showShortBottom("Your PIN has been configured.");
}
});
}
});
}
protected changePin_click() {
var options: Models.DialogOptions,
model: Models.PinEntryDialogModel;
model = new Models.PinEntryDialogModel("Enter your current PIN", this.Preferences.pin, true);
options = new Models.DialogOptions(model);
// Show the PIN entry dialog; pass the existing PIN which they need to match.
this.UiHelper.showDialog(PinEntryController.ID, options).then((result1: Models.PinEntryDialogResultModel) => {
// If the PIN matched, then we can continue.
if (result1.matches) {
// Prompt for a new PIN.
model.promptText = "Enter your new PIN";
model.pinToMatch = null;
options.dialogData = model;
this.UiHelper.showDialog(PinEntryController.ID, options).then((result2: Models.PinEntryDialogResultModel) => {
// Show a second prompt to make sure they enter the same PIN twice.
// We pass in the first PIN value because we want them to be able to match it.
model.promptText = "Confirm your new PIN";
model.pinToMatch = result2.pin;
options.dialogData = model;
this.UiHelper.showDialog(PinEntryController.ID, options).then((result3: Models.PinEntryDialogResultModel) => {
// If the second new PIN entered matched the new first one, then use it.
if (result3.matches) {
this.Preferences.pin = result3.pin;
this.viewModel.isPinSet = true;
this.Plugins.toast.showShortBottom("Your PIN has been configured.");
}
});
});
}
});
}
protected removePin_click() {
var options: Models.DialogOptions,
model: Models.PinEntryDialogModel;
model = new Models.PinEntryDialogModel("Enter your current PIN", this.Preferences.pin, true);
options = new Models.DialogOptions(model);
// Show the PIN entry dialog; pass the existing PIN which they need to match.
this.UiHelper.showDialog(PinEntryController.ID, options).then((result: Models.PinEntryDialogResultModel) => {
// If the PIN entered matched, then we can remove it.
if (result.matches) {
this.Preferences.pin = null;
this.viewModel.isPinSet = false;
this.Plugins.toast.showShortBottom("The PIN has been removed.");
}
});
}
//#endregion
}
}
| mit |
DeepakRajendranMsft/azure-sdk-for-node | lib/services/networkManagement2/lib/models/applicationGatewayHttpListener.js | 4197 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
var models = require('./index');
var util = require('util');
/**
* @class
* Initializes a new instance of the ApplicationGatewayHttpListener class.
* @constructor
* Http listener of application gateway
*
* @member {object} [frontendIPConfiguration] Gets or sets frontend IP
* configuration resource of application gateway
*
* @member {string} [frontendIPConfiguration.id] Resource Id
*
* @member {object} [frontendPort] Gets or sets frontend port resource of
* application gateway
*
* @member {string} [frontendPort.id] Resource Id
*
* @member {string} [protocol] Gets or sets the protocol. Possible values
* include: 'Http', 'Https'
*
* @member {string} [hostName] Gets or sets the host name of http listener
*
* @member {object} [sslCertificate] Gets or sets ssl certificate resource of
* application gateway
*
* @member {string} [sslCertificate.id] Resource Id
*
* @member {boolean} [requireServerNameIndication] Gets or sets the
* requireServerNameIndication of http listener
*
* @member {string} [provisioningState] Gets or sets Provisioning state of the
* http listener resource Updating/Deleting/Failed
*
* @member {string} [name] Gets name of the resource that is unique within a
* resource group. This name can be used to access the resource
*
* @member {string} [etag] A unique read-only string that changes whenever the
* resource is updated
*
*/
function ApplicationGatewayHttpListener() {
ApplicationGatewayHttpListener['super_'].call(this);
}
util.inherits(ApplicationGatewayHttpListener, models['SubResource']);
/**
* Defines the metadata of ApplicationGatewayHttpListener
*
* @returns {object} metadata of ApplicationGatewayHttpListener
*
*/
ApplicationGatewayHttpListener.prototype.mapper = function () {
return {
required: false,
serializedName: 'ApplicationGatewayHttpListener',
type: {
name: 'Composite',
className: 'ApplicationGatewayHttpListener',
modelProperties: {
id: {
required: false,
serializedName: 'id',
type: {
name: 'String'
}
},
frontendIPConfiguration: {
required: false,
serializedName: 'properties.frontendIPConfiguration',
type: {
name: 'Composite',
className: 'SubResource'
}
},
frontendPort: {
required: false,
serializedName: 'properties.frontendPort',
type: {
name: 'Composite',
className: 'SubResource'
}
},
protocol: {
required: false,
serializedName: 'properties.protocol',
type: {
name: 'String'
}
},
hostName: {
required: false,
serializedName: 'properties.hostName',
type: {
name: 'String'
}
},
sslCertificate: {
required: false,
serializedName: 'properties.sslCertificate',
type: {
name: 'Composite',
className: 'SubResource'
}
},
requireServerNameIndication: {
required: false,
serializedName: 'properties.requireServerNameIndication',
type: {
name: 'Boolean'
}
},
provisioningState: {
required: false,
serializedName: 'properties.provisioningState',
type: {
name: 'String'
}
},
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
etag: {
required: false,
serializedName: 'etag',
type: {
name: 'String'
}
}
}
}
};
};
module.exports = ApplicationGatewayHttpListener;
| mit |
Team-Papaya-Web-Services-and-Cloud/Web-Services-and-Cloud-Teamwork-2014 | Votter/Votter.Services/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6501 | // Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace Votter.Services.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "Votter.Services.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | mit |
francjvs/FSPatcher | src/fspatcher/FSPatcher.java | 19028 | package fspatcher;
import java.awt.Color;
import java.awt.Font;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import lev.gui.LSaveFile;
import skyproc.*;
import skyproc.gui.SPMainMenuPanel;
import skyproc.gui.SUM;
import skyproc.gui.SUMGUI;
import fspatcher.YourSaveFile.Settings;
import java.io.File;
import java.util.Arrays;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import lev.gui.LPanel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import skyproc.gui.SPProgressBarPlug;
/**
*
* @author Francisco Silva
*/
public class FSPatcher implements SUM {
/*
* The important functions to change are:
* - getStandardMenu(), where you set up the GUI
* - runChangesToPatch(), where you put all the processing code and add records to the output patch.
*/
/*
* The types of records you want your patcher to import. Change this to
* customize the import to what you need.
*/
GRUP_TYPE[] importRequests = new GRUP_TYPE[]{
GRUP_TYPE.LVLI,
GRUP_TYPE.ARMO,
GRUP_TYPE.WEAP,
GRUP_TYPE.FLST,
GRUP_TYPE.KYWD,
GRUP_TYPE.OTFT,
GRUP_TYPE.NPC_,
GRUP_TYPE.AMMO,
GRUP_TYPE.PROJ
};
public static String myPatchName = "FS Patcher";
public static String authorName = "francjvs";
public static String version = "0.1";
public static String welcomeText = "Lootifies Weapons and Armor. "
+ "Based HEAVILY on Diene's Lootification";
public static String descriptionToShowInSUM = "Lootifies Weapons and Armor.";
public static Color headerColor = new Color(66, 181, 184); // Teal
public static Color settingsColor = new Color(72, 179, 58); // Green
public static Font settingsFont = new Font("Serif", Font.BOLD, 15);
public static SkyProcSave save = new YourSaveFile();
public static ArrayList<Mod> activeMods = new ArrayList<>(0);
public static Mod gearVariants;
public static Mod global;
public static ArrayList<Pair<String, ArrayList<ARMO>>> outfits = new ArrayList<>(0);
public static ArrayList<Pair<String, ArrayList<String>>> tiers = new ArrayList<>(0);
public static ArrayList<Pair<String, ArrayList<Pair<String,Integer>>>> factWeapons = new ArrayList<>(0);
public static ArrayList<String> FactionKeys = new ArrayList<>(Arrays.asList("Alikr", "OrcStronghold","Thalmor","Imperial","LegateImperial","Guard","Sons","BearSons","Wolf","Vigilants"));
public static ArrayList<Pair<Mod, ArrayList<Pair<ARMO, KYWD>>>> modArmors = new ArrayList<>(0);
public static ArrayList<Pair<Mod, ArrayList<Pair<WEAP, KYWD>>>> modWeapons = new ArrayList<>(0);
public static boolean listify = false;
public static ArrayList<Pair<String, Node>> lootifiedMods = new ArrayList<>(0);
public static ArrayList<ModPanel> modPanels = new ArrayList<>(0);
public static ArrayList<Pair<String,LPanel>> outfitPanels;
public static enum lk {
err;
};
// Do not write the bulk of your program here
// Instead, write your patch changes in the "runChangesToPatch" function
// at the bottom
public static void main(String[] args) {
try {
SPGlobal.createGlobalLog();
SPGlobal.newSpecialLog(lk.err, "lli_crash.txt");
SUMGUI.open(new FSPatcher(), args);
} catch (Exception e) {
// If a major error happens, print it everywhere and display a message box.
System.err.println(e.toString());
SPGlobal.logException(e);
JOptionPane.showMessageDialog(null, "There was an exception thrown during program execution: '" + e + "' Check the debug logs or contact the author.");
SPGlobal.closeDebug();
}
}
@Override
public String getName() {
return myPatchName;
}
// This function labels any record types that you "multiply".
// For example, if you took all the armors in a mod list and made 3 copies,
// you would put ARMO here.
// This is to help monitor/prevent issues where multiple SkyProc patchers
// multiply the same record type to yeild a huge number of records.
@Override
public GRUP_TYPE[] dangerousRecordReport() {
// None
return new GRUP_TYPE[0];
}
@Override
public GRUP_TYPE[] importRequests() {
return importRequests;
}
@Override
public boolean importAtStart() {
return false;
}
@Override
public boolean hasStandardMenu() {
return true;
}
// This is where you add panels to the main menu.
// First create custom panel classes (as shown by YourFirstSettingsPanel),
// Then add them here.
@Override
public SPMainMenuPanel getStandardMenu() {
final SPMainMenuPanel settingsMenu = new SPMainMenuPanel(getHeaderColor());
settingsMenu.setWelcomePanel(new WelcomePanel(settingsMenu));
settingsMenu.addMenu(new OtherSettingsPanel(settingsMenu), false, save, Settings.OTHER_SETTINGS);
Runnable r = new Runnable() {
@Override
public void run() {
theInitFunction();
initFactionWeapons();
for (Mod m : activeMods) {
ModPanel panel = new ModPanel(settingsMenu, m, global);
modPanels.add(panel);
settingsMenu.addMenu(panel);
}
settingsMenu.addMenu(new OutfitsPanel(settingsMenu), false, save, Settings.OTHER_SETTINGS);
//settingsMenu.addMenu(new FactionsPanel(settingsMenu), false, save, Settings.OTHER_SETTINGS);
settingsMenu.updateUI();
}
};
SUMGUI.startImport(r);
return settingsMenu;
}
// Usually false unless you want to make your own GUI
@Override
public boolean hasCustomMenu() {
return false;
}
@Override
public JFrame openCustomMenu() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasLogo() {
return false;
}
@Override
public URL getLogo() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasSave() {
return true;
}
@Override
public LSaveFile getSave() {
return save;
}
@Override
public String getVersion() {
return version;
}
@Override
public ModListing getListing() {
return new ModListing(getName(), false);
}
@Override
public Mod getExportPatch() {
Mod out = new Mod(getListing());
out.setAuthor(authorName);
return out;
}
@Override
public Color getHeaderColor() {
return headerColor;
}
// Add any custom checks to determine if a patch is needed.
// On Automatic Variants, this function would check if any new packages were
// added or removed.
@Override
public boolean needsPatching() {
return false;
}
// This function runs when the program opens to "set things up"
// It runs right after the save file is loaded, and before the GUI is displayed
@Override
public void onStart() throws Exception {
Runnable r = new Runnable() {
@Override
public void run() {
}
};
SUMGUI.startImport(r);
File fXmlFile = new File("Lootification.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList mList = doc.getElementsByTagName("mod");
for (int i = 0; i < mList.getLength(); i++) {
Node nMod = mList.item(i);
Element mod = (Element) nMod;
lootifiedMods.add(new Pair<>(mod.getAttribute("modName"), nMod));
}
File CustomXmlFile = new File("Custom.xml");
Document cDoc = dBuilder.parse(CustomXmlFile);
cDoc.getDocumentElement().normalize();
mList = cDoc.getElementsByTagName("mod");
for (int i = 0; i < mList.getLength(); i++) {
Node nMod = mList.item(i);
Element mod = (Element) nMod;
Pair<String, Node> p = new Pair<>(mod.getAttribute("modName"), nMod);
boolean found = false;
for (Pair<String, Node> q : lootifiedMods) {
if (q.getBase().contentEquals(p.getBase())) {
found = true;
break;
}
}
if (!found) {
lootifiedMods.add(p);
}
}
// Create Weapon Faction placeholders
for (String s : FSPatcher.FactionKeys) {
ArrayList<Pair<String,Integer>> p2 = new ArrayList<>(0);
Pair<String, ArrayList<Pair<String,Integer>>> p1 = new Pair<>(s,p2);
factWeapons.add(p1);
}
}
// This function runs right as the program is about to close.
@Override
public void onExit(boolean patchWasGenerated) throws Exception {
}
// Add any mods that you REQUIRE to be present in order to patch.
@Override
public ArrayList<ModListing> requiredMods() {
ArrayList<ModListing> req = new ArrayList<>(0);
ModListing gearVariants = new ModListing("FSConvergence", true);
req.add(gearVariants);
return req;
}
@Override
public String description() {
return descriptionToShowInSUM;
}
// This is where you should write the bulk of your code.
// Write the changes you would like to make to the patch,
// but DO NOT export it. Exporting is handled internally.
@Override
public void runChangesToPatch() throws Exception {
Mod patch = SPGlobal.getGlobalPatch();
Mod merger = new Mod(getName() + "Merger", false);
merger.addAsOverrides(SPGlobal.getDB());
// Write your changes to the patch here.
for (ModPanel mPanel : modPanels) {
boolean found = false;
if (!mPanel.armorKeys.isEmpty()) {
for (Pair<Mod, ArrayList<Pair<ARMO, KYWD>>> p : modArmors) {
if (p.getBase().equals(mPanel.myMod)) {
found = true;
break;
}
}
if (!found) {
Pair<Mod, ArrayList<Pair<ARMO, KYWD>>> p = new Pair<>(mPanel.myMod, mPanel.armorKeys);
modArmors.add(p);
}
}
found = false;
if (!mPanel.weaponKeys.isEmpty()) {
for (Pair<Mod, ArrayList<Pair<WEAP, KYWD>>> p : modWeapons) {
if (p.getBase().equals(mPanel.myMod)) {
found = true;
break;
}
}
if (!found) {
Pair<Mod, ArrayList<Pair<WEAP, KYWD>>> p = new Pair<>(mPanel.myMod, mPanel.weaponKeys);
modWeapons.add(p);
}
}
}
SPProgressBarPlug.setStatus("Processing XML");
XMLTools.addModsToXML(merger);
XMLTools.processXML(merger, patch);
FLST baseArmorKeysFLST = (FLST) merger.getMajor("LLI_BASE_ARMOR_KEYS", GRUP_TYPE.FLST);
FLST variantArmorKeysFLST = (FLST) merger.getMajor("LLI_VAR_ARMOR_KEYS", GRUP_TYPE.FLST);
// SPGlobal.log("base armor key formlist", baseArmorKeysFLST.getEDID());
// SPGlobal.log("variant armor keywords", variantArmorKeysFLST.getEDID());
FLST baseWeaponKeysFLST = (FLST) merger.getMajor("LLI_BASE_WEAPON_KEYS", GRUP_TYPE.FLST);
FLST variantWeaponKeysFLST = (FLST) merger.getMajor("LLI_VAR_WEAPON_KEYS", GRUP_TYPE.FLST);
boolean lootify = true; //save.getBool(Settings.LOOTIFY_MOD);
if (lootify) {
SPProgressBarPlug.setStatus("Setting up armor matches");
ArmorTools.setupArmorMatches(baseArmorKeysFLST, variantArmorKeysFLST, merger);
SPProgressBarPlug.setStatus("Building base armors");
ArmorTools.buildArmorBases(merger, baseArmorKeysFLST);
SPProgressBarPlug.setStatus("Setting up armor sets");
ArmorTools.setupSets(merger, patch);
SPProgressBarPlug.setStatus("Building armor variants");
ArmorTools.buildArmorVariants(merger, patch, baseArmorKeysFLST, variantArmorKeysFLST);
SPProgressBarPlug.setStatus("Setting up armor leveled lists");
ArmorTools.modLVLIArmors(merger, patch);
SPProgressBarPlug.setStatus("Processing outfit armors");
ArmorTools.buildOutfitsArmors(baseArmorKeysFLST, merger, patch);
SPProgressBarPlug.setStatus("Linking armor leveled lists");
ArmorTools.linkLVLIArmors(baseArmorKeysFLST, merger, patch);
SPProgressBarPlug.setStatus("Linking armor in NPC inventory");
ArmorTools.linkINVArmors(baseArmorKeysFLST, merger, patch);
WeaponTools.setMergeAndPatch(merger, patch);
SPProgressBarPlug.setStatus("Setting up weapon matches");
WeaponTools.setupWeaponMatches(baseWeaponKeysFLST, variantWeaponKeysFLST, merger);
SPProgressBarPlug.setStatus("Building base weapons");
WeaponTools.buildWeaponBases(baseWeaponKeysFLST);
SPProgressBarPlug.setStatus("Building weapon variants");
WeaponTools.buildWeaponVariants(baseWeaponKeysFLST, variantWeaponKeysFLST);
SPProgressBarPlug.setStatus("Setting up weapon leveled lists");
WeaponTools.modLVLIWeapons();
SPProgressBarPlug.setStatus("Processing outfit weapons");
WeaponTools.buildOutfitWeapons(baseWeaponKeysFLST);
SPProgressBarPlug.setStatus("Linking weapon leveled lists");
WeaponTools.linkLVLIWeapons(baseWeaponKeysFLST);
SPProgressBarPlug.setStatus("Linking weapon in NPC inventory");
WeaponTools.linkINVWeapons(baseWeaponKeysFLST);
if (save.getBool(YourSaveFile.Settings.PROCESS_ARMORS)) {
SPProgressBarPlug.setStatus("Patching Armors");
ArmorTools.patchArmors(merger, patch);
}
if (save.getBool(YourSaveFile.Settings.PROCESS_WEAPONS)) {
SPProgressBarPlug.setStatus("Patching Weapons");
WeaponTools.patchWeapons();
SPProgressBarPlug.setStatus("Patching Ammunition");
WeaponTools.patchAmmo();
}
if (save.getBool(YourSaveFile.Settings.PROCESS_AMMO)) {
SPProgressBarPlug.setStatus("Patching Projectiles");
WeaponTools.patchProj();
}
}
}
// OTHER FUNCTIONS
public void theInitFunction() {
try {
ArrayList<ModListing> activeModListing = SPImporter.getActiveModList();
ArrayList<Mod> allMods = new ArrayList<>(0);
gearVariants = new Mod(getName() + "MergerTemp", false);
gearVariants.addAsOverrides(SPGlobal.getDB());
for (ModListing listing : activeModListing) {
Mod newMod = new Mod(listing);
allMods.add(newMod);
}
for (ARMO armor : gearVariants.getArmors()) {
allMods.get(activeModListing.indexOf(armor.getFormMaster())).addRecord(armor);
KeywordSet keys = armor.getKeywordSet();
for (FormID form : keys.getKeywordRefs()) {
KYWD key = (KYWD) gearVariants.getMajor(form, GRUP_TYPE.KYWD);
if (key == null) {
String error = armor.getEDID()
+ " has an invalid keyword reference: "+ form
+ " The patch will fail. Clean it in tes5edit and rerun the patcher.";
Exception e = new Exception(error);
JOptionPane.showMessageDialog(null, e.toString());
throw e;
}
}
}
for (WEAP weapon : gearVariants.getWeapons()) {
allMods.get(activeModListing.indexOf(weapon.getFormMaster())).addRecord(weapon);
KeywordSet keys = weapon.getKeywordSet();
for (FormID form : keys.getKeywordRefs()) {
KYWD key = (KYWD) gearVariants.getMajor(form, GRUP_TYPE.KYWD);
if (key == null) {
String error = weapon.getEDID()
+ " has an invalid keyword reference: "+ form
+ " The patch will fail. Clean it in tes5edit and rerun the patcher.";
Exception e = new Exception(error);
JOptionPane.showMessageDialog(null, e.toString());
throw e;
}
}
}
for (OTFT o : gearVariants.getOutfits()) {
ArrayList<FormID> items = o.getInventoryList();
for (FormID f : items) {
LVLI litem = (LVLI) gearVariants.getMajor(f, GRUP_TYPE.LVLI);
ARMO arm = (ARMO) gearVariants.getMajor(f, GRUP_TYPE.ARMO);
WEAP weapon = (WEAP) gearVariants.getMajor(f, GRUP_TYPE.WEAP);
if( (litem == null)&&(arm==null)&&(weapon==null) ){
String error = o.getEDID()
+ " has an invalid entry: "+ f
+ " The patch will fail. Clean it in tes5edit and rerun the patcher.";
Exception e = new Exception(error);
JOptionPane.showMessageDialog(null, e.toString());
throw e;
}
}
}
for (Mod m : allMods) {
String modName = m.getName();
if (!(modName.contentEquals("Skyrim.esm") || (modName.contentEquals("FSConvergence.esm")) || modName.contentEquals("HearthFires.esm")
|| modName.contentEquals("Update.esm") || modName.contentEquals("Dragonborn.esm") || modName.contentEquals("Dawnguard.esm"))) {
int numArmors = m.getArmors().size();
int numWeapons = m.getWeapons().size();
if (numArmors > 0 || numWeapons > 0) {
activeMods.add(m);
}
}
}
} catch (Exception e) {
throw new RuntimeException (e.getMessage());
}
}
public void initFactionWeapons() {
for (String faction : FactionKeys) {
ArrayList<Pair<String,Integer>> weapon = new ArrayList<>(0);
Pair<String, ArrayList<Pair<String,Integer>>> fct = new Pair<>(faction,weapon);
factWeapons.add(fct);
}
}
}
| mit |
Azure/azure-sdk-for-net | sdk/cognitiveservices/Vision.Face/src/Generated/Models/IdentifyRequest.cs | 6678 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.CognitiveServices.Vision.Face.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Request body for identify face operation.
/// </summary>
public partial class IdentifyRequest
{
/// <summary>
/// Initializes a new instance of the IdentifyRequest class.
/// </summary>
public IdentifyRequest()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the IdentifyRequest class.
/// </summary>
/// <param name="faceIds">Array of query faces faceIds, created by the
/// Face - Detect. Each of the faces are identified independently. The
/// valid number of faceIds is between [1, 10].</param>
/// <param name="personGroupId">PersonGroupId of the target person
/// group, created by PersonGroup - Create. Parameter personGroupId and
/// largePersonGroupId should not be provided at the same time.</param>
/// <param name="largePersonGroupId">LargePersonGroupId of the target
/// large person group, created by LargePersonGroup - Create. Parameter
/// personGroupId and largePersonGroupId should not be provided at the
/// same time.</param>
/// <param name="maxNumOfCandidatesReturned">The range of
/// maxNumOfCandidatesReturned is between 1 and 100 (default is
/// 1).</param>
/// <param name="confidenceThreshold">Confidence threshold of
/// identification, used to judge whether one face belong to one
/// person. The range of confidenceThreshold is [0, 1] (default
/// specified by algorithm).</param>
public IdentifyRequest(IList<System.Guid> faceIds, string personGroupId = default(string), string largePersonGroupId = default(string), int? maxNumOfCandidatesReturned = default(int?), double? confidenceThreshold = default(double?))
{
FaceIds = faceIds;
PersonGroupId = personGroupId;
LargePersonGroupId = largePersonGroupId;
MaxNumOfCandidatesReturned = maxNumOfCandidatesReturned;
ConfidenceThreshold = confidenceThreshold;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets array of query faces faceIds, created by the Face -
/// Detect. Each of the faces are identified independently. The valid
/// number of faceIds is between [1, 10].
/// </summary>
[JsonProperty(PropertyName = "faceIds")]
public IList<System.Guid> FaceIds { get; set; }
/// <summary>
/// Gets or sets personGroupId of the target person group, created by
/// PersonGroup - Create. Parameter personGroupId and
/// largePersonGroupId should not be provided at the same time.
/// </summary>
[JsonProperty(PropertyName = "personGroupId")]
public string PersonGroupId { get; set; }
/// <summary>
/// Gets or sets largePersonGroupId of the target large person group,
/// created by LargePersonGroup - Create. Parameter personGroupId and
/// largePersonGroupId should not be provided at the same time.
/// </summary>
[JsonProperty(PropertyName = "largePersonGroupId")]
public string LargePersonGroupId { get; set; }
/// <summary>
/// Gets or sets the range of maxNumOfCandidatesReturned is between 1
/// and 100 (default is 1).
/// </summary>
[JsonProperty(PropertyName = "maxNumOfCandidatesReturned")]
public int? MaxNumOfCandidatesReturned { get; set; }
/// <summary>
/// Gets or sets confidence threshold of identification, used to judge
/// whether one face belong to one person. The range of
/// confidenceThreshold is [0, 1] (default specified by algorithm).
/// </summary>
[JsonProperty(PropertyName = "confidenceThreshold")]
public double? ConfidenceThreshold { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (FaceIds == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "FaceIds");
}
if (FaceIds != null)
{
if (FaceIds.Count > 10)
{
throw new ValidationException(ValidationRules.MaxItems, "FaceIds", 10);
}
}
if (PersonGroupId != null)
{
if (PersonGroupId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "PersonGroupId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(PersonGroupId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "PersonGroupId", "^[a-z0-9-_]+$");
}
}
if (LargePersonGroupId != null)
{
if (LargePersonGroupId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "LargePersonGroupId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(LargePersonGroupId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "LargePersonGroupId", "^[a-z0-9-_]+$");
}
}
if (MaxNumOfCandidatesReturned > 100)
{
throw new ValidationException(ValidationRules.InclusiveMaximum, "MaxNumOfCandidatesReturned", 100);
}
if (MaxNumOfCandidatesReturned < 1)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "MaxNumOfCandidatesReturned", 1);
}
}
}
}
| mit |
sachinnitw1317/artphillic | application/modules/profile_page_videos/views/main_page.php | 301 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
//$this->load->view('header');
//$this->load->view('left_list');
$this->load->view('videos',$query);
//$this->load->view('right_list');
?>
<!--<li class="list-group-item">
<span class="badge">5</span>
GOLD
</li>-->
| mit |
Ezhil-Language-Foundation/open-tamil | examples/classifier/demo.py | 355 | import sklearn
from sklearn.neural_network import MLPClassifier
X = [[0, 1], [1, 0], [1, 1]]
Y = [1, 1, 0]
clf = MLPClassifier(
solver="lbfgs", alpha=1e-3, hidden_layer_sizes=(5, 2), random_state=1
)
clf.fit(X, Y)
clf.predict([[2, 2], [0, 0], [-1, -2]])
print(clf.score([[2, 2], [0, 0], [-1, -2]], [1, 0, 0]))
for coef in clf.coefs_:
print(coef)
| mit |
harizSalim/LOG6306-SalimAlex | lock/src/main/java/com/auth0/lock/error/LoginAuthenticationErrorBuilder.java | 3190 | /*
* LoginAuthenticationErrorBuilder.java
*
* Copyright (c) 2014 Auth0 (http://auth0.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.auth0.lock.error;
import com.auth0.api.APIClientException;
import com.auth0.lock.R;
import com.auth0.lock.event.AuthenticationError;
import java.util.Map;
public class LoginAuthenticationErrorBuilder implements AuthenticationErrorBuilder {
private static final String INVALID_USER_PASSWORD_ERROR = "invalid_user_password";
private static final String UNAUTHORIZED_ERROR = "unauthorized";
private final int titleResource;
private final int defaultMessageResource;
private final int invalidCredentialsResource;
public LoginAuthenticationErrorBuilder() {
this(R.string.com_auth0_db_login_error_title, R.string.com_auth0_db_login_error_message, R.string.com_auth0_db_login_invalid_credentials_error_message);
}
public LoginAuthenticationErrorBuilder(int titleResource, int defaultMessageResource, int invalidCredentialsResource) {
this.titleResource = titleResource;
this.defaultMessageResource = defaultMessageResource;
this.invalidCredentialsResource = invalidCredentialsResource;
}
@Override
public AuthenticationError buildFrom(Throwable throwable) {
int messageResource = defaultMessageResource;
if (throwable instanceof APIClientException) {
APIClientException exception = (APIClientException) throwable;
Map errorResponse = exception.getResponseError();
final String errorCode = (String) errorResponse.get(ERROR_KEY);
final String errorDescription = (String) errorResponse.get(ERROR_DESCRIPTION_KEY);
if (INVALID_USER_PASSWORD_ERROR.equalsIgnoreCase(errorCode)) {
messageResource = invalidCredentialsResource;
}
if (UNAUTHORIZED_ERROR.equalsIgnoreCase(errorCode) && errorDescription != null) {
return new AuthenticationError(titleResource, errorDescription, throwable);
}
}
return new AuthenticationError(titleResource, messageResource, throwable);
}
}
| mit |
gardr/validator | lib/rule/preprocess/screenshots.js | 2531 | var fs = require('fs');
var async = require('async');
var moment = require('moment');
var internals = {};
var REG_EXP_FILENAME = /^(\d+)x(\d+)_(\d+)/;
internals.getImages = function (harvested, output, next, options) {
fs.readdir(options.outputDirectory, function (err, folder) {
if (err) {
return next(err);
}
var pathList = folder.map(function (filename) {
return options.outputDirectory + '/' + filename;
});
async.map(pathList, fs.stat, function (err, results) {
if (err){
return next(err);
}
preprocess(folder, results);
});
});
function preprocess(folder, results){
// results is now an array of filesystem-stat-objects for each file,
// with same index as in folder list
function filterIsPngFile(file, i){
return results[i].isFile() && file.indexOf('.png') > -1;
}
var images = folder.filter(filterIsPngFile).map(format);
//add timing
if (images.length > 0 && images[0]){
var start = images[0].time;
images.forEach(function(img){
img.timing = img.time - start;
var diff = moment(img.time).diff(harvested.common.startTime, 'seconds');
img.formattedTiming = diff + ' sekund' + (diff > 1 ? 'er' : '');
});
}
output('images', images);
output('firstImage', images[0]);
output('hasScreenshots', images && images.length > 0);
next();
}
function format(filename, index, list) {
var match = filename.match(REG_EXP_FILENAME);
return {
'active': index === (list.length - 1),
'path': options.outputDirectory + '/' + filename,
'filename': filename,
'link': '/screenshots/'+options.id+'/'+filename,
'index': index +1,
'id': options.id,
'total': list.length,
'width': match && match[1]*1,
'height': match && match[2]*1,
'time': match && (match[3]*1),
'formattedTime': match && moment(match[3]*1).format('HH:mm:ss.SS')
};
}
};
module.exports = {
dependencies: ['screenshots'],
preprocess: function (harvested, output, next, options) {
if (harvested && options.outputDirectory) {
internals.getImages.apply(this, Array.prototype.slice.call(arguments));
} else {
next();
}
}
};
| mit |
drypot/raysoda | src/ts/server/express/express2-html-test.ts | 828 | import { Express2 } from '@server/express/express2'
import supertest, { SuperAgentTest } from 'supertest'
import { omanCloseAllObjects, omanGetObject, omanNewSession } from '@server/oman/oman'
describe('Express2 Html', () => {
let web: Express2
let sat: SuperAgentTest
beforeAll(async () => {
omanNewSession('config/raysoda-test.json')
web = await omanGetObject('Express2') as Express2
await web.start()
sat = supertest.agent(web.server)
})
afterAll(async () => {
await omanCloseAllObjects()
})
it('setup', () => {
web.router.get('/html', (req, res) => {
res.send('<p>some text</p>')
})
})
it('can return html', async () => {
const res = await sat.get('/html').expect(200)
expect(res.type).toBe('text/html')
expect(res.text).toBe('<p>some text</p>')
})
})
| mit |
axiom4/RaspiCamera | webapp/raspicamera/src/app/raspi-camera/image-preview/image-preview.component.ts | 296 | import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-image-preview',
templateUrl: './image-preview.component.html',
styleUrls: ['./image-preview.component.css']
})
export class ImagePreviewComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
| mit |
dudanogueira/tiss | tiss/extensoes/providers/cardio_senha/cardio_senha.py | 2908 | # -*- coding: utf-8 -*-
from yapsy.IPlugin import IPlugin
import datetime
import pymssql
class PluginModelo(IPlugin):
'''
Retorna provider de senhas do prestador para checagens
- Senha (indice)
- Cod Beneficiario
- Procedimentos: list com todos aprovados
Cardio Provider:
provider_confs = {
'cardio': {
'servidor': '192.0.0.4',
'usuario': 'sa',
'banco': 'CARDIO',
'senha': 'senhabd',
},
'autoridade':{
'operadora': {
'registroANS': '316881',
},
'prestador': {
'codigoPrestadorNaOperadora': '1000001',
'CNPJ': '66343559000394'
}
},
}
'''
name = "PROVIDER SENHA"
def executa(self, objeto):
print('''
#
# Executando: %s
#
''' % self.name)
# para todas as senhas da guia. textos são ignorados.
senhas = [ i.text for i in objeto.root.xpath("//ans:senha", namespaces=objeto.nsmap) if i.text.isdigit()]
# provider a ser registrado
provider = {}
try:
provider_conf = objeto.provider_conf['cardio']
servidor = provider_conf['servidor']
usuario = provider_conf['usuario']
banco = provider_conf['banco']
senha = provider_conf['senha']
print("conectando a banco...")
conn = pymssql.connect(servidor, usuario, senha, "CARDIO", as_dict=True)
cursor = conn.cursor()
query = '''
select
SolicitacaoServico.Codigo as senha,
SolicitacaoServico.BenefCodigoCartao as carteira,
COUNT(ItemSolServico.AutoId) as procedimentos
from SolicitacaoServico
inner join ItemSolServico on ItemSolServico.Solicitacao=SolicitacaoServico.AutoId
where
SolicitacaoServico.Codigo in (%s)
group by
SolicitacaoServico.Codigo,
SolicitacaoServico.BenefCodigoCartao
''' % ",".join(senhas)
print(query)
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
senha = row['senha']
carteira = row['carteira']
procedimentos = row['procedimentos']
# para cada um
# conecta no Cardio e Puxa os dados
dados = {
"carteira" : '0'+str(carteira),
"procedimentos" : procedimentos,
}
provider[str(senha)] = dados
objeto.registra_provider('senha', provider)
except KeyError:
print(u"Erro! Provider Conf do Cardio não encontrado!") | mit |
techlib/adminator | adminator/static/js/src/stores/ConfigPattern.js | 2841 | 'use strict'
import * as Reflux from 'reflux'
import {ConfigPatternActions, FeedbackActions} from '../actions'
import {ErrorMixin} from './Mixins'
import {hashHistory as BrowserHistory} from 'react-router'
export var ConfigPatternStore = Reflux.createStore({
mixins: [ErrorMixin],
listenables: [ConfigPatternActions],
data: {'pattern': {}, 'list': []},
onRead(id) {
$.ajax({url: `/config_pattern/${id}`, success: result => {
this.data.errors = []
this.data.pattern = result
this.trigger(this.data)
},
error: result => {
FeedbackActions.set('error', result.responseJSON.message)
}
})
},
onUpdate(pattern) {
$.ajax({
url: `/config_pattern/${pattern.uuid}`,
method: 'PUT',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(pattern),
success: function success() {
BrowserHistory.push('/cfgPattern/')
FeedbackActions.set('success', 'Pattern updated')
},
error: result => {
FeedbackActions.set('error', result.responseJSON.message)
}
})
},
onDelete(id) {
$.ajax({
url: `/config_pattern/${id}`,
method: 'DELETE',
dataType: 'json',
contentType: 'application/json',
success: () => {
BrowserHistory.push('/cfgPattern/')
FeedbackActions.set('success', 'Pattern deleted')
},
error: result => {
FeedbackActions.set('error', result.responseJSON.message)
}
})
},
onCreate(pattern) {
var _this = this
$.ajax({
url: '/config_pattern/',
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(pattern),
success: function success(result) {
BrowserHistory.push('/cfgPattern/' + result.uuid)
FeedbackActions.set('success', 'Pattern created')
},
error: result => {
FeedbackActions.set('error', result.responseJSON.message)
}
})
},
onList() {
$.ajax({url: '/config_pattern/', success: result => {
this.data.errors = []
this.data.list = result.result
this.trigger(this.data)
}
})
},
onRecalculate(id) {
$.ajax({url: `/config_pattern/${id}/recalculate`,
success: function success(result) {
var message = 'Pattern matching recalculated'
message += ', interfaces: ' + result.interfacses
message += ', matching interfaces: ' + result.matching
FeedbackActions.set('success', message)
},
error: result => {
FeedbackActions.set('error', result.responseJSON.message)
}
})
},
onRecalculateall() {
$.ajax({url: '/config_pattern/recalculate',
success: result => {
FeedbackActions.set('success', 'Pattern matching recalculated')
},
})
}
})
| mit |
nicholascloud/vette | src/validators/nodupe.js | 900 | 'use strict';
var sameValueZero = require('../same-value-zero');
var DuplicateElementValidationError = require('../errors').DuplicateElementValidationError;
module.exports = function nodupe (message) {
return function (adapter) {
var value = adapter.value();
if (!Array.isArray(value)) {
return new TypeError('value is not an array');
}
if (value.length === 0) {
return;
}
var index = 0,
compareIndex = 0,
maxIndex = value.length - 1;
while (index <= maxIndex) {
compareIndex = index + 1;
while (compareIndex <= maxIndex) {
var a = value[index],
b = value[compareIndex];
if (sameValueZero(a, b)) {
return new DuplicateElementValidationError(
index,
compareIndex,
message
);
}
compareIndex += 1;
}
index += 1;
}
};
}; | mit |
frainfreeze/studying | university/10004-Programming/home exercises 1/Di3z2.cpp | 580 | #include <iostream>
using namespace std;
bool neparan(int broj) {
//ako broj nije paran, vracamo true
if (broj % 2 != 0) {
return true;
}
//vracamo false jer je paran
return false;
}
int main() {
cout << "Unesite molim jedan broj: ";
int broj;
cin >> broj;
//poziv metode i stavljanje povratne vrijednosti u varijablu
bool je_neparan = neparan(broj);
if (je_neparan) {
cout << "Broj " << broj << " je neparan" << endl;
}
else {
cout << "Broj " << broj << " nije neparan" << endl;
}
return 0;
} | mit |
phucnguyen81/jeran | src/main/java/lou/jeran/db/RsMapper.java | 193 | package lou.jeran.db;
import java.sql.ResultSet;
/**
* Converts result-set to another type.
*
* @author phuc
*/
public interface RsMapper<T> {
T map(ResultSet rs) throws Exception;
} | mit |
ManakCP/NestJs | node_modules/face-api.js/build/commonjs/dom/bufferToImage.js | 926 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var env_1 = require("../env");
function bufferToImage(buf) {
return new Promise(function (resolve, reject) {
if (!(buf instanceof Blob)) {
return reject('bufferToImage - expected buf to be of type: Blob');
}
var reader = new FileReader();
reader.onload = function () {
if (typeof reader.result !== 'string') {
return reject('bufferToImage - expected reader.result to be a string, in onload');
}
var img = env_1.env.getEnv().createImageElement();
img.onload = function () { return resolve(img); };
img.onerror = reject;
img.src = reader.result;
};
reader.onerror = reject;
reader.readAsDataURL(buf);
});
}
exports.bufferToImage = bufferToImage;
//# sourceMappingURL=bufferToImage.js.map | mit |
Vertexwahn/appleseed | src/appleseed.studio/mainwindow/project/objectinstanceitem.cpp | 19091 |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "objectinstanceitem.h"
// appleseed.studio headers.
#include "mainwindow/project/assemblyitem.h"
#include "mainwindow/project/entitybrowser.h"
#include "mainwindow/project/entitybrowserwindow.h"
#include "mainwindow/project/entityeditorcontext.h"
#include "mainwindow/project/itemregistry.h"
#include "mainwindow/project/materialassignmenteditorwindow.h"
#include "mainwindow/project/materialcollectionitem.h"
#include "mainwindow/project/projectbuilder.h"
#include "mainwindow/project/projectexplorer.h"
#include "mainwindow/rendering/renderingmanager.h"
// appleseed.renderer headers.
#include "renderer/api/scene.h"
// appleseed.foundation headers.
#include "foundation/utility/uid.h"
// Qt headers.
#include <QAction>
#include <QColor>
#include <QMenu>
#include <QMetaType>
#include <QString>
#include <Qt>
#include <QVariant>
#include <QWidget>
// Standard headers.
#include <memory>
#include <string>
using namespace appleseed::studio;
using namespace foundation;
using namespace renderer;
using namespace std;
namespace
{
enum Side
{
FrontSide,
BackSide,
FrontAndBackSides
};
struct MaterialAssignmentData
{
string m_slot;
Side m_side;
QList<ItemBase*> m_items;
MaterialAssignmentData()
{
}
MaterialAssignmentData(
const char* slot,
const Side side,
const QList<ItemBase*>& items)
: m_slot(slot)
, m_side(side)
, m_items(items)
{
}
};
}
Q_DECLARE_METATYPE(MaterialAssignmentData);
namespace appleseed {
namespace studio {
const char* ObjectInstanceItem::DefaultSlotName = "default";
ObjectInstanceItem::ObjectInstanceItem(
EntityEditorContext& editor_context,
ObjectInstance* object_instance,
Assembly& parent,
ObjectInstanceCollectionItem* collection_item)
: Base(editor_context, object_instance, parent, collection_item)
{
update_style();
}
const Assembly& ObjectInstanceItem::get_assembly() const
{
return m_parent;
}
QMenu* ObjectInstanceItem::get_single_item_context_menu() const
{
QMenu* menu = ItemBase::get_single_item_context_menu();
menu->addSeparator();
menu->addAction("Assign New Disney Material", this, SLOT(slot_assign_new_disney_material()));
menu->addSeparator();
menu->addAction("Assign Materials...", this, SLOT(slot_open_material_assignment_editor()));
add_material_assignment_menu_actions(menu);
return menu;
}
namespace
{
QList<ObjectInstanceItem*> items_to_object_instance_items(const QList<ItemBase*>& items)
{
QList<ObjectInstanceItem*> object_instance_items;
for (int i = 0; i < items.size(); ++i)
object_instance_items.append(static_cast<ObjectInstanceItem*>(items[i]));
return object_instance_items;
}
bool are_in_assembly(
const QList<ObjectInstanceItem*>& object_instance_items,
const UniqueID assembly_uid)
{
for (int i = 0; i < object_instance_items.size(); ++i)
{
if (object_instance_items[i]->get_assembly().get_uid() != assembly_uid)
return false;
}
return true;
}
}
QMenu* ObjectInstanceItem::get_multiple_items_context_menu(const QList<ItemBase*>& items) const
{
if (!are_in_assembly(items_to_object_instance_items(items), m_parent.get_uid()))
return 0;
QMenu* menu = ItemBase::get_multiple_items_context_menu(items);
menu->addSeparator();
menu->addAction("Assign New Disney Material", this, SLOT(slot_assign_new_disney_material()))
->setData(QVariant::fromValue(items));
add_material_assignment_menu_actions(menu, items);
return menu;
}
// Friend of ObjectInstanceItem class, thus cannot be placed in anonymous namespace.
class AssignNewDisneyMaterialAction
: public RenderingManager::IScheduledAction
{
public:
AssignNewDisneyMaterialAction(
EntityEditorContext& editor_context,
const QList<ItemBase*>& items)
: m_editor_context(editor_context)
, m_items(items)
{
}
virtual void operator()(Project& project) APPLESEED_OVERRIDE
{
for (int i = 0; i < m_items.size(); ++i)
{
// Create a new Disney material and assign it to the object instance.
const Material& material =
create_and_assign_new_material(static_cast<ObjectInstanceItem*>(m_items[i]));
// Select the last added material.
if (i == m_items.size() - 1)
m_editor_context.m_project_explorer.select_entity(material.get_uid());
}
}
const Material& create_and_assign_new_material(ObjectInstanceItem* object_instance_item)
{
const ObjectInstance& object_instance = *object_instance_item->m_entity;
const Assembly& assembly = object_instance_item->m_parent;
// Name the material after the name of the object instance.
const string material_name =
make_unique_name(
string(object_instance.get_name()) + "_material",
assembly.materials());
// Create the material and insert it into the assembly.
const AssemblyItem* assembly_item = m_editor_context.m_item_registry.get_item<AssemblyItem>(assembly);
const Material& material =
assembly_item->get_material_collection_item().create_default_disney_material(material_name);
// Assign the material to the object instance.
// We need the object bound to the instance in order to retrieve the material slots.
const Object* object = object_instance.find_object();
if (object)
{
const size_t slot_count = object->get_material_slot_count();
if (slot_count > 0)
{
for (size_t i = 0; i < slot_count; ++i)
{
object_instance_item->do_assign_material(
object->get_material_slot(i),
true, // assign to front side
true, // assign to back side
material_name.c_str());
}
}
else
{
object_instance_item->do_assign_material(
ObjectInstanceItem::DefaultSlotName,
true, // assign to front side
true, // assign to back side
material_name.c_str());
}
}
return material;
}
private:
EntityEditorContext& m_editor_context;
const QList<ItemBase*> m_items;
};
void ObjectInstanceItem::slot_assign_new_disney_material()
{
m_editor_context.m_rendering_manager.schedule_or_execute(
auto_ptr<RenderingManager::IScheduledAction>(
new AssignNewDisneyMaterialAction(m_editor_context, get_action_items())));
}
void ObjectInstanceItem::slot_open_material_assignment_editor()
{
MaterialAssignmentEditorWindow* editor_window =
new MaterialAssignmentEditorWindow(
QTreeWidgetItem::treeWidget(),
*m_entity,
*this,
m_editor_context);
editor_window->showNormal();
editor_window->activateWindow();
}
namespace
{
class EnrichAndForwardAcceptedSignal
: public QObject
{
Q_OBJECT
public:
EnrichAndForwardAcceptedSignal(QObject* parent, const QVariant& data)
: QObject(parent)
, m_data(data)
{
}
public slots:
void slot_accepted(QString page_name, QString item_value)
{
emit signal_accepted(page_name, item_value, m_data);
}
signals:
void signal_accepted(QString page_name, QString item_value, QVariant data);
private:
const QVariant m_data;
};
}
void ObjectInstanceItem::slot_assign_material()
{
QAction* action = qobject_cast<QAction*>(sender());
const MaterialAssignmentData data = action->data().value<MaterialAssignmentData>();
const QString window_title =
data.m_items.empty()
? QString("Assign Material to %1").arg(m_entity->get_name())
: QString("Assign Material to Multiple Object Instances");
EntityBrowserWindow* browser_window =
new EntityBrowserWindow(
treeWidget(),
window_title.toStdString());
EntityBrowser<Assembly> entity_browser(m_parent);
browser_window->add_items_page(
"material",
"Materials",
entity_browser.get_entities("material"));
EnrichAndForwardAcceptedSignal* forwarder =
new EnrichAndForwardAcceptedSignal(browser_window, action->data());
connect(
browser_window, SIGNAL(signal_accepted(QString, QString)),
forwarder, SLOT(slot_accepted(QString, QString)));
connect(
forwarder, SIGNAL(signal_accepted(QString, QString, QVariant)),
this, SLOT(slot_assign_material_accepted(QString, QString, QVariant)));
browser_window->showNormal();
browser_window->activateWindow();
}
namespace
{
class AssignMaterialAction
: public RenderingManager::IScheduledAction
{
public:
AssignMaterialAction(
ObjectInstanceItem* parent,
const QString& page_name,
const QString& entity_name,
const QVariant& data)
: m_parent(parent)
, m_page_name(page_name)
, m_entity_name(entity_name)
, m_data(data)
{
}
virtual void operator()(
Project& project) APPLESEED_OVERRIDE
{
m_parent->assign_material(m_page_name, m_entity_name, m_data);
}
private:
ObjectInstanceItem* m_parent;
const QString m_page_name;
const QString m_entity_name;
const QVariant m_data;
};
}
void ObjectInstanceItem::slot_assign_material_accepted(QString page_name, QString entity_name, QVariant data)
{
m_editor_context.m_rendering_manager.schedule_or_execute(
auto_ptr<RenderingManager::IScheduledAction>(
new AssignMaterialAction(this, page_name, entity_name, data)));
qobject_cast<QWidget*>(sender()->parent())->close();
}
void ObjectInstanceItem::assign_material(
const QString& page_name,
const QString& entity_name,
const QVariant& untyped_data)
{
const string material_name = entity_name.toStdString();
const MaterialAssignmentData data = untyped_data.value<MaterialAssignmentData>();
const bool front_side = data.m_side == FrontSide || data.m_side == FrontAndBackSides;
const bool back_side = data.m_side == BackSide || data.m_side == FrontAndBackSides;
if (data.m_items.empty())
{
do_assign_material(data.m_slot.c_str(), front_side, back_side, material_name.c_str());
}
else
{
for (int i = 0; i < data.m_items.size(); ++i)
{
ObjectInstanceItem* item = static_cast<ObjectInstanceItem*>(data.m_items[i]);
item->do_assign_material(data.m_slot.c_str(), front_side, back_side, material_name.c_str());
}
}
}
namespace
{
class ClearMaterialAction
: public RenderingManager::IScheduledAction
{
public:
ClearMaterialAction(
ObjectInstanceItem* parent,
const QVariant& data)
: m_parent(parent)
, m_data(data)
{
}
virtual void operator()(
Project& project) APPLESEED_OVERRIDE
{
m_parent->clear_material(m_data);
}
private:
ObjectInstanceItem* m_parent;
const QVariant m_data;
};
}
void ObjectInstanceItem::slot_clear_material()
{
const QVariant data = qobject_cast<QAction*>(sender())->data();
m_editor_context.m_rendering_manager.schedule_or_execute(
auto_ptr<RenderingManager::IScheduledAction>(
new ClearMaterialAction(this, data)));
}
void ObjectInstanceItem::clear_material(const QVariant& untyped_data)
{
const MaterialAssignmentData data = untyped_data.value<MaterialAssignmentData>();
const bool front_side = data.m_side == FrontSide || data.m_side == FrontAndBackSides;
const bool back_side = data.m_side == BackSide || data.m_side == FrontAndBackSides;
if (data.m_items.empty())
{
do_unassign_material(data.m_slot.c_str(), front_side, back_side);
}
else
{
for (int i = 0; i < data.m_items.size(); ++i)
{
ObjectInstanceItem* item = static_cast<ObjectInstanceItem*>(data.m_items[i]);
item->do_unassign_material(data.m_slot.c_str(), front_side, back_side);
}
}
}
void ObjectInstanceItem::slot_delete()
{
m_editor_context.m_rendering_manager.schedule_or_execute(
auto_ptr<RenderingManager::IScheduledAction>(
new EntityDeletionAction<ObjectInstanceItem>(this)));
}
void ObjectInstanceItem::do_delete()
{
if (!allows_deletion())
return;
const UniqueID object_instance_uid = m_entity->get_uid();
// Remove and delete the object instance.
m_parent.object_instances().remove(
m_parent.object_instances().get_by_uid(object_instance_uid));
// Mark the assembly and the project as modified.
m_parent.bump_version_id();
m_editor_context.m_project_builder.notify_project_modification();
// Remove and delete the object instance item.
ItemBase* object_instance_item = m_editor_context.m_item_registry.get_item(object_instance_uid);
m_editor_context.m_item_registry.remove(object_instance_uid);
delete object_instance_item;
// At this point 'this' no longer exists.
}
void ObjectInstanceItem::add_material_assignment_menu_actions(
QMenu* menu,
const QList<ItemBase*>& items) const
{
Object* object = m_entity->find_object();
if (!object)
return;
menu->addSeparator();
QMenu* slots_menu = menu->addMenu("Material Slots");
const size_t slot_count = object->get_material_slot_count();
if (slot_count > 0)
{
for (size_t i = 0; i < slot_count; ++i)
{
const char* slot = object->get_material_slot(i);
QMenu* slot_menu = slots_menu->addMenu(slot);
add_material_assignment_menu_actions(slot_menu, slot, items);
}
}
else
{
QMenu* slot_menu = slots_menu->addMenu(DefaultSlotName);
add_material_assignment_menu_actions(slot_menu, DefaultSlotName, items);
}
}
void ObjectInstanceItem::add_material_assignment_menu_actions(
QMenu* menu,
const char* slot,
const QList<ItemBase*>& items) const
{
menu->addAction("Assign Material To Front Side...", this, SLOT(slot_assign_material()))
->setData(QVariant::fromValue(MaterialAssignmentData(slot, FrontSide, items)));
menu->addAction("Assign Material To Back Side...", this, SLOT(slot_assign_material()))
->setData(QVariant::fromValue(MaterialAssignmentData(slot, BackSide, items)));
menu->addAction("Assign Material To Both Sides...", this, SLOT(slot_assign_material()))
->setData(QVariant::fromValue(MaterialAssignmentData(slot, FrontAndBackSides, items)));
menu->addSeparator();
menu->addAction("Clear Front Side Material", this, SLOT(slot_clear_material()))
->setData(QVariant::fromValue(MaterialAssignmentData(slot, FrontSide, items)));
menu->addAction("Clear Back Side Material", this, SLOT(slot_clear_material()))
->setData(QVariant::fromValue(MaterialAssignmentData(slot, BackSide, items)));
menu->addAction("Clear Both Sides Materials", this, SLOT(slot_clear_material()))
->setData(QVariant::fromValue(MaterialAssignmentData(slot, FrontAndBackSides, items)));
}
void ObjectInstanceItem::do_assign_material(
const char* slot_name,
const bool front_side,
const bool back_side,
const char* material_name)
{
if (front_side)
m_entity->assign_material(slot_name, ObjectInstance::FrontSide, material_name);
if (back_side)
m_entity->assign_material(slot_name, ObjectInstance::BackSide, material_name);
m_editor_context.m_project_builder.notify_project_modification();
update_style();
}
void ObjectInstanceItem::do_unassign_material(
const char* slot_name,
const bool front_side,
const bool back_side)
{
if (front_side)
m_entity->unassign_material(slot_name, ObjectInstance::FrontSide);
if (back_side)
m_entity->unassign_material(slot_name, ObjectInstance::BackSide);
m_editor_context.m_project_builder.notify_project_modification();
update_style();
}
void ObjectInstanceItem::update_style()
{
if (m_entity->get_front_material_mappings().empty() &&
m_entity->get_back_material_mappings().empty())
{
setForeground(0, QColor(255, 0, 255, 255));
}
else
{
// Remove the color overload. Not sure this is the easiest way to do it.
setData(0, Qt::ForegroundRole, QVariant());
}
}
} // namespace studio
} // namespace appleseed
#include "mainwindow/project/moc_cpp_objectinstanceitem.cxx"
| mit |
myxvisual/react-uwp | docs/src/components/DocsTreeView/index.tsx | 5132 | import * as React from "react";
import * as PropTypes from "prop-types";
import { Link, browserHistory } from "react-router";
import AutoSuggestBox from "react-uwp/AutoSuggestBox";
import TreeView from "react-uwp/TreeView";
import docTreeData from "./docTreeData";
export interface Item {
titleNode?: string;
expanded?: boolean;
children?: Item[];
}
let prevItemFocused: any = {};
const convert2string = (titleNode?: any): any => {
if (typeof titleNode === "string") {
return titleNode;
} else {
titleNode = titleNode.props.children;
return convert2string(titleNode);
}
};
function setListItemsUrl(path = "/") {
const listItem: any = docTreeData;
const isRootPath = path === "/";
const parentUrl = isRootPath ? "" : `/${path}`;
const names = location.pathname.split("/").map(path => path.toLowerCase());
const setUrl = (listData: any) => {
if (Array.isArray(listData)) {
for (const listDataItem of listData) {
listDataItem.parentUrl = parentUrl;
setUrl(listDataItem);
}
return;
}
let title: string;
let titleNode: any = listData.titleNode;
title = convert2string(titleNode);
title = title.replace(/\s/gim, "-").toLowerCase();
if (names.includes(title)) {
listData.expanded = true;
if (names.slice(-1)[0] === title) {
listData.visited = true;
if (prevItemFocused !== listData) {
prevItemFocused.visited = false;
prevItemFocused = listData;
}
}
}
const parentUrlNow = `${listData.parentUrl}/${title}`;
if (typeof listData.titleNode === "string") {
listData.titleNode = <Link style={{ color: "inherit", textDecoration: "inherit" }} to={parentUrlNow}>{listData.titleNode}</Link>;
}
listData.onClick = () => {
browserHistory.push(parentUrlNow);
};
listData.style = {
textDecoration: "inherit"
};
listData.hoverStyle = {
textDecoration: "underline"
};
if (listData.children) {
listData.children.forEach((item: any) => {
item.parentUrl = parentUrlNow;
setUrl(item);
});
}
};
setUrl(listItem);
}
export interface DataProps {
path?: string;
}
export interface DocsTreeViewProps extends DataProps, React.HTMLAttributes<HTMLDivElement> {}
export interface DocsTreeViewState {
listItems?: any[];
}
export default class DocsTreeView extends React.Component<DocsTreeViewProps, DocsTreeViewState> {
static contextTypes = { theme: PropTypes.object };
context: { theme: ReactUWP.ThemeType };
state: DocsTreeViewState = {
listItems: docTreeData
};
searchTimeout: any = null;
handleChangeValue = (value: string) => {
const { listItems } = this.state;
clearTimeout(this.searchTimeout);
const checkItems = (items: any[], prevIndexArr: number[]) => {
items.forEach((item, index) => {
if (!item.prevIndexArr) item.prevIndexArr = [...prevIndexArr, index];
const title = convert2string(item.titleNode);
if (value && title.toLowerCase().includes(value.toLowerCase())) {
let currSetParentItems: any[] = listItems;
const length = item.prevIndexArr.length;
for (let i = 0; i < length; i++) {
const nowItem = currSetParentItems[item.prevIndexArr[i]];
if (nowItem.disable) return;
nowItem.expanded = true;
if (!nowItem.children) nowItem.focus = true;
currSetParentItems = nowItem.children;
}
} else {
item.expanded = false;
if (!item.children) item.focus = false;
}
if (item.children) { checkItems(item.children, item.prevIndexArr); }
});
};
this.searchTimeout = setTimeout(() => {
checkItems(listItems, []);
this.setState({ listItems });
}, 200);
}
getRootPath = () => {
const paths = location.pathname.split("/");
const versionPattern = /v\d{1,2}.\d{1,2}.\d{1,2}-?\w*\.?\d{0,2}/;
let version: string;
const rootPath = paths[1];
if (versionPattern.test(rootPath)) {
version = rootPath;
}
return version;
}
render() {
const {
path,
style,
...attributes
} = this.props;
const { theme } = this.context;
const { listItems } = this.state;
setListItemsUrl(path || this.getRootPath());
return (
<div
style={theme.prefixStyle({
...theme.acrylicTexture40.style,
width: 320,
padding: "10px 0",
...style
})}
{...attributes}
>
<AutoSuggestBox
background="none"
style={{
height: 32,
fontSize: 16,
width: "100%"
}}
iconSize={32}
placeholder="Search Docs..."
onChangeValue={this.handleChangeValue}
/>
<TreeView
background="none"
itemHeight={32}
itemPadding={20}
iconPadding={2}
listSource={listItems as any}
style={{
width: 320,
maxHeight: "100%"
}}
/>
</div>
);
}
}
| mit |
dsouzadyn/Hilo | build/cmd/hilo/tween/Tween.js | 13373 | /**
* Hilo 1.0.0 for cmd
* Copyright 2016 alibaba.com
* Licensed under the MIT License
*/
define(function(require, exports, module){
var Class = require('hilo/core/Class');
/**
* Hilo
* Copyright 2015 alibaba.com
* Licensed under the MIT License
*/
/**
* <iframe src='../../../examples/Tween.html?noHeader' width = '550' height = '130' scrolling='no'></iframe>
* <br/>
* 使用示例:
* <pre>
* ticker.addTick(Hilo.Tween);//需要把Tween加到ticker里才能使用
*
* var view = new View({x:5, y:10});
* Hilo.Tween.to(view, {
* x:100,
* y:20,
* alpha:0
* }, {
* duration:1000,
* delay:500,
* ease:Hilo.Ease.Quad.EaseIn,
* onComplete:function(){
* console.log('complete');
* }
* });
* </pre>
* @class Tween类提供缓动功能。
* @param {Object} target 缓动对象。
* @param {Object} fromProps 对象缓动的起始属性集合。
* @param {Object} toProps 对象缓动的目标属性集合。
* @param {Object} params 缓动参数。可包含Tween类所有可写属性。
* @module hilo/tween/Tween
* @requires hilo/core/Class
* @property {Object} target 缓动目标。只读属性。
* @property {Int} duration 缓动总时长。单位毫秒。
* @property {Int} delay 缓动延迟时间。单位毫秒。
* @property {Boolean} paused 缓动是否暂停。默认为false。
* @property {Boolean} loop 缓动是否循环。默认为false。
* @property {Boolean} reverse 缓动是否反转播放。默认为false。
* @property {Int} repeat 缓动重复的次数。默认为0。
* @property {Int} repeatDelay 缓动重复的延迟时长。单位为毫秒。
* @property {Function} ease 缓动变化函数。默认为null。
* @property {Int} time 缓动已进行的时长。单位毫秒。只读属性。
* @property {Function} onStart 缓动开始回调函数。它接受1个参数:tween。默认值为null。
* @property {Function} onUpdate 缓动更新回调函数。它接受2个参数:ratio和tween。默认值为null。
* @property {Function} onComplete 缓动结束回调函数。它接受1个参数:tween。默认值为null。
*/
var Tween = (function(){
function now(){
return +new Date();
}
return Class.create(/** @lends Tween.prototype */{
constructor: function(target, fromProps, toProps, params){
var me = this;
me.target = target;
me._startTime = 0;
me._seekTime = 0;
me._pausedTime = 0;
me._pausedStartTime = 0;
me._reverseFlag = 1;
me._repeatCount = 0;
//no fromProps if pass 3 arguments
if(arguments.length == 3){
params = toProps;
toProps = fromProps;
fromProps = null;
}
for(var p in params) me[p] = params[p];
me.setProps(fromProps, toProps);
//for old version compatiblity
if(!params.duration && params.time){
me.duration = params.time || 0;
me.time = 0;
}
},
target: null,
duration: 0,
delay: 0,
paused: false,
loop: false,
reverse: false,
repeat: 0,
repeatDelay: 0,
ease: null,
time: 0, //ready only
onStart: null,
onUpdate: null,
onComplete: null,
/**
* 设置缓动对象的初始和目标属性。
* @param {Object} fromProps 缓动对象的初始属性。
* @param {Object} toProps 缓动对象的目标属性。
* @returns {Tween} Tween变换本身。可用于链式调用。
*/
setProps: function(fromProps, toProps){
var me = this, target = me.target,
propNames = fromProps || toProps,
from = me._fromProps = {}, to = me._toProps = {};
fromProps = fromProps || target;
toProps = toProps || target;
for(var p in propNames){
to[p] = toProps[p] || 0;
target[p] = from[p] = fromProps[p] || 0;
}
return me;
},
/**
* 启动缓动动画的播放。
* @returns {Tween} Tween变换本身。可用于链式调用。
*/
start: function(){
var me = this;
me._startTime = now() + me.delay;
me._seekTime = 0;
me._pausedTime = 0;
me.paused = false;
Tween.add(me);
return me;
},
/**
* 停止缓动动画的播放。
* @returns {Tween} Tween变换本身。可用于链式调用。
*/
stop: function(){
Tween.remove(this);
return this;
},
/**
* 暂停缓动动画的播放。
* @returns {Tween} Tween变换本身。可用于链式调用。
*/
pause: function(){
var me = this;
me.paused = true;
me._pausedStartTime = now();
return me;
},
/**
* 恢复缓动动画的播放。
* @returns {Tween} Tween变换本身。可用于链式调用。
*/
resume: function(){
var me = this;
me.paused = false;
if(me._pausedStartTime) me._pausedTime += now() - me._pausedStartTime;
me._pausedStartTime = 0;
return me;
},
/**
* 跳转Tween到指定的时间。
* @param {Number} time 指定要跳转的时间。取值范围为:0 - duraion。
* @param {Boolean} pause 是否暂停。
* @returns {Tween} Tween变换本身。可用于链式调用。
*/
seek: function(time, pause){
var me = this, current = now();
me._startTime = current;
me._seekTime = time;
me._pausedTime = 0;
if(pause !== undefined) me.paused = pause;
me._update(current, true);
Tween.add(me);
return me;
},
/**
* 连接下一个Tween变换。其开始时间根据delay值不同而不同。当delay值为字符串且以'+'或'-'开始时,Tween的开始时间从当前变换结束点计算,否则以当前变换起始点计算。
* @param {Tween} tween 要连接的Tween变换。
* @returns {Tween} Tween变换本身。可用于链式调用。
*/
link: function(tween){
var me = this, delay = tween.delay, startTime = me._startTime;
if(typeof delay === 'string'){
var plus = delay.indexOf('+') == 0, minus = delay.indexOf('-') == 0;
delay = plus || minus ? Number(delay.substr(1)) * (plus ? 1 : -1) : Number(delay);
}
tween.delay = delay;
tween._startTime = plus || minus ? startTime + me.duration + delay : startTime + delay;
me._next = tween;
Tween.remove(tween);
return me;
},
/**
* Tween类的内部渲染方法。
* @private
*/
_render: function(ratio){
var me = this, target = me.target, fromProps = me._fromProps, p;
for(p in fromProps) target[p] = fromProps[p] + (me._toProps[p] - fromProps[p]) * ratio;
},
/**
* Tween类的内部更新方法。
* @private
*/
_update: function(time, forceUpdate){
var me = this;
if(me.paused && !forceUpdate) return;
//elapsed time
var elapsed = time - me._startTime - me._pausedTime + me._seekTime;
if(elapsed < 0) return;
//elapsed ratio
var ratio = elapsed / me.duration, complete = false, callback;
ratio = ratio <= 0 ? 0 : ratio >= 1 ? 1 : me.ease ? me.ease(ratio) : ratio;
if(me.reverse){
//backward
if(me._reverseFlag < 0) ratio = 1 - ratio;
//forward
if(ratio < 1e-7){
//repeat complete or not loop
if((me.repeat > 0 && me._repeatCount++ >= me.repeat) || (me.repeat == 0 && !me.loop)){
complete = true;
}else{
me._startTime = now();
me._pausedTime = 0;
me._reverseFlag *= -1;
}
}
}
//start callback
if(me.time == 0 && (callback = me.onStart)) callback.call(me, me);
me.time = elapsed;
//render & update callback
me._render(ratio);
(callback = me.onUpdate) && callback.call(me, ratio, me);
//check if complete
if(ratio >= 1){
if(me.reverse){
me._startTime = now();
me._pausedTime = 0;
me._reverseFlag *= -1;
}else if(me.loop || me.repeat > 0 && me._repeatCount++ < me.repeat){
me._startTime = now() + me.repeatDelay;
me._pausedTime = 0;
}else{
complete = true;
}
}
//next tween
var next = me._next;
if(next && next.time <= 0){
var nextStartTime = next._startTime;
if(nextStartTime > 0 && nextStartTime <= time){
//parallel tween
next._render(ratio);
next.time = elapsed;
Tween.add(next);
}else if(complete && (nextStartTime < 0 || nextStartTime > time)){
//next tween
next.start();
}
}
//complete
if(complete){
(callback = me.onComplete) && callback.call(me, me);
return true;
}
},
Statics: /** @lends Tween */ {
/**
* @private
*/
_tweens: [],
/**
* 更新所有Tween实例。
* @returns {Object} Tween。
*/
tick: function(){
var tweens = Tween._tweens, tween, i, len = tweens.length;
for(i = 0; i < len; i++){
tween = tweens[i];
if(tween && tween._update(now())){
tweens.splice(i, 1);
i--;
}
}
return Tween;
},
/**
* 添加Tween实例。
* @param {Tween} tween 要添加的Tween对象。
* @returns {Object} Tween。
*/
add: function(tween){
var tweens = Tween._tweens;
if(tweens.indexOf(tween) == -1) tweens.push(tween);
return Tween;
},
/**
* 删除Tween实例。
* @param {Tween|Object|Array} tweenOrTarget 要删除的Tween对象或target对象或要删除的一组对象。
* @returns {Object} Tween。
*/
remove: function(tweenOrTarget){
if(tweenOrTarget instanceof Array){
for(var i = 0, l = tweenOrTarget.length;i < l;i ++){
Tween.remove(tweenOrTarget[i]);
}
return Tween;
}
var tweens = Tween._tweens, i;
if(tweenOrTarget instanceof Tween){
i = tweens.indexOf(tweenOrTarget);
if(i > -1) tweens.splice(i, 1);
}else{
for(i = 0; i < tweens.length; i++){
if(tweens[i].target === tweenOrTarget){
tweens.splice(i, 1);
i--;
}
}
}
return Tween;
},
/**
* 删除所有Tween实例。
* @returns {Object} Tween。
*/
removeAll: function(){
Tween._tweens.length = 0;
return Tween;
},
/**
* 创建一个缓动动画,让目标对象从开始属性变换到目标属性。
* @param {Object|Array} target 缓动目标对象或缓动目标数组。
* @param fromProps 缓动目标对象的开始属性。
* @param toProps 缓动目标对象的目标属性。
* @param params 缓动动画的参数。
* @returns {Tween|Array} 一个Tween实例对象或Tween实例数组。
*/
fromTo: function(target, fromProps, toProps, params){
var isArray = target instanceof Array;
target = isArray ? target : [target];
var tween, i, stagger = params.stagger, tweens = [];
for(i = 0; i < target.length; i++){
tween = new Tween(target[i], fromProps, toProps, params);
if(stagger) tween.delay = (params.delay || 0) + (i * stagger || 0);
tween.start();
tweens.push(tween);
}
return isArray?tweens:tween;
},
/**
* 创建一个缓动动画,让目标对象从当前属性变换到目标属性。
* @param {Object|Array} target 缓动目标对象或缓动目标数组。
* @param toProps 缓动目标对象的目标属性。
* @param params 缓动动画的参数。
* @returns {Tween|Array} 一个Tween实例对象或Tween实例数组。
*/
to: function(target, toProps, params){
return Tween.fromTo(target, null, toProps, params);
},
/**
* 创建一个缓动动画,让目标对象从指定的起始属性变换到当前属性。
* @param {Object|Array} target 缓动目标对象或缓动目标数组。
* @param fromProps 缓动目标对象的目标属性。
* @param params 缓动动画的参数。
* @returns {Tween|Array} 一个Tween实例对象或Tween实例数组。
*/
from: function(target, fromProps, params){
return Tween.fromTo(target, fromProps, null, params);
}
}
});
})();
return Tween;
}); | mit |
rogeriochaves/react-decompiler | dist/stringify-object.js | 2200 | /* this is an monkey-patched copy of https://github.com/yeoman/stringify-object/blob/master/index.js */
'use strict';
var _reactAddonsTestUtils = require('react-addons-test-utils');
var _decompiler = require('./decompiler');
var isRegexp = require('is-regexp');
var isPlainObj = require('is-plain-obj');
module.exports = function (val, opts, pad) {
var seen = [];
return (function stringify(val, opts, pad) {
opts = opts || {};
opts.indent = opts.indent || '\t';
pad = pad || '';
/* monkey-patch do */
if ((0, _reactAddonsTestUtils.isElement)(val)) {
return (0, _decompiler.decompile)(val);
}
/* end */
if (val === null || val === undefined || typeof val === 'number' || typeof val === 'boolean' || typeof val === 'function' || isRegexp(val)) {
return String(val);
}
if (val instanceof Date) {
return 'new Date(\'' + val.toISOString() + '\')';
}
if (Array.isArray(val)) {
if (val.length === 0) {
return '[]';
}
return '[\n' + val.map(function (el, i) {
var eol = val.length - 1 === i ? '\n' : ',\n';
return pad + opts.indent + stringify(el, opts, pad + opts.indent) + eol;
}).join('') + pad + ']';
}
if (isPlainObj(val)) {
if (seen.indexOf(val) !== -1) {
return '"[Circular]"';
}
var objKeys = Object.keys(val);
if (objKeys.length === 0) {
return '{}';
}
seen.push(val);
var ret = '{\n' + objKeys.map(function (el, i) {
if (opts.filter && !opts.filter(val, el)) {
return '';
}
var eol = objKeys.length - 1 === i ? '\n' : ',\n';
var key = /^[a-z$_][a-z$_0-9]*$/i.test(el) ? el : stringify(el, opts);
return pad + opts.indent + key + ': ' + stringify(val[el], opts, pad + opts.indent) + eol;
}).join('') + pad + '}';
seen.pop(val);
return ret;
}
val = String(val).replace(/[\r\n]/g, function (x) {
return x === '\n' ? '\\n' : '\\r';
});
if (opts.singleQuotes === false) {
return '"' + val.replace(/"/g, '\\\"') + '"';
}
return '\'' + val.replace(/'/g, '\\\'') + '\'';
})(val, opts, pad);
};
| mit |
apalkowski/KinectMotionCapture | KinectMotionCapture/App.xaml.cs | 335 | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace KinectMotionCapture
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| mit |
Jamongkad/s36-beta | application/routes/dashboard.php | 821 | <?php
$company = new Company\Repositories\DBCompany;
$company_name = Config::get('application.subdomain');
return Array(
'GET /dashboard' => Array('name' => 'dashboard', 'before' => 's36_auth', 'do' => function() use($company,$company_name) {
$dash = new DBDashboard(S36Auth::user()->companyid);
$dashboard_summary = $dash->pull_summary();
$company_info = $company->get_company_info($company_name);
return View::of_layout()->partial('contents', 'dashboard/dashboard_index_view', Array(
'dashboard_summary' => $dashboard_summary
,'company_info' =>$company_info
));
}),
'GET /dashboard/pwet' => function() {
Helpers::show_data(Input::get('_pjax'));
echo "<div class='button-gray'><a href='#'>pwet ka</a></div>";
},
);
| mit |
coderFirework/app | js/jqwidgets-4.4.0/demos/angular2/app/popover/defaultfunctionality/app.module.ts | 474 | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { jqxPopoverComponent } from 'components/angular_jqxpopover';
import { jqxButtonComponent } from 'components/angular_jqxbuttons';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, jqxPopoverComponent, jqxButtonComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
| mit |
ditrace/csharp | Kontur.Tracing.Core/Impl/StringBuilderExtensions.cs | 1497 | using System.Collections.Generic;
using System.Text;
namespace Kontur.Tracing.Core.Impl
{
internal static class StringBuilderExtensions
{
public static StringBuilder AppendPlainObject(this StringBuilder builder, string name, IEnumerable<KeyValuePair<string, string>> fields)
{
builder
.AppendQuotedString(name)
.Append(':')
.Append('{');
bool isFirst = true;
foreach (var pair in fields)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.AppendComma();
}
builder.AppendKeyValuePair(pair.Key, pair.Value);
}
return builder.Append('}');
}
public static StringBuilder AppendKeyValuePair(this StringBuilder builder, string key, string value)
{
return builder
.AppendQuotedString(key)
.Append(':')
.AppendQuotedString(value);
}
public static StringBuilder AppendQuotedString(this StringBuilder builder, string value)
{
return builder
.Append('"')
.Append(value)
.Append('"');
}
public static StringBuilder AppendComma(this StringBuilder builder)
{
return builder.Append(',');
}
}
} | mit |
JHKennedy4/nqr-client | jspm_packages/npm/react@0.14.2/lib/ReactUpdateQueue.js | 7315 | /* */
(function(process) {
'use strict';
var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactElement = require("./ReactElement");
var ReactInstanceMap = require("./ReactInstanceMap");
var ReactUpdates = require("./ReactUpdates");
var assign = require("./Object.assign");
var invariant = require("fbjs/lib/invariant");
var warning = require("fbjs/lib/warning");
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined;
}
return null;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined;
}
return internalInstance;
}
var ReactUpdateQueue = {
isMounted: function(publicInstance) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
var internalInstance = ReactInstanceMap.get(publicInstance);
if (internalInstance) {
return !!internalInstance._renderedComponent;
} else {
return false;
}
},
enqueueCallback: function(publicInstance, callback) {
!(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
if (!internalInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
enqueueCallbackInternal: function(internalInstance, callback) {
!(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
enqueueForceUpdate: function(publicInstance) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate');
if (!internalInstance) {
return ;
}
internalInstance._pendingForceUpdate = true;
enqueueUpdate(internalInstance);
},
enqueueReplaceState: function(publicInstance, completeState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState');
if (!internalInstance) {
return ;
}
internalInstance._pendingStateQueue = [completeState];
internalInstance._pendingReplaceState = true;
enqueueUpdate(internalInstance);
},
enqueueSetState: function(publicInstance, partialState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return ;
}
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
enqueueSetProps: function(publicInstance, partialProps) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps');
if (!internalInstance) {
return ;
}
ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps);
},
enqueueSetPropsInternal: function(internalInstance, partialProps) {
var topLevelWrapper = internalInstance._topLevelWrapper;
!topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
var element = wrapElement.props;
var props = assign({}, element.props, partialProps);
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
enqueueUpdate(topLevelWrapper);
},
enqueueReplaceProps: function(publicInstance, props) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps');
if (!internalInstance) {
return ;
}
ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props);
},
enqueueReplacePropsInternal: function(internalInstance, props) {
var topLevelWrapper = internalInstance._topLevelWrapper;
!topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
var element = wrapElement.props;
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
enqueueUpdate(topLevelWrapper);
},
enqueueElementInternal: function(internalInstance, newElement) {
internalInstance._pendingElement = newElement;
enqueueUpdate(internalInstance);
}
};
module.exports = ReactUpdateQueue;
})(require("process"));
| mit |
benjamn/reify | test/export/default/object.js | 30 | export default {
foo: 42
};
| mit |
omegasoft7/DBFlow | library/src/main/java/com/raizlabs/android/dbflow/config/FlowSQLiteOpenHelper.java | 17672 | package com.raizlabs.android.dbflow.config;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import com.raizlabs.android.dbflow.DatabaseHelperListener;
import com.raizlabs.android.dbflow.runtime.DBTransactionInfo;
import com.raizlabs.android.dbflow.runtime.TransactionManager;
import com.raizlabs.android.dbflow.runtime.transaction.BaseTransaction;
import com.raizlabs.android.dbflow.sql.QueryBuilder;
import com.raizlabs.android.dbflow.sql.migration.Migration;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import com.raizlabs.android.dbflow.structure.ModelViewAdapter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Author: andrewgrosner
* Description:
*/
public class FlowSQLiteOpenHelper extends SQLiteOpenHelper {
public final static String TEMP_DB_NAME = "temp-";
/**
* Location where the migration files should exist.
*/
public final static String MIGRATION_PATH = "migrations";
private DatabaseHelperListener mListener;
private BaseDatabaseDefinition mManager;
private SQLiteOpenHelper mBackupDB;
public FlowSQLiteOpenHelper(BaseDatabaseDefinition flowManager, DatabaseHelperListener listener) {
super(FlowManager.getContext(), flowManager.getDatabaseName() + ".db", null, flowManager.getDatabaseVersion());
mListener = listener;
mManager = flowManager;
movePrepackagedDB(getDatabaseFileName(), getDatabaseFileName());
if (flowManager.backupEnabled()) {
// Temp database mirrors existing
mBackupDB = new SQLiteOpenHelper(FlowManager.getContext(), getTempDbFileName(),
null, flowManager.getDatabaseVersion()) {
@Override
public void onOpen(SQLiteDatabase db) {
checkForeignKeySupport(db);
}
@Override
public void onCreate(SQLiteDatabase db) {
checkForeignKeySupport(db);
executeCreations(db);
executeMigrations(db, -1, db.getVersion());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
checkForeignKeySupport(db);
executeCreations(db);
executeMigrations(db, oldVersion, newVersion);
}
};
restoreDatabase(getTempDbFileName(), getDatabaseFileName());
mBackupDB.getWritableDatabase();
}
}
/**
* @return the temporary database file name for when we have backups enabled {@link BaseDatabaseDefinition#backupEnabled()}
*/
private String getTempDbFileName() {
return TEMP_DB_NAME + mManager.getDatabaseName() + ".db";
}
private String getDatabaseFileName() {
return mManager.getDatabaseName() + ".db";
}
/**
* Pulled partially from code, runs the integrity check on pre-honeycomb devices.
*
* @return
*/
public boolean isDatabaseIntegrityOk() {
boolean integrityOk = true;
SQLiteStatement prog = null;
try {
prog = getWritableDatabase().compileStatement("PRAGMA quick_check(1)");
String rslt = prog.simpleQueryForString();
if (!rslt.equalsIgnoreCase("ok")) {
// integrity_checker failed on main or attached databases
FlowLog.log(FlowLog.Level.E, "PRAGMA integrity_check on " + mManager.getDatabaseName() + " returned: " + rslt);
integrityOk = false;
if (mManager.backupEnabled()) {
integrityOk = restoreBackUp();
}
}
} finally {
if (prog != null) {
prog.close();
}
}
return integrityOk;
}
/**
* Will use the already existing app database if {@link BaseDatabaseDefinition#backupEnabled()} is true. If the existing
* is not there we will try to use the prepackaged database for that purpose.
*
* @param databaseName The name of the database to restore
* @param prepackagedName The name of the prepackaged db file
*/
public void restoreDatabase(String databaseName, String prepackagedName) {
final File dbPath = FlowManager.getContext().getDatabasePath(databaseName);
// If the database already exists, return
if (dbPath.exists()) {
return;
}
// Make sure we have a path to the file
dbPath.getParentFile().mkdirs();
// Try to copy database file
try {
// check existing and use that as backup
File existingDb = FlowManager.getContext().getDatabasePath(getDatabaseFileName());
InputStream inputStream;
// if it exists and the integrity is ok
if (existingDb.exists() && (mManager.backupEnabled() && FlowManager.isDatabaseIntegrityOk(mBackupDB))) {
inputStream = new FileInputStream(existingDb);
} else {
inputStream = FlowManager.getContext().getAssets().open(prepackagedName);
}
writeDB(dbPath, inputStream);
} catch (IOException e) {
FlowLog.logError(e);
}
}
/**
* If integrity check fails, this method will use the backup db to fix itself. In order to prevent
* loss of data, please backup often!
*/
public boolean restoreBackUp() {
boolean success = true;
File db = FlowManager.getContext().getDatabasePath(TEMP_DB_NAME + mManager.getDatabaseName());
File corrupt = FlowManager.getContext().getDatabasePath(mManager.getDatabaseName());
if (corrupt.delete()) {
try {
writeDB(corrupt, new FileInputStream(db));
} catch (IOException e) {
FlowLog.logError(e);
success = false;
}
} else {
FlowLog.log(FlowLog.Level.E, "Failed to delete DB");
}
return success;
}
/**
* Writes the inputstream of the existing db to the file specified.
* @param dbPath
* @param existingDB
* @throws IOException
*/
private void writeDB(File dbPath, InputStream existingDB) throws IOException {
final OutputStream output = new FileOutputStream(dbPath);
byte[] buffer = new byte[1024];
int length;
while ((length = existingDB.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
existingDB.close();
}
/**
* Copies over the prepackaged DB into the main DB then deletes the existing DB to save storage space. If
* we have a backup that exists
*
* @param databaseName
*/
public void movePrepackagedDB(String databaseName, String prepackagedName) {
final File dbPath = FlowManager.getContext().getDatabasePath(databaseName);
// If the database already exists, and is ok return
if (dbPath.exists() && (!mManager.areConsistencyChecksEnabled() || (mManager.areConsistencyChecksEnabled() && isDatabaseIntegrityOk()))) {
return;
}
// Make sure we have a path to the file
dbPath.getParentFile().mkdirs();
// Try to copy database file
try {
// check existing and use that as backup
File existingDb = FlowManager.getContext().getDatabasePath(getTempDbFileName());
InputStream inputStream;
// if it exists and the integrity is ok we use backup as the main DB is no longer valid
if (existingDb.exists() && (!mManager.backupEnabled() || mManager.backupEnabled() && FlowManager.isDatabaseIntegrityOk(mBackupDB))) {
inputStream = new FileInputStream(existingDb);
} else {
inputStream = FlowManager.getContext().getAssets().open(prepackagedName);
}
writeDB(dbPath, inputStream);
} catch (IOException e) {
FlowLog.log(FlowLog.Level.E, "Failed to open file", e);
}
}
/**
* Saves the database as a backup on the {@link com.raizlabs.android.dbflow.runtime.DBTransactionQueue}. This will
* create a THIRD database to use as a backup to the backup in case somehow the overwrite fails.
*/
public void backupDB() {
if(!mManager.backupEnabled() || !mManager.areConsistencyChecksEnabled()) {
throw new IllegalStateException("Backups are not enabled for : " + mManager.getDatabaseName() + ". Please consider adding " +
"both backupEnabled and consistency checks enabled to the Database annotation");
}
// highest priority ever!
TransactionManager.getInstance().addTransaction(new BaseTransaction(DBTransactionInfo.create(BaseTransaction.PRIORITY_UI + 1)) {
@Override
public Object onExecute() {
Context context = FlowManager.getContext();
File backup = context.getDatabasePath(getTempDbFileName());
File temp = context.getDatabasePath(TEMP_DB_NAME + "-2-" + getDatabaseFileName());
// if exists we want to delete it before rename
if (temp.exists()) {
temp.delete();
}
backup.renameTo(temp);
if (backup.exists()) {
backup.delete();
}
File existing = context.getDatabasePath(getDatabaseFileName());
try {
backup.getParentFile().mkdirs();
writeDB(backup, new FileInputStream(existing));
temp.delete();
} catch (Exception e) {
FlowLog.logError(e);
}
return null;
}
});
}
/**
* Set a listener to listen for specific DB events and perform an action before we execute this classes
* specific methods.
*
* @param mListener
*/
public void setDatabaseListener(DatabaseHelperListener mListener) {
this.mListener = mListener;
}
@Override
public void onCreate(SQLiteDatabase db) {
if (mListener != null) {
mListener.onCreate(db);
}
checkForeignKeySupport(db);
executeCreations(db);
executeMigrations(db, -1, db.getVersion());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (mListener != null) {
mListener.onUpgrade(db, oldVersion, newVersion);
}
checkForeignKeySupport(db);
executeCreations(db);
executeMigrations(db, oldVersion, newVersion);
}
@Override
public void onOpen(SQLiteDatabase db) {
if (mListener != null) {
mListener.onOpen(db);
}
checkForeignKeySupport(db);
}
/**
* If foreign keys are supported, we turn it on the DB.
*
* @param database
*/
private void checkForeignKeySupport(SQLiteDatabase database) {
if (mManager.isForeignKeysSupported()) {
database.execSQL("PRAGMA foreign_keys=ON;");
FlowLog.log(FlowLog.Level.I, "Foreign Keys supported. Enabling foreign key features.");
}
}
/**
* This generates the SQLite commands to create the DB
*
* @param database
*/
private void executeCreations(final SQLiteDatabase database) {
TransactionManager.transact(database, new Runnable() {
@Override
public void run() {
List<ModelAdapter> modelAdapters = mManager.getModelAdapters();
for (ModelAdapter modelAdapter : modelAdapters) {
database.execSQL(modelAdapter.getCreationQuery());
}
// create our model views
List<ModelViewAdapter> modelViews = mManager.getModelViewAdapters();
for (ModelViewAdapter modelView : modelViews) {
QueryBuilder queryBuilder = new QueryBuilder()
.append("CREATE VIEW")
.appendSpaceSeparated(modelView.getViewName())
.append("AS ")
.append(modelView.getCreationQuery());
try {
database.execSQL(queryBuilder.getQuery());
} catch (SQLiteException e) {
FlowLog.logError(e);
}
}
}
});
}
private void executeMigrations(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
// will try migrations file or execute migrations from code
try {
final List<String> files = Arrays.asList(FlowManager.getContext().getAssets().list(MIGRATION_PATH+"/" + mManager.getDatabaseName()));
Collections.sort(files, new NaturalOrderComparator());
final Map<Integer, List<String>> migrationFileMap = new HashMap<>();
for(String file: files) {
try {
final Integer version = Integer.valueOf(file.replace(".sql", ""));
List<String> fileList = migrationFileMap.get(version);
if (fileList == null) {
fileList = new ArrayList<>();
migrationFileMap.put(version, fileList);
}
fileList.add(file);
} catch (NumberFormatException e) {
FlowLog.log(FlowLog.Level.W, "Skipping invalidly named file: " + file, e);
}
}
final Map<Integer, List<Migration>> migrationMap = mManager.getMigrations();
final int curVersion = oldVersion + 1;
TransactionManager.transact(db, new Runnable() {
@Override
public void run() {
// execute migrations in order, migration file first before wrapped migration classes.
for (int i = curVersion; i <= newVersion; i++) {
List<String> migrationFiles = migrationFileMap.get(i);
if (migrationFiles != null) {
for (String migrationFile : migrationFiles) {
executeSqlScript(db, migrationFile);
FlowLog.log(FlowLog.Level.I, migrationFile + " executed succesfully.");
}
}
if (migrationMap != null) {
List<Migration> migrationsList = migrationMap.get(i);
if (migrationsList != null) {
for (Migration migration : migrationsList) {
// before migration
migration.onPreMigrate();
// migrate
migration.migrate(db);
// after migration cleanup
migration.onPostMigrate();
}
}
}
}
}
});
} catch (IOException e) {
FlowLog.log(FlowLog.Level.E, "Failed to execute migrations.", e);
}
}
/**
* Supports multiline sql statements with ended with the standard ";"
* @param db The database to run it on
* @param file the file name in assets/migrations that we read from
*/
private void executeSqlScript(SQLiteDatabase db, String file) {
try {
final InputStream input = FlowManager.getContext().getAssets().open(MIGRATION_PATH + "/" + mManager.getDatabaseName()+ "/" + file);
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
// ends line with SQL
String querySuffix= ";";
// standard java comments
String queryCommentPrefix = "\\";
StringBuffer query = new StringBuffer();
while((line = reader.readLine()) != null){
line = line.trim();
boolean isEndOfQuery = line.endsWith(querySuffix);
if(line.startsWith(queryCommentPrefix)){
continue;
}
if(isEndOfQuery){
line = line.substring(0, line.length()-querySuffix.length());
}
query.append(" ").append(line);
if(isEndOfQuery){
db.execSQL(query.toString());
query = new StringBuffer();
}
}
if(query.length() > 0){
db.execSQL(query.toString());
}
} catch (IOException e) {
FlowLog.log(FlowLog.Level.E, "Failed to execute " + file, e);
}
}
}
| mit |
aLagoG/kygerand | and/lessThan10/eleven.cpp | 3215 | #define _CRT_SECURE_NO_DEPRECATE
#include <cctype>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
using namespace std;
inline int itoa(int n) { return n + '0'; }
int main() {
// infijo a posfijo
stack<char> st;
string in, res = "";
unordered_map<char, char> ch;
ch.insert({')', '('});
ch.insert({']', '['});
ch.insert({'}', '{'});
getline(cin, in);
bool last = false;
for (auto c : in) {
if (isdigit(c)) {
res += c;
last = true;
continue;
}
if (last) {
res += '_';
last = false;
}
switch (c) {
case ('('):
case ('['):
case ('{'):
st.push(c);
break;
case ('}'):
case (']'):
case (')'):
while (st.top() != ch[c]) {
res += st.top();
st.pop();
}
st.pop();
break;
case ('+'):
case ('-'):
while (!st.empty() && st.top() != '(' && st.top() != '{' &&
st.top() != '{') {
res += st.top();
st.pop();
}
st.push(c);
break;
case ('*'):
case ('/'):
case ('%'):
while (!st.empty() && st.top() != '(' && st.top() != '{' &&
st.top() != '{' && st.top() != '+' && st.top() != '-') {
res += st.top();
st.pop();
}
st.push(c);
break;
}
}
while (!st.empty()) {
res += st.top();
st.pop();
}
int a, b;
in.clear();
stack<int> nst;
string nm = "";
last = false;
for (auto c : res) {
if (isdigit(c)) {
nm += c;
last = true;
continue;
}
if (last) {
nst.push(stoi(nm));
nm = "";
last = false;
continue;
}
switch (c) {
case ('+'):
a = nst.top();
nst.pop();
b = nst.top();
nst.pop();
nst.push(a + b);
break;
case ('-'):
a = nst.top();
nst.pop();
b = nst.top();
nst.pop();
nst.push(a - b);
break;
case ('*'):
a = nst.top();
nst.pop();
b = nst.top();
nst.pop();
nst.push(a * b);
break;
case ('/'):
a = nst.top();
nst.pop();
b = nst.top();
nst.pop();
nst.push(a / b);
break;
case ('%'):
a = nst.top();
nst.pop();
b = nst.top();
nst.pop();
nst.push(a % b);
break;
}
}
printf("%d\n", nst.top());
} | mit |
fahadonline/sulu | vendor/sulu/sulu/src/Sulu/Bundle/ContentBundle/Resources/public/dist/validation/types/singleInternalLink.js | 528 | define(["type/default"],function(a){"use strict";var b=function(a,b){App.emit("sulu.preview.update",b,a),App.emit("sulu.content.changed")};return function(c,d){var e={},f={initializeSub:function(){var a="sulu.single-internal-link."+d.instanceName+".data-changed";App.off(a,b),App.on(a,b)},setValue:function(a){App.dom.data(c,"single-internal-link",a)},getValue:function(){return App.dom.data(c,"single-internal-link")},needsValidation:function(){return!1},validate:function(){return!0}};return new a(c,e,d,"internalLinks",f)}}); | mit |
srdjanRakic/devmeetup-vue | src/main.js | 1663 | import * as firebase from 'firebase';
import Vue from 'vue';
import Vuetify from 'vuetify';
import './stylus/main.styl';
import App from './App';
import router from './router';
import { store } from './store';
import DateFilter from './filters/date';
import AlertCmp from './components/Shared/Alert';
import EditMeetupDetailsDialog from './components/Meetup/Edit/EditMeetupDetailsDialog';
import EditMeetupDateDialog from './components/Meetup/Edit/EditMeetupDateDialog';
import EditMeetupTimeDialog from './components/Meetup/Edit/EditMeetupTimeDialog';
import RegisterDialog from './components/Meetup/Registration/RegisterDialog';
Vue.use(Vuetify);
Vue.config.productionTip = false;
Vue.filter('date', DateFilter);
Vue.component('app-alert', AlertCmp);
Vue.component('app-edit-meetup-details-dialog', EditMeetupDetailsDialog);
Vue.component('app-edit-meetup-date-dialog', EditMeetupDateDialog);
Vue.component('app-edit-meetup-time-dialog', EditMeetupTimeDialog);
Vue.component('app-meetup-register-dialog', RegisterDialog);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
render: h => h(App),
created() {
firebase.initializeApp({
apiKey: 'AIzaSyDbImZ1jGCUsVxeTg3WltMvl5BXSJ95l6U',
authDomain: 'devmeetup-55085.firebaseapp.com',
databaseURL: 'https://devmeetup-55085.firebaseio.com',
projectId: 'devmeetup-55085',
storageBucket: 'devmeetup-55085.appspot.com',
});
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.$store.dispatch('autoSignIn', user);
this.$store.dispatch('fetchUserData');
}
});
this.$store.dispatch('loadMeetups');
},
});
| mit |
space-wizards/space-station-14 | Content.Shared/Temperature/IsHotEvent.cs | 409 | using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
namespace Content.Shared.Temperature
{
/// <summary>
/// Directed event raised on entities to query whether they're "hot" or not.
/// For example, a lit welder or matchstick would be hot, etc.
/// </summary>
public class IsHotEvent : EntityEventArgs
{
public bool IsHot { get; set; } = false;
}
}
| mit |
mdoviedor/WEBsimon | src/GS/ConsultasBundle/Entity/Categoriapublicacion.php | 1111 | <?php
namespace GS\ConsultasBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Categoriapublicacion
*
* @ORM\Table(name="categoriapublicacion")
* @ORM\Entity
*/
class Categoriapublicacion
{
/**
* @var integer
*
* @ORM\Column(name="idcategoriaPublicacion", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idcategoriapublicacion;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=45, nullable=false)
*/
private $nombre;
/**
* Get idcategoriapublicacion
*
* @return integer
*/
public function getIdcategoriapublicacion()
{
return $this->idcategoriapublicacion;
}
/**
* Set nombre
*
* @param string $nombre
* @return Categoriapublicacion
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
}
| mit |
carney520/vuf7 | src/components/page/index.js | 97 | import Page from './page'
import PageContent from './page-content'
export { Page, PageContent }
| mit |
Kagami/material-ui | packages/material-ui-icons/src/DragIndicatorRounded.js | 523 | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M11 18c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2zm-2-8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 4c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" /></g></React.Fragment>
, 'DragIndicatorRounded');
| mit |
Kagami/material-ui | packages/material-ui-icons/src/DesktopMacSharp.js | 278 | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M23 2H1v16h9l-2 3v1h8v-1l-2-3h9V2zm-2 12H3V4h18v10z" /></g></React.Fragment>
, 'DesktopMacSharp');
| mit |
AHJenin/acm-type-problems | leetcode/AC/Easy/to-lower-case.py | 87 | class Solution:
def toLowerCase(self, str: str) -> str:
return str.lower()
| mit |
Crimx/crx-saladict | src/_locales/zh-TW/background.ts | 360 | import { locale as _locale } from '../zh-CN/background'
export const locale: typeof _locale = {
app: {
off: '沙拉查詞已關閉(快捷查詞依然可用)',
tempOff: '沙拉查詞已對當前標籤關閉(快捷查詞依然可用)',
unsupported: '內嵌查字介面不支援此類頁面(獨立視窗查字介面依然可用)'
}
}
| mit |
aspnetboilerplate/aspnetboilerplate-samples | GraphQLDemo/aspnet-core/src/Hotel.Core/Authorization/Roles/StaticRoleNames.cs | 300 | namespace Hotel.Authorization.Roles
{
public static class StaticRoleNames
{
public static class Host
{
public const string Admin = "Admin";
}
public static class Tenants
{
public const string Admin = "Admin";
}
}
}
| mit |
laslabs/Python-Carepoint | carepoint/tests/models/cph/fixtures/fdb_gcn.py | 432 | # -*- coding: utf-8 -*-
# Copyright 2015-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
from mixer.backend.sqlalchemy import mixer
from datetime import datetime
dt_now = datetime.now()
__model__ = 'carepoint.models.cph.fdb_gcn.FdbGcn'
fdb_gcn_default = mixer.blend(
__model__,
gcn_seqno=1,
gcn=11,
update_yn=False,
)
def fdb_gcn_rnd(cnt):
return mixer.cycle(cnt).blend(__model__)
| mit |
rosmantorres/SAF | lib/filter/doctrine/SAF_MINUTAFormFilter.class.php | 328 | <?php
/**
* SAF_MINUTA filter form.
*
* @package Proyecto_SAF
* @subpackage filter
* @author Rosman_Torres
* @version SVN: $Id: sfDoctrineFormFilterTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class SAF_MINUTAFormFilter extends BaseSAF_MINUTAFormFilter
{
public function configure()
{
}
}
| mit |
HallM/eslint-plugin-checkbugs | lib/rules/no-double-comparison.js | 2457 | /**
* @fileoverview Prevents comparing a comparison which may not operate as expected
* @author Matt Hall
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "Prevents comparing a comparison which may not operate as expected",
category: "Fill me in",
recommended: false
},
fixable: null, // or "code" or "whitespace"
schema: [
// fill in your schema
]
},
create: function(context) {
// variables should be defined here
var possibleOperators = [
">",
">=",
"<",
"<=",
"==",
"===",
"!=",
"!=="
];
//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------
// any helper functions should go here or else delete this section
function isComparisonNode(node) {
return possibleOperators.indexOf(node.operator) !== -1;
}
function checkBinaryExpression(node) {
if (!isComparisonNode(node)) {
return;
}
// only applies if one of the two are binary expressions with a comparison
if (node.left.type === "BinaryExpression" && isComparisonNode(node.left)) {
context.report(
node,
"A comparison of the result from a comparison may not work as intended. 3 > 2 > 1 is false and should instead be 3 > 2 && 2 > 1."
);
} else if (node.right.type === "BinaryExpression" && isComparisonNode(node.right)) {
context.report(
node.right,
"A comparison of the result from a comparison may not work as intended. 3 > 2 > 1 is false and should instead be 3 > 2 && 2 > 1."
);
}
}
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
return {
"BinaryExpression": checkBinaryExpression
};
}
};
| mit |
gfw-api/gfw-area | app/src/services/team.service.js | 887 | const logger = require('logger');
const { RWAPIMicroservice } = require('rw-api-microservice-node');
class TeamService {
static async getTeamByUserId(userId) {
logger.info('Get team by user id', userId);
const team = await RWAPIMicroservice.requestToMicroservice({
uri: `/teams/user/${userId}`,
method: 'GET',
json: true
});
if (!team || !team.data) return null;
return { ...team.data.attributes, id: team.data.id };
}
static async patchTeamById(teamId, body) {
logger.info('Get team by user id');
const team = await RWAPIMicroservice.requestToMicroservice({
uri: `/teams/${teamId}`,
method: 'PATCH',
body,
json: true
});
return { ...team.data.attributes, id: team.data.id };
}
}
module.exports = TeamService;
| mit |
stormbrew/channel9 | environments/ruby/src/rb_glob.cpp | 3338 | #include "c9/channel9.hpp"
#include "c9/message.hpp"
#include "c9/string.hpp"
#include "c9/value.hpp"
#include "c9/context.hpp"
#include "rb_glob.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fnmatch.h>
#include <unistd.h>
#include <list>
#include <string>
using namespace Channel9;
typedef std::vector<Value> result_set;
void match(result_set &res, const std::string &up, const std::string &down);
void match_alldir(result_set &res, const std::string &up, const std::string &down)
{
size_t slash_pos = down.find('/');
std::string matcher = down.substr(0, slash_pos);
std::string rest = "";
if (slash_pos != std::string::npos)
rest = down.substr(slash_pos + 1);
DIR *in;
if (!up.size())
in = opendir(".");
else
in = opendir(up.c_str());
struct dirent entry = {0};
struct dirent *entry_p = NULL;
// search this directory first.
match(res, up, down);
// now recurse through all subdirectories and resume matches there.
rewinddir(in);
while (readdir_r(in, &entry, &entry_p) == 0 && entry_p != NULL)
{
if (entry.d_type == DT_DIR && strcmp(".", entry.d_name) != 0 &&
strcmp("..", entry.d_name) != 0)
match_alldir(res, up + entry.d_name + "/", rest);
}
}
void match(result_set &res, const std::string &up, const std::string &down)
{
size_t slash_pos = down.find('/');
std::string matcher = down.substr(0, slash_pos);
std::string rest = "";
if (slash_pos != std::string::npos)
rest = down.substr(slash_pos + 1);
DIR *in;
if (!up.size())
in = opendir(".");
else
in = opendir(up.c_str());
struct dirent entry = {0};
struct dirent *entry_p = NULL;
if (matcher == "**")
{
// search this directory first.
match(res, up, rest);
// now recurse through all subdirectories and resume matches there.
rewinddir(in);
while (readdir_r(in, &entry, &entry_p) == 0 && entry_p != NULL)
{
if (entry.d_type == DT_DIR && strcmp(".", entry.d_name) != 0 &&
strcmp("..", entry.d_name) != 0)
match_alldir(res, up + entry.d_name + "/", rest);
}
} else {
// look for anything that's a fnmatch. If it's a directory,
// recurse. If rest is empty we're at the leaf of the match
// pattern and we should add it to the matches.
while (readdir_r(in, &entry, &entry_p) == 0 && entry_p != NULL)
{
if (fnmatch(matcher.c_str(), entry.d_name, 0) == 0 &&
strcmp(".", entry.d_name) != 0 && strcmp("..", entry.d_name) != 0)
{
if (!rest.size()) // empty, done
res.push_back(value(new_string(up + entry.d_name)));
else if (entry.d_type == DT_DIR)
match(res, up + entry.d_name + "/", rest);
}
}
}
closedir(in);
}
Tuple *match(const std::string &pattern)
{
result_set res;
std::string up = "";
std::string down = pattern;
if (pattern[0] == '/')
{
up = "/";
down = pattern.substr(1);
}
match(res, up, down);
return new_tuple(res.begin(), res.end());
}
void GlobChannel::send(Environment *env, const Value &val, const Value &ret)
{
if (is(val, MESSAGE))
{
Message *msg = ptr<Message>(val);
if (msg->arg_count() == 1)
{
if (is(msg->args()[0], STRING))
{
String *pattern = ptr<String>(msg->args()[0]);
Tuple *matches = match(pattern->str());
channel_send(env, ret, value(matches), value(&no_return_ctx));
return;
}
}
}
channel_send(env, ret, Nil, value(&no_return_ctx));
}
| mit |
vdaubry/photo-api | spec/models/post_image_spec.rb | 872 | require "rails_helper"
describe PostImage do
describe "create" do
let(:website_post) { FactoryGirl.create(:website_post) }
let(:website_post2) { FactoryGirl.create(:website_post) }
context "valid PostImage" do
it { FactoryGirl.build(:post_image).save.should == true }
end
context "duplicate key" do
it {
FactoryGirl.build(:post_image, :key => "foo", :website_post => website_post).save.should == true
FactoryGirl.build(:post_image, :key => "foo", :website_post => website_post).save.should == false
}
end
context "same key for different website_post" do
it {
FactoryGirl.build(:post_image, :key => "foo", :website_post => website_post).save.should == true
FactoryGirl.build(:post_image, :key => "foo", :website_post => website_post2).save.should == true
}
end
end
end | mit |
swarnimsinha1994/gamer | src/qt/gamertip.cpp | 9179 | /*
* W.J. van der Laan 2011-2012
*/
#include "gamertipgui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#if defined(gamertip_NEED_QT_PLUGINS) && !defined(_gamertip_QT_PLUGINS_INCLUDED)
#define _gamertip_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static gamertipGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("gamertip-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", gamertipGUI::tr("A fatal error occurred. gamertip can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef gamertip_QT_TEST
int main(int argc, char *argv[])
{
// Do this early as we don't want to bother initializing if we are just calling IPC
ipcScanRelay(argc, argv);
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(gamertip);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then gamertip.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in gamertip.conf in the data directory)
QMessageBox::critical(0, "gamertip",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("gamertip");
app.setOrganizationDomain("gamertip.su");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("gamertip-Qt-testnet");
else
app.setApplicationName("gamertip-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. gamertip_de.qm (shortcut "de" needs to be defined in gamertip.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. gamertip_de_DE.qm (shortcut "de_DE" needs to be defined in gamertip.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
gamertipGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit(argc, argv);
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit gamertip-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // gamertip_QT_TEST
| mit |
gravitano/framework | src/App/Http/Controllers/HomeController.php | 182 | <?php namespace App\Http\Controllers;
use Gravitano\Routing\Controller;
class HomeController extends Controller {
public function index()
{
return view()->make('hello');
}
} | mit |
mrLSD/go-benchmark-app | tools/siege_test.go | 3272 | package tools
import (
cfg "github.com/mrlsd/go-benchmark-app/config"
"testing"
)
const SIEGE_RESULT = `
Transactions: 146229 hits
Availability: 99.63 %
Elapsed time: 9.11 secs
Data transferred: 2.65 MB
Response time: 0.01 secs
Transaction rate: 16051.48 trans/sec
Throughput: 0.29 MB/sec
Concurrency: 91.92
Successful transactions: 0
Failed transactions: 546
Longest transaction: 0.31
Shortest transaction: 0.00
`
// TestSiegeBenchCommand - test Siege command generator
func TestSiegeBenchCommand(t *testing.T) {
var tool SiegeTool
config := &cfg.Config{}
config.Siege.Concurrent = 1
config.Siege.Time = 1
tool = SiegeTool{&config.Siege}
_, err := tool.BenchCommand("test")
if err != nil {
t.Fatal(err)
}
config.Siege.Concurrent = 0
config.Siege.Time = 1
tool = SiegeTool{&config.Siege}
_, err = tool.BenchCommand("test")
if err == nil {
t.Fatal("Unexpected result for Concurrent")
}
config.Siege.Concurrent = 1
config.Siege.Time = 0
tool = SiegeTool{&config.Siege}
_, err = tool.BenchCommand("test")
if err == nil {
t.Fatal("Unexpected result for Time")
}
}
// TestSiegeCommonResults - text common results interface
func TestSiegeCommonResults(t *testing.T) {
var tool SiegeTool
cfg.Cfg.Verbose = true
config := &cfg.Config{}
config.Siege.Concurrent = 1
config.Siege.Time = 1
tool = SiegeTool{&config.Siege}
result, err := tool.BenchCommand("test")
if err != nil {
t.Fatal(err)
}
_ = result.Command()
_ = result.Params()
data := []byte("")
result.Parse(data)
data = []byte(SIEGE_RESULT)
result.Parse(data)
}
// TestSiegeCalculate - test Siege total results calculation
func TestSiegeCalculate(t *testing.T) {
initConfig := &cfg.Config{}
_, err := cfg.LoadConfig("../"+cfg.ConfigFile, initConfig)
if err != nil {
t.Fatal(err)
}
cfg.Cfg.Try = 3
// Init Aggregated results
data := make(AggreatedResults, 1)
data[0] = make([]BenchResults, cfg.Cfg.Try)
// Init Results 1
result1 := SiegeResults{}
result1.Transactions = 90.
result1.Availability = 99.
result1.Concurrency = 90.
result1.LongestTransaction = 1.2
result1.TransactionRate = 1200
// Init Results 2
result2 := SiegeResults{}
result2.Transactions = 180.
result2.Availability = 66.
result2.Concurrency = 60.
result2.LongestTransaction = 1.5
result2.TransactionRate = 1500
data[0][0].Siege = result1
data[0][1].Siege = result2
data[0][2].Siege = result2
result := data.DataAnalyze()
if len(result) > 1 {
t.Fatalf("Faile result length: %v", "DataAnalyze")
}
// Test PrintResults
result[0].Siege.PrintResults()
if int(result[0].Siege.Transactions) != 150 {
t.Fatalf("Error calculation: %v", "Siege.TransactionRate")
}
if int(result[0].Siege.Availability) != 77 {
t.Fatalf("Error calculation: %v", "Siege.Availability")
}
if result[0].Siege.LongestTransaction != 1.4 {
t.Fatalf("Error calculation: %v", "Siege.LongestTransaction")
}
if int(result[0].Siege.TransactionRate) != 1400 {
t.Fatalf("Error calculation: %v", "Siege.TransactionRate")
}
config := &cfg.Config{
App: []cfg.AppConfig{
{
Title: "Test 1",
Path: "/bin/bash",
Url: "test",
},
},
}
PrintResults(&result, config)
}
| mit |
Ameliorate/Buildstation-Server | Buildstation-Server/Class/NetworkThread.cs | 2872 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Sockets;
using System.Threading;
namespace Buildstation_Server.Class
{
static class NetworkThread
{
private static TcpClient NewConnection;
private static Dictionary<string, ClientTracker> ClientTrackers = new Dictionary<string, ClientTracker>();
private static Dictionary<string, Thread> ClientThreads = new Dictionary<string, Thread>();
public static List<string> ClientTrackerKeys = new List<string>();
public static void NetworkListenerThread()
{
// Some needed varibles for network connections.
TcpListener Listener = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 25565);
Listener.Start();
string NewConnectionString;
Random Random = new Random();
while (true)
{
NewConnection = Listener.AcceptTcpClient();
NewConnectionString = Random.Next(int.MaxValue).ToString();
ClientTrackers.Add(NewConnectionString, new ClientTracker(NewConnection, NewConnectionString));
ClientThreads.Add(NewConnectionString, new Thread(ClientTrackers[NewConnectionString].Connect));
ClientTrackerKeys.Add(NewConnectionString);
ClientThreads[NewConnectionString].Start(); // Creates an instance of the client tracking class, creates a new thread of it, then starts the thread. Also it adds the key to a list for use in broadcasting.
Console.WriteLine("[Info] New client " + NewConnectionString + " connected.");
}
}
public static Dictionary<string, dynamic> NetworkSorters = new Dictionary<string, dynamic>();
public static void RegisterNetworkSorter(string SorterName, dynamic NetworkSorter)
{
NetworkSorters.Add(SorterName, NetworkSorter);
}
public static void BroadcastMessage(string Sorter, string Message)
{
int Progress = 0;
string Key;
while (Progress <= ClientTrackerKeys.Count)
{
Key = ClientTrackerKeys[Progress];
ClientTrackers[Key].SendMessage(Sorter, Message);
Progress++;
}
}
public static void BroadcastMessage(string Sorter, string[] Message)
{
int Progress = 0;
string Key;
while (Progress <= ClientTrackerKeys.Count)
{
if (Progress >= ClientTrackerKeys.Count)
break;
Key = ClientTrackerKeys[Progress];
ClientTrackers[Key].SendMessage(Sorter, Message);
Progress++;
}
}
}
}
| mit |
rtnews/rtsfnt | node_modules/@swimlane/ngx-charts/release/polar-chart/polar-series.component.d.ts | 1195 | import { OnChanges, SimpleChanges } from '@angular/core';
import { LocationStrategy } from '@angular/common';
export declare class PolarSeriesComponent implements OnChanges {
private location;
name: any;
data: any;
xScale: any;
yScale: any;
colors: any;
scaleType: any;
curve: any;
activeEntries: any[];
rangeFillOpacity: number;
tooltipDisabled: boolean;
tooltipText: (o: any) => string;
gradient: boolean;
path: string;
circles: any[];
circleRadius: number;
outerPath: string;
areaPath: string;
gradientId: string;
gradientUrl: string;
hasGradient: boolean;
gradientStops: any[];
areaGradientStops: any[];
seriesColor: string;
active: boolean;
inactive: boolean;
constructor(location: LocationStrategy);
ngOnChanges(changes: SimpleChanges): void;
update(): void;
getAngle(d: any): any;
getRadius(d: any): any;
getLineGenerator(): any;
sortData(data: any): any;
isActive(entry: any): boolean;
isInactive(entry: any): boolean;
defaultTooltipText({label, value}: {
label: any;
value: any;
}): string;
updateGradients(): void;
}
| mit |
stas-vilchik/bdd-ml | data/7659.js | 1127 | {
var OnePlugin = createPlugin({
eventTypes: {
click: {
registrationName: "onClick"
},
focus: {
registrationName: "onFocus"
}
}
});
var TwoPlugin = createPlugin({
eventTypes: {
magic: {
phasedRegistrationNames: {
bubbled: "onMagicBubble",
captured: "onMagicCapture"
}
}
}
});
EventPluginRegistry.injectEventPluginsByName({
one: OnePlugin
});
EventPluginRegistry.injectEventPluginOrder(["one", "two"]);
expect(Object.keys(EventPluginRegistry.registrationNameModules).length).toBe(
2
);
expect(EventPluginRegistry.registrationNameModules.onClick).toBe(OnePlugin);
expect(EventPluginRegistry.registrationNameModules.onFocus).toBe(OnePlugin);
EventPluginRegistry.injectEventPluginsByName({
two: TwoPlugin
});
expect(Object.keys(EventPluginRegistry.registrationNameModules).length).toBe(
4
);
expect(EventPluginRegistry.registrationNameModules.onMagicBubble).toBe(
TwoPlugin
);
expect(EventPluginRegistry.registrationNameModules.onMagicCapture).toBe(
TwoPlugin
);
}
| mit |
caseyhammond/COMP4711-01 | Student.php | 1095 | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Student
*
* @author caseyy
*/
class Student {
function __construct() {
$this->surname = '';
$this->first_name = '';
$this->emails = array();
$this->grades = array();
}
function add_email($which,$address) {
$this->emails[$which] = $address;
}
function add_grade($grade) {
$this->grades[] = $grade;
}
function average() {
$total = 0;
foreach ($this->grades as $value)
$total += $value;
return $total / count($this->grades);
}
function toString() {
$result = $this->first_name . ' ' .
$this->surname;
$result .= ' ('.$this->average().")\n";
foreach($this->emails as $which=>$what)
$result .= $which . ': '. $what. "\n";
$result .= "\n";
return '<pre>'.$result.'</pre>';
}
}
| mit |
cmorenokkatoo/kkatooapp | amqp-1.8.0beta2/tests/amqpqueue_bind_basic.phpt | 522 | --TEST--
AMQPQueue
--SKIPIF--
<?php if (!extension_loaded("amqp")) print "skip"; ?>
--FILE--
<?php
$cnn = new AMQPConnection();
$cnn->connect();
$ch = new AMQPChannel($cnn);
$ex = new AMQPExchange($ch);
$ex->setName('exchange-' . microtime(true));
$ex->setType(AMQP_EX_TYPE_DIRECT);
$ex->declareExchange();
$queue = new AMQPQueue($ch);
$queue->setName("queue-" . microtime(true));
$queue->declareQueue();
var_dump($queue->bind($ex->getName(), 'routing.key'));
$queue->delete();
$ex->delete();
?>
--EXPECT--
bool(true)
| mit |
andersjo/hals | hals/cli/predict.py | 68 | def predict(args):
print(args)
print("Doing the prediction") | mit |
pedrogpimenta/dropmarks | app/components/Home.js | 195 | var React = require('react');
var Home = React.createClass({
render: function() {
return(
<h2 className="text-center">
See your bookmarks in Dropbox
</h2>
)
}
}); | mit |
alymdrictels/symfony-cms | src/Alymdrictels/CMSBundle/Controller/PageController.php | 6133 | <?php
namespace Alymdrictels\CMSBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Alymdrictels\CMSBundle\Entity\Page;
use Alymdrictels\CMSBundle\Form\PageType;
/**
* Page controller.
*
*/
class PageController extends Controller
{
/**
* Lists all Page entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AlymdrictelsCMSBundle:Page')->findAll();
return $this->render('AlymdrictelsCMSBundle:Page:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Page entity.
*
*/
public function createAction(Request $request)
{
$entity = new Page();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('cms_page_show', array('id' => $entity->getId())));
}
return $this->render('AlymdrictelsCMSBundle:Page:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a Page entity.
*
* @param Page $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Page $entity)
{
$form = $this->createForm(new PageType(), $entity, array(
'action' => $this->generateUrl('cms_page_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Page entity.
*
*/
public function newAction()
{
$entity = new Page();
$form = $this->createCreateForm($entity);
return $this->render('AlymdrictelsCMSBundle:Page:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Page entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AlymdrictelsCMSBundle:Page')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Page entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('AlymdrictelsCMSBundle:Page:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing Page entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AlymdrictelsCMSBundle:Page')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Page entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('AlymdrictelsCMSBundle:Page:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to edit a Page entity.
*
* @param Page $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Page $entity)
{
$form = $this->createForm(new PageType(), $entity, array(
'action' => $this->generateUrl('cms_page_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Page entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AlymdrictelsCMSBundle:Page')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Page entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('cms_page_edit', array('id' => $id)));
}
return $this->render('AlymdrictelsCMSBundle:Page:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Page entity.
*
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AlymdrictelsCMSBundle:Page')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Page entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('cms_page'));
}
/**
* Creates a form to delete a Page entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('cms_page_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
| mit |
ssi-anik/clan | library/constants.php | 492 | <?php
define('MAXIMUM_USERNAME_CHARACTER_LENGTH', 30);
define('MAXIMUM_NAME_CHARACTER_LENGTH', 50);
define('MAXIMUM_EMAIL_CHARACTER_LENGTH', 80);
define('MAXIMUM_PASSWORD_CHARACTER_LENGTH', 60);
define('MAXIMUM_UID_CHARACTER_LENGTH', 50);
define('ADMIN_USER', 1);
define('GENERAL_USER', 2);
define('MAXIMUM_DESIGNATION_CHARACTER_LENGTH', 40);
define('MAXIMUM_DESIGNATION_SLUG_LENGTH', 60);
define('CONTACT_TYPE_EMAIL', 1);
define('CONTACT_TYPE_PHONE', 2);
define('CONTACT_TYPE_ADDRESS', 3); | mit |
in9web/ultracms | core/helpers/language.php | 218 | <?php
use \Ultra\App;
function _t($text)
{
if (isset(App::$lang[$text])) {
return App::$lang[$text];
} else {
return $text;
}
}
function t($text)
{
echo _t($text);
} | mit |
akhildhanuka/slush-ppp-generator | templates/app/vendor.js | 121 | require('jquery');
require('angular');
require('angular-ui-router');
require('angular-sanitize');
require('ng-focus-if'); | mit |
xlplbo/translate_tool | vendor/github.com/360EntSecGroup-Skylar/excelize/styles_test.go | 2558 | package excelize
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSetConditionalFormat(t *testing.T) {
cases := []struct {
label string
format string
rules []*xlsxCfRule
}{{
label: "3_color_scale",
format: `[{
"type":"3_color_scale",
"criteria":"=",
"min_type":"num",
"mid_type":"num",
"max_type":"num",
"min_value": "-10",
"mid_value": "0",
"max_value": "10",
"min_color":"ff0000",
"mid_color":"00ff00",
"max_color":"0000ff"
}]`,
rules: []*xlsxCfRule{{
Priority: 1,
Type: "colorScale",
ColorScale: &xlsxColorScale{
Cfvo: []*xlsxCfvo{{
Type: "num",
Val: "-10",
}, {
Type: "num",
Val: "0",
}, {
Type: "num",
Val: "10",
}},
Color: []*xlsxColor{{
RGB: "FFFF0000",
}, {
RGB: "FF00FF00",
}, {
RGB: "FF0000FF",
}},
},
}},
}, {
label: "3_color_scale default min/mid/max",
format: `[{
"type":"3_color_scale",
"criteria":"=",
"min_type":"num",
"mid_type":"num",
"max_type":"num",
"min_color":"ff0000",
"mid_color":"00ff00",
"max_color":"0000ff"
}]`,
rules: []*xlsxCfRule{{
Priority: 1,
Type: "colorScale",
ColorScale: &xlsxColorScale{
Cfvo: []*xlsxCfvo{{
Type: "num",
Val: "0",
}, {
Type: "num",
Val: "50",
}, {
Type: "num",
Val: "0",
}},
Color: []*xlsxColor{{
RGB: "FFFF0000",
}, {
RGB: "FF00FF00",
}, {
RGB: "FF0000FF",
}},
},
}},
}, {
label: "2_color_scale default min/max",
format: `[{
"type":"2_color_scale",
"criteria":"=",
"min_type":"num",
"max_type":"num",
"min_color":"ff0000",
"max_color":"0000ff"
}]`,
rules: []*xlsxCfRule{{
Priority: 1,
Type: "colorScale",
ColorScale: &xlsxColorScale{
Cfvo: []*xlsxCfvo{{
Type: "num",
Val: "0",
}, {
Type: "num",
Val: "0",
}},
Color: []*xlsxColor{{
RGB: "FFFF0000",
}, {
RGB: "FF0000FF",
}},
},
}},
}}
for _, testCase := range cases {
xl := NewFile()
const sheet = "Sheet1"
const cellRange = "A1:A1"
err := xl.SetConditionalFormat(sheet, cellRange, testCase.format)
if err != nil {
t.Fatalf("%s", err)
}
xlsx := xl.workSheetReader(sheet)
cf := xlsx.ConditionalFormatting
assert.Len(t, cf, 1, testCase.label)
assert.Len(t, cf[0].CfRule, 1, testCase.label)
assert.Equal(t, cellRange, cf[0].SQRef, testCase.label)
assert.EqualValues(t, testCase.rules, cf[0].CfRule, testCase.label)
}
}
| mit |
s-bear/H5TL | doc/html/navtreeindex0.js | 18438 | var NAVTREEINDEX0 =
{
"_h5_t_l_8hpp.html":[2,0,0,0],
"_h5_t_l_8hpp.html#a0a256efae396de32f6c8e17a0ac5b410":[2,0,0,0,48],
"_h5_t_l_8hpp.html#a1068acc4b97b59901883bbb88b1f4434":[2,0,0,0,36],
"_h5_t_l_8hpp.html#a112af217f39b59064ce8a48cccc74764":[2,0,0,0,50],
"_h5_t_l_8hpp.html#a18b8ab0e48c3efb5dca7d93efd1bfbf6":[2,0,0,0,45],
"_h5_t_l_8hpp.html#a18d3869e336e2b6a64ec318cf9890c90":[2,0,0,0,57],
"_h5_t_l_8hpp.html#a195c328d15cb83d2cfede33d7a7a5b35":[2,0,0,0,38],
"_h5_t_l_8hpp.html#a1c8362f6cee0689275ecfddccba88274":[2,0,0,0,46],
"_h5_t_l_8hpp.html#a1d69ddff4138c6eae990acc82730d434":[2,0,0,0,37],
"_h5_t_l_8hpp.html#a2bb6834f5cfb632c59f6b8833fb062e1":[2,0,0,0,56],
"_h5_t_l_8hpp.html#a31797435e6c9f7813cc320fc4529192f":[2,0,0,0,53],
"_h5_t_l_8hpp.html#a4d53214bda1e246cb4f3d3d6919d1380":[2,0,0,0,54],
"_h5_t_l_8hpp.html#a5583c20a945634c741c4c006f5abd3a6":[2,0,0,0,51],
"_h5_t_l_8hpp.html#a59058fd08440d7ea30ed09d8de233185":[2,0,0,0,27],
"_h5_t_l_8hpp.html#a603d589a4de14384ef7d47104e6a7862":[2,0,0,0,43],
"_h5_t_l_8hpp.html#a7ccc1cda9969334b121fe7715c9f874a":[2,0,0,0,28],
"_h5_t_l_8hpp.html#a85542c4df7874da8c91127958faa22a4":[2,0,0,0,40],
"_h5_t_l_8hpp.html#a889fa5a542d1ee8e363d2686f1e447d7":[2,0,0,0,47],
"_h5_t_l_8hpp.html#a9435795a9a0055ccdfa8194228e692a2":[2,0,0,0,35],
"_h5_t_l_8hpp.html#aa0de5dcbc2c4c8a99ed8e35774ba15ab":[2,0,0,0,39],
"_h5_t_l_8hpp.html#aa1cd20e4f5fb1a248b8475f923d3b1b5":[2,0,0,0,52],
"_h5_t_l_8hpp.html#aa42336b53e3ba0b95d2495ba8084df67":[2,0,0,0,49],
"_h5_t_l_8hpp.html#ab1eb736c80826c4999a4644ff4d1b918":[2,0,0,0,31],
"_h5_t_l_8hpp.html#ab549a1bd6205a5bff9dc8e5ca83fa76a":[2,0,0,0,42],
"_h5_t_l_8hpp.html#ab5f7e50bf1e42f78c4fc0214b6cceb57":[2,0,0,0,33],
"_h5_t_l_8hpp.html#ab61feeb286c0d3e6c82b22277ac9291b":[2,0,0,0,34],
"_h5_t_l_8hpp.html#ac159834e78342cf3e5daf694c65b0dc9":[2,0,0,0,44],
"_h5_t_l_8hpp.html#adcc1829002ae4d479fad02d0bf47f793":[2,0,0,0,41],
"_h5_t_l_8hpp.html#add11f817badecc20cdffaeca031e7ab5":[2,0,0,0,32],
"_h5_t_l_8hpp.html#ae09d3a5b75f86dad261e807592fee081":[2,0,0,0,58],
"_h5_t_l_8hpp.html#ae8a2ececf9e0f95ab928f168fcedef34":[2,0,0,0,55],
"_h5_t_l_8hpp.html#aee6ce891703ca7ed2cb72046c3d1768f":[2,0,0,0,29],
"_h5_t_l_8hpp.html#af374af4623acf05fb53284ae67ffc911":[2,0,0,0,30],
"_h5_t_l_8hpp_source.html":[2,0,0,0],
"annotated.html":[1,0],
"class_h5_t_l_1_1_attribute.html":[1,0,0,14],
"class_h5_t_l_1_1_attribute.html#a0720b5f434e636e22a3ed34f847eec57":[1,0,0,14,13],
"class_h5_t_l_1_1_attribute.html#a14e297e1930afdcb1e6f4fd446587b72":[1,0,0,14,11],
"class_h5_t_l_1_1_attribute.html#a16fd54489901878488beb8fd75be846f":[1,0,0,14,8],
"class_h5_t_l_1_1_attribute.html#a32ac6a40d8cbefb6b4b6cd069dcc919f":[1,0,0,14,12],
"class_h5_t_l_1_1_attribute.html#a52de6c303533cc5f76ed4e158332da49":[1,0,0,14,6],
"class_h5_t_l_1_1_attribute.html#a6429348b75c240ee43281d76fe523ba4":[1,0,0,14,0],
"class_h5_t_l_1_1_attribute.html#a6d651fbe37b2311c62deed182d1d2371":[1,0,0,14,3],
"class_h5_t_l_1_1_attribute.html#a7b476eaa2bdc241d05ae5d57861e3cb0":[1,0,0,14,1],
"class_h5_t_l_1_1_attribute.html#a813d411fb240af759bc6f38f8b64aede":[1,0,0,14,4],
"class_h5_t_l_1_1_attribute.html#a976384a5498eca27eeb00d20031ac6b0":[1,0,0,14,5],
"class_h5_t_l_1_1_attribute.html#ab468364f2302366ca16e53edfbdfef21":[1,0,0,14,9],
"class_h5_t_l_1_1_attribute.html#ad8ce0c28ab0d1c442a5ed668b3bcb62a":[1,0,0,14,10],
"class_h5_t_l_1_1_attribute.html#aebc7274e4e3313000fdefac4aa2e18c3":[1,0,0,14,7],
"class_h5_t_l_1_1_attribute.html#af0918ea5d8b3ee3eace2b4b70de083da":[1,0,0,14,2],
"class_h5_t_l_1_1_d_props.html":[1,0,0,9],
"class_h5_t_l_1_1_d_props.html#a3c5536e4dd3c26da5f0fd14b85929394":[1,0,0,9,13],
"class_h5_t_l_1_1_d_props.html#a4477e3f09c8df3b9235cc59a6107d18b":[1,0,0,9,1],
"class_h5_t_l_1_1_d_props.html#a4d9c048bbe6890fb8a76f42f5e41e02c":[1,0,0,9,9],
"class_h5_t_l_1_1_d_props.html#a4e6371b21d3b981b9813709a367f7c8a":[1,0,0,9,8],
"class_h5_t_l_1_1_d_props.html#a558ee807583c289f062942f91e6bfc39":[1,0,0,9,2],
"class_h5_t_l_1_1_d_props.html#a881b1504af4a748112c0193ad712f058":[1,0,0,9,4],
"class_h5_t_l_1_1_d_props.html#a8861717b78465e2b929a8f9822a25f91":[1,0,0,9,0],
"class_h5_t_l_1_1_d_props.html#aa6168baf2f7cc4e171f8c65ed2e7f0e3":[1,0,0,9,11],
"class_h5_t_l_1_1_d_props.html#ab50eedeeb4f15976869e2314cda43f28":[1,0,0,9,5],
"class_h5_t_l_1_1_d_props.html#adf68d5443694c5a28d089efaca1ccefc":[1,0,0,9,14],
"class_h5_t_l_1_1_d_props.html#ae0515ee98e2bcd02c55160a33a63aabf":[1,0,0,9,6],
"class_h5_t_l_1_1_d_props.html#ae8ab837067c35b714b517f9cf08c6833":[1,0,0,9,12],
"class_h5_t_l_1_1_d_props.html#ae93cfa78bd2904d835be0ef8c01ac328":[1,0,0,9,10],
"class_h5_t_l_1_1_d_props.html#af1283799daeee775b41effb026792b79":[1,0,0,9,7],
"class_h5_t_l_1_1_d_props.html#af24985828926acc30de48fbf2351620f":[1,0,0,9,3],
"class_h5_t_l_1_1_d_space.html":[1,0,0,11],
"class_h5_t_l_1_1_d_space.html#a0ba05245349237b1e42813cf4397fa32":[1,0,0,11,2],
"class_h5_t_l_1_1_d_space.html#a0bacd841219760f82023a5c6d34d71c8":[1,0,0,11,4],
"class_h5_t_l_1_1_d_space.html#a217bb888d3d9666e1105a7b839f130d7":[1,0,0,11,13],
"class_h5_t_l_1_1_d_space.html#a361184a3052fd5fe5bd71454b244007d":[1,0,0,11,5],
"class_h5_t_l_1_1_d_space.html#a376a9922dbf0eb7234bb33d5e14825a9":[1,0,0,11,6],
"class_h5_t_l_1_1_d_space.html#a527298cfe321414033f52329a49e6b7a":[1,0,0,11,10],
"class_h5_t_l_1_1_d_space.html#a62a6b850d17c08da4437c6080f7c3598":[1,0,0,11,12],
"class_h5_t_l_1_1_d_space.html#a7557c53c7dc3b9b4e8a12cc35a438564":[1,0,0,11,11],
"class_h5_t_l_1_1_d_space.html#a7abcd0097c46b8f3252b6610bca3ebd1":[1,0,0,11,9],
"class_h5_t_l_1_1_d_space.html#a8d0637d8c3adbee551721f7fbd609de1":[1,0,0,11,14],
"class_h5_t_l_1_1_d_space.html#a911e7f9f9398e7324c508f55fe63baaa":[1,0,0,11,7],
"class_h5_t_l_1_1_d_space.html#aa253d3194c386398cd3a614022226091":[1,0,0,11,15],
"class_h5_t_l_1_1_d_space.html#ab42688e0331b2b49d311d43dde36c31e":[1,0,0,11,16],
"class_h5_t_l_1_1_d_space.html#ab93eacb81dea8d0c21041812e61f85ab":[1,0,0,11,18],
"class_h5_t_l_1_1_d_space.html#abd4bab8f7ee748d7ea63f7f9b6248611":[1,0,0,11,17],
"class_h5_t_l_1_1_d_space.html#abe4839703fc08c5851b8388ee43177ef":[1,0,0,11,1],
"class_h5_t_l_1_1_d_space.html#add7bd418265b7dcea2e6b0fd60ea15e0":[1,0,0,11,0],
"class_h5_t_l_1_1_d_space.html#aed1106ff0fb79eda9c2666b62eebc4d8":[1,0,0,11,8],
"class_h5_t_l_1_1_d_space.html#af10333ae1d222213a34db2a338ae158c":[1,0,0,11,3],
"class_h5_t_l_1_1_d_type.html":[1,0,0,4],
"class_h5_t_l_1_1_d_type.html#a0839ae0745f1ed4f15bfe521f14e983e":[1,0,0,4,6],
"class_h5_t_l_1_1_d_type.html#a11fb262f22fd509d1fb047120c5b0a92":[1,0,0,4,4],
"class_h5_t_l_1_1_d_type.html#a16e2caeb17c88224bb286201d1b6463c":[1,0,0,4,8],
"class_h5_t_l_1_1_d_type.html#a1ece4a21faeb565b63695521a0cf0767":[1,0,0,4,9],
"class_h5_t_l_1_1_d_type.html#a2e4087bdb1aae026237ac05894e559b9":[1,0,0,4,3],
"class_h5_t_l_1_1_d_type.html#a5ba85ceb49042ecd7c9a536d3342a143":[1,0,0,4,2],
"class_h5_t_l_1_1_d_type.html#a693b78e01470174565503241195fa7d9":[1,0,0,4,5],
"class_h5_t_l_1_1_d_type.html#a7de5859c78eac6aacb64b355c40db270":[1,0,0,4,0],
"class_h5_t_l_1_1_d_type.html#a9b125e54e616f2bd5c0c52849c6b2383":[1,0,0,4,1],
"class_h5_t_l_1_1_d_type.html#ab93eacb81dea8d0c21041812e61f85ab":[1,0,0,4,11],
"class_h5_t_l_1_1_d_type.html#abd4bab8f7ee748d7ea63f7f9b6248611":[1,0,0,4,10],
"class_h5_t_l_1_1_d_type.html#af32cf33b4b23e8326ea7134fac1fa6b8":[1,0,0,4,7],
"class_h5_t_l_1_1_dataset.html":[1,0,0,16],
"class_h5_t_l_1_1_dataset.html#a077d5bb62ed4b99db4900ae2af64cb7b":[1,0,0,16,27],
"class_h5_t_l_1_1_dataset.html#a0857ba27c707399302da28064342915f":[1,0,0,16,1],
"class_h5_t_l_1_1_dataset.html#a09b7f1c8bf3d92fd3dfdf0e21138350d":[1,0,0,16,6],
"class_h5_t_l_1_1_dataset.html#a0a8e406f9036b0e95d6645bc7f17dd85":[1,0,0,16,14],
"class_h5_t_l_1_1_dataset.html#a0db33d74e18e6908a30ee8048a42ae5d":[1,0,0,16,4],
"class_h5_t_l_1_1_dataset.html#a0dbc91a3302c8affed45970aeb3cdd88":[1,0,0,16,2],
"class_h5_t_l_1_1_dataset.html#a13145066f529134568242b3aa03ff991":[1,0,0,16,15],
"class_h5_t_l_1_1_dataset.html#a1b66996cc6de6e7ea03a110e15888a3a":[1,0,0,16,19],
"class_h5_t_l_1_1_dataset.html#a21a8ba439908fc08837b01e737247f37":[1,0,0,16,7],
"class_h5_t_l_1_1_dataset.html#a2697825715974a353728f0d4d5658112":[1,0,0,16,32],
"class_h5_t_l_1_1_dataset.html#a3ac128ce40c50aaf352c70c96c853748":[1,0,0,16,13],
"class_h5_t_l_1_1_dataset.html#a3b0cc1434d993029fcbff1998767e0c3":[1,0,0,16,23],
"class_h5_t_l_1_1_dataset.html#a57a932b797520777fb16ebe9161cffd5":[1,0,0,16,28],
"class_h5_t_l_1_1_dataset.html#a59c376ac04cbb6f040d3bcf7ddac2c21":[1,0,0,16,31],
"class_h5_t_l_1_1_dataset.html#a5eff3aaf3ac89c159cd8182400947b50":[1,0,0,16,25],
"class_h5_t_l_1_1_dataset.html#a72b917d03cf1be028b0a60663f3735da":[1,0,0,16,11],
"class_h5_t_l_1_1_dataset.html#a791cc0c96a11264f01137984487ee17c":[1,0,0,16,9],
"class_h5_t_l_1_1_dataset.html#a82d72341e7102390af4995aaaea3962a":[1,0,0,16,10],
"class_h5_t_l_1_1_dataset.html#a85346218808829de0cb2c84fa42efe86":[1,0,0,16,30],
"class_h5_t_l_1_1_dataset.html#a870b88885b1edd806edcc15cc4a68b89":[1,0,0,16,12],
"class_h5_t_l_1_1_dataset.html#a918b06db14171308441b89b701d827ba":[1,0,0,16,3],
"class_h5_t_l_1_1_dataset.html#a919ef513e9cd4bb57c796551d4b1d2f7":[1,0,0,16,29],
"class_h5_t_l_1_1_dataset.html#a993f08f7a55ecf7cef453c58af2de7c8":[1,0,0,16,21],
"class_h5_t_l_1_1_dataset.html#aa7ffa9c5a6f1e11351fecea1dbf7d9c5":[1,0,0,16,20],
"class_h5_t_l_1_1_dataset.html#aa8d9fd06fae090ddded69ac66040443a":[1,0,0,16,18],
"class_h5_t_l_1_1_dataset.html#ab0f7e4ae35955b9c4990f23405b37186":[1,0,0,16,17],
"class_h5_t_l_1_1_dataset.html#aba2bb711bf30e38ac5078663c200c318":[1,0,0,16,8],
"class_h5_t_l_1_1_dataset.html#abddc9236c56c2631b70dc2347d5788bd":[1,0,0,16,16],
"class_h5_t_l_1_1_dataset.html#add8fa95fb77a9167f432e5d6abddc2ed":[1,0,0,16,22],
"class_h5_t_l_1_1_dataset.html#aebd58da33d992bb608067c85c944e688":[1,0,0,16,24],
"class_h5_t_l_1_1_dataset.html#aec3ddf07a6b592c8e7f8b44e7fd35375":[1,0,0,16,26],
"class_h5_t_l_1_1_dataset.html#af0f65d79e42993b413fdc48760a28bf5":[1,0,0,16,5],
"class_h5_t_l_1_1_dataset.html#af6f2cd1a5170e2b7d866721c9be0fd11":[1,0,0,16,0],
"class_h5_t_l_1_1_error_handler.html":[1,0,0,2],
"class_h5_t_l_1_1_error_handler.html#ad45ba2e2661df16f5f78d4c1e9aeec33":[1,0,0,2,0],
"class_h5_t_l_1_1_file.html":[1,0,0,18],
"class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208":[1,0,0,18,0],
"class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208a1827760549531e870388ec6866d0165e":[1,0,0,18,0,3],
"class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208a7595a9318f8f007c8177eb6129cc8a55":[1,0,0,18,0,0],
"class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208ab0b0c0c75d3e15b086124b605f60d753":[1,0,0,18,0,2],
"class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208afcf13dfdb15f7aa5839846725365a240":[1,0,0,18,0,1],
"class_h5_t_l_1_1_file.html#a5499e761feeab4c85ca3aba1fb218ec9":[1,0,0,18,3],
"class_h5_t_l_1_1_file.html#a91c89c5f48ddd0762fd39ee1e0ae73b8":[1,0,0,18,1],
"class_h5_t_l_1_1_file.html#aa05382409178af69cda0f65a13bd969f":[1,0,0,18,2],
"class_h5_t_l_1_1_group.html":[1,0,0,17],
"class_h5_t_l_1_1_group.html#a1acf181964e091a05491bdd07dc2acf2":[1,0,0,17,28],
"class_h5_t_l_1_1_group.html#a21fb4c34f51a8a56817f5a8ea1c8b9f3":[1,0,0,17,2],
"class_h5_t_l_1_1_group.html#a23cda162d64c296d39cdd3c63551c275":[1,0,0,17,1],
"class_h5_t_l_1_1_group.html#a24d333709b9200ecc94c51f4081ebd70":[1,0,0,17,24],
"class_h5_t_l_1_1_group.html#a2b8d910eb930a2ec45b3051452a79d73":[1,0,0,17,9],
"class_h5_t_l_1_1_group.html#a3161bd364a0f5f4df9d81619482ff559":[1,0,0,17,10],
"class_h5_t_l_1_1_group.html#a33879ce41734238eb50b6917268d279d":[1,0,0,17,4],
"class_h5_t_l_1_1_group.html#a35a7440b9f212a8498da095fffa6df6d":[1,0,0,17,18],
"class_h5_t_l_1_1_group.html#a373048dcbc38705ab6439b7eb7d66a7e":[1,0,0,17,3],
"class_h5_t_l_1_1_group.html#a3bc589843f86da0a0e3c7c0382c47188":[1,0,0,17,15],
"class_h5_t_l_1_1_group.html#a3ebe23fce9aecac979096da6a71db0c5":[1,0,0,17,23],
"class_h5_t_l_1_1_group.html#a574293c18fed3e5391267dd3c33bf81a":[1,0,0,17,7],
"class_h5_t_l_1_1_group.html#a60f8bb8b3a76fa457331a375172fc716":[1,0,0,17,21],
"class_h5_t_l_1_1_group.html#a709506d6232025482633abcb97a4d7c5":[1,0,0,17,8],
"class_h5_t_l_1_1_group.html#a7f928985e0131b63c21764136bf1a01d":[1,0,0,17,14],
"class_h5_t_l_1_1_group.html#a84745fdcd43c75880ca4cd1e064e4ac9":[1,0,0,17,16],
"class_h5_t_l_1_1_group.html#a90c193fd37dd7f35b9b62f05f830b084":[1,0,0,17,26],
"class_h5_t_l_1_1_group.html#aa7ec7b8867f7e0bcf2fb1ee7de321119":[1,0,0,17,27],
"class_h5_t_l_1_1_group.html#aa894ff509b260d0c5d68a765a5940da9":[1,0,0,17,5],
"class_h5_t_l_1_1_group.html#ab4fbf0c28300b542e2279f5e85fb641f":[1,0,0,17,25],
"class_h5_t_l_1_1_group.html#ab6faa3a0b9c6f9358130e1e5e4a08ad1":[1,0,0,17,6],
"class_h5_t_l_1_1_group.html#ab726c68a6db6a1055085e59dfb87621f":[1,0,0,17,17],
"class_h5_t_l_1_1_group.html#ab8333c1f74f0d82b87b0a3056b36bfa7":[1,0,0,17,20],
"class_h5_t_l_1_1_group.html#abbf255a903c6a9c5a5dcb33660ce0370":[1,0,0,17,12],
"class_h5_t_l_1_1_group.html#ac23072a42de2e938f27e64ea0cd9d96f":[1,0,0,17,19],
"class_h5_t_l_1_1_group.html#ac40bee3d18aed5cc150ec47d61554ef3":[1,0,0,17,13],
"class_h5_t_l_1_1_group.html#acc0a96894857a334132329442482803b":[1,0,0,17,22],
"class_h5_t_l_1_1_group.html#ad2459b5cc9b72fe123565b5afa9c0c8a":[1,0,0,17,0],
"class_h5_t_l_1_1_group.html#af143a648b8feec1260727e16960afff1":[1,0,0,17,11],
"class_h5_t_l_1_1_hyperslab.html":[1,0,0,13],
"class_h5_t_l_1_1_hyperslab.html#a5dcf0570bbda6a425edaaf2af29f3fb1":[1,0,0,13,0],
"class_h5_t_l_1_1_hyperslab.html#a6767e21930b6bf0045ff24344b062c25":[1,0,0,13,1],
"class_h5_t_l_1_1_hyperslab.html#a70290a488decd4290d13257aae5e6a4b":[1,0,0,13,4],
"class_h5_t_l_1_1_hyperslab.html#a84b19741f0b131c62fdf82a596ae3a29":[1,0,0,13,3],
"class_h5_t_l_1_1_hyperslab.html#a9d67100bbeba66acc2d936da2ffdc79d":[1,0,0,13,8],
"class_h5_t_l_1_1_hyperslab.html#ae3087ea27a6ab424547472e6c4a6c531":[1,0,0,13,7],
"class_h5_t_l_1_1_hyperslab.html#ae3e0aa330ed576da3267eeb02e4ca4c0":[1,0,0,13,6],
"class_h5_t_l_1_1_hyperslab.html#af558c4b94ecde78058d2c47520d1e8b0":[1,0,0,13,2],
"class_h5_t_l_1_1_hyperslab.html#afc57fefbc6fa76330390afb77a3c889d":[1,0,0,13,5],
"class_h5_t_l_1_1_i_d.html":[1,0,0,3],
"class_h5_t_l_1_1_i_d.html#a408f510fcc998acb721e21c483846caa":[1,0,0,3,2],
"class_h5_t_l_1_1_i_d.html#a51fe296eef6fafcddcbdac65255ea1e8":[1,0,0,3,0],
"class_h5_t_l_1_1_i_d.html#a619d958450480ffdd8369ef2895560b5":[1,0,0,3,1],
"class_h5_t_l_1_1_i_d.html#a62a65c2333d41830c1410a6487dee22d":[1,0,0,3,7],
"class_h5_t_l_1_1_i_d.html#a71ff0b5de76ffecc1292c8b6ef8292f1":[1,0,0,3,6],
"class_h5_t_l_1_1_i_d.html#a84bdd4ffb1463004dfaef450b4e19d37":[1,0,0,3,9],
"class_h5_t_l_1_1_i_d.html#ac262957473b62ff680747b1244be8ff0":[1,0,0,3,4],
"class_h5_t_l_1_1_i_d.html#ac3f6aeae98925e043f2e2e3c892d42fd":[1,0,0,3,3],
"class_h5_t_l_1_1_i_d.html#ace3dd29ee46843c37e8622369698baf2":[1,0,0,3,8],
"class_h5_t_l_1_1_i_d.html#ad1a35bb991077bb094cdb0bb44339907":[1,0,0,3,5],
"class_h5_t_l_1_1_i_d.html#ade483b65e8a77310b025e86b11cbc38c":[1,0,0,3,10],
"class_h5_t_l_1_1_l_props.html":[1,0,0,8],
"class_h5_t_l_1_1_l_props.html#a32b5f1fffdf3c896f5bf227bc16ef4d7":[1,0,0,8,1],
"class_h5_t_l_1_1_l_props.html#a6604710a45e0f3cc1c124be10b3d8dac":[1,0,0,8,0],
"class_h5_t_l_1_1_l_props.html#aa517b340764074934db64700f5b8f904":[1,0,0,8,4],
"class_h5_t_l_1_1_l_props.html#aad7af2c22c381bfb797ba6571efd0979":[1,0,0,8,3],
"class_h5_t_l_1_1_l_props.html#ad653b9016ec853a59877d154a963f4fe":[1,0,0,8,2],
"class_h5_t_l_1_1_object.html":[1,0,0,15],
"class_h5_t_l_1_1_object.html#a0df22bfe64e6dad435b5213bd30f4b9f":[1,0,0,15,1],
"class_h5_t_l_1_1_object.html#a2754b17af0171db4213ff3471f43735e":[1,0,0,15,5],
"class_h5_t_l_1_1_object.html#a33796a47bc89d5296c62e979480a650a":[1,0,0,15,4],
"class_h5_t_l_1_1_object.html#a78d80a9f9e9423d1d57c3b6a31900a32":[1,0,0,15,10],
"class_h5_t_l_1_1_object.html#a8010c2daf63f2040fab6301f34285159":[1,0,0,15,3],
"class_h5_t_l_1_1_object.html#aa30a49c0c7cef0c84c1b2a8ea281e191":[1,0,0,15,6],
"class_h5_t_l_1_1_object.html#ab22f9aa2fa49a3a69a88e92612e31d2a":[1,0,0,15,7],
"class_h5_t_l_1_1_object.html#ab4e2a0eb603b800ef2166050b0675270":[1,0,0,15,2],
"class_h5_t_l_1_1_object.html#ab51c998e3e77a3dd32e6fb045adfac87":[1,0,0,15,9],
"class_h5_t_l_1_1_object.html#ac17e32f04e0626a107f15bc9cf076214":[1,0,0,15,12],
"class_h5_t_l_1_1_object.html#aceb78cc5b05918cf22a7f299baf790af":[1,0,0,15,0],
"class_h5_t_l_1_1_object.html#adc6638b07f5ea389c7cd507837b0c0be":[1,0,0,15,11],
"class_h5_t_l_1_1_object.html#afc9034606870ae1b5cd6a40f51ce35ee":[1,0,0,15,8],
"class_h5_t_l_1_1_p_d_type.html":[1,0,0,5],
"class_h5_t_l_1_1_p_d_type.html#a108044a31b27a19222feaaf06e801020":[1,0,0,5,1],
"class_h5_t_l_1_1_p_d_type.html#a1a81627ad759d043623abd9311347fa4":[1,0,0,5,5],
"class_h5_t_l_1_1_p_d_type.html#a300306023ca0360e2810732c7779681b":[1,0,0,5,2],
"class_h5_t_l_1_1_p_d_type.html#a5d84f01f19b6b9adfe0592af6acff6bf":[1,0,0,5,0],
"class_h5_t_l_1_1_p_d_type.html#a6addc1c1ab9e438912b9e3bf65cd6f6a":[1,0,0,5,3],
"class_h5_t_l_1_1_p_d_type.html#a85fa032de8ec7be551f92e2115743518":[1,0,0,5,4],
"class_h5_t_l_1_1_props.html":[1,0,0,7],
"class_h5_t_l_1_1_props.html#a362a126d171e718c9505390e239759a6":[1,0,0,7,1],
"class_h5_t_l_1_1_props.html#a3a3d47cfae590b862326a5f1d7de3090":[1,0,0,7,3],
"class_h5_t_l_1_1_props.html#a3b066dc66162bf42d0c63b3aa0739444":[1,0,0,7,0],
"class_h5_t_l_1_1_props.html#a6ef94b756784840c67410dd5dacdfa40":[1,0,0,7,2],
"class_h5_t_l_1_1_props.html#a7c0e3fcebfb68468dc1c63958d31533b":[1,0,0,7,5],
"class_h5_t_l_1_1_props.html#a90b5f20064452d9b1da869c2cbb317cb":[1,0,0,7,4],
"class_h5_t_l_1_1_select_all.html":[1,0,0,12],
"class_h5_t_l_1_1_selection.html":[1,0,0,10],
"class_h5_t_l_1_1_selection.html#a171d5093cb878eb3e30d0779667fbb13":[1,0,0,10,3],
"class_h5_t_l_1_1_selection.html#a9594895f58f917d8c450c66583d3f7ff":[1,0,0,10,2],
"class_h5_t_l_1_1_selection.html#ab7e340d2861f5e60b0e80381d39ba0c3":[1,0,0,10,1],
"class_h5_t_l_1_1_selection.html#aeab63be2c41250d0ab36c00356a8f750":[1,0,0,10,0],
"class_h5_t_l_1_1_selection.html#af2025c1e456b063868920512aedc05c9":[1,0,0,10,4],
"class_h5_t_l_1_1h5tl__error.html":[1,0,0,1],
"class_h5_t_l_1_1h5tl__error.html#abd8aa21e8e8a60d268d57a770c754390":[1,0,0,1,1],
"class_h5_t_l_1_1h5tl__error.html#ad46996ee68c341429d40437d57d2ccda":[1,0,0,1,0],
"classes.html":[1,1],
"dir_f33336c2fcaa8208dac3bc1a258ddbd4.html":[2,0,0],
"files.html":[2,0],
"functions.html":[1,3,0],
"functions.html":[1,3,0,0],
"functions_b.html":[1,3,0,1],
"functions_c.html":[1,3,0,2],
"functions_d.html":[1,3,0,3],
"functions_e.html":[1,3,0,4],
"functions_enum.html":[1,3,4]
};
| mit |
ArcherSys/ArcherSys | node_modules/npm/node_modules/cmd-shim/test/basic.js | 17714 | <<<<<<< HEAD
<<<<<<< HEAD
var test = require('tap').test
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var fixtures = path.resolve(__dirname, 'fixtures')
var cmdShim = require('../')
test('no shebang', function (t) {
var from = path.resolve(fixtures, 'from.exe')
var to = path.resolve(fixtures, 'exe.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
t.equal(fs.readFileSync(to, 'utf8'),
"\"$basedir/from.exe\" \"$@\"\nexit $?\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"\"%~dp0\\from.exe\" %*\r\n")
t.end()
})
})
test('env shebang', function (t) {
var from = path.resolve(fixtures, 'from.env')
var to = path.resolve(fixtures, 'env.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh"+
"\nbasedir=`dirname \"$0\"`"+
"\n"+
"\ncase `uname` in"+
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;"+
"\nesac"+
"\n"+
"\nif [ -x \"$basedir/node\" ]; then"+
"\n \"$basedir/node\" \"$basedir/from.env\" \"$@\""+
"\n ret=$?"+
"\nelse "+
"\n node \"$basedir/from.env\" \"$@\""+
"\n ret=$?"+
"\nfi"+
"\nexit $ret"+
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\node.exe\" (\r"+
"\n \"%~dp0\\node.exe\" \"%~dp0\\from.env\" %*\r"+
"\n) ELSE (\r"+
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n node \"%~dp0\\from.env\" %*\r"+
"\n)")
t.end()
})
})
test('env shebang with args', function (t) {
var from = path.resolve(fixtures, 'from.env.args')
var to = path.resolve(fixtures, 'env.args.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh"+
"\nbasedir=`dirname \"$0\"`"+
"\n"+
"\ncase `uname` in"+
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;"+
"\nesac"+
"\n"+
"\nif [ -x \"$basedir/node\" ]; then"+
"\n \"$basedir/node\" --expose_gc \"$basedir/from.env.args\" \"$@\""+
"\n ret=$?"+
"\nelse "+
"\n node --expose_gc \"$basedir/from.env.args\" \"$@\""+
"\n ret=$?"+
"\nfi"+
"\nexit $ret"+
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\node.exe\" (\r"+
"\n \"%~dp0\\node.exe\" --expose_gc \"%~dp0\\from.env.args\" %*\r"+
"\n) ELSE (\r"+
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n node --expose_gc \"%~dp0\\from.env.args\" %*\r"+
"\n)")
t.end()
})
})
test('explicit shebang', function (t) {
var from = path.resolve(fixtures, 'from.sh')
var to = path.resolve(fixtures, 'sh.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh" +
"\nbasedir=`dirname \"$0\"`" +
"\n" +
"\ncase `uname` in" +
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;" +
"\nesac" +
"\n" +
"\nif [ -x \"$basedir//usr/bin/sh\" ]; then" +
"\n \"$basedir//usr/bin/sh\" \"$basedir/from.sh\" \"$@\"" +
"\n ret=$?" +
"\nelse " +
"\n /usr/bin/sh \"$basedir/from.sh\" \"$@\"" +
"\n ret=$?" +
"\nfi" +
"\nexit $ret" +
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\/usr/bin/sh.exe\" (\r" +
"\n \"%~dp0\\/usr/bin/sh.exe\" \"%~dp0\\from.sh\" %*\r" +
"\n) ELSE (\r" +
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n /usr/bin/sh \"%~dp0\\from.sh\" %*\r" +
"\n)")
t.end()
})
})
test('explicit shebang with args', function (t) {
var from = path.resolve(fixtures, 'from.sh.args')
var to = path.resolve(fixtures, 'sh.args.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh" +
"\nbasedir=`dirname \"$0\"`" +
"\n" +
"\ncase `uname` in" +
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;" +
"\nesac" +
"\n" +
"\nif [ -x \"$basedir//usr/bin/sh\" ]; then" +
"\n \"$basedir//usr/bin/sh\" -x \"$basedir/from.sh.args\" \"$@\"" +
"\n ret=$?" +
"\nelse " +
"\n /usr/bin/sh -x \"$basedir/from.sh.args\" \"$@\"" +
"\n ret=$?" +
"\nfi" +
"\nexit $ret" +
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\/usr/bin/sh.exe\" (\r" +
"\n \"%~dp0\\/usr/bin/sh.exe\" -x \"%~dp0\\from.sh.args\" %*\r" +
"\n) ELSE (\r" +
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n /usr/bin/sh -x \"%~dp0\\from.sh.args\" %*\r" +
"\n)")
t.end()
})
})
=======
var test = require('tap').test
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var fixtures = path.resolve(__dirname, 'fixtures')
var cmdShim = require('../')
test('no shebang', function (t) {
var from = path.resolve(fixtures, 'from.exe')
var to = path.resolve(fixtures, 'exe.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
t.equal(fs.readFileSync(to, 'utf8'),
"\"$basedir/from.exe\" \"$@\"\nexit $?\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"\"%~dp0\\from.exe\" %*\r\n")
t.end()
})
})
test('env shebang', function (t) {
var from = path.resolve(fixtures, 'from.env')
var to = path.resolve(fixtures, 'env.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh"+
"\nbasedir=`dirname \"$0\"`"+
"\n"+
"\ncase `uname` in"+
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;"+
"\nesac"+
"\n"+
"\nif [ -x \"$basedir/node\" ]; then"+
"\n \"$basedir/node\" \"$basedir/from.env\" \"$@\""+
"\n ret=$?"+
"\nelse "+
"\n node \"$basedir/from.env\" \"$@\""+
"\n ret=$?"+
"\nfi"+
"\nexit $ret"+
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\node.exe\" (\r"+
"\n \"%~dp0\\node.exe\" \"%~dp0\\from.env\" %*\r"+
"\n) ELSE (\r"+
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n node \"%~dp0\\from.env\" %*\r"+
"\n)")
t.end()
})
})
test('env shebang with args', function (t) {
var from = path.resolve(fixtures, 'from.env.args')
var to = path.resolve(fixtures, 'env.args.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh"+
"\nbasedir=`dirname \"$0\"`"+
"\n"+
"\ncase `uname` in"+
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;"+
"\nesac"+
"\n"+
"\nif [ -x \"$basedir/node\" ]; then"+
"\n \"$basedir/node\" --expose_gc \"$basedir/from.env.args\" \"$@\""+
"\n ret=$?"+
"\nelse "+
"\n node --expose_gc \"$basedir/from.env.args\" \"$@\""+
"\n ret=$?"+
"\nfi"+
"\nexit $ret"+
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\node.exe\" (\r"+
"\n \"%~dp0\\node.exe\" --expose_gc \"%~dp0\\from.env.args\" %*\r"+
"\n) ELSE (\r"+
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n node --expose_gc \"%~dp0\\from.env.args\" %*\r"+
"\n)")
t.end()
})
})
test('explicit shebang', function (t) {
var from = path.resolve(fixtures, 'from.sh')
var to = path.resolve(fixtures, 'sh.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh" +
"\nbasedir=`dirname \"$0\"`" +
"\n" +
"\ncase `uname` in" +
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;" +
"\nesac" +
"\n" +
"\nif [ -x \"$basedir//usr/bin/sh\" ]; then" +
"\n \"$basedir//usr/bin/sh\" \"$basedir/from.sh\" \"$@\"" +
"\n ret=$?" +
"\nelse " +
"\n /usr/bin/sh \"$basedir/from.sh\" \"$@\"" +
"\n ret=$?" +
"\nfi" +
"\nexit $ret" +
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\/usr/bin/sh.exe\" (\r" +
"\n \"%~dp0\\/usr/bin/sh.exe\" \"%~dp0\\from.sh\" %*\r" +
"\n) ELSE (\r" +
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n /usr/bin/sh \"%~dp0\\from.sh\" %*\r" +
"\n)")
t.end()
})
})
test('explicit shebang with args', function (t) {
var from = path.resolve(fixtures, 'from.sh.args')
var to = path.resolve(fixtures, 'sh.args.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh" +
"\nbasedir=`dirname \"$0\"`" +
"\n" +
"\ncase `uname` in" +
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;" +
"\nesac" +
"\n" +
"\nif [ -x \"$basedir//usr/bin/sh\" ]; then" +
"\n \"$basedir//usr/bin/sh\" -x \"$basedir/from.sh.args\" \"$@\"" +
"\n ret=$?" +
"\nelse " +
"\n /usr/bin/sh -x \"$basedir/from.sh.args\" \"$@\"" +
"\n ret=$?" +
"\nfi" +
"\nexit $ret" +
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\/usr/bin/sh.exe\" (\r" +
"\n \"%~dp0\\/usr/bin/sh.exe\" -x \"%~dp0\\from.sh.args\" %*\r" +
"\n) ELSE (\r" +
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n /usr/bin/sh -x \"%~dp0\\from.sh.args\" %*\r" +
"\n)")
t.end()
})
})
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
var test = require('tap').test
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var fixtures = path.resolve(__dirname, 'fixtures')
var cmdShim = require('../')
test('no shebang', function (t) {
var from = path.resolve(fixtures, 'from.exe')
var to = path.resolve(fixtures, 'exe.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
t.equal(fs.readFileSync(to, 'utf8'),
"\"$basedir/from.exe\" \"$@\"\nexit $?\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"\"%~dp0\\from.exe\" %*\r\n")
t.end()
})
})
test('env shebang', function (t) {
var from = path.resolve(fixtures, 'from.env')
var to = path.resolve(fixtures, 'env.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh"+
"\nbasedir=`dirname \"$0\"`"+
"\n"+
"\ncase `uname` in"+
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;"+
"\nesac"+
"\n"+
"\nif [ -x \"$basedir/node\" ]; then"+
"\n \"$basedir/node\" \"$basedir/from.env\" \"$@\""+
"\n ret=$?"+
"\nelse "+
"\n node \"$basedir/from.env\" \"$@\""+
"\n ret=$?"+
"\nfi"+
"\nexit $ret"+
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\node.exe\" (\r"+
"\n \"%~dp0\\node.exe\" \"%~dp0\\from.env\" %*\r"+
"\n) ELSE (\r"+
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n node \"%~dp0\\from.env\" %*\r"+
"\n)")
t.end()
})
})
test('env shebang with args', function (t) {
var from = path.resolve(fixtures, 'from.env.args')
var to = path.resolve(fixtures, 'env.args.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh"+
"\nbasedir=`dirname \"$0\"`"+
"\n"+
"\ncase `uname` in"+
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;"+
"\nesac"+
"\n"+
"\nif [ -x \"$basedir/node\" ]; then"+
"\n \"$basedir/node\" --expose_gc \"$basedir/from.env.args\" \"$@\""+
"\n ret=$?"+
"\nelse "+
"\n node --expose_gc \"$basedir/from.env.args\" \"$@\""+
"\n ret=$?"+
"\nfi"+
"\nexit $ret"+
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\node.exe\" (\r"+
"\n \"%~dp0\\node.exe\" --expose_gc \"%~dp0\\from.env.args\" %*\r"+
"\n) ELSE (\r"+
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n node --expose_gc \"%~dp0\\from.env.args\" %*\r"+
"\n)")
t.end()
})
})
test('explicit shebang', function (t) {
var from = path.resolve(fixtures, 'from.sh')
var to = path.resolve(fixtures, 'sh.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh" +
"\nbasedir=`dirname \"$0\"`" +
"\n" +
"\ncase `uname` in" +
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;" +
"\nesac" +
"\n" +
"\nif [ -x \"$basedir//usr/bin/sh\" ]; then" +
"\n \"$basedir//usr/bin/sh\" \"$basedir/from.sh\" \"$@\"" +
"\n ret=$?" +
"\nelse " +
"\n /usr/bin/sh \"$basedir/from.sh\" \"$@\"" +
"\n ret=$?" +
"\nfi" +
"\nexit $ret" +
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\/usr/bin/sh.exe\" (\r" +
"\n \"%~dp0\\/usr/bin/sh.exe\" \"%~dp0\\from.sh\" %*\r" +
"\n) ELSE (\r" +
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n /usr/bin/sh \"%~dp0\\from.sh\" %*\r" +
"\n)")
t.end()
})
})
test('explicit shebang with args', function (t) {
var from = path.resolve(fixtures, 'from.sh.args')
var to = path.resolve(fixtures, 'sh.args.shim')
cmdShim(from, to, function(er) {
if (er)
throw er
console.error('%j', fs.readFileSync(to, 'utf8'))
console.error('%j', fs.readFileSync(to + '.cmd', 'utf8'))
t.equal(fs.readFileSync(to, 'utf8'),
"#!/bin/sh" +
"\nbasedir=`dirname \"$0\"`" +
"\n" +
"\ncase `uname` in" +
"\n *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;" +
"\nesac" +
"\n" +
"\nif [ -x \"$basedir//usr/bin/sh\" ]; then" +
"\n \"$basedir//usr/bin/sh\" -x \"$basedir/from.sh.args\" \"$@\"" +
"\n ret=$?" +
"\nelse " +
"\n /usr/bin/sh -x \"$basedir/from.sh.args\" \"$@\"" +
"\n ret=$?" +
"\nfi" +
"\nexit $ret" +
"\n")
t.equal(fs.readFileSync(to + '.cmd', 'utf8'),
"@IF EXIST \"%~dp0\\/usr/bin/sh.exe\" (\r" +
"\n \"%~dp0\\/usr/bin/sh.exe\" -x \"%~dp0\\from.sh.args\" %*\r" +
"\n) ELSE (\r" +
"\n @SETLOCAL\r"+
"\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r"+
"\n /usr/bin/sh -x \"%~dp0\\from.sh.args\" %*\r" +
"\n)")
t.end()
})
})
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
| mit |
Biont/Linak-Control | src/js/app.js | 1145 | import {Renderer as background} from "./util/ipcHandler";
import AppSettingsModel from "./backbone/Models/AppSettings";
import AppView from "./backbone/Views/AppView";
import ScheduleCollection from "./backbone/Collections/ScheduleCollection.js";
import ScheduleItem from "./backbone/Models/ScheduleItem";
class App {
init() {
this.listenToNotifications();
this.settings = new AppSettingsModel( {
id : 'mainApp',
heightOffset : 62.5,
maxHeight : 6449,
autoStart : false,
enableStatistics: true
} );
this.settings.fetch( {
success: () => {
appView.render();
}
} );
let schedule = new ScheduleCollection( [], {
model : ScheduleItem,
comparator: function( m ) {
return m.getTimeStamp();
}
} );
let appView = new AppView( {
el : '#main-app',
settings : this.settings,
collection: schedule
} );
schedule.fetch();
}
listenToNotifications() {
background.subscribe( 'subscribe-notifications', ( event, data ) => {
let notification = new Notification( 'Linak Control', {
body: data.message
} );
} );
}
}
module.exports = App;
| mit |
RachelWiens/minesweeper_website | tile.js | 1999 | /**
* Minesweeper board tile
* UNKNOWN : Tile has not been clicked so its contents is not known
* EMPTY : Tile is not a mine and is not a neighbour of any mines
* ONE - EIGHT : Tile is a neighbour of some number of mines. The number of mines is the value of the number
* MINE : Tile is a mine.
* FLAGGED : Tile is flagged as a suspected mine
* @author Rachel Wiens
*
*/
/**
* Constructor for Tile "class"
* @param: {number} n
*/
function Tile(n) {
this.number = n;
return this;
}
/**
* @enum {number}
*/
Tile.TileEnum = {
UNKNOWN: -1,
EMPTY: 0,
ONE: 1, TWO: 2 , THREE: 3, FOUR: 4, FIVE: 5, SIX: 6, SEVEN: 7, EIGHT: 8,
MINE: 9,
FLAGGED: 10
};
/**
* @enum {Tile}
*/
Tile.TileType = {
UNKNOWN: new Tile(Tile.TileEnum.UNKNOWN),
EMPTY: new Tile(Tile.TileEnum.EMPTY),
ONE: new Tile(Tile.TileEnum.ONE),
TWO: new Tile(Tile.TileEnum.TWO),
THREE: new Tile(Tile.TileEnum.THREE),
FOUR: new Tile(Tile.TileEnum.FOUR),
FIVE: new Tile(Tile.TileEnum.FIVE),
SIX: new Tile(Tile.TileEnum.SIX),
SEVEN: new Tile(Tile.TileEnum.SEVEN),
EIGHT: new Tile(Tile.TileEnum.EIGHT),
MINE: new Tile(Tile.TileEnum.MINE),
FLAGGED: new Tile(Tile.TileEnum.FLAGGED)
}
/**
* @param {number} n
* @return {Tile}
*/
Tile.getTile = function(n) {
if( n >= 0 && n <= 10 ) {
return new Tile(n);
}
return Tile.TileType.UNKNOWN;
}
/**
* @return {number}
*/
Tile.prototype.getNumber = function() {
return this.number;
}
/**
* @param {Tile}
* @return boolean
*/
Tile.prototype.equals = function(otherTile) {
return ( this.number == otherTile.getNumber() );
}
/**
* @return {string}
*/
Tile.prototype.toString = function() {
switch(this.number){
case Tile.TileEnum.UNKNOWN:
return " ";
case Tile.TileEnum.MINE:
return "*";
case Tile.TileEnum.FLAGGED:
return "X";
default:
return this.number.toString();
}
}
| mit |
26rahulsingh/attandence_mean.io | app/routes/leavedeny.server.routes.js | 242 | 'use strict';
module.exports = function(app) {
// Routing logic
// ...
var leavedeny = require('../../app/controllers/leavedeny.server.controller');
app.route('/leavedeny')
.post(leavedeny.delete);
//.post(leave.create);
}; | mit |
andres1537/ml-java | src/main/java/com/cgomez/search/lsh/hash/IHashFunction.java | 457 | /*
* Copyright (c) 2015 cgomez. All rights reserved.
*/
package com.cgomez.search.lsh.hash;
import java.io.Serializable;
/**
* The Interface HashFunction.
*
* @author <a href="mailto:andres1537@gmail.com">Carlos Gomez</a>
* @param <T> the generic type
* @since ml-java-1.0
*/
public interface IHashFunction<T> extends Serializable {
/**
* Hash.
*
* @param t the t
* @return the integer
*/
Integer hash(T t);
} | mit |
antonioalegria/esper-ext | src/frogfish/esper/ext/TrixAggregationFunction.java | 1807 | package frogfish.esper.ext;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.espertech.esper.epl.agg.AggregationSupport;
import com.espertech.esper.epl.agg.AggregationValidationContext;
public class TrixAggregationFunction extends AggregationSupport {
private int mDataWindowSize;
private int mSignalWindowSize;
private LinkedList<Double> mDataWindow;
private LinkedList<Double> mSignalWindow;
private double mEMA1;
private double mEMA2;
private double mEMA3;
private double mSignal;
public TrixAggregationFunction() { }
/* (non-Javadoc)
* @see com.espertech.esper.epl.agg.AggregationSupport#validate(com.espertech.esper.epl.agg.AggregationValidationContext)
*/
@Override
public void validate(AggregationValidationContext validationContext) {
if ((validationContext.getParameterTypes().length != 1) || (validationContext.getParameterTypes()[0] != String.class)) {
throw new IllegalArgumentException("Concat aggregation requires a single parameter of type String");
}
}
/* (non-Javadoc)
* @see com.espertech.esper.epl.agg.AggregationMethod#clear()
*/
@Override
public void clear() {
mDataWindow.clear();
mSignalWindow.clear();
}
@Override
public void enter(Object value) {
if (value != null) {
mDataWindow.addLast((Double) value);
mSignalWindow.addLast((Double) value);
}
if (mDataWindow.size() > mDataWindowSize) {
mDataWindow.removeFirst();
}
if (mSignalWindow.size() > mSignalWindowSize) {
mSignalWindow.removeFirst();
}
}
@Override
public Object getValue() {
// TODO Auto-generated method stub
return null;
}
@Override
public Class getValueType() {
return Double.TYPE;
}
@Override
public void leave(Object arg0) {
// TODO Auto-generated method stub
}
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/yui/3.0.0/datasource/datasource-local.js | 130 | version https://git-lfs.github.com/spec/v1
oid sha256:ab3a9ba97498cc1665b8a21cded0192ec053d263b1c7c8f3c0da8ee524c1c5d9
size 11096
| mit |
tehmaze-labs/pkidump | x500.go | 4803 | package main
import "encoding/asn1"
var attributeNameMap = map[string]string{
"0.9.2342.19200300.100.1.1": "user ID",
"0.9.2342.19200300.100.1.2": "address",
"0.9.2342.19200300.100.1.3": "mailbox",
"0.9.2342.19200300.100.1.4": "info",
"0.9.2342.19200300.100.1.5": "favourite drink",
"0.9.2342.19200300.100.1.6": "room number",
"0.9.2342.19200300.100.1.8": "user class",
"0.9.2342.19200300.100.1.9": "host",
"0.9.2342.19200300.100.1.10": "manager",
"0.9.2342.19200300.100.1.11": "document identifier",
"0.9.2342.19200300.100.1.12": "document title",
"0.9.2342.19200300.100.1.13": "document version",
"0.9.2342.19200300.100.1.14": "document author",
"0.9.2342.19200300.100.1.15": "document location",
"0.9.2342.19200300.100.1.25": "domain component",
"0.9.2342.19200300.100.1.26": "a record",
"0.9.2342.19200300.100.1.27": "md record",
"0.9.2342.19200300.100.1.28": "mx record",
"0.9.2342.19200300.100.1.29": "ns record",
"0.9.2342.19200300.100.1.30": "soa record",
"0.9.2342.19200300.100.1.31": "cname record",
"0.9.2342.19200300.100.1.42": "pager",
"0.9.2342.19200300.100.1.44": "uniqueidentifier",
"1.2.840.113549.1.9.1": "e-mail address",
"1.2.840.113549.1.9.2": "unstructured name",
"1.2.840.113549.1.9.3": "content type",
"1.2.840.113549.1.9.4": "message digest",
"1.2.840.113549.1.9.5": "signing time",
"1.2.840.113549.1.9.7": "challenge password",
"1.2.840.113549.1.9.8": "unstructured address",
"1.2.840.113549.1.9.13": "signing description",
"1.2.840.113549.1.9.14": "extension request",
"1.2.840.113549.1.9.15": "S/MIME capabilities",
"1.2.840.113549.1.9.16": "S/MIME object identifier registry",
"1.2.840.113549.1.9.20": "friendly name",
"1.2.840.113549.1.9.22": "cert types",
"2.5.4.0": "object class",
"2.5.4.1": "aliased entry",
"2.5.4.2": "knowldgeinformation",
"2.5.4.3": "common name",
"2.5.4.4": "surname",
"2.5.4.5": "serial number",
"2.5.4.6": "country",
"2.5.4.7": "locality",
"2.5.4.8": "state or province",
"2.5.4.9": "street address",
"2.5.4.10": "organization",
"2.5.4.11": "organizational unit",
"2.5.4.12": "title",
"2.5.4.13": "description",
"2.5.4.14": "search guide",
"2.5.4.15": "business category",
"2.5.4.16": "postal address",
"2.5.4.17": "postal code",
"2.5.4.18": "post office box",
"2.5.4.19": "physical delivery office name",
"2.5.4.20": "telephone number",
"2.5.4.21": "telex number",
"2.5.4.22": "teletex terminal identifier",
"2.5.4.23": "facsimile telephone number",
"2.5.4.24": "x121 address",
"2.5.4.25": "international ISDN number",
"2.5.4.26": "registered address",
"2.5.4.27": "destination indicator",
"2.5.4.28": "preferred delivery method",
"2.5.4.29": "presentation address",
"2.5.4.30": "supported application context",
"2.5.4.31": "member",
"2.5.4.32": "owner",
"2.5.4.33": "role occupant",
"2.5.4.34": "see also",
"2.5.4.35": "user password",
"2.5.4.36": "user certificate",
"2.5.4.37": "CA certificate",
"2.5.4.38": "authority revocation list",
"2.5.4.39": "certificate revocation list",
"2.5.4.40": "cross certificate pair",
"2.5.4.41": "name",
"2.5.4.42": "given name",
"2.5.4.43": "initials",
"2.5.4.44": "generation qualifier",
"2.5.4.45": "unique identifier",
"2.5.4.46": "DN qualifier",
"2.5.4.47": "enhanced search guide",
"2.5.4.48": "protocol information",
"2.5.4.49": "distinguished name",
"2.5.4.50": "unique member",
"2.5.4.51": "house identifier",
"2.5.4.52": "supported algorithms",
"2.5.4.53": "delta revocation list",
"2.5.4.58": "attribute certificate",
"2.5.4.65": "pseudonym",
}
func attributeName(oid asn1.ObjectIdentifier) string {
var name = oid.String()
if value, ok := attributeNameMap[name]; ok {
return value
}
return name
}
| mit |
bobril/bobril-m-icons | gen/generate.js | 4013 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var path = require("path");
var svgs = Object.create(null);
function humanize(str) {
var frags = str.split('_');
for (var i = 1; i < frags.length; i++) {
frags[i] = frags[i].charAt(0).toUpperCase() + frags[i].slice(1);
}
if (/^[0-9]/.test(frags[0]))
frags[0] = '_' + frags[0];
return frags.join('');
}
function svgCircle(cx, cy, r) {
return "M" + (cx - r).toString() + " " + cy.toString() + "A" + r.toString() + " " + r.toString() + " 0 1 0 " + (cx + r).toString() + " " + cy.toString()
+ "A" + r.toString() + " " + r.toString() + " 0 1 0 " + (cx - r).toString() + " " + cy.toString() + "Z";
}
function recursiveSearch(fspath, dir) {
var nest = fs.readdirSync(fspath);
nest.forEach(function (n) {
var mn = path.join(fspath, n);
var stats = fs.statSync(mn);
if (stats.isDirectory()) {
if (dir.length > 0 && dir[dir.length - 1] == "svg" && n == "design")
return;
dir.push(n);
recursiveSearch(mn, dir);
dir.pop();
return;
}
if (!stats.isFile())
return;
var match = /^ic_(.+)_24px.svg$/.exec(n);
if (!match)
return;
var niceName = humanize(dir[0] + "_" + match[1]);
var content = fs.readFileSync(mn, 'utf-8');
content = content.replace(/ fill="[^"]*"/g, "");
content = content.replace(/ fill-opacity=/g, " opacity=");
content = content.replace(/<svg[^>]*>/, "");
content = content.replace(/<\/svg>/, "");
content = content.replace(/<g>(.*)<\/g>/, "$1");
var svgPath = [];
while (content.length > 0) {
match = /^<path d=\"([^\"]+)\"\/>/g.exec(content);
if (match) {
svgPath.push(1, match[1]);
content = content.substr(match[0].length);
continue;
}
match = /^<path opacity=\"([^\"]+)\" d=\"([^\"]+)\"\/>/g.exec(content);
if (match) {
svgPath.push(parseFloat(match[1]), match[2]);
content = content.substr(match[0].length);
continue;
}
match = /^<path d=\"([^\"]+)\" opacity=\"([^\"]+)\"\/>/g.exec(content);
if (match) {
svgPath.push(parseFloat(match[2]), match[1]);
content = content.substr(match[0].length);
continue;
}
match = /^<circle cx=\"([^\"]+)\" cy=\"([^\"]+)\" r=\"([^\"]+)\"\/>/g.exec(content);
if (match) {
svgPath.push(1, svgCircle(parseFloat(match[1]), parseFloat(match[2]), parseFloat(match[3])));
content = content.substr(match[0].length);
continue;
}
console.log(mn);
console.log(content);
return;
}
for (var i = 2; i < svgPath.length; i += 2) {
if (svgPath[i - 2] == svgPath[i]) {
svgPath[i - 1] += svgPath[i + 1];
svgPath.splice(i, 2);
i -= 2;
}
}
if (svgPath.length === 2 && svgPath[0] === 1) {
svgs[niceName] = svgPath[1];
}
else {
svgs[niceName] = svgPath;
}
});
}
recursiveSearch("../node_modules/material-design-icons", []);
svgs["menuRight"] = "M10,17L15,12L10,7V17Z";
svgs["menuLeft"] = "M14,7L9,12L14,17V7Z";
var out = fs.readFileSync('begin.ts', 'utf-8');
var keys = Object.keys(svgs);
keys.sort();
for (var i = 0; i < keys.length; i++) {
out += 'export const ' + keys[i] + ' = f';
var svgPath = svgs[keys[i]];
if (typeof svgPath !== 'string') {
out += "2";
}
out += "(" + JSON.stringify(svgPath) + ");\n";
}
fs.writeFileSync('../index.ts', out);
| mit |
lynxtdc/bioscan | database/migrations/2015_02_11_215056_create_person_table.php | 774 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePersonTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('person', function(Blueprint $table)
{
$table->increments('id');
$table->enum('program', array('bioscanme', 'masonchairmassage'));
$table->string('firstname', 75);
$table->string('lastname', 100);
$table->string('email');
$table->string('phone', 25);
$table->string('company_name');
$table->integer('company_address');
$table->string('referral_source');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('person');
}
}
| mit |
radu-matei/mic-slack-integration | src/SlackIntegration.API/DAL/SlackDbContext.cs | 315 | using SlackIntegration.SlackLibrary;
using System.Data.Entity;
namespace SlackIntegration.DAL
{
public class SlackDbContext : DbContext
{
public SlackDbContext(string connectionString): base(connectionString)
{
}
public DbSet<SlackMessage> Messages { get; set; }
}
} | mit |
s3inlc/cineast-evaluator | inc/gamification/achievements/GamesInDayLevel3Achievement.class.php | 1319 | <?php
use DBA\Player;
/**
* Created by IntelliJ IDEA.
* User: sein
* Date: 25.04.17
* Time: 15:31
*/
class GamesInDayLevel3Achievement extends GameAchievement {
/**
* @return string
*/
function getAchievementName() {
return "Games per day Level 3";
}
function getIsHidden() {
return false;
}
/**
* @param $player Player
* @return bool
*/
function isReachedByPlayer($player) {
if ($player == null || $this->alreadyReached($player)) {
return false;
}
$count = $this->getMaxGamesInDay($player);
if ($count >= 20) {
return true;
}
return false;
}
/**
* @return string
*/
function getAchievementImage() {
return "success.png"; // TODO: add image
}
/**
* @return float
*/
function getMultiplicatorGain() {
return 1.05;
}
/**
* @return string
*/
function getIdentifier() {
return "gamesPerDayLevel3";
}
/**
* @return string
*/
function getDescription() {
return "Play 20 games during one day.<br>Gives 5% extra score";
}
/**
* @param $player Player
* @return int progress in %
*/
function getProgress($player) {
if ($player == null) {
return 0;
}
return floor(min(100, $this->getMaxGamesInDay($player) / 20 * 100));
}
} | mit |
yht-fand/cardone-platform-authority | consumer-bak/src/test/java/top/cardone/func/v1/authority/role/D0002FuncTest.java | 3243 | package top.cardone.func.v1.authority.role;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import top.cardone.CardoneConsumerApplication;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.CollectionUtils;
import top.cardone.context.ApplicationContextHolder;
import java.util.Map;
@Log4j2
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = CardoneConsumerApplication.class, value = {"spring.profiles.active=test"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class D0002FuncTest {
@Value("http://localhost:${server.port:8765}${server.servlet.context-path:}/v1/authority/role/d0002.json")
private String funcUrl;
@Value("file:src/test/resources/top/cardone/func/v1/authority/role/D0002FuncTest.func.input.json")
private Resource funcInputResource;
@Value("file:src/test/resources/top/cardone/func/v1/authority/role/D0002FuncTest.func.output.json")
private Resource funcOutputResource;
@Test
public void func() throws Exception {
if (!funcInputResource.exists()) {
FileUtils.write(funcInputResource.getFile(), "{}", Charsets.UTF_8);
}
val input = FileUtils.readFileToString(funcInputResource.getFile(), Charsets.UTF_8);
Map<String, Object> parametersMap = ApplicationContextHolder.getBean(Gson.class).fromJson(input, Map.class);
Assert.assertFalse("输入未配置", CollectionUtils.isEmpty(parametersMap));
Map<String, Object> output = Maps.newLinkedHashMap();
for (val parametersEntry : parametersMap.entrySet()) {
val body = ApplicationContextHolder.getBean(Gson.class).toJson(parametersEntry.getValue());
val headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.set("collectionStationCodeForToken", parametersEntry.getKey().split(":")[0]);
headers.set("token", ApplicationContextHolder.getBean(org.apache.shiro.authc.credential.PasswordService.class).encryptPassword(headers.get("collectionStationCodeForToken").get(0)));
val httpEntity = new HttpEntity<>(body, headers);
val json = new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class);
val value = ApplicationContextHolder.getBean(Gson.class).fromJson(json, Map.class);
output.put(parametersEntry.getKey(), value);
}
FileUtils.write(funcOutputResource.getFile(), ApplicationContextHolder.getBean(Gson.class).toJson(output), Charsets.UTF_8);
}
} | mit |