code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Test\Block\Product;
use Magento\ConfigurableProduct\Test\Block\Product\View\ConfigurableOptions;
use Magento\ConfigurableProduct\Test\Fixture\ConfigurableProduct;
use Magento\Mtf\Fixture\FixtureInterface;
use Magento\Mtf\Fixture\InjectableFixture;
/**
* Class View
* Detail view block on frontend page
*/
class View extends \Magento\Catalog\Test\Block\Product\View
{
/**
* Get configurable options block
*
* @return ConfigurableOptions
*/
public function getConfigurableOptionsBlock()
{
return $this->blockFactory->create(
'Magento\ConfigurableProduct\Test\Block\Product\View\ConfigurableOptions',
['element' => $this->_rootElement]
);
}
/**
* Fill in the option specified for the product
*
* @param FixtureInterface $product
* @return void
*/
public function fillOptions(FixtureInterface $product)
{
/** @var ConfigurableProduct $product */
$attributesData = $product->getConfigurableAttributesData()['attributes_data'];
$checkoutData = $product->getCheckoutData();
// Prepare attribute data
foreach ($attributesData as $attributeKey => $attribute) {
$attributesData[$attributeKey] = [
'type' => $attribute['frontend_input'],
'title' => $attribute['label'],
'options' => [],
];
foreach ($attribute['options'] as $optionKey => $option) {
$attributesData[$attributeKey]['options'][$optionKey] = [
'title' => $option['label'],
];
}
$attributesData[$attributeKey]['options'] = array_values($attributesData[$attributeKey]['options']);
}
$attributesData = array_values($attributesData);
$configurableCheckoutData = isset($checkoutData['options']['configurable_options'])
? $checkoutData['options']['configurable_options']
: [];
$checkoutOptionsData = $this->prepareCheckoutData($attributesData, $configurableCheckoutData);
$this->getCustomOptionsBlock()->fillCustomOptions($checkoutOptionsData);
parent::fillOptions($product);
}
/**
* Return product options
*
* @param FixtureInterface $product [optional]
* @return array
*/
public function getOptions(FixtureInterface $product = null)
{
$options = [
'configurable_options' => $this->getConfigurableOptionsBlock()->getOptions($product),
'matrix' => $this->getConfigurableOptionsBlock()->getOptionsPrices($product)
];
$options += parent::getOptions($product);
return $options;
}
}
| enettolima/magento-training | magento2ce/dev/tests/functional/tests/app/Magento/ConfigurableProduct/Test/Block/Product/View.php | PHP | mit | 2,867 |
<?php
namespace Oro\Bundle\SegmentBundle\Tests\Unit\Filter;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\QueryBuilder;
use Oro\Bundle\EntityConfigBundle\Config\Config;
use Oro\Bundle\EntityConfigBundle\Config\Id\EntityConfigId;
use Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider;
use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope;
use Oro\Bundle\FilterBundle\Datasource\Orm\OrmFilterDatasourceAdapter;
use Oro\Bundle\FilterBundle\Filter\FilterUtility;
use Oro\Bundle\FilterBundle\Form\Type\Filter\ChoiceFilterType;
use Oro\Bundle\FilterBundle\Form\Type\Filter\EntityFilterType;
use Oro\Bundle\FilterBundle\Form\Type\Filter\FilterType;
use Oro\Bundle\QueryDesignerBundle\QueryDesigner\SubQueryLimitHelper;
use Oro\Bundle\SegmentBundle\Entity\Manager\SegmentManager;
use Oro\Bundle\SegmentBundle\Entity\Segment;
use Oro\Bundle\SegmentBundle\Entity\SegmentType;
use Oro\Bundle\SegmentBundle\Filter\SegmentFilter;
use Oro\Bundle\SegmentBundle\Provider\EntityNameProvider;
use Oro\Bundle\SegmentBundle\Query\DynamicSegmentQueryBuilder;
use Oro\Bundle\SegmentBundle\Query\SegmentQueryBuilderRegistry;
use Oro\Bundle\SegmentBundle\Query\StaticSegmentQueryBuilder;
use Oro\Bundle\SegmentBundle\Tests\Unit\Stub\Entity\CmsUser;
use Oro\Component\Testing\Unit\PreloadedExtension;
use Oro\Component\TestUtils\ORM\OrmTestCase;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\Forms;
class SegmentFilterTest extends OrmTestCase
{
const TEST_FIELD_NAME = 't1.id';
const TEST_PARAM_VALUE = '%test%';
/** @var \PHPUnit\Framework\MockObject\MockObject|FormFactoryInterface */
protected $formFactory;
/** @var \PHPUnit\Framework\MockObject\MockObject */
protected $doctrine;
/** @var DynamicSegmentQueryBuilder|\PHPUnit\Framework\MockObject\MockObject */
protected $dynamicSegmentQueryBuilder;
/** @var StaticSegmentQueryBuilder|\PHPUnit\Framework\MockObject\MockObject */
protected $staticSegmentQueryBuilder;
/** @var EntityNameProvider|\PHPUnit\Framework\MockObject\MockObject */
protected $entityNameProvider;
/** @var ConfigProvider|\PHPUnit\Framework\MockObject\MockObject */
protected $entityConfigProvider;
/** @var ConfigProvider|\PHPUnit\Framework\MockObject\MockObject */
protected $extendConfigProvider;
/** @var EntityManager|\PHPUnit\Framework\MockObject\MockObject */
protected $em;
/** @var SegmentFilter */
protected $filter;
/** @var SubQueryLimitHelper|\PHPUnit\Framework\MockObject\MockObject */
protected $subqueryLimitHelper;
protected function setUp()
{
$this->em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
->disableOriginalConstructor()->getMock();
$translator = $this->createMock('Symfony\Contracts\Translation\TranslatorInterface');
$translator->expects($this->any())->method('trans')->will($this->returnArgument(0));
$registry = $this->getMockForAbstractClass('Doctrine\Common\Persistence\ManagerRegistry', [], '', false);
$registry->expects($this->any())
->method('getManagerForClass')
->will($this->returnValue($this->em));
$this->formFactory = Forms::createFormFactoryBuilder()
->addExtensions(
[
new PreloadedExtension(
[
'oro_type_filter' => new FilterType($translator),
'oro_type_choice_filter' => new ChoiceFilterType($translator),
'entity' => new EntityType($registry),
'oro_type_entity_filter' => new EntityFilterType($translator),
],
[]
),
new CsrfExtension(
$this->createMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')
)
]
)
->getFormFactory();
$this->doctrine = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')
->disableOriginalConstructor()
->getMock();
$this->doctrine->expects($this->any())
->method('getManagerForClass')
->will($this->returnValue($this->em));
$this->em->expects($this->any())
->method('getClassMetadata')
->will($this->returnValue($this->getClassMetadata()));
$this->dynamicSegmentQueryBuilder = $this
->getMockBuilder('Oro\Bundle\SegmentBundle\Query\DynamicSegmentQueryBuilder')
->disableOriginalConstructor()->getMock();
$this->staticSegmentQueryBuilder = $this
->getMockBuilder('Oro\Bundle\SegmentBundle\Query\StaticSegmentQueryBuilder')
->disableOriginalConstructor()->getMock();
$this->entityNameProvider = $this->createMock('Oro\Bundle\SegmentBundle\Provider\EntityNameProvider');
$this->entityNameProvider
->expects($this->any())
->method('getEntityName')
->will($this->returnValue('Namespace\Entity'));
$this->entityConfigProvider = $this
->getMockBuilder('Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider')
->disableOriginalConstructor()->getMock();
$this->extendConfigProvider = $this
->getMockBuilder('Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider')
->disableOriginalConstructor()->getMock();
$configManager = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Config\ConfigManager')
->disableOriginalConstructor()
->getMock();
$this->entityConfigProvider->expects($this->any())
->method('getConfigManager')
->will($this->returnValue($configManager));
$configManager->expects($this->any())
->method('getEntityManager')
->will($this->returnValue($this->em));
$segmentQueryBuilderRegistry = new SegmentQueryBuilderRegistry();
$segmentQueryBuilderRegistry->addQueryBuilder('static', $this->staticSegmentQueryBuilder);
$segmentQueryBuilderRegistry->addQueryBuilder('dynamic', $this->dynamicSegmentQueryBuilder);
$this->subqueryLimitHelper = $this->createMock(SubQueryLimitHelper::class);
$segmentManager = new SegmentManager(
$this->em,
$segmentQueryBuilderRegistry,
$this->subqueryLimitHelper,
new ArrayCache()
);
$this->filter = new SegmentFilter(
$this->formFactory,
new FilterUtility(),
$this->doctrine,
$segmentManager,
$this->entityNameProvider,
$this->entityConfigProvider,
$this->extendConfigProvider
);
$this->filter->init('segment', ['entity' => '']);
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject
*/
protected function getClassMetadata()
{
$classMetaData = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')
->disableOriginalConstructor()
->getMock();
$classMetaData->expects($this->any())
->method('getName')
->will($this->returnValue('OroSegment:Segment'));
$classMetaData->expects($this->any())
->method('getIdentifier')
->will($this->returnValue(['id']));
$classMetaData->expects($this->any())
->method('getIdentifierFieldNames')
->will($this->returnValue(['id']));
$classMetaData->expects($this->any())
->method('getSingleIdentifierFieldName')
->will($this->returnValue('id'));
$classMetaData->expects($this->any())
->method('getTypeOfField')
->will($this->returnValue('integer'));
return $classMetaData;
}
protected function tearDown()
{
unset($this->formFactory, $this->dynamicSegmentQueryBuilder, $this->filter);
}
public function testGetMetadata()
{
$activeClassName = 'Oro\Bundle\SegmentBundle\Entity\Segment';
$newClassName = 'Test\NewEntity';
$deletedClassName = 'Test\DeletedEntity';
$entityConfigIds = [
new EntityConfigId('entity', $activeClassName),
new EntityConfigId('entity', $newClassName),
new EntityConfigId('entity', $deletedClassName),
];
$this->entityConfigProvider->expects($this->once())
->method('getIds')
->will($this->returnValue($entityConfigIds));
$this->extendConfigProvider->expects($this->any())
->method('getConfig')
->will(
$this->returnValueMap(
[
[
$activeClassName,
null,
$this->createExtendConfig($activeClassName, ExtendScope::STATE_ACTIVE)
],
[
$newClassName,
null,
$this->createExtendConfig($newClassName, ExtendScope::STATE_NEW)
],
[
$deletedClassName,
null,
$this->createExtendConfig($deletedClassName, ExtendScope::STATE_DELETE)
],
]
)
);
$this->prepareRepo();
$metadata = $this->filter->getMetadata();
$this->assertTrue(isset($metadata['entity_ids']));
$this->assertEquals(
[$activeClassName => 'id'],
$metadata['entity_ids']
);
}
/**
* @param string $className
* @param string $state
*
* @return Config
*/
protected function createExtendConfig($className, $state)
{
$configId = new EntityConfigId('extend', $className);
$config = new Config($configId);
$config->set('state', $state);
return $config;
}
protected function prepareRepo()
{
$query = $this->getMockBuilder('Doctrine\ORM\AbstractQuery')
->disableOriginalConstructor()
->setMethods(['execute', 'getSQL'])
->getMockForAbstractClass();
$query->expects($this->any())
->method('execute')
->will($this->returnValue([]));
$query->expects($this->any())
->method('getSQL')
->will($this->returnValue('SQL QUERY'));
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->disableOriginalConstructor()
->getMock();
$qb->expects($this->once())
->method('where')
->will($this->returnSelf());
$qb->expects($this->once())
->method('setParameter')
->will($this->returnSelf());
$qb->expects($this->any())
->method('getParameters')
->will($this->returnValue(new ArrayCollection()));
$qb->expects($this->any())
->method('getQuery')
->will($this->returnValue($query));
$repo = $this->getMockBuilder('Doctrine\ORM\EntityRepository')
->disableOriginalConstructor()
->getMock();
$repo->expects($this->once())
->method('createQueryBuilder')
->will($this->returnValue($qb));
$this->em->expects($this->any())
->method('getRepository')
->with($this->equalTo('OroSegmentBundle:Segment'))
->will($this->returnValue($repo));
}
public function testGetForm()
{
$this->prepareRepo();
$form = $this->filter->getForm();
$this->assertInstanceOf('Symfony\Component\Form\FormInterface', $form);
}
public function testApplyInvalidData()
{
$dsMock = $this->createMock('Oro\Bundle\FilterBundle\Datasource\FilterDatasourceAdapterInterface');
$result = $this->filter->apply($dsMock, [null]);
$this->assertFalse($result);
}
public function testStaticApply()
{
$staticSegmentStub = new Segment();
$staticSegmentStub->setType(new SegmentType(SegmentType::TYPE_STATIC));
$staticSegmentStub->setEntity('Oro\Bundle\SegmentBundle\Tests\Unit\Stub\Entity\CmsUser');
$filterData = ['value' => $staticSegmentStub];
$em = $this->getEM();
$qb = $em->createQueryBuilder()
->select(['t1.name'])
->from('OroSegmentBundle:CmsUser', 't1');
$queryBuilder = new QueryBuilder($em);
$queryBuilder->select(['ts1.id'])
->from('OroSegmentBundle:SegmentSnapshot', 'ts1')
->andWhere('ts1.segmentId = :segment')
->setParameter('segment', self::TEST_PARAM_VALUE);
$ds = new OrmFilterDatasourceAdapter($qb);
$this->staticSegmentQueryBuilder
->expects(static::once())
->method('getQueryBuilder')
->with($staticSegmentStub)
->will(static::returnValue($queryBuilder));
$this->filter->init('someName', [FilterUtility::DATA_NAME_KEY => self::TEST_FIELD_NAME]);
$this->filter->apply($ds, $filterData);
$expectedResult = [
'SELECT t1.name FROM OroSegmentBundle:CmsUser t1 WHERE',
't1.id IN(SELECT ts1.id FROM OroSegmentBundle:SegmentSnapshot ts1 WHERE ts1.segmentId = :segment)'
];
$expectedResult = implode(' ', $expectedResult);
static::assertEquals($expectedResult, $ds->getQueryBuilder()->getDQL());
$params = $ds->getQueryBuilder()->getParameters();
static::assertCount(1, $params, 'Should pass params to main query builder');
static::assertEquals(self::TEST_PARAM_VALUE, $params[0]->getValue());
}
/**
* @return \Oro\Component\TestUtils\ORM\Mocks\EntityManagerMock
*/
protected function getEM()
{
$reader = new AnnotationReader();
$metadataDriver = new AnnotationDriver(
$reader,
'Oro\Bundle\SegmentBundle\Tests\Unit\Stub\Entity'
);
$em = $this->getTestEntityManager();
$em->getConfiguration()->setMetadataDriverImpl($metadataDriver);
$em->getConfiguration()->setEntityNamespaces(
[
'OroSegmentBundle' => 'Oro\Bundle\SegmentBundle\Tests\Unit\Stub\Entity'
]
);
return $em;
}
public function testDynamicApplyWithoutLimit()
{
$dynamicSegment = (new Segment())
->setType(new SegmentType(SegmentType::TYPE_DYNAMIC))
->setEntity(CmsUser::class);
$filterData = ['value' => $dynamicSegment];
$em = $this->getEM();
$qb = $em->createQueryBuilder()
->select(['t1.name'])
->from('OroSegmentBundle:CmsUser', 't1');
$queryBuilder = new QueryBuilder($em);
$queryBuilder->select(['ts1.id'])
->from('OroSegmentBundle:SegmentSnapshot', 'ts1')
->andWhere('ts1.segmentId = :segment')
->setParameter('segment', self::TEST_PARAM_VALUE);
$ds = new OrmFilterDatasourceAdapter($qb);
$this->dynamicSegmentQueryBuilder
->expects(static::once())
->method('getQueryBuilder')
->with($dynamicSegment)
->will(static::returnValue($queryBuilder));
$this->filter->init('someName', [FilterUtility::DATA_NAME_KEY => self::TEST_FIELD_NAME]);
$this->filter->apply($ds, $filterData);
$expectedResult = [
'SELECT t1.name FROM OroSegmentBundle:CmsUser t1 WHERE',
't1.id IN(SELECT ts1.id FROM OroSegmentBundle:SegmentSnapshot ts1 WHERE ts1.segmentId = :segment)'
];
$expectedResult = implode(' ', $expectedResult);
static::assertEquals($expectedResult, $ds->getQueryBuilder()->getDQL());
$params = $ds->getQueryBuilder()->getParameters();
static::assertCount(1, $params, 'Should pass params to main query builder');
static::assertEquals(self::TEST_PARAM_VALUE, $params[0]->getValue());
}
public function testDynamicApplyWithLimit()
{
$dynamicSegment = (new Segment())
->setType(new SegmentType(SegmentType::TYPE_DYNAMIC))
->setEntity(CmsUser::class)
->setRecordsLimit(10);
$filterData = ['value' => $dynamicSegment];
$em = $this->getEM();
$qb = $em->createQueryBuilder()
->select(['t1.name'])
->from('OroSegmentBundle:CmsUser', 't1');
$queryBuilder = new QueryBuilder($em);
$queryBuilder->select(['ts1.id'])
->from('OroSegmentBundle:SegmentSnapshot', 'ts1')
->andWhere('ts1.segmentId = :segment')
->setParameter('segment', self::TEST_PARAM_VALUE);
$ds = new OrmFilterDatasourceAdapter($qb);
$this->dynamicSegmentQueryBuilder
->expects(static::once())
->method('getQueryBuilder')
->with($dynamicSegment)
->will(static::returnValue($queryBuilder));
$this->subqueryLimitHelper->expects($this->once())
->method('setLimit')
->with($queryBuilder, 10, 'id')
->willReturn($queryBuilder);
$this->filter->init('someName', [FilterUtility::DATA_NAME_KEY => self::TEST_FIELD_NAME]);
$this->filter->apply($ds, $filterData);
$expectedResult = [
'SELECT t1.name FROM OroSegmentBundle:CmsUser t1 WHERE',
't1.id IN(SELECT ts1.id FROM OroSegmentBundle:SegmentSnapshot ts1 WHERE ts1.segmentId = :segment)'
];
$expectedResult = implode(' ', $expectedResult);
static::assertEquals($expectedResult, $ds->getQueryBuilder()->getDQL());
$params = $ds->getQueryBuilder()->getParameters();
static::assertCount(1, $params, 'Should pass params to main query builder');
static::assertEquals(self::TEST_PARAM_VALUE, $params[0]->getValue());
}
}
| orocrm/platform | src/Oro/Bundle/SegmentBundle/Tests/Unit/Filter/SegmentFilterTest.php | PHP | mit | 18,418 |
<?php
namespace Milax\Mconsole\Models;
use Illuminate\Database\Eloquent\Model;
class Upload extends Model
{
use \HasTags;
protected $fillable = ['type', 'path', 'preset_id', 'filename', 'copies', 'related_id', 'related_class', 'group', 'order', 'unique', 'language_id', 'title', 'description', 'link'];
protected $casts = [
'copies' => 'array',
];
/**
* Relationship to MconsoleUploadPreset
*
* @return BelongsTo
*/
public function preset()
{
return $this->belongsTo('Milax\Mconsole\Models\MconsoleUploadPreset', 'preset_id');
}
/**
* Relationship to Language
*
* @return BelongsTo
*/
public function language()
{
return $this->belongsTo('Milax\Mconsole\Models\Language');
}
/**
* Get image url for given copy
*
* @param string $size
* @return string
*/
public function getImagePath($size = 'original')
{
return sprintf('/storage/uploads/%s/%s/%s', $this->path, $size, $this->filename);
}
/**
* Get document url for given copy
*
* @return string
*/
public function getDocumentPath()
{
return sprintf('/storage/uploads/%s/%s', $this->path, $this->filename);
}
/**
* Get original file path
*
* @return string
*/
public function getOriginalPath($size = 'original')
{
switch ($this->type) {
case 'image':
return $this->getImagePath($size);
default:
return $this->getDocumentPath();
}
}
/**
* Undocumented function
*
* @param boolean $includeOriginal [Include original file path]
* @return void
*/
public function getCopies($includeOriginal = false)
{
$copies = [];
foreach ($this->copies as $copy) {
$copies[$copy['path']] = $this->getImagePath($copy['path']);
}
if ($includeOriginal) {
$copies['original'] = $this->getOriginalPath();
}
return $copies;
}
// @TODO: REMOVE THIS METHOD
public function getImageCopies()
{
throw new \Milax\Mconsole\Exceptions\DeprecatedException('Upload getImageCopies is deprecated, use getCopies() instead');
}
/**
* Automatically delete related data
*
* @return void
*/
public static function boot()
{
parent::boot();
static::deleting(function ($file) {
if (\File::exists(sprintf('%s/%s/%s', MX_UPLOADS_PATH, $file->path, $file->filename))) {
\File::delete(sprintf('%s/%s/%s', MX_UPLOADS_PATH, $file->path, $file->filename));
}
if (\File::exists(sprintf('%s/%s/original/%s', MX_UPLOADS_PATH, $file->path, $file->filename))) {
\File::delete(sprintf('%s/%s/original/%s', MX_UPLOADS_PATH, $file->path, $file->filename));
}
if (\File::exists(sprintf('%s/%s/mconsole/%s', MX_UPLOADS_PATH, $file->path, $file->filename))) {
\File::delete(sprintf('%s/%s/mconsole/%s', MX_UPLOADS_PATH, $file->path, $file->filename));
}
if ($file->copies && count($file->copies) > 0) {
foreach ($file->copies as $copy) {
if (\File::exists(sprintf('%s/%s/%s/%s', MX_UPLOADS_PATH, $file->path, $copy['path'], $file->filename))) {
\File::delete(sprintf('%s/%s/%s/%s', MX_UPLOADS_PATH, $file->path, $copy['path'], $file->filename));
}
}
}
});
}
}
| misterpaladin/mconsole | src/Milax/Mconsole/Models/Upload.php | PHP | mit | 3,675 |
class Station < ActiveRecord::Base
belongs_to :forecast
# validates :pws_id, uniqueness: true
end
| jackzampolin/my_weather_map | app/models/station.rb | Ruby | mit | 102 |
package com.ngll_prototype;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.ngll_prototype.object.IMGCoordinate;
import com.searchly.jestdroid.DroidClientConfig;
import com.searchly.jestdroid.JestClientFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
CustomDrawableView cd;
private ImageView image;
private ImageView imageView;
private int ImgInfo[];
private TextView tvMac;
private Button mbtnExe;
private Button mbtnStop;
ProgressDialog mProgressDialog;
DisaplyPoint disaplyPoint;
private Bitmap bitmapBG, bitmap;
private Canvas canvas;
private Paint paint;
private int StatusBarHeight, ActionBarHeight;
private JSONArray list;
private Matrix matrix;
private ArrayList<IMGCoordinate> IMGCoorlist = new ArrayList<>();
private boolean firstExe = true;
private static boolean goFlag;
String query = "{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"data.macAddr\" : {\n" +
" \"query\" : \"101a0a000024\",\n" +
" \"type\" : \"boolean\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }";
String query2 = "{\n"
+ " \"query\":{\n"
+ " \"match\":{\n"
+ " \"data\": {\n"
+ " \"macAddr\" : \"101a0a000024\" \n"
+ " }\n"
+ " }\n"
+ " }\n"
+ "}";
String query3 =
"{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"data.macAddr\" : {\n" +
" \"query\" : \"101a0a000024\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
tvMac = (TextView) findViewById(R.id.tvmac);
mbtnExe = (Button) findViewById(R.id.btnexe);
mbtnStop = (Button) findViewById(R.id.btnstop);
setTitle("NGLL Prototype");
Log.d(TAG, "---- Old Activity ----");
setup();
// Node node = nodeBuilder().node();
// Client client = node.client();
// try {
// Settings settings = Settings.settingsBuilder()
// .put("", "").build();
// TransportClient client = TransportClient.builder().settings(settings).build()
// .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("54.169.218.103"), 9200));
// Log.d(TAG, "client:\t" + client.toString());
// client.close();
//// GetRequestBuilder getRequestBuilder = client.prepareGet();
//// getRequestBuilder.setFields("");
//// GetResponse response = getRequestBuilder.execute().actionGet();
//// String name = response.getField("").getValue().toString();
//// Log.d(TAG, "name:\t" + name );
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
}
private void setup() {
// int count = 0;
mbtnExe.setOnClickListener(new View.OnClickListener() {
// int count = 0;
@Override
public void onClick(View view) {
// Log.d(TAG, "mbtnExe pressed");
// int indoorCo[] ={8, count};
// paint(indoorCo);
// count = count +1;
disaplyPoint = new DisaplyPoint();
disaplyPoint.execute("101a0a000024");
goFlag = true;
chgButtonST(mbtnExe, false);
}
});
mbtnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goFlag = false;
chgButtonST(mbtnExe, true);
}
});
tvMac.setText("101a0a000024");
}
private void init() {
// RelativeLayout layout = (RelativeLayout) findViewById(R.id.root);
// final DrawView view = new DrawView(this);
// view.setMinimumHeight(700);
// view.setMinimumWidth(1274);
//
// //通知view组件重绘
// view.invalidate();
// layout.addView(view);
}
private void chgButtonST(Button btn, boolean state) {
btn.setClickable(state);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d(TAG, "onWindowFocusChanged");
if (firstExe) {
firstExe = false;
ImgInfo = getImageStartCoordinate(image); //get Image top, left, Height, wight
Log.d(TAG, "ImgInfo Top:\t" + ImgInfo[0]);
Log.d(TAG, "ImgInfo Left:\t" + ImgInfo[1]);
Log.d(TAG, "ImgInfo Height:\t" + ImgInfo[2]);
Log.d(TAG, "ImgInfo Wight:\t" + ImgInfo[3]);
bitmapBG = BitmapFactory.decodeResource(getResources(), R.drawable.gemtek8b_block2);
Log.d(TAG, "bitmapBG.getHeight():\t" + bitmapBG.getHeight() + "\tbitmapBG.getWidth():\t" + bitmapBG.getWidth());
// View v = new MyCanvas(getApplicationContext());
bitmap = Bitmap.createBitmap(bitmapBG.getWidth()/*width*/, bitmapBG.getHeight()/*height*/, Bitmap.Config.ARGB_8888); //create a bitmap size same as bitmapBG
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
matrix = new Matrix();
canvas.drawBitmap(bitmapBG, matrix, paint);
// canvas.drawCircle(324, 330, 10, paint);
// canvas.drawCircle(324, 168, 10, paint);
// canvas.drawText("Sample Text", 10, 10, paint);
StatusBarHeight = getStatusBarHeight();
ActionBarHeight = getActionBarHeight();
Log.d(TAG, "StatusBarHeight:\t" + StatusBarHeight + "\tActionBarHeight:\t" + ActionBarHeight);
image.setImageBitmap(bitmap);
// canvas.save();
ImgCoordinateSet(ImgInfo);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG, "onTouchEvent....");
int x = (int) event.getX();//取x軸
int y = (int) event.getY();//取y軸
int action = event.getAction();//取整數
switch (action) {
case MotionEvent.ACTION_DOWN:
// setTitle("按下:" + x + "," + y);
break;
case MotionEvent.ACTION_MOVE:
// setTitle("平移:" + x + "," + y);
break;
case MotionEvent.ACTION_UP:
setTitle("彈起:" + x + "," + y);
break;
}
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Drawable drawable = imageView.getDrawable();
Rect imageBounds = drawable.getBounds();
int[] posXY = new int[2];
imageView.getLocationOnScreen(posXY);
//original height and width of the bitmap
int intrinsicHeight = drawable.getIntrinsicHeight();
int intrinsicWidth = drawable.getIntrinsicWidth();
//height and width of the visible (scaled) image
int scaledHeight = imageBounds.height();
int scaledWidth = imageBounds.width();
//Find the ratio of the original image to the scaled image
//Should normally be equal unless a disproportionate scaling
//(e.g. fitXY) is used.
float heightRatio = intrinsicHeight / scaledHeight;
float widthRatio = intrinsicWidth / scaledWidth;
//do whatever magic to get your touch point
//MotionEvent event;
//get the distance from the left and top of the image bounds
float scaledImageOffsetX = event.getX() - imageBounds.left;
float scaledImageOffsetY = event.getY() - imageBounds.top;
Log.d(TAG, "scaledImageOffsetX:\n" + scaledImageOffsetX);
Log.d(TAG, "scaledImageOffsetY:\n" + scaledImageOffsetY);
//scale these distances according to the ratio of your scaling
//For example, if the original image is 1.5x the size of the scaled
//image, and your offset is (10, 20), your original image offset
//values should be (15, 30).
float originalImageOffsetX = scaledImageOffsetX * widthRatio;
float originalImageOffsetY = scaledImageOffsetY * heightRatio;
return super.onTouchEvent(event);
}
public class CustomDrawableView extends View {
private ShapeDrawable mDrawable;
private Paint mPaint;
private int x = 200;
private int y = 600;
private int width = 100;
private int height = 50;
public CustomDrawableView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.setBounds(x, y, x + width, y + height);
mPaint = mDrawable.getPaint();
mPaint.setColor(Color.BLUE);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
mDrawable.draw(canvas);
}
}
public static int[] getBitmapPositionInsideImageView(ImageView imageView) {
int[] ret = new int[4];
if (imageView == null || imageView.getDrawable() == null)
return ret;
// Get image dimensions
// Get image matrix values and place them in an array
float[] f = new float[9];
imageView.getImageMatrix().getValues(f);
// for(int i =0; i < f.length; i++){
// Log.d(TAG, "f:" + f[i]);
// }
// Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
final float scaleX = f[Matrix.MSCALE_X];
final float scaleY = f[Matrix.MSCALE_Y];
// Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
final Drawable d = imageView.getDrawable();
final int origW = d.getIntrinsicWidth();
final int origH = d.getIntrinsicHeight();
// Calculate the actual dimensions
final int actW = Math.round(origW * scaleX);
final int actH = Math.round(origH * scaleY);
ret[2] = actW;
ret[3] = actH;
// Get image position
// We assume that the image is centered into ImageView
int imgViewW = imageView.getWidth();
int imgViewH = imageView.getHeight();
Log.d(TAG, "origW:\t" + origW + "\norigH:\t" + origH);
Log.d(TAG, "actW:\t" + actW + "\nactH:\t" + actH);
Log.d(TAG, "imgViewW:\t" + imgViewW + "\nimgViewH:\t" + imgViewH);
int top = (int) (imgViewH - actH) / 2;
int left = (int) (imgViewW - actW) / 2;
ret[0] = left;
ret[1] = top;
return ret;
}
public int[] getImageStartCoordinate(ImageView image) {
int[] intXY = new int[2];
// ImageView image = (ImageView)findViewById(R.id.imageView);
Drawable drawable = image.getDrawable();
Rect imageBounds = drawable.getBounds();
image.getLocationOnScreen(intXY);
// imageView.getLocationInWindow(intXY);
final int origW = drawable.getIntrinsicWidth();
final int origH = drawable.getIntrinsicHeight();
// drawable.get
final int[] ret = new int[4];
//intXY[0] = x, [1] = y, start top & left
ret[0] = intXY[0];
ret[1] = intXY[1];
ret[2] = origH;
ret[3] = origW;
return ret;
}
/*
* calculation pic's coordinate with number save by Json
*/
public void ImgCoordinateSet(int[] ImgInfo) {
IMGCoordinate icl;
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
list = new JSONArray();
int toScaleH = 5;
int toScaleW = 6;
int spacingH = ImgInfo[2] / toScaleH;
int spacingW = ImgInfo[3] / toScaleW;
Log.d(TAG, "spacingH:\t" + spacingH + "\tspacingW:\t" + spacingW);
// int x = ImgInfo[0];
// int y = ImgInfo[1];
int x = 0;
int y = 0;
int count = 0;
Log.d(TAG, "Start x:\t" + x + "\ty:\t" + y);
for (int i = 1; i < toScaleH; i++) {
// x = ImgInfo[0];
x = 0;
y = y + spacingH;
for (int j = 1; j < toScaleW; j++) {
try {
x = x + spacingW;
obj.put("x", x);
obj.put("y", y);
obj2.put(Integer.toString(count), obj);
// Log.d(TAG, "No." + count +"\tX:\t" + x + "\tY:\t" + y);
// Log.d(TAG, "obj2:\t" + obj2.toString());
// canvas.drawCircle(x, y -StatusBarHeight - ActionBarHeight, 5, paint);
canvas.drawCircle(x, y, 5, paint);
list.put(obj2);
obj = new JSONObject();
obj2 = new JSONObject();
icl = new IMGCoordinate(count, x, y);
IMGCoorlist.add(icl);
count = count + 1;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Log.d(TAG, "IMGCoorlist.length:\t" + IMGCoorlist.size());
for (int i = 0; i < IMGCoorlist.size(); i++) {
Log.d(TAG, "I:\t" + i + "\tcount:\t" + IMGCoorlist.get(i).getNumber() + "\tX:\t" + IMGCoorlist.get(i).getX()
+ "\tY:\t" + IMGCoorlist.get(i).getY());
}
}
class DisaplyPoint extends AsyncTask<String, Integer, int[]> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// blockUI(getString(R.string.loading));
}
@Override
protected int[] doInBackground(String... strings) {
int coordinate[];
while (goFlag) {
try {
JestClientFactory factory = new JestClientFactory();
factory.setDroidClientConfig(new DroidClientConfig.Builder(getString(R.string.elasticsvr))
.multiThreaded(true)
.build());
JestClient client = factory.getObject();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.sort("@timestamp", SortOrder.DESC);
searchSourceBuilder.size(50);
searchSourceBuilder.query(QueryBuilders.matchQuery("data.macAddr", strings[0])); // generate DSL format
// newer search rule, desc find latest data & GPS_N not 0
SearchSourceBuilder searchSourceBuilderTry = new SearchSourceBuilder();
searchSourceBuilderTry.sort("@timestamp", SortOrder.DESC);
searchSourceBuilderTry.size(1);
searchSourceBuilderTry.query(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("data.macAddr", strings[0])).mustNot(QueryBuilders.termQuery("data.GPS_N", "0")));
Search search = new Search.Builder(searchSourceBuilderTry.toString()).addIndex("client_report").addType("asset_tracker").build();
SearchResult searchResult = client.execute(search);
// Log.d(TAG, "searchSourceBuilder:\t" + searchSourceBuilder.toString());
// Log.d(TAG, "Total:\t" + searchResult.getTotal());
// Log.d(TAG, "searchResult:\t" + searchResult.getJsonString());
IndoorLocation indoorLocation = new IndoorLocation();
coordinate = indoorLocation.getPositionNum(searchResult.getJsonObject());
//get specific document
// Get get = new Get.Builder("client_report", "AVe2_o5uJozORed8MBm_").type("asset_tracker").build();
// JestResult result = client.execute(get);
// Log.d(TAG, "Getting Document:\t" + result.getJsonString());
if (coordinate != null) {
publishProgress(coordinate[1]);
}
client.shutdownClient();
Thread.sleep(5000);
} catch (UnknownError e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
paint(values[0]);
}
@Override
protected void onPostExecute(int result[]) {
super.onPostExecute(result);
// Log.d(TAG, "result[]:\t" + result[0] + "\t, " + result[1] );
// paint(result[1]);
// blockUI(null);
}
}
public void paint(int anchorNUM) {
if (anchorNUM + 1 > IMGCoorlist.size()) {
return;
}
canvas.drawBitmap(bitmapBG, matrix, paint); // clear screen
int x = IMGCoorlist.get(anchorNUM).getX();
// int y = IMGCoorlist.get(coordinate[1]).getY() - StatusBarHeight - ActionBarHeight;
int y = IMGCoorlist.get(anchorNUM).getY();
// Log.d(TAG,"paint, input para coordinate[] :\t" + "\t[0]:\t" + coordinate[0] + "\t[1]:\t" + coordinate[1]);
Log.d(TAG, "paint, x:\t" + x);
Log.d(TAG, "paint, y:\t" + y);
canvas.drawCircle(x, y, 7, paint);
image.invalidate();
}
/*
* get Status bar Height
*/
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/*
* get Action bar Height
*/
public int getActionBarHeight() {
int result = 0;
// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
result = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
}
return result;
}
private void blockUI(final String message) {
if (message != null) {
mProgressDialog = ProgressDialog.show(this, "", message, true);
mProgressDialog.show();
} else {
mProgressDialog.dismiss();
}
}
} | GIOT-POC/NGLL-APP | app/src/main/java/com/ngll_prototype/MainActivity.java | Java | mit | 20,066 |
#region File Header
// The MIT License (MIT)
//
// Copyright (c) 2016 Stefan Stolz
//
// 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.
#endregion
#region using directives
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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("EmbeddedData")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EmbeddedData")]
[assembly: AssemblyCopyright("")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0")]
[assembly: AssemblyFileVersion("1.3.0")]
| StefanStolz/EmbeddedDataVisualStudioExtension | EmbeddedData/EmbeddedData/Properties/AssemblyInfo.cs | C# | mit | 2,427 |
import asyncio
import signal
import configargparse
from structlog import get_logger
from alarme import Application
from alarme.scripts.common import init_logging, uncaught_exception, loop_uncaught_exception
def exit_handler(app, logger, sig):
logger.info('application_signal', name=sig.name, value=sig.value)
app.stop()
def run(config_path, log,
core_application_factory=Application,
):
# Logging init
logger = get_logger()
loop = asyncio.get_event_loop()
init_logging(log, 'server')
loop.set_exception_handler(loop_uncaught_exception)
# Core init
logger.info('application_init')
core_app = core_application_factory(exception_handler=uncaught_exception)
loop.run_until_complete(core_app.load_config(config_path))
for signal_code in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(signal_code, exit_handler, core_app, logger, signal_code)
loop.run_until_complete(core_app.run())
loop.close()
def main():
parser = configargparse.ArgParser(description='Alarm system software for Raspberry Pi')
parser.add_argument('-gc', '--generic-config', is_config_file=True, help='Generic config')
parser.add_argument('-c', '--config', help='Config directory')
parser.add_argument('-l', '--log', type=str, default='/var/log/alarme', help='Logs dir')
args = parser.parse_args()
run(args.config, args.log)
if __name__ == '__main__':
main()
| insolite/alarme | alarme/scripts/server.py | Python | mit | 1,452 |
"""
Last: 5069
Script with simple UI for creating gaplines data
Run: python WordClassDM.py --index 0
Controls:
setting gaplines - click and drag
saving gaplines - 's' key
reseting gaplines - 'r' key
skip to next img - 'n' key
delete last line - 'd' key
"""
import cv2
import os
import numpy as np
import glob
import argparse
import simplejson
from ocr.normalization import imageNorm
from ocr.viz import printProgressBar
def loadImages(dataloc, idx=0, num=None):
""" Load images and labels """
print("Loading words...")
# Load images and short them from the oldest to the newest
imglist = glob.glob(os.path.join(dataloc, u'*.jpg'))
imglist.sort(key=lambda x: float(x.split("_")[-1][:-4]))
tmpLabels = [name[len(dataloc):] for name in imglist]
labels = np.array(tmpLabels)
images = np.empty(len(imglist), dtype=object)
if num is None:
upper = len(imglist)
else:
upper = min(idx + num, len(imglist))
num += idx
for i, img in enumerate(imglist):
# TODO Speed up loading - Normalization
if i >= idx and i < upper:
images[i] = imageNorm(
cv2.cvtColor(cv2.imread(img), cv2.COLOR_BGR2RGB),
height=60,
border=False,
tilt=True,
hystNorm=True)
printProgressBar(i-idx, upper-idx-1)
print()
return (images[idx:num], labels[idx:num])
def locCheck(loc):
return loc + '/' if loc[-1] != '/' else loc
class Cycler:
drawing = False
scaleF = 4
def __init__(self, idx, data_loc, save_loc):
""" Load images and starts from given index """
# self.images, self.labels = loadImages(loc, idx)
# Create save_loc directory if not exists
if not os.path.exists(save_loc):
os.makedirs(save_loc)
self.data_loc = locCheck(data_loc)
self.save_loc = locCheck(save_loc)
self.idx = 0
self.org_idx = idx
self.blockLoad()
self.image_act = self.images[self.idx]
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.mouseHandler)
self.nextImage()
self.run()
def run(self):
while(1):
self.imageShow()
k = cv2.waitKey(1) & 0xFF
if k == ord('d'):
# Delete last line
self.deleteLastLine()
elif k == ord('r'):
# Clear current gaplines
self.nextImage()
elif k == ord('s'):
# Save gaplines with image
if self.saveData():
self.idx += 1
if self.idx >= len(self.images):
if not self.blockLoad():
break
self.nextImage()
elif k == ord('n'):
# Skip to next image
self.idx += 1
if self.idx >= len(self.images):
if not self.blockLoad():
break
self.nextImage()
elif k == 27:
cv2.destroyAllWindows()
break
print("End of labeling at INDEX: " + str(self.org_idx + self.idx))
def blockLoad(self):
self.images, self.labels = loadImages(
self.data_loc, self.org_idx + self.idx, 100)
self.org_idx += self.idx
self.idx = 0
return len(self.images) is not 0
def imageShow(self):
cv2.imshow(
'image',
cv2.resize(
self.image_act,
(0,0),
fx=self.scaleF,
fy=self.scaleF,
interpolation=cv2.INTERSECT_NONE))
def nextImage(self):
self.image_act = cv2.cvtColor(self.images[self.idx], cv2.COLOR_GRAY2RGB)
self.label_act = self.labels[self.idx][:-4]
self.gaplines = [0, self.image_act.shape[1]]
self.redrawLines()
print(self.org_idx + self.idx, ":", self.label_act.split("_")[0])
self.imageShow();
def saveData(self):
self.gaplines.sort()
print("Saving image with gaplines: ", self.gaplines)
try:
assert len(self.gaplines) - 1 == len(self.label_act.split("_")[0])
cv2.imwrite(
self.save_loc + '%s.jpg' % (self.label_act),
self.images[self.idx])
with open(self.save_loc + '%s.txt' % (self.label_act), 'w') as fp:
simplejson.dump(self.gaplines, fp)
return True
except:
print("Wront number of gaplines")
return False
print()
self.nextImage()
def deleteLastLine(self):
if len(self.gaplines) > 0:
del self.gaplines[-1]
self.redrawLines()
def redrawLines(self):
self.image_act = cv2.cvtColor(self.images[self.idx], cv2.COLOR_GRAY2RGB)
for x in self.gaplines:
self.drawLine(x)
def drawLine(self, x):
cv2.line(
self.image_act, (x, 0), (x, self.image_act.shape[0]), (0,255,0), 1)
def mouseHandler(self, event, x, y, flags, param):
# Clip x into image width range
x = max(min(self.image_act.shape[1], x // self.scaleF), 0)
if event == cv2.EVENT_LBUTTONDOWN:
self.drawing = True
self.tmp = self.image_act.copy()
self.drawLine(x)
elif event == cv2.EVENT_MOUSEMOVE:
if self.drawing == True:
self.image_act = self.tmp.copy()
self.drawLine(x)
elif event == cv2.EVENT_LBUTTONUP:
self.drawing = False
if x not in self.gaplines:
self.gaplines.append(x)
self.image_act = self.tmp.copy()
self.drawLine(x)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
"Script creating UI for gaplines classification")
parser.add_argument(
"--index",
type=int,
default=0,
help="Index of starting image")
parser.add_argument(
"--data",
type=str,
default='data/words_raw',
help="Path to folder with images")
parser.add_argument(
"--save",
type=str,
default='data/words2',
help="Path to folder for saving images with gaplines")
args = parser.parse_args()
Cycler(args.index, args.data, args.save)
| Breta01/handwriting-ocr | src/data/data_creation/WordClassDM.py | Python | mit | 6,492 |
class FixColumnVerificationTypeVerifications < ActiveRecord::Migration
def self.up
change_column :verifications, :verification_type, "enum('idchecker', 'directid', 'netverify', 'authenticid')"
end
def self.down
end
end
| malahinisolutions/verify | db/migrate/20151008092718_fix_column_verification_type_verifications.rb | Ruby | mit | 232 |
package tilat;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import hallinta.Grafiikka;
import hallinta.Hiiri;
import hallinta.Musiikki;
import hallinta.Nappaimisto;
import hallinta.PeliAlue;
import hallinta.PeliOhi;
import hallinta.PeliPaussi;
import main.IkkunaPaneeli;
/**Luokka, joka hoitaa itse pelin hallinnan
* Perustuu kolmen eri luokan ilmentymiin
* Nämä ovat {@link PeliAlue}, {@link PeliOhi} ja {@link PeliPaussi}
* @author Juho Kuusinen
*
*/
public class Peli extends Pelitila{
private PeliAlue peli;
private PeliOhi peliOhi;
private PeliPaussi peliPaussi;
private boolean peliOhiAlustettu;
private Pelintilanhallitsija gm;
private boolean paussi;
/**
* Luodaan uusi Peli-luokan ilmentymä parametrina annetun {@link Pelintilanhallitsija}-luokan ilmentymän mukaan
* @param gm {@link Pelintilanhallitsija}
*/
public Peli(Pelintilanhallitsija gm){
alusta();
this.gm = gm;
}
@Override
public void alusta() {
paussi = false;
peli = new PeliAlue(0, 0, IkkunaPaneeli.LEVEYS, IkkunaPaneeli.KORKEUS,Grafiikka.annaKuva(Grafiikka.TAUSTA));
peliOhi = new PeliOhi(0, 0, IkkunaPaneeli.LEVEYS, IkkunaPaneeli.KORKEUS, Grafiikka.annaKuva(Grafiikka.TAUSTA),Grafiikka.annaKuva(Grafiikka.PISTETAULULOGO));
peliPaussi = new PeliPaussi(0, 0, IkkunaPaneeli.LEVEYS, IkkunaPaneeli.KORKEUS, Grafiikka.annaKuva(Grafiikka.TAUSTA),Grafiikka.annaKuva(Grafiikka.PAUSSI), gm);
peliPaussi.alusta();
}
@Override
public void paivita() {
kasitteleSyote();
if(peli.onkoElossa()){
if(paussi){
peliPaussi.paivita();
}else{
peli.paivita();
}
}else if(!peli.onkoElossa()){
if(!peliOhiAlustettu){
peliOhi.alusta(peli.annaPisteet());
peliOhiAlustettu = true;
}
peliOhi.paivita();
}else{
System.out.println("KUINKAS NÄIN KÄVI...");
}
Musiikki.toistaAudiotListasta();
}
@Override
public void piirra(Graphics2D g) {
if(peli.onkoElossa()){
if(paussi){
peliPaussi.piirra(g);
}else{
peli.piirra(g);
}
}else if(!peli.onkoElossa()){
peliOhi.piirra(g);
}else{
System.out.println("KUINKAS NÄIN KÄVI...");
}
}
@Override
public void kasitteleSyote() {
if(Nappaimisto.annaPainettuNappi() == KeyEvent.VK_ESCAPE){
if(paussi){
paussi = false;
}else{
paussi = true;
peliPaussi.asetaHiiri(Hiiri.annaX(), Hiiri.annaY());
}
}
if(paussi && Hiiri.tapahtuma==1){
if(Hiiri.annaX() > IkkunaPaneeli.LEVEYS/2 - Grafiikka.annaKuva(Grafiikka.NAPPI).getWidth()/2 && Hiiri.annaX() < IkkunaPaneeli.LEVEYS/2 + Grafiikka.annaKuva(Grafiikka.NAPPI).getWidth()/2 ){
if(Hiiri.annaY() > 150+50 && Hiiri.annaY() < 150 + Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight() + 50){
paussi = false;
}
if(Hiiri.annaY() > 150+50 +Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight() && Hiiri.annaY() < 150 + Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight() * 2 + 50){
gm.asetaTila(Pelintilanhallitsija.PAAMENU);
}
if(Hiiri.annaY() > 150+50 +Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight()*2 && Hiiri.annaY() < 150 + Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight() * 3 + 50){
System.exit(0);
}
}
}
if(!peli.onkoElossa() && Hiiri.tapahtuma ==1){
if(Hiiri.annaX() > 50 && Hiiri.annaX() < 50 + Grafiikka.annaKuva(Grafiikka.NAPPI).getWidth() &&
Hiiri.annaY() > 50 && Hiiri.annaY() < 50 + Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight()){
gm.asetaTila(Pelintilanhallitsija.PAAMENU);
}
}
}
}
| Qurred/Bubble-Game | src/tilat/Peli.java | Java | mit | 3,583 |
<?php
/* SonataAdminBundle:CRUD:edit_sonata_type_immutable_array.html.twig */
class __TwigTemplate_4756e8c5a9c146a3fcb19b2bc6e739a2 extends Twig_Template
{
protected $parent;
public function getParent(array $context)
{
if (null === $this->parent) {
$this->parent = $this->getContext($context, 'base_template');
if (!$this->parent instanceof Twig_Template) {
$this->parent = $this->env->loadTemplate($this->parent);
}
}
return $this->parent;
}
protected function doDisplay(array $context, array $blocks = array())
{
$context = array_merge($this->env->getGlobals(), $context);
$this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
}
public function getTemplateName()
{
return "SonataAdminBundle:CRUD:edit_sonata_type_immutable_array.html.twig";
}
public function isTraitable()
{
return false;
}
}
| kohr/HRSymfony2 | app/cache/dev/twig/47/56/e8c5a9c146a3fcb19b2bc6e739a2.php | PHP | mit | 992 |
/**
* @author weism
* copyright 2015 Qcplay All Rights Reserved.
*/
qc.RoundedRectangle = Phaser.RoundedRectangle;
/**
* 类名
*/
Object.defineProperty(qc.RoundedRectangle.prototype, 'class', {
get : function() { return 'qc.RoundedRectangle'; }
});
/**
* 序列化
*/
qc.RoundedRectangle.prototype.toJson = function() {
return [this.x, this.y, this.width, this.height, this.radius];
}
/**
* 反序列化
*/
qc.RoundedRectangle.prototype.fromJson = function(v) {
this.x = v[0];
this.y = v[1];
this.width = v[2];
this.height = v[3];
this.radius = v[4];
}
| qiciengine/qiciengine-core | src/geom/RoundedRectangle.js | JavaScript | mit | 594 |
package zame.game.store.products;
public class ProductText extends Product {
public int purchasedTextResourceId;
public int purchasedImageResourceId;
public ProductText(
int id,
int dependsOnId,
int price,
int titleResourceId,
int descriptionResourceId,
int iconResourceId,
int imageResourceId,
int purchasedTextResourceId,
int purchasedImageResourceId
) {
super(id, dependsOnId, price, titleResourceId, descriptionResourceId, iconResourceId, imageResourceId);
this.purchasedTextResourceId = purchasedTextResourceId;
this.purchasedImageResourceId = purchasedImageResourceId;
}
}
| restorer/gloomy-dungeons-2 | src/main/java/zame/game/store/products/ProductText.java | Java | mit | 610 |
shared_examples_for type: :collection do |context|
let(:described_collection) { described_class.new(service: service) }
end
| cpb/opennorth-represent | spec/support/shared_examples/collection_spec.rb | Ruby | mit | 126 |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "treemap.hoverlabel"
_path_str = "treemap.hoverlabel.font"
_valid_props = {"color", "colorsrc", "family", "familysrc", "size", "sizesrc"}
# color
# -----
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
# colorsrc
# --------
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
# family
# ------
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
# familysrc
# ---------
@property
def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for family .
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"]
@familysrc.setter
def familysrc(self, val):
self["familysrc"] = val
# size
# ----
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
# sizesrc
# -------
@property
def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"]
@sizesrc.setter
def sizesrc(self, val):
self["sizesrc"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
"""
def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
size=None,
sizesrc=None,
**kwargs
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.treemap.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
Returns
-------
Font
"""
super(Font, self).__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.treemap.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.treemap.hoverlabel.Font`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("colorsrc", None)
_v = colorsrc if colorsrc is not None else _v
if _v is not None:
self["colorsrc"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("familysrc", None)
_v = familysrc if familysrc is not None else _v
if _v is not None:
self["familysrc"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
_v = arg.pop("sizesrc", None)
_v = sizesrc if sizesrc is not None else _v
if _v is not None:
self["sizesrc"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| plotly/python-api | packages/python/plotly/plotly/graph_objs/treemap/hoverlabel/_font.py | Python | mit | 11,209 |
package Test;
import LinkedList.*;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestSuite
{
@Test
public void addItems() {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Hello");
linkedList.add("Spaghetti");
linkedList.add("This is a sentence");
linkedList.add("Bleh");
assertEquals(linkedList.get(0), "Hello");
assertEquals(linkedList.get(1), "Spaghetti");
assertEquals(linkedList.get(2), "This is a sentence");
assertEquals(linkedList.get(3), "Bleh");
assertEquals(linkedList.get(4), null);
}
@Test
public void removeHead() {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Hello");
linkedList.add("Spaghetti");
linkedList.add("This is a sentence");
linkedList.add("Bleh");
linkedList.remove(0);
assertEquals(linkedList.get(0), "Spaghetti");
assertEquals(linkedList.get(1), "This is a sentence");
assertEquals(linkedList.get(2), "Bleh");
assertEquals(linkedList.get(3), null);
}
@Test
public void removeTail() {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Hello");
linkedList.add("Spaghetti");
linkedList.add("This is a sentence");
linkedList.add("Bleh");
linkedList.remove(3);
assertEquals(linkedList.get(0), "Hello");
assertEquals(linkedList.get(1), "Spaghetti");
assertEquals(linkedList.get(2), "This is a sentence");
assertEquals(linkedList.get(3), null);
}
@Test
public void removeInside() {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Hello");
linkedList.add("Spaghetti");
linkedList.add("This is a sentence");
linkedList.add("Bleh");
linkedList.remove(2);
assertEquals(linkedList.get(0),"Hello");
assertEquals(linkedList.get(1), "Spaghetti");
assertEquals(linkedList.get(2), "Bleh");
assertEquals(linkedList.get(3), null);
}
@Test
public void removeNonexistent() {
LinkedList<String> linkedList = new LinkedList<String>();
try {
linkedList.remove(4);
}
catch (Exception e) {
// Remove should silently fail
fail();
}
}
@Test
public void addItemsLength() {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Hello");
assertEquals(linkedList.length(), 1);
linkedList.add("Spaghetti");
assertEquals(linkedList.length(), 2);
linkedList.add("This is a sentence");
assertEquals(linkedList.length(), 3);
linkedList.add("Bleh");
assertEquals(linkedList.length(), 4);
}
@Test
public void removeItemsLength() {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Hello");
linkedList.add("Spaghetti");
linkedList.add("This is a sentence");
linkedList.add("Bleh");
linkedList.remove(3);
assertEquals(linkedList.length(), 3);
linkedList.remove(2);
assertEquals(linkedList.length(), 2);
linkedList.remove(1);
assertEquals(linkedList.length(), 1);
linkedList.remove(0);
assertEquals(linkedList.length(), 0);
}
@Test
public void getNonexistent() {
LinkedList<String> linkedList = new LinkedList<String>();
assertEquals(linkedList.get(4), null);
}
@Test
public void getFirst() {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Hello");
linkedList.add("Spaghetti");
linkedList.add("This is a sentence");
linkedList.add("Bleh");
assertEquals(linkedList.getFirst(), "Hello");
}
} | jaredpetersen/data-structures-and-algorithms | data_structures/linked_list/java/test/TestSuite.java | Java | mit | 3,391 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings
{
public partial class PreviewTests
{
[WpfFact]
public async Task TestExceptionInComputePreview()
{
using var workspace = CreateWorkspaceFromFile("class D {}", new TestParameters());
await GetPreview(workspace, new ErrorCases.ExceptionInCodeAction());
}
[WpfFact]
public void TestExceptionInDisplayText()
{
using var workspace = CreateWorkspaceFromFile("class D {}", new TestParameters());
DisplayText(workspace, new ErrorCases.ExceptionInCodeAction());
}
[WpfFact]
public async Task TestExceptionInActionSets()
{
using var workspace = CreateWorkspaceFromFile("class D {}", new TestParameters());
await ActionSets(workspace, new ErrorCases.ExceptionInCodeAction());
}
private static async Task GetPreview(TestWorkspace workspace, CodeRefactoringProvider provider)
{
var codeActions = new List<CodeAction>();
RefactoringSetup(workspace, provider, codeActions, out var extensionManager, out var textBuffer);
var suggestedAction = new CodeRefactoringSuggestedAction(
workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
workspace.ExportProvider.GetExportedValue<SuggestedActionsSourceProvider>(),
workspace, textBuffer, provider, codeActions.First());
await suggestedAction.GetPreviewAsync(CancellationToken.None);
Assert.True(extensionManager.IsDisabled(provider));
Assert.False(extensionManager.IsIgnored(provider));
}
private static void DisplayText(TestWorkspace workspace, CodeRefactoringProvider provider)
{
var codeActions = new List<CodeAction>();
RefactoringSetup(workspace, provider, codeActions, out var extensionManager, out var textBuffer);
var suggestedAction = new CodeRefactoringSuggestedAction(
workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
workspace.ExportProvider.GetExportedValue<SuggestedActionsSourceProvider>(),
workspace, textBuffer, provider, codeActions.First());
_ = suggestedAction.DisplayText;
Assert.True(extensionManager.IsDisabled(provider));
Assert.False(extensionManager.IsIgnored(provider));
}
private static async Task ActionSets(TestWorkspace workspace, CodeRefactoringProvider provider)
{
var codeActions = new List<CodeAction>();
RefactoringSetup(workspace, provider, codeActions, out var extensionManager, out var textBuffer);
var suggestedAction = new CodeRefactoringSuggestedAction(
workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
workspace.ExportProvider.GetExportedValue<SuggestedActionsSourceProvider>(),
workspace, textBuffer, provider, codeActions.First());
_ = await suggestedAction.GetActionSetsAsync(CancellationToken.None);
Assert.True(extensionManager.IsDisabled(provider));
Assert.False(extensionManager.IsIgnored(provider));
}
private static void RefactoringSetup(
TestWorkspace workspace, CodeRefactoringProvider provider, List<CodeAction> codeActions,
out EditorLayerExtensionManager.ExtensionManager extensionManager,
out VisualStudio.Text.ITextBuffer textBuffer)
{
var document = GetDocument(workspace);
textBuffer = workspace.GetTestDocument(document.Id).GetTextBuffer();
var span = document.GetSyntaxRootAsync().Result.Span;
var context = new CodeRefactoringContext(document, span, (a) => codeActions.Add(a), CancellationToken.None);
provider.ComputeRefactoringsAsync(context).Wait();
var action = codeActions.Single();
extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager;
}
}
}
| diryboy/roslyn | src/EditorFeatures/CSharpTest/CodeActions/Preview/PreviewExceptionTests.cs | C# | mit | 4,931 |
<?php
namespace Oro\Bundle\DataGridBundle\Datagrid;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Oro\Bundle\SecurityBundle\SecurityFacade;
use Oro\Bundle\DataGridBundle\Event\BuildAfter;
use Oro\Bundle\DataGridBundle\Event\BuildBefore;
use Oro\Bundle\DataGridBundle\Extension\Acceptor;
use Oro\Bundle\DataGridBundle\Datasource\DatasourceInterface;
use Oro\Bundle\DataGridBundle\Extension\ExtensionVisitorInterface;
use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration;
class Builder
{
const DATASOURCE_PATH = '[source]';
const DATASOURCE_TYPE_PATH = '[source][type]';
const DATASOURCE_ACL_PATH = '[source][acl_resource]';
const BASE_DATAGRID_CLASS_PATH = '[options][base_datagrid_class]';
/** @var string */
protected $baseDatagridClass;
/** @var string */
protected $acceptorClass;
/** @var EventDispatcherInterface */
protected $eventDispatcher;
/** @var DatasourceInterface[] */
protected $dataSources = [];
/** @var ExtensionVisitorInterface[] */
protected $extensions = [];
/** @var SecurityFacade */
protected $securityFacade;
public function __construct(
$baseDatagridClass,
$acceptorClass,
EventDispatcherInterface $eventDispatcher,
SecurityFacade $securityFacade
) {
$this->baseDatagridClass = $baseDatagridClass;
$this->acceptorClass = $acceptorClass;
$this->eventDispatcher = $eventDispatcher;
$this->securityFacade = $securityFacade;
}
/**
* Create, configure and build datagrid
*
* @param DatagridConfiguration $config
*
* @return DatagridInterface
*/
public function build(DatagridConfiguration $config)
{
$class = $config->offsetGetByPath(self::BASE_DATAGRID_CLASS_PATH, $this->baseDatagridClass);
$name = $config->getName();
/** @var Acceptor $acceptor */
$acceptor = new $this->acceptorClass($config);
/** @var DatagridInterface $datagrid */
$datagrid = new $class($name, $acceptor);
$event = new BuildBefore($datagrid, $config);
$this->eventDispatcher->dispatch(BuildBefore::NAME, $event);
// duplicate event dispatch with grid name
$this->eventDispatcher->dispatch(BuildBefore::NAME . '.' . $name, $event);
$this->buildDataSource($datagrid, $config);
foreach ($this->extensions as $extension) {
if ($extension->isApplicable($config)) {
$acceptor->addExtension($extension);
}
}
$acceptor->processConfiguration();
$event = new BuildAfter($datagrid);
$this->eventDispatcher->dispatch(BuildAfter::NAME, $event);
// duplicate event dispatch with grid name
$this->eventDispatcher->dispatch(BuildAfter::NAME . '.' . $name, $event);
return $datagrid;
}
/**
* Register datasource type
* Automatically registered services tagged by oro_datagrid.datasource tag
*
* @param string $type
* @param DatasourceInterface $dataSource
*
* @return $this
*/
public function registerDatasource($type, DatasourceInterface $dataSource)
{
$this->dataSources[$type] = $dataSource;
return $this;
}
/**
* Register extension
* Automatically registered services tagged by oro_datagrid.extension tag
*
* @param ExtensionVisitorInterface $extension
*
* @return $this
*/
public function registerExtension(ExtensionVisitorInterface $extension)
{
$this->extensions[] = $extension;
return $this;
}
/**
* Try to find datasource adapter and process it
* Datasource object should be self-acceptable to grid
*
* @param DatagridInterface $grid
* @param DatagridConfiguration $config
*
* @throws \RuntimeException
*/
protected function buildDataSource(DatagridInterface $grid, DatagridConfiguration $config)
{
$sourceType = $config->offsetGetByPath(self::DATASOURCE_TYPE_PATH, false);
if (!$sourceType) {
throw new \RuntimeException('Datagrid source does not configured');
}
if (!isset($this->dataSources[$sourceType])) {
throw new \RuntimeException(sprintf('Datagrid source "%s" does not exist', $sourceType));
}
$acl = $config->offsetGetByPath(self::DATASOURCE_ACL_PATH);
if ($acl && !$this->isResourceGranted($acl)) {
throw new AccessDeniedException('Access denied.');
}
$this->dataSources[$sourceType]->process($grid, $config->offsetGetByPath(self::DATASOURCE_PATH, []));
}
/**
* Checks if an access to a resource is granted or not
*
* @param string $aclResource An ACL annotation id or "permission;descriptor"
*
* @return bool
*/
protected function isResourceGranted($aclResource)
{
$delimiter = strpos($aclResource, ';');
if ($delimiter) {
$permission = substr($aclResource, 0, $delimiter);
$descriptor = substr($aclResource, $delimiter + 1);
return $this->securityFacade->isGranted($permission, $descriptor);
}
return $this->securityFacade->isGranted($aclResource);
}
}
| akeneo/platform | src/Oro/Bundle/DataGridBundle/Datagrid/Builder.php | PHP | mit | 5,430 |
export enum Collection {
NESTJS = '@nestjs/schematics',
}
| ThomRick/nest-cli | lib/schematics/collection.ts | TypeScript | mit | 60 |
namespace DataTradeExamples
{
class Program
{
static void Main()
{
string address = "localhost";
string username = "5";
string password = "123qwe!";
//var example = new TradeServerInfoExample(address, username, password);
var example = new AccountInfoExample(address, username, password);
//var example = new SendLimitOrderExample(address, username, password);
//var example = new SendMarketOrderExample(address, username, password);
//var example = new SendStopOrderExample(address, username, password);
//var example = new CloseAllPositionsExample(address, username, password);
//var example = new ClosePositionExample(address, username, password);
//var example = new ClosePartiallyPositionExample(address, username, password);
//var example = new DeletePendingOrderExample(address, username, password);
//var example = new GetOrdersExample(address, username, password);
//var example = new GetTradeTransactionReportsExample(address, username, password);
//var example = new ModifyTradeRecordExample(address, username, password);
//var example = new CloseByExample(address, username, password);
//var example = new GetDailyAccountSnapshotsExample(address, username, password);
using (example)
{
example.Run();
}
}
}
}
| SoftFx/FDK | Examples/CSharp/DataTradeExamples/Program.cs | C# | mit | 1,518 |
package com.skidsdev.fyrestone.item;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
public final class ItemRegister
{
public static Item itemShard;
public static Item itemFyrestoneIngot;
public static Item itemEarthstoneIngot;
public static Item itemMysticalOrb;
public static Item itemPlagueEssence;
public static Item itemPlagueCore;
public static Item itemBlazingCore;
public static Item itemFyrestoneCatalyst;
public static Item itemGuideBook;
public static Item itemSword;
public static ToolMaterial FYRESTONE = EnumHelper.addToolMaterial("FYRESTONE", 2, 500, 10.0F, 2.0F, 18);
public static List<Item> registeredItems;
public static final void createItems()
{
registeredItems = new ArrayList<Item>();
GameRegistry.register(itemShard = new ItemBaseShard());
itemFyrestoneIngot = registerItem(new BaseItem("itemFyrestoneIngot"), "ingotFyrestone");
itemEarthstoneIngot = registerItem(new BaseItem("itemEarthstoneIngot"), "ingotEarthstone");
itemMysticalOrb = registerItem(new BaseItem("itemMysticalOrb"));
itemPlagueEssence = registerItem(new BaseItem("itemPlagueEssence"));
itemPlagueCore = registerItem(new BaseItem("itemPlagueCore"));
itemBlazingCore = registerItem(new BaseItem("itemBlazingCore"));
itemFyrestoneCatalyst = registerItem(new BaseItem("itemFyrestoneCatalyst"));
itemGuideBook = registerItem(new ItemGuideBook());
itemSword = registerItem(new ItemBaseSword(FYRESTONE, "itemSword"));
}
private static Item registerItem(Item item, String oreDict)
{
OreDictionary.registerOre(oreDict, registerItem(item));
return item;
}
private static Item registerItem(Item item)
{
GameRegistry.register(item);
registeredItems.add(item);
return item;
}
} | gunnerwolf/Fyrestone | src/main/java/com/skidsdev/fyrestone/item/ItemRegister.java | Java | mit | 2,022 |
// Copyright (c) 2013 Richard Long & HexBeerium
//
// Released under the MIT license ( http://opensource.org/licenses/MIT )
//
package jsonbroker.library.common.broker;
import jsonbroker.library.common.exception.BaseException;
/**
*
* @deprecated use jsonbroker.library.broker.BrokerMessageType
*
*/
public class BrokerMessageType extends jsonbroker.library.broker.BrokerMessageType {
public static final BrokerMessageType FAULT = new BrokerMessageType("fault");
public static final BrokerMessageType NOTIFICATION = new BrokerMessageType("notification");
public static final BrokerMessageType ONEWAY = new BrokerMessageType("oneway");
public static final BrokerMessageType META_REQUEST = new BrokerMessageType("meta-request");
public static final BrokerMessageType META_RESPONSE = new BrokerMessageType("meta-response");
public static final BrokerMessageType REQUEST = new BrokerMessageType("request");
public static final BrokerMessageType RESPONSE = new BrokerMessageType("response");
private BrokerMessageType(String identifier) {
super( identifier );
}
public static BrokerMessageType lookup( String identifier) {
if( FAULT._identifier.equals(identifier) ) {
return FAULT;
}
if( NOTIFICATION._identifier.equals( identifier) ) {
return NOTIFICATION;
}
if( ONEWAY._identifier.equals(identifier) ) {
return ONEWAY;
}
if( META_REQUEST._identifier.equals(identifier) ) {
return META_REQUEST;
}
if( META_RESPONSE._identifier.equals(identifier) ) {
return META_RESPONSE;
}
if( REQUEST._identifier.equals(identifier) ) {
return REQUEST;
}
if( RESPONSE._identifier.equals(identifier) ) {
return RESPONSE;
}
String technicalError = String.format("unexpected identifier; identifier = '%s'", identifier);
throw new BaseException(BrokerMessageType.class, technicalError);
}
}
| rlong/java.jsonbroker.library | src/jsonbroker/library/common/broker/BrokerMessageType.java | Java | mit | 1,946 |
class DropTable < ActiveRecord::Migration
def up
end
def down
drop_table :Stat
end
end
| suhasdeshpande/DigFollowers | db/migrate/20120308180244_drop_table.rb | Ruby | mit | 97 |
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("BusinessLogic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BusinessLogic")]
[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("96558876-6abb-4f6f-a392-b1503c239f40")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| PhatTrien-MNM/ptnm_cuoiki | BusinessLogic/Properties/AssemblyInfo.cs | C# | mit | 1,402 |
require 'spec_helper'
module Recurly
describe BillingInfo do
# version accounts based on this current files modification dates
timestamp = File.mtime(__FILE__).to_i
def verify_billing_info(billing_info, billing_attributes)
# check the billing data fields
billing_info.first_name.should == billing_attributes[:first_name]
billing_info.last_name.should == billing_attributes[:last_name]
billing_info.address1.should == billing_attributes[:address1]
billing_info.city.should == billing_attributes[:city]
billing_info.state.should == billing_attributes[:state]
billing_info.zip.should == billing_attributes[:zip]
# check the credit card fields
billing_info.credit_card.last_four.should == billing_attributes[:credit_card][:number][-4, 4]
end
describe "create an account's billing information" do
use_vcr_cassette "billing/create/#{timestamp}"
let(:account){ Factory.create_account("billing-create-#{timestamp}") }
before(:each) do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name
})
@billing_info = BillingInfo.create(@billing_attributes)
end
it "should successfully create the billing info record" do
@billing_info.updated_at.should_not be_nil
end
it "should set the correct billing_info on the server " do
billing_info = BillingInfo.find(account.account_code)
verify_billing_info(billing_info, @billing_attributes)
end
end
describe "update an account's billing information" do
use_vcr_cassette "billing/update/#{timestamp}"
let(:account){ Factory.create_account_with_billing_info("billing-update-#{timestamp}") }
before(:each) do
@new_billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name,
:address1 => "1st Ave South, Apt 5001"
})
@billing_info = BillingInfo.create(@new_billing_attributes)
end
it "should set the correct billing_info on the server " do
billing_info = BillingInfo.find(account.account_code)
verify_billing_info(billing_info, @new_billing_attributes)
end
end
describe "get account's billing information" do
use_vcr_cassette "billing/find/#{timestamp}"
let(:account){ Factory.create_account_with_billing_info("billing-find-#{timestamp}") }
before(:each) do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name
})
@billing_info = BillingInfo.find(account.account_code)
end
it "should return the correct billing_info from the server" do
billing_info = BillingInfo.find(account.account_code)
verify_billing_info(billing_info, @billing_attributes)
end
end
describe "clearing an account's billing information" do
use_vcr_cassette "billing/destroy/#{timestamp}"
let(:account){ Factory.create_account("billing-destroy-#{timestamp}") }
before(:each) do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name,
:address1 => "500 South Central Blvd",
:city => "Los Angeles",
:state => "CA",
:zip => "90001"
})
BillingInfo.create(@billing_attributes)
@billing_info = BillingInfo.find(account.account_code)
end
it "should allow destroying the billing info for an account" do
@billing_info.destroy
expect {
fresh = BillingInfo.find(account.account_code)
}.to raise_error ActiveResource::ResourceNotFound
end
end
describe "set the appropriate error" do
use_vcr_cassette "billing/errors/#{timestamp}"
let(:account){ Factory.create_account("billing-errors-#{timestamp}") }
it "should set an error on base if the card number is blank" do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name,
:credit_card => {
:number => '',
},
})
billing_info = BillingInfo.create(@billing_attributes)
billing_info.errors[:base].count.should == 1
end
it "should set an error if the card number is invalid" do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name,
:credit_card => {
:number => '4000-0000-0000-0002',
},
})
billing_info = BillingInfo.create(@billing_attributes)
billing_info.errors.count.should == 1
end
end
end
end | compactcode/recurly-client-ruby | spec/integration/billing_info_spec.rb | Ruby | mit | 5,228 |
<?php
namespace Fer\UserBundle\Security\User\Provider;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use \BaseFacebook;
use \FacebookApiException;
class FacebookProvider implements UserProviderInterface
{
/**
* @var \Facebook
*/
protected $facebook;
protected $userManager;
protected $validator;
public function __construct(BaseFacebook $facebook, $userManager, $validator)
{
$this->facebook = $facebook;
$this->userManager = $userManager;
$this->validator = $validator;
}
public function supportsClass($class)
{
return $this->userManager->supportsClass($class);
}
public function findUserByFbId($fbId)
{
return $this->userManager->findUserBy(array('facebookId' => $fbId));
}
public function loadUserByUsername($username)
{
$user = $this->findUserByFbId($username);
try {
$fbdata = $this->facebook->api('/me');
} catch (FacebookApiException $e) {
$fbdata = null;
}
if (!empty($fbdata)) {
if (empty($user)) {
$user = $this->userManager->createUser();
$user->setEnabled(true);
$user->setPassword('');
}
// TODO use http://developers.facebook.com/docs/api/realtime
$user->setFBData($fbdata);
if (count($this->validator->validate($user, 'Facebook'))) {
// TODO: the user was found obviously, but doesnt match our expectations, do something smart
throw new UsernameNotFoundException('The facebook user could not be stored');
}
$this->userManager->updateUser($user);
}
if (empty($user)) {
throw new UsernameNotFoundException('The user is not authenticated on facebook');
}
return $user;
}
public function refreshUser(UserInterface $user)
{
if (!$this->supportsClass(get_class($user)) || !$user->getFacebookId()) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
return $this->loadUserByUsername($user->getFacebookId());
}
} | farconada/sfapi | src/Fer/UserBundle/Security/User/Provider/FacebookProvider.php | PHP | mit | 2,117 |
<?php
/*
* The MIT License
*
* Copyright 2014 Ronny Hildebrandt <ronny.hildebrandt@avorium.de>.
*
* 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.
*/
/**
* This file is used for installation.
*/
require_once './code/App.php';
// Check file permissions
$candeleteinstallsript = Install::canDeleteInstallScript();
$canwritelocalconfig = Install::canWriteLocalConfig();
$canwritemediadir = Install::canWriteMediaDir();
$canwritelocaledir = Install::canWriteLocaleDir();
$isdatabaseavailable = Install::isPostgresAvailable();
$isgdavailable = Install::isGdAvailable();
// Handle postbacks for form
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
// Form was posted back
$databasehost = filter_input(INPUT_POST, 'databasehost');
$databaseusername = filter_input(INPUT_POST, 'databaseusername');
$databasepassword = filter_input(INPUT_POST, 'databasepassword');
$databasename = filter_input(INPUT_POST, 'databasename');
$tableprefix = filter_input(INPUT_POST, 'tableprefix');
$defaultlanguage = filter_input(INPUT_POST, 'defaultlanguage');
$GLOBALS['databasehost'] = $databasehost;
$GLOBALS['databaseusername'] = $databaseusername;
$GLOBALS['databasepassword'] = $databasepassword;
$GLOBALS['databasename'] = $databasename;
$GLOBALS['tableprefix'] = $tableprefix;
$GLOBALS['defaultlanguage'] = $defaultlanguage;
// Check database connection
$databaseerror = !Install::canAccessDatabase();
if ($candeleteinstallsript && $canwritelocalconfig && $canwritemediadir && $canwritelocaledir && $isdatabaseavailable && $isgdavailable && !$databaseerror) {
// Store localconfig file
$installationprogress = Install::createLocalConfig();
// Perform the database installation
$installationprogress .= Install::createAndUpdateTables($tableprefix);
rename('install.php', 'install.php.bak');
$installationprogress .= '<p class="success">'.sprintf(__('The installation is completed. The %s file was renamed to %s for security reasons.'), 'install.php', 'install.php.bak').'</p>';
} else {
$installationprogress = false;
}
} else {
// Single GET page call
if (file_exists('config/localconfig.inc.php')) {
require_once 'config/localconfig.inc.php';
} else {
$databasehost = 'localhost';
$databaseusername = '';
$databasepassword = '';
$databasename = '';
$tableprefix = 'mps_';
$defaultlanguage = 'en';
}
$databaseerror = null;
$installationprogress = false;
}
?><!DOCTYPE html>
<html>
<head>
<title><?php echo __('Install MyPhotoStorage') ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="static/css/install.css" />
</head>
<body>
<h1><?php echo __('Install MyPhotoStorage') ?></h1>
<form method="post" action="install.php#end" class="simple install">
<h2><?php echo __('File system check') ?></h2>
<div>
<?php if ($candeleteinstallsript) : ?>
<p class="success"><?php echo __('Install script can be deleted.') ?></p>
<?php else : ?>
<p class="error"><?php echo sprintf(__('Install script cannot be deleted. Please make sure that the webserver process has write permissions to the file %s'), Install::$installFileName) ?></p>
<?php endif ?>
<?php if ($canwritelocalconfig) : ?>
<p class="success"><?php echo __('Config file is writeable.') ?></p>
<?php else : ?>
<p class="error"><?php echo sprintf(__('Config file is not writeable. Please make sure that the webserver process has write permissions to the file %s'), Install::$localConfigFileName) ?></p>
<?php endif ?>
<?php if ($canwritemediadir) : ?>
<p class="success"><?php echo __('Media directory is writeable.') ?></p>
<?php else : ?>
<p class="error"><?php echo sprintf(__('Media directory is not writeable. Please make sure that the webserver process has write permissions to the directory %s'), Install::$mediaDir) ?></p>
<?php endif ?>
<?php if ($canwritelocaledir) : ?>
<p class="success"><?php echo __('Locale directory is writeable.') ?></p>
<?php else : ?>
<p class="error"><?php echo sprintf(__('Locale directory is not writeable. Please make sure that the webserver process has write permissions to the directory %s'), Install::$localeDir) ?></p>
<?php endif ?>
</div>
<h2><?php echo __('PHP modules') ?></h2>
<div>
<?php if ($isdatabaseavailable) : ?>
<p class="success"><?php echo __('Database is available.') ?></p>
<?php else : ?>
<p class="error"><?php echo __('The Database PHP extension is not available. Please install it. On Debian you can use "sudo apt-get install php5-mysql"') ?></p>
<?php endif ?>
<?php if ($isgdavailable) : ?>
<p class="success"><?php echo __('GD is available.') ?></p>
<?php else : ?>
<p class="error"><?php echo __('The GD PHP extension is not available. Please install it. On Debian you can use "sudo apt-get install php5-gd"') ?></p>
<?php endif ?>
</div>
<h2><?php echo __('Database connection') ?></h2>
<div>
<?php if ($isdatabaseavailable) : ?>
<label><?php echo __('Database host') ?></label>
<input type="text" name="databasehost" value="<?php echo $databasehost ?>" />
<label><?php echo __('Database username') ?></label>
<input type="text" name="databaseusername" value="<?php echo $databaseusername ?>" />
<label><?php echo __('Database password') ?></label>
<input type="text" name="databasepassword" value="<?php echo $databasepassword ?>" />
<label><?php echo __('Database name') ?></label>
<input type="text" name="databasename" value="<?php echo $databasename ?>" />
<label><?php echo __('Table prefix') ?></label>
<input type="text" name="tableprefix" value="<?php echo $tableprefix ?>" />
<?php endif ?>
<?php if ($databaseerror === true) : ?>
<p class="error"><?php echo __('Cannot access database. Please check the settings above.') ?></p>
<?php elseif ($databaseerror === false) : ?>
<p class="success"><?php echo __('Database connection succeeded.') ?></p>
<?php endif ?>
</div>
<h2><?php echo __('Language') ?></h2>
<div>
<label><?php echo __('Default language') ?></label>
<input type="text" name="defaultlanguage" value="<?php echo $defaultlanguage ?>" />
</div>
<div>
<input type="submit" value="<?php echo __('Install') ?>" />
</div>
<?php if ($installationprogress) : ?>
<h2><?php echo __('Installation progress') ?></h2>
<div>
<?php echo $installationprogress ?>
</div>
<div><a href="account/register.php"><?php echo __('Register a new account') ?></a></div>
<?php endif ?>
</form>
<a name="end"></a>
</body>
</html> | avorium/myphotostorage | install.php | PHP | mit | 7,966 |
package com.mindera.skeletoid.rxbindings.extensions.views.searchview.support;
import android.view.View;
import androidx.appcompat.widget.SearchView;
import com.jakewharton.rxbinding3.InitialValueObservable;
import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;
public class SearchViewFocusChangeObservable extends InitialValueObservable<Boolean> {
private final SearchView view;
public SearchViewFocusChangeObservable(SearchView view) {
this.view = view;
}
@Override
protected void subscribeListener(Observer<? super Boolean> observer) {
Listener listener = new Listener(view, observer);
observer.onSubscribe(listener);
view.setOnQueryTextFocusChangeListener(listener);
}
@Override
protected Boolean getInitialValue() {
return view.hasFocus();
}
static final class Listener extends MainThreadDisposable
implements SearchView.OnFocusChangeListener {
private final SearchView view;
private final Observer<? super Boolean> observer;
Listener(SearchView view, Observer<? super Boolean> observer) {
this.view = view;
this.observer = observer;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!isDisposed()) {
observer.onNext(hasFocus);
}
}
@Override
protected void onDispose() {
view.setOnFocusChangeListener(null);
}
}
}
| Mindera/skeletoid | rxbindings/src/main/java/com/mindera/skeletoid/rxbindings/extensions/views/searchview/support/SearchViewFocusChangeObservable.java | Java | mit | 1,529 |
import Ember from "ember";
import ENV from '../../config/environment';
export default Ember.Route.extend({
model: function() {
return this.store.find('clip');
},
afterModel: function(){
this.metaTags.setTags({
title: "Clips • " + ENV.name,
description: ENV.description,
url: this.get('router.url')
});
}
}); | APMG/audio-backpack | app/routes/clips/index.js | JavaScript | mit | 387 |
'use strict';
var _ = require('lodash');
var desireds = require('./desireds');
var runner = require('./runconfig');
var gruntConfig = {
env: {
options:{
}
},
simplemocha: {
ltr: {
options: {
timeout: 60000,
captureFile: 'reports.xml',
reporter: 'spec'
},
src: ['test/sauce/sanity/studentCreat*.js','test/sauce/sanity/studentAssign*.js']
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/**/*.js']
}
},
concurrent: {
'test-sauce': []// dynamically filled
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test']
}
},
exec: {
generate_report: {
cmd: function(firstName, lastName) {
return 'xmljade -o reportjade.html report.jade jadexml.xml';
}
}
}
};
//console.log(gruntConfig);
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig(gruntConfig);
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-env');
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-exec');
var target = grunt.option('target') || 'staging';
var product = grunt.option('product') || 'default';
var course = grunt.option('course') || 'default';
var student_userid = grunt.option('student_userid') || 'default';
var instructor_userid = grunt.option('instructor_userid') || 'default';
var coursekey = grunt.option('coursekey') || 'default';
var cs = grunt.option('cs') || 'no';
var rc = grunt.option('rc') || 'no';
var sel_grid = grunt.option('grid') || 'http://127.0.0.1:4444/wd/hub';
var browser = grunt.option('browser') || 'chrome';
gruntConfig.env.common = {
RUNNER: JSON.stringify(runner),
RUN_ENV: JSON.stringify(target),
RUN_IN_GRID: JSON.stringify(sel_grid),
RUN_IN_BROWSER:JSON.stringify(browser),
RUN_FOR_PRODUCT: JSON.stringify(product),
RUN_FOR_COURSE: JSON.stringify(course),
RUN_FOR_STUDENT_USERID: JSON.stringify(student_userid),
RUN_FOR_INSTRUCTOR_USERID: JSON.stringify(instructor_userid),
RUN_FOR_COURSEKEY:JSON.stringify(coursekey),
CREATE_STUDENT: JSON.stringify(cs),
REGISTER_COURSE:JSON.stringify(rc)
};
grunt.registerTask('default', ['env:common','simplemocha:ltr']);
};
| Devanshu1991/4LTRProject | GF_CreateStudentAndRunStudentSubmission.js | JavaScript | mit | 2,979 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlotRenderer.cs" company="OxyPlot">
// The MIT License (MIT)
//
// Copyright (c) 2012 Oystein Bjorke
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
namespace OxyPlot
{
public class PlotRenderer
{
protected readonly PlotModel plot;
protected readonly IRenderContext rc;
public PlotRenderer(IRenderContext rc, PlotModel p)
{
this.rc = rc;
plot = p;
}
public void RenderTitle(string title, string subtitle)
{
OxySize size1 = rc.MeasureText(title, plot.TitleFont, plot.TitleFontSize, plot.TitleFontWeight);
OxySize size2 = rc.MeasureText(subtitle, plot.TitleFont, plot.TitleFontSize, plot.TitleFontWeight);
double height = size1.Height + size2.Height;
double dy = (plot.AxisMargins.Top - height) * 0.5;
double dx = (plot.Bounds.Left + plot.Bounds.Right) * 0.5;
if (!String.IsNullOrEmpty(title))
rc.DrawText(
new ScreenPoint(dx, dy), title, plot.TextColor,
plot.TitleFont, plot.TitleFontSize, plot.TitleFontWeight,
0,
HorizontalTextAlign.Center, VerticalTextAlign.Top);
if (!String.IsNullOrEmpty(subtitle))
rc.DrawText(new ScreenPoint(dx, dy + size1.Height), subtitle, plot.TextColor,
plot.TitleFont, plot.SubtitleFontSize, plot.SubtitleFontWeight, 0,
HorizontalTextAlign.Center, VerticalTextAlign.Top);
}
public void RenderRect(OxyRect bounds, OxyColor fill, OxyColor borderColor, double borderThickness)
{
var border = new[]
{
new ScreenPoint(bounds.Left, bounds.Top), new ScreenPoint(bounds.Right, bounds.Top),
new ScreenPoint(bounds.Right, bounds.Bottom), new ScreenPoint(bounds.Left, bounds.Bottom),
new ScreenPoint(bounds.Left, bounds.Top)
};
rc.DrawPolygon(border, fill, borderColor, borderThickness, null, true);
}
private static readonly double LEGEND_PADDING = 8;
public void RenderLegends()
{
double maxWidth = 0;
double maxHeight = 0;
double totalHeight = 0;
// Measure
foreach (var s in plot.Series)
{
if (String.IsNullOrEmpty(s.Title))
continue;
var oxySize = rc.MeasureText(s.Title, plot.LegendFont, plot.LegendFontSize);
if (oxySize.Width > maxWidth) maxWidth = oxySize.Width;
if (oxySize.Height > maxHeight) maxHeight = oxySize.Height;
totalHeight += oxySize.Height;
}
double lineLength = plot.LegendSymbolLength;
// Arrange
double x0 = double.NaN, x1 = double.NaN, y0 = double.NaN;
// padding padding
// lineLength
// y0 -----o---- seriesName
// x0 x1
double sign = 1;
if (plot.IsLegendOutsidePlotArea)
sign = -1;
// Horizontal alignment
HorizontalTextAlign ha = HorizontalTextAlign.Left;
switch (plot.LegendPosition)
{
case LegendPosition.TopRight:
case LegendPosition.BottomRight:
x0 = plot.Bounds.Right - LEGEND_PADDING * sign;
x1 = x0 - lineLength * sign - LEGEND_PADDING * sign;
ha = sign == 1 ? HorizontalTextAlign.Right : HorizontalTextAlign.Left;
break;
case LegendPosition.TopLeft:
case LegendPosition.BottomLeft:
x0 = plot.Bounds.Left + LEGEND_PADDING * sign;
x1 = x0 + lineLength * sign + LEGEND_PADDING * sign;
ha = sign == 1 ? HorizontalTextAlign.Left : HorizontalTextAlign.Right;
break;
}
// Vertical alignment
VerticalTextAlign va = VerticalTextAlign.Middle;
switch (plot.LegendPosition)
{
case LegendPosition.TopRight:
case LegendPosition.TopLeft:
y0 = plot.Bounds.Top + LEGEND_PADDING + maxHeight / 2;
break;
case LegendPosition.BottomRight:
case LegendPosition.BottomLeft:
y0 = plot.Bounds.Bottom - maxHeight + LEGEND_PADDING;
break;
}
foreach (var s in plot.Series)
{
if (String.IsNullOrEmpty(s.Title))
continue;
rc.DrawText(new ScreenPoint(x1, y0),
s.Title, plot.TextColor,
plot.LegendFont, plot.LegendFontSize, 500, 0,
ha, va);
OxyRect rect = new OxyRect(x0 - lineLength, y0 - maxHeight / 2, lineLength, maxHeight);
if (ha == HorizontalTextAlign.Left)
rect = new OxyRect(x0, y0 - maxHeight / 2, lineLength, maxHeight);
s.RenderLegend(rc, rect);
if (plot.LegendPosition == LegendPosition.TopLeft || plot.LegendPosition == LegendPosition.TopRight)
y0 += maxHeight;
else
y0 -= maxHeight;
}
}
}
} | ylatuya/oxyplot | Source/OxyPlot/Render/PlotRenderer.cs | C# | mit | 7,113 |
version https://git-lfs.github.com/spec/v1
oid sha256:d99fc51072a5fe30289f7dc885457700f9b08ae17fe81d034245aba73c408033
size 34706
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.1/model/model.js | JavaScript | mit | 130 |
<?php
namespace Dreamhood\CmsBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class DreamhoodCmsExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
$loader->load('services_for_sonata_admin.yml');
}
}
| chanakasan/cms-sandbox | src/Dreamhood/CmsBundle/DependencyInjection/DreamhoodCmsExtension.php | PHP | mit | 939 |
<?php
namespace App\AWS;
use Aws\S3\S3Client;
use Psr\Log\LoggerInterface;
class S3
{
private $s3;
private $bucketName;
private $baseUrl;
private $logger;
/**
* S3 constructor.
*
* @param S3Client $s3
* @param $baseUrl
* @param $bucketName
* @param LoggerInterface $loggerInterface
*/
public function __construct(S3Client $s3, $baseUrl, $bucketName, LoggerInterface $loggerInterface)
{
$this->bucketName = $bucketName;
$this->baseUrl = $baseUrl;
$this->s3 = $s3;
$this->logger = $loggerInterface;
}
/**
* @param string $path
* @param string $filename
* @param array $headers
*
* @return mixed
*
* @throws \Exception
*/
public function upload($path, $filename, $headers = [])
{
try {
$config = [
'Bucket' => $this->bucketName,
'Key' => trim($filename, '/'),
'Body' => fopen($path, 'r'),
'ACL' => 'public-read'
];
foreach ($headers as $key => $header) {
$config[$key] = $header;
}
$result = $this->s3->putObject($config);
return $result['ObjectURL'];
} catch (\Exception $e) {
$this->logger->error('Failed to upload file', ['e' => $e]);
throw $e;
}
}
/**
* @param string $filename
*/
public function delete($filename)
{
$this->s3->deleteObject([
'Bucket' => $this->bucketName,
'Key' => trim($filename, '/'),
]);
}
/**
* @param array $parameters
*
* @return \Aws\ResultPaginator
*/
public function getPaginator(array $parameters)
{
return $this->s3->getPaginator('ListObjectsV2', array_merge(['Bucket' => $this->bucketName], $parameters));
}
/**
* @param array $parameters
*
* @return \Iterator
*/
public function getIterator(array $parameters)
{
return $this->s3->getIterator('ListObjectsV2', array_merge(['Bucket' => $this->bucketName], $parameters));
}
/**
* @param array $parameters
*
* @return \Aws\Result
*/
public function getListObject(array $parameters)
{
return $this->s3->listObjectsV2(array_merge(['Bucket' => $this->bucketName], $parameters));
}
/**
* @param string $key
*
* @return string
*/
public function getObjectByKey($key)
{
$result = $this->s3->getObject([
'Bucket' => $this->bucketName,
'Key' => $key,
]);
return (string) $result['Body'];
}
}
| ekreative/apps-server | src/AWS/S3.php | PHP | mit | 2,714 |
namespace CameraBazar.Services.Models.Users
{
using System;
public class UserDetailsModel
{
public string Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Phone { get; set; }
public DateTime LasLogin { get; set; }
}
}
| VaskoViktorov/SoftUni-Homework | 11. C# ASP.NET Core - 30.10.2017/06. Razor & Filters - Part II - Exercise/CameraBazar/CameraBazar.Services/Models/Users/UserDetailsModel.cs | C# | mit | 335 |
module GURPS
class Template
@modifiers = []
def initialize name
@name = name
end
def << modifier
@modifiers << modifier
end
def applyTo char
# Apply this template to a GURPS character.
@modifiers.each do |modifier|
modifier.applyTo char
end
char.templates << self
end
end
class PropertyModifier
def initialize prop, modifier, op="add"
@property = prop
@modifier = modifier
@operator = op
end
def applyTo char
if prop = char.try(@property.to_sym)
case @operator
when "add" then prop += @modifier
when "mult" then prop *= @modifier
end
end
end
end
module TemplateShorthands
# @todo Fill this in.
def template templ_name
send templ_name
end
end
end
| AlexSafatli/gurps | lib/gurps/template.rb | Ruby | mit | 840 |
package org.karoglan.tollainmear.signeditor.commandexecutor;
import org.karoglan.tollainmear.signeditor.KSECommandManager;
import org.karoglan.tollainmear.signeditor.KSERecordsManager;
import org.karoglan.tollainmear.signeditor.KaroglanSignEditor;
import org.karoglan.tollainmear.signeditor.utils.Translator;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.serializer.TextSerializers;
import java.io.IOException;
public class ReloadExecutor implements CommandExecutor {
private KSERecordsManager rm;
private KaroglanSignEditor kse = KaroglanSignEditor.getInstance();
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
kse = KaroglanSignEditor.getInstance();
rm = KaroglanSignEditor.getInstance().getKSERecordsManager();
try {
kse.cfgInit();
rm.init();
kse.setTranslator(new Translator(kse));
kse.getTranslator().checkUpdate();
kse.setKseCmdManager(new KSECommandManager(kse));
} catch (IOException e) {
e.printStackTrace();
}
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(kse.getTranslator().getstring("message.KSEprefix")+kse.getTranslator().getstring("message.reload")));
return CommandResult.success();
}
}
| Tollainmear/KaroglanSignEditor | src/main/java/org/karoglan/tollainmear/signeditor/commandexecutor/ReloadExecutor.java | Java | mit | 1,591 |
package gl8080.lifegame.web.resource;
import java.net.URI;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import gl8080.lifegame.application.definition.RegisterGameDefinitionService;
import gl8080.lifegame.application.definition.RemoveGameDefinitionService;
import gl8080.lifegame.application.definition.SearchGameDefinitionService;
import gl8080.lifegame.application.definition.UpdateGameDefinitionService;
import gl8080.lifegame.logic.definition.GameDefinition;
import gl8080.lifegame.util.Maps;
@Path("/game/definition")
@ApplicationScoped
public class GameDefinitionResource {
@Inject
private RegisterGameDefinitionService registerService;
@Inject
private SearchGameDefinitionService searchService;
@Inject
private UpdateGameDefinitionService saveService;
@Inject
private RemoveGameDefinitionService removeService;
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response register(@QueryParam("size") int size) {
GameDefinition gameDefinition = this.registerService.register(size);
long id = gameDefinition.getId();
URI uri = UriBuilder
.fromResource(GameDefinitionResource.class)
.path(GameDefinitionResource.class, "search")
.build(id);
return Response
.created(uri)
.entity(Maps.map("id", id))
.build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public LifeGameDto search(@PathParam("id") long id) {
GameDefinition gameDefinition = this.searchService.search(id);
return LifeGameDto.of(gameDefinition);
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(LifeGameDto dto) {
if (dto == null) {
return Response.status(Status.BAD_REQUEST).build();
}
GameDefinition gameDefinition = this.saveService.update(dto);
return Response.ok()
.entity(Maps.map("version", gameDefinition.getVersion()))
.build();
}
@DELETE
@Path("/{id}")
public Response remove(@PathParam("id") long id) {
this.removeService.remove(id);
return Response.noContent().build();
}
}
| opengl-8080/lifegame-javaee | src/main/java/gl8080/lifegame/web/resource/GameDefinitionResource.java | Java | mit | 2,858 |
package edacc.parameterspace.domain;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
@SuppressWarnings("serial")
public class RealDomain extends Domain {
protected Double low, high;
public static final String name = "Real";
@SuppressWarnings("unused")
private RealDomain() {
}
public RealDomain(Double low, Double high) {
this.low = low;
this.high = high;
}
public RealDomain(Integer low, Integer high) {
this.low = Double.valueOf(low);
this.high = Double.valueOf(high);
}
@Override
public boolean contains(Object value) {
if (!(value instanceof Number)) return false;
double d = ((Number)value).doubleValue();
return d >= this.low && d <= this.high;
}
@Override
public Object randomValue(Random rng) {
return rng.nextDouble() * (this.high - this.low) + this.low;
}
@Override
public String toString() {
return "[" + this.low + "," + this.high + "]";
}
public Double getLow() {
return low;
}
public void setLow(Double low) {
this.low = low;
}
public Double getHigh() {
return high;
}
public void setHigh(Double high) {
this.high = high;
}
@Override
public Object mutatedValue(Random rng, Object value) {
return mutatedValue(rng, value, 0.1f);
}
@Override
public Object mutatedValue(Random rng, Object value, float stdDevFactor) {
if (!contains(value)) return value;
double r = rng.nextGaussian() * ((high - low) * stdDevFactor);
return Math.min(Math.max(this.low, ((Number)value).doubleValue() + r), this.high);
}
@Override
public List<Object> getDiscreteValues() {
List<Object> values = new LinkedList<Object>();
for (double d = low; d <= high; d += (high - low) / 100.0f) {
values.add(d);
}
return values;
}
@Override
public String getName() {
return name;
}
@Override
public List<Object> getGaussianDiscreteValues(Random rng, Object value,
float stdDevFactor, int numberSamples) {
List<Object> vals = new LinkedList<Object>();
for (int i = 0; i < numberSamples; i++) {
vals.add(mutatedValue(rng, value, stdDevFactor));
}
return vals;
}
@Override
public List<Object> getUniformDistributedValues(int numberSamples) {
List<Object> vals = new LinkedList<Object>();
double dist = (high - low) / (double) (numberSamples-1);
double cur = low;
for (int i = 0; i < numberSamples; i++) {
if (i == numberSamples -1)
cur = high;
vals.add(cur);
cur += dist;
}
return vals;
}
@Override
public Object getMidValueOrNull(Object o1, Object o2) {
if (!(o1 instanceof Double) || !(o2 instanceof Double))
return null;
Double d1 = (Double) o1;
Double d2 = (Double) o2;
if (d1.equals(d2)) {
return null;
}
return (d1+d2) / 2;
}
}
| EDACC/edacc_api | src/edacc/parameterspace/domain/RealDomain.java | Java | mit | 2,816 |
'use strict';
const isUriStringCheck = require('../strCheck');
/**
* First test if the argument passed in is a String. If true, get page version from uri.
* Otherwise throw an error.
* @example /pages/foo/@published returns published
* @param {string} uri
* @return {string|null}
*/
module.exports = function (uri) {
isUriStringCheck.strCheck(uri);
const result = /\/pages\/.+?@(.+)/.exec(uri);
return result && result[1];
};
| nymag/clay-utils | lib/getPageVersion/index.js | JavaScript | mit | 442 |
//# sourceMappingURL=request-constructor.js.map | jlberrocal/ng2-dynatable | src/interfaces/request-constructor.js | JavaScript | mit | 47 |
/*
* jQuery File Upload Plugin 5.0.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://creativecommons.org/licenses/MIT/
*/
/*jslint nomen: false, unparam: true, regexp: false */
/*global document, XMLHttpRequestUpload, Blob, File, FormData, location, jQuery */
(function ($) {
'use strict';
// The fileupload widget listens for change events on file input fields
// defined via fileInput setting and drop events of the given dropZone.
// In addition to the default jQuery Widget methods, the fileupload widget
// exposes the "add" and "send" methods, to add or directly send files
// using the fileupload API.
// By default, files added via file input selection, drag & drop or
// "add" method are uploaded immediately, but it is possible to override
// the "add" callback option to queue file uploads.
$.widget('blueimp.fileupload', {
options: {
// The namespace used for event handler binding on the dropZone and
// fileInput collections.
// If not set, the name of the widget ("fileupload") is used.
namespace: undefined,
// The drop target collection, by the default the complete document.
// Set to null or an empty collection to disable drag & drop support:
dropZone: $(document),
// The file input field collection, that is listened for change events.
// If undefined, it is set to the file input fields inside
// of the widget element on plugin initialization.
// Set to null or an empty collection to disable the change listener.
fileInput: undefined,
// By default, the file input field is replaced with a clone after
// each input field change event. This is required for iframe transport
// queues and allows change events to be fired for the same file
// selection, but can be disabled by setting the following option to false:
replaceFileInput: true,
// The parameter name for the file form data (the request argument name).
// If undefined or empty, the name property of the file input field is
// used, or "files[]" if the file input name property is also empty:
paramName: undefined,
// By default, each file of a selection is uploaded using an individual
// request for XHR type uploads. Set to false to upload file
// selections in one request each:
singleFileUploads: true,
// Set the following option to true to issue all file upload requests
// in a sequential order:
sequentialUploads: false,
// Set the following option to true to force iframe transport uploads:
forceIframeTransport: false,
// By default, XHR file uploads are sent as multipart/form-data.
// The iframe transport is always using multipart/form-data.
// Set to false to enable non-multipart XHR uploads:
multipart: true,
// To upload large files in smaller chunks, set the following option
// to a preferred maximum chunk size. If set to 0, null or undefined,
// or the browser does not support the required Blob API, files will
// be uploaded as a whole.
maxChunkSize: undefined,
// When a non-multipart upload or a chunked multipart upload has been
// aborted, this option can be used to resume the upload by setting
// it to the size of the already uploaded bytes. This option is most
// useful when modifying the options object inside of the "add" or
// "send" callbacks, as the options are cloned for each file upload.
uploadedBytes: undefined,
// By default, failed (abort or error) file uploads are removed from the
// global progress calculation. Set the following option to false to
// prevent recalculating the global progress data:
recalculateProgress: true,
// Additional form data to be sent along with the file uploads can be set
// using this option, which accepts an array of objects with name and
// value properties, a function returning such an array, a FormData
// object (for XHR file uploads), or a simple object.
// The form of the first fileInput is given as parameter to the function:
formData: function (form) {
return form.serializeArray();
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// If the singleFileUploads option is enabled, this callback will be
// called once for each file in the selection for XHR file uplaods, else
// once for each file selection.
// The upload starts when the submit method is invoked on the data parameter.
// The data object contains a files property holding the added files
// and allows to override plugin options as well as define ajax settings.
// Listeners for this callback can also be bound the following way:
// .bind('fileuploadadd', func);
// data.submit() returns a Promise object and allows to attach additional
// handlers using jQuery's Deferred callbacks:
// data.submit().done(func).fail(func).always(func);
add: function (e, data) {
data.submit();
},
// Other callbacks:
// Callback for the start of each file upload request:
// send: function (e, data) {}, // .bind('fileuploadsend', func);
// Callback for successful uploads:
// done: function (e, data) {}, // .bind('fileuploaddone', func);
// Callback for failed (abort or error) uploads:
// fail: function (e, data) {}, // .bind('fileuploadfail', func);
// Callback for completed (success, abort or error) requests:
// always: function (e, data) {}, // .bind('fileuploadalways', func);
// Callback for upload progress events:
// progress: function (e, data) {}, // .bind('fileuploadprogress', func);
// Callback for global upload progress events:
// progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
// Callback for uploads start, equivalent to the global ajaxStart event:
// start: function (e) {}, // .bind('fileuploadstart', func);
// Callback for uploads stop, equivalent to the global ajaxStop event:
// stop: function (e) {}, // .bind('fileuploadstop', func);
// Callback for change events of the fileInput collection:
// change: function (e, data) {}, // .bind('fileuploadchange', func);
// Callback for drop events of the dropZone collection:
// drop: function (e, data) {}, // .bind('fileuploaddrop', func);
// Callback for dragover events of the dropZone collection:
// dragover: function (e) {}, // .bind('fileuploaddragover', func);
// The plugin options are used as settings object for the ajax calls.
// The following are jQuery ajax settings required for the file uploads:
processData: false,
contentType: false,
cache: false
},
// A list of options that require a refresh after assigning a new value:
_refreshOptionsList: ['namespace', 'dropZone', 'fileInput'],
_isXHRUpload: function (options) {
var undef = 'undefined';
return !options.forceIframeTransport &&
typeof XMLHttpRequestUpload !== undef && typeof File !== undef &&
(!options.multipart || typeof FormData !== undef);
},
_getFormData: function (options) {
var formData;
if (typeof options.formData === 'function') {
return options.formData(options.form);
} else if ($.isArray(options.formData)) {
return options.formData;
} else if (options.formData) {
formData = [];
$.each(options.formData, function (name, value) {
formData.push({name: name, value: value});
});
return formData;
}
return [];
},
_getTotal: function (files) {
var total = 0;
$.each(files, function (index, file) {
total += file.size || 1;
});
return total;
},
_onProgress: function (e, data) {
if (e.lengthComputable) {
var total = data.total || this._getTotal(data.files),
loaded = parseInt(
e.loaded / e.total * (data.chunkSize || total),
10
) + (data.uploadedBytes || 0);
this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
data.lengthComputable = true;
data.loaded = loaded;
data.total = total;
// Trigger a custom progress event with a total data property set
// to the file size(s) of the current upload and a loaded data
// property calculated accordingly:
this._trigger('progress', e, data);
// Trigger a global progress event for all current file uploads,
// including ajax calls queued for sequential file uploads:
this._trigger('progressall', e, {
lengthComputable: true,
loaded: this._loaded,
total: this._total
});
}
},
_initProgressListener: function (options) {
var that = this,
xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
// Accesss to the native XHR object is required to add event listeners
// for the upload progress event:
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener('progress', function (e) {
that._onProgress(e, options);
}, false);
options.xhr = function () {
return xhr;
};
}
},
_initXHRData: function (options) {
var formData,
file = options.files[0];
if (!options.multipart || options.blob) {
// For non-multipart uploads and chunked uploads,
// file meta data is not part of the request body,
// so we transmit this data as part of the HTTP headers.
// For cross domain requests, these headers must be allowed
// via Access-Control-Allow-Headers or removed using
// the beforeSend callback:
options.headers = $.extend(options.headers, {
'X-File-Name': file.name,
'X-File-Type': file.type,
'X-File-Size': file.size
});
if (!options.blob) {
// Non-chunked non-multipart upload:
options.contentType = file.type;
options.data = file;
} else if (!options.multipart) {
// Chunked non-multipart upload:
options.contentType = 'application/octet-stream';
options.data = options.blob;
}
}
if (options.multipart) {
if (options.formData instanceof FormData) {
formData = options.formData;
} else {
formData = new FormData();
$.each(this._getFormData(options), function (index, field) {
formData.append(field.name, field.value);
});
}
if (options.blob) {
formData.append(options.paramName, options.blob);
} else {
$.each(options.files, function (index, file) {
// File objects are also Blob instances.
// This check allows the tests to run with
// dummy objects:
if (file instanceof Blob) {
formData.append(options.paramName, file);
}
});
}
options.data = formData;
}
// Blob reference is not needed anymore, free memory:
options.blob = null;
},
_initIframeSettings: function (options) {
// Setting the dataType to iframe enables the iframe transport:
options.dataType = 'iframe ' + (options.dataType || '');
// The iframe transport accepts a serialized array as form data:
options.formData = this._getFormData(options);
},
_initDataSettings: function (options) {
if (this._isXHRUpload(options)) {
if (!this._chunkedUpload(options, true)) {
if (!options.data) {
this._initXHRData(options);
}
this._initProgressListener(options);
}
} else {
this._initIframeSettings(options);
}
},
_initFormSettings: function (options) {
// Retrieve missing options from the input field and the
// associated form, if available:
if (!options.form || !options.form.length) {
options.form = $(options.fileInput.prop('form'));
}
if (!options.paramName) {
options.paramName = options.fileInput.prop('name') ||
'files[]';
}
if (!options.url) {
options.url = options.form.prop('action') || location.href;
}
// The HTTP request method must be "POST" or "PUT":
options.type = (options.type || options.form.prop('method') || '')
.toUpperCase();
if (options.type !== 'POST' && options.type !== 'PUT') {
options.type = 'POST';
}
},
_getAJAXSettings: function (data) {
var options = $.extend({}, this.options, data);
this._initFormSettings(options);
this._initDataSettings(options);
return options;
},
// Maps jqXHR callbacks to the equivalent
// methods of the given Promise object:
_enhancePromise: function (promise) {
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.always;
return promise;
},
// Creates and returns a Promise object enhanced with
// the jqXHR methods abort, success, error and complete:
_getXHRPromise: function (resolveOrReject, context) {
var dfd = $.Deferred(),
promise = dfd.promise();
context = context || this.options.context || promise;
if (resolveOrReject === true) {
dfd.resolveWith(context);
} else if (resolveOrReject === false) {
dfd.rejectWith(context);
}
promise.abort = dfd.promise;
return this._enhancePromise(promise);
},
// Uploads a file in multiple, sequential requests
// by splitting the file up in multiple blob chunks.
// If the second parameter is true, only tests if the file
// should be uploaded in chunks, but does not invoke any
// upload requests:
_chunkedUpload: function (options, testOnly) {
var that = this,
file = options.files[0],
fs = file.size,
ub = options.uploadedBytes = options.uploadedBytes || 0,
mcs = options.maxChunkSize || fs,
// Use the Blob methods with the slice implementation
// according to the W3C Blob API specification:
slice = file.webkitSlice || file.mozSlice || file.slice,
upload,
n,
jqXHR,
pipe;
if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
options.data) {
return false;
}
if (testOnly) {
return true;
}
if (ub >= fs) {
file.error = 'uploadedBytes';
return this._getXHRPromise(false);
}
// n is the number of blobs to upload,
// calculated via filesize, uploaded bytes and max chunk size:
n = Math.ceil((fs - ub) / mcs);
// The chunk upload method accepting the chunk number as parameter:
upload = function (i) {
if (!i) {
return that._getXHRPromise(true);
}
// Upload the blobs in sequential order:
return upload(i -= 1).pipe(function () {
// Clone the options object for each chunk upload:
var o = $.extend({}, options);
o.blob = slice.call(
file,
ub + i * mcs,
ub + (i + 1) * mcs
);
// Store the current chunk size, as the blob itself
// will be dereferenced after data processing:
o.chunkSize = o.blob.size;
// Process the upload data (the blob and potential form data):
that._initXHRData(o);
// Add progress listeners for this chunk upload:
that._initProgressListener(o);
jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
.done(function () {
// Create a progress event if upload is done and
// no progress event has been invoked for this chunk:
if (!o.loaded) {
that._onProgress($.Event('progress', {
lengthComputable: true,
loaded: o.chunkSize,
total: o.chunkSize
}), o);
}
options.uploadedBytes = o.uploadedBytes
+= o.chunkSize;
});
return jqXHR;
});
};
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe = upload(n);
pipe.abort = function () {
return jqXHR.abort();
};
return this._enhancePromise(pipe);
},
_beforeSend: function (e, data) {
if (this._active === 0) {
// the start callback is triggered when an upload starts
// and no other uploads are currently running,
// equivalent to the global ajaxStart event:
this._trigger('start');
}
this._active += 1;
// Initialize the global progress values:
this._loaded += data.uploadedBytes || 0;
this._total += this._getTotal(data.files);
},
_onDone: function (result, textStatus, jqXHR, options) {
if (!this._isXHRUpload(options)) {
// Create a progress event for each iframe load:
this._onProgress($.Event('progress', {
lengthComputable: true,
loaded: 1,
total: 1
}), options);
}
options.result = result;
options.textStatus = textStatus;
options.jqXHR = jqXHR;
this._trigger('done', null, options);
},
_onFail: function (jqXHR, textStatus, errorThrown, options) {
options.jqXHR = jqXHR;
options.textStatus = textStatus;
options.errorThrown = errorThrown;
this._trigger('fail', null, options);
if (options.recalculateProgress) {
// Remove the failed (error or abort) file upload from
// the global progress calculation:
this._loaded -= options.loaded || options.uploadedBytes || 0;
this._total -= options.total || this._getTotal(options.files);
}
},
_onAlways: function (result, textStatus, jqXHR, options) {
this._active -= 1;
options.result = result;
options.textStatus = textStatus;
options.jqXHR = jqXHR;
this._trigger('always', null, options);
if (this._active === 0) {
// The stop callback is triggered when all uploads have
// been completed, equivalent to the global ajaxStop event:
this._trigger('stop');
// Reset the global progress values:
this._loaded = this._total = 0;
}
},
_onSend: function (e, data) {
var that = this,
jqXHR,
pipe,
options = that._getAJAXSettings(data),
send = function () {
jqXHR = ((that._trigger('send', e, options) !== false && (
that._chunkedUpload(options) ||
$.ajax(options)
)) || that._getXHRPromise(false, options.context)
).done(function (result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, options);
}).fail(function (jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, options);
}).always(function (result, textStatus, jqXHR) {
that._onAlways(result, textStatus, jqXHR, options);
});
return jqXHR;
};
this._beforeSend(e, options);
if (this.options.sequentialUploads) {
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe = (this._sequence = this._sequence.pipe(send, send));
pipe.abort = function () {
return jqXHR.abort();
};
return this._enhancePromise(pipe);
}
return send();
},
_onAdd: function (e, data) {
var that = this,
result = true,
options = $.extend({}, this.options, data);
if (options.singleFileUploads && this._isXHRUpload(options)) {
$.each(data.files, function (index, file) {
var newData = $.extend({}, data, {files: [file]});
newData.submit = function () {
return that._onSend(e, newData);
};
return (result = that._trigger('add', e, newData));
});
return result;
} else if (data.files.length) {
data = $.extend({}, data);
data.submit = function () {
return that._onSend(e, data);
};
return this._trigger('add', e, data);
}
},
// File Normalization for Gecko 1.9.1 (Firefox 3.5) support:
_normalizeFile: function (index, file) {
if (file.name === undefined && file.size === undefined) {
file.name = file.fileName;
file.size = file.fileSize;
}
},
_replaceFileInput: function (input) {
var inputClone = input.clone(true);
$('<form></form>').append(inputClone)[0].reset();
// Detaching allows to insert the fileInput on another form
// without loosing the file input value:
input.after(inputClone).detach();
// Replace the original file input element in the fileInput
// collection with the clone, which has been copied including
// event handlers:
this.options.fileInput = this.options.fileInput.map(function (i, el) {
if (el === input[0]) {
return inputClone[0];
}
return el;
});
},
_onChange: function (e) {
var that = e.data.fileupload,
data = {
files: $.each($.makeArray(e.target.files), that._normalizeFile),
fileInput: $(e.target),
form: $(e.target.form)
};
if (!data.files.length) {
// If the files property is not available, the browser does not
// support the File API and we add a pseudo File object with
// the input value as name with path information removed:
data.files = [{name: e.target.value.replace(/^.*\\/, '')}];
}
// Store the form reference as jQuery data for other event handlers,
// as the form property is not available after replacing the file input:
if (data.form.length) {
data.fileInput.data('blueimp.fileupload.form', data.form);
} else {
data.form = data.fileInput.data('blueimp.fileupload.form');
}
if (that.options.replaceFileInput) {
that._replaceFileInput(data.fileInput);
}
if (that._trigger('change', e, data) === false ||
that._onAdd(e, data) === false) {
return false;
}
},
_onDrop: function (e) {
var that = e.data.fileupload,
dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
data = {
files: $.each(
$.makeArray(dataTransfer && dataTransfer.files),
that._normalizeFile
)
};
if (that._trigger('drop', e, data) === false ||
that._onAdd(e, data) === false) {
return false;
}
e.preventDefault();
},
_onDragOver: function (e) {
var that = e.data.fileupload,
dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
if (that._trigger('dragover', e) === false) {
return false;
}
if (dataTransfer) {
dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy';
}
e.preventDefault();
},
_initEventHandlers: function () {
var ns = this.options.namespace || this.name;
this.options.dropZone
.bind('dragover.' + ns, {fileupload: this}, this._onDragOver)
.bind('drop.' + ns, {fileupload: this}, this._onDrop);
this.options.fileInput
.bind('change.' + ns, {fileupload: this}, this._onChange);
},
_destroyEventHandlers: function () {
var ns = this.options.namespace || this.name;
this.options.dropZone
.unbind('dragover.' + ns, this._onDragOver)
.unbind('drop.' + ns, this._onDrop);
this.options.fileInput
.unbind('change.' + ns, this._onChange);
},
_beforeSetOption: function (key, value) {
this._destroyEventHandlers();
},
_afterSetOption: function (key, value) {
var options = this.options;
if (!options.fileInput) {
options.fileInput = $();
}
if (!options.dropZone) {
options.dropZone = $();
}
this._initEventHandlers();
},
_setOption: function (key, value) {
var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
if (refresh) {
this._beforeSetOption(key, value);
}
$.Widget.prototype._setOption.call(this, key, value);
if (refresh) {
this._afterSetOption(key, value);
}
},
_create: function () {
var options = this.options;
if (options.fileInput === undefined) {
options.fileInput = this.element.is('input:file') ?
this.element : this.element.find('input:file');
} else if (!options.fileInput) {
options.fileInput = $();
}
if (!options.dropZone) {
options.dropZone = $();
}
this._sequence = this._getXHRPromise(true);
this._active = this._loaded = this._total = 0;
this._initEventHandlers();
},
destroy: function () {
this._destroyEventHandlers();
$.Widget.prototype.destroy.call(this);
},
enable: function () {
$.Widget.prototype.enable.call(this);
this._initEventHandlers();
},
disable: function () {
this._destroyEventHandlers();
$.Widget.prototype.disable.call(this);
},
// This method is exposed to the widget API and allows adding files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('add', {files: filesList});
add: function (data) {
if (!data || this.options.disabled) {
return;
}
data.files = $.each($.makeArray(data.files), this._normalizeFile);
this._onAdd(null, data);
},
// This method is exposed to the widget API and allows sending files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('send', {files: filesList});
// The method returns a Promise object for the file upload call.
send: function (data) {
if (data && !this.options.disabled) {
data.files = $.each($.makeArray(data.files), this._normalizeFile);
if (data.files.length) {
return this._onSend(null, data);
}
}
return this._getXHRPromise(false, data && data.context);
}
});
}(jQuery)); | ilyakatz/cucumber-cinema | public/javascripts/jquery.fileupload.js | JavaScript | mit | 31,875 |
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosPint extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M368,170.085c0-21.022-0.973-88.554-19.308-125.013C344.244,36.228,336.25,32,316.999,32H195.001
c-19.25,0-27.246,4.197-31.693,13.041C144.973,81.5,144,149.25,144,170.272c0,98,32,100.353,32,180.853c0,39.5-16,71.402-16,99.402
c0,27,9,29.473,32,29.473h128c23,0,32-2.535,32-29.535c0-28-16-59.715-16-99.215C336,270.75,368,268.085,368,170.085z
M177.602,51.983c0.778-1.546,1.339-1.763,2.53-2.295c1.977-0.884,6.161-1.688,14.869-1.688h121.998
c8.708,0,12.893,0.803,14.869,1.687c1.19,0.532,1.752,0.872,2.53,2.418c8.029,15.967,13.601,42.611,16.105,75.896H161.496
C164.001,94.653,169.572,67.951,177.602,51.983z"></path>
</g>;
} return <IconBase>
<path d="M368,170.085c0-21.022-0.973-88.554-19.308-125.013C344.244,36.228,336.25,32,316.999,32H195.001
c-19.25,0-27.246,4.197-31.693,13.041C144.973,81.5,144,149.25,144,170.272c0,98,32,100.353,32,180.853c0,39.5-16,71.402-16,99.402
c0,27,9,29.473,32,29.473h128c23,0,32-2.535,32-29.535c0-28-16-59.715-16-99.215C336,270.75,368,268.085,368,170.085z
M177.602,51.983c0.778-1.546,1.339-1.763,2.53-2.295c1.977-0.884,6.161-1.688,14.869-1.688h121.998
c8.708,0,12.893,0.803,14.869,1.687c1.19,0.532,1.752,0.872,2.53,2.418c8.029,15.967,13.601,42.611,16.105,75.896H161.496
C164.001,94.653,169.572,67.951,177.602,51.983z"></path>
</IconBase>;
}
};IosPint.defaultProps = {bare: false} | fbfeix/react-icons | src/icons/IosPint.js | JavaScript | mit | 1,517 |
#include "pch.h"
#include "Item.h"
#include "GameManager.h"
#include "ObjectLayer.h"
Item::Item(Vec2 createPos, float scale, BuffTarget buffType)
{
m_UnitType = UNIT_ITEM;
m_CenterSprite->setPosition(createPos);
m_CenterSprite->setScale(scale);
switch (buffType)
{
case BUFF_HP: m_RealSprite = Sprite::create("Images/Unit/item_hp.png"); break;
case BUFF_DAMAGE: m_RealSprite = Sprite::create("Images/Unit/item_damage.png"); break;
case BUFF_COOLTIME: m_RealSprite = Sprite::create("Images/Unit/item_cooltime.png"); break;
case BUFF_SHIELD: m_RealSprite = Sprite::create("Images/Unit/item_shield.png"); break;
case BUFF_SPEED: m_RealSprite = Sprite::create("Images/Unit/item_speed.png"); break;
}
m_RealSprite->setScale(scale);
m_CenterSprite->addChild(m_RealSprite);
}
Item::~Item()
{
}
| dlakwwkd/CommitAgain | Skima/Classes/Item.cpp | C++ | mit | 873 |
namespace TwitterBackup.Services
{
using TwitterBackup.Data;
using TwitterBackup.Models;
using TwitterBackup.Services.Contracts;
using System.Linq;
using System.Collections.Generic;
using System;
using TwitterBackup.Services.Exceptions;
public class UserService : IUserService
{
private readonly IRepository<User> userRepo;
public UserService(IRepository<User> userRepo)
{
this.userRepo = userRepo;
}
/// <summary>
/// Store user in the TwitterBackup database
/// </summary>
/// <param name="user"></param>
public User Save(User user)
{
if (user == null)
{
throw new ArgumentException("Tweet is not valid");
}
var hasAlreadyExist = userRepo
.All()
.Any(userDTO => userDTO.ScreenName == user.ScreenName);
if (hasAlreadyExist)
{
throw new UserException(UserExceptionType.IsAlreadySaved);
}
var userDataModel = userRepo.Add(user);
return userDataModel;
}
public int GetUsersCount()
{
var usersCount = this.userRepo
.All()
.Count();
return usersCount;
}
public IEnumerable<User> GetUsers()
{
var allUsers = this.userRepo
.All()
.ToArray();
return allUsers;
}
}
}
| luboganchev/TwitterBackup | TwitterBackup/TwitterBackup.Services/UserService.cs | C# | mit | 1,545 |
package ee.golive.personal.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "workout")
public class Workout implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", unique=true, nullable = false)
private Integer id;
private String source;
private String source_id;
private String sport_type;
private Date date_created;
private Long duration;
private Double calories;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSource_id() {
return source_id;
}
public void setSource_id(String source_id) {
this.source_id = source_id;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public String getSport_type() {
return sport_type;
}
public void setSport_type(String sport_type) {
this.sport_type = sport_type;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public Double getCalories() {
return calories;
}
public void setCalories(Double calories) {
this.calories = calories;
}
}
| ilves/finance | src/main/java/ee/golive/personal/model/Workout.java | Java | mit | 1,619 |
namespace BlockchainSharp.Tests.Compilers
{
using System;
using BlockchainSharp.Compilers;
using BlockchainSharp.Vm;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class SimpleCompilerTests
{
[TestMethod]
public void CompileEmptyString()
{
var compiler = new SimpleCompiler(string.Empty);
var result = compiler.Compile();
Assert.IsNotNull(result);
Assert.AreEqual(0, result.Length);
}
[TestMethod]
public void CompileNullString()
{
var compiler = new SimpleCompiler(null);
var result = compiler.Compile();
Assert.IsNotNull(result);
Assert.AreEqual(0, result.Length);
}
[TestMethod]
public void CompileArithmeticOperations()
{
CompileBytecode("add", Bytecodes.Add);
CompileBytecode("subtract", Bytecodes.Subtract);
CompileBytecode("multiply", Bytecodes.Multiply);
CompileBytecode("divide", Bytecodes.Divide);
}
[TestMethod]
public void CompileStopOperation()
{
CompileBytecode("stop", Bytecodes.Stop);
}
[TestMethod]
public void CompileStorageOperation()
{
CompileBytecode("sload", Bytecodes.SLoad);
CompileBytecode("sstore", Bytecodes.SStore);
}
[TestMethod]
public void CompileDup()
{
CompileBytecode("dup 1", Bytecodes.Dup1);
CompileBytecode("dup 2", Bytecodes.Dup2);
CompileBytecode("dup 3", Bytecodes.Dup3);
CompileBytecode("dup 4", Bytecodes.Dup4);
CompileBytecode("dup 5", Bytecodes.Dup5);
CompileBytecode("dup 6", Bytecodes.Dup6);
CompileBytecode("dup 7", Bytecodes.Dup7);
CompileBytecode("dup 8", Bytecodes.Dup8);
CompileBytecode("dup 9", Bytecodes.Dup9);
CompileBytecode("dup 10", Bytecodes.Dup10);
CompileBytecode("dup 11", Bytecodes.Dup11);
CompileBytecode("dup 12", Bytecodes.Dup12);
CompileBytecode("dup 13", Bytecodes.Dup13);
CompileBytecode("dup 14", Bytecodes.Dup14);
CompileBytecode("dup 15", Bytecodes.Dup15);
CompileBytecode("dup 16", Bytecodes.Dup16);
}
[TestMethod]
public void CompileSwap()
{
CompileBytecode("swap 1", Bytecodes.Swap1);
CompileBytecode("swap 2", Bytecodes.Swap2);
CompileBytecode("swap 3", Bytecodes.Swap3);
CompileBytecode("swap 4", Bytecodes.Swap4);
CompileBytecode("swap 5", Bytecodes.Swap5);
CompileBytecode("swap 6", Bytecodes.Swap6);
CompileBytecode("swap 7", Bytecodes.Swap7);
CompileBytecode("swap 8", Bytecodes.Swap8);
CompileBytecode("swap 9", Bytecodes.Swap9);
CompileBytecode("swap 10", Bytecodes.Swap10);
CompileBytecode("swap 11", Bytecodes.Swap11);
CompileBytecode("swap 12", Bytecodes.Swap12);
CompileBytecode("swap 13", Bytecodes.Swap13);
CompileBytecode("swap 14", Bytecodes.Swap14);
CompileBytecode("swap 15", Bytecodes.Swap15);
CompileBytecode("swap 16", Bytecodes.Swap16);
}
[TestMethod]
public void CompilePop()
{
CompileBytecode("pop", Bytecodes.Pop);
}
[TestMethod]
public void CompileLessThanGreaterThan()
{
CompileBytecode("lessthan", Bytecodes.LessThan);
CompileBytecode("greaterthan", Bytecodes.GreaterThan);
CompileBytecode("lt", Bytecodes.LessThan);
CompileBytecode("gt", Bytecodes.GreaterThan);
}
[TestMethod]
public void CompilePush()
{
CompileBytecode("push 0", Bytecodes.Push1, 0);
CompileBytecode("push 1", Bytecodes.Push1, 1);
CompileBytecode("push 256", Bytecodes.Push2, 1, 0);
}
[TestMethod]
public void CompileEqualIsZero()
{
CompileBytecode("equal", Bytecodes.Equal);
CompileBytecode("eq", Bytecodes.Equal);
CompileBytecode("iszero", Bytecodes.IsZero);
}
[TestMethod]
public void CompileSkippingCommentsAndEmptyLines()
{
CompileBytecode("add\n", Bytecodes.Add);
CompileBytecode("add\r\n", Bytecodes.Add);
CompileBytecode("add\r", Bytecodes.Add);
CompileBytecode("# comment\nadd\n", Bytecodes.Add);
CompileBytecode("\n\nadd # comment\n", Bytecodes.Add);
CompileBytecode("\r\n\r\nadd # comment\n", Bytecodes.Add);
CompileBytecode("\r\radd # comment\n", Bytecodes.Add);
}
[TestMethod]
public void CompileLogicalOperations()
{
CompileBytecode("and", Bytecodes.And);
CompileBytecode("or", Bytecodes.Or);
CompileBytecode("not", Bytecodes.Not);
CompileBytecode("xor", Bytecodes.Xor);
}
[TestMethod]
public void CompileStorageAccess()
{
CompileBytecode("sload", Bytecodes.SLoad);
CompileBytecode("sstore", Bytecodes.SStore);
}
[TestMethod]
public void CompileMemoryAccess()
{
CompileBytecode("mload", Bytecodes.MLoad);
CompileBytecode("mstore", Bytecodes.MStore);
CompileBytecode("mstore8", Bytecodes.MStore8);
}
[TestMethod]
public void CompileJump()
{
CompileBytecode("jump", Bytecodes.Jump);
}
[TestMethod]
public void CompileJumpI()
{
CompileBytecode("jumpi", Bytecodes.JumpI);
}
[TestMethod]
public void CompilePc()
{
CompileBytecode("pc", Bytecodes.Pc);
}
private static void CompileBytecode(string text, Bytecodes bc)
{
var compiler = new SimpleCompiler(text);
var result = compiler.Compile();
Assert.IsNotNull(result);
Assert.AreEqual(1, result.Length);
Assert.AreEqual((byte)bc, result[0]);
}
private static void CompileBytecode(string text, Bytecodes bc, params byte[] bytes)
{
var compiler = new SimpleCompiler(text);
var result = compiler.Compile();
Assert.IsNotNull(result);
Assert.AreEqual(1 + bytes.Length, result.Length);
Assert.AreEqual((byte)bc, result[0]);
for (int k = 0; k < bytes.Length; k++)
Assert.AreEqual(bytes[k], result[k + 1]);
}
}
}
| ajlopez/BlockchainSharp | Src/BlockchainSharp.Tests/Compilers/SimpleCompilerTests.cs | C# | mit | 7,021 |
/**
* Wheel, copyright (c) 2020 - present by Arno van der Vegt
* Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const $ = require('../../program/commands');
const errors = require('../errors');
const err = require('../errors').errors;
const t = require('../tokenizer/tokenizer');
const Objct = require('../types/Objct').Objct;
const Var = require('../types/Var');
const CompileRecord = require('./CompileRecord').CompileRecord;
exports.CompileObjct = class extends CompileRecord {
getDataType() {
let token = this._token;
let objct = new Objct(null, this.getNamespacedRecordName(token.lexeme), false, this._compiler.getNamespace()).setToken(token);
objct.setCompiler(this._compiler);
return objct;
}
addLinterItem(token) {
this._linter && this._linter.addObject(this._token);
}
compileExtends(iterator, dataType) {
let token = iterator.skipWhiteSpace().peek();
if (token.lexeme === t.LEXEME_EXTENDS) {
iterator.next();
iterator.skipWhiteSpace();
token = iterator.next();
if (token.cls !== t.TOKEN_IDENTIFIER) {
throw errors.createError(err.IDENTIFIER_EXPECTED, token, 'Identifier expected.');
}
let superObjct = this._scope.findIdentifier(token.lexeme);
if (!superObjct) {
throw errors.createError(err.UNDEFINED_IDENTIFIER, token, 'Undefined identifier.');
}
if (!(superObjct instanceof Objct)) {
throw errors.createError(err.OBJECT_TYPE_EXPECTED, token, 'Object type expected.');
}
dataType.extend(superObjct, this._compiler);
}
}
compileMethodTable(objct, methodTable) {
let compiler = this._compiler;
let program = this._program;
let methods = compiler.getUseInfo().getUseObjct(objct.getName());
// Move the self pointer to the pointer register...
program.addCommand($.CMD_SET, $.T_NUM_G, $.REG_PTR, $.T_NUM_L, 0);
// Get the methods from the super objects...
let superObjct = objct.getParentScope();
while (superObjct instanceof Objct) {
let superMethods = compiler.getUseInfo().getUseObjct(superObjct.getName());
for (let i = 0; i < superMethods; i++) {
methodTable.push(program.getLength());
program.addCommand($.CMD_SET, $.T_NUM_P, 0, $.T_NUM_C, 0);
}
superObjct = superObjct.getParentScope();
}
// Create the virtual method table...
for (let i = 0; i < methods; i++) {
methodTable.push(program.getLength());
// The offset relative to the self pointer and the method offset will be set when the main procedure is found!
program.addCommand($.CMD_SET, $.T_NUM_P, 0, $.T_NUM_C, 0);
}
program.addCommand($.CMD_RET, $.T_NUM_C, 0, 0, 0);
}
compile(iterator) {
let objct = super.compile(iterator);
let compiler = this._compiler;
compiler.getUseInfo().setUseObjct(objct.getName());
if (compiler.getPass() === 0) {
return;
}
let program = this._program;
let codeUsed = program.getCodeUsed();
let methodTable = [];
program.setCodeUsed(true);
objct
.setConstructorCodeOffset(program.getLength())
.setMethodTable(methodTable);
this.compileMethodTable(objct, methodTable);
program.addCommand($.CMD_RET, 0, 0, 0, 0);
program.setCodeUsed(codeUsed);
}
};
| ArnoVanDerVegt/wheel | js/frontend/compiler/keyword/CompileObjct.js | JavaScript | mit | 3,710 |
"""Transformation functions for expressions."""
from tt.expressions import BooleanExpression
from tt.transformations.utils import ensure_bexpr
def apply_de_morgans(expr):
"""Convert an expression to a form with De Morgan's Law applied.
:returns: A new expression object, transformed so that De Morgan's Law has
been applied to negated *ANDs* and *ORs*.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a couple of simple examples showing De Morgan's Law being applied
to a negated AND and a negated OR::
>>> from tt import apply_de_morgans
>>> apply_de_morgans('~(A /\\ B)')
<BooleanExpression "~A \\/ ~B">
>>> apply_de_morgans('~(A \\/ B)')
<BooleanExpression "~A /\\ ~B">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.apply_de_morgans())
def apply_identity_law(expr):
"""Convert an expression to a form with the Identity Law applied.
It should be noted that this transformation will also annihilate terms
when possible. One such case where this would be applicable is the
expression ``A and 0``, which would be transformed to the constant value
``0``.
:returns: A new expression object, transformed so that the Identity Law
has been applied to applicable *ANDs* and *ORs*.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here are a few simple examples showing the behavior of this transformation
across all two-operand scenarios::
>>> from tt import apply_identity_law
>>> apply_identity_law('A and 1')
<BooleanExpression "A">
>>> apply_identity_law('A and 0')
<BooleanExpression "0">
>>> apply_identity_law('A or 0')
<BooleanExpression "A">
>>> apply_identity_law('A or 1')
<BooleanExpression "1">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.apply_identity_law())
def apply_idempotent_law(expr):
"""Convert an expression to a form with the Idempotent Law applied.
:returns: A new expression object, transformed so that the Idempotent Law
has been applied to applicable clauses.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid data type.
This transformation will apply the Idempotent Law to clauses of *AND* and
*OR* operators containing redundant operands. Here are a couple of simple
examples::
>>> from tt import apply_idempotent_law
>>> apply_idempotent_law('A and A')
<BooleanExpression "A">
>>> apply_idempotent_law('B or B')
<BooleanExpression "B">
This transformation will consider similarly-negated operands to be
redundant; for example::
>>> from tt import apply_idempotent_law
>>> apply_idempotent_law('~A and ~~~A')
<BooleanExpression "~A">
>>> apply_idempotent_law('B or ~B or ~~B or ~~~B or ~~~~B or ~~~~~B')
<BooleanExpression "B or ~B">
Let's also take a quick look at this transformation's ability to prune
redundant operands from CNF and DNF clauses::
>>> from tt import apply_idempotent_law
>>> apply_idempotent_law('(A and B and C and C and B) or (A and A)')
<BooleanExpression "(A and B and C) or A">
Of important note is that this transformation will not recursively apply
the Idempotent Law to operands that bubble up. Here's an example
illustrating this case::
>>> from tt import apply_idempotent_law
>>> apply_idempotent_law('(A or A) and (A or A)')
<BooleanExpression "A and A">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.apply_idempotent_law())
def apply_inverse_law(expr):
"""Convert an expression to a form with the Inverse Law applied.
:returns: A new expression object, transformed so that the Inverse Law
has been applied to applicable *ANDs* and *ORs*.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
This transformation will apply the Identity Law to simple binary
expressions consisting of negated and non-negated forms of the same
operand. Let's take a look::
>>> from tt.transformations import apply_inverse_law
>>> apply_inverse_law('A and ~A')
<BooleanExpression "0">
>>> apply_inverse_law('A or B or ~B or C')
<BooleanExpression "1">
This transformation will also apply the behavior expected of the Inverse
Law when negated and non-negated forms of the same operand appear in the
same CNF or DNF clause in an expression::
>>> from tt.transformations import apply_inverse_law
>>> apply_inverse_law('(A or B or ~A) -> (C and ~C)')
<BooleanExpression "1 -> 0">
>>> apply_inverse_law('(A or !!!A) xor (not C or not not C)')
<BooleanExpression "1 xor 1">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.apply_inverse_law())
def coalesce_negations(expr):
"""Convert an expression to a form with all negations condensed.
:returns: A new expression object, transformed so that all "runs" of
logical *NOTs* are condensed into the minimal equivalent number.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a simple example showing the basic premise of this transformation::
>>> from tt import coalesce_negations
>>> coalesce_negations('~~A or ~B or ~~~C or ~~~~D')
<BooleanExpression "A or ~B or ~C or D">
This transformation works on more complex expressions, too::
>>> coalesce_negations('!!(A -> not not B) or ~(~(A xor B))')
<BooleanExpression "(A -> B) or (A xor B)">
It should be noted that this transformation will also apply negations
to constant operands, as well. The behavior for this functionality is as
follows::
>>> coalesce_negations('~0')
<BooleanExpression "1">
>>> coalesce_negations('~1')
<BooleanExpression "0">
>>> coalesce_negations('~~~0 -> ~1 -> not 1')
<BooleanExpression "1 -> 0 -> 0">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.coalesce_negations())
def distribute_ands(expr):
"""Convert an expression to distribute ANDs over ORed clauses.
:param expr: The expression to transform.
:type expr: :class:`str <python:str>` or :class:`BooleanExpression \
<tt.expressions.bexpr.BooleanExpression>`
:returns: A new expression object, transformed to distribute ANDs over ORed
clauses.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a couple of simple examples::
>>> from tt import distribute_ands
>>> distribute_ands('A and (B or C or D)')
<BooleanExpression "(A and B) or (A and C) or (A and D)">
>>> distribute_ands('(A or B) and C')
<BooleanExpression "(A and C) or (B and C)">
And an example involving distributing a sub-expression::
>>> distribute_ands('(A and B) and (C or D or E)')
<BooleanExpression "(A and B and C) or (A and B and D) or \
(A and B and E)">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.distribute_ands())
def distribute_ors(expr):
"""Convert an expression to distribute ORs over ANDed clauses.
:param expr: The expression to transform.
:type expr: :class:`str <python:str>` or :class:`BooleanExpression \
<tt.expressions.bexpr.BooleanExpression>`
:returns: A new expression object, transformed to distribute ORs over ANDed
clauses.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a couple of simple examples::
>>> from tt import distribute_ors
>>> distribute_ors('A or (B and C and D and E)')
<BooleanExpression "(A or B) and (A or C) and (A or D) and (A or E)">
>>> distribute_ors('(A and B) or C')
<BooleanExpression "(A or C) and (B or C)">
And an example involving distributing a sub-expression::
>>> distribute_ors('(A or B) or (C and D)')
<BooleanExpression "(A or B or C) and (A or B or D)">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.distribute_ors())
def to_cnf(expr):
"""Convert an expression to conjunctive normal form (CNF).
This transformation only guarantees to produce an equivalent form of the
passed expression in conjunctive normal form; the transformed expression
may be an inefficent representation of the passed expression.
:param expr: The expression to transform.
:type expr: :class:`str <python:str>` or :class:`BooleanExpression \
<tt.expressions.bexpr.BooleanExpression>`
:returns: A new expression object, transformed to be in CNF.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here are a few examples::
>>> from tt import to_cnf
>>> b = to_cnf('(A nor B) impl C')
>>> b
<BooleanExpression "A or B or C">
>>> b.is_cnf
True
>>> b = to_cnf(r'~(~(A /\\ B) /\\ C /\\ D)')
>>> b
<BooleanExpression "(A \\/ ~C \\/ ~D) /\\ (B \\/ ~C \\/ ~D)">
>>> b.is_cnf
True
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.to_cnf())
def to_primitives(expr):
"""Convert an expression to a form with only primitive operators.
All operators will be transformed equivalent form composed only of the
logical AND, OR,and NOT operators. Symbolic operators in the passed
expression will remain symbolic in the transformed expression and the same
applies for plain English operators.
:param expr: The expression to transform.
:type expr: :class:`str <python:str>` or :class:`BooleanExpression \
<tt.expressions.bexpr.BooleanExpression>`
:returns: A new expression object, transformed to contain only primitive
operators.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a simple transformation of exclusive-or::
>>> from tt import to_primitives
>>> to_primitives('A xor B')
<BooleanExpression "(A and not B) or (not A and B)">
And another example of if-and-only-if (using symbolic operators)::
>>> to_primitives('A <-> B')
<BooleanExpression "(A /\\ B) \\/ (~A /\\ ~B)">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.to_primitives())
| welchbj/tt | tt/transformations/bexpr.py | Python | mit | 11,265 |
const assert = require('assert');
const MockServer = require('../../../../lib/mockserver.js');
const CommandGlobals = require('../../../../lib/globals/commands.js');
const Nightwatch = require('../../../../lib/nightwatch.js');
describe('browser.getFirstElementChild', function(){
before(function(done) {
CommandGlobals.beforeEach.call(this, done);
});
after(function(done) {
CommandGlobals.afterEach.call(this, done);
});
it('.getFirstElementChild', function(done){
MockServer.addMock({
url: '/wd/hub/session/1352110219202/execute',
method: 'POST',
response: {
value: {
'ELEMENT': '1'
}
}
}, true);
this.client.api.getFirstElementChild('#weblogin', function callback(result){
assert.strictEqual(result.value.getId(), '1');
});
this.client.start(done);
});
it('.getFirstElementChild - no such element', function(done) {
MockServer.addMock({
url: '/wd/hub/session/1352110219202/elements',
method: 'POST',
postdata: {
using: 'css selector',
value: '#badDriver'
},
response: {
status: 0,
sessionId: '1352110219202',
value: [{
ELEMENT: '2'
}]
}
});
MockServer.addMock({
url: '/wd/hub/session/1352110219202/execute',
method: 'POST',
response: {
status: 0,
value: null
}
});
this.client.api.getFirstElementChild('#badDriver', function callback(result){
assert.strictEqual(result.value, null);
});
this.client.start(done);
});
it('.getFirstElementChild - webdriver protcol', function(done){
Nightwatch.initW3CClient({
silent: true,
output: false
}).then(client => {
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: {
'element-6066-11e4-a52e-4f735466cecf': 'f54dc0ef-c84f-424a-bad0-16fef6595a70'
}
}
}, true);
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: {
'element-6066-11e4-a52e-4f735466cecf': 'f54dc0ef-c84f-424a-bad0-16fef6595a70'
}
}
}, true);
client.api.getFirstElementChild('#webdriver', function(result) {
assert.ok(result.value);
assert.strictEqual(result.value.getId(), 'f54dc0ef-c84f-424a-bad0-16fef6595a70');
}).getFirstElementChild('#webdriver', function callback(result){
assert.ok(result.value);
assert.strictEqual(result.value.getId(), 'f54dc0ef-c84f-424a-bad0-16fef6595a70');
});
client.start(done);
});
});
it('.getFirstElementChild - webdriver protcol no such element', function(done){
Nightwatch.initW3CClient({
silent: true,
output: false
}).then(client => {
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: null
}
});
client.api.getFirstElementChild('#webdriver', function(result) {
assert.strictEqual(result.value, null);
});
client.start(done);
});
});
}); | nightwatchjs/nightwatch | test/src/api/commands/element/testGetFirstElementChild.js | JavaScript | mit | 3,229 |
#!/usr/bin/python2.7
#-*- coding: utf-8 -*-
import numpy as np
import gl
def testkf(input1,Q,R):
print gl.X_i_1
print gl.P_i_1
#rang(1,N) do not contain N
K_i = gl.P_i_1 / (gl.P_i_1 + R)
X_i = gl.X_i_1 + K_i * (input1 - gl.X_i_1)
P_i = gl.P_i_1 - K_i * gl.P_i_1 + Q
#print (X[i])
#Update
gl.P_i_1 = P_i
gl.X_i_1 = X_i
return X_i
| zharuosi/2017 | pythonNRC/modules/testkf.py | Python | mit | 379 |
using System;
using System.Collections.Generic;
using System.Text;
namespace Nucleo.Web.EventsManagement
{
public class ProviderErrorEvent : WebMonitoringEventBase
{
private const string EVENT_MESSAGE = "An error occurred within the provider '{0}', with an exception of: {1}";
private const int EVENT_CODE = 100101;
#region " Constructors "
public ProviderErrorEvent(Type providerType, object source, Exception ex)
: base(string.Format(EVENT_MESSAGE, providerType.FullName, ex.ToString()), source, EVENT_CODE) { }
#endregion
}
}
| brianmains/Nucleo.NET | src/Nucleo.Web/Web/EventsManagement/ProviderErrorEvent.cs | C# | mit | 550 |
version https://git-lfs.github.com/spec/v1
oid sha256:e63ec89c8bce1f67a79c0a8042e7ad0f2197f9bf615c88fd1ce36266c4050e1b
size 5126
| yogeshsaroya/new-cdnjs | ajax/libs/backbone.layoutmanager/0.7.0/backbone.layoutmanager.min.js | JavaScript | mit | 129 |
<?php
use Illuminate\Database\Seeder;
use App\System\System;
/**
* @author Setiadi, 20 Agustus 2017
*/
class RoleUserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('t_role_user')->delete();
DB::table('t_role_user')->insert([
[
'user_id' => 1,
'role_id' => 1,
'flg_default' => 'Y',
'create_datetime' => System::dateTime(),
'update_datetime' => System::dateTime(),
'create_user_id' => -99,
'update_user_id' => -99
],
[
'user_id' => 2,
'role_id' => 2,
'flg_default' => 'Y',
'create_datetime' => System::dateTime(),
'update_datetime' => System::dateTime(),
'create_user_id' => -99,
'update_user_id' => -99
]
]);
}
}
| setiadi01/Office-Attendance-System-Rest | database/seeds/RoleUserTableSeeder.php | PHP | mit | 917 |
class AndroidController < ApplicationController
def index
end
def create
app = RailsPushNotifications::GCMApp.new
app.gcm_key = params[:gcm_api_key]
app.save
if app.save
notif = app.notifications.build(
destinations: [params[:destination]],
data: { text: params[:message] }
)
if notif.save
app.push_notifications
notif.reload
flash[:notice] = "Notification successfully pushed through!. Results #{notif.results.success} succeded, #{notif.results.failed} failed"
redirect_to :android_index
else
flash.now[:error] = notif.errors.full_messages
render :index
end
else
flash.now[:error] = app.errors.full_messages
render :index
end
end
end
| calonso/rails_push_notifications_test | app/controllers/android_controller.rb | Ruby | mit | 776 |
module tsp {
export interface IDOMBinder {
attributes?: { [name: string]: string; };
contentEditable?: bool;
dynamicAttributes?: { [name: string]: { (el: IElX): string; }; };
dynamicClasses?: { [name: string]: { (el: IElX): bool; }; };
dynamicStyles?: { [name: string]: { (el: IElX): string; }; };
classes?: string[];
id?: string;
kids?: IRenderable[];
kidsGet? (el: IElX): IElX[];
styles?: { [name: string]: string; };
tag?: string;
//Inner Content - used if textGet is null
text?: string;
//Dynamic Inner Content
textGet? (el: IElX): string;
//child elements - used if kidsGet is null
toggleKidsOnParentClick?: bool;
collapsed?: bool;
dataContext?: any;
selectSettings?: ISelectBinder;
container?: any;
onNotifyAddedToDom? (el: IElX): any;
}
export interface IRenderable {
parentElement: IRenderable;
doRender(context: IRenderContext);
ID: string;
}
export interface IElX extends IRenderable {
bindInfo: IDOMBinder;
//parentElement: IElX;
//doRender(context: IRenderContext);
//ID: string;
el: HTMLElement;
kidElements: IElX[];
selected: bool;
_rendered: bool;
innerRender(settings: IRenderContextProps);
removeClass(className: string);
ensureClass(className: string);
}
export interface IRenderContext {
output: string;
elements: IElX[];
settings: IRenderContextProps;
}
export interface ISelectBinder {
//static
selected?: bool;
//dynamic
selectGet? (elX: IElX): bool;
selectSet? (elX: IElX, newVal: bool): void;
group?: string;
selClassName?: string;
partialSelClassName?: string;
unselClassName?: string;
conformWithParent?: bool;
}
export interface IListenForTopic {
topicName: string;
conditionForNotification? (tEvent: ITopicEvent): bool;
callback(tEvent: ITopicEvent): void;
/**
element extension listening for the event
*/
elX?: IElX;
elXID?: string;
}
export interface ITopicEvent extends IListenForTopic {
topicEvent: Event;
}
export interface IRenderContextProps {
targetDomID?: string;
targetDom?: HTMLElement;
}
} | bahrus/teaspoon | TypeStrictTests/Interface_ElX.ts | TypeScript | mit | 2,489 |
package ee.tuleva.onboarding.user.exception;
public class UserAlreadyAMemberException extends RuntimeException {
public UserAlreadyAMemberException(String message) {
super(message);
}
}
| TulevaEE/onboarding-service | src/main/java/ee/tuleva/onboarding/user/exception/UserAlreadyAMemberException.java | Java | mit | 196 |
namespace ImageGallery.Data.Common.Models
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public abstract class BaseModel<TKey> : IAuditInfo, IDeletableEntity
{
public DateTime CreatedOn { get; set; }
public DateTime? DeletedOn { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public TKey Id { get; set; }
[Index]
public bool IsDeleted { get; set; }
public DateTime? ModifiedOn { get; set; }
}
} | atanas-georgiev/ImageGallery | src/ImageGallery.Data.Common/Models/BaseModel{TKey}.cs | C# | mit | 581 |
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-laptop"></i> 한글제품 현재사용내역</h3>
</div>
</div>
<br/>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
목록
</header>
<table class="table table-striped table-advance table-hover">
<thead>
<tr>
<th scope="col">사용자</th>
<th scope="col">제품명</th>
<th scope="col">버전</th>
<th scope="col">제조사</th>
</tr>
</thead>
<tbody>
<?php
foreach ($use_hangul as $lt) {
?>
<tr>
<td>
<b><?php echo $lt->user_name; ?></b>
</td>
<td>
<?php echo $lt->product_number; ?>
</td>
<td>
<?php echo $lt->gian_num; ?>
</td>
<td>
<?php echo $lt->duration; ?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</section>
| jangmac/CodeIgniter | application/views/list/computational/using_soft/use_hangul.php | PHP | mit | 1,961 |
//-----------------------------------------
// Grunt configuration
//-----------------------------------------
module.exports = function(grunt) {
// Init config
grunt.initConfig({
// environment constant
ngconstant: {
options: {
space: ' ',
name: 'envConstant',
dest: 'public/js/envConstant.js'
},
dev: {
constants: {
ENV: {
appURI: 'http://localhost:3000/',
instagramClientId: 'yourDevClientId'
}
}
},
prod:{
constants: {
ENV: {
appURI: 'http://instalurker-andreavitali.rhcloud.com/',
instagramClientId: 'yourProdClientId'
}
}
}
},
// concat
concat: {
options: {
separator: ';' // useful for following uglify
},
app: {
src: 'public/js/**/*.js',
dest: 'public/instalurker.js'
},
vendor: {
src: ['public/vendor/jquery.min.js','public/vendor/angular.min.js','public/vendor/*.min.js'], // order is important!
dest: 'public/vendor.min.js'
}
},
// uglify (only app JS because vendor's are already minified)
uglify: {
options: {
mangle: false
},
app: {
src: 'public/instalurker.js',
dest: 'public/instalurker.min.js',
ext: '.min.js'
}
},
// CSS minification
cssmin: {
prod: {
files: {
'public/stylesheets/app.min.css' : ['public/stylesheets/app.css']
}
}
},
// Change index.html to use minified files
targethtml: {
prod: {
files: {
'public/index.html': 'public/index.html'
}
}
}
// SASS compilation made by IDE
});
// Load plugins
grunt.loadNpmTasks('grunt-ng-constant');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-targethtml');
// Dev task
grunt.registerTask('dev', ['ngconstant:dev']); // no
// Default (prod) task
grunt.registerTask('default', ['ngconstant:prod','concat:vendor','concat:app','uglify:app','cssmin','targethtml']);
}
| andreavitali/instalurker | gruntfile.js | JavaScript | mit | 2,712 |
<?php
namespace Smath\VentasBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Smath\VentasBundle\Entity\Pedido;
use Smath\VentasBundle\Form\PedidoType;
/**
* Pedido controller.
*
* @Route("/pedido")
*/
class PedidoController extends Controller
{
/**
* Lists all Pedido entities.
*
* @Route("/", name="pedido")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SmathVentasBundle:Pedido')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Lists all Pedido entities.
*
* @Route("/list", name="pedido_list")
* @Method("GET")
*/
public function listAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository('SmathVentasBundle:Pedido')->createQueryBuilder('p')
->add('select','p.id, p.fechaCreacion, p.fechaEntrega, pv.nombre as puntoVenta, e.nombre as empleado, c.razonSocial')
->leftJoin('p.puntoVenta','pv')
->leftJoin('pv.cliente', 'c')
->leftJoin('p.usuario','u')
->leftJoin('u.empleado','e');
$fields = array (
'id' => 'p.id',
'fechaCreacion' => 'p.fechaCreacion',
'fechaEntrega' => 'p.fechaEntrega',
'empleado' => 'empleado',
'puntoVenta' => 'puntoVenta',
'empleado' => 'e.nombre',
'cliente' => 'c.razonSocial',
);
$paginator = $this->get('knp_paginator');
$r = $this->get('smath_helpers')->jqGridJson($request, $em, $qb, $fields, $paginator);
$response = new Response();
return $response->setContent($r);
}
/**
* Creates a new Pedido entity.
*
* @Route("/", name="pedido_create")
* @Method("POST")
* @Template("SmathVentasBundle:Pedido:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Pedido();
$entity->setFechaCreacion(new \DateTime());
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('pedido_edit', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Creates a form to create a Pedido entity.
*
* @param Pedido $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Pedido $entity)
{
$form = $this->createForm(new PedidoType(), $entity, array(
'action' => $this->generateUrl('pedido_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Pedido entity.
*
* @Route("/new", name="pedido_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$entity = new Pedido();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Pedido entity.
*
* @Route("/{id}", name="pedido_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Pedido entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Pedido entity.
*
* @Route("/{id}/edit", name="pedido_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Pedido entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
'pedidoId' => $entity->getId()
);
}
/**
* Creates a form to edit a Pedido entity.
*
* @param Pedido $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Pedido $entity)
{
$form = $this->createForm(new PedidoType(), $entity, array(
'action' => $this->generateUrl('pedido_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Pedido entity.
*
* @Route("/{id}", name="pedido_update")
* @Method("PUT")
* @Template("SmathVentasBundle:Pedido:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Pedido entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('pedido'));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Pedido entity.
*
* @Route("/{id}", name="pedido_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Pedido entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('pedido'));
}
/**
* Creates a form to delete a Pedido 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('pedido_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
| rsuarezdeveloper/smath | src/Smath/VentasBundle/Controller/PedidoController.php | PHP | mit | 7,983 |
package com.backusnaurparser.helper;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* Runtime Exception thrown when something goes wrong with parsing the EBNF
* grammar. A reason is always given (automatically printed via every
* printStackTrace(...) permutation)
*
* @author Dominik Horn
*
*/
public class LanguageParseException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String reason;
public LanguageParseException() {
this("Unknown cause");
}
public LanguageParseException(String reason) {
this.reason = reason;
}
@Override
public void printStackTrace() {
super.printStackTrace();
System.err.println("\nReason: " + this.reason);
}
@Override
public void printStackTrace(PrintStream s) {
super.printStackTrace(s);
s.println("\nReason: " + this.reason);
}
@Override
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
s.print("\nReason: " + this.reason);
}
}
| DominikHorn/FormalLanguageParser | src/com/backusnaurparser/helper/LanguageParseException.java | Java | mit | 981 |
require 'spec_helper'
describe Skywriter::Resource::CloudFormation::Authentication do
it "is a Resource" do
expect(Skywriter::Resource::CloudFormation::Authentication.new('name')).to be_a(Skywriter::Resource)
end
describe "#as_json" do
it "allows the user to define the keyspace" do
resource = Skywriter::Resource::CloudFormation::Authentication.new(
'name',
Foo: {
access_key_id: 'some kind of key'
},
Bar: {
access_key_id: 'some other kind of key'
}
)
expect(resource.as_json).to eq(
{
'name' => {
'Type' => "AWS::CloudFormation::Authentication",
'Foo' => {
'accessKeyId' => 'some kind of key',
},
'Bar' => {
'accessKeyId' => 'some other kind of key',
},
'DependsOn' => [],
}
}
)
end
end
end
| otherinbox/skywriter | spec/skywriter/resource/cloud_formation/authentication_spec.rb | Ruby | mit | 937 |
/*!
* vue-i18n v9.0.0-beta.13
* (c) 2020 kazuya kawaguchi
* Released under the MIT License.
*/
import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue';
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const inBrowser = typeof window !== 'undefined';
let mark;
let measure;
{
const perf = inBrowser && window.performance;
if (perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures) {
mark = (tag) => perf.mark(tag);
measure = (name, startTag, endTag) => {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
};
}
}
const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
/* eslint-disable */
function format(message, ...args) {
if (args.length === 1 && isObject(args[0])) {
args = args[0];
}
if (!args || !args.hasOwnProperty) {
args = {};
}
return message.replace(RE_ARGS, (match, identifier) => {
return args.hasOwnProperty(identifier) ? args[identifier] : '';
});
}
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
/** @internal */
const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
/** @internal */
const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
/** @internal */
const friendlyJSONstringify = (json) => JSON.stringify(json)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/\u0027/g, '\\u0027');
const isNumber = (val) => typeof val === 'number' && isFinite(val);
const isDate = (val) => toTypeString(val) === '[object Date]';
const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
function warn(msg, err) {
if (typeof console !== 'undefined') {
const label = 'vue-i18n' ;
console.warn(`[${label}] ` + msg);
/* istanbul ignore if */
if (err) {
console.warn(err.stack);
}
}
}
let _globalThis;
const getGlobalThis = () => {
// prettier-ignore
return (_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {}));
};
function escapeHtml(rawText) {
return rawText
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/* eslint-enable */
/**
* Useful Utilites By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isBoolean = (val) => typeof val === 'boolean';
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
// for converting list and named values to displayed strings.
const toDisplayString = (val) => {
return val == null
? ''
: isArray(val) || (isPlainObject(val) && val.toString === objectToString)
? JSON.stringify(val, null, 2)
: String(val);
};
const RANGE = 2;
function generateCodeFrame(source, start = 0, end = source.length) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
if (j < 0 || j >= lines.length)
continue;
const line = j + 1;
res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1;
const length = Math.max(1, end > count ? lineLength - pad : end - start);
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
}
else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + '^'.repeat(length));
}
count += lineLength + 1;
}
}
break;
}
}
return res.join('\n');
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var env = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.hook = exports.target = exports.isBrowser = void 0;
exports.isBrowser = typeof navigator !== 'undefined';
exports.target = exports.isBrowser
? window
: typeof commonjsGlobal !== 'undefined'
? commonjsGlobal
: {};
exports.hook = exports.target.__VUE_DEVTOOLS_GLOBAL_HOOK__;
});
var _const = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiHookEvents = void 0;
var ApiHookEvents;
(function (ApiHookEvents) {
ApiHookEvents["SETUP_DEVTOOLS_PLUGIN"] = "devtools-plugin:setup";
})(ApiHookEvents = exports.ApiHookEvents || (exports.ApiHookEvents = {}));
});
var api = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var app = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var component = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var context = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var hooks = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hooks = void 0;
var Hooks;
(function (Hooks) {
Hooks["TRANSFORM_CALL"] = "transformCall";
Hooks["GET_APP_RECORD_NAME"] = "getAppRecordName";
Hooks["GET_APP_ROOT_INSTANCE"] = "getAppRootInstance";
Hooks["REGISTER_APPLICATION"] = "registerApplication";
Hooks["WALK_COMPONENT_TREE"] = "walkComponentTree";
Hooks["WALK_COMPONENT_PARENTS"] = "walkComponentParents";
Hooks["INSPECT_COMPONENT"] = "inspectComponent";
Hooks["GET_COMPONENT_BOUNDS"] = "getComponentBounds";
Hooks["GET_COMPONENT_NAME"] = "getComponentName";
Hooks["GET_ELEMENT_COMPONENT"] = "getElementComponent";
Hooks["GET_INSPECTOR_TREE"] = "getInspectorTree";
Hooks["GET_INSPECTOR_STATE"] = "getInspectorState";
})(Hooks = exports.Hooks || (exports.Hooks = {}));
});
var api$1 = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(api, exports);
__exportStar(app, exports);
__exportStar(component, exports);
__exportStar(context, exports);
__exportStar(hooks, exports);
});
var lib = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupDevtoolsPlugin = void 0;
__exportStar(api$1, exports);
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
if (env.hook) {
env.hook.emit(_const.ApiHookEvents.SETUP_DEVTOOLS_PLUGIN, pluginDescriptor, setupFn);
}
else {
const list = env.target.__VUE_DEVTOOLS_PLUGINS__ = env.target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn
});
}
}
exports.setupDevtoolsPlugin = setupDevtoolsPlugin;
});
const pathStateMachine = [];
pathStateMachine[0 /* BEFORE_PATH */] = {
["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[1 /* IN_PATH */] = {
["w" /* WORKSPACE */]: [1 /* IN_PATH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[2 /* BEFORE_IDENT */] = {
["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
};
pathStateMachine[3 /* IN_IDENT */] = {
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
};
pathStateMachine[4 /* IN_SUB_PATH */] = {
["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [
4 /* IN_SUB_PATH */,
2 /* INC_SUB_PATH_DEPTH */
],
["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
};
pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
};
pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
};
/**
* Check if an expression is a literal value.
*/
const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
return literalValueRE.test(exp);
}
/**
* Strip quotes from a string
*/
function stripQuotes(str) {
const a = str.charCodeAt(0);
const b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
}
/**
* Determine the type of a character in a keypath.
*/
function getPathCharType(ch) {
if (ch === undefined || ch === null) {
return "o" /* END_OF_FAIL */;
}
const code = ch.charCodeAt(0);
switch (code) {
case 0x5b: // [
case 0x5d: // ]
case 0x2e: // .
case 0x22: // "
case 0x27: // '
return ch;
case 0x5f: // _
case 0x24: // $
case 0x2d: // -
return "i" /* IDENT */;
case 0x09: // Tab (HT)
case 0x0a: // Newline (LF)
case 0x0d: // Return (CR)
case 0xa0: // No-break space (NBSP)
case 0xfeff: // Byte Order Mark (BOM)
case 0x2028: // Line Separator (LS)
case 0x2029: // Paragraph Separator (PS)
return "w" /* WORKSPACE */;
}
return "i" /* IDENT */;
}
/**
* Format a subPath, return its plain form if it is
* a literal string or number. Otherwise prepend the
* dynamic indicator (*).
*/
function formatSubPath(path) {
const trimmed = path.trim();
// invalid leading 0
if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
return false;
}
return isLiteral(trimmed)
? stripQuotes(trimmed)
: "*" /* ASTARISK */ + trimmed;
}
/**
* Parse a string path into an array of segments
*/
function parse(path) {
const keys = [];
let index = -1;
let mode = 0 /* BEFORE_PATH */;
let subPathDepth = 0;
let c;
let key; // eslint-disable-line
let newChar;
let type;
let transition;
let action;
let typeMap;
const actions = [];
actions[0 /* APPEND */] = () => {
if (key === undefined) {
key = newChar;
}
else {
key += newChar;
}
};
actions[1 /* PUSH */] = () => {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
actions[0 /* APPEND */]();
subPathDepth++;
};
actions[3 /* PUSH_SUB_PATH */] = () => {
if (subPathDepth > 0) {
subPathDepth--;
mode = 4 /* IN_SUB_PATH */;
actions[0 /* APPEND */]();
}
else {
subPathDepth = 0;
if (key === undefined) {
return false;
}
key = formatSubPath(key);
if (key === false) {
return false;
}
else {
actions[1 /* PUSH */]();
}
}
};
function maybeUnescapeQuote() {
const nextChar = path[index + 1];
if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
nextChar === "'" /* SINGLE_QUOTE */) ||
(mode === 6 /* IN_DOUBLE_QUOTE */ &&
nextChar === "\"" /* DOUBLE_QUOTE */)) {
index++;
newChar = '\\' + nextChar;
actions[0 /* APPEND */]();
return true;
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue;
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
// check parse error
if (transition === 8 /* ERROR */) {
return;
}
mode = transition[0];
if (transition[1] !== undefined) {
action = actions[transition[1]];
if (action) {
newChar = c;
if (action() === false) {
return;
}
}
}
// check parse finish
if (mode === 7 /* AFTER_PATH */) {
return keys;
}
}
}
// path token cache
const cache = new Map();
function resolveValue(obj, path) {
// check object
if (!isObject(obj)) {
return null;
}
// parse path
let hit = cache.get(path);
if (!hit) {
hit = parse(path);
if (hit) {
cache.set(path, hit);
}
}
// check hit
if (!hit) {
return null;
}
// resolve path value
const len = hit.length;
let last = obj;
let i = 0;
while (i < len) {
const val = last[hit[i]];
if (val === undefined) {
return null;
}
last = val;
i++;
}
return last;
}
const DEFAULT_MODIFIER = (str) => str;
const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
const DEFAULT_MESSAGE_DATA_TYPE = 'text';
const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
const DEFAULT_INTERPOLATE = toDisplayString;
function pluralDefault(choice, choicesLength) {
choice = Math.abs(choice);
if (choicesLength === 2) {
// prettier-ignore
return choice
? choice > 1
? 1
: 0
: 1;
}
return choice ? Math.min(choice, 2) : 0;
}
function getPluralIndex(options) {
// prettier-ignore
const index = isNumber(options.pluralIndex)
? options.pluralIndex
: -1;
// prettier-ignore
return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
? isNumber(options.named.count)
? options.named.count
: isNumber(options.named.n)
? options.named.n
: index
: index;
}
function normalizeNamed(pluralIndex, props) {
if (!props.count) {
props.count = pluralIndex;
}
if (!props.n) {
props.n = pluralIndex;
}
}
function createMessageContext(options = {}) {
const locale = options.locale;
const pluralIndex = getPluralIndex(options);
const pluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? options.pluralRules[locale]
: pluralDefault;
const orgPluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? pluralDefault
: undefined;
const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
const _list = options.list || [];
const list = (index) => _list[index];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _named = options.named || {};
isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
const named = (key) => _named[key];
// TODO: need to design resolve message function?
function message(key) {
// prettier-ignore
const msg = isFunction(options.messages)
? options.messages(key)
: isObject(options.messages)
? options.messages[key]
: false;
return !msg
? options.parent
? options.parent.message(key) // resolve from parent messages
: DEFAULT_MESSAGE
: msg;
}
const _modifier = (name) => options.modifiers
? options.modifiers[name]
: DEFAULT_MODIFIER;
const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
? options.processor.normalize
: DEFAULT_NORMALIZE;
const interpolate = isPlainObject(options.processor) &&
isFunction(options.processor.interpolate)
? options.processor.interpolate
: DEFAULT_INTERPOLATE;
const type = isPlainObject(options.processor) && isString(options.processor.type)
? options.processor.type
: DEFAULT_MESSAGE_DATA_TYPE;
const ctx = {
["list" /* LIST */]: list,
["named" /* NAMED */]: named,
["plural" /* PLURAL */]: plural,
["linked" /* LINKED */]: (key, modifier) => {
// TODO: should check `key`
const msg = message(key)(ctx);
return isString(modifier) ? _modifier(modifier)(msg) : msg;
},
["message" /* MESSAGE */]: message,
["type" /* TYPE */]: type,
["interpolate" /* INTERPOLATE */]: interpolate,
["normalize" /* NORMALIZE */]: normalize
};
return ctx;
}
/** @internal */
const errorMessages = {
// tokenizer error messages
[0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`,
[1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`,
[2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`,
[3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`,
[4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`,
[5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`,
[6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`,
[7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`,
[8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`,
[9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`,
// parser error messages
[10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`,
[11 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'`
};
/** @internal */
function createCompileError(code, loc, optinos = {}) {
const { domain, messages, args } = optinos;
const msg = format((messages || errorMessages)[code] || '', ...(args || []))
;
const error = new SyntaxError(String(msg));
error.code = code;
if (loc) {
error.location = loc;
}
error.domain = domain;
return error;
}
/** @internal */
function defaultOnError(error) {
throw error;
}
function createPosition(line, column, offset) {
return { line, column, offset };
}
function createLocation(start, end, source) {
const loc = { start, end };
if (source != null) {
loc.source = source;
}
return loc;
}
const CHAR_SP = ' ';
const CHAR_CR = '\r';
const CHAR_LF = '\n';
const CHAR_LS = String.fromCharCode(0x2028);
const CHAR_PS = String.fromCharCode(0x2029);
function createScanner(str) {
const _buf = str;
let _index = 0;
let _line = 1;
let _column = 1;
let _peekOffset = 0;
const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
const isLF = (index) => _buf[index] === CHAR_LF;
const isPS = (index) => _buf[index] === CHAR_PS;
const isLS = (index) => _buf[index] === CHAR_LS;
const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
const index = () => _index;
const line = () => _line;
const column = () => _column;
const peekOffset = () => _peekOffset;
const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
const currentChar = () => charAt(_index);
const currentPeek = () => charAt(_index + _peekOffset);
function next() {
_peekOffset = 0;
if (isLineEnd(_index)) {
_line++;
_column = 0;
}
if (isCRLF(_index)) {
_index++;
}
_index++;
_column++;
return _buf[_index];
}
function peek() {
if (isCRLF(_index + _peekOffset)) {
_peekOffset++;
}
_peekOffset++;
return _buf[_index + _peekOffset];
}
function reset() {
_index = 0;
_line = 1;
_column = 1;
_peekOffset = 0;
}
function resetPeek(offset = 0) {
_peekOffset = offset;
}
function skipToPeek() {
const target = _index + _peekOffset;
// eslint-disable-next-line no-unmodified-loop-condition
while (target !== _index) {
next();
}
_peekOffset = 0;
}
return {
index,
line,
column,
peekOffset,
charAt,
currentChar,
currentPeek,
next,
peek,
reset,
resetPeek,
skipToPeek
};
}
const EOF = undefined;
const LITERAL_DELIMITER = "'";
const ERROR_DOMAIN = 'tokenizer';
function createTokenizer(source, options = {}) {
const location = !options.location;
const _scnr = createScanner(source);
const currentOffset = () => _scnr.index();
const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
const _initLoc = currentPosition();
const _initOffset = currentOffset();
const _context = {
currentType: 14 /* EOF */,
offset: _initOffset,
startLoc: _initLoc,
endLoc: _initLoc,
lastType: 14 /* EOF */,
lastOffset: _initOffset,
lastStartLoc: _initLoc,
lastEndLoc: _initLoc,
braceNest: 0,
inLinked: false,
text: ''
};
const context = () => _context;
const { onError } = options;
function emitError(code, pos, offset, ...args) {
const ctx = context();
pos.column += offset;
pos.offset += offset;
if (onError) {
const loc = createLocation(ctx.startLoc, pos);
const err = createCompileError(code, loc, {
domain: ERROR_DOMAIN,
args
});
onError(err);
}
}
function getToken(context, type, value) {
context.endLoc = currentPosition();
context.currentType = type;
const token = { type };
if (location) {
token.loc = createLocation(context.startLoc, context.endLoc);
}
if (value != null) {
token.value = value;
}
return token;
}
const getEndToken = (context) => getToken(context, 14 /* EOF */);
function eat(scnr, ch) {
if (scnr.currentChar() === ch) {
scnr.next();
return ch;
}
else {
emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch);
return '';
}
}
function peekSpaces(scnr) {
let buf = '';
while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
buf += scnr.currentPeek();
scnr.peek();
}
return buf;
}
function skipSpaces(scnr) {
const buf = peekSpaces(scnr);
scnr.skipToPeek();
return buf;
}
function isIdentifierStart(ch) {
if (ch === EOF) {
return false;
}
const cc = ch.charCodeAt(0);
return ((cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90)); // A-Z
}
function isNumberStart(ch) {
if (ch === EOF) {
return false;
}
const cc = ch.charCodeAt(0);
return cc >= 48 && cc <= 57; // 0-9
}
function isNamedIdentifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ret = isIdentifierStart(scnr.currentPeek());
scnr.resetPeek();
return ret;
}
function isListIdentifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
const ret = isNumberStart(ch);
scnr.resetPeek();
return ret;
}
function isLiteralStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === LITERAL_DELIMITER;
scnr.resetPeek();
return ret;
}
function isLinkedDotStart(scnr, context) {
const { currentType } = context;
if (currentType !== 8 /* LinkedAlias */) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === "." /* LinkedDot */;
scnr.resetPeek();
return ret;
}
function isLinkedModifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 9 /* LinkedDot */) {
return false;
}
peekSpaces(scnr);
const ret = isIdentifierStart(scnr.currentPeek());
scnr.resetPeek();
return ret;
}
function isLinkedDelimiterStart(scnr, context) {
const { currentType } = context;
if (!(currentType === 8 /* LinkedAlias */ ||
currentType === 12 /* LinkedModifier */)) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */;
scnr.resetPeek();
return ret;
}
function isLinkedReferStart(scnr, context) {
const { currentType } = context;
if (currentType !== 10 /* LinkedDelimiter */) {
return false;
}
const fn = () => {
const ch = scnr.currentPeek();
if (ch === "{" /* BraceLeft */) {
return isIdentifierStart(scnr.peek());
}
else if (ch === "@" /* LinkedAlias */ ||
ch === "%" /* Modulo */ ||
ch === "|" /* Pipe */ ||
ch === ":" /* LinkedDelimiter */ ||
ch === "." /* LinkedDot */ ||
ch === CHAR_SP ||
!ch) {
return false;
}
else if (ch === CHAR_LF) {
scnr.peek();
return fn();
}
else {
// other charactors
return isIdentifierStart(ch);
}
};
const ret = fn();
scnr.resetPeek();
return ret;
}
function isPluralStart(scnr) {
peekSpaces(scnr);
const ret = scnr.currentPeek() === "|" /* Pipe */;
scnr.resetPeek();
return ret;
}
function isTextStart(scnr, reset = true) {
const fn = (hasSpace = false, prev = '', detectModulo = false) => {
const ch = scnr.currentPeek();
if (ch === "{" /* BraceLeft */) {
return prev === "%" /* Modulo */ ? false : hasSpace;
}
else if (ch === "@" /* LinkedAlias */ || !ch) {
return prev === "%" /* Modulo */ ? true : hasSpace;
}
else if (ch === "%" /* Modulo */) {
scnr.peek();
return fn(hasSpace, "%" /* Modulo */, true);
}
else if (ch === "|" /* Pipe */) {
return prev === "%" /* Modulo */ || detectModulo
? true
: !(prev === CHAR_SP || prev === CHAR_LF);
}
else if (ch === CHAR_SP) {
scnr.peek();
return fn(true, CHAR_SP, detectModulo);
}
else if (ch === CHAR_LF) {
scnr.peek();
return fn(true, CHAR_LF, detectModulo);
}
else {
return true;
}
};
const ret = fn();
reset && scnr.resetPeek();
return ret;
}
function takeChar(scnr, fn) {
const ch = scnr.currentChar();
if (ch === EOF) {
return EOF;
}
if (fn(ch)) {
scnr.next();
return ch;
}
return null;
}
function takeIdentifierChar(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return ((cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90) || // A-Z
(cc >= 48 && cc <= 57) || // 0-9
cc === 95 ||
cc === 36); // _ $
};
return takeChar(scnr, closure);
}
function takeDigit(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return cc >= 48 && cc <= 57; // 0-9
};
return takeChar(scnr, closure);
}
function takeHexDigit(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return ((cc >= 48 && cc <= 57) || // 0-9
(cc >= 65 && cc <= 70) || // A-F
(cc >= 97 && cc <= 102)); // a-f
};
return takeChar(scnr, closure);
}
function getDigits(scnr) {
let ch = '';
let num = '';
while ((ch = takeDigit(scnr))) {
num += ch;
}
return num;
}
function readText(scnr) {
const fn = (buf) => {
const ch = scnr.currentChar();
if (ch === "{" /* BraceLeft */ ||
ch === "}" /* BraceRight */ ||
ch === "@" /* LinkedAlias */ ||
!ch) {
return buf;
}
else if (ch === "%" /* Modulo */) {
if (isTextStart(scnr)) {
buf += ch;
scnr.next();
return fn(buf);
}
else {
return buf;
}
}
else if (ch === "|" /* Pipe */) {
return buf;
}
else if (ch === CHAR_SP || ch === CHAR_LF) {
if (isTextStart(scnr)) {
buf += ch;
scnr.next();
return fn(buf);
}
else if (isPluralStart(scnr)) {
return buf;
}
else {
buf += ch;
scnr.next();
return fn(buf);
}
}
else {
buf += ch;
scnr.next();
return fn(buf);
}
};
return fn('');
}
function readNamedIdentifier(scnr) {
skipSpaces(scnr);
let ch = '';
let name = '';
while ((ch = takeIdentifierChar(scnr))) {
name += ch;
}
if (scnr.currentChar() === EOF) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
return name;
}
function readListIdentifier(scnr) {
skipSpaces(scnr);
let value = '';
if (scnr.currentChar() === '-') {
scnr.next();
value += `-${getDigits(scnr)}`;
}
else {
value += getDigits(scnr);
}
if (scnr.currentChar() === EOF) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
return value;
}
function readLiteral(scnr) {
skipSpaces(scnr);
eat(scnr, `\'`);
let ch = '';
let literal = '';
const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
while ((ch = takeChar(scnr, fn))) {
if (ch === '\\') {
literal += readEscapeSequence(scnr);
}
else {
literal += ch;
}
}
const current = scnr.currentChar();
if (current === CHAR_LF || current === EOF) {
emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0);
// TODO: Is it correct really?
if (current === CHAR_LF) {
scnr.next();
eat(scnr, `\'`);
}
return literal;
}
eat(scnr, `\'`);
return literal;
}
function readEscapeSequence(scnr) {
const ch = scnr.currentChar();
switch (ch) {
case '\\':
case `\'`:
scnr.next();
return `\\${ch}`;
case 'u':
return readUnicodeEscapeSequence(scnr, ch, 4);
case 'U':
return readUnicodeEscapeSequence(scnr, ch, 6);
default:
emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch);
return '';
}
}
function readUnicodeEscapeSequence(scnr, unicode, digits) {
eat(scnr, unicode);
let sequence = '';
for (let i = 0; i < digits; i++) {
const ch = takeHexDigit(scnr);
if (!ch) {
emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
break;
}
sequence += ch;
}
return `\\${unicode}${sequence}`;
}
function readInvalidIdentifier(scnr) {
skipSpaces(scnr);
let ch = '';
let identifiers = '';
const closure = (ch) => ch !== "{" /* BraceLeft */ &&
ch !== "}" /* BraceRight */ &&
ch !== CHAR_SP &&
ch !== CHAR_LF;
while ((ch = takeChar(scnr, closure))) {
identifiers += ch;
}
return identifiers;
}
function readLinkedModifier(scnr) {
let ch = '';
let name = '';
while ((ch = takeIdentifierChar(scnr))) {
name += ch;
}
return name;
}
function readLinkedRefer(scnr) {
const fn = (detect = false, buf) => {
const ch = scnr.currentChar();
if (ch === "{" /* BraceLeft */ ||
ch === "%" /* Modulo */ ||
ch === "@" /* LinkedAlias */ ||
ch === "|" /* Pipe */ ||
!ch) {
return buf;
}
else if (ch === CHAR_SP) {
return buf;
}
else if (ch === CHAR_LF) {
buf += ch;
scnr.next();
return fn(detect, buf);
}
else {
buf += ch;
scnr.next();
return fn(true, buf);
}
};
return fn(false, '');
}
function readPlural(scnr) {
skipSpaces(scnr);
const plural = eat(scnr, "|" /* Pipe */);
skipSpaces(scnr);
return plural;
}
// TODO: We need refactoring of token parsing ...
function readTokenInPlaceholder(scnr, context) {
let token = null;
const ch = scnr.currentChar();
switch (ch) {
case "{" /* BraceLeft */:
if (context.braceNest >= 1) {
emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0);
}
scnr.next();
token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */);
skipSpaces(scnr);
context.braceNest++;
return token;
case "}" /* BraceRight */:
if (context.braceNest > 0 &&
context.currentType === 2 /* BraceLeft */) {
emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0);
}
scnr.next();
token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
context.braceNest--;
context.braceNest > 0 && skipSpaces(scnr);
if (context.inLinked && context.braceNest === 0) {
context.inLinked = false;
}
return token;
case "@" /* LinkedAlias */:
if (context.braceNest > 0) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
token = readTokenInLinked(scnr, context) || getEndToken(context);
context.braceNest = 0;
return token;
default:
let validNamedIdentifier = true;
let validListIdentifier = true;
let validLeteral = true;
if (isPluralStart(scnr)) {
if (context.braceNest > 0) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (context.braceNest > 0 &&
(context.currentType === 5 /* Named */ ||
context.currentType === 6 /* List */ ||
context.currentType === 7 /* Literal */)) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
context.braceNest = 0;
return readToken(scnr, context);
}
if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr));
skipSpaces(scnr);
return token;
}
if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
token = getToken(context, 6 /* List */, readListIdentifier(scnr));
skipSpaces(scnr);
return token;
}
if ((validLeteral = isLiteralStart(scnr, context))) {
token = getToken(context, 7 /* Literal */, readLiteral(scnr));
skipSpaces(scnr);
return token;
}
if (!validNamedIdentifier && !validListIdentifier && !validLeteral) {
// TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr));
emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value);
skipSpaces(scnr);
return token;
}
break;
}
return token;
}
// TODO: We need refactoring of token parsing ...
function readTokenInLinked(scnr, context) {
const { currentType } = context;
let token = null;
const ch = scnr.currentChar();
if ((currentType === 8 /* LinkedAlias */ ||
currentType === 9 /* LinkedDot */ ||
currentType === 12 /* LinkedModifier */ ||
currentType === 10 /* LinkedDelimiter */) &&
(ch === CHAR_LF || ch === CHAR_SP)) {
emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
}
switch (ch) {
case "@" /* LinkedAlias */:
scnr.next();
token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */);
context.inLinked = true;
return token;
case "." /* LinkedDot */:
skipSpaces(scnr);
scnr.next();
return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */);
case ":" /* LinkedDelimiter */:
skipSpaces(scnr);
scnr.next();
return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */);
default:
if (isPluralStart(scnr)) {
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (isLinkedDotStart(scnr, context) ||
isLinkedDelimiterStart(scnr, context)) {
skipSpaces(scnr);
return readTokenInLinked(scnr, context);
}
if (isLinkedModifierStart(scnr, context)) {
skipSpaces(scnr);
return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr));
}
if (isLinkedReferStart(scnr, context)) {
skipSpaces(scnr);
if (ch === "{" /* BraceLeft */) {
// scan the placeholder
return readTokenInPlaceholder(scnr, context) || token;
}
else {
return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr));
}
}
if (currentType === 8 /* LinkedAlias */) {
emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
}
context.braceNest = 0;
context.inLinked = false;
return readToken(scnr, context);
}
}
// TODO: We need refactoring of token parsing ...
function readToken(scnr, context) {
let token = { type: 14 /* EOF */ };
if (context.braceNest > 0) {
return readTokenInPlaceholder(scnr, context) || getEndToken(context);
}
if (context.inLinked) {
return readTokenInLinked(scnr, context) || getEndToken(context);
}
const ch = scnr.currentChar();
switch (ch) {
case "{" /* BraceLeft */:
return readTokenInPlaceholder(scnr, context) || getEndToken(context);
case "}" /* BraceRight */:
emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0);
scnr.next();
return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
case "@" /* LinkedAlias */:
return readTokenInLinked(scnr, context) || getEndToken(context);
default:
if (isPluralStart(scnr)) {
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (isTextStart(scnr)) {
return getToken(context, 0 /* Text */, readText(scnr));
}
if (ch === "%" /* Modulo */) {
scnr.next();
return getToken(context, 4 /* Modulo */, "%" /* Modulo */);
}
break;
}
return token;
}
function nextToken() {
const { currentType, offset, startLoc, endLoc } = _context;
_context.lastType = currentType;
_context.lastOffset = offset;
_context.lastStartLoc = startLoc;
_context.lastEndLoc = endLoc;
_context.offset = currentOffset();
_context.startLoc = currentPosition();
if (_scnr.currentChar() === EOF) {
return getToken(_context, 14 /* EOF */);
}
return readToken(_scnr, _context);
}
return {
nextToken,
currentOffset,
currentPosition,
context
};
}
const ERROR_DOMAIN$1 = 'parser';
// Backslash backslash, backslash quote, uHHHH, UHHHHHH.
const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
function fromEscapeSequence(match, codePoint4, codePoint6) {
switch (match) {
case `\\\\`:
return `\\`;
case `\\\'`:
return `\'`;
default: {
const codePoint = parseInt(codePoint4 || codePoint6, 16);
if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
return String.fromCodePoint(codePoint);
}
// invalid ...
// Replace them with U+FFFD REPLACEMENT CHARACTER.
return '�';
}
}
}
function createParser(options = {}) {
const location = !options.location;
const { onError } = options;
function emitError(tokenzer, code, start, offset, ...args) {
const end = tokenzer.currentPosition();
end.offset += offset;
end.column += offset;
if (onError) {
const loc = createLocation(start, end);
const err = createCompileError(code, loc, {
domain: ERROR_DOMAIN$1,
args
});
onError(err);
}
}
function startNode(type, offset, loc) {
const node = {
type,
start: offset,
end: offset
};
if (location) {
node.loc = { start: loc, end: loc };
}
return node;
}
function endNode(node, offset, pos, type) {
node.end = offset;
if (type) {
node.type = type;
}
if (location && node.loc) {
node.loc.end = pos;
}
}
function parseText(tokenizer, value) {
const context = tokenizer.context();
const node = startNode(3 /* Text */, context.offset, context.startLoc);
node.value = value;
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseList(tokenizer, index) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(5 /* List */, offset, loc);
node.index = parseInt(index, 10);
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseNamed(tokenizer, key) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(4 /* Named */, offset, loc);
node.key = key;
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLiteral(tokenizer, value) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(9 /* Literal */, offset, loc);
node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinkedModifier(tokenizer) {
const token = tokenizer.nextToken();
const context = tokenizer.context();
// check token
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
const node = startNode(8 /* LinkedModifier */, offset, loc);
node.value = token.value || '';
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinkedKey(tokenizer, value) {
const context = tokenizer.context();
const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc);
node.value = value;
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinked(tokenizer) {
const context = tokenizer.context();
const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc);
let token = tokenizer.nextToken();
if (token.type === 9 /* LinkedDot */) {
linkedNode.modifier = parseLinkedModifier(tokenizer);
token = tokenizer.nextToken();
}
// asset check token
if (token.type !== 10 /* LinkedDelimiter */) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
token = tokenizer.nextToken();
// skip brace left
if (token.type === 2 /* BraceLeft */) {
token = tokenizer.nextToken();
}
switch (token.type) {
case 11 /* LinkedKey */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
break;
case 5 /* Named */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseNamed(tokenizer, token.value || '');
break;
case 6 /* List */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseList(tokenizer, token.value || '');
break;
case 7 /* Literal */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseLiteral(tokenizer, token.value || '');
break;
}
endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
return linkedNode;
}
function parseMessage(tokenizer) {
const context = tokenizer.context();
const startOffset = context.currentType === 1 /* Pipe */
? tokenizer.currentOffset()
: context.offset;
const startLoc = context.currentType === 1 /* Pipe */
? context.endLoc
: context.startLoc;
const node = startNode(2 /* Message */, startOffset, startLoc);
node.items = [];
do {
const token = tokenizer.nextToken();
switch (token.type) {
case 0 /* Text */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseText(tokenizer, token.value || ''));
break;
case 6 /* List */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseList(tokenizer, token.value || ''));
break;
case 5 /* Named */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseNamed(tokenizer, token.value || ''));
break;
case 7 /* Literal */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseLiteral(tokenizer, token.value || ''));
break;
case 8 /* LinkedAlias */:
node.items.push(parseLinked(tokenizer));
break;
}
} while (context.currentType !== 14 /* EOF */ &&
context.currentType !== 1 /* Pipe */);
// adjust message node loc
const endOffset = context.currentType === 1 /* Pipe */
? context.lastOffset
: tokenizer.currentOffset();
const endLoc = context.currentType === 1 /* Pipe */
? context.lastEndLoc
: tokenizer.currentPosition();
endNode(node, endOffset, endLoc);
return node;
}
function parsePlural(tokenizer, offset, loc, msgNode) {
const context = tokenizer.context();
let hasEmptyMessage = msgNode.items.length === 0;
const node = startNode(1 /* Plural */, offset, loc);
node.cases = [];
node.cases.push(msgNode);
do {
const msg = parseMessage(tokenizer);
if (!hasEmptyMessage) {
hasEmptyMessage = msg.items.length === 0;
}
node.cases.push(msg);
} while (context.currentType !== 14 /* EOF */);
if (hasEmptyMessage) {
emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0);
}
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseResource(tokenizer) {
const context = tokenizer.context();
const { offset, startLoc } = context;
const msgNode = parseMessage(tokenizer);
if (context.currentType === 14 /* EOF */) {
return msgNode;
}
else {
return parsePlural(tokenizer, offset, startLoc, msgNode);
}
}
function parse(source) {
const tokenizer = createTokenizer(source, { ...options });
const context = tokenizer.context();
const node = startNode(0 /* Resource */, context.offset, context.startLoc);
if (location && node.loc) {
node.loc.source = source;
}
node.body = parseResource(tokenizer);
// assert wheather achieved to EOF
if (context.currentType !== 14 /* EOF */) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, context.currentType);
}
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
return { parse };
}
function createTransformer(ast, options = {} // eslint-disable-line
) {
const _context = {
ast,
helpers: new Set()
};
const context = () => _context;
const helper = (name) => {
_context.helpers.add(name);
return name;
};
return { context, helper };
}
function traverseNodes(nodes, transformer) {
for (let i = 0; i < nodes.length; i++) {
traverseNode(nodes[i], transformer);
}
}
function traverseNode(node, transformer) {
// TODO: if we need pre-hook of transform, should be implemeted to here
switch (node.type) {
case 1 /* Plural */:
traverseNodes(node.cases, transformer);
transformer.helper("plural" /* PLURAL */);
break;
case 2 /* Message */:
traverseNodes(node.items, transformer);
break;
case 6 /* Linked */:
const linked = node;
traverseNode(linked.key, transformer);
transformer.helper("linked" /* LINKED */);
break;
case 5 /* List */:
transformer.helper("interpolate" /* INTERPOLATE */);
transformer.helper("list" /* LIST */);
break;
case 4 /* Named */:
transformer.helper("interpolate" /* INTERPOLATE */);
transformer.helper("named" /* NAMED */);
break;
}
// TODO: if we need post-hook of transform, should be implemeted to here
}
// transform AST
function transform(ast, options = {} // eslint-disable-line
) {
const transformer = createTransformer(ast);
transformer.helper("normalize" /* NORMALIZE */);
// traverse
ast.body && traverseNode(ast.body, transformer);
// set meta information
const context = transformer.context();
ast.helpers = [...context.helpers];
}
function createCodeGenerator(ast, options) {
const { sourceMap, filename } = options;
const _context = {
source: ast.loc.source,
filename,
code: '',
column: 1,
line: 1,
offset: 0,
map: undefined,
indentLevel: 0
};
const context = () => _context;
function push(code, node) {
_context.code += code;
}
function _newline(n) {
push('\n' + ` `.repeat(n));
}
function indent() {
_newline(++_context.indentLevel);
}
function deindent(withoutNewLine) {
if (withoutNewLine) {
--_context.indentLevel;
}
else {
_newline(--_context.indentLevel);
}
}
function newline() {
_newline(_context.indentLevel);
}
const helper = (key) => `_${key}`;
return {
context,
push,
indent,
deindent,
newline,
helper
};
}
function generateLinkedNode(generator, node) {
const { helper } = generator;
generator.push(`${helper("linked" /* LINKED */)}(`);
generateNode(generator, node.key);
if (node.modifier) {
generator.push(`, `);
generateNode(generator, node.modifier);
}
generator.push(`)`);
}
function generateMessageNode(generator, node) {
const { helper } = generator;
generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
generator.indent();
const length = node.items.length;
for (let i = 0; i < length; i++) {
generateNode(generator, node.items[i]);
if (i === length - 1) {
break;
}
generator.push(', ');
}
generator.deindent();
generator.push('])');
}
function generatePluralNode(generator, node) {
const { helper } = generator;
if (node.cases.length > 1) {
generator.push(`${helper("plural" /* PLURAL */)}([`);
generator.indent();
const length = node.cases.length;
for (let i = 0; i < length; i++) {
generateNode(generator, node.cases[i]);
if (i === length - 1) {
break;
}
generator.push(', ');
}
generator.deindent();
generator.push(`])`);
}
}
function generateResource(generator, node) {
if (node.body) {
generateNode(generator, node.body);
}
else {
generator.push('null');
}
}
function generateNode(generator, node) {
const { helper } = generator;
switch (node.type) {
case 0 /* Resource */:
generateResource(generator, node);
break;
case 1 /* Plural */:
generatePluralNode(generator, node);
break;
case 2 /* Message */:
generateMessageNode(generator, node);
break;
case 6 /* Linked */:
generateLinkedNode(generator, node);
break;
case 8 /* LinkedModifier */:
generator.push(JSON.stringify(node.value), node);
break;
case 7 /* LinkedKey */:
generator.push(JSON.stringify(node.value), node);
break;
case 5 /* List */:
generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
break;
case 4 /* Named */:
generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
break;
case 9 /* Literal */:
generator.push(JSON.stringify(node.value), node);
break;
case 3 /* Text */:
generator.push(JSON.stringify(node.value), node);
break;
default:
{
throw new Error(`unhandled codegen node type: ${node.type}`);
}
}
}
// generate code from AST
const generate = (ast, options = {} // eslint-disable-line
) => {
const mode = isString(options.mode) ? options.mode : 'normal';
const filename = isString(options.filename)
? options.filename
: 'message.intl';
const sourceMap = isBoolean(options.sourceMap) ? options.sourceMap : false;
const helpers = ast.helpers || [];
const generator = createCodeGenerator(ast, { mode, filename, sourceMap });
generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
generator.indent();
if (helpers.length > 0) {
generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
generator.newline();
}
generator.push(`return `);
generateNode(generator, ast);
generator.deindent();
generator.push(`}`);
const { code, map } = generator.context();
return {
ast,
code,
map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
};
};
function baseCompile(source, options = {}) {
// parse source codes
const parser = createParser({ ...options });
const ast = parser.parse(source);
// transform ASTs
transform(ast, { ...options });
// generate javascript codes
return generate(ast, { ...options });
}
/** @internal */
const warnMessages = {
[0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
[1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
[2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
[3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
[4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
[5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
};
/** @internal */
function getWarnMessage(code, ...args) {
return format(warnMessages[code], ...args);
}
/** @internal */
const NOT_REOSLVED = -1;
/** @internal */
const MISSING_RESOLVE_VALUE = '';
function getDefaultLinkedModifiers() {
return {
upper: (val) => (isString(val) ? val.toUpperCase() : val),
lower: (val) => (isString(val) ? val.toLowerCase() : val),
// prettier-ignore
capitalize: (val) => (isString(val)
? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
: val)
};
}
let _compiler;
/** @internal */
function registerMessageCompiler(compiler) {
_compiler = compiler;
}
/** @internal */
function createCoreContext(options = {}) {
// setup options
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
isString(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const messages = isPlainObject(options.messages)
? options.messages
: { [locale]: {} };
const datetimeFormats = isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [locale]: {} };
const numberFormats = isPlainObject(options.numberFormats)
? options.numberFormats
: { [locale]: {} };
const modifiers = Object.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
const pluralRules = options.pluralRules || {};
const missing = isFunction(options.missing) ? options.missing : null;
const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
const fallbackFormat = !!options.fallbackFormat;
const unresolving = !!options.unresolving;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
const processor = isPlainObject(options.processor) ? options.processor : null;
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
const escapeParameter = !!options.escapeParameter;
const messageCompiler = isFunction(options.messageCompiler)
? options.messageCompiler
: _compiler;
const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
// setup internal options
const internalOptions = options;
const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
? internalOptions.__datetimeFormatters
: new Map();
const __numberFormatters = isObject(internalOptions.__numberFormatters)
? internalOptions.__numberFormatters
: new Map();
const context = {
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
modifiers,
pluralRules,
missing,
missingWarn,
fallbackWarn,
fallbackFormat,
unresolving,
postTranslation,
processor,
warnHtmlMessage,
escapeParameter,
messageCompiler,
onWarn,
__datetimeFormatters,
__numberFormatters
};
// for vue-devtools timeline event
{
context.__emitter =
internalOptions.__emitter != null ? internalOptions.__emitter : undefined;
}
return context;
}
/** @internal */
function isTranslateFallbackWarn(fallback, key) {
return fallback instanceof RegExp ? fallback.test(key) : fallback;
}
/** @internal */
function isTranslateMissingWarn(missing, key) {
return missing instanceof RegExp ? missing.test(key) : missing;
}
/** @internal */
function handleMissing(context, key, locale, missingWarn, type) {
const { missing, onWarn } = context;
// for vue-devtools timeline event
{
const emitter = context.__emitter;
if (emitter) {
emitter.emit("missing" /* MISSING */, {
locale,
key,
type
});
}
}
if (missing !== null) {
const ret = missing(context, locale, key, type);
return isString(ret) ? ret : key;
}
else {
if ( isTranslateMissingWarn(missingWarn, key)) {
onWarn(getWarnMessage(0 /* NOT_FOUND_KEY */, { key, locale }));
}
return key;
}
}
/** @internal */
function getLocaleChain(ctx, fallback, start = '') {
const context = ctx;
if (start === '') {
return [];
}
if (!context.__localeChainCache) {
context.__localeChainCache = new Map();
}
let chain = context.__localeChainCache.get(start);
if (!chain) {
chain = [];
// first block defined by start
let block = [start];
// while any intervening block found
while (isArray(block)) {
block = appendBlockToChain(chain, block, fallback);
}
// prettier-ignore
// last block defined by default
const defaults = isArray(fallback)
? fallback
: isPlainObject(fallback)
? fallback['default']
? fallback['default']
: null
: fallback;
// convert defaults to array
block = isString(defaults) ? [defaults] : defaults;
if (isArray(block)) {
appendBlockToChain(chain, block, false);
}
context.__localeChainCache.set(start, chain);
}
return chain;
}
function appendBlockToChain(chain, block, blocks) {
let follow = true;
for (let i = 0; i < block.length && isBoolean(follow); i++) {
const locale = block[i];
if (isString(locale)) {
follow = appendLocaleToChain(chain, block[i], blocks);
}
}
return follow;
}
function appendLocaleToChain(chain, locale, blocks) {
let follow;
const tokens = locale.split('-');
do {
const target = tokens.join('-');
follow = appendItemToChain(chain, target, blocks);
tokens.splice(-1, 1);
} while (tokens.length && follow === true);
return follow;
}
function appendItemToChain(chain, target, blocks) {
let follow = false;
if (!chain.includes(target)) {
follow = true;
if (target) {
follow = target[target.length - 1] !== '!';
const locale = target.replace(/!/g, '');
chain.push(locale);
if ((isArray(blocks) || isPlainObject(blocks)) &&
blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
follow = blocks[locale];
}
}
}
return follow;
}
/** @internal */
function updateFallbackLocale(ctx, locale, fallback) {
const context = ctx;
context.__localeChainCache = new Map();
getLocaleChain(ctx, fallback, locale);
}
const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
function checkHtmlMessage(source, options) {
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
warn(format(WARN_MESSAGE, { source }));
}
}
const defaultOnCacheKey = (source) => source;
let compileCache = Object.create(null);
/** @internal */
function compileToFunction(source, options = {}) {
{
// check HTML message
checkHtmlMessage(source, options);
// check caches
const onCacheKey = options.onCacheKey || defaultOnCacheKey;
const key = onCacheKey(source);
const cached = compileCache[key];
if (cached) {
return cached;
}
// compile error detecting
let occured = false;
const onError = options.onError || defaultOnError;
options.onError = (err) => {
occured = true;
onError(err);
};
// compile
const { code } = baseCompile(source, options);
// evaluate function
const msg = new Function(`return ${code}`)();
// if occured compile error, don't cache
return !occured ? (compileCache[key] = msg) : msg;
}
}
/** @internal */
function createCoreError(code) {
return createCompileError(code, null, { messages: errorMessages$1 } );
}
/** @internal */
const errorMessages$1 = {
[12 /* INVALID_ARGUMENT */]: 'Invalid arguments',
[13 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
'Make sure your Date represents a valid date.',
[14 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
};
const NOOP_MESSAGE_FUNCTION = () => '';
const isMessageFunction = (val) => isFunction(val);
// implementationo of `translate` function
/** @internal */
function translate(context, ...args) {
const { fallbackFormat, postTranslation, unresolving, fallbackLocale } = context;
const [key, options] = parseTranslateArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const escapeParameter = isBoolean(options.escapeParameter)
? options.escapeParameter
: context.escapeParameter;
// prettier-ignore
const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
? !isBoolean(options.default)
? options.default
: key
: fallbackFormat // default by `fallbackFormat` option
? key
: '';
const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
const locale = isString(options.locale) ? options.locale : context.locale;
// escape params
escapeParameter && escapeParams(options);
// resolve message format
// eslint-disable-next-line prefer-const
let [format, targetLocale, message] = resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn);
// if you use default message, set it as message format!
let cacheBaseKey = key;
if (!(isString(format) || isMessageFunction(format))) {
if (enableDefaultMsg) {
format = defaultMsgOrKey;
cacheBaseKey = format;
}
}
// checking message format and target locale
if (!(isString(format) || isMessageFunction(format)) ||
!isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
// setup compile error detecting
let occured = false;
const errorDetector = () => {
occured = true;
};
// compile message format
const msg = compileMessasgeFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector);
// if occured compile error, return the message format
if (occured) {
return format;
}
// evaluate message with context
const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
const msgContext = createMessageContext(ctxOptions);
const messaged = evaluateMessage(context, msg, msgContext);
// if use post translation option, procee it with handler
return postTranslation ? postTranslation(messaged) : messaged;
}
function escapeParams(options) {
if (isArray(options.list)) {
options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
}
else if (isObject(options.named)) {
Object.keys(options.named).forEach(key => {
if (isString(options.named[key])) {
options.named[key] = escapeHtml(options.named[key]);
}
});
}
}
function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
const { messages, onWarn } = context;
const locales = getLocaleChain(context, fallbackLocale, locale);
let message = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'translate';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(1 /* FALLBACK_TO_TRANSLATE */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
message =
messages[targetLocale] || {};
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-resolve-start';
endTag = 'intlify-message-resolve-end';
mark && mark(startTag);
}
if ((format = resolveValue(message, key)) === null) {
// if null, resolve with object key path
format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
}
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start && format) {
emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
type: "message-resolve" /* MESSAGE_RESOLVE */,
key,
message: format,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message resolve', startTag, endTag);
}
}
if (isString(format) || isFunction(format))
break;
const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
if (missingRet !== key) {
format = missingRet;
}
from = to;
}
return [format, targetLocale, message];
}
function compileMessasgeFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
const { messageCompiler, warnHtmlMessage } = context;
if (isMessageFunction(format)) {
const msg = format;
msg.locale = msg.locale || targetLocale;
msg.key = msg.key || key;
return msg;
}
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-compilation-start';
endTag = 'intlify-message-compilation-end';
mark && mark(startTag);
}
const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start) {
emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
type: "message-compilation" /* MESSAGE_COMPILATION */,
message: format,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message compilation', startTag, endTag);
}
}
msg.locale = targetLocale;
msg.key = key;
msg.source = format;
return msg;
}
function evaluateMessage(context, msg, msgCtx) {
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-evaluation-start';
endTag = 'intlify-message-evaluation-end';
mark && mark(startTag);
}
const messaged = msg(msgCtx);
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start) {
emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
type: "message-evaluation" /* MESSAGE_EVALUATION */,
value: messaged,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message evaluation', startTag, endTag);
}
}
return messaged;
}
/** @internal */
function parseTranslateArgs(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
if (!isString(arg1)) {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isString(arg2)) {
options.default = arg2;
}
else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
options.named = arg2;
}
else if (isArray(arg2)) {
options.list = arg2;
}
if (isNumber(arg3)) {
options.plural = arg3;
}
else if (isString(arg3)) {
options.default = arg3;
}
else if (isPlainObject(arg3)) {
Object.assign(options, arg3);
}
return [key, options];
}
function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
return {
warnHtmlMessage,
onError: (err) => {
errorDetector && errorDetector(err);
{
const message = `Message compilation error: ${err.message}`;
const codeFrame = err.location &&
generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
const emitter = context.__emitter;
if (emitter) {
emitter.emit("compile-error" /* COMPILE_ERROR */, {
message: source,
error: err.message,
start: err.location && err.location.start.offset,
end: err.location && err.location.end.offset
});
}
console.error(codeFrame ? `${message}\n${codeFrame}` : message);
}
},
onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
};
}
function getMessageContextOptions(context, locale, message, options) {
const { modifiers, pluralRules } = context;
const resolveMessage = (key) => {
const val = resolveValue(message, key);
if (isString(val)) {
let occured = false;
const errorDetector = () => {
occured = true;
};
const msg = compileMessasgeFormat(context, key, locale, val, key, errorDetector);
return !occured
? msg
: NOOP_MESSAGE_FUNCTION;
}
else if (isMessageFunction(val)) {
return val;
}
else {
// TODO: should be implemented warning message
return NOOP_MESSAGE_FUNCTION;
}
};
const ctxOptions = {
locale,
modifiers,
pluralRules,
messages: resolveMessage
};
if (context.processor) {
ctxOptions.processor = context.processor;
}
if (options.list) {
ctxOptions.list = options.list;
}
if (options.named) {
ctxOptions.named = options.named;
}
if (isNumber(options.plural)) {
ctxOptions.pluralIndex = options.plural;
}
return ctxOptions;
}
const intlDefined = typeof Intl !== 'undefined';
const Availabilities = {
dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
};
// implementation of `datetime` function
/** @internal */
function datetime(context, ...args) {
const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
const { __datetimeFormatters } = context;
if ( !Availabilities.dateTimeFormat) {
onWarn(getWarnMessage(4 /* CANNOT_FORMAT_DATE */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, orverrides] = parseDateTimeArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.DateTimeFormat(locale).format(value);
}
// resolve format
let datetimeFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'datetime format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(5 /* FALLBACK_TO_DATE_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
datetimeFormat =
datetimeFormats[targetLocale] || {};
format = datetimeFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(orverrides)) {
id = `${id}__${JSON.stringify(orverrides)}`;
}
let formatter = __datetimeFormatters.get(id);
if (!formatter) {
formatter = new Intl.DateTimeFormat(targetLocale, Object.assign({}, format, orverrides));
__datetimeFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseDateTimeArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let orverrides = {};
let value;
if (isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
throw createCoreError(14 /* INVALID_ISO_DATE_ARGUMENT */);
}
value = new Date(arg1);
try {
// This will fail if the date is not valid
value.toISOString();
}
catch (e) {
throw createCoreError(14 /* INVALID_ISO_DATE_ARGUMENT */);
}
}
else if (isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(13 /* INVALID_DATE_ARGUMENT */);
}
value = arg1;
}
else if (isNumber(arg1)) {
value = arg1;
}
else {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
orverrides = arg3;
}
if (isPlainObject(arg4)) {
orverrides = arg4;
}
return [options.key || '', value, options, orverrides];
}
/** @internal */
function clearDateTimeFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__datetimeFormatters.has(id)) {
continue;
}
context.__datetimeFormatters.delete(id);
}
}
// implementation of `number` function
/** @internal */
function number(context, ...args) {
const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
const { __numberFormatters } = context;
if ( !Availabilities.numberFormat) {
onWarn(getWarnMessage(2 /* CANNOT_FORMAT_NUMBER */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, orverrides] = parseNumberArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.NumberFormat(locale).format(value);
}
// resolve format
let numberFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'number format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
numberFormat =
numberFormats[targetLocale] || {};
format = numberFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(orverrides)) {
id = `${id}__${JSON.stringify(orverrides)}`;
}
let formatter = __numberFormatters.get(id);
if (!formatter) {
formatter = new Intl.NumberFormat(targetLocale, Object.assign({}, format, orverrides));
__numberFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseNumberArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let orverrides = {};
if (!isNumber(arg1)) {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
const value = arg1;
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
orverrides = arg3;
}
if (isPlainObject(arg4)) {
orverrides = arg4;
}
return [options.key || '', value, options, orverrides];
}
/** @internal */
function clearNumberFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__numberFormatters.has(id)) {
continue;
}
context.__numberFormatters.delete(id);
}
}
const DevToolsLabels = {
["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]: 'Vue I18n: Compile Errors',
["vue-i18n-missing" /* TIMELINE_MISSING */]: 'Vue I18n: Missing',
["vue-i18n-fallback" /* TIMELINE_FALLBACK */]: 'Vue I18n: Fallback',
["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]: 'Vue I18n: Performance'
};
const DevToolsPlaceholders = {
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
};
const DevToolsTimelineColors = {
["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]: 0xff0000,
["vue-i18n-missing" /* TIMELINE_MISSING */]: 0xffcd19,
["vue-i18n-fallback" /* TIMELINE_FALLBACK */]: 0xffcd19,
["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]: 0xffcd19
};
const DevToolsTimelineLayerMaps = {
["compile-error" /* COMPILE_ERROR */]: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */,
["missing" /* MISSING */]: "vue-i18n-missing" /* TIMELINE_MISSING */,
["fallback" /* FALBACK */]: "vue-i18n-fallback" /* TIMELINE_FALLBACK */,
["message-resolve" /* MESSAGE_RESOLVE */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
["message-compilation" /* MESSAGE_COMPILATION */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
["message-evaluation" /* MESSAGE_EVALUATION */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */
};
/**
* Event emitter, forked from the below:
* - original repository url: https://github.com/developit/mitt
* - code url: https://github.com/developit/mitt/blob/master/src/index.ts
* - author: Jason Miller (https://github.com/developit)
* - license: MIT
*/
/**
* Create a event emitter
*
* @returns An event emitter
*/
function createEmitter() {
const events = new Map();
const emitter = {
events,
on(event, handler) {
const handlers = events.get(event);
const added = handlers && handlers.push(handler);
if (!added) {
events.set(event, [handler]);
}
},
off(event, handler) {
const handlers = events.get(event);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
},
emit(event, payload) {
(events.get(event) || [])
.slice()
.map(handler => handler(payload));
(events.get('*') || [])
.slice()
.map(handler => handler(event, payload));
}
};
return emitter;
}
let devtools;
function setDevtoolsHook(hook) {
devtools = hook;
}
function devtoolsRegisterI18n(i18n, version) {
if (!devtools) {
return;
}
devtools.emit("intlify:register" /* REGISTER */, i18n, version);
}
let devtoolsApi;
async function enableDevTools(app, i18n) {
return new Promise((resolve, reject) => {
try {
lib.setupDevtoolsPlugin({
id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
label: DevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
app
}, api => {
devtoolsApi = api;
api.on.inspectComponent(payload => {
const componentInstance = payload.componentInstance;
if (componentInstance.vnode.el.__INTLIFY__ &&
payload.instanceData) {
inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__);
}
});
api.addInspector({
id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
label: DevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
icon: 'language',
treeFilterPlaceholder: DevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
});
api.on.getInspectorTree(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
registerScope(payload, i18n);
}
});
api.on.getInspectorState(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
inspectScope(payload, i18n);
}
});
api.addTimelineLayer({
id: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */,
label: DevToolsLabels["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */],
color: DevToolsTimelineColors["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]
});
api.addTimelineLayer({
id: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
label: DevToolsLabels["vue-i18n-performance" /* TIMELINE_PERFORMANCE */],
color: DevToolsTimelineColors["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]
});
api.addTimelineLayer({
id: "vue-i18n-missing" /* TIMELINE_MISSING */,
label: DevToolsLabels["vue-i18n-missing" /* TIMELINE_MISSING */],
color: DevToolsTimelineColors["vue-i18n-missing" /* TIMELINE_MISSING */]
});
api.addTimelineLayer({
id: "vue-i18n-fallback" /* TIMELINE_FALLBACK */,
label: DevToolsLabels["vue-i18n-fallback" /* TIMELINE_FALLBACK */],
color: DevToolsTimelineColors["vue-i18n-fallback" /* TIMELINE_FALLBACK */]
});
resolve(true);
});
}
catch (e) {
console.error(e);
reject(false);
}
});
}
function inspectComposer(instanceData, composer) {
const type = 'vue-i18n: composer properties';
instanceData.state.push({
type,
key: 'locale',
editable: false,
value: composer.locale.value
});
instanceData.state.push({
type,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
});
instanceData.state.push({
type,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
});
instanceData.state.push({
type,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
});
instanceData.state.push({
type,
key: 'messages',
editable: false,
value: composer.messages.value
});
instanceData.state.push({
type,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
});
instanceData.state.push({
type,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
});
}
function registerScope(payload, i18n) {
const children = [];
for (const [keyInstance, instance] of i18n.__instances) {
// prettier-ignore
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
const label = keyInstance.type.name ||
keyInstance.type.displayName ||
keyInstance.type.__file;
children.push({
id: composer.id.toString(),
label: `${label} Scope`
});
}
payload.rootNodes.push({
id: 'global',
label: 'Global Scope',
children
});
}
function inspectScope(payload, i18n) {
if (payload.nodeId === 'global') {
payload.state = makeScopeInspectState(i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer);
}
else {
const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === payload.nodeId);
if (instance) {
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
payload.state = makeScopeInspectState(composer);
}
}
}
function makeScopeInspectState(composer) {
const state = {};
const localeType = 'Locale related info';
const localeStates = [
{
type: localeType,
key: 'locale',
editable: false,
value: composer.locale.value
},
{
type: localeType,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
},
{
type: localeType,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
},
{
type: localeType,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
}
];
state[localeType] = localeStates;
const localeMessagesType = 'Locale messages info';
const localeMessagesStates = [
{
type: localeMessagesType,
key: 'messages',
editable: false,
value: composer.messages.value
}
];
state[localeMessagesType] = localeMessagesStates;
const datetimeFormatsType = 'Datetime formats info';
const datetimeFormatsStates = [
{
type: datetimeFormatsType,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
}
];
state[datetimeFormatsType] = datetimeFormatsStates;
const numberFormatsType = 'Datetime formats info';
const numberFormatsStates = [
{
type: numberFormatsType,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
}
];
state[numberFormatsType] = numberFormatsStates;
return state;
}
function addTimelineEvent(event, payload) {
if (devtoolsApi) {
devtoolsApi.addTimelineEvent({
layerId: DevToolsTimelineLayerMaps[event],
event: {
time: Date.now(),
meta: {},
data: payload || {}
}
});
}
}
/**
* Vue I18n Version
*
* @remarks
* Semver format. Same format as the package.json `version` field.
*
* @VueI18nGeneral
*/
const VERSION = '9.0.0-beta.13';
/**
* This is only called development env
* istanbul-ignore-next
*/
function initDev() {
const target = getGlobalThis();
target.__INTLIFY__ = true;
setDevtoolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
{
console.info(`You are running a development build of vue-i18n.\n` +
`Make sure to use the production build (*.prod.js) when deploying for production.`);
}
}
const warnMessages$1 = {
[6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
[7 /* NOT_SUPPORTED_PRESERVE */]: `Not supportted 'preserve'.`,
[8 /* NOT_SUPPORTED_FORMATTER */]: `Not supportted 'formatter'.`,
[9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supportted 'preserveDirectiveContent'.`,
[10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supportted 'getChoiceIndex'.`,
[11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
[12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
};
function getWarnMessage$1(code, ...args) {
return format(warnMessages$1[code], ...args);
}
function createI18nError(code, ...args) {
return createCompileError(code, null, { messages: errorMessages$2, args } );
}
const errorMessages$2 = {
[12 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
[13 /* INVALID_ARGUMENT */]: 'Invalid argument',
[14 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
[15 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
[20 /* UNEXPECTED_ERROR */]: 'Unexpected error',
[16 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
[17 /* REQUIRED_VALUE */]: `Required in value: {0}`,
[18 /* INVALID_VALUE */]: `Invalid value`,
[19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
};
/**
* Composer
*
* Composer is offered composable API for Vue 3
* This module is offered new style vue-i18n API
*/
const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
const DatetimePartsSymbol = makeSymbol('__datetimeParts');
const NumberPartsSymbol = makeSymbol('__numberParts');
const EnableEmitter = makeSymbol('__enableEmitter');
const DisableEmitter = makeSymbol('__disableEmitter');
let composerID = 0;
function defineCoreMissingHandler(missing) {
return ((ctx, locale, key, type) => {
return missing(locale, key, getCurrentInstance() || undefined, type);
});
}
function getLocaleMessages(locale, options) {
const { messages, __i18n } = options;
// prettier-ignore
const ret = isPlainObject(messages)
? messages
: isArray(__i18n)
? {}
: { [locale]: {} };
// merge locale messages of i18n custom block
if (isArray(__i18n)) {
__i18n.forEach(raw => {
deepCopy(isString(raw) ? JSON.parse(raw) : raw, ret);
});
return ret;
}
if (isFunction(__i18n)) {
const { functions } = __i18n();
addPreCompileMessages(ret, functions);
}
return ret;
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function deepCopy(source, destination) {
for (const key in source) {
if (hasOwn(source, key)) {
if (!isObject(source[key])) {
destination[key] = destination[key] != null ? destination[key] : {};
destination[key] = source[key];
}
else {
destination[key] = destination[key] != null ? destination[key] : {};
deepCopy(source[key], destination[key]);
}
}
}
}
function addPreCompileMessages(messages, functions) {
const keys = Object.keys(functions);
keys.forEach(key => {
const compiled = functions[key];
const { l, k } = JSON.parse(key);
if (!messages[l]) {
messages[l] = {};
}
const targetLocaleMessage = messages[l];
const paths = parse(k);
if (paths != null) {
const len = paths.length;
let last = targetLocaleMessage; // eslint-disable-line @typescript-eslint/no-explicit-any
let i = 0;
while (i < len) {
const path = paths[i];
if (i === len - 1) {
last[path] = compiled;
break;
}
else {
let val = last[path];
if (!val) {
last[path] = val = {};
}
last = val;
i++;
}
}
}
});
}
/**
* Create composer interface factory
*
* @internal
*/
function createComposer(options = {}) {
const { __root } = options;
const _isGlobal = __root === undefined;
let _inheritLocale = isBoolean(options.inheritLocale)
? options.inheritLocale
: true;
const _locale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.locale.value
: isString(options.locale)
? options.locale
: 'en-US');
const _fallbackLocale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.fallbackLocale.value
: isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: _locale.value);
const _messages = ref(getLocaleMessages(_locale.value, options));
const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [_locale.value]: {} });
const _numberFormats = ref(isPlainObject(options.numberFormats)
? options.numberFormats
: { [_locale.value]: {} });
// warning suppress options
// prettier-ignore
let _missingWarn = __root
? __root.missingWarn
: isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
// prettier-ignore
let _fallbackWarn = __root
? __root.fallbackWarn
: isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
let _fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
// configure fall bakck to root
let _fallbackFormat = !!options.fallbackFormat;
// runtime missing
let _missing = isFunction(options.missing) ? options.missing : null;
let _runtimeMissing = isFunction(options.missing)
? defineCoreMissingHandler(options.missing)
: null;
// postTranslation handler
let _postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
let _escapeParameter = !!options.escapeParameter;
// custom linked modifiers
// prettier-ignore
const _modifiers = __root
? __root.modifiers
: isPlainObject(options.modifiers)
? options.modifiers
: {};
// pluralRules
const _pluralRules = options.pluralRules;
// runtime context
// eslint-disable-next-line prefer-const
let _context;
function getCoreContext() {
return createCoreContext({
locale: _locale.value,
fallbackLocale: _fallbackLocale.value,
messages: _messages.value,
datetimeFormats: _datetimeFormats.value,
numberFormats: _numberFormats.value,
modifiers: _modifiers,
pluralRules: _pluralRules,
missing: _runtimeMissing === null ? undefined : _runtimeMissing,
missingWarn: _missingWarn,
fallbackWarn: _fallbackWarn,
fallbackFormat: _fallbackFormat,
unresolving: true,
postTranslation: _postTranslation === null ? undefined : _postTranslation,
warnHtmlMessage: _warnHtmlMessage,
escapeParameter: _escapeParameter,
__datetimeFormatters: isPlainObject(_context)
? _context.__datetimeFormatters
: undefined,
__numberFormatters: isPlainObject(_context)
? _context.__numberFormatters
: undefined,
__emitter: isPlainObject(_context)
? _context.__emitter
: undefined
});
}
_context = getCoreContext();
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
/*!
* define properties
*/
// locale
const locale = computed({
get: () => _locale.value,
set: val => {
_locale.value = val;
_context.locale = _locale.value;
}
});
// fallbackLocale
const fallbackLocale = computed({
get: () => _fallbackLocale.value,
set: val => {
_fallbackLocale.value = val;
_context.fallbackLocale = _fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, val);
}
});
// messages
const messages = computed(() => _messages.value);
// datetimeFormats
const datetimeFormats = computed(() => _datetimeFormats.value);
// numberFormats
const numberFormats = computed(() => _numberFormats.value);
/**
* define methods
*/
// getPostTranslationHandler
function getPostTranslationHandler() {
return isFunction(_postTranslation) ? _postTranslation : null;
}
// setPostTranslationHandler
function setPostTranslationHandler(handler) {
_postTranslation = handler;
_context.postTranslation = handler;
}
// getMissingHandler
function getMissingHandler() {
return _missing;
}
// setMissingHandler
function setMissingHandler(handler) {
if (handler !== null) {
_runtimeMissing = defineCoreMissingHandler(handler);
}
_missing = handler;
_context.missing = _runtimeMissing;
}
function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
const context = getCoreContext();
const ret = fn(context); // track reactive dependency, see the getRuntimeContext
if (isNumber(ret) && ret === NOT_REOSLVED) {
const key = argumentParser();
if ( _fallbackRoot && __root) {
warn(getWarnMessage$1(6 /* FALLBACK_TO_ROOT */, {
key,
type: warnType
}));
// for vue-devtools timeline event
{
const { __emitter: emitter } = context;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type: warnType,
key,
to: 'global'
});
}
}
}
return _fallbackRoot && __root
? fallbackSuccess(__root)
: fallbackFail(key);
}
else if (successCondition(ret)) {
return ret;
}
else {
/* istanbul ignore next */
throw createI18nError(12 /* UNEXPECTED_RETURN_TYPE */);
}
}
// t
function t(...args) {
return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args)[0], 'translate', root => root.t(...args), key => key, val => isString(val));
}
// d
function d(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// n
function n(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// for custom processor
function normalize(values) {
return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val);
}
const interpolate = (val) => val;
const processor = {
normalize,
interpolate,
type: 'vnode'
};
// __transrateVNode, using for `i18n-t` component
function __transrateVNode(...args) {
return wrapWithDeps(context => {
let ret;
const _context = context;
try {
_context.processor = processor;
ret = translate(_context, ...args);
}
finally {
_context.processor = null;
}
return ret;
}, () => parseTranslateArgs(...args)[0], 'translate',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));
}
// __numberParts, using for `i18n-n` component
function __numberParts(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// __datetimeParts, using for `i18n-d` component
function __datetimeParts(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// te
function te(key, locale) {
const targetLocale = isString(locale) ? locale : _locale.value;
const message = getLocaleMessage(targetLocale);
return resolveValue(message, key) !== null;
}
// tm
function tm(key) {
const messages = _messages.value[_locale.value] || {};
const target = resolveValue(messages, key);
// prettier-ignore
return target != null
? target
: __root
? __root.tm(key) || {}
: {};
}
// getLocaleMessage
function getLocaleMessage(locale) {
return (_messages.value[locale] || {});
}
// setLocaleMessage
function setLocaleMessage(locale, message) {
_messages.value[locale] = message;
_context.messages = _messages.value;
}
// mergeLocaleMessage
function mergeLocaleMessage(locale, message) {
_messages.value[locale] = Object.assign(_messages.value[locale] || {}, message);
_context.messages = _messages.value;
}
// getDateTimeFormat
function getDateTimeFormat(locale) {
return _datetimeFormats.value[locale] || {};
}
// setDateTimeFormat
function setDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = format;
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// mergeDateTimeFormat
function mergeDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = Object.assign(_datetimeFormats.value[locale] || {}, format);
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// getNumberFormat
function getNumberFormat(locale) {
return _numberFormats.value[locale] || {};
}
// setNumberFormat
function setNumberFormat(locale, format) {
_numberFormats.value[locale] = format;
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// mergeNumberFormat
function mergeNumberFormat(locale, format) {
_numberFormats.value[locale] = Object.assign(_numberFormats.value[locale] || {}, format);
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// for debug
composerID++;
// watch root locale & fallbackLocale
if (__root) {
watch(__root.locale, (val) => {
if (_inheritLocale) {
_locale.value = val;
_context.locale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
watch(__root.fallbackLocale, (val) => {
if (_inheritLocale) {
_fallbackLocale.value = val;
_context.fallbackLocale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
}
// export composition API!
const composer = {
// properties
id: composerID,
locale,
fallbackLocale,
get inheritLocale() {
return _inheritLocale;
},
set inheritLocale(val) {
_inheritLocale = val;
if (val && __root) {
_locale.value = __root.locale.value;
_fallbackLocale.value = __root.fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
},
get availableLocales() {
return Object.keys(_messages.value).sort();
},
messages,
datetimeFormats,
numberFormats,
get modifiers() {
return _modifiers;
},
get pluralRules() {
return _pluralRules || {};
},
get isGlobal() {
return _isGlobal;
},
get missingWarn() {
return _missingWarn;
},
set missingWarn(val) {
_missingWarn = val;
_context.missingWarn = _missingWarn;
},
get fallbackWarn() {
return _fallbackWarn;
},
set fallbackWarn(val) {
_fallbackWarn = val;
_context.fallbackWarn = _fallbackWarn;
},
get fallbackRoot() {
return _fallbackRoot;
},
set fallbackRoot(val) {
_fallbackRoot = val;
},
get fallbackFormat() {
return _fallbackFormat;
},
set fallbackFormat(val) {
_fallbackFormat = val;
_context.fallbackFormat = _fallbackFormat;
},
get warnHtmlMessage() {
return _warnHtmlMessage;
},
set warnHtmlMessage(val) {
_warnHtmlMessage = val;
_context.warnHtmlMessage = val;
},
get escapeParameter() {
return _escapeParameter;
},
set escapeParameter(val) {
_escapeParameter = val;
_context.escapeParameter = val;
},
// methods
t,
d,
n,
te,
tm,
getLocaleMessage,
setLocaleMessage,
mergeLocaleMessage,
getDateTimeFormat,
setDateTimeFormat,
mergeDateTimeFormat,
getNumberFormat,
setNumberFormat,
mergeNumberFormat,
getPostTranslationHandler,
setPostTranslationHandler,
getMissingHandler,
setMissingHandler,
[TransrateVNodeSymbol]: __transrateVNode,
[NumberPartsSymbol]: __numberParts,
[DatetimePartsSymbol]: __datetimeParts
};
// for vue-devtools timeline event
{
composer[EnableEmitter] = (emitter) => {
_context.__emitter = emitter;
};
composer[DisableEmitter] = () => {
_context.__emitter = undefined;
};
}
return composer;
}
/**
* Legacy
*
* This module is offered legacy vue-i18n API compatibility
*/
/**
* Convert to I18n Composer Options from VueI18n Options
*
* @internal
*/
function convertComposerOptions(options) {
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const missing = isFunction(options.missing) ? options.missing : undefined;
const missingWarn = isBoolean(options.silentTranslationWarn) ||
isRegExp(options.silentTranslationWarn)
? !options.silentTranslationWarn
: true;
const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
isRegExp(options.silentFallbackWarn)
? !options.silentFallbackWarn
: true;
const fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
const fallbackFormat = !!options.formatFallbackMessages;
const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
const pluralizationRules = options.pluralizationRules;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: undefined;
const warnHtmlMessage = isString(options.warnHtmlInMessage)
? options.warnHtmlInMessage !== 'off'
: true;
const escapeParameter = !!options.escapeParameterHtml;
const inheritLocale = isBoolean(options.sync) ? options.sync : true;
if ( options.formatter) {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
}
if ( options.preserveDirectiveContent) {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
}
let messages = options.messages;
if (isPlainObject(options.sharedMessages)) {
const sharedMessages = options.sharedMessages;
const locales = Object.keys(sharedMessages);
messages = locales.reduce((messages, locale) => {
const message = messages[locale] || (messages[locale] = {});
Object.assign(message, sharedMessages[locale]);
return messages;
}, (messages || {}));
}
const { __i18n, __root } = options;
const datetimeFormats = options.datetimeFormats;
const numberFormats = options.numberFormats;
return {
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
missing,
missingWarn,
fallbackWarn,
fallbackRoot,
fallbackFormat,
modifiers,
pluralRules: pluralizationRules,
postTranslation,
warnHtmlMessage,
escapeParameter,
inheritLocale,
__i18n,
__root
};
}
/**
* create VueI18n interface factory
*
* @internal
*/
function createVueI18n(options = {}) {
const composer = createComposer(convertComposerOptions(options));
// defines VueI18n
const vueI18n = {
/**
* properties
*/
// id
id: composer.id,
// locale
get locale() {
return composer.locale.value;
},
set locale(val) {
composer.locale.value = val;
},
// fallbackLocale
get fallbackLocale() {
return composer.fallbackLocale.value;
},
set fallbackLocale(val) {
composer.fallbackLocale.value = val;
},
// messages
get messages() {
return composer.messages.value;
},
// datetimeFormats
get datetimeFormats() {
return composer.datetimeFormats.value;
},
// numberFormats
get numberFormats() {
return composer.numberFormats.value;
},
// availableLocales
get availableLocales() {
return composer.availableLocales;
},
// formatter
get formatter() {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
// dummy
return {
interpolate() {
return [];
}
};
},
set formatter(val) {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
},
// missing
get missing() {
return composer.getMissingHandler();
},
set missing(handler) {
composer.setMissingHandler(handler);
},
// silentTranslationWarn
get silentTranslationWarn() {
return isBoolean(composer.missingWarn)
? !composer.missingWarn
: composer.missingWarn;
},
set silentTranslationWarn(val) {
composer.missingWarn = isBoolean(val) ? !val : val;
},
// silentFallbackWarn
get silentFallbackWarn() {
return isBoolean(composer.fallbackWarn)
? !composer.fallbackWarn
: composer.fallbackWarn;
},
set silentFallbackWarn(val) {
composer.fallbackWarn = isBoolean(val) ? !val : val;
},
// modifiers
get modifiers() {
return composer.modifiers;
},
// formatFallbackMessages
get formatFallbackMessages() {
return composer.fallbackFormat;
},
set formatFallbackMessages(val) {
composer.fallbackFormat = val;
},
// postTranslation
get postTranslation() {
return composer.getPostTranslationHandler();
},
set postTranslation(handler) {
composer.setPostTranslationHandler(handler);
},
// sync
get sync() {
return composer.inheritLocale;
},
set sync(val) {
composer.inheritLocale = val;
},
// warnInHtmlMessage
get warnHtmlInMessage() {
return composer.warnHtmlMessage ? 'warn' : 'off';
},
set warnHtmlInMessage(val) {
composer.warnHtmlMessage = val !== 'off';
},
// escapeParameterHtml
get escapeParameterHtml() {
return composer.escapeParameter;
},
set escapeParameterHtml(val) {
composer.escapeParameter = val;
},
// preserveDirectiveContent
get preserveDirectiveContent() {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
return true;
},
set preserveDirectiveContent(val) {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
},
// pluralizationRules
get pluralizationRules() {
return composer.pluralRules || {};
},
// for internal
__composer: composer,
/**
* methods
*/
// t
t(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(13 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// tc
tc(...args) {
const [arg1, arg2, arg3] = args;
const options = { plural: 1 };
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(13 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// te
te(key, locale) {
return composer.te(key, locale);
},
// tm
tm(key) {
return composer.tm(key);
},
// getLocaleMessage
getLocaleMessage(locale) {
return composer.getLocaleMessage(locale);
},
// setLocaleMessage
setLocaleMessage(locale, message) {
composer.setLocaleMessage(locale, message);
},
// mergeLocaleMessasge
mergeLocaleMessage(locale, message) {
composer.mergeLocaleMessage(locale, message);
},
// d
d(...args) {
return composer.d(...args);
},
// getDateTimeFormat
getDateTimeFormat(locale) {
return composer.getDateTimeFormat(locale);
},
// setDateTimeFormat
setDateTimeFormat(locale, format) {
composer.setDateTimeFormat(locale, format);
},
// mergeDateTimeFormat
mergeDateTimeFormat(locale, format) {
composer.mergeDateTimeFormat(locale, format);
},
// n
n(...args) {
return composer.n(...args);
},
// getNumberFormat
getNumberFormat(locale) {
return composer.getNumberFormat(locale);
},
// setNumberFormat
setNumberFormat(locale, format) {
composer.setNumberFormat(locale, format);
},
// mergeNumberFormat
mergeNumberFormat(locale, format) {
composer.mergeNumberFormat(locale, format);
},
// getChoiceIndex
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getChoiceIndex(choice, choicesLength) {
warn(getWarnMessage$1(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
return -1;
},
// for internal
__onComponentInstanceCreated(target) {
const { componentInstanceCreatedListener } = options;
if (componentInstanceCreatedListener) {
componentInstanceCreatedListener(target, vueI18n);
}
}
};
// for vue-devtools timeline event
{
vueI18n.__enableEmitter = (emitter) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[EnableEmitter] && __composer[EnableEmitter](emitter);
};
vueI18n.__disableEmitter = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[DisableEmitter] && __composer[DisableEmitter]();
};
}
return vueI18n;
}
const baseFormatProps = {
tag: {
type: [String, Object]
},
locale: {
type: String
},
scope: {
type: String,
validator: (val) => val === 'parent' || val === 'global',
default: 'parent'
}
};
/**
* Translation Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [TranslationProps](component#translationprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Component Interpolation](../advanced/component)
*
* @example
* ```html
* <div id="app">
* <!-- ... -->
* <i18n path="term" tag="label" for="tos">
* <a :href="url" target="_blank">{{ $t('tos') }}</a>
* </i18n>
* <!-- ... -->
* </div>
* ```
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* const messages = {
* en: {
* tos: 'Term of Service',
* term: 'I accept xxx {0}.'
* },
* ja: {
* tos: '利用規約',
* term: '私は xxx の{0}に同意します。'
* }
* }
*
* const i18n = createI18n({
* locale: 'en',
* messages
* })
*
* const app = createApp({
* data: {
* url: '/term'
* }
* }).use(i18n).mount('#app')
* ```
*
* @VueI18nComponent
*/
const Translation = {
/* eslint-disable */
name: 'i18n-t',
props: {
...baseFormatProps,
keypath: {
type: String,
required: true
},
plural: {
type: [Number, String],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validator: (val) => isNumber(val) || !isNaN(val)
}
},
/* eslint-enable */
setup(props, context) {
const { slots, attrs } = context;
const i18n = useI18n({ useScope: props.scope });
const keys = Object.keys(slots).filter(key => key !== '_');
return () => {
const options = {};
if (props.locale) {
options.locale = props.locale;
}
if (props.plural !== undefined) {
options.plural = isString(props.plural) ? +props.plural : props.plural;
}
const arg = getInterpolateArg(context, keys);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
};
function getInterpolateArg({ slots }, keys) {
if (keys.length === 1 && keys[0] === 'default') {
// default slot only
return slots.default ? slots.default() : [];
}
else {
// named slots
return keys.reduce((arg, key) => {
const slot = slots[key];
if (slot) {
arg[key] = slot();
}
return arg;
}, {});
}
}
function renderFormatter(props, context, slotKeys, partFormatter) {
const { slots, attrs } = context;
return () => {
const options = { part: true };
let orverrides = {};
if (props.locale) {
options.locale = props.locale;
}
if (isString(props.format)) {
options.key = props.format;
}
else if (isObject(props.format)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isString(props.format.key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.key = props.format.key;
}
// Filter out number format options only
orverrides = Object.keys(props.format).reduce((options, prop) => {
return slotKeys.includes(prop)
? Object.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
: options;
}, {});
}
const parts = partFormatter(...[props.value, options, orverrides]);
let children = [options.key];
if (isArray(parts)) {
children = parts.map((part, index) => {
const slot = slots[part.type];
return slot
? slot({ [part.type]: part.value, index, parts })
: [part.value];
});
}
else if (isString(parts)) {
children = [parts];
}
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
const NUMBER_FORMAT_KEYS = [
'localeMatcher',
'style',
'unit',
'unitDisplay',
'currency',
'currencyDisplay',
'useGrouping',
'numberingSystem',
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
'notation',
'formatMatcher'
];
/**
* Number Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../essentials/number#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.NumberForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
*
* @VueI18nComponent
*/
const NumberFormat = {
/* eslint-disable */
name: 'i18n-n',
props: {
...baseFormatProps,
value: {
type: Number,
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[NumberPartsSymbol](...args));
}
};
const DATETIME_FORMAT_KEYS = [
'dateStyle',
'timeStyle',
'fractionalSecondDigits',
'calendar',
'dayPeriod',
'numberingSystem',
'localeMatcher',
'timeZone',
'hour12',
'hourCycle',
'formatMatcher',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName'
];
/**
* Datetime Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../essentials/datetime#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.DateTimeForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
*
* @VueI18nComponent
*/
const DatetimeFormat = {
/* eslint-disable */
name: 'i18n-d',
props: {
...baseFormatProps,
value: {
type: [Number, Date],
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[DatetimePartsSymbol](...args));
}
};
function getComposer(i18n, instance) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
return (i18nInternal.__getInstance(instance) || i18n.global);
}
else {
const vueI18n = i18nInternal.__getInstance(instance);
return vueI18n != null
? vueI18n.__composer
: i18n.global.__composer;
}
}
function vTDirective(i18n) {
const bind = (el, { instance, value, modifiers }) => {
/* istanbul ignore if */
if (!instance || !instance.$) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const composer = getComposer(i18n, instance.$);
if ( modifiers.preserve) {
warn(getWarnMessage$1(7 /* NOT_SUPPORTED_PRESERVE */));
}
const parsedValue = parseValue(value);
el.textContent = composer.t(...makeParams(parsedValue));
};
return {
beforeMount: bind,
beforeUpdate: bind
};
}
function parseValue(value) {
if (isString(value)) {
return { path: value };
}
else if (isPlainObject(value)) {
if (!('path' in value)) {
throw createI18nError(17 /* REQUIRED_VALUE */, 'path');
}
return value;
}
else {
throw createI18nError(18 /* INVALID_VALUE */);
}
}
function makeParams(value) {
const { path, locale, args, choice, plural } = value;
const options = {};
const named = args || {};
if (isString(locale)) {
options.locale = locale;
}
if (isNumber(choice)) {
options.plural = choice;
}
if (isNumber(plural)) {
options.plural = plural;
}
return [path, named, options];
}
function apply(app, i18n, ...options) {
const pluginOptions = isPlainObject(options[0])
? options[0]
: {};
const useI18nComponentName = !!pluginOptions.useI18nComponentName;
const globalInstall = isBoolean(pluginOptions.globalInstall)
? pluginOptions.globalInstall
: true;
if ( globalInstall && useI18nComponentName) {
warn(getWarnMessage$1(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
name: Translation.name
}));
}
if (globalInstall) {
// install components
app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
app.component(NumberFormat.name, NumberFormat);
app.component(DatetimeFormat.name, DatetimeFormat);
}
// install directive
app.directive('t', vTDirective(i18n));
}
// supports compatibility for legacy vue-i18n APIs
function defineMixin(vuei18n, composer, i18n) {
return {
beforeCreate() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const options = this.$options;
if (options.i18n) {
const optionsI18n = options.i18n;
if (options.__i18n) {
optionsI18n.__i18n = options.__i18n;
}
optionsI18n.__root = composer;
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, optionsI18n);
}
else {
this.$i18n = createVueI18n(optionsI18n);
}
}
else if (options.__i18n) {
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, options);
}
else {
this.$i18n = createVueI18n({
__i18n: options.__i18n,
__root: composer
});
}
}
else {
// set global
this.$i18n = vuei18n;
}
vuei18n.__onComponentInstanceCreated(this.$i18n);
i18n.__setInstance(instance, this.$i18n);
// defines vue-i18n legacy APIs
this.$t = (...args) => this.$i18n.t(...args);
this.$tc = (...args) => this.$i18n.tc(...args);
this.$te = (key, locale) => this.$i18n.te(key, locale);
this.$d = (...args) => this.$i18n.d(...args);
this.$n = (...args) => this.$i18n.n(...args);
this.$tm = (key) => this.$i18n.tm(key);
},
mounted() {
/* istanbul ignore if */
{
this.$el.__INTLIFY__ = this.$i18n.__composer;
const emitter = (this.__emitter = createEmitter());
const _vueI18n = this.$i18n;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
emitter.on('*', addTimelineEvent);
}
},
beforeUnmount() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
/* istanbul ignore if */
{
if (this.__emitter) {
this.__emitter.off('*', addTimelineEvent);
delete this.__emitter;
}
const _vueI18n = this.$i18n;
_vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
delete this.$el.__INTLIFY__;
}
delete this.$t;
delete this.$tc;
delete this.$te;
delete this.$d;
delete this.$n;
delete this.$tm;
i18n.__deleteInstance(instance);
delete this.$i18n;
}
};
}
function mergeToRoot(root, optoins) {
root.locale = optoins.locale || root.locale;
root.fallbackLocale = optoins.fallbackLocale || root.fallbackLocale;
root.missing = optoins.missing || root.missing;
root.silentTranslationWarn =
optoins.silentTranslationWarn || root.silentFallbackWarn;
root.silentFallbackWarn =
optoins.silentFallbackWarn || root.silentFallbackWarn;
root.formatFallbackMessages =
optoins.formatFallbackMessages || root.formatFallbackMessages;
root.postTranslation = optoins.postTranslation || root.postTranslation;
root.warnHtmlInMessage = optoins.warnHtmlInMessage || root.warnHtmlInMessage;
root.escapeParameterHtml =
optoins.escapeParameterHtml || root.escapeParameterHtml;
root.sync = optoins.sync || root.sync;
const messages = getLocaleMessages(root.locale, {
messages: optoins.messages,
__i18n: optoins.__i18n
});
Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
if (optoins.datetimeFormats) {
Object.keys(optoins.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, optoins.datetimeFormats[locale]));
}
if (optoins.numberFormats) {
Object.keys(optoins.numberFormats).forEach(locale => root.mergeNumberFormat(locale, optoins.numberFormats[locale]));
}
return root;
}
/**
* Vue I18n factory
*
* @param options - An options, see the {@link I18nOptions}
*
* @returns {@link I18n} instance
*
* @remarks
* If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
*
* If you use composition API mode, you need to specify {@link ComposerOptions}.
*
* @VueI18nSee [Getting Started](../essentials/started)
* @VueI18nSee [Composition API](../advanced/composition)
*
* @example
* case: for Legacy API
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* // ...
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @example
* case: for composition API
* ```js
* import { createApp } from 'vue'
* import { createI18n, useI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* legacy: false, // you must specify 'lagacy: false' option
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* setup() {
* // ...
* const { t } = useI18n({ ... })
* return { ... , t }
* }
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @VueI18nGeneral
*/
function createI18n(options = {}) {
// prettier-ignore
const __legacyMode = isBoolean(options.legacy)
? options.legacy
: true;
const __globalInjection = !!options.globalInjection;
const __instances = new Map();
// prettier-ignore
const __global = __legacyMode
? createVueI18n(options)
: createComposer(options);
const symbol = makeSymbol( 'vue-i18n' );
const i18n = {
// mode
get mode() {
// prettier-ignore
return __legacyMode
? 'legacy'
: 'composition'
;
},
// install plugin
async install(app, ...options) {
{
app.__VUE_I18N__ = i18n;
}
// setup global provider
app.__VUE_I18N_SYMBOL__ = symbol;
app.provide(app.__VUE_I18N_SYMBOL__, i18n);
// global method and properties injection for Composition API
if (!__legacyMode && __globalInjection) {
injectGlobalFields(app, i18n.global);
}
// install built-in components and directive
{
apply(app, i18n, ...options);
}
// setup mixin for Legacy API
if ( __legacyMode) {
app.mixin(defineMixin(__global, __global.__composer, i18n));
}
// setup vue-devtools plugin
{
const ret = await enableDevTools(app, i18n);
if (!ret) {
throw createI18nError(19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
}
const emitter = createEmitter();
if (__legacyMode) {
const _vueI18n = __global;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
}
else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = __global;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
}
emitter.on('*', addTimelineEvent);
}
},
// global accsessor
get global() {
return __global;
},
// @internal
__instances,
// @internal
__getInstance(component) {
return __instances.get(component) || null;
},
// @internal
__setInstance(component, instance) {
__instances.set(component, instance);
},
// @internal
__deleteInstance(component) {
__instances.delete(component);
}
};
{
devtoolsRegisterI18n(i18n, VERSION);
}
return i18n;
}
/**
* Use Composition API for Vue I18n
*
* @param options - An options, see {@link UseI18nOptions}
*
* @returns {@link Composer} instance
*
* @remarks
* This function is mainly used by `setup`.
*
* If options are specified, Composer instance is created for each component and you can be localized on the component.
*
* If options are not specified, you can be localized using the global Composer.
*
* @example
* case: Component resource base localization
* ```html
* <template>
* <form>
* <label>{{ t('language') }}</label>
* <select v-model="locale">
* <option value="en">en</option>
* <option value="ja">ja</option>
* </select>
* </form>
* <p>message: {{ t('hello') }}</p>
* </template>
*
* <script>
* import { useI18n } from 'vue-i18n'
*
* export default {
* setup() {
* const { t, locale } = useI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
* // Something to do ...
*
* return { ..., t, locale }
* }
* }
* </script>
* ```
*
* @VueI18nComposition
*/
function useI18n(options = {}) {
const instance = getCurrentInstance();
if (instance == null) {
throw createI18nError(14 /* MUST_BE_CALL_SETUP_TOP */);
}
if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
throw createI18nError(15 /* NOT_INSLALLED */);
}
const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
/* istanbul ignore if */
if (!i18n) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
// prettier-ignore
const scope = isEmptyObject(options)
? ('__i18n' in instance.type)
? 'local'
: 'global'
: !options.useScope
? 'local'
: options.useScope;
if (scope === 'global') {
let messages = isObject(options.messages) ? options.messages : {};
if ('__i18nGlobal' in instance.type) {
messages = getLocaleMessages(global.locale.value, {
messages,
__i18n: instance.type.__i18nGlobal
});
}
// merge locale messages
const locales = Object.keys(messages);
if (locales.length) {
locales.forEach(locale => {
global.mergeLocaleMessage(locale, messages[locale]);
});
}
// merge datetime formats
if (isObject(options.datetimeFormats)) {
const locales = Object.keys(options.datetimeFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
});
}
}
// merge number formats
if (isObject(options.numberFormats)) {
const locales = Object.keys(options.numberFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeNumberFormat(locale, options.numberFormats[locale]);
});
}
}
return global;
}
if (scope === 'parent') {
let composer = getComposer$1(i18n, instance);
if (composer == null) {
{
warn(getWarnMessage$1(12 /* NOT_FOUND_PARENT_SCOPE */));
}
composer = global;
}
return composer;
}
// scope 'local' case
if (i18n.mode === 'legacy') {
throw createI18nError(16 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
}
const i18nInternal = i18n;
let composer = i18nInternal.__getInstance(instance);
if (composer == null) {
const type = instance.type;
const composerOptions = {
...options
};
if (type.__i18n) {
composerOptions.__i18n = type.__i18n;
}
if (global) {
composerOptions.__root = global;
}
composer = createComposer(composerOptions);
setupLifeCycle(i18nInternal, instance, composer);
i18nInternal.__setInstance(instance, composer);
}
return composer;
}
function getComposer$1(i18n, target) {
let composer = null;
const root = target.root;
let current = target.parent;
while (current != null) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
composer = i18nInternal.__getInstance(current);
}
else {
const vueI18n = i18nInternal.__getInstance(current);
if (vueI18n != null) {
composer = vueI18n
.__composer;
}
}
if (composer != null) {
break;
}
if (root === current) {
break;
}
current = current.parent;
}
return composer;
}
function setupLifeCycle(i18n, target, composer) {
let emitter = null;
onMounted(() => {
// inject composer instance to DOM for intlify-devtools
if (
target.vnode.el) {
target.vnode.el.__INTLIFY__ = composer;
emitter = createEmitter();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
emitter.on('*', addTimelineEvent);
}
}, target);
onUnmounted(() => {
// remove composer instance from DOM for intlify-devtools
if (
target.vnode.el &&
target.vnode.el.__INTLIFY__) {
emitter && emitter.off('*', addTimelineEvent);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[DisableEmitter] && _composer[DisableEmitter]();
delete target.vnode.el.__INTLIFY__;
}
i18n.__deleteInstance(target);
}, target);
}
const globalExportProps = [
'locale',
'fallbackLocale',
'availableLocales'
];
const globalExportMethods = ['t', 'd', 'n', 'tm'];
function injectGlobalFields(app, composer) {
const i18n = Object.create(null);
globalExportProps.forEach(prop => {
const desc = Object.getOwnPropertyDescriptor(composer, prop);
if (!desc) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const wrap = isRef(desc.value) // check computed props
? {
get() {
return desc.value.value;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
set(val) {
desc.value.value = val;
}
}
: {
get() {
return desc.get && desc.get();
}
};
Object.defineProperty(i18n, prop, wrap);
});
app.config.globalProperties.$i18n = i18n;
globalExportMethods.forEach(method => {
const desc = Object.getOwnPropertyDescriptor(composer, method);
if (!desc) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
});
}
// register message compiler at vue-i18n
registerMessageCompiler(compileToFunction);
initDev();
export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };
| cdnjs/cdnjs | ajax/libs/vue-i18n/9.0.0-beta.13/vue-i18n.esm-browser.js | JavaScript | mit | 168,066 |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/msg/Motors.msg"
services_str = "/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/srv/AddTwoInts.srv"
pkg_name = "er1_motor_driver"
dependencies_str = "std_msgs"
langs = "gencpp;genlisp;genpy"
dep_include_paths_str = "er1_motor_driver;/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/msg;std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/indigo/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
| arvindpereira/clover_hack_day | er1_robot/build/er1_motor_driver/cmake/er1_motor_driver-genmsg-context.py | Python | mit | 677 |
export default {
name: 'selfie-card',
type: 'text',
render() {
return '[ :) ]';
}
};
| atonse/mobiledoc-kit | demo/app/mobiledoc-cards/text/selfie.js | JavaScript | mit | 97 |
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("ChallengeAccepted.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ChallengeAccepted.Models")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("186858b4-52b9-4a17-84aa-f4946a821fa2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| NativeScriptHybrids/ChallengeAccepted | ChallengeAccepted.Service/ChallengeAccepted.Models/Properties/AssemblyInfo.cs | C# | mit | 1,424 |
from mimetypes import guess_type
def get_git_info():
"""
Parses the git info and returns a tuple containg the owner and repo
:deprecated:
:rtype: tuple
:return: (owner name, repo name)
"""
repo = ''
with open('.git/config') as f:
for line in f.readlines():
if 'url' in line:
repo = line.replace('url = ', '').strip()
r = repo.split('/')
# Return a tuple containing the owner and the repo name
return r[-2], r[-1]
def detect_mimetype(file_):
"""
Detects the provided file's mimetype. Used to determine if we should read
the file line-by-line.
:param str file_: The name of the file to guess the mimetype of
:rtype: str
:return: The mimetype of the file provided
"""
return guess_type(file_)
| GrappigPanda/pygemony | pyg/utils.py | Python | mit | 811 |
#include "ticTacToeFunc.h"
#include <cstdio>
TicTacToeFunc::TicTacToeFunc()
{
size = 3;
winSize = 3;
field = new States *[size];
for (int i = 0; i < size; i++)
field[i] = new States[size];
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
field[i][j] = stateFree;
move = moveX;
state = inProcess;
}
TicTacToeFunc::~TicTacToeFunc()
{
for (int i = 0; i < size; i++)
delete[] field[i];
delete[] field;
}
TicTacToeFunc::States TicTacToeFunc::getCell(int x, int y)
{
return field[x][y];
}
void TicTacToeFunc::horizontalWin()
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size - winSize + 1; j++)
{
bool win = true;
for (int k = 0; k < winSize - 1; k++)
if (field[i][j + k] == TicTacToeFunc::stateFree || field[i][j + k] != field[i][j + k + 1])
{
win = false;
break;
}
if (!win)
continue;
state = (field[i][j] == stateX) ? winX : winO;
return;
}
}
void TicTacToeFunc::verticalWin()
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size - winSize + 1; j++)
{
bool win = true;
for (int k = 0; k < winSize - 1; k++)
if (field[j + k][i] == TicTacToeFunc::stateFree || field[j + k][i] != field[j + k + 1][i])
{
win = false;
break;
}
if (!win)
continue;
state = (field[j][i] == stateX) ? winX : winO;
return;
}
}
void TicTacToeFunc::mainDiagonalWin()
{
for (int i = 0; i < size - winSize + 1; i++)
for (int j = 0; j < size - winSize + 1; j++)
{
bool win = true;
for (int k = 0; k < winSize - 1; k++)
if (field[i + k][j + k] == TicTacToeFunc::stateFree || field[i + k][j + k] != field[i + k + 1][j + k + 1])
{
win = false;
break;
}
if (!win)
continue;
state = (field[i][j] == stateX) ? winX : winO;
return;
}
}
void TicTacToeFunc::secondaryDiagonalWin()
{
for (int i = 0; i < size - winSize + 1; i++)
for (int j = winSize - 1; j < size; j++)
{
bool win = true;
for (int k = 0; k < winSize - 1; k++)
if (field[i + k][j - k] == TicTacToeFunc::stateFree || field[i + k][j - k] != field[i + k + 1][j - k - 1])
{
win = false;
break;
}
if (!win)
continue;
state = (field[j][i] == stateX) ? winX : winO;
}
}
void TicTacToeFunc::updateState()
{
if (state != inProcess)
return;
horizontalWin();
if (state != inProcess)
return;
verticalWin();
if (state != inProcess)
return;
mainDiagonalWin();
if (state != inProcess)
return;
secondaryDiagonalWin();
}
TicTacToeFunc::Moves TicTacToeFunc::nextMove()
{
if (move == moveX)
return moveO;
return moveX;
}
TicTacToeFunc::States TicTacToeFunc::changeState(Moves m)
{
if (m == moveX)
return stateX;
return stateO;
}
void TicTacToeFunc::makeMove(int x, int y)
{
if (isFinished())
return;
field[x][y] = changeState(move);
updateState();
move = nextMove();
}
TicTacToeFunc::CurrentState TicTacToeFunc::getState()
{
return state;
}
bool TicTacToeFunc::isFinished()
{
if (state == winX || state == winO)
return true;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
if (field[i][j] == stateFree)
return false;
return true;
}
void TicTacToeFunc::changeSize(int newSize)
{
for (int i = 0; i < size; i++)
delete[] field[i];
delete[] field;
field = new States*[newSize];
for (int i = 0; i < newSize; i++)
field[i] = new TicTacToeFunc::States[newSize];
for (int i = 0; i < newSize; i++)
for (int j = 0; j < newSize; j++)
field[i][j] = TicTacToeFunc::stateFree;
size = newSize;
winSize = 5;
move = TicTacToeFunc::moveX;
}
int TicTacToeFunc::getSize()
{
return size;
}
| Sergey-Pravdyukov/Homeworks | term2/hw7/3/tictactoefunc.cpp | C++ | mit | 4,600 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace QrF.Core.Admin.Dto
{
public class BasePageInput
{
public BasePageInput()
{
this.Page = 1;
this.PageSize = 20;
}
/// <summary>
/// 当前分页
/// </summary>
public int Page { set; get; }
/// <summary>
/// 每页数量
/// </summary>
public int PageSize { set; get; }
}
}
| ren8179/QrF.Core | src/apis/QrF.Core.Admin/Dto/BasePageInput.cs | C# | mit | 507 |
package com.paratussoftware.ui.cli;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class GrimoireCLI {
private static final String TITLE_FILE_NAME = "./lib/grimoire_title.txt";
public static void startGrimoireCLI(String[] args){
showTitle();
CLIMenuManager cliMenuManager = new CLIMenuManager();
while (true){
cliMenuManager.showMainMenu();
}
}
public static void showTitle(){
try (BufferedReader br = new BufferedReader(new FileReader(TITLE_FILE_NAME))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {}
}
}
| JArthurJohnston/Grimoire-V2 | Demo/src/main/java/com/paratussoftware/ui/cli/GrimoireCLI.java | Java | mit | 754 |
<?php
namespace BDN\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20170820234613 extends AbstractMigration {
/**
* @param Schema $schema
*/
public function up(Schema $schema) {
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf(
$this->connection->getDatabasePlatform()->getName() !== 'mysql',
'Migration can only be executed safely on \'mysql\'.'
);
$this->addSql(
'CREATE TABLE cron_task (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, commands LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', `interval` INT NOT NULL, lastrun DATETIME DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE orders (id INT AUTO_INCREMENT NOT NULL, number VARCHAR(255) DEFAULT NULL, additional_information VARCHAR(1000) DEFAULT NULL, state VARCHAR(255) NOT NULL, completed_at DATETIME DEFAULT NULL, items_total INT NOT NULL, adjustments_total INT NOT NULL, total INT NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, deleted_at DATETIME DEFAULT NULL, email VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_E52FFDEE96901F54 (number), UNIQUE INDEX UNIQ_E52FFDEEE7927C74 (email), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE order_items (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, quantity INT NOT NULL, unit_price INT NOT NULL, units_total INT NOT NULL, adjustments_total INT NOT NULL, total INT NOT NULL, is_immutable TINYINT(1) NOT NULL, INDEX IDX_62809DB08D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE user_group (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(180) NOT NULL, roles LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', community_id INT NOT NULL, UNIQUE INDEX UNIQ_8F02BF9D5E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE login_access_tokens (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, t_key VARCHAR(255) NOT NULL, expired TINYINT(1) NOT NULL, date DATETIME NOT NULL, redirect VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_7EC367D32CCFDC5D (t_key), INDEX IDX_7EC367D3A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE oauth2_access_tokens (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D247A21B5F37A13B (token), INDEX IDX_D247A21B19EB6921 (client_id), INDEX IDX_D247A21BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE oauth2_auth_codes (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, redirect_uri LONGTEXT NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_A018A10D5F37A13B (token), INDEX IDX_A018A10D19EB6921 (client_id), INDEX IDX_A018A10DA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE oauth2_clients (id INT AUTO_INCREMENT NOT NULL, random_id VARCHAR(255) NOT NULL, redirect_uris LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', secret VARCHAR(255) NOT NULL, allowed_grant_types LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE oauth2_refresh_tokens (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D394478C5F37A13B (token), INDEX IDX_D394478C19EB6921 (client_id), INDEX IDX_D394478CA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE session (id INT AUTO_INCREMENT NOT NULL, ip VARCHAR(45) NOT NULL, date DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE user (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(180) NOT NULL, username_canonical VARCHAR(180) NOT NULL, email VARCHAR(180) NOT NULL, email_canonical VARCHAR(180) NOT NULL, enabled TINYINT(1) NOT NULL, salt VARCHAR(255) DEFAULT NULL, password VARCHAR(255) NOT NULL, last_login DATETIME DEFAULT NULL, confirmation_token VARCHAR(180) DEFAULT NULL, password_requested_at DATETIME DEFAULT NULL, roles LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', api_key VARCHAR(255) DEFAULT NULL, google_authenticator_secret VARCHAR(255) DEFAULT NULL, forums_id INT NOT NULL, forums_access_token INT NOT NULL, community_id INT NOT NULL, UNIQUE INDEX UNIQ_8D93D64992FC23A8 (username_canonical), UNIQUE INDEX UNIQ_8D93D649A0D96FBF (email_canonical), UNIQUE INDEX UNIQ_8D93D649C05FB297 (confirmation_token), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE user_user_group (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_28657971A76ED395 (user_id), INDEX IDX_28657971FE54D947 (group_id), PRIMARY KEY(user_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE user_oauth_clients (user_id INT NOT NULL, client_id INT NOT NULL, INDEX IDX_FD402C51A76ED395 (user_id), INDEX IDX_FD402C5119EB6921 (client_id), PRIMARY KEY(user_id, client_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE slack_invite (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, date DATETIME NOT NULL, INDEX IDX_738D77CA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE language (id INT AUTO_INCREMENT NOT NULL, active TINYINT(1) NOT NULL, language_key VARCHAR(15) NOT NULL, language VARCHAR(64) NOT NULL, UNIQUE INDEX UNIQ_D4DB71B55B160485 (language_key), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE library (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, version DOUBLE PRECISION NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE script (id INT AUTO_INCREMENT NOT NULL, git_id INT DEFAULT NULL, creator_id INT DEFAULT NULL, name VARCHAR(255) NOT NULL, product LONGTEXT NOT NULL COMMENT \'(DC2Type:object)\', description LONGTEXT NOT NULL, forum INT DEFAULT NULL, active TINYINT(1) NOT NULL, build_type_id VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_1C81873A5E237E06 (name), UNIQUE INDEX UNIQ_1C81873A4D4CA094 (git_id), INDEX IDX_1C81873A61220EA6 (creator_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE script_authors (script_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_D304ED1BA1C01850 (script_id), INDEX IDX_D304ED1BA76ED395 (user_id), PRIMARY KEY(script_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE script_users (script_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_78458A76A1C01850 (script_id), INDEX IDX_78458A76A76ED395 (user_id), PRIMARY KEY(script_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE script_groups (script_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_90B1718AA1C01850 (script_id), INDEX IDX_90B1718AFE54D947 (group_id), PRIMARY KEY(script_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE script_categories (script_id INT NOT NULL, category_id INT NOT NULL, INDEX IDX_CD9E8798A1C01850 (script_id), INDEX IDX_CD9E879812469DE2 (category_id), PRIMARY KEY(script_id, category_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE category (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE git (id INT AUTO_INCREMENT NOT NULL, url VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE releases (id INT AUTO_INCREMENT NOT NULL, script_id INT DEFAULT NULL, changelog LONGTEXT DEFAULT NULL, version DOUBLE PRECISION NOT NULL, date DATETIME NOT NULL, INDEX IDX_7896E4D1A1C01850 (script_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE review (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, script_id INT DEFAULT NULL, review LONGTEXT NOT NULL, stars INT NOT NULL, date DATETIME NOT NULL, accepted TINYINT(1) NOT NULL, INDEX IDX_794381C6A76ED395 (user_id), INDEX IDX_794381C6A1C01850 (script_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE hook (id INT AUTO_INCREMENT NOT NULL, server_id INT DEFAULT NULL, accessor VARCHAR(255) DEFAULT NULL, methodname VARCHAR(255) DEFAULT NULL, desctype VARCHAR(255) DEFAULT NULL, callclass VARCHAR(255) DEFAULT NULL, callmethod VARCHAR(255) DEFAULT NULL, calldesc VARCHAR(255) DEFAULT NULL, callargs VARCHAR(255) DEFAULT NULL, field VARCHAR(255) DEFAULT NULL, descfield VARCHAR(255) DEFAULT NULL, intoclass VARCHAR(255) DEFAULT NULL, classname VARCHAR(255) DEFAULT NULL, interface VARCHAR(255) DEFAULT NULL, invokemethod VARCHAR(255) DEFAULT NULL, argsdesc VARCHAR(255) DEFAULT NULL, type VARCHAR(255) NOT NULL, version DOUBLE PRECISION NOT NULL, INDEX IDX_A45843551844E6B7 (server_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE server (id INT AUTO_INCREMENT NOT NULL, server_id INT DEFAULT NULL, name VARCHAR(255) NOT NULL, active TINYINT(1) NOT NULL, version DOUBLE PRECISION NOT NULL, description LONGTEXT NOT NULL, provider_id INT DEFAULT NULL, INDEX IDX_5A6DD5F6A53A8AA (provider_id), UNIQUE INDEX UNIQ_5A6DD5F61844E6B7 (server_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE server_groups (server_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_891100B61844E6B7 (server_id), INDEX IDX_891100B6FE54D947 (group_id), PRIMARY KEY(server_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE server_authors (server_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_FC7231ED1844E6B7 (server_id), INDEX IDX_FC7231EDA76ED395 (user_id), PRIMARY KEY(server_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE server_details (server_id INT NOT NULL, serverdetail_id INT NOT NULL, INDEX IDX_5810361844E6B7 (server_id), INDEX IDX_58103634B5C767 (serverdetail_id), PRIMARY KEY(server_id, serverdetail_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE server_detail (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE server_slack_channel (id INT AUTO_INCREMENT NOT NULL, channel VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE server_use (id INT AUTO_INCREMENT NOT NULL, datetime DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE user_serveruses (serveruse_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_2E513393EB1E3248 (serveruse_id), INDEX IDX_2E513393A76ED395 (user_id), PRIMARY KEY(serveruse_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE server_serveruse (serveruse_id INT NOT NULL, server_id INT NOT NULL, INDEX IDX_28A1B5EAEB1E3248 (serveruse_id), INDEX IDX_28A1B5EA1844E6B7 (server_id), PRIMARY KEY(serveruse_id, server_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE user_signature (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(255) NOT NULL, abstract_signature_id INT DEFAULT NULL, INDEX IDX_AE688CA57E0AA10B (abstract_signature_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE type_client (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE type_default_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE type_dreamscape_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE type_osscape_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE type_pkhonor_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE type_randoms (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE sylius_sequence (id INT AUTO_INCREMENT NOT NULL, idx INT NOT NULL, type VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_AD3D8CC48CDE5729 (type), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE sylius_adjustment (id INT AUTO_INCREMENT NOT NULL, order_id INT DEFAULT NULL, order_item_id INT DEFAULT NULL, order_item_unit_id INT DEFAULT NULL, type VARCHAR(255) NOT NULL, label VARCHAR(255) DEFAULT NULL, amount INT NOT NULL, is_neutral TINYINT(1) NOT NULL, is_locked TINYINT(1) NOT NULL, origin_id INT DEFAULT NULL, origin_type VARCHAR(255) DEFAULT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, INDEX IDX_ACA6E0F28D9F6D38 (order_id), INDEX IDX_ACA6E0F2E415FB15 (order_item_id), INDEX IDX_ACA6E0F2F720C233 (order_item_unit_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE sylius_order_comment (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, state VARCHAR(255) NOT NULL, comment LONGTEXT DEFAULT NULL, notify_customer TINYINT(1) NOT NULL, author VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, INDEX IDX_8EA9CF098D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE sylius_order_identity (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(255) DEFAULT NULL, INDEX IDX_5757A18E8D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'CREATE TABLE sylius_order_item_unit (id INT AUTO_INCREMENT NOT NULL, order_item_id INT NOT NULL, adjustments_total INT NOT NULL, INDEX IDX_82BF226EE415FB15 (order_item_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'
);
$this->addSql(
'ALTER TABLE order_items ADD CONSTRAINT FK_62809DB08D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE'
);
$this->addSql(
'ALTER TABLE login_access_tokens ADD CONSTRAINT FK_7EC367D3A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE oauth2_access_tokens ADD CONSTRAINT FK_D247A21B19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)'
);
$this->addSql(
'ALTER TABLE oauth2_access_tokens ADD CONSTRAINT FK_D247A21BA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE oauth2_auth_codes ADD CONSTRAINT FK_A018A10D19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)'
);
$this->addSql(
'ALTER TABLE oauth2_auth_codes ADD CONSTRAINT FK_A018A10DA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE oauth2_refresh_tokens ADD CONSTRAINT FK_D394478C19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)'
);
$this->addSql(
'ALTER TABLE oauth2_refresh_tokens ADD CONSTRAINT FK_D394478CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE user_user_group ADD CONSTRAINT FK_28657971A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE user_user_group ADD CONSTRAINT FK_28657971FE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)'
);
$this->addSql(
'ALTER TABLE user_oauth_clients ADD CONSTRAINT FK_FD402C51A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE user_oauth_clients ADD CONSTRAINT FK_FD402C5119EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)'
);
$this->addSql(
'ALTER TABLE slack_invite ADD CONSTRAINT FK_738D77CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql('ALTER TABLE script ADD CONSTRAINT FK_1C81873A4D4CA094 FOREIGN KEY (git_id) REFERENCES git (id)');
$this->addSql(
'ALTER TABLE script ADD CONSTRAINT FK_1C81873A61220EA6 FOREIGN KEY (creator_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE script_authors ADD CONSTRAINT FK_D304ED1BA1C01850 FOREIGN KEY (script_id) REFERENCES script (id)'
);
$this->addSql(
'ALTER TABLE script_authors ADD CONSTRAINT FK_D304ED1BA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE script_users ADD CONSTRAINT FK_78458A76A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)'
);
$this->addSql(
'ALTER TABLE script_users ADD CONSTRAINT FK_78458A76A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE script_groups ADD CONSTRAINT FK_90B1718AA1C01850 FOREIGN KEY (script_id) REFERENCES script (id)'
);
$this->addSql(
'ALTER TABLE script_groups ADD CONSTRAINT FK_90B1718AFE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)'
);
$this->addSql(
'ALTER TABLE script_categories ADD CONSTRAINT FK_CD9E8798A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)'
);
$this->addSql(
'ALTER TABLE script_categories ADD CONSTRAINT FK_CD9E879812469DE2 FOREIGN KEY (category_id) REFERENCES category (id)'
);
$this->addSql(
'ALTER TABLE releases ADD CONSTRAINT FK_7896E4D1A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)'
);
$this->addSql(
'ALTER TABLE review ADD CONSTRAINT FK_794381C6A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE review ADD CONSTRAINT FK_794381C6A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)'
);
$this->addSql(
'ALTER TABLE hook ADD CONSTRAINT FK_A45843551844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)'
);
$this->addSql(
'ALTER TABLE server ADD CONSTRAINT FK_5A6DD5F61844E6B7 FOREIGN KEY (server_id) REFERENCES server_slack_channel (id)'
);
$this->addSql(
'ALTER TABLE server_groups ADD CONSTRAINT FK_891100B61844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)'
);
$this->addSql(
'ALTER TABLE server_groups ADD CONSTRAINT FK_891100B6FE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)'
);
$this->addSql(
'ALTER TABLE server_authors ADD CONSTRAINT FK_FC7231ED1844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)'
);
$this->addSql(
'ALTER TABLE server_authors ADD CONSTRAINT FK_FC7231EDA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE server_details ADD CONSTRAINT FK_5810361844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)'
);
$this->addSql(
'ALTER TABLE server_details ADD CONSTRAINT FK_58103634B5C767 FOREIGN KEY (serverdetail_id) REFERENCES server_detail (id)'
);
$this->addSql(
'ALTER TABLE user_serveruses ADD CONSTRAINT FK_2E513393EB1E3248 FOREIGN KEY (serveruse_id) REFERENCES server_use (id)'
);
$this->addSql(
'ALTER TABLE user_serveruses ADD CONSTRAINT FK_2E513393A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'
);
$this->addSql(
'ALTER TABLE server_serveruse ADD CONSTRAINT FK_28A1B5EAEB1E3248 FOREIGN KEY (serveruse_id) REFERENCES server_use (id)'
);
$this->addSql(
'ALTER TABLE server_serveruse ADD CONSTRAINT FK_28A1B5EA1844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)'
);
$this->addSql(
'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F28D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE'
);
$this->addSql(
'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F2E415FB15 FOREIGN KEY (order_item_id) REFERENCES order_items (id) ON DELETE CASCADE'
);
$this->addSql(
'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F2F720C233 FOREIGN KEY (order_item_unit_id) REFERENCES sylius_order_item_unit (id) ON DELETE CASCADE'
);
$this->addSql(
'ALTER TABLE sylius_order_comment ADD CONSTRAINT FK_8EA9CF098D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id)'
);
$this->addSql(
'ALTER TABLE sylius_order_identity ADD CONSTRAINT FK_5757A18E8D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id)'
);
$this->addSql(
'ALTER TABLE sylius_order_item_unit ADD CONSTRAINT FK_82BF226EE415FB15 FOREIGN KEY (order_item_id) REFERENCES order_items (id) ON DELETE CASCADE'
);
}
/**
* @param Schema $schema
*/
public function down(Schema $schema) {
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf(
$this->connection->getDatabasePlatform()->getName() !== 'mysql',
'Migration can only be executed safely on \'mysql\'.'
);
$this->addSql('ALTER TABLE order_items DROP FOREIGN KEY FK_62809DB08D9F6D38');
$this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F28D9F6D38');
$this->addSql('ALTER TABLE sylius_order_comment DROP FOREIGN KEY FK_8EA9CF098D9F6D38');
$this->addSql('ALTER TABLE sylius_order_identity DROP FOREIGN KEY FK_5757A18E8D9F6D38');
$this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F2E415FB15');
$this->addSql('ALTER TABLE sylius_order_item_unit DROP FOREIGN KEY FK_82BF226EE415FB15');
$this->addSql('ALTER TABLE user_user_group DROP FOREIGN KEY FK_28657971FE54D947');
$this->addSql('ALTER TABLE script_groups DROP FOREIGN KEY FK_90B1718AFE54D947');
$this->addSql('ALTER TABLE server_groups DROP FOREIGN KEY FK_891100B6FE54D947');
$this->addSql('ALTER TABLE oauth2_access_tokens DROP FOREIGN KEY FK_D247A21B19EB6921');
$this->addSql('ALTER TABLE oauth2_auth_codes DROP FOREIGN KEY FK_A018A10D19EB6921');
$this->addSql('ALTER TABLE oauth2_refresh_tokens DROP FOREIGN KEY FK_D394478C19EB6921');
$this->addSql('ALTER TABLE user_oauth_clients DROP FOREIGN KEY FK_FD402C5119EB6921');
$this->addSql('ALTER TABLE login_access_tokens DROP FOREIGN KEY FK_7EC367D3A76ED395');
$this->addSql('ALTER TABLE oauth2_access_tokens DROP FOREIGN KEY FK_D247A21BA76ED395');
$this->addSql('ALTER TABLE oauth2_auth_codes DROP FOREIGN KEY FK_A018A10DA76ED395');
$this->addSql('ALTER TABLE oauth2_refresh_tokens DROP FOREIGN KEY FK_D394478CA76ED395');
$this->addSql('ALTER TABLE user_user_group DROP FOREIGN KEY FK_28657971A76ED395');
$this->addSql('ALTER TABLE user_oauth_clients DROP FOREIGN KEY FK_FD402C51A76ED395');
$this->addSql('ALTER TABLE slack_invite DROP FOREIGN KEY FK_738D77CA76ED395');
$this->addSql('ALTER TABLE script DROP FOREIGN KEY FK_1C81873A61220EA6');
$this->addSql('ALTER TABLE script_authors DROP FOREIGN KEY FK_D304ED1BA76ED395');
$this->addSql('ALTER TABLE script_users DROP FOREIGN KEY FK_78458A76A76ED395');
$this->addSql('ALTER TABLE review DROP FOREIGN KEY FK_794381C6A76ED395');
$this->addSql('ALTER TABLE server_authors DROP FOREIGN KEY FK_FC7231EDA76ED395');
$this->addSql('ALTER TABLE user_serveruses DROP FOREIGN KEY FK_2E513393A76ED395');
$this->addSql('ALTER TABLE script_authors DROP FOREIGN KEY FK_D304ED1BA1C01850');
$this->addSql('ALTER TABLE script_users DROP FOREIGN KEY FK_78458A76A1C01850');
$this->addSql('ALTER TABLE script_groups DROP FOREIGN KEY FK_90B1718AA1C01850');
$this->addSql('ALTER TABLE script_categories DROP FOREIGN KEY FK_CD9E8798A1C01850');
$this->addSql('ALTER TABLE releases DROP FOREIGN KEY FK_7896E4D1A1C01850');
$this->addSql('ALTER TABLE review DROP FOREIGN KEY FK_794381C6A1C01850');
$this->addSql('ALTER TABLE script_categories DROP FOREIGN KEY FK_CD9E879812469DE2');
$this->addSql('ALTER TABLE script DROP FOREIGN KEY FK_1C81873A4D4CA094');
$this->addSql('ALTER TABLE hook DROP FOREIGN KEY FK_A45843551844E6B7');
$this->addSql('ALTER TABLE server_groups DROP FOREIGN KEY FK_891100B61844E6B7');
$this->addSql('ALTER TABLE server_authors DROP FOREIGN KEY FK_FC7231ED1844E6B7');
$this->addSql('ALTER TABLE server_details DROP FOREIGN KEY FK_5810361844E6B7');
$this->addSql('ALTER TABLE server_serveruse DROP FOREIGN KEY FK_28A1B5EA1844E6B7');
$this->addSql('ALTER TABLE server_details DROP FOREIGN KEY FK_58103634B5C767');
$this->addSql('ALTER TABLE server DROP FOREIGN KEY FK_5A6DD5F61844E6B7');
$this->addSql('ALTER TABLE user_serveruses DROP FOREIGN KEY FK_2E513393EB1E3248');
$this->addSql('ALTER TABLE server_serveruse DROP FOREIGN KEY FK_28A1B5EAEB1E3248');
$this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F2F720C233');
$this->addSql('DROP TABLE cron_task');
$this->addSql('DROP TABLE orders');
$this->addSql('DROP TABLE order_items');
$this->addSql('DROP TABLE user_group');
$this->addSql('DROP TABLE login_access_tokens');
$this->addSql('DROP TABLE oauth2_access_tokens');
$this->addSql('DROP TABLE oauth2_auth_codes');
$this->addSql('DROP TABLE oauth2_clients');
$this->addSql('DROP TABLE oauth2_refresh_tokens');
$this->addSql('DROP TABLE session');
$this->addSql('DROP TABLE user');
$this->addSql('DROP TABLE user_user_group');
$this->addSql('DROP TABLE user_oauth_clients');
$this->addSql('DROP TABLE slack_invite');
$this->addSql('DROP TABLE language');
$this->addSql('DROP TABLE library');
$this->addSql('DROP TABLE script');
$this->addSql('DROP TABLE script_authors');
$this->addSql('DROP TABLE script_users');
$this->addSql('DROP TABLE script_groups');
$this->addSql('DROP TABLE script_categories');
$this->addSql('DROP TABLE category');
$this->addSql('DROP TABLE git');
$this->addSql('DROP TABLE releases');
$this->addSql('DROP TABLE review');
$this->addSql('DROP TABLE hook');
$this->addSql('DROP TABLE server');
$this->addSql('DROP TABLE server_groups');
$this->addSql('DROP TABLE server_authors');
$this->addSql('DROP TABLE server_details');
$this->addSql('DROP TABLE server_detail');
$this->addSql('DROP TABLE server_slack_channel');
$this->addSql('DROP TABLE server_use');
$this->addSql('DROP TABLE user_serveruses');
$this->addSql('DROP TABLE server_serveruse');
$this->addSql('DROP TABLE user_signature');
$this->addSql('DROP TABLE type_client');
$this->addSql('DROP TABLE type_default_provider');
$this->addSql('DROP TABLE type_dreamscape_provider');
$this->addSql('DROP TABLE type_osscape_provider');
$this->addSql('DROP TABLE type_pkhonor_provider');
$this->addSql('DROP TABLE type_randoms');
$this->addSql('DROP TABLE sylius_sequence');
$this->addSql('DROP TABLE sylius_adjustment');
$this->addSql('DROP TABLE sylius_order_comment');
$this->addSql('DROP TABLE sylius_order_identity');
$this->addSql('DROP TABLE sylius_order_item_unit');
}
}
| Parabot/BDN-V3 | app/Migrations/Version20170820234613.php | PHP | mit | 32,193 |
package com.openknowl.okhttpexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.github.com/users/KimKyung-man")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "" + response.body().string());
}
});
}
}
| openknowl/android-prototyper-tutorials | android/android_tutorial_8/OkHttpExample/app/src/main/java/com/openknowl/okhttpexample/MainActivity.java | Java | mit | 1,171 |
/* global describe, it */
var assert = require('assert')
var constantCase = require('./')
describe('constant case', function () {
it('should upper case a single word', function () {
assert.equal(constantCase('test'), 'TEST')
assert.equal(constantCase('TEST'), 'TEST')
})
it('should constant case regular sentence cased strings', function () {
assert.equal(constantCase('test string'), 'TEST_STRING')
assert.equal(constantCase('Test String'), 'TEST_STRING')
})
it('should constant case non-alphanumeric separators', function () {
assert.equal(constantCase('dot.case'), 'DOT_CASE')
assert.equal(constantCase('path/case'), 'PATH_CASE')
})
it('should constant case pascal cased strings', function () {
assert.equal(constantCase('TestString'), 'TEST_STRING')
})
it('should support locales', function () {
assert.equal(constantCase('myString', 'tr'), 'MY_STRİNG')
})
})
| blakeembrey/constant-case | test.js | JavaScript | mit | 922 |
(function($){
$.fn.onImagesLoaded = function(_cb,_ca) {
return this.each(function() {
var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this),
_cont = this,
i = 0,
_loading=function() {
if( typeof _cb === 'function') _cb(_cont);
},
_done=function() {
if( typeof _ca === 'function' ) _ca(_cont);
};
if( $imgs.length ) {
$imgs.each(function() {
var _img = this;
_loading();
$(_img).load(function(){
_done();
});
});
}
});
}
})(jQuery) | flashycud/timestack | static/js/lib.js | JavaScript | mit | 614 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'order/all';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
| z32556601/90ping_backend | application/config/routes.php | PHP | mit | 1,971 |
@NodeEntity
public class Country{
@GraphId
private Long id;
@Indexed(unique=true)
private String coutryName;
@RelatedTo
private Set<City> cities;
public Country(){}
public Country(String countryName){
this.countryName = countryName;
}
} | yanisIk/Hobdy | Domain/Country.java | Java | mit | 254 |
<?php
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;
/**
* appDevUrlMatcher
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
/**
* Constructor.
*/
public function __construct(RequestContext $context)
{
$this->context = $context;
}
public function match($pathinfo)
{
$allow = array();
$pathinfo = rawurldecode($pathinfo);
if (0 === strpos($pathinfo, '/_')) {
// _wdt
if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
}
if (0 === strpos($pathinfo, '/_profiler')) {
// _profiler_home
if (rtrim($pathinfo, '/') === '/_profiler') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_profiler_home');
}
return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',);
}
if (0 === strpos($pathinfo, '/_profiler/search')) {
// _profiler_search
if ($pathinfo === '/_profiler/search') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',);
}
// _profiler_search_bar
if ($pathinfo === '/_profiler/search_bar') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '_profiler_search_bar',);
}
}
// _profiler_purge
if ($pathinfo === '/_profiler/purge') {
return array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', '_route' => '_profiler_purge',);
}
if (0 === strpos($pathinfo, '/_profiler/i')) {
// _profiler_info
if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',));
}
// _profiler_import
if ($pathinfo === '/_profiler/import') {
return array ( '_controller' => 'web_profiler.controller.profiler:importAction', '_route' => '_profiler_import',);
}
}
// _profiler_export
if (0 === strpos($pathinfo, '/_profiler/export') && preg_match('#^/_profiler/export/(?P<token>[^/\\.]++)\\.txt$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_export')), array ( '_controller' => 'web_profiler.controller.profiler:exportAction',));
}
// _profiler_phpinfo
if ($pathinfo === '/_profiler/phpinfo') {
return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',);
}
// _profiler_search_results
if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
}
// _profiler
if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',));
}
// _profiler_router
if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',));
}
// _profiler_exception
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',));
}
// _profiler_exception_css
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',));
}
}
if (0 === strpos($pathinfo, '/_configurator')) {
// _configurator_home
if (rtrim($pathinfo, '/') === '/_configurator') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_configurator_home');
}
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', '_route' => '_configurator_home',);
}
// _configurator_step
if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',));
}
// _configurator_final
if ($pathinfo === '/_configurator/final') {
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', '_route' => '_configurator_final',);
}
}
}
// application_sonata_super_market_homepage
if (0 === strpos($pathinfo, '/hello') && preg_match('#^/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'application_sonata_super_market_homepage')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\DefaultController::indexAction',));
}
// application_sonata_supermarket_price
if ($pathinfo === '/price') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PriceController::getPriceAction', '_route' => 'application_sonata_supermarket_price',);
}
if (0 === strpos($pathinfo, '/admin')) {
// sonata_admin_redirect
if (rtrim($pathinfo, '/') === '/admin') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'sonata_admin_redirect');
}
return array ( '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::redirectAction', 'route' => 'sonata_admin_dashboard', 'permanent' => 'true', '_route' => 'sonata_admin_redirect',);
}
// sonata_admin_dashboard
if ($pathinfo === '/admin/dashboard') {
return array ( '_controller' => 'Sonata\\AdminBundle\\Controller\\CoreController::dashboardAction', '_route' => 'sonata_admin_dashboard',);
}
if (0 === strpos($pathinfo, '/admin/core')) {
// sonata_admin_retrieve_form_element
if ($pathinfo === '/admin/core/get-form-field-element') {
return array ( '_controller' => 'sonata.admin.controller.admin:retrieveFormFieldElementAction', '_route' => 'sonata_admin_retrieve_form_element',);
}
// sonata_admin_append_form_element
if ($pathinfo === '/admin/core/append-form-field-element') {
return array ( '_controller' => 'sonata.admin.controller.admin:appendFormFieldElementAction', '_route' => 'sonata_admin_append_form_element',);
}
// sonata_admin_short_object_information
if (0 === strpos($pathinfo, '/admin/core/get-short-object-description') && preg_match('#^/admin/core/get\\-short\\-object\\-description(?:\\.(?P<_format>html|json))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'sonata_admin_short_object_information')), array ( '_controller' => 'sonata.admin.controller.admin:getShortObjectDescriptionAction', '_format' => 'html',));
}
// sonata_admin_set_object_field_value
if ($pathinfo === '/admin/core/set-object-field-value') {
return array ( '_controller' => 'sonata.admin.controller.admin:setObjectFieldValueAction', '_route' => 'sonata_admin_set_object_field_value',);
}
}
if (0 === strpos($pathinfo, '/admin/s')) {
// sonata_admin_search
if ($pathinfo === '/admin/search') {
return array ( '_controller' => 'Sonata\\AdminBundle\\Controller\\CoreController::searchAction', '_route' => 'sonata_admin_search',);
}
if (0 === strpos($pathinfo, '/admin/sonata/supermarket')) {
if (0 === strpos($pathinfo, '/admin/sonata/supermarket/brand')) {
// admin_sonata_supermarket_brand_list
if ($pathinfo === '/admin/sonata/supermarket/brand/list') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_list', '_route' => 'admin_sonata_supermarket_brand_list',);
}
// admin_sonata_supermarket_brand_create
if ($pathinfo === '/admin/sonata/supermarket/brand/create') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_create', '_route' => 'admin_sonata_supermarket_brand_create',);
}
// admin_sonata_supermarket_brand_batch
if ($pathinfo === '/admin/sonata/supermarket/brand/batch') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_batch', '_route' => 'admin_sonata_supermarket_brand_batch',);
}
// admin_sonata_supermarket_brand_edit
if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_edit',));
}
// admin_sonata_supermarket_brand_delete
if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_delete',));
}
// admin_sonata_supermarket_brand_show
if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_show',));
}
// admin_sonata_supermarket_brand_export
if ($pathinfo === '/admin/sonata/supermarket/brand/export') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_export', '_route' => 'admin_sonata_supermarket_brand_export',);
}
}
if (0 === strpos($pathinfo, '/admin/sonata/supermarket/category')) {
// admin_sonata_supermarket_category_list
if ($pathinfo === '/admin/sonata/supermarket/category/list') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_list', '_route' => 'admin_sonata_supermarket_category_list',);
}
// admin_sonata_supermarket_category_create
if ($pathinfo === '/admin/sonata/supermarket/category/create') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_create', '_route' => 'admin_sonata_supermarket_category_create',);
}
// admin_sonata_supermarket_category_batch
if ($pathinfo === '/admin/sonata/supermarket/category/batch') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_batch', '_route' => 'admin_sonata_supermarket_category_batch',);
}
// admin_sonata_supermarket_category_edit
if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_edit',));
}
// admin_sonata_supermarket_category_delete
if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_delete',));
}
// admin_sonata_supermarket_category_show
if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_show',));
}
// admin_sonata_supermarket_category_export
if ($pathinfo === '/admin/sonata/supermarket/category/export') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_export', '_route' => 'admin_sonata_supermarket_category_export',);
}
}
if (0 === strpos($pathinfo, '/admin/sonata/supermarket/product')) {
// admin_sonata_supermarket_product_list
if ($pathinfo === '/admin/sonata/supermarket/product/list') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_list', '_route' => 'admin_sonata_supermarket_product_list',);
}
// admin_sonata_supermarket_product_create
if ($pathinfo === '/admin/sonata/supermarket/product/create') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_create', '_route' => 'admin_sonata_supermarket_product_create',);
}
// admin_sonata_supermarket_product_batch
if ($pathinfo === '/admin/sonata/supermarket/product/batch') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_batch', '_route' => 'admin_sonata_supermarket_product_batch',);
}
// admin_sonata_supermarket_product_edit
if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_edit',));
}
// admin_sonata_supermarket_product_delete
if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_delete',));
}
// admin_sonata_supermarket_product_show
if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_show',));
}
// admin_sonata_supermarket_product_export
if ($pathinfo === '/admin/sonata/supermarket/product/export') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_export', '_route' => 'admin_sonata_supermarket_product_export',);
}
}
if (0 === strpos($pathinfo, '/admin/sonata/supermarket/customer')) {
// admin_sonata_supermarket_customer_list
if ($pathinfo === '/admin/sonata/supermarket/customer/list') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_list', '_route' => 'admin_sonata_supermarket_customer_list',);
}
// admin_sonata_supermarket_customer_create
if ($pathinfo === '/admin/sonata/supermarket/customer/create') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_create', '_route' => 'admin_sonata_supermarket_customer_create',);
}
// admin_sonata_supermarket_customer_batch
if ($pathinfo === '/admin/sonata/supermarket/customer/batch') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_batch', '_route' => 'admin_sonata_supermarket_customer_batch',);
}
// admin_sonata_supermarket_customer_edit
if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_edit',));
}
// admin_sonata_supermarket_customer_delete
if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_delete',));
}
// admin_sonata_supermarket_customer_show
if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_show',));
}
// admin_sonata_supermarket_customer_export
if ($pathinfo === '/admin/sonata/supermarket/customer/export') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_export', '_route' => 'admin_sonata_supermarket_customer_export',);
}
}
if (0 === strpos($pathinfo, '/admin/sonata/supermarket/purchaseorder')) {
// admin_sonata_supermarket_purchaseorder_list
if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/list') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_list', '_route' => 'admin_sonata_supermarket_purchaseorder_list',);
}
// admin_sonata_supermarket_purchaseorder_create
if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/create') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_create', '_route' => 'admin_sonata_supermarket_purchaseorder_create',);
}
// admin_sonata_supermarket_purchaseorder_batch
if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/batch') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_batch', '_route' => 'admin_sonata_supermarket_purchaseorder_batch',);
}
// admin_sonata_supermarket_purchaseorder_edit
if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_edit',));
}
// admin_sonata_supermarket_purchaseorder_delete
if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_delete',));
}
// admin_sonata_supermarket_purchaseorder_show
if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_show',));
}
// admin_sonata_supermarket_purchaseorder_export
if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/export') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_export', '_route' => 'admin_sonata_supermarket_purchaseorder_export',);
}
}
if (0 === strpos($pathinfo, '/admin/sonata/supermarket/orderitem')) {
// admin_sonata_supermarket_orderitem_list
if ($pathinfo === '/admin/sonata/supermarket/orderitem/list') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_list', '_route' => 'admin_sonata_supermarket_orderitem_list',);
}
// admin_sonata_supermarket_orderitem_create
if ($pathinfo === '/admin/sonata/supermarket/orderitem/create') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_create', '_route' => 'admin_sonata_supermarket_orderitem_create',);
}
// admin_sonata_supermarket_orderitem_batch
if ($pathinfo === '/admin/sonata/supermarket/orderitem/batch') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_batch', '_route' => 'admin_sonata_supermarket_orderitem_batch',);
}
// admin_sonata_supermarket_orderitem_edit
if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_edit',));
}
// admin_sonata_supermarket_orderitem_delete
if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_delete',));
}
// admin_sonata_supermarket_orderitem_show
if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_show',));
}
// admin_sonata_supermarket_orderitem_export
if ($pathinfo === '/admin/sonata/supermarket/orderitem/export') {
return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_export', '_route' => 'admin_sonata_supermarket_orderitem_export',);
}
}
}
}
}
if (0 === strpos($pathinfo, '/shtumi_')) {
// shtumi_ajaxautocomplete
if ($pathinfo === '/shtumi_ajaxautocomplete') {
return array ( '_controller' => 'Shtumi\\UsefulBundle\\Controller\\AjaxAutocompleteJSONController::getJSONAction', '_route' => 'shtumi_ajaxautocomplete',);
}
// shtumi_dependent_filtered_entity
if ($pathinfo === '/shtumi_dependent_filtered_entity') {
return array ( '_controller' => 'ShtumiUsefulBundle:DependentFilteredEntity:getOptions', '_route' => 'shtumi_dependent_filtered_entity',);
}
}
// _welcome
if (rtrim($pathinfo, '/') === '') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_welcome');
}
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\WelcomeController::indexAction', '_route' => '_welcome',);
}
if (0 === strpos($pathinfo, '/demo')) {
if (0 === strpos($pathinfo, '/demo/secured')) {
if (0 === strpos($pathinfo, '/demo/secured/log')) {
if (0 === strpos($pathinfo, '/demo/secured/login')) {
// _demo_login
if ($pathinfo === '/demo/secured/login') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction', '_route' => '_demo_login',);
}
// _security_check
if ($pathinfo === '/demo/secured/login_check') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction', '_route' => '_security_check',);
}
}
// _demo_logout
if ($pathinfo === '/demo/secured/logout') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction', '_route' => '_demo_logout',);
}
}
if (0 === strpos($pathinfo, '/demo/secured/hello')) {
// acme_demo_secured_hello
if ($pathinfo === '/demo/secured/hello') {
return array ( 'name' => 'World', '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', '_route' => 'acme_demo_secured_hello',);
}
// _demo_secured_hello
if (preg_match('#^/demo/secured/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',));
}
// _demo_secured_hello_admin
if (0 === strpos($pathinfo, '/demo/secured/hello/admin') && preg_match('#^/demo/secured/hello/admin/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello_admin')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction',));
}
}
}
// _demo
if (rtrim($pathinfo, '/') === '/demo') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_demo');
}
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction', '_route' => '_demo',);
}
// _demo_hello
if (0 === strpos($pathinfo, '/demo/hello') && preg_match('#^/demo/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction',));
}
// _demo_contact
if ($pathinfo === '/demo/contact') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction', '_route' => '_demo_contact',);
}
}
throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
}
}
| rangakomarthicomo/SuperMarket | app/cache/dev/appDevUrlMatcher.php | PHP | mit | 39,321 |
// The MIT License (MIT)
//
// Copyright (c) 2015-2018 Rasmus Mikkelsen
// Copyright (c) 2015-2018 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using EventFlow.Aggregates;
using EventFlow.Configuration;
using EventFlow.Core;
using EventFlow.EventStores.Files;
using EventFlow.Extensions;
using EventFlow.TestHelpers;
using EventFlow.TestHelpers.Aggregates;
using EventFlow.TestHelpers.Aggregates.Commands;
using EventFlow.TestHelpers.Aggregates.Queries;
using EventFlow.TestHelpers.Aggregates.ValueObjects;
using FluentAssertions;
using NUnit.Framework;
namespace EventFlow.Tests.IntegrationTests
{
[Category(Categories.Integration)]
public class BackwardCompatibilityTests : Test
{
private readonly ThingyId _thingyId = ThingyId.With("thingy-1acea1eb-3e11-45c0-83c1-bc32e57ee8e7");
private IResolver _resolver;
private ICommandBus _commandBus;
private IAggregateStore _aggregateStore;
[SetUp]
public void SetUp()
{
var codeBase = ReflectionHelper.GetCodeBase(GetType().Assembly);
var filesEventStoreDirectory = Path.GetFullPath(Path.Combine(codeBase, "..", "..", "..", "TestData", "FilesEventStore"));
_resolver = EventFlowOptions.New
.UseFilesEventStore(FilesEventStoreConfiguration.Create(filesEventStoreDirectory))
.AddEvents(EventFlowTestHelpers.Assembly)
.AddCommandHandlers(EventFlowTestHelpers.Assembly)
.RegisterServices(sr => sr.Register<IScopedContext, ScopedContext>(Lifetime.Scoped))
.CreateResolver();
_commandBus = _resolver.Resolve<ICommandBus>();
_aggregateStore = _resolver.Resolve<IAggregateStore>();
}
[Test]
public async Task ValidateTestAggregate()
{
// Act
var testAggregate = await _aggregateStore.LoadAsync<ThingyAggregate, ThingyId>(_thingyId, CancellationToken.None);
// Assert
testAggregate.Version.Should().Be(2);
testAggregate.PingsReceived.Should().Contain(PingId.With("95433aa0-11f7-4128-bd5f-18e0ecc4d7c1"));
testAggregate.PingsReceived.Should().Contain(PingId.With("2352d09b-4712-48cc-bb4f-5560d7c52558"));
}
[Test, Explicit]
public void CreateEventHelper()
{
_commandBus.Publish(new ThingyPingCommand(_thingyId, PingId.New), CancellationToken.None);
}
}
} | rasmus/EventFlow | Source/EventFlow.Tests/IntegrationTests/BackwardCompatibilityTests.cs | C# | mit | 3,638 |
// Generated from ./Select.g4 by ANTLR 4.5
// jshint ignore: start
var antlr4 = require('../../index');
var serializedATN = ["\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd",
"\2\17\177\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t",
"\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\3\2\3\2\3\2\3",
"\2\3\2\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3",
"\7\3\7\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\3",
"\n\5\nD\n\n\3\13\3\13\3\13\3\f\5\fJ\n\f\3\f\6\fM\n\f\r\f\16\fN\3\f\7",
"\fR\n\f\f\f\16\fU\13\f\3\f\7\fX\n\f\f\f\16\f[\13\f\3\f\3\f\3\f\3\f\3",
"\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\7\fl\n\f\f\f\16\fo\13\f\3",
"\f\5\fr\n\f\3\r\6\ru\n\r\r\r\16\rv\3\16\6\16z\n\16\r\16\16\16{\3\16",
"\3\16\3m\2\17\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31",
"\16\33\17\3\2\7\4\2--//\3\2\62;\3\2\60\60\5\2C\\aac|\5\2\13\f\17\17",
"\"\"\u008d\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2",
"\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2",
"\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\3\35\3\2\2\2\5$\3\2\2\2\7&\3",
"\2\2\2\t(\3\2\2\2\13*\3\2\2\2\r/\3\2\2\2\17\63\3\2\2\2\21\66\3\2\2\2",
"\23C\3\2\2\2\25E\3\2\2\2\27q\3\2\2\2\31t\3\2\2\2\33y\3\2\2\2\35\36\7",
"u\2\2\36\37\7g\2\2\37 \7n\2\2 !\7g\2\2!\"\7e\2\2\"#\7v\2\2#\4\3\2\2",
"\2$%\7.\2\2%\6\3\2\2\2&\'\7*\2\2\'\b\3\2\2\2()\7+\2\2)\n\3\2\2\2*+\7",
"h\2\2+,\7t\2\2,-\7q\2\2-.\7o\2\2.\f\3\2\2\2/\60\7c\2\2\60\61\7p\2\2",
"\61\62\7f\2\2\62\16\3\2\2\2\63\64\7q\2\2\64\65\7t\2\2\65\20\3\2\2\2",
"\66\67\7y\2\2\678\7j\2\289\7g\2\29:\7t\2\2:;\7g\2\2;\22\3\2\2\2<D\7",
">\2\2=>\7>\2\2>D\7?\2\2?D\7@\2\2@A\7@\2\2AD\7?\2\2BD\7?\2\2C<\3\2\2",
"\2C=\3\2\2\2C?\3\2\2\2C@\3\2\2\2CB\3\2\2\2D\24\3\2\2\2EF\7k\2\2FG\7",
"p\2\2G\26\3\2\2\2HJ\t\2\2\2IH\3\2\2\2IJ\3\2\2\2JL\3\2\2\2KM\t\3\2\2",
"LK\3\2\2\2MN\3\2\2\2NL\3\2\2\2NO\3\2\2\2OS\3\2\2\2PR\t\4\2\2QP\3\2\2",
"\2RU\3\2\2\2SQ\3\2\2\2ST\3\2\2\2TY\3\2\2\2US\3\2\2\2VX\t\3\2\2WV\3\2",
"\2\2X[\3\2\2\2YW\3\2\2\2YZ\3\2\2\2Zr\3\2\2\2[Y\3\2\2\2\\]\7v\2\2]^\7",
"t\2\2^_\7w\2\2_r\7g\2\2`a\7h\2\2ab\7c\2\2bc\7n\2\2cd\7u\2\2dr\7g\2\2",
"ef\7p\2\2fg\7w\2\2gh\7n\2\2hr\7n\2\2im\7)\2\2jl\13\2\2\2kj\3\2\2\2l",
"o\3\2\2\2mn\3\2\2\2mk\3\2\2\2np\3\2\2\2om\3\2\2\2pr\7)\2\2qI\3\2\2\2",
"q\\\3\2\2\2q`\3\2\2\2qe\3\2\2\2qi\3\2\2\2r\30\3\2\2\2su\t\5\2\2ts\3",
"\2\2\2uv\3\2\2\2vt\3\2\2\2vw\3\2\2\2w\32\3\2\2\2xz\t\6\2\2yx\3\2\2\2",
"z{\3\2\2\2{y\3\2\2\2{|\3\2\2\2|}\3\2\2\2}~\b\16\2\2~\34\3\2\2\2\f\2",
"CINSYmqv{\3\b\2\2"].join("");
var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);
var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); });
function SelectLexer(input) {
antlr4.Lexer.call(this, input);
this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache());
return this;
}
SelectLexer.prototype = Object.create(antlr4.Lexer.prototype);
SelectLexer.prototype.constructor = SelectLexer;
SelectLexer.EOF = antlr4.Token.EOF;
SelectLexer.T__0 = 1;
SelectLexer.T__1 = 2;
SelectLexer.T__2 = 3;
SelectLexer.T__3 = 4;
SelectLexer.T__4 = 5;
SelectLexer.T__5 = 6;
SelectLexer.T__6 = 7;
SelectLexer.T__7 = 8;
SelectLexer.OPERATOR = 9;
SelectLexer.ARRAYOPERATOR = 10;
SelectLexer.CONSTANT = 11;
SelectLexer.FIELD = 12;
SelectLexer.WS = 13;
SelectLexer.modeNames = [ "DEFAULT_MODE" ];
SelectLexer.literalNames = [ 'null', "'select'", "','", "'('", "')'", "'from'",
"'and'", "'or'", "'where'", 'null', "'in'" ];
SelectLexer.symbolicNames = [ 'null', 'null', 'null', 'null', 'null', 'null',
'null', 'null', 'null', "OPERATOR", "ARRAYOPERATOR",
"CONSTANT", "FIELD", "WS" ];
SelectLexer.ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5",
"T__6", "T__7", "OPERATOR", "ARRAYOPERATOR", "CONSTANT",
"FIELD", "WS" ];
SelectLexer.grammarFileName = "Select.g4";
exports.SelectLexer = SelectLexer;
| bvellacott/papu-force-adapter | lib/antlr4/parsers/select/SelectLexer.js | JavaScript | mit | 4,185 |
using System;
using Microsoft.VisualStudio.Shell.Interop;
using NUnit.Framework;
using Telerik.JustMock;
using VisualStudioSync.Controllers;
namespace VisualStudioSync.Tests
{
[TestFixture]
public class SettingsControllerTest
{
private const string Path = "path";
private const string Value = "test";
private IVsProfileDataManager _manager;
private IVsSettingsErrorInformation _errorInformation;
private IVsProfileSettingsFileCollection _files;
private IXmlRepository _xmlRepository;
private IVsProfileSettingsFileInfo _settingsFileInfo;
private IVsProfileSettingsTree _sets;
[SetUp]
public void Setup()
{
_manager = Mock.Create<IVsProfileDataManager>();
_errorInformation = Mock.Create<IVsSettingsErrorInformation>();
_files = Mock.Create<IVsProfileSettingsFileCollection>();
_xmlRepository = Mock.Create<IXmlRepository>();
_settingsFileInfo = Mock.Create<IVsProfileSettingsFileInfo>();
_sets = Mock.Create<IVsProfileSettingsTree>();
}
[Test]
public void Get_CheckManager_CalledExportAllSettings()
{
//Arrange
Mock.Arrange(() => _manager.ExportAllSettings(
Arg.Matches<string>(path => path.StartsWith(Path)),
out _errorInformation))
.MustBeCalled();
//Act
CreateController().Get();
//Assert
Mock.AssertAll(_manager);
}
[Test]
public void Get_CheckRepository_CalledGetXml()
{
//Arrange
Mock.Arrange(() => _xmlRepository.GetXml(
Arg.Matches<string>(path => path.StartsWith(Path))))
.MustBeCalled();
//Act
CreateController().Get();
//Assert
Mock.AssertAll(_xmlRepository);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void Set_ValueIsNull_ExpectedException()
{
//Act
CreateController().Set(null);
}
[Test]
public void Set_ValueIsntNull_CalledSetXml()
{
//Arrange
Mock.Arrange(() => _xmlRepository.SetXml(
Arg.Matches<string>(path => path.StartsWith(Path)),
Value))
.MustBeCalled();
Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing();
Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files));
//Act
CreateController().Set(Value);
//Assert
Mock.AssertAll(_xmlRepository);
}
[Test]
public void Set_ValueIsntNull_CalleGetSettingsFiles()
{
//Arrange
Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files))
.MustBeCalled();
Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing();
Mock.Arrange(() => _settingsFileInfo.GetSettingsForImport(out _sets)).DoNothing();
//Act
CreateController().Set(Value);
//Assert
Mock.AssertAll(_xmlRepository);
}
[Test]
public void Set_ValueIsntNull_CalleAddBrowseFile()
{
//Arrange
Mock.Arrange(() => _files.AddBrowseFile(
Arg.Matches<string>(path => path.StartsWith(Path)),
out _settingsFileInfo))
.MustBeCalled();
Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files));
//Act
CreateController().Set(Value);
//Assert
Mock.AssertAll(_xmlRepository);
}
[Test]
public void Set_ValueIsntNull_CalleGetSettingsForImport()
{
//Arrange
Mock.Arrange(() => _settingsFileInfo.GetSettingsForImport(out _sets))
.MustBeCalled();
Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files));
Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo));
//Act
CreateController().Set(Value);
//Assert
Mock.AssertAll(_xmlRepository);
}
[Test]
public void Set_ValueIsntNull_CalleImportSettings()
{
//Arrange
Mock.Arrange(() => _manager.ImportSettings(_sets, out _errorInformation))
.MustBeCalled();
Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files));
Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing();
//Act
CreateController().Set(Value);
//Assert
Mock.AssertAll(_xmlRepository);
}
private SettingsController CreateController()
{
return new SettingsController(Path, _manager, _xmlRepository);
}
}
}
| aquiladev/Coding4Fun.VisualStudioSync | VisualStudioSync.Tests/SettingsControllerTest.cs | C# | mit | 4,052 |
import styled from 'styled-components';
const Wrapper = styled.div`
width: 100%;
height: 100%;
display: block;
align-items: space-between;
`;
export default Wrapper;
| andyfrith/weather.goodapplemedia.com | app/containers/ForecastListItem/Wrapper.js | JavaScript | mit | 176 |
<?php
/**
* Low Seg2Cat Language file
*
* @package low_seg2cat
* @author Lodewijk Schutte <hi@gotolow.com>
* @link http://gotolow.com/addons/low-seg2cat
* @license http://creativecommons.org/licenses/by-sa/3.0/
*/
$lang = array(
'category_groups' =>
'Category groups',
'all_groups' =>
'-- All --',
'uri_pattern' =>
'URI pattern',
'set_all_segments' =>
'Set all segments',
'ignore_pagination' =>
'Ignore pagination',
'parse_file_paths' =>
'Parse file paths'
);
/* End of file low_seg2cat_lang.php */ | noslouch/pa | core/expressionengine/third_party/low_seg2cat/language/english/low_seg2cat_lang.php | PHP | mit | 547 |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Reflection;
namespace AKDK.Messages.DockerEvents.Converters
{
/// <summary>
/// JSON converter that that enables custom selection logic during deserialisation of the object to create based on the JSON encountered.
/// </summary>
/// <typeparam name="TBase">
/// The base type of object that the converter can deserialise.
/// </typeparam>
public abstract class JsonCreationConverter<TBase>
: JsonConverter
{
/// <summary>
/// Create a new <see cref="JsonCreationConverter{T}"/>.
/// </summary>
protected JsonCreationConverter()
{
}
/// <summary>
/// Can the converter write JSON?
/// </summary>
public override bool CanWrite
{
get
{
return false;
}
}
/// <summary>
/// Determine whether the converter can convert an object of the specified type.
/// </summary>
/// <param name="objectType">
/// The object type.
/// </param>
/// <returns>
/// <c>true</c>, if the converter can convert an object of the specified type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
if (objectType == null)
throw new ArgumentNullException(nameof(objectType));
return typeof(TBase).IsAssignableFrom(objectType);
}
/// <summary>
/// Deserialise an object from JSON.
/// </summary>
/// <param name="reader">
/// The <see cref="JsonReader"/> to read from.
/// </param><param name="objectType">
/// Type (or base type) of the object being deserialised.
/// </param><param name="existingValue">
/// The existing value of the object being read.
/// </param>
/// <param name="serializer">
/// The calling serializer.
/// </param>
/// <returns>
/// The deserialised object.
/// </returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
if (objectType == null)
throw new ArgumentNullException(nameof(objectType));
if (serializer == null)
throw new ArgumentNullException(nameof(serializer));
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType != JsonToken.StartObject)
{
throw new FormatException(
String.Format(
"Unexpected token '{0}' encountered while deserialising object of type '{1}'.",
reader.TokenType,
typeof(TBase).FullName
)
);
}
JObject json = JObject.Load(reader);
TBase target = Create(json);
if (target == null)
throw new InvalidOperationException("JsonCreationConverter.Create returned null.");
// Populate the object properties
serializer.Populate(
json.CreateReader(),
target
);
return target;
}
/// <summary>
/// Serialise an object to JSON.
/// </summary>
/// <param name="writer">
/// The <see cref="JsonWriter"/> to which serialised object data will be written.
/// </param>
/// <param name="value">
/// The object to serialise.
/// </param>
/// <param name="serializer">
/// The calling serialiser.
/// </param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
if (serializer == null)
throw new ArgumentNullException(nameof(serializer));
throw new NotImplementedException("JsonCreationConverter cannot write JSON.");
}
/// <summary>
/// Create an instance of to be populated, based properties in the JSON.
/// </summary>
/// <param name="json">
/// The JSON containing serialised object data.
/// </param>
/// <returns>
/// The object instance to be populated.
/// </returns>
protected abstract TBase Create(JObject json);
}
} | tintoy/aykay-deekay | src/AKDK/Messages/DockerEvents/Converters/JsonCreationConverter.cs | C# | mit | 3,851 |
<?php
$files = array('global', 'module', 'admin', 'bootstrap', 'bootstrap-responsive', 'bootstrap-wysihtml5','datetimepicker');
$extended = array('install' => 'installation css', 'mailer' => 'Custom mailer css');
/* Do not edit below this line //-------------------------------*/
header("Content-Type: text/css; charset: UTF-8");
header("Cache-Control: must-revalidate");
header("Last-Modified: " . date(DateTime::RFC1123));
header("Expires: " . date(DateTime::RFC1123, time() + 600));
$css_file = '/*
------------------------------------------------------------
Expanse
http://expansecms.org
Content management for the web deisgner, by the web designer
Written, with love, by Ian Tearle @iantearle
Based on original work by Nate Cavanaugh and Jason Morrison
All rights reserved.
============================================================
*/
';
$folder = dirname(__FILE__).'/';
echo $css_file;
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}
$get_extended = isset($_GET['extend']) && ctype_alnum($_GET['extend']) ? $_GET['extend'] : '';
/* your css files */
foreach($files as $include) {
$include = trim($include);
if(!empty($get_extended) && isset($extended[$get_extended])) {
$the_file = $folder.$get_extended.'.css';
} else {
$the_file = $folder.$include.'.css';
}
if(empty($include) || !file_exists($the_file)) {
continue;
}
include($the_file);
}
ob_end_flush(); | iantearle/Expanse-CMS-Public | expanse/css/expanse.css.php | PHP | mit | 1,657 |
module.exports={
setup(context, cb){
//context.sigslot.signalAt('* * * * * *', 'sayHello')
cb()
},
sep(msg,next){
console.log(msg); return next()
},
route(req, next){
switch(req.method){
case 'POST': return next()
case 'GET': this.setOutput(this.time)
default: return next(null, this.sigslot.abort())
}
},
help(next){
next(this.error(404, `api ${this.api} is not supported yet`))
},
sayNow(next){
console.log(Date.now())
next()
}
}
| ldarren/pico-api | test/util.js | JavaScript | mit | 464 |
<?php
namespace Murky\HomeBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
| rlbaltha/biblio | src/Murky/HomeBundle/Tests/Controller/DefaultControllerTest.php | PHP | mit | 399 |
/***********************************************
* MIT License
*
* Copyright (c) 2016 珠峰课堂,Ramroll
* 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.
*
*/
export * from "./ZButton"
export * from "./BButton"
export * from "./navbar/ZNavbar"
export * from "./tabbar/Tabbar"
export * from "./tabbar/TabbarItem"
export * from "./ZBottomButton"
export * from "./NetworkError"
export * from "./CourseCardBig"
export * from "./CourseCardSmall"
export * from "./ZInput"
export * from "./ZSwitch"
export * from "./ZVCode"
export * from "./ZImgCode"
export * from "./NavBar"
export * from "./HomeMenuView"
export * from "./HomeMenuItem"
export * from "./HomeGridView"
export * from "./HomeGridItem"
export * from "./QrImage"
| njxiaohan/TransPal | app/domain/component/index.js | JavaScript | mit | 1,752 |
goog.provide('ngeo.CreatefeatureController');
goog.provide('ngeo.createfeatureDirective');
goog.require('ngeo');
goog.require('ngeo.EventHelper');
/** @suppress {extraRequire} */
goog.require('ngeo.filters');
goog.require('ngeo.interaction.MeasureArea');
goog.require('ngeo.interaction.MeasureLength');
goog.require('ol.Feature');
goog.require('ol.geom.GeometryType');
goog.require('ol.interaction.Draw');
goog.require('ol.style.Style');
/**
* A directive used to draw vector features of a single geometry type using
* either a 'draw' or 'measure' interaction. Once a feature is finished being
* drawn, it is added to a collection of features.
*
* The geometry types supported are:
* - Point
* - LineString
* - Polygon
*
* Example:
*
* <a
* href
* translate
* ngeo-btn
* ngeo-createfeature
* ngeo-createfeature-active="ctrl.createPointActive"
* ngeo-createfeature-features="ctrl.features"
* ngeo-createfeature-geom-type="ctrl.pointGeomType"
* ngeo-createfeature-map="::ctrl.map"
* class="btn btn-default ngeo-createfeature-point"
* ng-class="{active: ctrl.createPointActive}"
* ng-model="ctrl.createPointActive">
* </a>
*
* @htmlAttribute {boolean} ngeo-createfeature-active Whether the directive is
* active or not.
* @htmlAttribute {ol.Collection} ngeo-createfeature-features The collection of
* features where to add those created by this directive.
* @htmlAttribute {string} ngeo-createfeature-geom-type Determines the type
* of geometry this directive should draw.
* @htmlAttribute {ol.Map} ngeo-createfeature-map The map.
* @return {angular.Directive} The directive specs.
* @ngInject
* @ngdoc directive
* @ngname ngeoCreatefeature
*/
ngeo.createfeatureDirective = function() {
return {
controller: 'ngeoCreatefeatureController as cfCtrl',
bindToController: true,
scope: {
'active': '=ngeoCreatefeatureActive',
'features': '=ngeoCreatefeatureFeatures',
'geomType': '=ngeoCreatefeatureGeomType',
'map': '=ngeoCreatefeatureMap'
}
};
};
ngeo.module.directive('ngeoCreatefeature', ngeo.createfeatureDirective);
/**
* @param {gettext} gettext Gettext service.
* @param {angular.$compile} $compile Angular compile service.
* @param {angular.$filter} $filter Angular filter
* @param {!angular.Scope} $scope Scope.
* @param {angular.$timeout} $timeout Angular timeout service.
* @param {ngeo.EventHelper} ngeoEventHelper Ngeo event helper service
* @constructor
* @struct
* @ngInject
* @ngdoc controller
* @ngname ngeoCreatefeatureController
*/
ngeo.CreatefeatureController = function(gettext, $compile, $filter, $scope,
$timeout, ngeoEventHelper) {
/**
* @type {boolean}
* @export
*/
this.active = this.active === true;
/**
* @type {ol.Collection.<ol.Feature>|ol.source.Vector}
* @export
*/
this.features;
/**
* @type {string}
* @export
*/
this.geomType;
/**
* @type {ol.Map}
* @export
*/
this.map;
/**
* @type {angular.$timeout}
* @private
*/
this.timeout_ = $timeout;
/**
* @type {ngeo.EventHelper}
* @private
*/
this.ngeoEventHelper_ = ngeoEventHelper;
// Create the draw or measure interaction depending on the geometry type
var interaction;
var helpMsg;
var contMsg;
if (this.geomType === ngeo.GeometryType.POINT ||
this.geomType === ngeo.GeometryType.MULTI_POINT
) {
interaction = new ol.interaction.Draw({
type: ol.geom.GeometryType.POINT
});
} else if (this.geomType === ngeo.GeometryType.LINE_STRING ||
this.geomType === ngeo.GeometryType.MULTI_LINE_STRING
) {
helpMsg = gettext('Click to start drawing length');
contMsg = gettext(
'Click to continue drawing<br/>' +
'Double-click or click last point to finish'
);
interaction = new ngeo.interaction.MeasureLength(
$filter('ngeoUnitPrefix'),
{
style: new ol.style.Style(),
startMsg: $compile('<div translate>' + helpMsg + '</div>')($scope)[0],
continueMsg: $compile('<div translate>' + contMsg + '</div>')($scope)[0]
}
);
} else if (this.geomType === ngeo.GeometryType.POLYGON ||
this.geomType === ngeo.GeometryType.MULTI_POLYGON
) {
helpMsg = gettext('Click to start drawing area');
contMsg = gettext(
'Click to continue drawing<br/>' +
'Double-click or click starting point to finish'
);
interaction = new ngeo.interaction.MeasureArea(
$filter('ngeoUnitPrefix'),
{
style: new ol.style.Style(),
startMsg: $compile('<div translate>' + helpMsg + '</div>')($scope)[0],
continueMsg: $compile('<div translate>' + contMsg + '</div>')($scope)[0]
}
);
}
goog.asserts.assert(interaction);
interaction.setActive(this.active);
this.map.addInteraction(interaction);
/**
* The draw or measure interaction responsible of drawing the vector feature.
* The actual type depends on the geometry type.
* @type {ol.interaction.Interaction}
* @private
*/
this.interaction_ = interaction;
// == Event listeners ==
$scope.$watch(
function() {
return this.active;
}.bind(this),
function(newVal) {
this.interaction_.setActive(newVal);
}.bind(this)
);
var uid = ol.getUid(this);
if (interaction instanceof ol.interaction.Draw) {
this.ngeoEventHelper_.addListenerKey(
uid,
ol.events.listen(
interaction,
ol.interaction.Draw.EventType.DRAWEND,
this.handleDrawEnd_,
this
),
true
);
} else if (interaction instanceof ngeo.interaction.MeasureLength ||
interaction instanceof ngeo.interaction.MeasureArea) {
this.ngeoEventHelper_.addListenerKey(
uid,
ol.events.listen(
interaction,
ngeo.MeasureEventType.MEASUREEND,
this.handleDrawEnd_,
this
),
true
);
}
$scope.$on('$destroy', this.handleDestroy_.bind(this));
};
/**
* Called when a feature is finished being drawn. Add the feature to the
* collection.
* @param {ol.interaction.Draw.Event|ngeo.MeasureEvent} event Event.
* @export
*/
ngeo.CreatefeatureController.prototype.handleDrawEnd_ = function(event) {
var feature = new ol.Feature(event.feature.getGeometry());
if (this.features instanceof ol.Collection) {
this.features.push(feature);
} else {
this.features.addFeature(feature);
}
};
/**
* Cleanup event listeners and remove the interaction from the map.
* @private
*/
ngeo.CreatefeatureController.prototype.handleDestroy_ = function() {
this.timeout_(function() {
var uid = ol.getUid(this);
this.ngeoEventHelper_.clearListenerKey(uid);
this.interaction_.setActive(false);
this.map.removeInteraction(this.interaction_);
}.bind(this), 0);
};
ngeo.module.controller(
'ngeoCreatefeatureController', ngeo.CreatefeatureController);
| ger-benjamin/ngeo | src/directives/createfeature.js | JavaScript | mit | 6,955 |
using System.Collections.Generic;
using System.Security.Claims;
namespace FujiyBlog.Web.Areas.Admin.ViewModels
{
public class AdminRoleSave
{
public string Id { get; set; }
public string Name { get; set; }
public IEnumerable<string> Claims { get; set; }
}
}
| fujiy/FujiyBlog | src/FujiyBlog.Web/Areas/Admin/ViewModels/AdminRoleSave.cs | C# | mit | 302 |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class StartMenuUIControl : MonoBehaviour {
/*===================== GameObjects =====================================================================================*/
public GameObject characterCreationMenuPrefab;
/*===================== Menus =====================================================================================*/
public GameObject characterCreationMenu;
/*===================== UI Elements =====================================================================================*/
public Button StartNewGameButton;
public Button LoadGameButton;
public Button GameInfoButton;
public Button ExitGameButton;
/*===================== Methods =====================================================================================*/
/*===================== Start() =====================================================================================*/
void Start(){
// Setup the characterCreationMenu
// Get reference for menu because it was instantiated
characterCreationMenu = GameObject.FindWithTag ("CharacterCreationMenu");
// Set characterCreationMenu's aphla to 0 (Makes transperent)
characterCreationMenu.GetComponent<CanvasGroup> ().alpha = 0;
// Block raycasts - making the menu not clickable
characterCreationMenu.GetComponent<CanvasGroup> ().blocksRaycasts = false;
// Activate CharacterCreationMenu
characterCreationMenu.gameObject.SetActive (true);
// Activate CharacterTraitsMenu
characterCreationMenu.GetComponent<CharacterCreationUIControl> ().characterTraitsMenu.gameObject.SetActive (true);
} // Start()
/*===================== NewGame() =====================================================================================*/
// Fires when player clicks "StartNewGameButton"
public void NewGame(){
// Deactivates MainMenu
gameObject.SetActive(false);
// Activates Character Creation Menu
characterCreationMenu.gameObject.SetActive(true);
// Runs setup needed for characterCreationMenu
characterCreationMenu.GetComponent<CharacterCreationUIControl> ().SetUp ();
} // NewGame()
/*===================== LoadGame() =====================================================================================*/
// Fires when player clicks "LoadGameButton"
public void LoadGame(){
Application.LoadLevel (1);
} // LoadGame()
/*===================== GameInfo() =====================================================================================*/
// Fires when player clicks "GameInfoButton"
public void GameInfo(){
} // GameInfo()
/*===================== ExitGame() =====================================================================================*/
// Fires when player clicks "ExitGameButton"
public void ExitGame(){
// Exits the game
Application.Quit();
} // ExitGame()
} // class
| Ross-Byrne/Management_Mayhem | Assets/Scripts/UI/StartMenu/StartMenuUIControl.cs | C# | mit | 2,906 |
Mini.define('layerTemplate', function(){
var $detail = $('#t-detail').html()
return {
detail: _.template($detail)
}
});
Mini.define('serviceLayer', [
'layerTemplate'
], function(layerTemplate){
return {
ctn: function(e) {
layer.open({
title: '箱动态列表',
type: 1,
skin: 'layui-layer-rim my-layer-skin', //加上边框
area: ['480px', 'auto'], //宽高
content: layerTemplate.detail(e.data)
})
}
}
}) | hoozi/hyd2 | js/site/components/serviceLayer.js | JavaScript | mit | 559 |
# frozen_string_literal: true
Rails.application.routes.draw do
match "lock/login", to: "lock#login", as: "lock_login", via: :get
match "lock/refused", to: "lock#refused", as: "unlock_refused", via: :get
match "lock/unlock", to: "lock#unlock", as: "unlock", via: :post
end
| charlotte-ruby/lock | config/routes.rb | Ruby | mit | 279 |
// For vendors for example jQuery, Lodash, angular2-jwt just import them here unless you plan on
// chunking vendors files for async loading. You would need to import the async loaded vendors
// at the entry point of the async loaded file. Also see custom-typings.d.ts as you also need to
// run `typings install x` where `x` is your module
// Angular 2
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/router';
import '@angular/forms';
import '@angular/common';
import '@angular/core';
import '@angular/http';
import '@angularclass/form-validators';
// RxJS
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
if ('production' === ENV) {
// Production
} else {
// Development
}
| katallaxie/generator-angular2-starter | template/src/vendor.ts | TypeScript | mit | 756 |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Internal function to process the separation of a physics body from a tile.
*
* @function Phaser.Physics.Arcade.Tilemap.ProcessTileSeparationX
* @since 3.0.0
*
* @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
* @param {number} x - The x separation amount.
*/
var ProcessTileSeparationX = function (body, x)
{
if (x < 0)
{
body.blocked.left = true;
}
else if (x > 0)
{
body.blocked.right = true;
}
body.position.x -= x;
if (body.bounce.x === 0)
{
body.velocity.x = 0;
}
else
{
body.velocity.x = -body.velocity.x * body.bounce.x;
}
};
module.exports = ProcessTileSeparationX;
| rblopes/phaser | src/physics/arcade/tilemap/ProcessTileSeparationX.js | JavaScript | mit | 901 |
<?php
namespace Oro\Bundle\UserBundle\Tests\Unit\Type;
use Oro\Bundle\UserBundle\Form\Type\ChangePasswordType;
use Symfony\Component\Form\Test\FormIntegrationTestCase;
class ChangePasswordTypeTest extends FormIntegrationTestCase
{
/** @var \PHPUnit_Framework_MockObject_MockObject */
protected $subscriber;
/** @var ChangePasswordType */
protected $type;
public function setUp()
{
parent::setUp();
$this->subscriber = $this->getMockBuilder('Oro\Bundle\UserBundle\Form\EventListener\ChangePasswordSubscriber')
->disableOriginalConstructor()
->getMock();
$this->type = new ChangePasswordType($this->subscriber);
}
/**
* Test buildForm
*/
public function testBuildForm()
{
$builder = $this->getMock('Symfony\Component\Form\Test\FormBuilderInterface');
$options = array();
$builder->expects($this->once())
->method('addEventSubscriber')
->with($this->isInstanceOf('Oro\Bundle\UserBundle\Form\EventListener\ChangePasswordSubscriber'));
$builder->expects($this->exactly(2))
->method('add')
->will($this->returnSelf());
$this->type->buildForm($builder, $options);
}
/**
* Test defaults
*/
public function testSetDefaultOptions()
{
$resolver = $this->getMock('Symfony\Component\OptionsResolver\OptionsResolverInterface');
$resolver->expects($this->once())
->method('setDefaults')
->with($this->isType('array'));
$this->type->configureOptions($resolver);
}
/**
* Test name
*/
public function testName()
{
$this->assertEquals('oro_change_password', $this->type->getName());
}
}
| akeneo/platform | src/Oro/Bundle/UserBundle/Tests/Unit/Form/Type/ChangePasswordTypeTest.php | PHP | mit | 1,781 |
export function mergeUsers({ props, state, uuid }) {
if (props.response.result.users && props.response.result.users.length !== 0) {
let orderKey = 1
for (const user of props.response.result.users) {
user.orderKey = orderKey
const usersInState = state.get('admin.users')
const uidInState = Object.keys(usersInState).filter((uid) => {
return usersInState[uid].email === user.email
})[0]
if (uidInState) {
state.merge(`admin.users.${uidInState}`, user)
} else {
state.set(`admin.users.${uuid()}`, user)
}
orderKey++
}
} else {
return { noUsersFound: true }
}
}
export function getNextPage({ props, state }) {
let nextPage = 1
switch (props.nextPage) {
case 'previous':
nextPage = parseInt(state.get('admin.currentPage')) - 1
break
case 'next':
nextPage = parseInt(state.get('admin.currentPage')) + 1
break
case 'last':
nextPage = state.get('admin.pages')
break
default:
if (typeof props.nextPage === 'number') {
nextPage = Math.floor(props.nextPage)
}
}
return { nextPage }
}
| yacoma/auth-boilerplate | client/app/modules/admin/actions.js | JavaScript | mit | 1,148 |
<?php
namespace Dodici\Fansworld\WebBundle\Controller;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Dodici\Fansworld\WebBundle\Controller\SiteController;
use Dodici\Fansworld\WebBundle\Entity\Comment;
use Dodici\Fansworld\WebBundle\Entity\Contest;
use Dodici\Fansworld\WebBundle\Entity\ContestParticipant;
use Dodici\Fansworld\WebBundle\Entity\ContestVote;
use Dodici\Fansworld\WebBundle\Entity\Privacy;
use Symfony\Component\HttpFoundation\Request;
/**
* Home controller.
*/
class ContestController extends SiteController
{
const commentsLimit = 6;
const contestLimit = 20;
const participantsLimit = 5;
/**
* Site's home
*
* @Template
*/
public function indexAction()
{
return array(
);
}
/**
* My Contests
*
* @Route("/my-contests", name="contest_mycontests")
* @Template
*/
public function myContestsAction()
{
$user = $this->getUser();
$participating = $this->getRepository('ContestParticipant')->userParticipating($user);
$contests = array();
foreach ($participating as $item) {
$contest = $this->getRepository('Contest')->find($item->getContest()->getId());
$contests[] = $contest;
}
return array(
'user' => $user,
'contests' => $contests
);
}
/**
*
* @Route("/ajax/contest/comments", name="contest_ajaxcomments")
*/
public function ajaxCommentsAction()
{
$request = $this->getRequest();
$contestId = $request->get('contestId');
$page = $request->get('page', 0);
$page--;
$contestRepo = $this->getRepository('Contest');
$contestComments = $contestRepo->findOneBy(array('id' => $contestId))->getComments();
$chunked = array_chunk($contestComments, self::commentsLimit);
$response = new Response(json_encode($chunked[$page]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/ajax/contest/add_comment", name = "contest_ajaxaddcomment")
*/
public function ajaxAddCommentAction()
{
$response = null;
try {
$request = $this->getRequest();
$contestId = $request->get('contestId');
$content = $request->get('content');
$contest = $this->getRepository('Contest')->findOneBy(array('id' => $contestId));
$user = $this->getUser();
$newComment = new Comment();
$newComment->setAuthor($user);
$newComment->setContent($content);
$newComment->setContest($contest);
$newComment->setActive(true);
$newComment->setPrivacy(Privacy::EVERYONE);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($newComment);
$em->flush();
$response = array(
'saved' => true,
'comment' => array(
'id' => $newComment->getId(),
'name' => (string) $user,
'content' => $content,
'avatar' => $this->getImageUrl($user->getImage()),
'createdAt' => $newComment->getCreatedAt(),
'like' => $this->renderView('DodiciFansworldWebBundle:Default:like_button.html.twig', array(
'showcount' => false,
'entity' => $newComment
))
)
);
} catch (\Exception $exc) {
$response = array('saved' => false, 'exception' => $exc->getMessage());
}
$response = new Response(json_encode($response));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/ajax/contest/participate", name="contest_ajaxparticipate")
*/
public function ajaxParticipateAction()
{
$request = $this->getRequest();
$contest = $request->get('contestId');
$user = $this->getUser();
$contest = $this->getRepository('Contest')->findOneBy(array('id' => $contest));
$isParticipant = $this->getRepository('ContestParticipant')->findOneBy(array('author' => $user, 'contest' => $contest));
if (!$isParticipant) {
try {
$newParticipant = new ContestParticipant();
$newParticipant->setAuthor($user);
switch ($contest->getType()) {
case Contest::TYPE_TEXT:
$newParticipant->setText($request->get('text'));
break;
case Contest::TYPE_PHOTO:
$photoId = $request->get('photo');
$photo = $this->getRepository('Photo')->find($photoId);
$newParticipant->setPhoto($photo);
break;
case Contest::TYPE_VIDEO:
$videoId = $request->get('video');
$video = $this->getRepository('Video')->find($videoId);
$newParticipant->setVideo($video);
break;
}
$newParticipant->setContest($contest);
$newParticipant->setWinner(false);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($newParticipant);
$em->flush();
$response = true;
} catch (\Exception $exc) {
echo $exc->getMessage();
$response = false;
}
} else {
$response = false;
}
$response = new Response(json_encode($response));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/contests", name="contest_list")
*
* @Template
*/
public function listAction()
{
$contests = $this->getRepository('Contest')->findBy(array('active' => true), array('createdAt' => 'desc'), self::contestLimit);
$countContests = $this->getRepository('Contest')->countBy(array('active' => true));
$addMore = $countContests > self::contestLimit ? true : false;
$filterType = array(
'TYPE_PARTICIPATE' => Contest::TYPE_PARTICIPATE,
'TYPE_TEXT' => Contest::TYPE_TEXT,
'TYPE_PHOTO' => Contest::TYPE_PHOTO,
'TYPE_VIDEO' => Contest::TYPE_VIDEO
);
return array('contests' => $contests, 'addMore' => $addMore, 'filterType' => $filterType);
}
/**
* @Route("/ajax/contest/list", name="contest_ajaxlist")
*/
public function ajaxListAction()
{
$request = $this->getRequest();
$filter = $request->get('filter', false);
$page = $request->get('page', 1);
$page--;
$offset = $page * self::contestLimit;
if ($filter && $filter !== 'null') {
$criteria = array(
'active' => true,
'type' => $filter
);
} else {
$criteria = array(
'active' => true
);
}
$contests = $this->getRepository('Contest')->findBy($criteria, array('createdAt' => 'desc'), self::contestLimit, $offset);
$contestsCount = $this->getRepository('Contest')->countBy($criteria);
$contestsCount = $contestsCount / self::contestLimit;
$addMore = $contestsCount > $page ? true : false;
$response = array();
foreach ($contests as $contest) {
$response[] = array(
'id' => $contest->getId(),
'title' => $contest->getTitle(),
'active' => $contest->getActive(),
'content' => $contest->getContent(),
'image' => $this->getImageUrl($contest->getImage()),
'createdAt' => $contest->getCreatedAt(),
'endDate' => $contest->getEndDate(),
'type' => $contest->getType(),
'slug' => $contest->getSlug()
);
}
$response = new Response(json_encode(array('contests' => $response, 'addMore' => $addMore)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/contest/{id}/{slug}", name= "contest_show", defaults = {"id" = 0}, requirements={"id"="\d+"})
* @Template
* @Secure(roles="ROLE_USER")
*/
public function showAction($id)
{
if ($id > 0) {
$contest = $this->getRepository('Contest')->findOneBy(array('id' => $id));
} else {
$contest = false;
}
$user = $this->getUser();
$isParticipant = $this->getRepository('ContestParticipant')->findOneBy(array('contest' => $contest->getId(), 'author' => $user->getId()));
$participants = $this->getRepository('ContestParticipant')->findBy(array('contest' => $contest->getId()), array('createdAt' => 'desc'), self::participantsLimit);
$countAllParticipants = $this->getRepository('ContestParticipant')->countBy(array('contest' => $contest->getId()));
$addMoreParticipants = $countAllParticipants > self::participantsLimit ? true : false;
$winners = $this->getRepository('ContestParticipant')->findBy(array('contest' => $contest->getId(), 'winner' => true));
$filesUploaded = array();
$textUploaded = array();
$participants = $this->getRepository('ContestParticipant')->findBy(array('contest' => $contest->getId()), array('createdAt' => 'desc'), self::participantsLimit);
$alreadyVoted = $this->getRepository('ContestVote')->byUserAndContest($user, $contest);
switch ($contest->getType()) {
case Contest::TYPE_TEXT:
foreach ($participants as $participant) {
$cantVotes = $this->getRepository('ContestVote')->countBy(array('contestparticipant' => $participant->getId()));
array_push($textUploaded, array(
'participantId' => $participant->getId(),
'text' => $participant->getText(),
'author' => $participant->getAuthor(),
'votes' => $cantVotes
));
}
break;
case Contest::TYPE_PHOTO:
foreach ($participants as $participant) {
if($participant->getPhoto()){
$cantVotes = $this->getRepository('ContestVote')->countBy(array('contestparticipant' => $participant->getId()));
array_push($filesUploaded, array(
'participantId' => $participant->getId(),
'file' => $participant->getPhoto(),
'author' => $participant->getAuthor(),
'votes' => $cantVotes
));
}
}
break;
case Contest::TYPE_VIDEO:
foreach ($participants as $participant) {
if($participant->getVideo()){
$cantVotes = $this->getRepository('ContestVote')->countBy(array('contestparticipant' => $participant->getId()));
array_push($filesUploaded, array(
'participantId' => $participant->getId(),
'file' => $participant->getVideo(),
'author' => $participant->getAuthor(),
'votes' => $cantVotes
));
}
}
}
return array('contest' => $contest, 'voted' => $alreadyVoted, 'isParticipant' => $isParticipant, 'participants' => $participants, 'winners' => $winners, 'files' => $filesUploaded, 'texts' => $textUploaded, 'addMoreParticipants' => $addMoreParticipants);
}
/**
* @Route("/ajax/contest/participants", name="contest_pagerParticipants")
*/
public function pagerParticipants()
{
$request = $this->getRequest();
$contestId = $request->get('contest');
$page = $request->get('page', 1);
$offset = ($page - 1) * self::participantsLimit;
$response = array();
$countAllParticipants = $this->getRepository('ContestParticipant')->countBy(array('contest' => $contestId));
$participantsCount = $countAllParticipants / self::participantsLimit;
$response['addMore'] = $participantsCount > $page ? true : false;
$participants = $this->getRepository('ContestParticipant')->findBy(array('contest' => $contestId), array('createdAt' => 'desc'), self::participantsLimit, $offset);
foreach ($participants as $participant) {
$author = $participant->getAuthor();
$element = array();
$cantVotes = $this->getRepository('ContestVote')->countBy(array('contestparticipant' => $participant->getId()));
switch ($participant->getContest()->getType()) {
case Contest::TYPE_TEXT:
$element = array(
'id' => $participant->getId(),
'text' => $participant->getText(),
'votes' => $cantVotes
);
break;
case Contest::TYPE_PHOTO:
$element = array(
'id' => $participant->getPhoto()->getId(),
'image' => $this->getImageUrl($participant->getPhoto()),
'votes' => $cantVotes
);
break;
case Contest::TYPE_VIDEO:
$element = array(
'id' => $participant->getVideo()->getId(),
'votes' => $cantVotes
);
break;
}
$response['participants'][] = array(
'id' => $author->getId(),
'name' => (string) $author,
'avatar' => $this->getImageUrl($author->getImage()),
'contestType' => $participant->getContest()->getType(),
'element' => $element
);
}
return $this->jsonResponse($response);
}
/**
* @Route("/ajax/contest/participant/vote", name="contest_voteParticipant")
*/
public function voteParticipant()
{
$request = $this->getRequest();
$contestId = $request->get('contest', false);
$participantId = $request->get('participant', false);
$author = $this->getUser();
$response = array();
$participant = $this->getRepository('ContestParticipant')->find($participantId);
$contest = $this->getRepository('Contest')->find($contestId);
$alreadyVoted = $this->getRepository('ContestVote')->byUserAndContest($author, $contest);
if (!$alreadyVoted) {
try {
$entity = new ContestVote;
$entity->setAuthor($author);
$entity->setContestparticipant($participant);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
$response['voted'] = true;
} catch (Exception $exc) {
$response['voted'] = false;
$response['error'] = $exc->getMessage();
}
} else {
$response['voted'] = false;
$response['error'] = 'already voted';
}
return $this->jsonResponse($response);
}
}
| FansWorldTV/web | src/Dodici/Fansworld/WebBundle/Controller/ContestController.php | PHP | mit | 16,104 |
QuakeMap::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = 'public, max-age=3600'
# Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets
config.assets.allow_debugging = true
end
| QuakeMap/quakemap | config/environments/test.rb | Ruby | mit | 1,814 |
package errors
import (
"net/http"
"fmt"
)
// NewValidationError creates a new APIError with 422 Unprocessable entity http status code to be used as reporting the validation failure
func NewValidationError(e ... error) APIError {
return APIError{
StatusCode: http.StatusUnprocessableEntity,
Title: "Request data validation error",
LocalizationKey: "validation_error",
Errors: e,
}
}
// NewParameterRequiredError returns a new native error reporting that a specified parameter is missing
func NewParameterRequiredError(param string) error {
return New(fmt.Sprintf("Parameter %s is required", param))
}
// NewParameterRequiredError returns a new native error reporting that a specified parameter is invalid
func NewParameterInvalidError(param string) error {
return New(fmt.Sprintf("Parameter %s failed to pass validation", param))
}
| uroshercog/kanban-board-backend | http/errors/validation.go | GO | mit | 874 |