repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
snukal/All-Telerik-Homeworks | C#OOP/Defining-Classes-Part-1-Constructors-Properties/1. Define class/Calls.cs | 445 | namespace GSMove
{
using System;
public class Call
{
private DateTime date;
private DateTime time;
private string dialedNumber;
private int duration;
public Call(DateTime date, DateTime time, string dialed, int duration)
{
this.date = date;
this.time = time;
this.dialedNumber = dialed;
this.duration = duration;
}
}
} | mit |
scci/security-employee-tracker | resources/views/visit/create.blade.php | 486 | @extends('layouts.master')
@section('title', 'Add A Visit')
@section('content')
<div class="card">
<div class="card-content">
<div class="card-title">Add a Visit</div>
{!! Form::open(array('action' => ['VisitController@store', $user->id], 'method' => 'POST')) !!}
@include('visit._form', ['submit' => 'Create'])
{!! Form::close() !!}
</div>
</div>
@stop
@section('help')
<h3>Add a Visit</h3>
@stop
| mit |
nemesis-platform/platform | src/NemesisPlatform/Modules/Game/QAGame/Controller/Admin/RoundController.php | 3598 | <?php
/**
* Created by PhpStorm.
* User: Pavel Batanov <[email protected]>
* Date: 19.06.2015
* Time: 14:58
*/
namespace NemesisPlatform\Modules\Game\QAGame\Controller\Admin;
use Doctrine\ORM\EntityManager;
use NemesisPlatform\Modules\Game\QAGame\Entity\QARound;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Class RoundController
*
* @package NemesisPlatform\Modules\Game\QAGame\Controller\Admin
* @Route("/round")
*/
class RoundController extends Controller
{
/**
* @param Request $request
*
* @Route("/create", name="admin_module_qa_game_round_create")
* @Method({"GET","POST"})
* @Template()
*
* @return Response|array
*/
public function createAction(Request $request)
{
/** @var EntityManager $manager */
$manager = $this->getDoctrine()->getManager();
$form = $this->createForm('module_qa_game_round');
$form->add('submit', 'submit', ['label' => 'Создать раунд']);
$form->handleRequest($request);
if ($form->isValid()) {
$round = $form->getData();
$manager->persist($round);
$manager->flush();
$this->get('session')->getFlashBag()->add('success', 'Успешное создание раунда');
return $this->redirectToRoute('module_qa_game_admin_dashboard');
}
return ['form' => $form->createView()];
}
/**
* @param $round
*
* @Route("/{round}/delete", name="admin_module_qa_game_round_delete")
* @Method("GET")
*
* @return RedirectResponse
*/
public function deleteAction(QARound $round)
{
$manager = $this->getDoctrine()->getManager();
$manager->remove($round);
$manager->flush();
$this->get('session')->getFlashBag()->add('warning', 'Раунд был успешно удален');
return $this->redirectToRoute('module_qa_game_admin_dashboard');
}
/**
* @Route("/{round}/edit", name="admin_module_qa_game_round_edit")
* @Method({"GET","POST"})
* @Template()
*
* @param Request $request
* @param $round
*
* @return Response|array
*/
public function editAction(Request $request, QARound $round)
{
/** @var EntityManager $manager */
$manager = $this->getDoctrine()->getManager();
$form = $this->createForm('module_qa_game_round', $round)
->add('submit', 'submit', ['label' => 'Обновить раунд']);
$form->handleRequest($request);
if ($form->isValid()) {
$manager->flush();
$this->get('session')->getFlashBag()->add('success', 'Раунд успешно обновлен');
return $this->redirectToRoute('module_qa_game_admin_dashboard');
}
return [
'form' => $form->createView(),
'round' => $round,
];
}
/**
* @param QARound $round
*
* @return array
* @Route("/{round}/view", name="admin_module_qa_game_round_view")
* @Method("GET")
* @Template()
*/
public function viewAction(QARound $round)
{
return [
'round' => $round,
];
}
}
| mit |
dcrystalj/RubiKS | rubiKS/app/database/migrations/2014_03_16_193026_create_credits_table.php | 474 | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateCreditsTable extends Migration {
public function up()
{
Schema::create('credits', function(Blueprint $table) {
$table->increments('id');
$table->string('organization');
$table->string('address');
$table->string('url');
$table->string('banner');
$table->string('visible', 1);
});
}
public function down()
{
Schema::drop('credits');
}
} | mit |
petehouston/bladie | src/BladieServiceProvider.php | 1278 | <?php namespace Petehouston\Bladie;
use Illuminate\Support\ServiceProvider;
class BladieServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->registerBladeExtensions();
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
/**
* Register Blade extensions.
*
* @return void
*/
protected function registerBladeExtensions()
{
// get blade compiler
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
// add guest
$this->addGuest($blade);
}
/**
* Add Auth::guest() checking syntax
*
* @param [Blade] $blade the Blade compiler
*/
protected function addGuest($blade)
{
$blade->extend(function($view, $compiler)
{
return preg_replace('/@guest/', '<?php if( Auth::guest() ): ?>', $view);
});
$blade->extend(function($view, $compiler)
{
$pattern = $compiler->createPlainMatcher('endguest');
return preg_replace($pattern, '<?php endif; ?>', $view);
});
}
} | mit |
McShooterz/OpenSpace4x | Assets/Scripts/Enum/StarType.cs | 470 | /*****************************************************************************************************************************************
Author: Michael Shoots
Email: [email protected]
Project: Open Space 4x
License: MIT License
Notes:
******************************************************************************************************************************************/
using UnityEngine;
using System.Collections;
public enum StarType
{
Yellow
}
| mit |
AshwinKumarVijay/ECS-Development | ECS/Project/Project/Systems/RenderingSystem/RenderingSystem.cpp | 19462 | #include "RenderingSystem.h"
#include "../../ECS/EntityManager/EntityManager.h"
#include "../ECS/DispatcherReceiver/EventDispatcher/EventDispatcher.h"
#include "../ECS/DispatcherReceiver/EventReceiver/EventReceiver.h"
#include "../../ECS/ECSEvent/ECSEvent.h"
#include "../Events/ResourceEvent/ResourceEvent.h"
#include "../Renderers/Renderer/Renderer.h"
#include "../Renderers/BasicRenderer/BasicRenderer.h"
#include "../Renderers/DeferredRenderer/DeferredRenderer.h"
#include "../Renderers/Renderable/Renderable.h"
#include "../Camera/Camera.h"
#include "../../ECS/Component/Component.h"
#include "../Components/HierarchyComponent/HierarchyComponent.h"
#include "../Components/TransformComponent/TransformComponent.h"
#include "../Components/GeometryComponent/GeometryComponent.h"
#include "../Components/RenderingComponent/RenderingComponent.h"
#include "../Components/CameraComponent/CameraComponent.h"
#include "../Transform/Transform.h"
// Default RenderingSystem Constructor
RenderingSystem::RenderingSystem(std::shared_ptr<EntityManager> newEntityManager, std::shared_ptr<EventQueue> newEventQueue)
:System(newEntityManager, newEventQueue, ModuleType::TRANSFORM_SYSTEM)
{
}
// Default RenderingSystem Destructor
RenderingSystem::~RenderingSystem()
{
}
// Initialize the Rendering System.
void RenderingSystem::initializeSystem()
{
// Create the Default Renderer.
renderer = std::make_shared<DeferredRenderer>();
// Initialize the Renderer.
renderer->initializeRenderer();
// Create a Default Camera, which will have the default camera data.
defaultCamera = std::make_shared<Camera>();
// Create an Active Camera, into which we will copy over the data camera data, and use it for rendering.
activeCamera = std::make_shared<Camera>();
}
// Update the Rendering System this frame.
void RenderingSystem::update(const float & deltaTime, const float & currentFrameTime, const float & lastFrameTime)
{
// Process the Events.
processEvents(deltaTime, currentFrameTime, lastFrameTime);
// Update the Active Camera.
activeCamera->updateCamera();
// Render the Renderer
renderer->render(deltaTime, currentFrameTime, lastFrameTime, activeCamera);
}
// Process the Events that have occurred.
void RenderingSystem::processEvents(const float & deltaTime, const float & currentFrameTime, const float & lastFrameTime)
{
// Check if there are any Events.
while (getReceiver()->getNumberOfEvents() > 0)
{
// Get the events.
std::shared_ptr<const ECSEvent> nextEvent = getReceiver()->getNextEvent();
// Make sure this Event was not sent out by the Rendering System.
if (nextEvent->getModuleOrigin() != ModuleType::RENDERING_SYSTEM)
{
// Component Added.
if (nextEvent->getEventType() == EventType::COMPONENT_ADDED)
{
// Check if the component added was a Rendering Component.
if (nextEvent->getComponentType() == ComponentType::RENDERING_COMPONENT)
{
addRenderable(nextEvent->getEntityID());
}
} // Component Changed.
else if (nextEvent->getEventType() == EventType::COMPONENT_CHANGED)
{
// Check if the component changed was the Transform Component.
if (nextEvent->getComponentType() == ComponentType::TRANSFORM_COMPONENT)
{
updateRenderable(nextEvent->getEntityID());
updateCamera();
} // Check if the component changed was the Geometry Component.
else if (nextEvent->getComponentType() == ComponentType::GEOMETRY_COMPONENT)
{
updateRenderable(nextEvent->getEntityID());
} // Check if the component changed was the Rendering Component.
else if (nextEvent->getComponentType() == ComponentType::RENDERING_COMPONENT)
{
updateRenderable(nextEvent->getEntityID());
} // Check if the component changed was the Camera Component.
else if (nextEvent->getComponentType() == ComponentType::CAMERA_COMPONENT)
{
updateCamera();
}
else
{
}
} // Component Destroyed.
else if (nextEvent->getEventType() == EventType::COMPONENT_DESTROYED)
{
// Check if the component changed destroyed was a Rendering Component.
if (nextEvent->getComponentType() == ComponentType::RENDERING_COMPONENT)
{
removeRenderable(nextEvent->getEntityID());
}
else if (nextEvent->getComponentType() == ComponentType::CAMERA_COMPONENT)
{
updateCamera();
}
} // Shut Down the System.
else if (nextEvent->getEventType() == EventType::ECS_SHUTDOWN_EVENT)
{
shutDownSystem();
}
}
// Process the Resource Events.
processResourceEvents(nextEvent);
}
}
// Process the Event if it is a ResourceEvent.
void RenderingSystem::processResourceEvents(std::shared_ptr<const ECSEvent> nextEvent)
{
// Convert the event to a Resource ECS Event.
std::shared_ptr<const ResourceEvent> resourceEvent = std::dynamic_pointer_cast<const ResourceEvent>(nextEvent);
// Check if it was a Resource ECS Event.
if (resourceEvent != NULL)
{
if (resourceEvent->getEventType() == EventType::RESOURCE_EVENT)
{
if (resourceEvent->getResourceEventType() == ResourceEventType::RESOURCE_ADDED)
{
// Add the Geometry resource, if the event was a Geometry resource event.
if (resourceEvent->getResourceType() == ResourceType::GEOMETRY_RESOURCE)
{
renderer->addGeometry(resourceEvent->getResourceName(), std::dynamic_pointer_cast<const GeometryData>(resourceEvent->getResourceData()));
} // Add the Material resource, if the event was a Material resource event.
else if (resourceEvent->getResourceType() == ResourceType::MATERIAL_RESOURCE)
{
renderer->addMaterial(resourceEvent->getResourceName(), std::dynamic_pointer_cast<const MaterialData>(resourceEvent->getResourceData()));
} // Add the Shader resource, if the event was a Shader resource event.
else if (resourceEvent->getResourceType() == ResourceType::SHADER_RESOURCE)
{
renderer->addShader(std::dynamic_pointer_cast<const ShaderData>(resourceEvent->getResourceData()));
} // Add the Light resource, if the event was a Light resource event.
else if (resourceEvent->getResourceType() == ResourceType::LIGHT_RESOURCE)
{
renderer->addLight(resourceEvent->getResourceName(), std::dynamic_pointer_cast<const LightData>(resourceEvent->getResourceData()));
} // Add the Texture resource, if the event was a Texture resource event.
else if (resourceEvent->getResourceType() == ResourceType::TEXTURE_RESOURCE)
{
renderer->addTexture(resourceEvent->getResourceName(), std::dynamic_pointer_cast<const TextureData>(resourceEvent->getResourceData()));
}
}
else if (resourceEvent->getResourceEventType() == ResourceEventType::RESOURCE_UPDATED)
{
// Add the Geometry resource, if the event was a Geometry resource event.
if (resourceEvent->getResourceType() == ResourceType::GEOMETRY_RESOURCE)
{
renderer->updateGeometry(resourceEvent->getResourceName(), std::dynamic_pointer_cast<const GeometryData>(resourceEvent->getResourceData()));
} // Add the Material resource, if the event was a Material resource event.
else if (resourceEvent->getResourceType() == ResourceType::MATERIAL_RESOURCE)
{
renderer->updateMaterial(resourceEvent->getResourceName(), std::dynamic_pointer_cast<const MaterialData>(resourceEvent->getResourceData()));
} // Add the Light resource, if the event was a Light resource event.
else if (resourceEvent->getResourceType() == ResourceType::LIGHT_RESOURCE)
{
renderer->updateLight(resourceEvent->getResourceName(), std::dynamic_pointer_cast<const LightData>(resourceEvent->getResourceData()));
} // Add the Texture resource, if the event was a Texture resource event.
else if (resourceEvent->getResourceType() == ResourceType::TEXTURE_RESOURCE)
{
renderer->updateTexture(resourceEvent->getResourceName(), std::dynamic_pointer_cast<const TextureData>(resourceEvent->getResourceData()));
}
}
else if (resourceEvent->getResourceEventType() == ResourceEventType::RESOURCE_DESTROYED)
{
// Delete the appropriate Geometry resource, if it is a Geometry resource.
if (resourceEvent->getResourceType() == ResourceType::GEOMETRY_RESOURCE)
{
renderer->deleteGeometry(resourceEvent->getResourceName());
} // Delete the appropriate Material resource, if it is a Material resource.
else if (resourceEvent->getResourceType() == ResourceType::MATERIAL_RESOURCE)
{
renderer->deleteMaterial(resourceEvent->getResourceName());
} // Delete the appropriate Shader resource, if it is a Shader resource.
else if (resourceEvent->getResourceType() == ResourceType::SHADER_RESOURCE)
{
renderer->deleteShader(resourceEvent->getResourceName());
} // Delete the appropriate Light resource, if it is a Light resource.
else if (resourceEvent->getResourceType() == ResourceType::LIGHT_RESOURCE)
{
renderer->deleteLight(resourceEvent->getResourceName());
} // Dlete the appropriate Texture resource, if it is a Texture resource.
else if (resourceEvent->getResourceType() == ResourceType::TEXTURE_RESOURCE)
{
renderer->deleteTexture(resourceEvent->getResourceName());
}
}
}
}
}
// Return a pointer to the Renderer associated with the Renderer.
std::shared_ptr<Renderer> RenderingSystem::getRenderer()
{
return renderer;
}
// Shut Down the System.
void RenderingSystem::shutDownSystem()
{
renderer->cleanUpRenderer();
}
// Clean up the Rendering System.
void RenderingSystem::destroySystem()
{
}
// Add the Renderable to the associated Renderer.
void RenderingSystem::addRenderable(const long int & entityID)
{
// Get the Rendering Component of the current entity.
std::shared_ptr<RenderingComponent> renderingComponent = std::dynamic_pointer_cast<RenderingComponent>(getEntityManager()->getComponentOfEntity(entityID, ComponentType::RENDERING_COMPONENT, ModuleType::RENDERING_SYSTEM));
// Check if there is actual Rendering Component.
if (renderingComponent != NULL && renderingComponent->getActiveRendering() && renderingComponent->getRenderableID() == -1)
{
// Get the Transform Component of the current entity.
std::shared_ptr<const TransformComponent> transformComponent = std::dynamic_pointer_cast<const TransformComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::TRANSFORM_COMPONENT));
// Get the Geometry Component of the current entity.
std::shared_ptr<const GeometryComponent> geometryComponent = std::dynamic_pointer_cast<const GeometryComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::GEOMETRY_COMPONENT));
// Set the RenderableID associated with the RenderingComponent.
renderingComponent->setRenderableID(renderer->createRenderable());
// Update the Shader Type associated with the Renderable of this EntityID.
updateRenderableShaderType(entityID);
// Update the Geometry Type associated with the Renderable of this EntityID.
updateRenderableGeometryType(entityID);
// Update the Material Type associated with the Renderable of this EntityID.
updateRenderableMaterialType(entityID);
// Update the Transform associated with the Renderable of this EntityID.
updateRenderableTransformMatrix(entityID);
}
}
// Update the Renderable.
void RenderingSystem::updateRenderable(const long int & entityID)
{
// Get the Rendering Component of the current entity.
std::shared_ptr<const RenderingComponent> renderingComponent = std::dynamic_pointer_cast<const RenderingComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::RENDERING_COMPONENT));
// Check if this Rendering Component is Active Rendering.
if (renderingComponent != NULL && !renderingComponent->getActiveRendering())
{
if (renderingComponent->getRenderableID() != -1)
{
std::shared_ptr<RenderingComponent> currentRenderingComponent = std::dynamic_pointer_cast<RenderingComponent>(getEntityManager()->getComponentOfEntity(entityID, ComponentType::RENDERING_COMPONENT, ModuleType::RENDERING_SYSTEM));
removeRenderable(currentRenderingComponent->getRenderableID());
currentRenderingComponent->setRenderableID(-1);
}
}
else if(renderingComponent != NULL && renderingComponent->getActiveRendering())
{
if (renderingComponent->getRenderableID() == -1)
{
addRenderable(entityID);
}
// Update the Shader Type associated with the Renderable of this EntityID.
updateRenderableShaderType(entityID);
// Update the Material Type associated with the Renderable of this EntityID.
updateRenderableMaterialType(entityID);
// Update the Geometry Type associated with the Renderable of this EntityID.
updateRenderableGeometryType(entityID);
// Update the Transform Matrix associated with the Renderable of this EntityID.
updateRenderableTransformMatrix(entityID);
}
else
{
}
}
// Update the Shader Type of the specified Renderable.
void RenderingSystem::updateRenderableShaderType(const long int & entityID)
{
// Get the Rendering Component of the current entity.
std::shared_ptr<const RenderingComponent> renderingComponent = std::dynamic_pointer_cast<const RenderingComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::RENDERING_COMPONENT));
// Check if there is actual Rendering Component.
if (renderingComponent != NULL && renderingComponent->getRenderableID() != -1)
{
// Update the Shader Type associated with this Renderable.
renderer->updateShadingType(renderingComponent->getRenderableID(), renderingComponent->getShadingType());
}
}
// Update the Material Type of the specified Renderable.
void RenderingSystem::updateRenderableMaterialType(const long int & entityID)
{
// Get the Rendering Component of the current entity.
std::shared_ptr<const RenderingComponent> renderingComponent = std::dynamic_pointer_cast<const RenderingComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::RENDERING_COMPONENT));
// Check if there is actual Rendering Component.
if (renderingComponent != NULL && renderingComponent->getRenderableID() != -1)
{
// Update the Material Name associated with this Renderable.
renderer->updateMaterialType(renderingComponent->getRenderableID(), renderingComponent->getMaterialType());
}
}
// Update the Geometry Type of the specified Renderable.
void RenderingSystem::updateRenderableGeometryType(const long int & entityID)
{
// Get the Rendering Component of the current entity.
std::shared_ptr<const RenderingComponent> renderingComponent = std::dynamic_pointer_cast<const RenderingComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::RENDERING_COMPONENT));
// Check if there is actual Rendering Component.
if (renderingComponent != NULL && renderingComponent->getRenderableID() != -1)
{
// Get the Geometry Component of the current entity.
std::shared_ptr<const GeometryComponent> geometryComponent = std::dynamic_pointer_cast<const GeometryComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::GEOMETRY_COMPONENT));
// Update the Geometry Name associated with this Renderable.
renderer->updateGeometryType(renderingComponent->getRenderableID(), geometryComponent->getGeometryType());
}
}
// Update the Transform Matrix of the specified Renderable.
void RenderingSystem::updateRenderableTransformMatrix(const long int & entityID)
{
// Get the Rendering Component of the current entity.
std::shared_ptr<const RenderingComponent> renderingComponent = std::dynamic_pointer_cast<const RenderingComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::RENDERING_COMPONENT));
// Check if there is actual Rendering Component.
if (renderingComponent != NULL && renderingComponent->getRenderableID() != -1)
{
// Get the Transform Component of the current entity.
std::shared_ptr<const TransformComponent> transformComponent = std::dynamic_pointer_cast<const TransformComponent>(getEntityManager()->viewComponentOfEntity(entityID, ComponentType::TRANSFORM_COMPONENT));
// Update the Transform associated with this Renderable.
renderer->updateTransformMatrix(renderingComponent->getRenderableID(), *transformComponent->viewTransform()->getHierarchyTransformMatrix());
}
}
// Update the Camera used with Renderer.
void RenderingSystem::updateCamera()
{
// Get the EntityManager.
std::shared_ptr<EntityManager> entityManager = getEntityManager();
// Get the entities with a Transform Component.
std::shared_ptr<std::vector<long int>> entities = entityManager->getEntitiesWithComponentOfType(ComponentType::CAMERA_COMPONENT);
// Check if an Active Camera Component was found.
bool activeCameraAvailable = false;
// If there are no entities, we do not really have to do anything.
if (entities != NULL)
{
// Iterate over the entities, and process them.
for (auto currentEntity : *entities)
{
// Get the Camera Component.
std::shared_ptr<const TransformComponent> transformComponent = std::dynamic_pointer_cast<const TransformComponent>(entityManager->viewComponentOfEntity(currentEntity, ComponentType::TRANSFORM_COMPONENT));
// Get the Camera Component.
std::shared_ptr<const CameraComponent> cameraComponent = std::dynamic_pointer_cast<const CameraComponent>(entityManager->viewComponentOfEntity(currentEntity, ComponentType::CAMERA_COMPONENT));
// Check if this is the Actice Camera.
if (cameraComponent->getIsActive())
{
// Active Camera.
activeCameraAvailable = true;
// Set the Transform Related Camera Properties.
activeCamera->setCameraPosition(transformComponent->viewTransform()->getPosition());
activeCamera->setUpVector(transformComponent->viewTransform()->getUpVector());
activeCamera->setLookAtDirection(transformComponent->viewTransform()->getFowardDirection());
// Set the Aspect Ratio and Field of View.
activeCamera->setAspectRatio(cameraComponent->getAspectRatio());
activeCamera->setFOV(cameraComponent->getFOV());
// Set the Near and Far Clip.
activeCamera->setFarClip(cameraComponent->getFarClip());
activeCamera->setNearClip(cameraComponent->getNearClip());
}
}
}
// If an Active Camera Component was not found, use the default camera properties.
if (activeCameraAvailable == false)
{
// Set the Transform Related Camera Properties.
activeCamera->setCameraPosition(defaultCamera->getCameraPosition());
activeCamera->setUpVector(defaultCamera->getUpVector());
activeCamera->setLookAtDirection(defaultCamera->getLookAtDirection());
// Set the Aspect Ratio and Field of View.
activeCamera->setAspectRatio(defaultCamera->getAspectRatio());
activeCamera->setFOV(defaultCamera->getFOV());
// Set the Near and Far Clip.
activeCamera->setFarClip(defaultCamera->getFarClip());
activeCamera->setNearClip(defaultCamera->getNearClip());
}
}
// Remove the Renderable.
void RenderingSystem::removeRenderable(const long int & entityID)
{
// Get the Rendering Component of the current entity.
std::shared_ptr<RenderingComponent> renderingComponent = std::dynamic_pointer_cast<RenderingComponent>(getEntityManager()->getComponentOfEntity(entityID, ComponentType::RENDERING_COMPONENT, ModuleType::RENDERING_SYSTEM));
// Check if there is actual Rendering Component.
if (renderingComponent != NULL && renderingComponent->getRenderableID() != -1)
{
// Remove the Renderable from the Renderer.
renderer->removeRenderable(entityID);
// Set the Renderable ID.
renderingComponent->setRenderableID(-1);
}
} | mit |
levjj/esverify-web | src/components/user_study.tsx | 1614 | import * as React from 'react';
import { AppState, Action, UserStudyStep } from '../app';
import UserStudyTutorial1 from './user_study_tutorial_1';
import UserStudyTutorial2 from './user_study_tutorial_2';
import UserStudyTutorial3 from './user_study_tutorial_3';
import UserStudyTutorial4 from './user_study_tutorial_4';
import UserStudyExperiment1 from './user_study_experiment_1';
import UserStudyExperiment2 from './user_study_experiment_2';
import UserStudyExperiment3 from './user_study_experiment_3';
export interface Props {
state: AppState;
dispatch: (action: Action) => void;
}
export default function UserStudy ({ state, dispatch }: Props) {
if (state.userStudy.currentStep === UserStudyStep.TUTORIAL_1) {
return (<UserStudyTutorial1 state={state} dispatch={dispatch} />);
} else if (state.userStudy.currentStep === UserStudyStep.TUTORIAL_2) {
return (<UserStudyTutorial2 state={state} dispatch={dispatch} />);
} else if (state.userStudy.currentStep === UserStudyStep.TUTORIAL_3) {
return (<UserStudyTutorial3 state={state} dispatch={dispatch} />);
} else if (state.userStudy.currentStep === UserStudyStep.TUTORIAL_4) {
return (<UserStudyTutorial4 state={state} dispatch={dispatch} />);
} else if (state.userStudy.currentStep === UserStudyStep.EXPERIMENT_1) {
return (<UserStudyExperiment1 state={state} dispatch={dispatch} />);
} else if (state.userStudy.currentStep === UserStudyStep.EXPERIMENT_2) {
return (<UserStudyExperiment2 state={state} dispatch={dispatch} />);
} else {
return (<UserStudyExperiment3 state={state} dispatch={dispatch} />);
}
}
| mit |
matsko/angular | packages/platform-server/testing/src/server.ts | 1103 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {createPlatformFactory, NgModule, PlatformRef, StaticProvider} from '@angular/core';
import {BrowserDynamicTestingModule, ɵplatformCoreDynamicTesting as platformCoreDynamicTesting} from '@angular/platform-browser-dynamic/testing';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {ɵINTERNAL_SERVER_PLATFORM_PROVIDERS as INTERNAL_SERVER_PLATFORM_PROVIDERS, ɵSERVER_RENDER_PROVIDERS as SERVER_RENDER_PROVIDERS} from '@angular/platform-server';
/**
* Platform for testing
*
* @publicApi
*/
export const platformServerTesting = createPlatformFactory(
platformCoreDynamicTesting, 'serverTesting', INTERNAL_SERVER_PLATFORM_PROVIDERS);
/**
* NgModule for testing.
*
* @publicApi
*/
@NgModule({
exports: [BrowserDynamicTestingModule],
imports: [NoopAnimationsModule],
providers: SERVER_RENDER_PROVIDERS
})
export class ServerTestingModule {
}
| mit |
TheIndifferent/jenkins-scm-koji-plugin | fake-koji/src/main/java/org/fakekoji/jobmanager/JenkinsJobUpdater.java | 6171 | package org.fakekoji.jobmanager;
import org.fakekoji.Utils;
import org.fakekoji.jobmanager.model.Job;
import org.fakekoji.jobmanager.model.JobUpdateResult;
import org.fakekoji.jobmanager.model.JobUpdateResults;
import org.fakekoji.xmlrpc.server.JavaServerConstants;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Logger;
public class JenkinsJobUpdater implements JobUpdater {
private static final Logger LOGGER = Logger.getLogger(JavaServerConstants.FAKE_KOJI_LOGGER);
static final String JENKINS_JOB_CONFIG_FILE = "config.xml";
private final File jobsRoot;
private final File jobArchiveRoot;
public JenkinsJobUpdater(File jobsRoot, File jobArchiveRoot) {
this.jobsRoot = jobsRoot;
this.jobArchiveRoot = jobArchiveRoot;
}
@Override
public JobUpdateResults update(Set<Job> oldJobs, Set<Job> newJobs) {
final Function<Job, JobUpdateResult> rewriteFunction = jobUpdateFunctionWrapper(getRewriteFunction());
final Function<Job, JobUpdateResult> createFunction = jobUpdateFunctionWrapper(getCreateFunction());
final Function<Job, JobUpdateResult> archiveFunction = jobUpdateFunctionWrapper(getArchiveFunction());
final Function<Job, JobUpdateResult> reviveFunction = jobUpdateFunctionWrapper(getReviveFunction());
final List<JobUpdateResult> jobsCreated = new LinkedList<>();
final List<JobUpdateResult> jobsArchived = new LinkedList<>();
final List<JobUpdateResult> jobsRewritten = new LinkedList<>();
final List<JobUpdateResult> jobsRevived= new LinkedList<>();
final Set<String> archivedJobs = new HashSet<>(Arrays.asList(Objects.requireNonNull(jobArchiveRoot.list())));
for (final Job job : oldJobs) {
if (newJobs.stream().noneMatch(newJob -> job.toString().equals(newJob.toString()))) {
jobsArchived.add(archiveFunction.apply(job));
}
}
for (final Job job : newJobs) {
if (archivedJobs.contains(job.toString())) {
jobsRevived.add(reviveFunction.apply(job));
continue;
}
final Optional<Job> optional = oldJobs.stream()
.filter(oldJob -> job.toString().equals(oldJob.toString()))
.findAny();
if (optional.isPresent()) {
final Job oldJob = optional.get();
if (!oldJob.equals(job)) {
jobsRewritten.add(rewriteFunction.apply(job));
}
continue;
}
jobsCreated.add(createFunction.apply(job));
}
return new JobUpdateResults(
jobsCreated,
jobsArchived,
jobsRewritten,
jobsRevived
);
}
private Function<Job, JobUpdateResult> jobUpdateFunctionWrapper(JobUpdateFunction updateFunction) {
return job -> {
try {
return updateFunction.apply(job);
} catch (IOException e) {
LOGGER.warning(e.getMessage());
return new JobUpdateResult(job.toString(), false, e.getMessage());
}
};
}
private JobUpdateFunction getCreateFunction() {
return job -> {
final String jobName = job.toString();
LOGGER.info("Creating job " + jobName);
final String jobsRootPath = jobsRoot.getAbsolutePath();
LOGGER.info("Creating directory " + jobName + " in " + jobsRootPath);
final File jobDir = Paths.get(jobsRootPath, jobName).toFile();
if (!jobDir.mkdir()) {
throw new IOException("Could't create file: " + jobDir.getAbsolutePath());
}
final String jobDirPath = jobDir.getAbsolutePath();
LOGGER.info("Creating file " + JENKINS_JOB_CONFIG_FILE + " in " + jobDirPath);
Utils.writeToFile(
Paths.get(jobDirPath, JENKINS_JOB_CONFIG_FILE),
job.generateTemplate()
);
return new JobUpdateResult(jobName, true);
};
}
private JobUpdateFunction getReviveFunction() {
return job -> {
final String jobName = job.toString();
final File src = Paths.get(jobArchiveRoot.getAbsolutePath(), job.toString()).toFile();
final File dst = Paths.get(jobsRoot.getAbsolutePath(), job.toString()).toFile();
LOGGER.info("Reviving job " + jobName);
LOGGER.info("Moving directory " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
Utils.moveFile(src, dst);
return new JobUpdateResult(jobName, true);
};
}
private JobUpdateFunction getArchiveFunction() {
return job -> {
final String jobName = job.toString();
final File src = Paths.get(jobsRoot.getAbsolutePath(), job.toString()).toFile();
final File dst = Paths.get(jobArchiveRoot.getAbsolutePath(), job.toString()).toFile();
LOGGER.info("Archiving job " + jobName);
LOGGER.info("Moving directory " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
Utils.moveFile(src, dst);
return new JobUpdateResult(jobName, true);
};
}
private JobUpdateFunction getRewriteFunction() {
return job -> {
final String jobName = job.toString();
final File jobConfig = Paths.get(jobsRoot.getAbsolutePath(), jobName, JENKINS_JOB_CONFIG_FILE).toFile();
LOGGER.info("Rewriting job " + jobName);
LOGGER.info("Writing to file " + jobConfig.getAbsolutePath());
Utils.writeToFile(jobConfig, job.generateTemplate());
return new JobUpdateResult(jobName, true);
};
}
interface JobUpdateFunction {
JobUpdateResult apply(Job job) throws IOException;
}
}
| mit |
lostinplace/filtered-intervaltree | test/test_interval.py | 3792 | from intervaltree.interval import *
def test_basic():
t = Interval(1, 2)
assert t.begin is 1
assert t.end is 2
def test_removal_no_overlap():
interval_one = Interval(10, 15)
interval_two = Interval(8, 10)
result = interval_one.remove(interval_two)
assert result == [interval_one]
def test_removal_whole_contains():
interval_one = Interval(10, 20)
interval_two = Interval(12, 17)
expectation = [
Interval(10, 12),
Interval(17, 20)
]
result = interval_one.remove(interval_two)
assert result == expectation
def test_removal_reduction():
interval_one = Interval(10, 20)
interval_two = Interval(10, 12)
expectation = [
Interval(12, 20)
]
result = interval_one.remove(interval_two)
assert result == expectation
interval_one = Interval(10, 20)
interval_two = Interval(18, 20)
expectation = [
Interval(10, 18)
]
result = interval_one.remove(interval_two)
assert result == expectation
def test_removal_overlap():
interval_one = Interval(10, 20)
interval_two = Interval(8, 12)
expectation = [
Interval(12, 20)
]
result = interval_one.remove(interval_two)
assert result == expectation
interval_one = Interval(10, 20)
interval_two = Interval(18, 24)
expectation = [
Interval(10, 18)
]
result = interval_one.remove(interval_two)
assert result == expectation
def test_removal_edge_cases():
interval_one = Interval(10, 20)
interval_two = Interval(10, 10)
expectation = [
Interval(10, 20)
]
result = interval_one.remove(interval_two)
assert result == expectation
interval_one = Interval(10, 20)
interval_two = Interval(20, 20)
expectation = [
Interval(10, 20)
]
result = interval_one.remove(interval_two)
assert result == expectation
interval_one = Interval(10, 10)
interval_two = Interval(10, 20)
expectation = [
]
result = interval_one.remove(interval_two)
assert result == expectation
interval_one = Interval(10, 15)
interval_two = Interval(8, 20)
expectation = [
]
result = interval_one.remove(interval_two)
assert result == expectation
import timeit
import random
def test_compare_addition():
num_ops = 10000
op_range = range(0, num_ops)
random.seed('test')
data = map(lambda _: (random.randint(0, 1000), random.randint(0, 30)), range(0, 1000))
intervals = map(lambda v: Interval(v[0], v[0] + v[1]), data)
interval_list = list(intervals)
pairs_map = map(lambda _:(random.choice(interval_list), random.choice(interval_list)), op_range)
pairs = list(pairs_map)
trips_map = map(lambda _:(random.choice(interval_list), random.choice(interval_list), random.choice(interval_list)),
op_range)
trips = list(trips_map)
op_1 = lambda: [combine_intervals(pair[0], pair[1]) for pair in pairs]
op_2 = lambda: [get_minimum_bounding_interval(pair[0], pair[1]) for pair in pairs]
op_3 = lambda: [pair[0] + pair[1] for pair in pairs]
op_3x_1 = lambda: [combine_intervals(combine_intervals(trip[0], trip[1]), trip[2]) for trip in trips]
op_3x_2 = lambda: [combine_three_intervals(trip[0], trip[1], trip[2]) for trip in trips]
repetitions = 20
op_1_result = timeit.timeit(op_1, number=repetitions)
op_2_result = timeit.timeit(op_2, number=repetitions)
op_3_result = timeit.timeit(op_3, number=repetitions)
op_3x_1_result = timeit.timeit(op_3x_1, number=repetitions)
op_3x_2_result = timeit.timeit(op_3x_2, number=repetitions)
assert op_3x_2_result < op_3x_1_result
assert op_1_result < op_2_result
assert op_3_result > op_1_result
# assert op_3_result < op_2_result
| mit |
nakamura-yuta-i7/ietopia-appli | src/pages/parts/CheckboxesSection.js | 1748 | import Html from "./Html";
import "./checkboxes_section.scss";
var moji = require('moji');
export default class CheckboxesSection extends Html {
constructor(params={}) {
super();
var title = params.title || "";
var identifier = params.identifier || "";
this.identifier = identifier;
this.apiResult = params.apiResult || "";
this.selectedVals = params.selectedVals || []
this.selectedVals = is("Array", this.selectedVals) ? this.selectedVals : [this.selectedVals];
var $section = $(`
<section class="checkboxes-section ${identifier}-section">
<h2>${title}</h2>
</section>
`);
var $checkboxesArea = $(`
<div class="${identifier}-checkboxes-area">
</div>
`);
var $checkboxes = $(`
<div class="${identifier}-checkboxes checkboxes">
<div class="remove-all-checks">
<a>すべてのチェックを外す</a>
</div>
</div>
`);
this.apiResult.forEach((data)=>{
var $checkbox = this.buildCheckbox(data);
$checkboxes.append($checkbox);
});
$checkboxesArea.append($checkboxes);
$section.append($checkboxesArea);
var $removeAllChecks = $checkboxes.find(".remove-all-checks");
$removeAllChecks.tappable( ()=>{
$section.find(":checked").trigger("click");
});
this.$html = $section;
}
buildCheckbox(data) {
var $checkbox = $(`
<label class="checkbox">
<input type="checkbox" name="${this.identifier}" value="${data.value}">
<span>${moji(data.name).convert('ZK', 'HK').toString()}</span>
</label>
`);
if ( $.inArray(data.value, this.selectedVals) !== -1 ) {
$checkbox.find("input").trigger("click");
}
return $checkbox;
}
}
| mit |
mustafasezgin/bubbles | spec/bubbles/pcp/mmv/table_of_contents_spec.rb | 174 | require 'spec_helper'
describe Bubbles::TableOfContents do
it "should have a total length of 16 bytes" do
Bubbles::TableOfContents.new.num_bytes.should be 16
end
end | mit |
bartsch-dev/jabref | src/main/java/org/jabref/gui/push/PushToLyx.java | 3551 | package org.jabref.gui.push;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.jabref.Globals;
import org.jabref.JabRefExecutorService;
import org.jabref.gui.BasePanel;
import org.jabref.gui.IconTheme;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.metadata.MetaData;
import org.jabref.preferences.JabRefPreferences;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PushToLyx extends AbstractPushToApplication implements PushToApplication {
private static final Log LOGGER = LogFactory.getLog(PushToLyx.class);
@Override
public String getApplicationName() {
return "LyX/Kile";
}
@Override
public Icon getIcon() {
return IconTheme.getImage("lyx");
}
@Override
protected void initParameters() {
commandPathPreferenceKey = JabRefPreferences.LYXPIPE;
}
@Override
public void operationCompleted(BasePanel panel) {
if(couldNotConnect) {
panel.output(Localization.lang("Error") + ": " +
Localization.lang("verify that LyX is running and that the lyxpipe is valid")
+ ". [" + commandPath + "]");
} else if(couldNotCall) {
panel.output(Localization.lang("Error") + ": " +
Localization.lang("unable to write to") + " " + commandPath +
".in");
} else {
super.operationCompleted(panel);
}
}
@Override
protected void initSettingsPanel() {
super.initSettingsPanel();
settings = new JPanel();
settings.add(new JLabel(Localization.lang("Path to LyX pipe") + ":"));
settings.add(path);
}
@Override
public void pushEntries(BibDatabase database, final List<BibEntry> entries, final String keyString,
MetaData metaData) {
couldNotConnect = false;
couldNotCall = false;
notDefined = false;
initParameters();
commandPath = Globals.prefs.get(commandPathPreferenceKey);
if ((commandPath == null) || commandPath.trim().isEmpty()) {
notDefined = true;
return;
}
if (!commandPath.endsWith(".in")) {
commandPath = commandPath + ".in";
}
File lp = new File(commandPath); // this needs to fixed because it gives "asdf" when going prefs.get("lyxpipe")
if (!lp.exists() || !lp.canWrite()) {
// See if it helps to append ".in":
lp = new File(commandPath + ".in");
if (!lp.exists() || !lp.canWrite()) {
couldNotConnect = true;
return;
}
}
final File lyxpipe = lp;
JabRefExecutorService.INSTANCE.executeAndWait(() -> {
try (FileWriter fw = new FileWriter(lyxpipe); BufferedWriter lyxOut = new BufferedWriter(fw)) {
String citeStr;
citeStr = "LYXCMD:sampleclient:citation-insert:" + keyString;
lyxOut.write(citeStr + "\n");
lyxOut.close();
fw.close();
} catch (IOException excep) {
couldNotCall = true;
LOGGER.warn("Problem pushing to LyX/Kile.", excep);
}
});
}
}
| mit |
jwbay/i18next-json-sync | tests/primary-language-zh/options.ts | 135 | import { IOptions } from '../../src';
const options: IOptions = {
primary: 'zh',
createResources: ['pt-BR']
};
export = options; | mit |
softsky/site-security-site | app/public/js/main.js | 2841 | $(document).ready(() => {
console.log('ready');
// making all client links opening in a new window
$('#clients a').attr('target', '_new');
$("input[name=url]:eq(0)").focus();
// TODO add some initialization stuff here
$('img[src*=class]').each((idx, it) => {
const clazz = $(it).attr('src').match(/class=([^$\&]*)/)[1];
$(it).addClass(clazz);
console.log(clazz);
});
$('input[name=url]').on('blur',(e)=>{
$('#ajax-form-0').validator('validate'); // TODO fix validation
const url = $('input[name=url]').val();
if(url && url != ''){
$(".slider-text").fadeOut('slow');
$("#details").removeClass('hidden');
$.ajax({
type: 'POST',
url: '/api/whois',
contentType:'application/x-www-form-urlencoded; charset=UTF-8',
data: `domain=${url}`
}).done((data) => {
let whois = $(data, 'pre').text().substring('version: ').match(/(.*)\:\s(.*)/gi);
$('#details .code').text(whois);
}).fail((xhr, status, errorThrown) => {
console.log(xhr, status, errorThrown);
});
$.ajax({
type: 'POST',
url: '/api/whatweb',
contentType:'application/x-www-form-urlencoded; charset=UTF-8',
data: `target=${url}`
}).done((data) => {
let r = data.match(/(.*)\s(\[\d*\])\s(.*)/);
let fa = r[3].split(/\,\s?/);
console.log(fa);
$("#details ul").html('');
$.each(fa, (idx, it) => {
var x = it.match(/(.*)\[(.*)\]/) || [it, it, it];
var e = $(`<li class="list-group-item"><span class='badge'>${x[2]}</span>${x[1]}</li>`);
$("#details ul").append(e);
});
}).fail((xhr, status, errorThrown) => {
console.log(xhr, status, errorThrown);
});
}
// $.ajax({
// type: 'POST',
// url:'http://whatweb.net/whatweb.php',
// contentType:'application/x-www-form-urlencoded; charset=UTF-8',
// data: `target=${url}`,
// failure: (err) => {
// console.error(err);
// },
// success: (data) => {
// console.log(data);
// }
// });
});
// $('#pricing a.btn').on('click',(e)=>{
// var data = $(e.target).data();
// data.action && $('#contact #ajax-form').attr('action', data.action);
// data.subject && $('#contact input[name=subject]').val(data.subject);
// data.message && $('#contact input[name=message]').val(data.message);
// });
});
| mit |
FMTCco/fmtc-php | src/Feeds/NetworkFeed.php | 1644 | <?php
namespace Fmtc\Feeds;
use Illuminate\Database\Capsule\Manager as DB;
class NetworkFeed extends Feed
{
protected $url = 'http://services.fmtc.co/v2/getNetworks';
protected function storeFull($json)
{
$networks = json_decode($json, true);
// grab networks from the database
$dbNetworks = collect(DB::table('networks')->get(['cSlug']))->keyBy('cSlug')->toArray();
// grab an array of columns in the networks table
$columns = DB::select('select COLUMN_NAME as `column` from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = \'fmtc_networks\'');
// set the counters for reporting
$insertCount = 0;
$removeCount = 0;
// walk through the networks from a merchant feed
$jsonNetworksIds = [];
foreach($networks as $network) {
// is the network missing from the database?
if (! isset($dbNetworks[$network['cSlug']])) {
// insert it (this is faster than building an insert queue and bulk inserting)
DB::table('networks')->insert($this->formatForInsertion($network, $columns));
$insertCount++;
}
// collect an array of ids to aid in the remove queue
$jsonNetworksIds[] = $network['cSlug'];
}
// remove old networks showing up in the database but not in the new merchant feed.
$removeQueue = array_diff(array_keys($dbNetworks), $jsonNetworksIds);
$removeCount = count($removeQueue);
foreach ($removeQueue as $networkId) {
DB::table('networks')->where('cSlug', $networkId)->delete();
}
//---- debugging
// debug($removeCount . ' removed');
// debug($insertCount . ' inserted');
//-----
return true;
}
public function processIncremental()
{
return false;
}
} | mit |
alvarolobato/blueocean-plugin | blueocean-dashboard/src/main/js/credentials/bitbucket/BbCredentialsManager.js | 2385 | import { action, observable } from 'mobx';
import PromiseDelayUtils from '../../util/PromiseDelayUtils';
import BbCredentialsApi from './BbCredentialsApi';
import BbCredentialState from './BbCredentialsState';
import { LoadError, SaveError } from './BbCredentialsApi';
const MIN_DELAY = 500;
const { delayBoth } = PromiseDelayUtils;
/**
* Manages retrieving, validating and saving Bitbucket credential
* Also holds the state of the credential for use in BbCredentialStep.
*/
class BbCredentialsManager {
@observable
stateId = null;
@observable
pendingValidation = false;
configure(scmId, apiUrl) {
this._credentialsApi = new BbCredentialsApi(scmId);
this.apiUrl = apiUrl;
}
constructor(credentialsApi) {
this._credentialsApi = credentialsApi;
}
@action
findExistingCredential() {
this.stateId = BbCredentialState.PENDING_LOADING_CREDS;
return this._credentialsApi.findExistingCredential(this.apiUrl)
.then(...delayBoth(MIN_DELAY))
.catch(error => this._findExistingCredentialFailure(error));
}
@action
_findExistingCredentialFailure(error) {
if (error.type === LoadError.TOKEN_NOT_FOUND) {
this.stateId = BbCredentialState.NEW_REQUIRED;
} else if (error.type === LoadError.TOKEN_INVALID) {
this.stateId = BbCredentialState.INVALID_CREDENTIAL;
} else {
this.stateId = BbCredentialState.UNEXPECTED_ERROR_CREDENTIAL;
}
}
@action
createCredential(userName, password) {
this.pendingValidation = true;
return this._credentialsApi.createBbCredential(this.apiUrl, userName, password)
.then(...delayBoth(MIN_DELAY))
.then(response => this._createCredentialSuccess(response))
.catch(error => this._onCreateTokenFailure(error));
}
@action
_createCredentialSuccess(credential) {
this.pendingValidation = false;
this.stateId = BbCredentialState.SAVE_SUCCESS;
return credential;
}
@action
_onCreateTokenFailure(error) {
this.pendingValidation = false;
if (error.type === SaveError.INVALID_CREDENTIAL) {
this.stateId = BbCredentialState.INVALID_CREDENTIAL;
} else {
throw error;
}
}
}
export default BbCredentialsManager;
| mit |
philiplaureano/Akka.Configuration.Lambdas | Akka.Configuration.LambdaTests/Properties/AssemblyInfo.cs | 1436 | 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("Akka.Configuration.LambdaTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Akka.Configuration.LambdaTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("92f9b584-daa0-4dfe-b220-3adf2fb59279")]
// 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")]
| mit |
CloudI/CloudI | src/api/go/erlang/erlang_test.go | 23969 | package erlang
//-*-Mode:Go;coding:utf-8;tab-width:4;c-basic-offset:4-*-
// ex: set ft=go fenc=utf-8 sts=4 ts=4 sw=4 noet nomod:
//
// MIT License
//
// Copyright (c) 2017-2019 Michael Truog <mjtruog at protonmail dot com>
// Copyright (c) 2009-2013 Dmitry Vasiliev <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import (
"fmt"
"log"
"math/big"
"reflect"
"strings"
"testing"
)
func assertEqual(t *testing.T, expect interface{}, result interface{}, message string) {
// Go doesn't believe in assertions (https://golang.org/doc/faq#assertions)
// (Go isn't pursuing fail-fast development or fault-tolerance)
if reflect.DeepEqual(expect, result) {
return
}
if len(message) == 0 {
message = fmt.Sprintf("%#v != %#v", expect, result)
}
t.Fail()
log.SetPrefix("\t")
log.SetFlags(log.Lshortfile)
log.Output(2, message)
}
func assertDecodeError(t *testing.T, expectedError, b string, message string) {
_, err := BinaryToTerm([]byte(b))
if err == nil {
log.SetPrefix("\t")
log.SetFlags(log.Lshortfile)
log.Output(2, fmt.Sprintf("no error to compare with \"%s\"", expectedError))
t.FailNow()
return
}
resultError := err.Error()
if expectedError == resultError {
return
}
if len(message) == 0 {
message = fmt.Sprintf("\"%s\" != \"%s\"", expectedError, resultError)
}
t.Fail()
log.SetPrefix("\t")
log.SetFlags(log.Lshortfile)
log.Output(2, message)
}
func decode(t *testing.T, b string) interface{} {
term, err := BinaryToTerm([]byte(b))
if err != nil {
log.SetPrefix("\t")
log.SetFlags(log.Lshortfile)
log.Output(2, err.Error())
t.FailNow()
return nil
}
return term
}
func encode(t *testing.T, term interface{}, compressed int) string {
b, err := TermToBinary(term, compressed)
if err != nil {
log.SetPrefix("\t")
log.SetFlags(log.Lshortfile)
log.Output(2, err.Error())
t.FailNow()
return ""
}
return string(b)
}
func TestAtom(t *testing.T) {
atom1 := OtpErlangAtom("test")
assertEqual(t, OtpErlangAtom("test"), atom1, "")
assertEqual(t, strings.Repeat("X", 255), string(OtpErlangAtom(strings.Repeat("X", 255))), "")
assertEqual(t, strings.Repeat("X", 256), string(OtpErlangAtom(strings.Repeat("X", 256))), "")
}
func TestPid(t *testing.T) {
pid1 := OtpErlangPid{NodeTag: 100, Node: []uint8{0x0, 0xd, 0x6e, 0x6f, 0x6e, 0x6f, 0x64, 0x65, 0x40, 0x6e, 0x6f, 0x68, 0x6f, 0x73, 0x74}, ID: []uint8{0x0, 0x0, 0x0, 0x3b}, Serial: []uint8{0x0, 0x0, 0x0, 0x0}, Creation: []uint8{0x0}}
binary := "\x83\x67\x64\x00\x0D\x6E\x6F\x6E\x6F\x64\x65\x40\x6E\x6F\x68\x6F\x73\x74\x00\x00\x00\x3B\x00\x00\x00\x00\x00"
assertEqual(t, pid1, decode(t, binary), "")
assertEqual(t, binary, encode(t, pid1, -1), "")
pidOldBinary := "\x83\x67\x64\x00\x0D\x6E\x6F\x6E\x6F\x64\x65\x40\x6E\x6F\x68\x6F\x73\x74\x00\x00\x00\x4E\x00\x00\x00\x00\x00"
pidOld := decode(t, pidOldBinary)
assertEqual(t, "\x83gd\x00\rnonode@nohost\x00\x00\x00N\x00\x00\x00\x00\x00", encode(t, pidOld, -1), "")
pidNewBinary := "\x83\x58\x64\x00\x0D\x6E\x6F\x6E\x6F\x64\x65\x40\x6E\x6F\x68\x6F\x73\x74\x00\x00\x00\x4E\x00\x00\x00\x00\x00\x00\x00\x00"
pidNew := decode(t, pidNewBinary)
assertEqual(t, "\x83Xd\x00\rnonode@nohost\x00\x00\x00N\x00\x00\x00\x00\x00\x00\x00\x00", encode(t, pidNew, -1), "")
}
func TestPort(t *testing.T) {
portOldBinary := "\x83\x66\x64\x00\x0D\x6E\x6F\x6E\x6F\x64\x65\x40\x6E\x6F\x68\x6F\x73\x74\x00\x00\x00\x06\x00"
portOld := decode(t, portOldBinary)
assertEqual(t, "\x83fd\x00\rnonode@nohost\x00\x00\x00\x06\x00", encode(t, portOld, -1), "")
portNewBinary := "\x83\x59\x64\x00\x0D\x6E\x6F\x6E\x6F\x64\x65\x40\x6E\x6F\x68\x6F\x73\x74\x00\x00\x00\x06\x00\x00\x00\x00"
portNew := decode(t, portNewBinary)
assertEqual(t, "\x83Yd\x00\rnonode@nohost\x00\x00\x00\x06\x00\x00\x00\x00", encode(t, portNew, -1), "")
}
func TestFunction(t *testing.T) {
fun1 := OtpErlangFunction{Tag: 113, Value: []uint8{0x64, 0x0, 0x5, 0x6c, 0x69, 0x73, 0x74, 0x73, 0x64, 0x0, 0x6, 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x61, 0x2}}
binary := "\x83\x71\x64\x00\x05\x6C\x69\x73\x74\x73\x64\x00\x06\x6D\x65\x6D\x62\x65\x72\x61\x02"
assertEqual(t, fun1, decode(t, binary), "")
assertEqual(t, binary, encode(t, fun1, -1), "")
}
func TestReference(t *testing.T) {
ref1 := OtpErlangReference{NodeTag: 100, Node: []uint8{0x0, 0xd, 0x6e, 0x6f, 0x6e, 0x6f, 0x64, 0x65, 0x40, 0x6e, 0x6f, 0x68, 0x6f, 0x73, 0x74}, ID: []uint8{0x0, 0x0, 0x0, 0xaf, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0}, Creation: []uint8{0x0}}
binary := "\x83\x72\x00\x03\x64\x00\x0D\x6E\x6F\x6E\x6F\x64\x65\x40\x6E\x6F\x68\x6F\x73\x74\x00\x00\x00\x00\xAF\x00\x00\x00\x03\x00\x00\x00\x00"
assertEqual(t, ref1, decode(t, binary), "")
assertEqual(t, binary, encode(t, ref1, -1), "")
refNewBinary := "\x83\x72\x00\x03\x64\x00\x0D\x6E\x6F\x6E\x6F\x64\x65\x40\x6E\x6F\x68\x6F\x73\x74\x00\x00\x03\xE8\x4E\xE7\x68\x00\x02\xA4\xC8\x53\x40"
refNew := decode(t, refNewBinary)
assertEqual(t, "\x83r\x00\x03d\x00\rnonode@nohost\x00\x00\x03\xe8N\xe7h\x00\x02\xa4\xc8S@", encode(t, refNew, -1), "")
refNewerBinary := "\x83\x5A\x00\x03\x64\x00\x0D\x6E\x6F\x6E\x6F\x64\x65\x40\x6E\x6F\x68\x6F\x73\x74\x00\x00\x00\x00\x00\x01\xAC\x03\xC7\x00\x00\x04\xBB\xB2\xCA\xEE"
refNewer := decode(t, refNewerBinary)
assertEqual(t, "\x83Z\x00\x03d\x00\rnonode@nohost\x00\x00\x00\x00\x00\x01\xac\x03\xc7\x00\x00\x04\xbb\xb2\xca\xee", encode(t, refNewer, -1), "")
}
func TestDecodeBinaryToTerm(t *testing.T) {
assertDecodeError(t, "null input", "", "")
assertDecodeError(t, "null input", "\x00", "")
assertDecodeError(t, "null input", "\x83", "")
assertDecodeError(t, "invalid tag", "\x83z", "")
}
func TestDecodeBinaryToTermAtom(t *testing.T) {
assertDecodeError(t, "EOF", "\x83d", "")
assertDecodeError(t, "unexpected EOF", "\x83d\x00", "")
assertDecodeError(t, "EOF", "\x83d\x00\x01", "")
assertDecodeError(t, "EOF", "\x83s\x01", "")
assertEqual(t, OtpErlangAtom(""), decode(t, "\x83d\x00\x00"), "")
assertEqual(t, OtpErlangAtom(""), decode(t, "\x83s\x00"), "")
assertEqual(t, OtpErlangAtom("test"), decode(t, "\x83d\x00\x04test"), "")
assertEqual(t, OtpErlangAtom("test"), decode(t, "\x83s\x04test"), "")
}
func TestDecodeBinaryToTermPredefinedAtom(t *testing.T) {
assertEqual(t, OtpErlangAtom("true"), decode(t, "\x83s\x04true"), "")
assertEqual(t, OtpErlangAtom("false"), decode(t, "\x83s\x05false"), "")
assertEqual(t, OtpErlangAtom("undefined"), decode(t, "\x83d\x00\x09undefined"), "")
}
func TestDecodeBinaryToTermEmptyList(t *testing.T) {
assertEqual(t, OtpErlangList{Value: make([]interface{}, 0), Improper: false}, decode(t, "\x83j"), "")
}
func TestDecodeBinaryToTermStringList(t *testing.T) {
assertDecodeError(t, "EOF", "\x83k", "")
assertDecodeError(t, "unexpected EOF", "\x83k\x00", "")
assertDecodeError(t, "EOF", "\x83k\x00\x01", "")
assertEqual(t, "", decode(t, "\x83k\x00\x00"), "")
assertEqual(t, "test", decode(t, "\x83k\x00\x04test"), "")
}
func TestDecodeBinaryToTermList(t *testing.T) {
assertDecodeError(t, "EOF", "\x83l", "")
assertDecodeError(t, "unexpected EOF", "\x83l\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83l\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83l\x00\x00\x00", "")
assertDecodeError(t, "EOF", "\x83l\x00\x00\x00\x00", "")
assertEqual(t, OtpErlangList{Value: make([]interface{}, 0), Improper: false}, decode(t, "\x83l\x00\x00\x00\x00j"), "")
list1 := make([]interface{}, 2)
list1[0] = OtpErlangList{Value: make([]interface{}, 0), Improper: false}
list1[1] = OtpErlangList{Value: make([]interface{}, 0), Improper: false}
assertEqual(t, OtpErlangList{Value: list1, Improper: false}, decode(t, "\x83l\x00\x00\x00\x02jjj"), "")
}
func TestDecodeBinaryToTermImproperList(t *testing.T) {
assertDecodeError(t, "EOF", "\x83l\x00\x00\x00k", "")
lst := decode(t, "\x83l\x00\x00\x00\x01jd\x00\x04tail")
lstCmp := make([]interface{}, 2)
lstCmp[0] = OtpErlangList{Value: make([]interface{}, 0), Improper: false}
lstCmp[1] = OtpErlangAtom("tail")
assertEqual(t, OtpErlangList{Value: lstCmp, Improper: true}, lst, "")
}
func TestDecodeBinaryToTermSmallTuple(t *testing.T) {
assertDecodeError(t, "EOF", "\x83h", "")
assertDecodeError(t, "EOF", "\x83h\x01", "")
assertEqual(t, OtpErlangTuple(make([]interface{}, 0)), decode(t, "\x83h\x00"), "")
tuple1 := make([]interface{}, 2)
tuple1[0] = OtpErlangList{Value: make([]interface{}, 0), Improper: false}
tuple1[1] = OtpErlangList{Value: make([]interface{}, 0), Improper: false}
assertEqual(t, OtpErlangTuple(tuple1), decode(t, "\x83h\x02jj"), "")
}
func TestDecodeBinaryToTermLargeTuple(t *testing.T) {
assertDecodeError(t, "EOF", "\x83i", "")
assertDecodeError(t, "unexpected EOF", "\x83i\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83i\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83i\x00\x00\x00", "")
assertDecodeError(t, "EOF", "\x83i\x00\x00\x00\x01", "")
assertEqual(t, OtpErlangTuple(make([]interface{}, 0)), decode(t, "\x83i\x00\x00\x00\x00"), "")
tuple1 := make([]interface{}, 2)
tuple1[0] = OtpErlangList{Value: make([]interface{}, 0), Improper: false}
tuple1[1] = OtpErlangList{Value: make([]interface{}, 0), Improper: false}
assertEqual(t, OtpErlangTuple(tuple1), decode(t, "\x83i\x00\x00\x00\x02jj"), "")
}
func TestDecodeBinaryToTermSmallInteger(t *testing.T) {
assertDecodeError(t, "EOF", "\x83a", "")
assertEqual(t, uint8(0), decode(t, "\x83a\x00"), "")
assertEqual(t, uint8(255), decode(t, "\x83a\xff"), "")
}
func TestDecodeBinaryToTermInteger(t *testing.T) {
assertDecodeError(t, "EOF", "\x83b", "")
assertDecodeError(t, "unexpected EOF", "\x83b\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83b\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83b\x00\x00\x00", "")
assertEqual(t, int32(0), decode(t, "\x83b\x00\x00\x00\x00"), "")
assertEqual(t, int32(2147483647), decode(t, "\x83b\x7f\xff\xff\xff"), "")
assertEqual(t, int32(-2147483648), decode(t, "\x83b\x80\x00\x00\x00"), "")
assertEqual(t, int32(-1), decode(t, "\x83b\xff\xff\xff\xff"), "")
}
func TestDecodeBinaryToTermBinary(t *testing.T) {
assertDecodeError(t, "EOF", "\x83m", "")
assertDecodeError(t, "unexpected EOF", "\x83m\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83m\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83m\x00\x00\x00", "")
assertEqual(t, OtpErlangBinary{Value: []byte(""), Bits: 8}, decode(t, "\x83m\x00\x00\x00\x00"), "")
assertEqual(t, OtpErlangBinary{Value: []byte("data"), Bits: 8}, decode(t, "\x83m\x00\x00\x00\x04data"), "")
}
func TestDecodeBinaryToTermFloat(t *testing.T) {
assertDecodeError(t, "EOF", "\x83F", "")
assertDecodeError(t, "unexpected EOF", "\x83F\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83F\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83F\x00\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83F\x00\x00\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83F\x00\x00\x00\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83F\x00\x00\x00\x00\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83F\x00\x00\x00\x00\x00\x00\x00", "")
assertEqual(t, 0.0, decode(t, "\x83F\x00\x00\x00\x00\x00\x00\x00\x00"), "")
assertEqual(t, 1.5, decode(t, "\x83F?\xf8\x00\x00\x00\x00\x00\x00"), "")
}
func TestDecodeBinaryToTermSmallBigInteger(t *testing.T) {
assertDecodeError(t, "EOF", "\x83n", "")
assertDecodeError(t, "EOF", "\x83n\x00", "")
assertDecodeError(t, "EOF", "\x83n\x01\x00", "")
assertEqual(t, big.NewInt(0), decode(t, "\x83n\x00\x00"), "")
bignum1, _ := big.NewInt(0).SetString("6618611909121", 10)
assertEqual(t, bignum1, decode(t, "\x83n\x06\x00\x01\x02\x03\x04\x05\x06"), "")
bignum2, _ := big.NewInt(0).SetString("-6618611909121", 10)
assertEqual(t, bignum2, decode(t, "\x83n\x06\x01\x01\x02\x03\x04\x05\x06"), "")
}
func TestDecodeBinaryToTermLargeBigInteger(t *testing.T) {
assertDecodeError(t, "EOF", "\x83o", "")
assertDecodeError(t, "unexpected EOF", "\x83o\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83o\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83o\x00\x00\x00", "")
assertDecodeError(t, "EOF", "\x83o\x00\x00\x00\x00", "")
assertDecodeError(t, "EOF", "\x83o\x00\x00\x00\x01\x00", "")
assertEqual(t, big.NewInt(0), decode(t, "\x83o\x00\x00\x00\x00\x00"), "")
bignum1, _ := big.NewInt(0).SetString("6618611909121", 10)
assertEqual(t, bignum1, decode(t, "\x83o\x00\x00\x00\x06\x00\x01\x02\x03\x04\x05\x06"), "")
bignum2, _ := big.NewInt(0).SetString("-6618611909121", 10)
assertEqual(t, bignum2, decode(t, "\x83o\x00\x00\x00\x06\x01\x01\x02\x03\x04\x05\x06"), "")
}
func TestDecodeBinaryToTermCompressedTerm(t *testing.T) {
assertDecodeError(t, "EOF", "\x83P", "")
assertDecodeError(t, "unexpected EOF", "\x83P\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83P\x00\x00", "")
assertDecodeError(t, "unexpected EOF", "\x83P\x00\x00\x00", "")
assertDecodeError(t, "compressed data null", "\x83P\x00\x00\x00\x00", "")
assertEqual(t, strings.Repeat("d", 20), decode(t, "\x83P\x00\x00\x00\x17\x78\xda\xcb\x66\x10\x49\xc1\x02\x00\x5d\x60\x08\x50"), "")
}
func TestEncodeTermToBinaryTuple(t *testing.T) {
assertEqual(t, "\x83h\x00", encode(t, []interface{}{}, -1), "")
assertEqual(t, "\x83h\x00", encode(t, OtpErlangTuple{}, -1), "")
assertEqual(t, "\x83h\x02h\x00h\x00", encode(t, []interface{}{[]interface{}{}, []interface{}{}}, -1), "")
tuple1 := make(OtpErlangTuple, 255)
for i := 0; i < 255; i++ {
tuple1[i] = OtpErlangTuple{}
}
assertEqual(t, "\x83h\xff"+strings.Repeat("h\x00", 255), encode(t, tuple1, -1), "")
tuple2 := make(OtpErlangTuple, 256)
for i := 0; i < 256; i++ {
tuple2[i] = OtpErlangTuple{}
}
assertEqual(t, "\x83i\x00\x00\x01\x00"+strings.Repeat("h\x00", 256), encode(t, tuple2, -1), "")
}
func TestEncodeTermToBinaryEmptyList(t *testing.T) {
assertEqual(t, "\x83j", encode(t, OtpErlangList{}, -1), "")
assertEqual(t, "\x83j", encode(t, OtpErlangList{Value: []interface{}{}}, -1), "")
assertEqual(t, "\x83j", encode(t, OtpErlangList{Value: []interface{}{}, Improper: false}, -1), "")
}
func TestEncodeTermToBinaryStringList(t *testing.T) {
assertEqual(t, "\x83j", encode(t, "", -1), "")
assertEqual(t, "\x83k\x00\x01\x00", encode(t, "\x00", -1), "")
s := "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
assertEqual(t, "\x83k\x01\x00"+s, encode(t, s, -1), "")
}
func TestEncodeTermToBinaryListBasic(t *testing.T) {
assertEqual(t, "\x83\x6A", encode(t, OtpErlangList{}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x6A\x6A", encode(t, OtpErlangList{Value: []interface{}{""}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x61\x01\x6A", encode(t, OtpErlangList{Value: []interface{}{1}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x61\xFF\x6A", encode(t, OtpErlangList{Value: []interface{}{255}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x62\x00\x00\x01\x00\x6A", encode(t, OtpErlangList{Value: []interface{}{256}}, -1), "")
i1 := 2147483647
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x62\x7F\xFF\xFF\xFF\x6A", encode(t, OtpErlangList{Value: []interface{}{i1}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x6E\x04\x00\x00\x00\x00\x80\x6A", encode(t, OtpErlangList{Value: []interface{}{i1 + 1}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x61\x00\x6A", encode(t, OtpErlangList{Value: []interface{}{0}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x62\xFF\xFF\xFF\xFF\x6A", encode(t, OtpErlangList{Value: []interface{}{-1}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x62\xFF\xFF\xFF\x00\x6A", encode(t, OtpErlangList{Value: []interface{}{-256}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x62\xFF\xFF\xFE\xFF\x6A", encode(t, OtpErlangList{Value: []interface{}{-257}}, -1), "")
i2 := -2147483648
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x62\x80\x00\x00\x00\x6A", encode(t, OtpErlangList{Value: []interface{}{i2}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x6E\x04\x01\x01\x00\x00\x80\x6A", encode(t, OtpErlangList{Value: []interface{}{i2 - 1}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x6B\x00\x04\x74\x65\x73\x74\x6A", encode(t, OtpErlangList{Value: []interface{}{"test"}}, -1), "")
assertEqual(t, "\x83\x6C\x00\x00\x00\x02\x62\x00\x00\x01\x75\x62\x00\x00\x01\xC7\x6A", encode(t, OtpErlangList{Value: []interface{}{373, 455}}, -1), "")
list1 := OtpErlangList{}
list2 := OtpErlangList{Value: []interface{}{list1}}
assertEqual(t, "\x83\x6C\x00\x00\x00\x01\x6A\x6A", encode(t, list2, -1), "")
list3 := OtpErlangList{Value: []interface{}{list1, list1}}
assertEqual(t, "\x83\x6C\x00\x00\x00\x02\x6A\x6A\x6A", encode(t, list3, -1), "")
list4 := OtpErlangList{Value: []interface{}{OtpErlangList{Value: []interface{}{"this", "is"}}, OtpErlangList{Value: []interface{}{OtpErlangList{Value: []interface{}{"a"}}}}, "test"}}
assertEqual(t, "\x83\x6C\x00\x00\x00\x03\x6C\x00\x00\x00\x02\x6B\x00\x04\x74\x68\x69\x73\x6B\x00\x02\x69\x73\x6A\x6C\x00\x00\x00\x01\x6C\x00\x00\x00\x01\x6B\x00\x01\x61\x6A\x6A\x6B\x00\x04\x74\x65\x73\x74\x6A", encode(t, list4, -1), "")
}
func TestEncodeTermToBinaryList(t *testing.T) {
list1 := OtpErlangList{}
list2 := OtpErlangList{Value: []interface{}{list1}}
assertEqual(t, "\x83l\x00\x00\x00\x01jj", encode(t, list2, -1), "")
list3 := OtpErlangList{Value: []interface{}{list1, list1, list1, list1, list1}}
assertEqual(t, "\x83l\x00\x00\x00\x05jjjjjj", encode(t, list3, -1), "")
}
func TestEncodeTermToBinaryImproperList(t *testing.T) {
list1 := OtpErlangList{Value: []interface{}{OtpErlangTuple{}, []interface{}{}}, Improper: true}
assertEqual(t, "\x83l\x00\x00\x00\x01h\x00h\x00", encode(t, list1, -1), "")
list2 := OtpErlangList{Value: []interface{}{0, 1}, Improper: true}
assertEqual(t, "\x83l\x00\x00\x00\x01a\x00a\x01", encode(t, list2, -1), "")
}
func TestEncodeTermToBinaryUnicode(t *testing.T) {
assertEqual(t, "\x83j", encode(t, "", -1), "")
assertEqual(t, "\x83k\x00\x04test", encode(t, "test", -1), "")
assertEqual(t, "\x83k\x00\x03\x00\xc3\xbf", encode(t, "\x00\xc3\xbf", -1), "")
assertEqual(t, "\x83k\x00\x02\xc4\x80", encode(t, "\xc4\x80", -1), "")
assertEqual(t, "\x83k\x00\x08\xd1\x82\xd0\xb5\xd1\x81\xd1\x82", encode(t, "\xd1\x82\xd0\xb5\xd1\x81\xd1\x82", -1), "")
// becomes a list of small integers
assertEqual(t, "\x83l\x00\x02\x00\x00"+strings.Repeat("a\xd0a\x90", 65536)+"j", encode(t, strings.Repeat("\xd0\x90", 65536), -1), "")
}
func TestEncodeTermToBinaryAtom(t *testing.T) {
assertEqual(t, "\x83s\x00", encode(t, OtpErlangAtom(""), -1), "")
assertEqual(t, "\x83s\x04test", encode(t, OtpErlangAtom("test"), -1), "")
}
func TestEncodeTermToBinaryStringBasic(t *testing.T) {
assertEqual(t, "\x83\x6A", encode(t, "", -1), "")
assertEqual(t, "\x83\x6B\x00\x04\x74\x65\x73\x74", encode(t, "test", -1), "")
assertEqual(t, "\x83\x6B\x00\x09\x74\x77\x6F\x20\x77\x6F\x72\x64\x73", encode(t, "two words", -1), "")
assertEqual(t, "\x83\x6B\x00\x16\x74\x65\x73\x74\x69\x6E\x67\x20\x6D\x75\x6C\x74\x69\x70\x6C\x65\x20\x77\x6F\x72\x64\x73", encode(t, "testing multiple words", -1), "")
assertEqual(t, "\x83\x6B\x00\x01\x20", encode(t, " ", -1), "")
assertEqual(t, "\x83\x6B\x00\x02\x20\x20", encode(t, " ", -1), "")
assertEqual(t, "\x83\x6B\x00\x01\x31", encode(t, "1", -1), "")
assertEqual(t, "\x83\x6B\x00\x02\x33\x37", encode(t, "37", -1), "")
assertEqual(t, "\x83\x6B\x00\x07\x6F\x6E\x65\x20\x3D\x20\x31", encode(t, "one = 1", -1), "")
assertEqual(t, "\x83\x6B\x00\x20\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x5F\x2B\x2D\x3D\x5B\x5D\x7B\x7D\x5C\x7C\x3B\x27\x3A\x22\x2C\x2E\x2F\x3C\x3E\x3F\x7E\x60", encode(t, "!@#$%^&*()_+-=[]{}\\|;':\",./<>?~`", -1), "")
assertEqual(t, "\x83\x6B\x00\x09\x22\x08\x0C\x0A\x0D\x09\x0B\x53\x12", encode(t, "\"\b\f\n\r\t\v\123\x12", -1), "")
}
func TestEncodeTermToBinaryString(t *testing.T) {
assertEqual(t, "\x83j", encode(t, "", -1), "")
assertEqual(t, "\x83k\x00\x04test", encode(t, "test", -1), "")
}
func TestEncodeTermToBinaryPredefinedAtoms(t *testing.T) {
assertEqual(t, "\x83s\x04true", encode(t, true, -1), "")
assertEqual(t, "\x83s\x05false", encode(t, false, -1), "")
assertEqual(t, "\x83s\x09undefined", encode(t, nil, -1), "")
}
func TestEncodeTermToBinaryShortInteger(t *testing.T) {
assertEqual(t, "\x83a\x00", encode(t, 0, -1), "")
assertEqual(t, "\x83a\xff", encode(t, 255, -1), "")
}
func TestEncodeTermToBinaryInteger(t *testing.T) {
assertEqual(t, "\x83b\xff\xff\xff\xff", encode(t, -1, -1), "")
assertEqual(t, "\x83b\x80\x00\x00\x00", encode(t, -2147483648, -1), "")
assertEqual(t, "\x83b\x00\x00\x01\x00", encode(t, 256, -1), "")
assertEqual(t, "\x83b\x7f\xff\xff\xff", encode(t, 2147483647, -1), "")
}
func TestEncodeTermToBinaryLongInteger(t *testing.T) {
assertEqual(t, "\x83n\x04\x00\x00\x00\x00\x80", encode(t, 2147483648, -1), "")
assertEqual(t, "\x83n\x04\x01\x01\x00\x00\x80", encode(t, -2147483649, -1), "")
i1 := big.NewInt(0)
i1.Exp(big.NewInt(2), big.NewInt(2040), nil)
assertEqual(t, "\x83o\x00\x00\x01\x00\x00"+strings.Repeat("\x00", 255)+"\x01", encode(t, i1, -1), "")
i2 := big.NewInt(0).Neg(i1)
assertEqual(t, "\x83o\x00\x00\x01\x00\x01"+strings.Repeat("\x00", 255)+"\x01", encode(t, i2, -1), "")
}
func TestEncodeTermToBinaryFloat(t *testing.T) {
assertEqual(t, "\x83F\x00\x00\x00\x00\x00\x00\x00\x00", encode(t, 0.0, -1), "")
assertEqual(t, "\x83F?\xe0\x00\x00\x00\x00\x00\x00", encode(t, 0.5, -1), "")
assertEqual(t, "\x83F\xbf\xe0\x00\x00\x00\x00\x00\x00", encode(t, -0.5, -1), "")
assertEqual(t, "\x83F@\t!\xfbM\x12\xd8J", encode(t, 3.1415926, -1), "")
assertEqual(t, "\x83F\xc0\t!\xfbM\x12\xd8J", encode(t, -3.1415926, -1), "")
}
func TestEncodeTermToBinaryCompressedTerm(t *testing.T) {
list1 := OtpErlangList{}
list2 := OtpErlangList{Value: []interface{}{list1, list1, list1, list1, list1, list1, list1, list1, list1, list1, list1, list1, list1, list1, list1}}
assertEqual(t, "\x83P\x00\x00\x00\x15x\x9c\xcaa``\xe0\xcfB\x03\x80\x00\x00\x00\xff\xffB@\a\x1c", encode(t, list2, 6), "")
assertEqual(t, "\x83P\x00\x00\x00\x15x\xda\xcaa``\xe0\xcfB\x03\x80\x00\x00\x00\xff\xffB@\a\x1c", encode(t, list2, 9), "")
assertEqual(t, "\x83P\x00\x00\x00\x15x\x01\x00\x15\x00\xea\xffl\x00\x00\x00\x0fjjjjjjjjjjjjjjjj\x01\x00\x00\xff\xffB@\a\x1c", encode(t, list2, 0), "")
assertEqual(t, "\x83P\x00\x00\x00\x17x\xda\xcaf\x10I\xc1\x02\x00\x01\x00\x00\xff\xff]`\bP", encode(t, strings.Repeat("d", 20), 9), "")
}
| mit |
Nascom/TeamleaderApiClient | src/Request/Ticket/ListMessagesRequest.php | 1552 | <?php
namespace Nascom\TeamleaderApiClient\Request\Ticket;
use Nascom\TeamleaderApiClient\Request\AbstractPostRequest;
/**
* Class ListMessagesRequest
*
* @package Nascom\TeamleaderApiClient\Request\Ticket
*/
class ListMessagesRequest extends AbstractPostRequest
{
/**
* ListMessagesRequest constructor.
*
* @param $ticket_id
* @param $include_internal_message
* @param $include_third_party_message
* @param array $options
*/
public function __construct($ticket_id, $include_internal_message, $include_third_party_message, array $options = [])
{
$this->options = $options;
$this->setTicketId($ticket_id);
$this->setIncludeInternalMessage($include_internal_message);
$this->setIncludeThirdPartyMessage($include_third_party_message);
}
/**
* @param $ticket_id
*/
public function setTicketId($ticket_id)
{
$this->options['ticket_id'] = $ticket_id;
}
/**
* @param $include_internal_message
*/
public function setIncludeInternalMessage($include_internal_message)
{
$this->options['include_internal_message'] = $include_internal_message;
}
/**
* @param $include_third_party_message
*/
public function setIncludeThirdPartyMessage($include_third_party_message)
{
$this->options['include_third_party_message'] = $include_third_party_message;
}
/**
* @return string
*/
public function getUri()
{
return 'getTicketMessages.php';
}
}
| mit |
Azure/azure-sdk-for-go | services/datafactory/mgmt/2018-06-01/datafactory/pipelineruns.go | 13593 | package datafactory
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// PipelineRunsClient is the the Azure Data Factory V2 management API provides a RESTful set of web services that
// interact with Azure Data Factory V2 services.
type PipelineRunsClient struct {
BaseClient
}
// NewPipelineRunsClient creates an instance of the PipelineRunsClient client.
func NewPipelineRunsClient(subscriptionID string) PipelineRunsClient {
return NewPipelineRunsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewPipelineRunsClientWithBaseURI creates an instance of the PipelineRunsClient client using a custom endpoint. Use
// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewPipelineRunsClientWithBaseURI(baseURI string, subscriptionID string) PipelineRunsClient {
return PipelineRunsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Cancel cancel a pipeline run by its run ID.
// Parameters:
// resourceGroupName - the resource group name.
// factoryName - the factory name.
// runID - the pipeline run identifier.
// isRecursive - if true, cancel all the Child pipelines that are triggered by the current pipeline.
func (client PipelineRunsClient) Cancel(ctx context.Context, resourceGroupName string, factoryName string, runID string, isRecursive *bool) (result autorest.Response, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/PipelineRunsClient.Cancel")
defer func() {
sc := -1
if result.Response != nil {
sc = result.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: factoryName,
Constraints: []validation.Constraint{{Target: "factoryName", Name: validation.MaxLength, Rule: 63, Chain: nil},
{Target: "factoryName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "factoryName", Name: validation.Pattern, Rule: `^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("datafactory.PipelineRunsClient", "Cancel", err.Error())
}
req, err := client.CancelPreparer(ctx, resourceGroupName, factoryName, runID, isRecursive)
if err != nil {
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "Cancel", nil, "Failure preparing request")
return
}
resp, err := client.CancelSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "Cancel", resp, "Failure sending request")
return
}
result, err = client.CancelResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "Cancel", resp, "Failure responding to request")
return
}
return
}
// CancelPreparer prepares the Cancel request.
func (client PipelineRunsClient) CancelPreparer(ctx context.Context, resourceGroupName string, factoryName string, runID string, isRecursive *bool) (*http.Request, error) {
pathParameters := map[string]interface{}{
"factoryName": autorest.Encode("path", factoryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"runId": autorest.Encode("path", runID),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if isRecursive != nil {
queryParameters["isRecursive"] = autorest.Encode("query", *isRecursive)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/pipelineruns/{runId}/cancel", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CancelSender sends the Cancel request. The method will close the
// http.Response Body if it receives an error.
func (client PipelineRunsClient) CancelSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// CancelResponder handles the response to the Cancel request. The method always
// closes the http.Response Body.
func (client PipelineRunsClient) CancelResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Get get a pipeline run by its run ID.
// Parameters:
// resourceGroupName - the resource group name.
// factoryName - the factory name.
// runID - the pipeline run identifier.
func (client PipelineRunsClient) Get(ctx context.Context, resourceGroupName string, factoryName string, runID string) (result PipelineRun, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/PipelineRunsClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: factoryName,
Constraints: []validation.Constraint{{Target: "factoryName", Name: validation.MaxLength, Rule: 63, Chain: nil},
{Target: "factoryName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "factoryName", Name: validation.Pattern, Rule: `^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("datafactory.PipelineRunsClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, factoryName, runID)
if err != nil {
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client PipelineRunsClient) GetPreparer(ctx context.Context, resourceGroupName string, factoryName string, runID string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"factoryName": autorest.Encode("path", factoryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"runId": autorest.Encode("path", runID),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/pipelineruns/{runId}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client PipelineRunsClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client PipelineRunsClient) GetResponder(resp *http.Response) (result PipelineRun, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// QueryByFactory query pipeline runs in the factory based on input filter conditions.
// Parameters:
// resourceGroupName - the resource group name.
// factoryName - the factory name.
// filterParameters - parameters to filter the pipeline run.
func (client PipelineRunsClient) QueryByFactory(ctx context.Context, resourceGroupName string, factoryName string, filterParameters RunFilterParameters) (result PipelineRunsQueryResponse, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/PipelineRunsClient.QueryByFactory")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: factoryName,
Constraints: []validation.Constraint{{Target: "factoryName", Name: validation.MaxLength, Rule: 63, Chain: nil},
{Target: "factoryName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "factoryName", Name: validation.Pattern, Rule: `^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$`, Chain: nil}}},
{TargetValue: filterParameters,
Constraints: []validation.Constraint{{Target: "filterParameters.LastUpdatedAfter", Name: validation.Null, Rule: true, Chain: nil},
{Target: "filterParameters.LastUpdatedBefore", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("datafactory.PipelineRunsClient", "QueryByFactory", err.Error())
}
req, err := client.QueryByFactoryPreparer(ctx, resourceGroupName, factoryName, filterParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "QueryByFactory", nil, "Failure preparing request")
return
}
resp, err := client.QueryByFactorySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "QueryByFactory", resp, "Failure sending request")
return
}
result, err = client.QueryByFactoryResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "datafactory.PipelineRunsClient", "QueryByFactory", resp, "Failure responding to request")
return
}
return
}
// QueryByFactoryPreparer prepares the QueryByFactory request.
func (client PipelineRunsClient) QueryByFactoryPreparer(ctx context.Context, resourceGroupName string, factoryName string, filterParameters RunFilterParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"factoryName": autorest.Encode("path", factoryName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/queryPipelineRuns", pathParameters),
autorest.WithJSON(filterParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// QueryByFactorySender sends the QueryByFactory request. The method will close the
// http.Response Body if it receives an error.
func (client PipelineRunsClient) QueryByFactorySender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// QueryByFactoryResponder handles the response to the QueryByFactory request. The method always
// closes the http.Response Body.
func (client PipelineRunsClient) QueryByFactoryResponder(resp *http.Response) (result PipelineRunsQueryResponse, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| mit |
bcoe/routers-news | lib/sources/news/major/latimes.js | 922 | var jDistiller = require('jdistiller').jDistiller,
Source = require('../../../source').Source;
exports.source = new Source({
source: "LATimes",
description: "The business and culture of our digital lives, from the L.A. Times.",
headlineURL: 'http://www.latimes.com/business/technology/',
headlineDistiller: new jDistiller()
.set('headlines', '.headline a', function(element) {
return [{
title: element.text().trim(),
href: 'http://www.latimes.com' + element.attr('href')
}]
}),
articleDistiller: new jDistiller()
.set('title', '.story h1')
.set('img', '.story img:first', function(element) {
return element.attr('src');
})
.set('body', '#story-body-text p', function(element, prev) {
prev.body = prev.body || '';
if (element.children().length) return;
prev.body += element.text().trim() + '\n\n';
return prev.body;
})
}); | mit |
naspinski/utilities | Naspinski.Utilities/StringConversions.cs | 6440 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.Security;
using System.Linq;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Naspinski.Utilities
{
public class Strings
{
/// <summary>
/// Generated a random string
/// </summary>
/// <param name="s">initialized string</param>
/// <param name="length">length of finished string</param>
/// <param name="isOnlyAlphaNumeric">if it is true, there will be no special characters</param>
/// <param name="minSpecialCharacters">if they are required, you can specify a minimum</param>
/// <returns>random string</returns>
public static string Random(int length, int minSpecialCharacters = 0)
{
bool isOnlyAlphaNumeric = minSpecialCharacters == 0;
string s = Membership.GeneratePassword(length, minSpecialCharacters);
if (!isOnlyAlphaNumeric) return s;
char[] msSpecialCharacters = "!@#$%^&*()_-+=[{]};:<>|./?".ToCharArray();
string filler = Membership.GeneratePassword(length, 0);
int fillerIndex = 0, fillerBuffer;
while (s.IndexOfAny(msSpecialCharacters) > -1 || s.Length < length)
{
s = s.RemoveCharacters(msSpecialCharacters);
fillerBuffer = length - s.Length;
if ((fillerBuffer + fillerIndex) > filler.Length)
{ // filler would out-of-bounds, get a new one
filler = Membership.GeneratePassword(length, 0);
fillerIndex = 0;
}
s += filler.Substring(fillerIndex, fillerBuffer);
fillerIndex += fillerBuffer;
}
return s;
}
}
public static class StringConversions
{
/// <summary>
/// Removes all characters from the string s
/// </summary>
/// <param name="s">string to remove characters from</param>
/// <param name="characters">array of characters to remove</param>
/// <returns>string with characters removed</returns>
public static string RemoveCharacters(this string s, char[] characters)
{
if (string.IsNullOrEmpty(s)) return s;
return new string(s.ToCharArray().Where(c => !characters.Contains(c)).ToArray());
}
/// <summary>
/// Converts a string to an enum of Type T
/// </summary>
/// <typeparam name="T">enum Type to convert to</typeparam>
/// <param name="s">string to convert</param>
/// <returns>enum of Type T</returns>
public static T ToEnum<T>(this string s)
{
try
{
return (T)Enum.Parse(typeof(T), s);
}
catch //tries to capitalize the first letter
{
CultureInfo cultureInfo = CultureInfo.GetCultureInfo("en-US");
TextInfo textInfo = cultureInfo.TextInfo;
s = textInfo.ToTitleCase(s.ToLower());
return (T)Enum.Parse(typeof(T), s);
}
}
/// <summary>
/// Converts a string to a nullable[T]
/// </summary>
/// <typeparam name="T">Type to convert to; this is the non-nullable version of the nullable return that will be returned</typeparam>
/// <param name="s">string to convert</param>
/// <returns>Nullable[T]</returns>
public static Nullable<T> ToNullable<T>(this string s) where T : struct
{
if (s != null && !string.IsNullOrEmpty(s.Trim()))
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T?));
return (T?)converter.ConvertFrom(s);
}
return null;
}
/// <summary>
/// Converts a string to Type T
/// </summary>
/// <typeparam name="T">Type to convert to</typeparam>
/// <param name="s">string to convert</param>
/// <returns>Type T Conversion of s if possible</returns>
public static T To<T>(this string s) where T : struct
{
if (string.IsNullOrEmpty(s)) throw new InvalidCastException("Cannot cast empty/null object to Type " + typeof(T).Name);
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T?));
return (T)converter.ConvertFrom(s);
}
/// <summary>
/// Splits a CamelCase word into a human readable - deals effectively with most abbreviations
/// </summary>
/// <param name="str">CamelCase String</param>
/// <returns>'Humanized' string</returns>
public static string SplitCamelCase(this string str)
{
return Regex.Replace(Regex.Replace(str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2"), @"(\p{Ll})(\P{Ll})", "$1 $2");
}
/// <summary>
/// Gets all instances of strings between two delimiters
/// </summary>
/// <param name="input">string to search</param>
/// <param name="left">left delimiter</param>
/// <param name="right">right delimiter</param>
/// <returns>List of strings that are located between delimiters</returns>
public static List<string> Between(this string input, string left, string right)
{
var pattern = "(" + Regex.Escape(left) + ")|(" + Regex.Escape(right) + ")";
var found = new List<string>();
var split = Regex.Split(input, pattern);
var leftSide = false;
var str = string.Empty;
foreach (var chunk in split)
{
if (leftSide && chunk != right)
{
str += chunk;
}
if (chunk == left)
{
leftSide = true;
}
if (chunk == right)
{
if (!string.IsNullOrEmpty(str))
{
found.Add(str);
}
str = string.Empty;
leftSide = false;
}
}
return found;
}
}
}
| mit |
quiaro/chunches | app/src/routes/index.js | 995 | import HomePublic from './HomePublic'
import HomePrivate from './HomePrivate'
import OfferedItems from './OfferedItems'
import OwnedItems from './OwnedItems'
import MyNetwork from './Network'
import LoginCallback from './LoginCallback'
import NotFoundPage from './NotFoundPage'
const routes = [
{
path: '/',
name: 'public-home',
exact: true,
public: true,
component: HomePublic,
},
{
path: '/home',
name: 'private-home',
exact: true,
component: HomePrivate,
},
{
path: '/offered',
name: 'offered',
exact: true,
component: OfferedItems,
},
{
path: '/owned',
name: 'owned',
exact: true,
component: OwnedItems,
},
{
path: '/network',
name: 'network',
exact: true,
component: MyNetwork,
},
{
path: '/callback',
name: 'callback',
public: true,
component: LoginCallback,
},
{
path: '*',
name: 'notfound',
component: NotFoundPage,
},
];
export default routes;
| mit |
pakx/the-mithril-diaries | src/app-structure-as-es6-modules/src/js/actions.js | 249 | export default createActions
var model = undefined
function createActions(mdl) {
model = mdl
return {
onIncrease: onIncrease
}
}
function onIncrease() {
model.clickCount += 1
model.msg = model.msg.toUpperCase()
} | mit |
alexander-emelyanov/yii2-articles-module | views/articles/update.php | 682 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model AlexanderEmelyanov\yii\modules\articles\models\Article */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'Article',
]) . ' ' . $model->article_id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Articles'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->article_id, 'url' => ['view', 'id' => $model->article_id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="article-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div> | mit |
AnkangLee/newcoder-oj-js_assessment | 09 数组合并/app.js | 59 | function concat(arr1, arr2) {
return arr1.concat(arr2);
}
| mit |
jdwil/xsd-tool | src/Output/Php/Traits/AnnotatedObjectTrait.php | 441 | <?php
declare(strict_types=1);
namespace JDWil\Xsd\Output\Php\Traits;
trait AnnotatedObjectTrait
{
/**
* @var string
*/
private $annotation;
/**
* @return string
*/
public function getAnnotation()
{
return $this->annotation;
}
/**
* @param string $annotation
*/
public function setAnnotation(string $annotation)
{
$this->annotation = $annotation;
}
}
| mit |
yousefmansour/Symfony-Practice-Project | app/cache/dev/twig/bc/bc1f6fa65f0b79d51f14745693073fc2e141e8b160f0472138d51eaaeb701309.php | 12055 | <?php
/* @WebProfiler/Router/panel.html.twig */
class __TwigTemplate_5e1572ea257fd168027c5526c810c7536f87f9db78ccd64a102fcfb436c63380 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_f72d700ddcddafc260c6ad89d8790a9c459218fa4e36c1a7e15aa697d6bf67e7 = $this->env->getExtension("native_profiler");
$__internal_f72d700ddcddafc260c6ad89d8790a9c459218fa4e36c1a7e15aa697d6bf67e7->enter($__internal_f72d700ddcddafc260c6ad89d8790a9c459218fa4e36c1a7e15aa697d6bf67e7_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@WebProfiler/Router/panel.html.twig"));
// line 1
echo "<h2>Routing</h2>
<div class=\"metrics\">
<div class=\"metric\">
<span class=\"value\">";
// line 5
echo twig_escape_filter($this->env, (($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "route", array())) ? ($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "route", array())) : ("(none)")), "html", null, true);
echo "</span>
<span class=\"label\">Matched route</span>
</div>
";
// line 9
if ($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "route", array())) {
// line 10
echo " <div class=\"metric\">
<span class=\"value\">";
// line 11
echo twig_escape_filter($this->env, twig_length_filter($this->env, (isset($context["traces"]) ? $context["traces"] : $this->getContext($context, "traces"))), "html", null, true);
echo "</span>
<span class=\"label\">Tested routes before match</span>
</div>
";
}
// line 15
echo "</div>
";
// line 17
if ($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "route", array())) {
// line 18
echo " <h3>Route Parameters</h3>
";
// line 20
if (twig_test_empty($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "routeParams", array()))) {
// line 21
echo " <div class=\"empty\">
<p>No parameters.</p>
</div>
";
} else {
// line 25
echo " ";
echo twig_include($this->env, $context, "@WebProfiler/Profiler/table.html.twig", array("data" => $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "routeParams", array()), "labels" => array(0 => "Name", 1 => "Value")), false);
echo "
";
}
}
// line 28
echo "
";
// line 29
if ($this->getAttribute((isset($context["router"]) ? $context["router"] : $this->getContext($context, "router")), "redirect", array())) {
// line 30
echo " <h3>Route Redirection</h3>
<p>This page redirects to:</p>
<div class=\"card\" style=\"break-long-words\">
";
// line 34
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["router"]) ? $context["router"] : $this->getContext($context, "router")), "targetUrl", array()), "html", null, true);
echo "
";
// line 35
if ($this->getAttribute((isset($context["router"]) ? $context["router"] : $this->getContext($context, "router")), "targetRoute", array())) {
echo "<span class=\"text-muted\">(route: \"";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["router"]) ? $context["router"] : $this->getContext($context, "router")), "targetRoute", array()), "html", null, true);
echo "\")</span>";
}
// line 36
echo " </div>
";
}
// line 38
echo "
<h3>Route Matching Logs</h3>
<div class=\"card\">
<strong>Path to match:</strong> <code>";
// line 42
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "pathinfo", array()), "html", null, true);
echo "</code>
</div>
<table id=\"router-logs\">
<thead>
<tr>
<th>#</th>
<th>Route name</th>
<th>Path</th>
<th>Log</th>
</tr>
</thead>
<tbody>
";
// line 55
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["traces"]) ? $context["traces"] : $this->getContext($context, "traces")));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["trace"]) {
// line 56
echo " <tr class=\"";
echo ((($this->getAttribute($context["trace"], "level", array()) == 1)) ? ("status-warning") : (((($this->getAttribute($context["trace"], "level", array()) == 2)) ? ("status-success") : (""))));
echo "\">
<td class=\"font-normal text-muted\">";
// line 57
echo twig_escape_filter($this->env, $this->getAttribute($context["loop"], "index", array()), "html", null, true);
echo "</td>
<td>";
// line 58
echo twig_escape_filter($this->env, $this->getAttribute($context["trace"], "name", array()), "html", null, true);
echo "</td>
<td>";
// line 59
echo twig_escape_filter($this->env, $this->getAttribute($context["trace"], "path", array()), "html", null, true);
echo "</td>
<td class=\"font-normal\">
";
// line 61
if (($this->getAttribute($context["trace"], "level", array()) == 1)) {
// line 62
echo " Path almost matches, but
<span class=\"newline\">";
// line 63
echo twig_escape_filter($this->env, $this->getAttribute($context["trace"], "log", array()), "html", null, true);
echo "</span>
";
} elseif (($this->getAttribute( // line 64
$context["trace"], "level", array()) == 2)) {
// line 65
echo " ";
echo twig_escape_filter($this->env, $this->getAttribute($context["trace"], "log", array()), "html", null, true);
echo "
";
} else {
// line 67
echo " Path does not match
";
}
// line 69
echo " </td>
</tr>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 72
echo " </tbody>
</table>
<p class=\"help\">
Note: These matching logs are based on the current router configuration,
which might differ from the configuration used when profiling this request.
</p>
";
$__internal_f72d700ddcddafc260c6ad89d8790a9c459218fa4e36c1a7e15aa697d6bf67e7->leave($__internal_f72d700ddcddafc260c6ad89d8790a9c459218fa4e36c1a7e15aa697d6bf67e7_prof);
}
public function getTemplateName()
{
return "@WebProfiler/Router/panel.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 191 => 72, 175 => 69, 171 => 67, 165 => 65, 163 => 64, 159 => 63, 156 => 62, 154 => 61, 149 => 59, 145 => 58, 141 => 57, 136 => 56, 119 => 55, 103 => 42, 97 => 38, 93 => 36, 87 => 35, 83 => 34, 77 => 30, 75 => 29, 72 => 28, 65 => 25, 59 => 21, 57 => 20, 53 => 18, 51 => 17, 47 => 15, 40 => 11, 37 => 10, 35 => 9, 28 => 5, 22 => 1,);
}
}
/* <h2>Routing</h2>*/
/* */
/* <div class="metrics">*/
/* <div class="metric">*/
/* <span class="value">{{ request.route ?: '(none)' }}</span>*/
/* <span class="label">Matched route</span>*/
/* </div>*/
/* */
/* {% if request.route %}*/
/* <div class="metric">*/
/* <span class="value">{{ traces|length }}</span>*/
/* <span class="label">Tested routes before match</span>*/
/* </div>*/
/* {% endif %}*/
/* </div>*/
/* */
/* {% if request.route %}*/
/* <h3>Route Parameters</h3>*/
/* */
/* {% if request.routeParams is empty %}*/
/* <div class="empty">*/
/* <p>No parameters.</p>*/
/* </div>*/
/* {% else %}*/
/* {{ include('@WebProfiler/Profiler/table.html.twig', { data: request.routeParams, labels: ['Name', 'Value'] }, with_context = false) }}*/
/* {% endif %}*/
/* {% endif %}*/
/* */
/* {% if router.redirect %}*/
/* <h3>Route Redirection</h3>*/
/* */
/* <p>This page redirects to:</p>*/
/* <div class="card" style="break-long-words">*/
/* {{ router.targetUrl }}*/
/* {% if router.targetRoute %}<span class="text-muted">(route: "{{ router.targetRoute }}")</span>{% endif %}*/
/* </div>*/
/* {% endif %}*/
/* */
/* <h3>Route Matching Logs</h3>*/
/* */
/* <div class="card">*/
/* <strong>Path to match:</strong> <code>{{ request.pathinfo }}</code>*/
/* </div>*/
/* */
/* <table id="router-logs">*/
/* <thead>*/
/* <tr>*/
/* <th>#</th>*/
/* <th>Route name</th>*/
/* <th>Path</th>*/
/* <th>Log</th>*/
/* </tr>*/
/* </thead>*/
/* <tbody>*/
/* {% for trace in traces %}*/
/* <tr class="{{ trace.level == 1 ? 'status-warning' : trace.level == 2 ? 'status-success' }}">*/
/* <td class="font-normal text-muted">{{ loop.index }}</td>*/
/* <td>{{ trace.name }}</td>*/
/* <td>{{ trace.path }}</td>*/
/* <td class="font-normal">*/
/* {% if trace.level == 1 %}*/
/* Path almost matches, but*/
/* <span class="newline">{{ trace.log }}</span>*/
/* {% elseif trace.level == 2 %}*/
/* {{ trace.log }}*/
/* {% else %}*/
/* Path does not match*/
/* {% endif %}*/
/* </td>*/
/* </tr>*/
/* {% endfor %}*/
/* </tbody>*/
/* </table>*/
/* */
/* <p class="help">*/
/* Note: These matching logs are based on the current router configuration,*/
/* which might differ from the configuration used when profiling this request.*/
/* </p>*/
/* */
| mit |
simondean/camel-mingle-spike | camel-mingle/src/main/java/org/simondean/camel/mingle/component/MingleConsumer.java | 1581 | package org.simondean.camel.mingle.component;
import org.apache.camel.Processor;
import org.apache.camel.impl.DefaultConsumer;
import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
public class MingleConsumer extends DefaultConsumer {
private final MingleEndpoint endpoint;
private boolean running = false;
private MingleInnerConsumer client;
private ScheduledExecutorService executor;
public MingleConsumer(MingleEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.endpoint = endpoint;
}
@Override
public MingleEndpoint getEndpoint() {
return (MingleEndpoint)super.getEndpoint();
}
@Override
protected void doStart() throws Exception {
super.doStart();
if (!running) {
createExecutor();
createClient();
startClient();
}
}
@Override
protected void doStop() throws Exception {
if (running) {
destroyExecutor();
destroyClient();
running = false;
}
super.doStop();
}
private void createClient() {
client = new MingleInnerConsumer(this);
}
private void startClient() {
executor.execute(client);
}
private void destroyClient() throws IOException {
client.close();
client = null;
}
private void createExecutor() {
executor = endpoint.getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(this, "MingleConsumer");
}
private void destroyExecutor() {
endpoint.getCamelContext().getExecutorServiceManager().shutdownNow(executor);
executor = null;
}
}
| mit |
CrOrc/Cr.ArgParse | src/Cr.ArgParse.Tests/TestCases/TestTypeUserDefined.cs | 1543 | using System;
namespace Cr.ArgParse.Tests.TestCases
{
public class TestTypeUserDefined : ParserTestCase
{
public class MyType : IEquatable<MyType>
{
public override int GetHashCode()
{
return (Value != null ? Value.GetHashCode() : 0);
}
public static bool operator ==(MyType left, MyType right)
{
return Equals(left, right);
}
public static bool operator !=(MyType left, MyType right)
{
return !Equals(left, right);
}
public MyType(string value)
{
Value = value;
}
public string Value { get; private set; }
public bool Equals(MyType other)
{
return other != null && Value == other.Value;
}
public override bool Equals(object obj)
{
return Equals(obj as MyType);
}
}
public TestTypeUserDefined()
{
ArgumentSignatures = new[]
{
new Argument("-x") {TypeFactory = arg => new MyType(arg)},
new Argument("spam") {TypeFactory = arg => new MyType(arg)}
};
Successes = new SuccessCollection
{
{"a -x b", new ParseResult {{"x", new MyType("b")}, {"spam", new MyType("a")}}}
};
}
}
} | mit |
micheljung/downlords-faf-client | src/test/java/com/faforever/client/game/CustomGamesControllerTest.java | 5450 | package com.faforever.client.game;
import com.faforever.client.i18n.I18n;
import com.faforever.client.preferences.Preferences;
import com.faforever.client.preferences.PreferencesService;
import com.faforever.client.test.AbstractPlainJavaFxTest;
import com.faforever.client.theme.UiService;
import com.faforever.client.vault.replay.WatchButtonController;
import com.google.common.eventbus.EventBus;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.event.ActionEvent;
import javafx.scene.layout.Pane;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.testfx.util.WaitForAsyncUtils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CustomGamesControllerTest extends AbstractPlainJavaFxTest {
private CustomGamesController instance;
@Mock
private GameService gameService;
@Mock
private PreferencesService preferencesService;
@Mock
private Preferences preferences;
@Mock
private UiService uiService;
@Mock
private GamesTableController gamesTableController;
@Mock
private EventBus eventBus;
@Mock
private GameDetailController gameDetailController;
@Mock
private WatchButtonController watchButtonController;
@Mock
private I18n i18n;
@Mock
private GamesTilesContainerController gamesTilesContainerController;
private ObservableList games;
@Before
public void setUp() throws Exception {
instance = new CustomGamesController(uiService, gameService, preferencesService, eventBus, i18n);
games = FXCollections.observableArrayList();
when(gameService.getGames()).thenReturn(games);
when(preferencesService.getPreferences()).thenReturn(preferences);
when(preferences.showModdedGamesProperty()).thenReturn(new SimpleBooleanProperty(true));
when(preferences.showPasswordProtectedGamesProperty()).thenReturn(new SimpleBooleanProperty(true));
when(preferences.getGamesViewMode()).thenReturn("tableButton");
when(uiService.loadFxml("theme/play/games_table.fxml")).thenReturn(gamesTableController);
when(uiService.loadFxml("theme/play/games_tiles_container.fxml")).thenReturn(gamesTilesContainerController);
when(gamesTilesContainerController.getRoot()).thenReturn(new Pane());
when(gamesTableController.getRoot()).thenReturn(new Pane());
when(gamesTableController.selectedGameProperty()).thenReturn(new SimpleObjectProperty<>());
when(gamesTilesContainerController.selectedGameProperty()).thenReturn(new SimpleObjectProperty<>());
loadFxml("theme/play/custom_games.fxml", clazz -> {
if (clazz == GameDetailController.class) {
return gameDetailController;
}
if (clazz == WatchButtonController.class) {
return watchButtonController;
}
return instance;
});
}
@Test
public void testSetSelectedGameShowsDetailPane() throws Exception {
assertFalse(instance.gameDetailPane.isVisible());
instance.setSelectedGame(GameBuilder.create().defaultValues().get());
assertTrue(instance.gameDetailPane.isVisible());
}
@Test
public void testSetSelectedGameNullHidesDetailPane() throws Exception {
instance.setSelectedGame(GameBuilder.create().defaultValues().get());
assertTrue(instance.gameDetailPane.isVisible());
instance.setSelectedGame(null);
assertFalse(instance.gameDetailPane.isVisible());
}
@Test
public void testUpdateFilters() throws Exception {
Game game = GameBuilder.create().defaultValues().get();
Game gameWithMod = GameBuilder.create().defaultValues().get();
Game gameWithPW = GameBuilder.create().defaultValues().get();
Game gameWithModAndPW = GameBuilder.create().defaultValues().get();
ObservableMap<String, String> simMods = FXCollections.observableHashMap();
simMods.put("123-456-789", "Fake mod name");
gameWithMod.setSimMods(simMods);
gameWithModAndPW.setSimMods(simMods);
gameWithPW.setPassword("password");
gameWithPW.passwordProtectedProperty().set(true);
gameWithModAndPW.setPassword("password");
gameWithModAndPW.passwordProtectedProperty().set(true);
ObservableList<Game> games = FXCollections.observableArrayList();
games.addAll(game, gameWithMod, gameWithPW, gameWithModAndPW);
instance.setFilteredList(games);
instance.showModdedGamesCheckBox.setSelected(true);
instance.showPasswordProtectedGamesCheckBox.setSelected(true);
assertTrue(instance.filteredItems.size() == 4);
instance.showModdedGamesCheckBox.setSelected(false);
assertTrue(instance.filteredItems.size() == 2);
instance.showPasswordProtectedGamesCheckBox.setSelected(false);
assertTrue(instance.filteredItems.size() == 1);
instance.showModdedGamesCheckBox.setSelected(true);
assertTrue(instance.filteredItems.size() == 2);
}
@Test
public void testTiles() throws Exception {
instance.tilesButton.getOnAction().handle(new ActionEvent());
WaitForAsyncUtils.waitForFxEvents();
verify(gamesTilesContainerController).createTiledFlowPane(games, instance.chooseSortingTypeChoiceBox);
}
}
| mit |
Vertexwahn/appleseed | src/appleseed.python/bindframe.cpp | 3503 |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited
// Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// appleseed.python headers.
#include "pyseed.h" // has to be first, to avoid redefinition warnings
#include "dict2dict.h"
// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/kernel/aov/imagestack.h"
// appleseed.foundation headers.
#include "foundation/image/image.h"
#include "foundation/image/tile.h"
namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;
namespace
{
auto_release_ptr<Frame> create_frame(
const std::string& name,
const bpy::dict& params)
{
return FrameFactory::create(name.c_str(), bpy_dict_to_param_array(params));
}
void transform_tile_to_output_color_space(const Frame* frame, Tile* tile)
{
frame->transform_to_output_color_space(*tile);
}
void transform_image_to_output_color_space(const Frame* frame, Image* image)
{
frame->transform_to_output_color_space(*image);
}
bpy::object archive_frame(const Frame* frame, const char* directory)
{
char* output = 0;
if (frame->archive(directory, &output))
{
const bpy::str path(output);
foundation::free_string(output);
return path;
}
// Return None.
return bpy::object();
}
}
void bind_frame()
{
bpy::class_<Frame, auto_release_ptr<Frame>, bpy::bases<Entity>, boost::noncopyable>("Frame", bpy::no_init)
.def("__init__", bpy::make_constructor(create_frame))
.def("image", &Frame::image, bpy::return_value_policy<bpy::reference_existing_object>())
.def("aov_images", &Frame::aov_images, bpy::return_value_policy<bpy::reference_existing_object>())
.def("transform_tile_to_output_color_space", transform_tile_to_output_color_space)
.def("transform_image_to_output_color_space", transform_image_to_output_color_space)
.def("clear_main_image", &Frame::clear_main_image)
.def("write_main_image", &Frame::write_main_image)
.def("write_aov_images", &Frame::write_aov_images)
.def("archive", archive_frame)
;
}
| mit |
Gustavo/reconsnet | app/helpers/versions_helper.rb | 1968 | module VersionsHelper
def self.event_name_i18n(name)
case name
when 'update' then return 'editou'
when 'create' then return 'adicionou'
when 'destroy' then return 'excluiu'
end
end
def self.changeset(version, resource)
# Esta listagem inclui os ignored para todos os objetos que estão cadastrados no
# paper_trail.
# Default para todos
ignore_attrs = %w(updated_at created_at id)
# Para PhoneNumber e Address
ignore_attrs += %w(phonable_id phonable_type addressable_id addressable_type)
# Para Participation. O nome do evento e da pessoa já aparecem no título então não é necessário aparecer no changeset
ignore_attrs += %w(event_id person_id)
changeset = {}
if version.event == 'destroy'
resource.serializable_hash.dup.except(*ignore_attrs).each do |k,v|
changeset[k] = [v, '']
end
else
changeset = version.changeset.dup.except(*ignore_attrs)
end
changeset
end
def self.attribute_display(resource_name, attrib_name, attrib_value, stripped = false)
return '<em class=text-muted><vazio></em>'.html_safe if attrib_value.blank?
html = ''
if resource_name == 'Participation' and attrib_name == 'person_id'
html += Person.find(attrib_value).name
elsif resource_name == 'Participation' and attrib_name == 'event_id'
html += Event.find(attrib_value).name
elsif resource_name == 'Participation' and attrib_name == 'attendance'
html += I18n.t("participation.attendance.#{attrib_value}").downcase
elsif resource_name == 'Participation' and attrib_name == 'p_type'
html += I18n.t("participation.types.#{attrib_value}").downcase
elsif resource_name == 'Participation' and attrib_name == 'status'
html += I18n.t("participation.status.#{attrib_value}").downcase
else
html += attrib_value.to_s
end
return stripped ? "<s>#{html}</s>".html_safe : html.html_safe
end
end | mit |
UUDigitalHumanitieslab/persistent-forking | templates/public_fork_box.php | 2630 | <?php
/**
* Render the inset with fork button and parent link for the
* public view of a post.
*
* Required parameters:
* $post_id the ID of the post for which the inset will be
* rendered
* $image_url the URL of the fork icon image file
*/
$fork_url = add_query_arg( array(
'action' => 'persistent_fork',
'post' => $post_id,
'nonce' => wp_create_nonce( 'persistent_forking' ),
), home_url() );
$parent_id = get_post_meta( $post_id, '_persistfork-parent', true );
$families = wp_get_object_terms( $post_id, 'family' );
$family = reset( $families );
?>
<div id="persistfork-inset">
<img src="<?php echo $image_url ?>" title="Fork" alt="Fork" />
<a href="<?php echo $fork_url ?>" title="Fork this post">Fork</a>
<?php if ( $parent_id ): ?>
Forked from:
<a href="<?php echo get_permalink( $parent_id ) ?>">
<?php echo get_post( $parent_id )->post_title ?>
</a>
<?php endif ?>
<?php if ( $family ):
$family_id = $family->term_id; ?>
<a href="#" onclick="persistfork.visualise(data_<?php echo $family_id ?>); return false;">
Show family
</a>
<?php
// Henceforth: JSON for vis.js graph. See also visualisation.js.
global $persistfork_rendered;
if ( ! isset( $persistfork_rendered ) ) $persistfork_rendered = array();
// Each family tree is represented only once.
if ( ! array_key_exists( $family_id, $persistfork_rendered ) ):
$persistfork_rendered[ $family_id ] = true;
$nodes = get_objects_in_term( $family_id, 'family' );
$edges = array();
foreach ( $nodes as $id ) {
$parent_id = get_post_meta( $id, '_persistfork-parent', true );
if ( $parent_id ) {
$edges[] = array(
'from' => $parent_id,
'to' => $id,
);
}
}
$current_node = reset( $nodes );
$current_edge = reset( $edges ); ?>
<script>
var data_<?php echo $family_id ?> = {
nodes: [
<?php while ( false !== $current_node ): ?>
{
id: <?php echo $current_node ?>,
label: '<?php
echo esc_js( get_post( $current_node )->post_title )
?>',
href: '<?php echo get_permalink( $current_node ) ?>'
}<?php
$current_node = next( $nodes );
if ( false !== $current_node ) {
echo ',';
}
endwhile ?>
],
edges: [
<?php while ( false !== $current_edge ): ?>
{
from: <?php echo $current_edge['from'] ?>,
to: <?php echo $current_edge['to'] ?>
}<?php
$current_edge = next( $edges );
if ( false !== $current_edge ) {
echo ',';
}
endwhile ?>
]
};
</script>
<?php endif ?>
<?php endif ?>
</div>
| mit |
SSStormy/Stormbot | Bot.Core/Modules/Twitch/BttvEmoteSource.cs | 1358 | using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Stormbot.Bot.Core.Services;
using StrmyCore;
namespace Stormbot.Bot.Core.Modules.Twitch
{
internal sealed class BttvEmoteSource : CentralziedEmoteSource
{
protected override string DataSource => "https://api.betterttv.net/2/emotes";
protected override void PopulateDictionary(JObject data)
{
foreach (JToken token in data["emotes"])
EmoteDict.Add(token["code"].ToObject<string>(), token["id"].ToObject<string>());
Logger.FormattedWrite(GetType().Name, $"Loaded {EmoteDict.Count} bttv emotes.", ConsoleColor.DarkGreen);
}
public override async Task<string> GetEmote(string emote, HttpService http)
{
if (!EmoteDict.ContainsKey(emote))
return null;
string imageId = EmoteDict[emote];
string dir = Path.Combine(Constants.TwitchEmoteFolderDir, imageId + ".png");
if (!File.Exists(dir))
{
HttpContent content =
await http.Send(HttpMethod.Get, $"https://cdn.betterttv.net/emote/{imageId}/2x");
File.WriteAllBytes(dir, await content.ReadAsByteArrayAsync());
}
return dir;
}
}
} | mit |
ktmud/david | david/static/js/lib/bootstrap.js | 138 | //@nowrap
//@import ../../bower_components/hammerjs/dist/jquery.hammer.js
//@import ../../bower_components/bootstrap/dist/js/bootstrap.js
| mit |
cuckata23/wurfl-data | data/nokia_n86_ver1_sub20067.php | 152 | <?php
return array (
'id' => 'nokia_n86_ver1_sub20067',
'fallback' => 'nokia_n86_ver1',
'capabilities' =>
array (
'aac' => 'true',
),
);
| mit |
Norbyte/enigma | test/enigma/transaction-assign.php | 406 | <?php
// Tests that a connection with an open transaction won't get assigned
// to other handles on the same pool
$poolOptions = ['persistent' => true, 'pool_size' => 2];
include 'connect.inc';
query('begin');
$pid1 = get_pg_pid($pool);
$pool2 = Enigma\create_pool($connectionOptions, $poolOptions);
for ($i = 0; $i < 10; $i++) {
$pid2 = get_pg_pid($pool2);
if ($pid2 == $pid1) echo 'FAIL';
}
| mit |
tdgs/image_editor | spec/image_editor/vertical_draw_command_spec.rb | 339 | require 'spec_helper'
describe ImageEditor::VerticalDrawCommand do
let(:image) {ImageEditor::Image.new(2,3)}
before do
ImageEditor.image = image
end
it "draws horizontaly" do
image.should_receive(:draw_vertical).with(1, 2, 3, "A")
ImageEditor::VerticalDrawCommand.run(x: "1", y1: "2", y2: "3", color: "A")
end
end
| mit |
tupamba/kardex | node_modules/firebase/storage/implementation/array.js | 1476 | /*! @license Firebase v4.5.0
Build: rev-f49c8b5
Terms: https://firebase.google.com/terms/ */
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.contains = contains;
exports.clone = clone;
exports.remove = remove;
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Returns true if the object is contained in the array (compared with ===).
* @template T
*/
function contains(array, elem) {
return array.indexOf(elem) !== -1;
}
/**
* Returns a shallow copy of the array or array-like object (e.g. arguments).
* @template T
*/
function clone(arraylike) {
return Array.prototype.slice.call(arraylike);
}
/**
* Removes the given element from the given array, if it is contained.
* Directly modifies the passed-in array.
* @template T
*/
function remove(array, elem) {
var i = array.indexOf(elem);
if (i !== -1) {
array.splice(i, 1);
}
}
//# sourceMappingURL=array.js.map
| mit |
PareshNavalakha/ObjectDiffUtil | src/main/java/com/paresh/diff/calculators/ObjectDiffCalculator.java | 1480 | package com.paresh.diff.calculators;
import com.paresh.diff.dto.Diff;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ObjectDiffCalculator extends DiffCalculator {
@Override
public Collection<Diff> apply(Object before, Object after, String description) {
Collection<Diff> diffs = new ConcurrentLinkedQueue<>();
if (before == null && after == null) {
diffs.add(new Diff.Builder().hasNotChanged().setFieldDescription(description).build());
} else if (before == null) {
diffs.add(new Diff.Builder().isAdded().setAfterValue(after).setFieldDescription(description).build());
} else if (after == null) {
diffs.add(new Diff.Builder().isDeleted().setBeforeValue(before).setFieldDescription(description).build());
} else {
if (before.equals(after)) {
diffs.add(new Diff.Builder().hasNotChanged().setBeforeValue(before).setAfterValue(after).setFieldDescription(description).build());
} else {
diffs.add(new Diff.Builder().isUpdated().setBeforeValue(before).setAfterValue(after).setFieldDescription(description).build());
}
}
return diffs;
}
//Default fallback in case no other calculator gets triggered
@Override
public int getOrder() {
return 0;
}
@Override
public boolean test(Object o1, Object o2) {
return true;
}
} | mit |
progitlabs/Ripple | public/js/beta-ripple.js | 12168 | document.onreadystatechange = function () {
if (document.readyState == 'loaded' || document.readyState == 'complete') {
setTimeout(function () {
$('.ripple-loader').fadeOut(1000).remove();
}, 500);
}
};
$(document).ready(function () {
"use strict";
//setInterval(function () { console.log(document.readyState) }, 100);
/*
* ***********************************************************************************
* Global js script Start
* ***********************************************************************************
*/
var body = document.body,
html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
$('#app').css('min-height', height + "px");
$('.rpl-container').css('min-height', (height - 53) + "px");
// Toastr Notifications.........
var toastrNotify = setInterval(function () {
if ($('#toast-container').length === 0) {
$('#toast-notify').remove();
clearInterval(toastrNotify);
}
}, 10);
// init Slim scroll on load
// initSlimScroll();
// init Slim scroll on window resize
$(window).on('resize', function () {
// initSlimScroll();
});
//TinyMCE Text Editor.......
tinymce.init({
menubar: false,
selector: 'textarea.ripple_text_editor',
skin: 'ripple',
plugins: 'link, image, code, youtube, giphy',
extended_valid_elements: 'input[onclick|value|style|type]',
file_browser_callback: function (field_name, url, type, win) {
if (type == 'image') {
$('#upload_file').trigger('click');
}
},
toolbar: 'styleselect bold italic underline | alignleft aligncenter alignright | bullist numlist outdent indent | link image youtube giphy | code',
convert_urls: false,
image_caption: true,
image_title: true
});
/*
* ***********************************************************************************
* Global js script End
* ***********************************************************************************
*/
/*
|----------------------------------------------------------------------
| Page content height
|----------------------------------------------------------------------
*/
$('.image-preview').previewImage({ id: 'asdfasfd' });
/**
* File field on change event
*/
$(document).on('change', '.custom-file-input', function () {
var attr = $(this).attr('multiple');
if (typeof attr === typeof undefined) {
var file = $(this)[0].files[0];
$(this).siblings('.custom-file-label').html('<div class="text-primary">' + file.name + '</div>');
}
});
/**
* Bread System image file on change
*/
$(document).on('change', '.custom-file-input-bread', function(){
var attr = $(this).attr('multiple');
if (typeof attr === typeof undefined) {
var file = $(this)[0].files[0];
if(file.size >= 1024 && file.size < 1048576){
var fileSize = (file.size / 1024).toFixed(2) + 'KB';
}else if(file.size >= 1048576 && file.size < 1073741824){
var fileSize = (file.size / 1048576).toFixed(2) + 'MB';
}
var HTML = '';
HTML += '<p><strong>Title:</strong> <code>' + file.name + '</code></p>';
HTML += '<p><strong>Size:</strong> <code>'+ fileSize +'</code></p>';
HTML += '<p><strong>Type:</strong> <code>'+ file.type +'</code></p>';
$($(this).attr('data-details')).html(HTML);
}
});
/*
|-------------------------------------------------------------------------------------------------------------------
| Setting Model "setting-key"
|-------------------------------------------------------------------------------------------------------------------
*/
var setting_key = "#setting-key, .setting-key, input[name=setting-key], input[data-id=setting-key]";
$(document).on('keydown keyup', setting_key, function (e) {
if ((e.which >= 65 && e.which <= 90) || e.which === 8 || e.which === 9 || e.which === 17 || e.which === 16 || e.which === 173) {
$(this).val($(this).val().toLowerCase());
return e.which;
}
e.preventDefault();
});
/*
|-------------------------------------------------------------------------------------------------------------------
| Setting Model "setting-type" Start
|-------------------------------------------------------------------------------------------------------------------
*/
var setting_type = "#setting-type, .setting-type, select[name=setting-type], select[data-id=setting-type]";
$(document).on('change', setting_type, function (e) {
var type = $(this).val(),
setting_options = "#setting-options, .setting-options, div[data-id=setting-options]",
option_name = 'input.option-name[data-id=option-name][data-name=option-name]',
option_value = 'input.option-value[data-id=option-value][data-name=option-value]';
if (type === "radio" || type === "dropdown") {
$(setting_options).slideDown(500, function () {
$(this).find(option_name).attr('name', 'option-name[]');
$(this).find(option_value).attr('name', 'option-value[]');
});
} else {
$(setting_options).slideUp(500, function () {
$(this).find(option_name + ', ' + option_value).removeAttr('name').val('');
$('.setting-option-group.option-group').each(function (index, ele) {
if (index !== 0)
$(this).remove();
});
});
}
});
$(document).on('click', '[data-dismiss="modal"]', function () {
var setting_options = "#setting-options, .setting-options, div[data-id=setting-options]",
option_name = 'input.option-name[data-id=option-name][data-name=option-name]',
option_value = 'input.option-value[data-id=option-value][data-name=option-value]';
$(setting_options).slideUp(500, function () {
$(this).find(option_name + ', ' + option_value).removeAttr('name').val('');
$('.setting-option-group.option-group').each(function (index, ele) {
if (index !== 0)
$(this).remove();
});
$('#setting-type').val('text_box');
});
});
$(document).on('click', '.add-options, #add-options', function () {
// var new_option = $('.option-group.setting-option-group:first').clone(true, true);
$('#option-wrappers.option-wrappers').append($('.option-group.setting-option-group:first').clone(true, true));
$('.option-group.setting-option-group:last').find('input').val('');
$('.option-group.setting-option-group:last').find('input:first').val('').trigger('focus');
});
$(document).on('click', '.remove-options', function () {
var options = $('.option-group.setting-option-group').length;
if (options > 1) {
$(this).parents('.option-group.setting-option-group').remove();
toastr.success('Option deleted successfully', "Deleted!");
} else {
toastr.warning('Cannot delete option...', "Warning!");
}
});
var ad_on_tab = '.option-group.setting-option-group:last .option-value[data-id=option-value]';
$(document).on('keydown', ad_on_tab, function (e) {
if (e.which === 9) {
$('#add-options.add-options').trigger('click');
$('.option-group.setting-option-group:last .option-name[data-id=option-name]').find('input:first').val('').trigger('focus');
}
});
jQuery('#option-sorting').sortable({
connectWith: '#option-wrappers',
items: '.setting-option-group',
opacity: .75,
handle: '.draggable-handler',
// placeholder: 'draggable-placeholder',
tolerance: 'pointer',
start: function (e, ui) {
ui.placeholder.css({
'height': ui.item.outerHeight(),
'margin-bottom': ui.item.css('margin-bottom')
});
}
});
/*
* ------------------------------------------------------------------------------------------------------------------
* Validate Add Setting Form
* ------------------------------------------------------------------------------------------------------------------
*/
$(document).on('click', '.save_setting_btn#save_setting_btn', function () {
var key = $('.setting-key[name=setting-key]').val(), name = $('.setting-name[name=setting-name]').val();
if (key !== '') {
if (name !== '') {
$('#add_new_setting').submit();
} else {
$('.setting-name[name=setting-name]').parents('div.form-group').addClass('has-error');
}
} else {
$('.setting-key[name=setting-key]').parents('div.form-group').addClass('has-error');
}
});
$(document).on('keyup blur', '.setting-name[name=setting-name], .setting-key[name=setting-key]', function () {
if ($(this).val() === '') {
$(this).parents('div.form-group').removeClass('has-success').addClass('has-error');
} else {
$(this).parents('div.form-group').removeClass('has-error').addClass('has-success');
}
});
/*
* Delete Setting
*/
$(document).on('click', '.setting-trash', function () {
var id = $(this).attr('data-id'), key = $(this).attr('data-key'), token = window.Laravel.csrfToken;
var data = {
_token: token,
id: id,
key: key,
"setting-delete": 'yes'
};
$.post(window.location, data, function (data) {
if (data.status === 'ok') {
window.location.reload();
}
})
});
/*
* testing
*/
});
/*
* Function Declarations
*/
$.fn.extend({
previewImage: function (o) {
this.on('change', function () {
var options = $.extend({ 'class': 'img-responsive', id: '', height: '200', width: 'auto', alt: '', wrapInto: '#' + $(this).attr('data-preview') }, o);
if($(this).attr('data-width')){
options.width = $(this).attr('data-width');
}
if($(this).attr('data-height')){
options.height = $(this).attr('data-height');
}
$(options.wrapInto)
//Setting up img wrapper height to prevent toggle div height
.css('height', $(options.wrapInto).children('img').height() + 'px')
.html('');
if (typeof (FileReader) !== 'undefined') {
for (var i in this.files) {
if (typeof this.files[i] === 'object' && this.files[i].type === 'image/jpeg' || this.files[i].type === 'image/png' || this.files[i].type === 'image/gif' || this.files[i].type === 'image/svg' || this.files[i].type === 'image/jpg') {
var image = new FileReader();
image.onload = function (e) {
$('<img/>', {
src: e.target.result, class: options.class, 'style': 'max-width :'+options.width+'px !important; height:'+options.height+'px;', alt: options.alt, id: options.id
}).appendTo(options.wrapInto);
};
image.readAsDataURL(this.files[i]);
}
}
}
});
}
});
| mit |
EricCharnesky/CIS2353-Fall2017 | HoldemYall/src/holdemyall/HoldemYall.java | 5031 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package holdemyall;
import java.util.ArrayList;
import stacks.LinkedStack;
import java.util.Random;
/**
*
* @author etcharn1
*/
public class HoldemYall {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Card> deck = GetPokerDeck();
for ( Card card : deck )
{
System.out.println(card.face + card.suit);
}
LinkedStack<Card> thisIsTheRealDeck = new LinkedStack<>();
Random random = new Random();
while ( !deck.isEmpty() )
{
thisIsTheRealDeck.push(
deck.remove( random.nextInt(deck.size())) );
}
// while ( !thisIsTheRealDeck.isEmpty() )
// {
// Card card = thisIsTheRealDeck.pop();
// System.out.println(card.face + card.suit);
// }
Card[] sharedCards = new Card[5];
for ( int cardNumber = 0; cardNumber < sharedCards.length; cardNumber++ )
{
sharedCards[cardNumber] = thisIsTheRealDeck.pop();
}
Card[] myCards = new Card[2];
myCards[0] = thisIsTheRealDeck.pop();
myCards[1] = thisIsTheRealDeck.pop();
HoldemHand myHand = new HoldemHand(myCards);
Card[] theirCards = new Card[2];
theirCards[0] = thisIsTheRealDeck.pop();
theirCards[1] = thisIsTheRealDeck.pop();
HoldemHand theirHand = new HoldemHand(theirCards);
PokerHand myBestHand = myHand.getBestPossibleHand(sharedCards);
ArrayList<Card> newDeck = GetPokerDeck();
ArrayList<Card> cardsToRemove = new ArrayList<Card>();
for ( int index = 0; index < newDeck.size(); index++ )
{
Card card = newDeck.get(index);
if ( card.equals(myCards[0] ) || card.equals(myCards[1] ) )
{
cardsToRemove.add(card);
}
else
{
for ( int sharedCardIndex = 0; sharedCardIndex < sharedCards.length; sharedCardIndex++ )
{
if ( card.equals(sharedCards[sharedCardIndex] ) )
{
cardsToRemove.add(card);
}
}
}
}
newDeck.removeAll(cardsToRemove);
ArrayList<PokerHand> bestPossibleOtherHands = new ArrayList<PokerHand>();
for ( int firstCardIndex = 0; firstCardIndex < 44; firstCardIndex++ )
{
for ( int secondCardIndex = firstCardIndex + 1; secondCardIndex < 45; secondCardIndex++)
{
bestPossibleOtherHands.add(
new HoldemHand(
new Card[] {
newDeck.get(firstCardIndex), newDeck.get(secondCardIndex)
})
.getBestPossibleHand(sharedCards));
}
}
double wins = 0;
double ties = 0;
double losses = 0;
for ( PokerHand other : bestPossibleOtherHands )
{
int result = myBestHand.compareTo( other );
if ( result > 0 )
{
wins++;
}
else if ( result < 0 )
{
losses++;
}
else
{
ties++;
}
}
System.out.println("My Cards: " + myCards[0] + " " + myCards[1] );
System.out.println("Shared Cards: " + sharedCards[0]
+ " " + sharedCards[1]
+ " " + sharedCards[2]
+ " " + sharedCards[3]
+ " " + sharedCards[4] );
System.out.println("Best possible hand: " + myBestHand.toString() );
System.out.println("Best hand rank: "+ myBestHand.getHandRank() );
System.out.println("Your change of winning is: " + wins / 990 );
System.out.println("Your change of lossing is: " + losses / 990 );
System.out.println("Your change of tieing is: " + ties / 990 );
}
private static ArrayList<Card> GetPokerDeck()
{
ArrayList<Card> deck = new ArrayList<Card>();
for ( int face = 2; face <= Face.ACE; face++ )
{
deck.add( new Card( Suit.SPADES, face ) );
}
for ( int face = 2; face <= Face.ACE; face++ )
{
deck.add( new Card( Suit.HEARTS, face ) );
}
for ( int face = 2; face <= Face.ACE; face++ )
{
deck.add( new Card( Suit.CLUBS, face ) );
}
for ( int face = 2; face <= Face.ACE; face++ )
{
deck.add( new Card( Suit.DIAMONDS, face ) );
}
return deck;
}
} | mit |
ThiagoNP/jaimito | lib/generators/jaimito/templates/mailer_seed.rb | 671 | ActiveRecord::Base.transaction do
MailTemplate.create!(
subject: 'Welcome [[User - Name]]!',
body: %Q(
<b>Welcome [[User - Name]]</b> to our platform!
<br>
<a href='example'>Click here</a> if you don't wish to receive emails.
),
mailer_name: 'sample_mailer',
method_name: 'welcome_mail',
locale: :en
)
MailTemplate.create!(
subject: 'Bem vindo [[Usuário - Nome]]!',
body: %Q(
<b>Bem vindo [[Usuário - Nome]]</b>!
<br>
<a href='example'>Clique aqui</a> para cancelar o recebimento de emails.
),
mailer_name: 'sample_mailer',
method_name: 'welcome_mail',
locale: :'pt-br'
)
end
| mit |
ageweke/parcels | lib/parcels/fortitude/widget_engine.rb | 668 | require 'tilt'
module Parcels
module Fortitude
class WidgetEngine < Tilt::Template
self.default_mime_type = 'text/css'
def self.engine_initialized?
true
end
def initialize_engine
require_template_library 'fortitude'
end
def prepare
end
def evaluate(context, locals, &block)
parcels_environment = context.environment.parcels
widget_class = parcels_environment.widget_class_from_file(context.pathname)
if widget_class
widget_class._parcels_widget_class_inline_css(parcels_environment, context)
else
""
end
end
end
end
end
| mit |
mglezh/visual-studio-2012 | WebAppOperaciones/WebAppOperaciones/Contact.aspx.cs | 308 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebAppOperaciones
{
public partial class Contact : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | mit |
jbt00000/RevolutionaryStuff | src/RevolutionaryStuff.Core/RandomHelpers.cs | 474 | namespace RevolutionaryStuff.Core;
public static class RandomHelpers
{
public static string NextString(this Random r, int characterCount, string characterSet)
{
var s = "";
for (int z = 0; z < characterCount; ++z)
{
var i = r.Next(characterSet.Length);
var ch = characterSet[i];
s += ch;
}
return s;
}
public static bool NextBoolean(this Random r)
=> r.Next(2) == 1;
}
| mit |
exercism/x-api | test/v1_helper.rb | 212 | require_relative 'test_helper'
require 'rack/test'
require 'approvals'
require 'yaml'
require 'xapi'
require_relative '../api/v1'
Approvals.configure do |c|
c.approvals_path = './test/fixtures/approvals/'
end
| mit |
jonathan-beard/Raft | ASTNodes/LOROp.cpp | 300 | /**
* LOROp.cpp -
* @author: Jonathan Beard
* @version: Tue Feb 11 12:51:41 2014
*/
#include "LOROp.hpp"
using namespace Node;
LOROp::LOROp() : CondOp( "LOROp" )
{
class_tree.addRelation( typeid( Node::CondOp ).hash_code(),
typeid( Node::LOROp ).hash_code() );
}
| mit |
erikzhouxin/CSharpSolution | EZWebTemplate/Areas/Help/Models/EnumValueDescription.cs | 241 | namespace EZOper.TechTester.EZWebTemplate.Areas.Help
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | mit |
daryl314/markdown-browser | pycmark/taggedtext/TaggedCmarkDocument.py | 5901 | from . import TaggedTextDocument as TTD
class TaggedTextDocument(TTD.TaggedTextDocument):
"""
Class representing a document as a list of TaggedTextBlocks
"""
@classmethod
def fromAST(cls, ast, width=80, **kwargs):
"""Parse an AST representation of a markdown document into a TaggedTextDocuent"""
doc = cls()
for node in ast.nodes:
for block in cls.wrapAstNode(node, width=width, **kwargs):
doc.append(block)
return doc
@classmethod
def wrapAstNode(cls, node, width=80, **kwargs):
def wrap(n):
return TaggedTextBlock(width=width, **kwargs).fromBlock(n)
if node._tag == 'block_quote':
wrapped = [wrap(qb).prependTag('block_quote') for qb in node.children]
else:
wrapped = [wrap(node)]
for wblock in wrapped:
for row in wblock.rows:
row.padTo(width)
return wrapped
class TaggedTextBlock(TTD.TaggedTextBlock):
"""
Class representing a block of TaggedText as a list of TaggedTextList rows
"""
def __init__(self, rows=None, width=80, ttclass=None, ttlclass=None, withUnicode=True):
self.width = width
self.rows = [] if rows is None else rows
self.TT = TaggedText if ttclass is None else ttclass
self.TTL = TaggedTextList if ttlclass is None else ttlclass
self.withUnicode = withUnicode
def fromBlocks(self, blocks):
for block in blocks:
self.fromBlock(block)
return self
def fromBlock(self, block):
##### block-level containers #####
if block._tag in {'paragraph', 'heading', 'item'}: # no line breaks
if block._tag == 'heading' and block.Level == 1:
wrapped = self.TTL.fromContainer(block, self.TT, ['heading1']).wrapTo(self.width)
else:
wrapped = self.TTL.fromContainer(block, self.TT).wrapTo(self.width)
for row in wrapped:
self.rows.append(row)
##### block-level leaf nodes ####
elif block._tag in {'code_block', 'html_block'}:
for row in block.Text.rstrip().split('\n'):
self.rows.append(self.TTL.fromText(row, self.TT, [block._tag]))
elif block._tag == 'thematic_break':
self.rows.append(self.TTL.fromText((u'\u2500' if self.withUnicode else '-') * self.width, self.TT, [block._tag]))
elif block._tag == 'table':
rowData = [[self.TTL.fromContainer(td, self.TT, [tr._tag]) for td in tr.children] for tr in block.children]
colWidth = [max([len(r[i]) for r in rowData]) for i in range(max(map(len, rowData)))]
rowData = [
self.TTL.join(
[td.padTo(w) for td, w in zip(tr, colWidth)],
u'\u2502' if self.withUnicode else '|',
self.TT)
for tr in rowData]
self.rows += rowData[:1] + [
self.TTL.fromText((u'\u253c' if self.withUnicode else '|').join(
[(u'\u2500' if self.withUnicode else '-') * x for x in colWidth]
), self.TT)
] + rowData[1:]
elif block._tag == 'list':
if block.Type == 'Bullet':
listHeader = lambda i: (u'\u203a' + ' ' if self.withUnicode else '* ')
elif block.Type == 'Ordered':
blockStart = block.Start
listHeader = lambda i: '%{}d. '.format(len(str(len(block.children)+blockStart-1))) % (i+blockStart)
else:
raise RuntimeError("Unrecognized list type: " + block.Type)
for i,li in enumerate(block.children):
subBlock = self.__class__(
width=self.width-2, ttclass=self.TT, ttlclass=self.TTL, withUnicode=self.withUnicode
).fromBlocks(li.children)
self.rows.append(subBlock.rows[0].pushLeft(listHeader(i),['list']))
self.rows += [row.pushLeft(' '*len(listHeader(i)),['list']) for row in subBlock.rows[1:]]
##### something unrecognized #####
else:
raise RuntimeError("Unrecognized container: " + block.__repr__())
##### return self for chaining #####
return self
class TaggedTextList(TTD.TaggedTextList):
"""
Class representing a list of TaggedText objects
"""
@classmethod
def fromContainer(cls, container, TT, tagStack=[], **kwargs):
obj = cls(TT)
obj.tt_list = obj.processContainer(container, tagStack[:]+[container._tag], **kwargs)
return obj
def processContainer(self, container, tagStack):
out = []
for child in container.children:
newstack = tagStack[:] + [child._tag]
if child._tag == 'softbreak':
out += [self.TT(' ', newstack)]
elif child._tag == 'linebreak':
out += [self.TT('\n', newstack)]
elif 'Text' in child._fields and len(child.children) == 0:
out.append(self.TT(child.Text, newstack))
elif 'Text' not in child._fields and len(child.children) > 0:
out += self.processContainer(child, newstack)
else:
raise RuntimeError("Unanticipated child container: {}".format(container))
return out
class TaggedText(TTD.TaggedText):
"""
Class representing a block with text with styles applied
"""
def simplifyStack(self):
"""Simplify tag stack to a single tag"""
for tag in self.tags:
if tag in {'code_block','block_quote','heading1','heading','table_header','latex_inline','latex_block'}:
return tag
for tag in reversed(self.tags):
if tag in {'emph','strong','strikethrough','code','image','link'}:
return tag
return 'body' | mit |
Paybook/sync-java | src/main/java/com/paybook/sync/User.java | 5848 | package com.paybook.sync;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Users are logical segmentations for end-users.
* It's a best practice to register users in order to have their information grouped and have control on both ends.
* It is required to have at least one user registered to create credentials.
* @author Mateo
* @version 1.0
* @since 2016-12-01
*/
public class User extends Paybook{
public String id_user;
public String id_external;
public String name;
public String dt_create;
public String dt_modify;
/**
* @param name User name.
* @param id_user User ID, this is the actual subtoken that is needed in other resources.
* @param id_external External ID, this field can be null and be used to keep track of that user with an external ID.
* @throws Error Error class
*/
public User(String name,String id_user,String id_external) throws Error{
List<User> users = null;
User user = null;
JSONObject response = null;
String responseInString = null;
try {
HashMap<String, Object> data = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();
data.put("api_key", Paybook.api_key);
if(StringUtils.isNotBlank(name) && StringUtils.isBlank(id_user)){
data.put("name", name);
if(StringUtils.isNotBlank(id_external)){
data.put("id_external", id_external);
}
response = call("users/", Method.POST, data);
responseInString = response.get("response").toString();
user = mapper.readValue(responseInString, User.class);
}else if(StringUtils.isNotBlank(id_user)){
if(StringUtils.isNotBlank(name) || StringUtils.isNotBlank(id_external)){
data.put("id_user", id_user);
if(StringUtils.isNotBlank(name)){
data.put("name", name);
}
if(StringUtils.isNotBlank(id_external)){
data.put("id_external", id_external);
}
response = call("users/"+id_user, Method.PUT, data);
responseInString = response.get("response").toString();
user = mapper.readValue(responseInString, User.class);
}else{
response = call("users/" + id_user, Method.GET, data);
responseInString = response.get("response").toString();
System.out.println(responseInString);
users = mapper.readValue(responseInString, new TypeReference<List<User>>(){});
user = users.get(0);
}
}else if(StringUtils.isNotBlank(id_external)){
data.put("id_external", id_external);
response = call("users/", Method.GET, data);
responseInString = response.get("response").toString();
users = mapper.readValue(responseInString, new TypeReference<List<User>>(){});
user = users.get(0);
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
throw new Error(500,false,e.getMessage(),null);
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
throw new Error(500,false,e.getMessage(),null);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new Error(500,false,e.getMessage(),null);
} catch (Error e) {
// TODO Auto-generated catch block
throw e;
}
this.id_user = user.id_user;
this.name = user.name;
this.id_external = user.id_external;
this.dt_create = user.dt_create;
this.dt_modify = user.dt_modify;
}//End of constructor
/**
* This method should be used for the Sync API connection in order to centralize the call to the API in just one method.
* @param name User name.
* @throws Error Error class
*/
public User(String name) throws Error{
this(name,"","");
}
/**
* This method should be used for the Sync API connection in order to centralize the call to the API in just one method.
* @param name User name.
* @param id_user User ID, this is the actual subtoken that is needed in other resources.
* @throws Error Error class
*/
public User(String name, String id_user) throws Error{
this(name,id_user,"");
}
public User() throws Error{
}
public static List<User> get(HashMap<String, Object> data) throws Error{
List<User> users = null;
try {
data.put("api_key", Paybook.api_key);
JSONObject response = call("users/", Method.GET, data);
String responseInString = response.get("response").toString();
ObjectMapper mapper = new ObjectMapper();
users = mapper.readValue(responseInString, new TypeReference<List<User>>(){});
} catch (JsonParseException e) {
// TODO Auto-generated catch block
throw new Error(500,false,e.getMessage(),null);
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
throw new Error(500,false,e.getMessage(),null);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new Error(500,false,e.getMessage(),null);
} catch (Error e) {
// TODO Auto-generated catch block
throw e;
}
return users;
}//End of get
public static List<User> get() throws Error{
HashMap<String, Object> data = new HashMap<String, Object>();
return get(data);
}
public static boolean delete(String id_user) throws Error{
try{
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("api_key", Paybook.api_key);
JSONObject response = call("users/" + id_user, Method.DELETE, data);
Boolean status = response.getBoolean("status");
return status;
}catch(Error e){
throw e;
}
}//End of delete
}
| mit |
sqlectron/sqlectron-core | src/utils.js | 2200 | import fs from 'fs';
import { homedir } from 'os';
import path from 'path';
import mkdirp from 'mkdirp';
import envPaths from 'env-paths';
import { readFile, resolveHomePathToAbsolute } from 'sqlectron-db-core/utils';
export {
createCancelablePromise,
getPort,
readFile,
resolveHomePathToAbsolute,
versionCompare,
} from 'sqlectron-db-core/utils';
let configPath = '';
export function getConfigPath() {
if (configPath) {
return configPath;
}
const configName = 'sqlectron.json';
const oldConfigPath = path.join(homedir(), `.${configName}`);
if (process.env.SQLECTRON_HOME) {
configPath = path.join(process.env.SQLECTRON_HOME, configName);
} else if (fileExistsSync(oldConfigPath)) {
configPath = oldConfigPath;
} else {
const newConfigDir = envPaths('Sqlectron', { suffix: '' }).config;
configPath = path.join(newConfigDir, configName);
}
return configPath;
}
export function fileExists(filename) {
return new Promise((resolve) => {
fs.stat(filename, (err, stats) => {
if (err) return resolve(false);
resolve(stats.isFile());
});
});
}
export function fileExistsSync(filename) {
try {
return fs.statSync(filename).isFile();
} catch (e) {
return false;
}
}
export function writeFile(filename, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, (err) => {
if (err) return reject(err);
resolve();
});
});
}
export function writeJSONFile(filename, data) {
return writeFile(filename, JSON.stringify(data, null, 2));
}
export function writeJSONFileSync(filename, data) {
return fs.writeFileSync(filename, JSON.stringify(data, null, 2));
}
export function readJSONFile(filename) {
return readFile(filename).then((data) => JSON.parse(data));
}
export function readJSONFileSync(filename) {
const filePath = resolveHomePathToAbsolute(filename);
const data = fs.readFileSync(path.resolve(filePath), { encoding: 'utf-8' });
return JSON.parse(data);
}
export function createParentDirectory(filename) {
return mkdirp(path.dirname(filename));
}
export function createParentDirectorySync(filename) {
mkdirp.sync(path.dirname(filename));
}
| mit |
summera/retscli | test/display_adapter_test.rb | 12161 | require 'test_helper'
describe Retscli::DisplayAdapter do
let(:dummy_client) do
Class.new do
def login; end
def logout; end
def find(quantity, params={})
if params[:count] == 2
2
elsif params[:query] == '(ListingID=0+)'
[{
'heading1' => 'value1',
'heading2' => 'value2'
}, {
'heading1' => 'value1',
'heading2' => 'value2'
}]
elsif params[:query] == '(ListingID=100+)'
[{
'heading1' => 'value1',
'heading2' => ''
}]
else
[]
end
end
def metadata
Rets::Metadata::Root.new(nil, RETS_METADATA)
end
end.new
end
subject { Retscli::DisplayAdapter.new(dummy_client) }
describe '#resources' do
it 'renders resources' do
resources = "Resource: Agent (Key Field: rets_agt_id)"\
"\nResource: Office (Key Field: DO_OFFICE_ID)"\
"\nResource: Property (Key Field: MST_MLS_NUMBER)"\
"\nResource: OpenHouse (Key Field: rets_oh_id)"
assert_equal resources, subject.resources
end
end
describe '#classes' do
let (:classes) do
"Class: Resd"\
"\n Visible Name: Residential"\
"\n Description : Residential"\
"\nClass: ResLand"\
"\n Visible Name: Residential_Land"\
"\n Description : Residential_Land"\
"\nClass: CmmlSales"\
"\n Visible Name: Commercial_Sales"\
"\n Description : Commercial_Sales"\
"\nClass: CmmlLand"\
"\n Visible Name: Commercial_Land"\
"\n Description : Commercial_Land"\
"\nClass: ResLse"\
"\n Visible Name: Residential_Lease"\
"\n Description : Residential_Lease"\
"\nClass: CmmlLse"\
"\n Visible Name: Commercial_Lease"\
"\n Description : Commercial_Lease"
end
it 'renders classes' do
assert_equal classes, subject.classes('Property')
end
it 'is case independent' do
assert_equal classes, subject.classes('proPeRty')
end
it 'returns resource does not exist message' do
assert_equal "\e[31mDoesNotExist resource does not exist\e[0m", subject.classes('DoesNotExist')
end
end
describe '#objects' do
it 'renders objects' do
objects = "Object: image"\
"\n MimeType: "\
"\n Description: Property_Photo"
assert_equal objects, subject.objects('property')
end
end
describe '#tables' do
it 'renders open house lookup table' do
tables = "LookupTable: rets_oh_activity_type"\
"\n Resource: OpenHouse"\
"\n ShortName: ActType"\
"\n LongName: Activity Type"\
"\n StandardName: "\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: "\
"\n Types:"\
"\n Open -> 0"\
"\n Private -> 1"
assert_equal tables, subject.tables('OpenHouse', 'OpenHouse')
end
it 'renders property tables for CmmlLand' do
tables = "Table: Address"\
"\n Resource: Property"\
"\n ShortName: Str Nm"\
"\n LongName: Street Name"\
"\n StandardName: StreetName"\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: "
assert_equal tables, subject.tables('Property', 'CmmlLand')
end
it 'returns resource does not exist message' do
assert_equal "\e[31mDoesNotExist resource does not exist\e[0m", subject.tables('DoesNotExist', '')
end
it 'returns class does not exist message' do
assert_equal "\e[31mDoesNotExist class does not exist\e[0m", subject.tables('Property', 'DoesNotExist')
end
end
describe '#timezone_offset' do
it 'returns rets server timezone offset' do
assert_equal "-07:00", subject.timezone_offset
end
describe 'without specified offset' do
let(:dummy_client) do
Class.new do
def login; end
def logout; end
def metadata
meta_with_no_tz = {}
meta_with_no_tz['SYSTEM'] = RETS_METADATA['SYSTEM'].dup
meta_with_no_tz['SYSTEM'].gsub!('TimeZoneOffset="-07:00"', '')
Rets::Metadata::Root.new(nil, meta_with_no_tz)
end
end.new
end
it 'returns offset not specified message' do
assert_equal "\e[31mNo offset specified\e[0m", subject.timezone_offset
end
end
end
describe '#metadata' do
it 'renders full metadata' do
assert_equal RENDERED_METDATA, subject.metadata
end
end
describe "#search_metadata" do
it 'searches long name of metadata tables' do
result = "Resource: OpenHouse (Key Field: rets_oh_id)"\
"\n Class: OpenHouse"\
"\n Visible Name: OpenHouse"\
"\n Description : Open House"\
"\n LookupTable: rets_oh_\e[31m\e[47mactivity\e[0m_type"\
"\n Resource: OpenHouse"\
"\n ShortName: ActType"\
"\n LongName: \e[31m\e[47mActivity\e[0m Type"\
"\n StandardName: "\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: "\
"\n Types:"\
"\n Open -> 0"\
"\n Private -> 1\n"
assert_equal result, subject.search_metadata('activity')
end
it 'searches system name of metadata tables' do
result = "Resource: Property (Key Field: MST_MLS_NUMBER)"\
"\n Class: CmmlLand"\
"\n Visible Name: Commercial_Land"\
"\n Description : Commercial_Land"\
"\n Table: \e[31m\e[47mAddress\e[0m"\
"\n Resource: Property"\
"\n ShortName: Str Nm"\
"\n LongName: Street Name"\
"\n StandardName: StreetName"\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: \n"
assert_equal result, subject.search_metadata('address')
end
it 'searches short name of metadata tables' do
result = "Resource: Property (Key Field: MST_MLS_NUMBER)"\
"\n Class: CmmlLand"\
"\n Visible Name: Commercial_Land"\
"\n Description : Commercial_Land"\
"\n Table: Address"\
"\n Resource: Property"\
"\n ShortName: \e[31m\e[47mStr\e[0m Nm"\
"\n LongName: \e[31m\e[47mStr\e[0meet Name"\
"\n StandardName: \e[31m\e[47mStr\e[0meetName"\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: \n"
assert_equal result, subject.search_metadata('str')
end
it 'searches standard name of metdata tables' do
result = "Resource: Property (Key Field: MST_MLS_NUMBER)"\
"\n Class: CmmlLand"\
"\n Visible Name: Commercial_Land"\
"\n Description : Commercial_Land"\
"\n Table: Address"\
"\n Resource: Property"\
"\n ShortName: Str Nm"\
"\n LongName: Street Name"\
"\n StandardName: \e[31m\e[47mStreetName\e[0m"\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: \n"
assert_equal result, subject.search_metadata('streetname')
end
describe 'with resource filter' do
it 'returns no results' do
assert_equal '', subject.search_metadata('streetname', :resources => ['openhouse'])
end
it 'returns results from filtered resources' do
result = "Resource: Property (Key Field: MST_MLS_NUMBER)"\
"\n Class: CmmlLand"\
"\n Visible Name: Commercial_Land"\
"\n Description : Commercial_Land"\
"\n Table: Address"\
"\n Resource: Property"\
"\n ShortName: Str Nm"\
"\n LongName: Street Name"\
"\n StandardName: \e[31m\e[47mStreetName\e[0m"\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: \n"
assert_equal result, subject.search_metadata('streetname', :resources => ['property'])
end
end
describe 'with class filter' do
it 'returns no results' do
assert_equal '', subject.search_metadata('streetname', :classes => ['resland'])
end
it 'returns results from filtered classes' do
result = "Resource: Property (Key Field: MST_MLS_NUMBER)"\
"\n Class: CmmlLand"\
"\n Visible Name: Commercial_Land"\
"\n Description : Commercial_Land"\
"\n Table: Address"\
"\n Resource: Property"\
"\n ShortName: Str Nm"\
"\n LongName: Street Name"\
"\n StandardName: \e[31m\e[47mStreetName\e[0m"\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: \n"
assert_equal result, subject.search_metadata('streetname', :classes => ['cmmlland'])
end
end
describe 'with resource and class filters' do
it 'returns no results when resource matches but class does not' do
assert_equal '', subject.search_metadata('streetname', :resources => ['property'], :classes => ['cool'])
end
it 'returns no results when class matches but resource does not' do
assert_equal '', subject.search_metadata('streetname', :resources => ['awesome'], :classes => ['cmmlland'])
end
it 'returns results from filtered resources and classes' do
result = "Resource: Property (Key Field: MST_MLS_NUMBER)"\
"\n Class: CmmlLand"\
"\n Visible Name: Commercial_Land"\
"\n Description : Commercial_Land"\
"\n Table: Address"\
"\n Resource: Property"\
"\n ShortName: Str Nm"\
"\n LongName: Street Name"\
"\n StandardName: \e[31m\e[47mStreetName\e[0m"\
"\n Units: "\
"\n Searchable: 1"\
"\n Required: \n"
assert_equal result, subject.search_metadata('streetname', :resources => ['property'], :classes => ['cmmlland'])
end
end
end
describe '#search' do
it 'returns results table with correct headings' do
result = subject.search('property', 'res', '(ListingID=0+)')
headings = result.headings.map{ |row| row.cells.map{ |cell| cell.value } }
assert_equal [['heading1', 'heading2']], headings
end
it 'returns results table with correct values' do
result = subject.search('property', 'res', '(ListingID=0+)')
values = result.rows.map{ |row| row.cells.map{ |cell| cell.value } }
assert_equal [['value1', 'value2'],['value1', 'value2']], values
end
it 'returns table with no results' do
result = subject.search('property', 'res', '')
values = result.rows.map{ |row| row.cells.map{ |cell| cell.value } }
assert_equal [[Retscli::DisplayAdapter::NO_RESULTS]], values
end
it 'returns table with number of results' do
result = subject.search('property', 'res', '(ListingID=0+)', :count => true)
values = result.rows.map{ |row| row.cells.map{ |cell| cell.value } }
assert_equal [[2]], values
end
it 'replaces empty strings with empty value' do
result = subject.search('property', 'res', '(ListingID=100+)')
values = result.rows.map{ |row| row.cells.map{ |cell| cell.value } }
assert_equal [['value1', Retscli::DisplayAdapter::EMPTY_VALUE]], values
end
end
describe '#page' do
it 'uses PAGER environment variable' do
ENV['PAGER'] = 'less'
mock = MiniTest::Mock.new
mock.expect(:call, nil, ['less', 'w'])
IO.stub(:popen, mock, StringIO.new) do
subject.page('')
end
mock.verify
end
end
describe '#open_in_editor' do
it 'uses EDITOR environment variable by default' do
ENV['EDITOR'] = 'vim'
mock = MiniTest::Mock.new
mock.expect(:call, nil, ['vim', 'text'])
subject.stub(:open_tempfile_with_content, mock) do
subject.open_in_editor('text')
end
mock.verify
end
it 'uses nano when EDITOR environment variable is not set' do
ENV.delete('EDITOR')
mock = MiniTest::Mock.new
mock.expect(:call, nil, ['nano', 'text'])
subject.stub(:open_tempfile_with_content, mock) do
subject.open_in_editor('text')
end
mock.verify
end
end
end
| mit |
ygorkrs/SYSGYM | SYSGYM/Classes/Classe_Aluno.cs | 935 | using System.Windows.Forms;
public class Classe_Aluno : Classe_Pessoa
{
private bool ativo;
public bool Ativo
{
get { return ativo; }
set { ativo = Ativo; }
}
private long matricula;
public long Matricula
{
get { return matricula; }
set { matricula = Matricula; }
}
private Classe_Mensalidade mensalidade;
public Classe_Mensalidade Mesnsalidade
{
get { return mensalidade; }
set { mensalidade = Mesnsalidade; }
}
public void SairAcademia()
{
if (Ativo == false)
{
MessageBox.Show("Não está dentro da Academia!");
}
else
Ativo = false;
}
public void EntraAcademia()
{
if (Ativo == true)
{
MessageBox.Show("Já está dentro da Academia!");
}
else
Ativo = true;
}
}
| mit |
bittisiirto/viitenumero | lib/viitenumero/viite.rb | 742 | require 'active_model'
module Viitenumero
class Viite
include ActiveModel::Validations
attr_reader :number
def initialize(s)
if FIViite.valid?(s)
@number = FIViite.new(s)
elsif RFViite.valid?(s)
@number = RFViite.new(s)
else
@number = FIViite.new(s)
end
end
def rf
number.is_a?(RFViite) ? number : number.to_rf
end
def fi
number.is_a?(FIViite) ? number : number.to_fi
end
def paper_format
number.paper_format
end
def machine_format
number.machine_format
end
def valid?
number.valid?
end
def self.valid?(s)
Viite.new(s).valid?
end
def to_s
machine_format
end
end
end
| mit |
Adar/dacato | src/main/java/co/ecso/dacato/config/ApplicationConfig.java | 1370 | package co.ecso.dacato.config;
import co.ecso.dacato.connection.ConnectionPool;
import java.sql.Connection;
import java.util.concurrent.ExecutorService;
/**
* ApplicationConfig.
*
* @author Christian Scharmach ([email protected])
* @since 25.08.16
*/
public interface ApplicationConfig {
/**
* Database Pool name.
*
* @return Database pool name.
*/
String databasePoolName();
/**
* Database minimum pool size.
*
* @return Minimum pool.
*/
@SuppressWarnings("SameReturnValue")
int databasePoolMin();
/**
* Database maximum pool size.
*
* @return Maximum pool.
*/
int databasePoolMax();
/**
* Pool max size.
*
* @return Maximum pool size.
*/
int databasePoolMaxSize();
/**
* Database pool/connection idle timeout.
*
* @return Idle timeout in milliseconds.
*/
long databasePoolIdleTimeout();
/**
* Database connection string.
*
* @return Database connection string.
*/
String connectionString();
/**
* Thread pool to use for database queries.
*
* @return Thread pool.
*/
ExecutorService threadPool();
/**
* Database connection pool to use.
*
* @return Database connection pool.
*/
ConnectionPool<Connection> databaseConnectionPool();
}
| mit |
giggals/Software-University | Exercises-Defining Classes/10 CarSalesman/Program.cs | 4644 | using System;
using System.Linq;
class Program
{
static void Main()
{
char[,] matrix = new char[8, 8];
ReadMatrix(matrix);
while (true)
{
string input = Console.ReadLine();
if (input == "END")
{
break;
}
char pieceType = input[0];
int currentPositionRow = input[1] - '0';
int currentPositionCol = input[2] - '0';
int nextPositionRow = input[4] - '0';
int nextPositionCol = input[5] - '0';
if (matrix[currentPositionRow, currentPositionCol] != pieceType)
{
Console.WriteLine("There is no such a piece!");
continue;
}
if (CheckIsMoveValid(matrix, new int[] { currentPositionRow, currentPositionCol }, new int[] { nextPositionRow, nextPositionCol }) == false)
{
Console.WriteLine("Invalid move!");
continue;
}
if (nextPositionRow >= matrix.GetLength(0) || nextPositionCol >= matrix.GetLength(1) || nextPositionRow < 0 || nextPositionCol < 0)
{
Console.WriteLine("Move go out of board!");
continue;
}
MovePiece(matrix, new int[] { currentPositionRow, currentPositionCol }, new int[] { nextPositionRow, nextPositionCol });
}
}
static void ReadMatrix(char[,] matrix)
{
for (int row = 0; row < matrix.GetLength(0); row++)
{
char[] input = Console.ReadLine()
.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(char.Parse)
.ToArray();
for (int col = 0; col < matrix.GetLength(1); col++)
{
matrix[row, col] = input[col];
}
}
}
static void MovePiece(char[,] matrix, int[] currentPosition, int[] nextPosition)
{
char piece = matrix[currentPosition[0], currentPosition[1]];
matrix[currentPosition[0], currentPosition[1]] = 'x';
matrix[nextPosition[0], nextPosition[1]] = piece;
}
static bool CheckIsMoveValid(char[,] matrix, int[] currentPosition, int[] nextPosition)
{
bool isValid = false;
char piece = matrix[currentPosition[0], currentPosition[1]];
if (piece == 'K')
{
if (new int[] { currentPosition[0], currentPosition[1] + 1 }.SequenceEqual(nextPosition) ||
new int[] { currentPosition[0] + 1, currentPosition[1] + 1 }.SequenceEqual(nextPosition) ||
new int[] { currentPosition[0] + 1, currentPosition[1] }.SequenceEqual(nextPosition) ||
new int[] { currentPosition[0], currentPosition[1] - 1 }.SequenceEqual(nextPosition) ||
new int[] { currentPosition[0] - 1, currentPosition[1] - 1 }.SequenceEqual(nextPosition) ||
new int[] { currentPosition[0] - 1, currentPosition[1] }.SequenceEqual(nextPosition) ||
new int[] { currentPosition[0] - 1, currentPosition[1] + 1 }.SequenceEqual(nextPosition) ||
new int[] { currentPosition[0] + 1, currentPosition[1] - 1 }.SequenceEqual(nextPosition))
{
isValid = true;
}
}
else if (piece == 'R')
{
if (currentPosition[0] == nextPosition[0] || currentPosition[1] == nextPosition[1])
{
isValid = true;
}
}
else if (piece == 'B')
{
int rowsDiference = Math.Abs(currentPosition[0] - nextPosition[0]);
int colsDiference = Math.Abs(currentPosition[1] - nextPosition[1]);
if (rowsDiference == colsDiference)
{
isValid = true;
}
}
else if (piece == 'P')
{
if (nextPosition[0] - currentPosition[0] == -1 && currentPosition[1] == nextPosition[1])
{
isValid = true;
}
}
else if (piece == 'Q')
{
if (currentPosition[0] == nextPosition[0] || currentPosition[1] == nextPosition[1])
{
isValid = true;
}
else
{
int rowsDiference = Math.Abs(currentPosition[0] - nextPosition[0]);
int colsDiference = Math.Abs(currentPosition[1] - nextPosition[1]);
if (rowsDiference == colsDiference)
{
isValid = true;
}
}
}
return isValid;
}
} | mit |
LampardNguyen/fibonacci | service-worker.js | 4287 | // tick this to make the cache invalidate and update
/*const CACHE_VERSION = 1;
const CURRENT_CACHES = {
'read-through': 'read-through-cache-v' + CACHE_VERSION
};
self.addEventListener('activate', (event) => {
// Delete all caches that aren't named in CURRENT_CACHES.
// While there is only one cache in this example, the same logic will handle the case where
// there are multiple versioned caches.
const expectedCacheNames = Object.keys(CURRENT_CACHES).map((key) => {
return CURRENT_CACHES[key];
});
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (expectedCacheNames.indexOf(cacheName) === -1) {
// If this cache name isn't present in the array of "expected" cache names, then delete it.
console.log('Deleting out of date cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
// This sample illustrates an aggressive approach to caching, in which every valid response is
// cached and every request is first checked against the cache.
// This may not be an appropriate approach if your web application makes requests for
// arbitrary URLs as part of its normal operation (e.g. a RSS client or a news aggregator),
// as the cache could end up containing large responses that might not end up ever being accessed.
// Other approaches, like selectively caching based on response headers or only caching
// responses served from a specific domain, might be more appropriate for those use cases.
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.open(CURRENT_CACHES['read-through']).then((cache) => {
return cache.match(event.request).then((response) => {
if (response) {
// If there is an entry in the cache for event.request, then response will be defined
// and we can just return it.
return response;
}
// Otherwise, if there is no entry in the cache for event.request, response will be
// undefined, and we need to fetch() the resource.
console.log(' No response for %s found in cache. ' +
'About to fetch from network...', event.request.url);
// We call .clone() on the request since we might use it in the call to cache.put() later on.
// Both fetch() and cache.put() "consume" the request, so we need to make a copy.
// (see https://fetch.spec.whatwg.org/#dom-request-clone)
return fetch(event.request.clone()).then((response) => {
// Optional: add in extra conditions here, e.g. response.type == 'basic' to only cache
// responses from the same domain. See https://fetch.spec.whatwg.org/#concept-response-type
if (response.status < 400 && response.type === 'basic') {
// We need to call .clone() on the response object to save a copy of it to the cache.
// (https://fetch.spec.whatwg.org/#dom-request-clone)
cache.put(event.request, response.clone());
}
// Return the original response object, which will be used to fulfill the resource request.
return response;
});
}).catch((error) => {
// This catch() will handle exceptions that arise from the match() or fetch() operations.
// Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
// It will return a normal response object that has the appropriate error code set.
console.error(' Read-through caching failed:', error);
throw error;
});
})
);
});*/
self.addEventListener('notificationclick', function(event) {
// console.log('[Service Worker] Notification click Received.', event.notification);
event.notification.close();
// console.log(window);
// event.waitUntil(
// );
});
| mit |
haggi/OpenMaya | src/mayaToThea/src/Thea/TheaWorld.cpp | 886 | #include "world.h"
#include "utilities/logging.h"
#include "../mtth_common/mtth_swatchRenderer.h"
#include "mayaSceneFactory.h"
namespace MayaTo{
void MayaToWorld::cleanUp()
{
mtth_SwatchRendererInterface::cleanUpStaticData();
}
void MayaToWorld::initialize()
{
mtth_SwatchRendererInterface::initializeStaticData();
}
void MayaToWorld::afterOpenScene()
{
Logging::debug("MayaToWorld::afterOpenScene");
}
void MayaToWorld::afterNewScene()
{
Logging::debug("MayaToWorld::afterNewScene");
}
void MayaToWorld::callAfterOpenCallback(void *)
{
getWorldPtr()->afterOpenScene();
}
void MayaToWorld::callAfterNewCallback(void *)
{
getWorldPtr()->afterNewScene();
}
void MayaToWorld::cleanUpAfterRender()
{
// after a normal rendering we do not need the maya scene data any more
// remove it to save memory
MayaSceneFactory().deleteMayaScene();
}
} | mit |
filepress/proofOfConcept | generate.js | 5950 | /*
Generate static HTML pages from markdwon.
*/
/**
* @typedef {Object} mdInfos
*
*/
const start = Date.now()
process.on('exit', logTime)
const path = require('path')
const fs = require('fs')
const Stream = require('stream')
const _ = require('highland')
const YAML = require('yamljs')
const hljs = require('highlight.js')
const md = require('markdown-it')({
html: true,
linkify: true,
typographer: true,
highlight: function(str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre class="hljs"><code>' +
hljs.highlight(lang, str, true).value +
'</code></pre>';
} catch (__) {}
}
return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
}
})
//Get all the md files.
let sourceFolder = path.join(__dirname, 'source')
generateMardownStream(sourceFolder)
.map(filePath => ({
filePath
}))
.flatMap(addMarkdown)
.map(parseFrontmatter)
.map(generateHTML)
.each(saveToHTML)
/**
* Saved an mdInfos html to a file.
* @param {mdInfos} obj - File that the html should be changed for
*/
function saveToHTML(obj) {
fs.writeFile(`public/${obj.config.title.replace(/\s/g,'-')}.html`, obj.html, () => {
})
}
/**
* Converts markdown to HTML.
* @param {mdInfos} obj - The infos to work with
* @return {mdInfos} - With added .html field
*/
function generateHTML(obj) {
const markdown = `# ${obj.config.title}\n\n${obj.body}`
obj.html = md.render(markdown)
return obj
}
function logTime() {
const end = Date.now()
let dur = (end - start) / 1000
console.log('Ran for:', dur);
}
/**
* Parses the given frontmatter of a markdown file.
* @param {mdInfos} obj - mdInfos object to work on
*/
function parseFrontmatter(obj) {
obj.config = parseYMLFrontmatter(obj.config)
return obj
}
/**
* Parse frontmatter in YML format.
* @param {String} header - The Frontmatter to parse
*/
function parseYMLFrontmatter(header) {
let headerYML = header.replace(/^.*\n/, '')
return YAML.parse(headerYML)
}
/**
* Adds config and body of the markdwon file to mdInfos object.
* @param {mdInfos} obj - The Infos to work on
*/
function addMarkdown(obj) {
return _(function(push, next) {
readMarkdown(obj.filePath)
.map(markdown => ({
config: onlyFrontmatter(markdown),
body: removeFrontmatter(markdown)
}))
.toCallback((err, result) => {
obj.config = result.config
obj.body = result.body
push(err, obj)
push(null, _.nil)
})
})
}
/**
* Reads a given markdwon file and emits it's content in an event.
* @param {String} filePath - Path to markdwon file to read
* @return {Stream} - A stream with the read file
*/
function readMarkdown(filePath) {
return _(function(push, next) {
fs.readFile(filePath, 'utf8', function(err, data) {
push(err, data)
push(null, _.nil)
});
});
};
/**
* Extracts the frontmatter from a file.
* Frontmatter should be enclosed in '---'.
* Will keep the first line but remove the closing '---'.
* @param {String} file - The file to work on
* @return {String} - The frontmatter of the given file
*/
function onlyFrontmatter(file) {
return file.split('\n')
.reduce((infos, line) => {
if (infos.markers >= 2) return infos
if (/^---/.test(line)) {
infos.markers += 1
if (infos.markers === 1) infos.header.push(line)
} else {
infos.header.push(line)
}
return infos
}, {
markers: 0,
header: []
})
.header.join('\n')
}
/**
* Removes the frontmatter from a markdown file.
* Frontmatter assumed to be marked with [--- somthing ---].
* @param {String} file - Markdown file to work on
* @return {String} - The body of the given Markdown file
*/
function removeFrontmatter(file) {
//Replace the frontmatter. [\s\S] matches any character including whitespaces.
file = file.replace(/---[\s\S]*---/, '')
return file
}
/**
* Creates a stream of markdown files in a directory.
* Looks into subdirectories recursively.
* @param {String} dir - Directory to start from
* @return {Stream} - A highland stream with the found files
*/
function generateMardownStream(dir) {
return _(function(push, next) {
walk(dir, /\.md$/, push, () => {
push(null, _.nil)
})
});
}
/**
* Walks a filestructure starting from a given root and pushes all found
* files onto a given stream. Compares all files against a filter.
* @param {String} dir - Root directory
* @param {RegEx} filter - RegEx to test found files against
* @param {Function} push - Push function for a highland stream
* @param {Function} done - Callback will be called with (err, foundFiles)
*/
function walk(dir, filter, push, done) {
fs.readdir(dir, function(err, list) {
if (err) return done(err)
var pending = list.length
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file)
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, filter, push, function(err, res) {
results = results.concat(res)
if (!--pending) done()
});
} else {
if (filter.test(file)) {
push(null, file)
}
if (!--pending) done()
}
})
})
})
}
| mit |
teco-kit/ARDevKitPlayer_Android | app/src/main/java/teco/ardevkit/andardevkitplayer/PausableARELActivity.java | 22289 | package teco.ardevkit.andardevkitplayer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.metaio.sdk.ARELActivity;
import com.metaio.sdk.jni.Camera;
import com.metaio.sdk.jni.CameraVector;
import com.metaio.sdk.jni.IMetaioSDKAndroid;
import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.Vector2di;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import teco.ardevkit.andardevkitplayer.network.TCPThread;
import teco.ardevkit.andardevkitplayer.network.UDPThread;
/**
* Created by dkarl on 19.03.15.
*/
public class PausableARELActivity extends ARELActivity {
private UDPThread udpThread;
private TCPThread tcpThread;
private String log = "ARELVIEWActivity-log";
private long maxProgressFileSize = 0;
private int oldProgress = 0;
private MenuItem pauseItem;
private boolean isPaused;
private boolean stateLoaded;
private Menu mMenu;
private Handler uiHandler = new Handler();
private File tempPauseImage;
protected Activity activity = this;
private String stateSavePath;
private String defaultTrackingFile;
private String noFuserTrackingFile;
IMetaioSDKCallback mSDKCallback;
@Override
protected int getGUILayout() {
// Attaching layout to the activity
return R.layout.template;
}
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
stateSavePath = Environment.getExternalStorageDirectory()
+ "/" + getResources().getString(R.string.app_name) + "/states/";
tempPauseImage = new File(stateSavePath + "temp/pause.jpg");
tempPauseImage.mkdirs();
setProgressBarVisibility(false);
Log.d(log, "ARELViewActivity.onResume");
if (udpThread == null) {
udpThread = new UDPThread(this);
udpThread.start();
}
if (tcpThread == null) {
tcpThread = new TCPThread(this);
tcpThread.start();
}
super.onResume();
String currentConfig = ((File)getIntent().getSerializableExtra(getPackageName() + INTENT_EXTRA_AREL_SCENE)).getAbsolutePath();
String currentProject = new File(currentConfig).getParent();
createFuserLessTracking(currentProject);
}
@Override
protected void onStop() {
Log.d(log, "ARELViewActivity.onPause");
udpThread.running = false;
udpThread.interrupt();
udpThread = null;
tcpThread.running = false;
tcpThread.interrupt();
tcpThread = null;
super.onStop();
}
public boolean loadNewProject() {
String appname = getResources().getString(R.string.app_name);
final File projectsFolder = new File(Environment.getExternalStorageDirectory()
+ "/" + appname);
String[] projects = projectsFolder.list(new FilenameFilter() {
@Override
public boolean accept(File file, String s) {
File toTest = new File(file.getAbsolutePath() + "/" + s);
if (toTest.isDirectory() && !s.equals("states")) {
return true;
}
return false;
}
});
Arrays.sort(projects);
String newsetProjectPath = projectsFolder.getAbsolutePath() + "/" + projects[projects.length - 1];
if (projects.length > 2) {
String oldestProjectPath = projectsFolder.getAbsolutePath() + "/" + projects[0];
File oldestProjectFolder = new File(oldestProjectPath);
try {
FileUtils.deleteDirectory(new File(oldestProjectPath));
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{oldestProjectFolder.getAbsolutePath()}, null, null);
}
mARELInterpreter.loadARELFile(new File(newsetProjectPath + "/arelConfig.xml"));
createFuserLessTracking(newsetProjectPath);
return true;
}
public void reportNewProjectIncoming() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (isPaused || stateLoaded) {
MenuItem item = mMenu.findItem(R.id.pause);
item.setIcon(android.R.drawable.ic_media_pause);
item.setTitle(R.string.pause);
isPaused = false;
stateLoaded = false;
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
startCamera();
}
});
}
setProgressBarVisibility(true);
setProgress(0);
Toast t = Toast.makeText(getApplicationContext(),
getResources().getString(R.string.indicate_projectLoading),
Toast.LENGTH_LONG);
t.show();
}
});
}
public void reportMaxProgress(final long l) {
runOnUiThread(new Runnable() {
@Override
public void run() {
setProgressBarIndeterminate(false);
}
});
oldProgress = 0;
maxProgressFileSize = l;
}
public void reportProgress(final long l) {
final int maxProgress = 10000;
final float currentProgress = (float) l / (float) maxProgressFileSize;
final int progressInt = (int) (currentProgress * maxProgress);
if (progressInt > oldProgress) {
oldProgress = progressInt;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (currentProgress < 1)
setProgress(progressInt);
else {
setProgressBarIndeterminate(true);
}
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
mMenu = menu;
pauseItem = menu.findItem(R.id.pause);
if (isPaused || stateLoaded) {
pauseItem.setIcon(android.R.drawable.ic_media_pause);
pauseItem.setTitle(R.string.resume);
}
// fill snapshot preview items with shots
File saveFolder = new File(stateSavePath);
final List<String> imageNames = new ArrayList<String>(Arrays.asList(saveFolder.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(".jpg")) {
return true;
}
return false;
}
})));
// set up snapshot/manage button
MenuItem saveload = menu.findItem(R.id.saveLoadMenu);
LinearLayout saveLoadButtonBase = (LinearLayout) saveload.getActionView();
saveLoadButtonBase.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
ImageButton saveLoadButton = (ImageButton) saveLoadButtonBase.getChildAt(0);
saveLoadButton.setScaleType(ImageView.ScaleType.CENTER);
saveLoadButton.setOnClickListener(new SaveOnClickListener(uiHandler));
saveLoadButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
StateManagerDialog statemanager = new StateManagerDialog(activity, metaioSDK);
statemanager.show();
return true;
}
});
java.util.Collections.sort(imageNames);
for (int i = 0; i < 5 && i < imageNames.size(); i++) {
String myJpgPath = saveFolder.getAbsolutePath() + "/" + imageNames.get(imageNames.size() - 1 - i);
BitmapDrawable snapshot = new BitmapDrawable(getResources(), myJpgPath);
ImageButton currentButton;
MenuItem snapshotMenuItem;
switch (i) {
case 0:
snapshotMenuItem = menu.findItem(R.id.snapshot1);
break;
case 1:
snapshotMenuItem = menu.findItem(R.id.snapshot2);
break;
case 2:
snapshotMenuItem = menu.findItem(R.id.snapshot3);
break;
case 3:
snapshotMenuItem = menu.findItem(R.id.snapshot4);
break;
case 4:
snapshotMenuItem = menu.findItem(R.id.snapshot5);
break;
default:
snapshotMenuItem = menu.findItem(R.id.snapshot1);
}
LinearLayout lin = (LinearLayout) snapshotMenuItem.getActionView();
currentButton = (ImageButton) lin.getChildAt(0);
currentButton.setImageDrawable(snapshot);
currentButton.setContentDescription(myJpgPath);
currentButton.setOnClickListener(new OnSnapshotClickListener());
snapshotMenuItem.setVisible(true);
snapshotMenuItem.setEnabled(true);
}
return true;
}
@Override
protected void startCamera() {
final CameraVector cameras = metaioSDK.getCameraList();
if (cameras.size() > 0) {
Camera camera = cameras.get(0);
// Choose back facing camera
for (int i = 0; i < cameras.size(); i++) {
if (cameras.get(i).getFacing() == Camera.FACE_BACK) {
camera = cameras.get(i);
break;
}
}
camera.setResolution(new Vector2di(1280, 720));
metaioSDK.startCamera(camera);
}
}
private class OnSnapshotClickListener implements ImageButton.OnClickListener {
@Override
public void onClick(View v) {
final String fileName = v.getContentDescription().toString();
final File toLoad = new File(fileName);
// make metaio open said file and allow for resuming
isPaused = false;
metaioSDK.setTrackingConfiguration(noFuserTrackingFile);
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
metaioSDK.setImage(fileName);
}
});
Log.i("State", "Previous state loaded");
pauseItem.setIcon(android.R.drawable.ic_media_play);
pauseItem.setTitle(R.string.resume);
stateLoaded = true;
}
}
public class StateManagerDialog extends Dialog {
public StateManagerDialog(final Context context, final IMetaioSDKAndroid metaioSDK) {
super(context);
this.setTitle("State Manager");
File saveFolder = new File(stateSavePath);
final List<String> imageNames = new ArrayList<String>(Arrays.asList(saveFolder.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(".jpg")) {
return true;
}
return false;
}
})));
java.util.Collections.sort(imageNames);
this.setContentView(R.layout.statemanagerlayout);
final ListView lv = (ListView) findViewById(R.id.stateList);
final ArrayAdapter adapter = new StateListAdapter(context, R.layout.statemanager_listrow, imageNames);
lv.setAdapter(adapter);
}
private class StateListAdapter extends ArrayAdapter<String> {
Context context;
int resource;
List<String> objects;
StateListAdapter adapter = this;
public StateListAdapter(Context context, int resource, List<String> imageNames) {
super(context, resource, imageNames);
this.resource = resource;
this.context = context;
this.objects = imageNames;
}
public boolean hasStableIds() {
return false;
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
// create new row layout
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(resource, parent, false);
ImageView img = (ImageView) row.findViewById(R.id.stateRowImage);
TextView text = (TextView) row.findViewById(R.id.stateRowText);
text.setText(objects.get(position));
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final File toLoad = new File(stateSavePath + objects.get(position));
// make metaio open said file and allow for resuming
isPaused = false;
metaioSDK.setTrackingConfiguration(noFuserTrackingFile);
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
metaioSDK.setImage(toLoad.getAbsolutePath());
}
});
Log.i("State", "Previous state loaded");
pauseItem.setIcon(android.R.drawable.ic_media_play);
pauseItem.setTitle(R.string.resume);
stateLoaded = true;
dismiss();
}
});
Bitmap bmap = BitmapFactory.decodeFile(stateSavePath + objects.get(position));
img.setImageBitmap(bmap);
ImageButton deleteButton = (ImageButton) row.findViewById(R.id.deleteButton);
deleteButton.setOnClickListener(new ImageButton.OnClickListener() {
@Override
public void onClick(View v) {
File toDelete = new File(stateSavePath + objects.get(position));
toDelete.delete();
objects.remove(position);
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
activity.invalidateOptionsMenu();
}
}, 500);
Log.i("State", "Previous state deleted");
}
});
return row;
}
}
}
private class SaveOnClickListener implements View.OnClickListener {
Handler handler;
public SaveOnClickListener(Handler handler) {
super();
this.handler = handler;
}
@Override
public void onClick(View view) {
// generate file path for current state
if (!isPaused) {
Long currentTime = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd-HH:mm:ss");
String currentTimestamp = formatter.format(new Date(currentTime));
final File toSave = new File(stateSavePath + currentTimestamp.toString() + ".jpg");
metaioSDK.requestCameraImage(toSave.getAbsolutePath());
//wait and do stuff
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
activity.invalidateOptionsMenu();
}
}, 500);
} else {
Long currentTime = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd-HH:mm:ss");
String currentTimestamp = formatter.format(new Date(currentTime));
final File toSave = new File(stateSavePath + currentTimestamp.toString() + ".jpg");
tempPauseImage.renameTo(toSave);
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
activity.invalidateOptionsMenu();
}
}, 500);
}
Toast.makeText(activity, "Current state saved", Toast.LENGTH_SHORT).show();
handler.postDelayed(new Runnable() {
@Override
public void run() {
invalidateOptionsMenu();
}
}, 700);
}
}
/**
* Function called when pause/resume button is clicked in menubar
*
* @param item the MenuItem that was clicked. Always the Pause/Resume item
*/
public void handlePause(MenuItem item) {
if (!stateLoaded) {
if (!isPaused) {
item.setIcon(android.R.drawable.ic_media_play);
item.setTitle(R.string.resume);
this.isPaused = true;
metaioSDK.requestCameraImage(tempPauseImage.getAbsolutePath());
metaioSDK.setTrackingConfiguration(noFuserTrackingFile);
// wait and set image
mSurfaceView.postDelayed(new Runnable() {
@Override
public void run() {
if (tempPauseImage.exists())
metaioSDK.setImage(tempPauseImage.getAbsolutePath());
else
mSurfaceView.postDelayed(this, 100);
}
}, 400);
} else {
item.setIcon(android.R.drawable.ic_media_pause);
item.setTitle(R.string.pause);
this.isPaused = false;
metaioSDK.setTrackingConfiguration(defaultTrackingFile);
this.startCamera();
}
} else {
item.setIcon(android.R.drawable.ic_media_pause);
item.setTitle(R.string.pause);
this.isPaused = false;
this.stateLoaded = false;
metaioSDK.setTrackingConfiguration(defaultTrackingFile);
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
startCamera();
}
});
}
}
private void createFuserLessTracking(String pathToProject) {
// take tracking config XML and convert to one that uses BestQualityFusers for every COS
try {
String AssetFolder = pathToProject + "/Assets";
defaultTrackingFile = AssetFolder + "/TrackingData_Marker.xml";
File file = new File(defaultTrackingFile);
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
// Change the content of node
NodeList nodes = doc.getElementsByTagName("Fuser");
for (int i = 0; i < nodes.getLength(); i++) {
Node current = nodes.item(i);
NamedNodeMap attr = current.getAttributes();
Attr newFuserType = doc.createAttribute("type");
newFuserType.setValue("BestQualityFuser");
Node success = attr.setNamedItem(newFuserType);
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// initialize StreamResult with File object to save to file
noFuserTrackingFile = AssetFolder + "/TrackingData_NoSmoothing.xml";
StreamResult result = new StreamResult(noFuserTrackingFile);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| mit |
aiming/Vagrant-template | Sandbox-fluent-plugin-secure-forward/site-cookbooks/create-user/recipes/default.rb | 179 | #
# Cookbook Name:: create-user
# Recipe:: default
#
# Copyright 2013, YOUR_COMPANY_NAME
#
# MIT License.
#
user 'fluentd' do
supports manage_home: true
action :create
end
| mit |
xrcat/x-guice | guice-mbean/src/test/java/com/maxifier/guice/mbean/Sandbox.java | 1238 | package com.maxifier.guice.mbean;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import javax.inject.Inject;
import javax.management.*;
import java.lang.management.ManagementFactory;
/**
* Created by: Aleksey Didik
* Date: 5/26/11
* Time: 10:13 PM
* <p/>
* Copyright (c) 1999-2011 Maxifier Ltd. All Rights Reserved.
* Code proprietary and confidential.
* Use is subject to license terms.
*
* @author Aleksey Didik
*/
public class Sandbox {
public static void main(String[] args) throws InterruptedException, MalformedObjectNameException, MBeanRegistrationException, InstanceAlreadyExistsException, NotCompliantMBeanException {
Foo object = new Foo();
Object o = Enhancer.create(Foo.class, new NoOp() {
});
ManagementFactory.getPlatformMBeanServer().registerMBean(o, new ObjectName("test", "serice", "hello"));
}
public static class Foo implements FooMBean {
}
public interface FooMBean {}
}
| mit |
PanosGr94/DSA-proyecto-REST | service/src/main/java/edu/upc/eetac/dsa/beeter/cors/CORSResponseFilter.java | 1225 | package edu.upc.eetac.dsa.beeter.cors;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import java.io.IOException;
/**
* Created by Panos on 18-Mar-16.
*/
public class CORSResponseFilter implements ContainerRequestFilter {
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
String reqHead = requestContext.getHeaderString("Access-Control-Request-Headers");
if (null != reqHead && !reqHead.equals("")) {
responseContext.getHeaders().add("Access-Control-Allow-Headers", reqHead);
}
responseContext.getHeaders().add("Access-Control-Expose-Headers", "Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Location");
}
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
}
}
| mit |
meatballhat/proximity | cmd/proximity-web/main.go | 389 | package main
import (
"fmt"
"os"
"github.com/meatballhat/proximity/web"
)
const (
usage = "Usage: proximity-web <addr>\n"
)
func main() {
addr := ":" + os.Getenv("PORT")
if addr == ":" {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, usage)
return
}
addr = ":" + os.Args[1]
}
server := web.NewServer(addr)
fmt.Printf("Serving on %s !!!\n", addr)
server.Serve()
}
| mit |
bironran/spring_issues_proxy_factory | src/main/java/com/rb/springissues/sample/Bean2.java | 303 | package com.rb.springissues.sample;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import com.rb.springissues.LoggerBase;
public class Bean2 extends LoggerBase {
@Inject
Provider<DummyBeanA> provider;
@Inject
@Named("bean1")
Bean1 bean1;
}
| mit |
jesseflorig/www.mtgdb.info | src/www.mtgdb.info/www.mtgdb.info/Content/javascript/mtgdb.info.js | 4226 | function updateTotal(n)
{
var amount = parseInt($('#total').text());
amount = amount + n;
$('#total').text(amount);
};
function updateUnique(n)
{
var amount = parseInt($('#unique').text());
amount = amount + n;
$('#unique').text(amount);
};
function updateSetCount(set, n)
{
var amount = parseInt($('#' + set).text());
amount = amount + n;
$('#' + set).text(amount);
};
function updateBlockCount(block, n)
{
var amount = parseInt($('#' + block).text());
amount = amount + n;
$('#' + block).text(amount);
};
function minusCard(cardId, block, set)
{
var amount = parseInt($('#' + cardId).val());
if(amount > 0)
{
amount = amount - 1;
set_amount(cardId, amount);
updateTotal(-1);
if(amount == 0)
{
updateUnique(-1);
if($('#active_block').length != 0)
{
var block = $('#active_block').val();
updateBlockCount(block, -1);
}
if($('#active_set').length != 0)
{
var set = $('#active_set').val();
updateSetCount(set, -1);
}
}
}
};
function addCard(cardId)
{
var amount = parseInt($('#' + cardId).val());
if(amount == 0)
{
updateUnique(1);
if($('#active_block').length != 0)
{
var block = $('#active_block').val();
updateBlockCount(block, 1);
}
if($('#active_set').length != 0)
{
var set = $('#active_set').val();
updateSetCount(set, 1);
}
}
amount = amount + 1;
set_amount(cardId, amount);
updateTotal(1);
};
function changeAmount(cardId)
{
var isInt = /^\d+$/;
if(isInt.test($('#' + cardId).val()))
{
var amount = parseInt($('#' + cardId).val());
set_amount(cardId, amount);
}
};
function set_amount(cardId, amount)
{
var opts = {
lines: 9, // The number of lines to draw
length: 8, // The length of each line
width: 10, // The line thickness
radius: 20, // The radius of the inner circle
corners: 1, // Corner roundness (0..1)
rotate: 24, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
color: '#000', // #rgb or #rrggbb or array of colors
speed: 1, // Rounds per second
trail: 90, // Afterglow percentage
shadow: true, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: 'auto', // Top position relative to parent in px
left: 'auto' // Left position relative to parent in px
};
var target = document.getElementById('card_' + cardId);
var spinner = new Spinner(opts).spin(target);
var jqxhr = $.post( "/cards/" + cardId + "/amount/" + amount)
.done(function( data ) {
$('#' + cardId).val(data);
if(amount > 0)
{
$('#img_' + cardId).attr('class', 'owned');
}
else
{
$('#img_' + cardId).attr('class', 'dontown');
}
if($('#value_' + cardId).length != 0)
{
$('#value_' + cardId).text(amount);
}
})
.fail(function() {
alert( "Could not update card amount. Please try again later." );
})
.always(function() {
spinner.stop();
});
};
function format(set) {
if (!set.id) return set.text; // optgroup
return "<img class='flag' src='https://api.mtgdb.info/content/set_images/symbols/" + set.id.toLowerCase() +
"_sym.png'/>" + " " + set.text;
}
$(document).ready(function() {
$("#set_list").select2({
matcher: function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())==0; },
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
});
function go()
{
window.location="/sets/" + document.getElementById("set_list").value
}
| mit |
jrbeaumont/workcraft | CpogPlugin/src/org/workcraft/plugins/cpog/commands/GraphToCpogConversionCommand.java | 1220 | package org.workcraft.plugins.cpog.commands;
import org.workcraft.commands.AbstractConversionCommand;
import org.workcraft.plugins.cpog.Cpog;
import org.workcraft.plugins.cpog.CpogDescriptor;
import org.workcraft.plugins.cpog.VisualCpog;
import org.workcraft.plugins.cpog.converters.GraphToCpogConverter;
import org.workcraft.plugins.graph.Graph;
import org.workcraft.plugins.graph.VisualGraph;
import org.workcraft.workspace.ModelEntry;
import org.workcraft.workspace.WorkspaceEntry;
import org.workcraft.workspace.WorkspaceUtils;
public class GraphToCpogConversionCommand extends AbstractConversionCommand {
@Override
public String getDisplayName() {
return "Conditional Partial Order Graph";
}
@Override
public boolean isApplicableTo(WorkspaceEntry we) {
return WorkspaceUtils.isApplicableExact(we, Graph.class);
}
@Override
public ModelEntry convert(ModelEntry me) {
final VisualGraph graph = me.getAs(VisualGraph.class);
final VisualCpog cpog = new VisualCpog(new Cpog());
final GraphToCpogConverter converter = new GraphToCpogConverter(graph, cpog);
return new ModelEntry(new CpogDescriptor(), converter.getDstModel());
}
}
| mit |
DimensionDataResearch/daas-demo | src/DaaSDemo.UI/webpack.config.js | 1773 | const path = require('path');
const webpack = require('webpack');
const { AureliaPlugin } = require('aurelia-webpack-plugin');
const bundleOutputDir = './wwwroot/dist';
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
stats: { modules: false },
entry: { 'app': 'aurelia-bootstrapper' },
resolve: {
extensions: ['.ts', '.js'],
modules: ['ClientApp', 'node_modules', 'lib/semantic/dist'],
},
output: {
path: path.resolve(bundleOutputDir),
publicPath: 'dist/',
filename: '[name].js'
},
module: {
rules: [
{ test: /\.ts$/i, include: /ClientApp/, use: 'ts-loader?silent=true' },
{ test: /\.html$/i, use: 'html-loader' },
{ test: /\.css$/i, use: isDevBuild ? 'css-loader' : 'css-loader?minimize' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [
new webpack.DefinePlugin({ IS_DEV_BUILD: JSON.stringify(isDevBuild) }),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
}),
new AureliaPlugin({ aureliaApp: 'boot' })
].concat(isDevBuild ? [
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
new webpack.optimize.UglifyJsPlugin()
])
}];
}
| mit |
kuldipem/fabric.js | test/unit/polyline.js | 5581 | (function() {
function getPoints() {
return [
{x: 10, y: 12},
{x: 20, y: 22}
];
}
var REFERENCE_OBJECT = {
'type': 'polyline',
'originX': 'left',
'originY': 'top',
'left': 10,
'top': 12,
'width': 10,
'height': 10,
'fill': 'rgb(0,0,0)',
'stroke': null,
'strokeWidth': 1,
'strokeDashArray': null,
'strokeLineCap': 'butt',
'strokeLineJoin': 'miter',
'strokeMiterLimit': 10,
'scaleX': 1,
'scaleY': 1,
'angle': 0,
'flipX': false,
'flipY': false,
'opacity': 1,
'points': getPoints(),
'shadow': null,
'visible': true,
'backgroundColor': '',
'clipTo': null,
'fillRule': 'nonzero',
'globalCompositeOperation': 'source-over',
'skewX': 0,
'skewY': 0,
'transformMatrix': null
};
var REFERENCE_EMPTY_OBJECT = {
'points': [],
'width': 0,
'height': 0,
'top': 0,
'left': 0
};
QUnit.module('fabric.Polyline');
test('constructor', function() {
ok(fabric.Polyline);
var polyline = new fabric.Polyline(getPoints());
ok(polyline instanceof fabric.Polyline);
ok(polyline instanceof fabric.Object);
equal(polyline.type, 'polyline');
deepEqual(polyline.get('points'), [{ x: 10, y: 12 }, { x: 20, y: 22 }]);
});
test('complexity', function() {
var polyline = new fabric.Polyline(getPoints());
ok(typeof polyline.complexity == 'function');
});
test('toObject', function() {
var polyline = new fabric.Polyline(getPoints());
ok(typeof polyline.toObject == 'function');
var objectWithOriginalPoints = fabric.util.object.extend(polyline.toObject(), {
points: getPoints()
});
deepEqual(objectWithOriginalPoints, REFERENCE_OBJECT);
});
asyncTest('fromObject', function() {
ok(typeof fabric.Polyline.fromObject == 'function');
fabric.Polyline.fromObject(REFERENCE_OBJECT, function(polyline) {
ok(polyline instanceof fabric.Polyline);
deepEqual(polyline.toObject(), REFERENCE_OBJECT);
start();
});
});
test('fromElement without points', function() {
ok(typeof fabric.Polyline.fromElement == 'function');
var elPolylineWithoutPoints = fabric.document.createElement('polyline');
var empty_object = fabric.util.object.extend({}, REFERENCE_OBJECT);
empty_object = fabric.util.object.extend(empty_object, REFERENCE_EMPTY_OBJECT);
fabric.Polyline.fromElement(elPolylineWithoutPoints, function(polyline) {
deepEqual(polyline.toObject(), empty_object);
});
});
test('fromElement with empty points', function() {
var elPolylineWithEmptyPoints = fabric.document.createElement('polyline');
elPolylineWithEmptyPoints.setAttribute('points', '');
fabric.Polyline.fromElement(elPolylineWithEmptyPoints, function(polyline) {
var empty_object = fabric.util.object.extend({}, REFERENCE_OBJECT);
empty_object = fabric.util.object.extend(empty_object, REFERENCE_EMPTY_OBJECT);
deepEqual(polyline.toObject(), empty_object);
});
});
test('fromElement', function() {
var elPolyline = fabric.document.createElement('polyline');
elPolyline.setAttribute('points', '10,12 20,22');
fabric.Polyline.fromElement(elPolyline, function(polyline) {
ok(polyline instanceof fabric.Polyline);
deepEqual(polyline.toObject(), REFERENCE_OBJECT);
});
});
test('fromElement with custom attr', function() {
var elPolylineWithAttrs = fabric.document.createElement('polyline');
elPolylineWithAttrs.setAttribute('points', '10,10 20,20 30,30 10,10');
elPolylineWithAttrs.setAttribute('fill', 'rgb(255,255,255)');
elPolylineWithAttrs.setAttribute('opacity', '0.34');
elPolylineWithAttrs.setAttribute('stroke-width', '3');
elPolylineWithAttrs.setAttribute('stroke', 'blue');
elPolylineWithAttrs.setAttribute('transform', 'translate(-10,-20) scale(2)');
elPolylineWithAttrs.setAttribute('stroke-dasharray', '5, 2');
elPolylineWithAttrs.setAttribute('stroke-linecap', 'round');
elPolylineWithAttrs.setAttribute('stroke-linejoin', 'bevil');
elPolylineWithAttrs.setAttribute('stroke-miterlimit', '5');
fabric.Polyline.fromElement(elPolylineWithAttrs, function(polylineWithAttrs) {
var expectedPoints = [{x: 10, y: 10}, {x: 20, y: 20}, {x: 30, y: 30}, {x: 10, y: 10}];
deepEqual(polylineWithAttrs.toObject(), fabric.util.object.extend(REFERENCE_OBJECT, {
'width': 20,
'height': 20,
'fill': 'rgb(255,255,255)',
'stroke': 'blue',
'strokeWidth': 3,
'strokeDashArray': [5, 2],
'strokeLineCap': 'round',
'strokeLineJoin': 'bevil',
'strokeMiterLimit': 5,
'opacity': 0.34,
'points': expectedPoints,
'left': 10,
'top': 10,
'transformMatrix': [2, 0, 0, 2, -10, -20]
}));
deepEqual(polylineWithAttrs.get('transformMatrix'), [2, 0, 0, 2, -10, -20]);
});
});
test('fromElement with nothing', function() {
fabric.Polyline.fromElement(null, function(polyline) {
equal(polyline, null);
});
});
})();
| mit |
muratg/fsdemo | CSharpProject/Properties/AssemblyInfo.cs | 1428 | 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("FSCSDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FSCSDemo")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("15199d6d-2aad-474a-9167-7a285df8412b")]
// 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")]
| mit |
brianb12321/RemotePlus | src/RemotePlusClientCmd/Requests/ConsoleReadLineRequest.cs | 1147 | using RemotePlusLibrary.Core;
using RemotePlusLibrary.RequestSystem;
using RemotePlusLibrary.RequestSystem.DefaultRequestBuilders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemotePlusClientCmd.Requests
{
public class ConsoleReadLineRequest : StandordRequest<ConsoleReadLineRequestBuilder, UpdateRequestBuilder>
{
public override string URI => "rcmd_readLine";
public override bool ShowProperties => false;
public override string FriendlyName => "Console ReadLine Request";
public override string Description => "What do you think it does?";
public override NetworkSide SupportedSides => NetworkSide.Client;
public override RawDataResponse RequestData(ConsoleReadLineRequestBuilder builder, NetworkSide executingSide)
{
Console.Write(builder.Message);
Console.ForegroundColor = builder.LineColor;
RawDataResponse response = RawDataResponse.Success(ConsoleHelper.LongReadLine());
Console.ResetColor();
return response;
}
}
} | mit |
ISO-tech/sw-d8 | web/2006-2/600/600_04_ViewsInBrief.php | 8777 | <html>
<head>
<title>
Views in brief
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>
</head>
<body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0">
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td>
<td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?>
</td></tr></table>
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="18" bgcolor="FFCC66"></td>
<td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td>
<td width="18"></td>
<td width="480" valign="top">
<?php include "../../legacy-includes/BodyInsert.htmlf" ?>
<font face="Times New Roman, Times, serif" size="5"><b>Views in brief</b></font><P>
<font face="Arial, Helvetica, sans-serif" size="2">September 8, 2006 | Page 4</font><P>
<font face="Times New Roman, Times, serif" size="3"><B>OTHER VIEWS BELOW:</B><BR>
<A HREF="#Enemy">Imperialism is the main enemy</A><BR>
<A HREF="#Move">A principled movement</A><P>
<font face="Times New Roman, Times, serif" size="4"><b>Nader's stand against the war</b></font><p>
<font face="Times New Roman, Times, serif" size="3">JOHN OSMOND is right to point out that Ralph Nader's hopes, expressed in a <i>Democracy Now! </i>interview, that the Democrats will "diminish" their opposition to third parties are misplaced ("Nader wrong on Lieberman," September 1). <p>
I only write to mention that Nader spent 90 percent of his time during the interview passionately denouncing U.S. support for Israel's invasion of Lebanon, and reminding the world that Israel and the U.S. were the aggressors and terrorists for targeting the civilian population. Jonathan Tasini, who was also on the show with Nader and is running in the Democratic primary against Hilary Clinton, bemoaned violence on both sides. <p>
Socialists certainly have important disagreements with Nader, but we agree fully with his principled opposition to U.S. support for Israel's terror and his belief that the Democratic Party cannot be reformed.<br>
<b>Todd Chretien,</b> Oakland, Calif.<p>
<font face="Arial, Helvetica, sans-serif" size="2"><a href="#Top">Back to the top</a></font><br>
<br>
<p><a name="Enemy"></a><font face="Times New Roman, Times, serif" size="4"><b>Imperialism is the main enemy</b></font><p>
<font face="Times New Roman, Times, serif" size="3">JOHN GREEN'S letter on the Afghan resistance is wrong in every way ("Taliban not a step forward," August 11). He falsely counterposes Hezbollah in Lebanon and the Taliban in Afghanistan, claiming that the former is leading (despite its socially reactionary politics) a genuine national liberation struggle while the latter "fails this criteria."<p>
His proof of their failure is that "most Afghans don't support the Taliban's fundamentalism, drug-trafficking and intimidation tactics." This sounds a lot like the Bush administration's rhetoric about the Iraqi resistance, minus the drug trafficking, and Green provides no evidence about what most Afghans support.<p>
Green's analysis leaves us totally unable to explain the new resurgence in the Taliban's strength. Occupation forces in Afghanistan have raided homes and villages with impunity, engaged in torture and committed other atrocities. This is precisely why the popularity of the Taliban has grown enormously since they were toppled from power almost five years ago.<p>
Like it or not, the Taliban is leading the resistance to Western imperialism in Afghanistan. Socialists should never hide our political differences and criticisms of Islamists, but any criticism can come only in the context of support for the struggle they are leading. <p>
In this case, the struggle is one for an Afghanistan free of imperialist control. Victory for the Taliban would not only be a blow to U.S. imperialism, but also a victory for the oppressed around the world, who are fighting the same enemy.<br>
<b>Pham Binh,</b> New York City<p>
<font face="Arial, Helvetica, sans-serif" size="2"><a href="#Top">Back to the top</a></font><br>
<br>
<p><a name="Move"></a><font face="Times New Roman, Times, serif" size="4"><b>A principled movement</b></font><p>
<font face="Times New Roman, Times, serif" size="3">IN HER "Which Side Are You On" column, Sharon Smith correctly points out that "the weakness of the mainstream U.S. antiwar movement toward Israeli war crimes is not a temporary aberration, but a long-standing phenomenon." <i>(SW, </i>July 28)<p>
She backs this up by connecting the United for Peace and Justice (UFPJ) leadership's "repeat(ing) the mainstream media's depiction" of the recent events in the Middle East to the position taken by their political predecessors (in many cases, the same people with the same politics) on the eve of Israel's last invasion of Lebanon in 1982, when a massive peace that they organized rally in New York City's Central Park conveniently made no mention of Israel's bombing of Lebanon. <p>
Both positions, however, stem from the "mainstream" liberal left's main "weakness"--toward the Democratic Party, which, as Sharon shows, is even more staunchly pro-Israel than the Republicans are. <p>
This "long-standing phenomenon," whether it goes under the name of "popular front," "lesser evil," "ABB" or "taking back Congress," subordinates any and every struggle and mass movement to the election of Democratic Party politicians to whatever office is being contested. (Remember how the reformists said that the "real fight" begins the day after Election Day...in 2004. Well, we're still waiting.)<p>
Since the mainstream left feels that anything else is an unobtainable pipedream--i.e., "another world" is not possible--its whole political universe revolves around putting more Democrats into office as the only "realistic" game in town, regardless of how right wing they are. <p>
Since Israel is, as Smith points out, the "U.S.'s historic regional partner in enforcing its Middle East policy," both Democrats and Republicans, as partner parties of the capitalist class, always close ranks when it comes to backing up Israeli aggression. That's because imperialism is a system, and not a policy preferred by "unilateralists" or "neo-cons." <p>
But since electing those same Democrats in November is UFPJ's top priority, any significant protest against Israel's outrages in Lebanon and Gaza will just have to be put on the back burner, as was opposition to the Iraq war in 2004, when electing the pro-war (and pro-Israel) John Kerry took top priority. <p>
For the UFPJ leadership, the "thousands of lives that are at stake" are apparently so much "collateral damage"; the price the Palestinians and the Lebanese will have to pay in order for the Democrats to "take back Congress." Then they can continue to vote to give Israel even more money to carry out its endless acts of aggression as part of the bigger and better "war on terror" that the Democrats desire. <p>
Indeed the Democrats recognize, no less than we do, that the one-sided "war" in Lebanon (and Gaza) is an important component of the war of terror to gain control of the Middle East, even if the leaders of UFPJ try to ignore or deny it. <p>
After all, if the "maximum program" of the "politics of the possible" consists of replacing one set of pro-war capitalist politicians with another, you can't take any unpopular positions. That might get in the way of their winning office, regardless of how many "lives are at stake" or how much it sets back building movements "on a principled basis"--i.e., independent of both bosses' parties.<p>
If the antiwar movement--or any other movement, for that matter--is to ever "revive" on that "principled basis" that Smith speaks of, it is necessary that those of us who are "principled" politically take on the mainstream left; not only by effectively exposing them, but by politically challenging and defeating them for leadership in these movements. <p>
While this paradoxically requires the broadest possible unity with these same forces, in order to expose them in action before their supporters, it also requires that we recognize them for what they are: the left lieutenants of the capitalist class within the mass movements, as the early American socialist Daniel DeLeon described the trade union bureaucracy, and deal with them as such.<br>
<b>Roy Rollin,</b> New York City<p>
<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>
<td width="12"></td>
<td width="108" valign="top">
<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>
</td>
</tr>
</table>
</body>
</html>
| mit |
RobertDober/lab42_streams | spec/support/expect_subject.rb | 150 | module ExpectSubject
def expect_subject; expect subject end
end # module ExpectSubject
RSpec.configure do | conf |
conf.include ExpectSubject
end
| mit |
zachdj/ultimate-tic-tac-toe | models/game/Board.py | 6215 | import numpy
class Board(object):
""" Abstract base class for board objects. Implements some methods that are common to both microboards and macroboards.
"""
""" constants for UTTT boards.
These are defined such that the sum of three cells is 3 iff X holds all three cells
and the sum is 6 iff O has captured all three cells """
X = 1
X_WIN_COND = X * 3
O = 2
O_WIN_COND = O * 3
EMPTY = -2
CAT = -3 # value representing a board that was completed but tied
def __init__(self):
self.board_completed = False
self.total_moves = 0
self.winner = Board.EMPTY
def make_move(self, move):
"""
Applies the specified move to this Board
:param move: the Move object to apply
:return: None
"""
raise Exception("The abstract Board method make_move must be overridden by child class")
# should return X, O, or EMPTY based on the contents of the specified cell
def check_cell(self, row, col):
"""
Checks the specified cell and returns the contents.
:param row: integer between 0 and 2 specifying the vertical coordinate of the cell to check
:param col: integer between 0 and 2 specifying the horizontal coordinate of the cell to check
:return: Board.X if the cell is captured by X, Board.O if the cell is captured by O, Board.EMPTY otherwise
"""
raise Exception("The abstract Board method check_cell must be overridden by the child class")
def check_board_completed(self, row, col):
"""
Checks whether the most recent move caused the board to be won, lost, or tied, then sets the
'board_completed' and 'winner' member variables appropriately.
A board is defined to be tied if all possible moves have been made but neither X nor O won.
Winner will be set to Board.EMPTY if the board is incomplete or tied
:param row: the row of the most recent move
:param col: the column of the most recent move
:return: True if the board is completed (won or tied), False otherwise
"""
rowsum = 0
colsum = 0
main_diag_sum = 0 # sum of diagonal from top-left to bottom-right
alt_diag_sum = 0 # sum of diagonal from top-right to bottom-left
for i in [0, 1, 2]:
rowsum += self.check_cell(row, i)
colsum += self.check_cell(i, col)
main_diag_sum += self.check_cell(i, i)
alt_diag_sum += self.check_cell(i, 2 - i)
if rowsum == Board.X_WIN_COND or colsum == Board.X_WIN_COND or main_diag_sum == Board.X_WIN_COND or alt_diag_sum == Board.X_WIN_COND:
self.board_completed = True
self.winner = Board.X
elif rowsum == Board.O_WIN_COND or colsum == Board.O_WIN_COND or main_diag_sum == Board.O_WIN_COND or alt_diag_sum == Board.O_WIN_COND:
self.board_completed = True
self.winner = Board.O
# check for tie
completed_boards = 0
for row in [0, 1, 2]:
for col in [0, 1, 2]:
if self.check_cell(row, col) in [Board.X, Board.O, Board.CAT]:
completed_boards += 1
if completed_boards == 9:
self.board_completed = True
def get_capture_vector(self, player):
""" Returns a vector of length 9 with a binary representation of which cells have been captured by the given player
For example, if the specified player has captured the center and corner cells, then this method returns
[1, 0, 1, 0, 1, 0, 1, 0, 1]
If the player has captured the center only, this method returns
[0, 0, 0, 0, 1, 0, 0, 0, 0]
:param player: Board.X or Board.O
:return: the capture vector for the specified player
"""
if player not in [self.X, self.O]:
raise Exception("Capture vector requested for invalid player")
capture_vector = numpy.zeros(9)
for row in [0, 1, 2]:
for col in [0, 1, 2]:
if self.check_cell(row, col) == player:
index = 3*row + col
capture_vector[index] = 1
return capture_vector
def count_attacking_sequences(self, player):
""" Returns the count of attacking sequences owned by the given player on this board
:param player: Board.X or Board.O
:return: an integer count of attacking sequences
"""
if player not in [self.X, self.O]:
raise Exception("Capture vector requested for invalid player")
count = 0
# check each row
for row in [0, 1, 2]:
player_controlled = 0
empty_cells = 0
for col in [0, 1, 2]:
controller = self.check_cell(row, col)
if controller == player: player_controlled += 1
elif controller == Board.EMPTY: empty_cells += 1
if player_controlled == 2 and empty_cells == 1:
count += 1
# check each col
for col in [0, 1, 2]:
player_controlled = 0
empty_cells = 0
for row in [0, 1, 2]:
controller = self.check_cell(row, col)
if controller == player: player_controlled += 1
elif controller == Board.EMPTY: empty_cells += 1
if player_controlled == 2 and empty_cells == 1:
count += 1
# check main diagonal
player_controlled = 0
empty_cells = 0
for i in [0, 1, 2]:
controller = self.check_cell(i,i)
if controller == player: player_controlled += 1
elif controller == Board.EMPTY: empty_cells += 1
if player_controlled == 2 and empty_cells == 1:
count += 1
# check alt diagonal
player_controlled = 0
empty_cells = 0
for i in [0, 1, 2]:
controller = self.check_cell(i, 2 - i)
if controller == player: player_controlled += 1
elif controller == Board.EMPTY: empty_cells += 1
if player_controlled == 2 and empty_cells == 1:
count += 1
return count
| mit |
meltingmedia/MODX-Shell | src/Configuration/Base.php | 922 | <?php namespace MODX\Shell\Configuration;
/**
* A base configuration class to extend
*/
abstract class Base implements ConfigurationInterface
{
protected $items = array();
public function get($key, $default = null)
{
if (isset($this->items[$key])) {
return $this->items[$key];
}
return $default;
}
public function set($key, $value = null)
{
$this->items[$key] = $value;
}
public function remove($key)
{
if (isset($this->items[$key])) {
unset($this->items[$key]);
}
}
public function getAll()
{
return $this->items;
}
public function getConfigPath()
{
return getenv('HOME') . '/.modx/';
}
public function makeSureConfigPathExists()
{
$path = $this->getConfigPath();
if (!file_exists($path)) {
mkdir($path);
}
}
}
| mit |
bdamage/tshirtStore | index.php | 17037 | <!DOCTYPE html>
<html>
<head>
<title>Your T-shirt store</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<link rel="stylesheet" href="css/font-awesome.min.css">
<style>
/* GLOBAL STYLES
-------------------------------------------------- */
/* Padding below the footer and lighter body text */
body {
padding-bottom: 40px;
color: #5a5a5a;
}
/* CUSTOMIZE THE NAVBAR
-------------------------------------------------- */
/* Special class on .container surrounding .navbar, used for positioning it into place. */
.navbar-wrapper {
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 10;
margin-top: 20px;
margin-bottom: -90px; /* Negative margin to pull up carousel. 90px is roughly margins and height of navbar. */
}
.navbar-wrapper .navbar {
}
/* Remove border and change up box shadow for more contrast */
.navbar .navbar-inner {
border: 0;
-webkit-box-shadow: 0 2px 10px rgba(0,0,0,.25);
-moz-box-shadow: 0 2px 10px rgba(0,0,0,.25);
box-shadow: 0 2px 10px rgba(0,0,0,.25);
}
/* Downsize the brand/project name a bit */
.navbar .brand {
padding: 14px 20px 16px; /* Increase vertical padding to match navbar links */
font-size: 16px;
font-weight: bold;
text-shadow: 0 -1px 0 rgba(0,0,0,.5);
}
/* Navbar links: increase padding for taller navbar */
.navbar .nav > li > a {
padding: 15px 20px;
}
.navbar .btn, .navbar .btn-group {
margin-top: 10px;
}
.navbar form {
margin-top: 10px;
}
/* Offset the responsive button for proper vertical alignment */
.navbar .btn-navbar {
margin-top: 10px;
}
/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
/* Carousel base class */
.carousel {
margin-bottom: 60px;
}
.carousel .container {
position: relative;
z-index: 9;
}
.carousel-control {
height: 80px;
margin-top: 0;
font-size: 120px;
text-shadow: 0 1px 1px rgba(0,0,0,.4);
background-color: transparent;
border: 0;
z-index: 10;
}
.carousel .item {
height: 400px;
}
.carousel img {
position: absolute;
top: 0;
left: 0;
min-width: 100%;
height: 400px;
}
.carousel-caption {
background-color: transparent;
position: static;
max-width: 550px;
padding: 0 20px;
margin-top: 200px;
}
.carousel-caption h1,
.carousel-caption .lead {
margin: 0;
line-height: 1.25;
color: #fff;
text-shadow: 0 1px 1px rgba(0,0,0,.4);
}
.carousel-caption .btn {
margin-top: 10px;
}
.carousel-indicators.middle {
left: 0;
right: 0;
top: auto;
bottom: 15px;
text-align: center;
}
.carousel-indicators.middle li {
float: none;
display: inline-block;
}
/* CUSTOMIZE THE CAROUSEL DETAILS
-------------------------------------------------- */
/* Carousel base class */
.carouselDetails {
margin-bottom: 60px;
}
.carouselDetails .container {
position: relative;
z-index: 9;
}
.carousel-controlDetails {
height: 80px;
margin-top: 0;
font-size: 120px;
text-shadow: 0 1px 1px rgba(0,0,0,.4);
background-color: transparent;
border: 0;
z-index: 10;
}
.carouselDetails .item {
height: 350px;
}
.carouselDetails img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right:0;
min-width: 0%;
height: 350px;
}
.carousel-indicatorsDetails.middle {
left: 0;
right: 0;
top: auto;
bottom: 15px;
text-align: center;
}
.carousel-indicatorsDetails.middle li {
float: none;
display: inline-block;
}
/* MARKETING CONTENT
-------------------------------------------------- */
/* Center align the text within the three columns below the carousel */
.marketing .span4 {
text-align: center;
}
.marketing h2 {
font-weight: normal;
}
.marketing .span4 p {
margin-left: 10px;
margin-right: 10px;
}
.details {
margin-top: 80px;
}
/* RESPONSIVE CSS
-------------------------------------------------- */
@media (max-width: 979px) {
.container.navbar-wrapper {
margin-bottom: 0;
width: auto;
}
.navbar-inner {
border-radius: 0;
margin: -20px 0;
}
.carousel .item {
height: 500px;
}
.carousel img {
width: auto;
height: 500px;
}
.featurette {
height: auto;
padding: 0;
}
.featurette-image.pull-left,
.featurette-image.pull-right {
display: block;
float: none;
max-width: 40%;
margin: 0 auto 20px;
}
}
@media (max-width: 767px) {
.navbar-inner {
margin: -20px;
}
.carousel {
margin-left: -20px;
margin-right: -20px;
}
.carousel .container {
}
.carousel .item {
height: 300px;
}
.carousel img {
height: 300px;
}
.carousel-caption {
width: 65%;
padding: 0 70px;
margin-top: 100px;
}
.carousel-caption h1 {
font-size: 30px;
}
.carousel-caption .lead,
.carousel-caption .btn {
font-size: 18px;
}
.marketing .span4 + .span4 {
margin-top: 40px;
}
.featurette-heading {
font-size: 30px;
}
.featurette .lead {
font-size: 18px;
line-height: 1.5;
}
}
/*
Popover modifcations for checkout
*/
.popover {
min-width:270px;
}
.popover hr{
margin:0;
}
</style>
</head>
<body>
<!-- NAVBAR
================================================== -->
<div class="navbar-wrapper">
<!-- Wrap the .navbar in .container to center it within the absolutely positioned parent. -->
<div class="container">
<div class="navbar navbar-inverse">
<div class="navbar-inner">
<!-- Responsive Navbar Part 1: Button for triggering responsive navbar (not covered in tutorial). Include responsive CSS to utilize. -->
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="#" onclick="showFront();">T-shirt store</a>
<!-- Responsive Navbar Part 2: Place all navbar contents you want collapsed withing .navbar-collapse.collapse. -->
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#" onclick="showFront();" data-toggle="tab">Home</a></li>
<li><a href="#about" data-toggle="tab">About</a></li>
<li><a href="#contact" data-toggle="tab">Contact</a></li>
<!-- Read about Bootstrap dropdowns at http://twitter.github.com/bootstrap/javascript.html#dropdowns -->
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<form class="navbar-search pull-left">
<input type="text" class="search-query" placeholder="Search">
</form>
<a id="checkoutBtn" class="btn btn-small btn-success pull-right" href="#" onclick="onCheckOut();" data-content="" rel="popover" data-html="true" data-placement="bottom" data-original-title="Shopping basket" data-trigger="hover"><i class="icon-shopping-cart"></i> Checkout</a>
</div><!--/.nav-collapse -->
</div><!-- /.navbar-inner -->
</div><!-- /.navbar -->
</div> <!-- /.container -->
</div><!-- /.navbar-wrapper -->
<!-- Carousel
================================================== -->
<div id="myCarousel" class="carousel slide">
<ol class="carousel-indicators middle">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<img src="./img/jumbotron_img1.jpg" alt="">
<div class="container">
<div class="carousel-caption">
</div>
</div>
</div>
<div class="item">
<img src="./img/jumbotron_img1.jpg" alt="">
<div class="container">
<!-- <div class="carousel-caption">
<h1>Another example headline.</h1>
<p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
<a class="btn btn-large btn-primary" href="#">Learn more</a>
</div>
-->
</div>
</div>
<div class="item">
<img src="./img/jumbotron_img1.jpg" alt="">
<div class="container">
<!-- <div class="carousel-caption">
<h1>One more for good measure.</h1>
<p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
<a class="btn btn-large btn-primary" href="#">Browse gallery</a>
</div>
-->
</div>
</div>
</div>
<a class="left carousel-control" href="#myCarousel" data-slide="prev">‹</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">›</a>
</div><!-- /.carousel -->
<div id="checkout" class="container hidden">
</div>
<!-- Marketing messaging and featurettes
================================================== -->
<!-- Wrap the rest of the page in another container to center all the content. -->
<div class="container marketing">
<!-- Three columns of text below the carousel -->
<div class="row">
<div class="span4">
<img class="img-box" src="./img/thumb_img01.jpg">
<h2>Heading</h2>
<p>Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. </p>
<p><a class="btn" href="#" onclick="showItemDetails('130701');">View details »</a></p>
</div><!-- /.span4 -->
<div class="span4">
<img class="img-box" src="./img/thumb_img02.jpg">
<h2>Heading</h2>
<p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. </p>
<p><a class="btn" href="#" onclick="showItemDetails('130702');">View details »</a></p>
</div><!-- /.span4 -->
<div class="span4">
<img class="img-box" src="./img/thumb_img01.jpg">
<h2>Heading</h2>
<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper.</p>
<p><a class="btn" href="#" onclick="showItemDetails('130703');">View details »</a></p>
</div><!-- /.span4 -->
</div><!-- /.row -->
</div><!-- /.marketing -->
<!-- Item Details -->
<div class="container details hidden">
<div class="row">
<div class="span6">
<div id="myCarouselDetails" class="carousel carouselDetails slide">
<ol class="carousel-indicators middle">
<li data-target="#myCarouselDetails" data-slide-to="0" class="active"></li>
<li data-target="#myCarouselDetails" data-slide-to="1"></li>
<li data-target="#myCarouselDetails" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<img src="./img/tshirt-agression01.jpg" alt="">
</div>
<div class="item">
<img src="./img/tshirt-darkforces01.jpg" alt="">
</div>
<div class="item">
<img src="./img/framed-agression.jpg" alt="">
</div>
</div> <!-- /carousel-inner -->
<a class="left carousel-control" href="#myCarouselDetails" data-slide="prev">‹</a>
<a class="right carousel-control" href="#myCarouselDetails" data-slide="next">›</a>
</div><!-- /.carousel -->
<div class="row">
<!-- <img class="img-box" src="./img/tshirt-agression01.jpg">
-->
<img class="img-box" src="./img/tshirt-agression01.jpg" data-target="#myCarouselDetails" data-slide-to="0" width="100">
<img class="img-box" src="./img/tshirt-darkforces01.jpg" data-target="#myCarouselDetails" data-slide-to="1" width="100">
<img class="img-box" src="./img/framed-agression.jpg" data-target="#myCarouselDetails" data-slide-to="2" width="100">
</div>
</div> <!-- /.span6 -->
<div class="span6">
<h2 id="shirtName">Heading</h2>
<h4 id="price">299 SEK</h4>
<p id="desc">Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. </p>
<hr>
<div class="btn-group" data-toggle="buttons-radio">
<button type="button" class="btn">S</button>
<button type="button" class="btn active">M</button>
<button type="button" class="btn">L</button>
<button type="button" class="btn">XL</button>
</div>
<br><br>
<a class="btn btn-primary" href="#" onclick="addItem();">Add to cart</a>
</div> <!-- /.span6 -->
</div> <!-- /.row -->
</div>
<!-- FOOTER -->
<footer>
<p class="pull-right"><a href="#">Back to top</a></p>
<p>© 2013 Company, Inc. · <a href="#">Privacy</a> · <a href="#">Terms</a></p>
</footer>
<script src="js/json.js"></script>
<script src="js/store.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
var g_nItems = 0;
var g_currentItem = undefined;
!function ($) {
$(function(){
store.clear();
// carousel demo
$('.carousel').carousel({
interval: 4000
});
})
}(window.jQuery)
function showFront(){
$("#myCarousel").show();
$(".marketing").show();
$(".details").addClass('hidden');
}
function showItemDetails(sku){
$("#myCarousel").hide();
$(".marketing").hide();
$(".details").removeClass('hidden');
loadSku(sku);
}
function addItem() {
g_nItems++;
$("#checkoutBtn").html('<i class="icon-shopping-cart"></i> Checkout ('+g_nItems+')');
g_currentItem.quantity = 1;
g_currentItem.fullsku = g_currentItem.sku+'-'+$(".btn-group > .btn.active").text();
var newsku = g_currentItem.fullsku;
if (store.get(newsku) != null){
var item = store.get(newsku);
item.quantity +=1;
store.set(newsku,item);
}else {
store.set(newsku,g_currentItem);
}
$('#checkoutBtn').popover();
var allItems = store.getAll();
var text="";
var price = 0;
$.each(allItems, function(i,item){
text+=item.name +' ('+item.fullsku + ") Qty: "+item.quantity+"<hr>";
price+=item.price;
});
$('#checkoutBtn[data-content]').attr("data-content",text);
$('#checkoutBtn[data-original-title]').attr("data-original-title","Shopping basket (price: "+price+" SEK)");
}
function loadSku(skuId) {
$.getJSON("item.php?",
{
sku : skuId,
format : "json"
},function(data) {
g_currentItem = data.item;
$("#shirtName").text(data.item.name);
$("#price").text(data.item.price+' SEK');
$("#desc").text(data.item.description);
}); //end callback function
}
function onCheckOut(){
$("#myCarousel").hide();
$(".marketing").hide();
$.ajax({
type: "POST",
url:"checkout.php"
}).done(function( msg ) {
$("#checkout").html(msg);
});
$("#checkout").removeClass('hidden');
}
</script>
</body>
</html> | mit |
mlechler/Bewerbungscoaching | resources/views/backend/layoutpurchases/detail.blade.php | 1103 | @extends('layouts.backend')
@section('title', 'Details of VALUE')
@section('content')
<table class="table table-hover">
<tbody>
<tr>
<td>
<h4>Member</h4>
</td>
<td>
<h4>{{ $layoutpurchase->member->getName() }}</h4>
</td>
</tr>
<tr>
<td>
<h4>Layout</h4>
</td>
<td>
<h4>{{ $layoutpurchase->applicationlayout->title }}</h4>
</td>
</tr>
<tr>
<td>
<h4>Price</h4>
</td>
<td>
<h4>{{ $layoutpurchase->price_incl_discount }} €</h4>
</td>
</tr>
<tr>
<td>
<h4>Paid</h4>
</td>
<td>
<h4><span class="glyphicon glyphicon-{{ $layoutpurchase->paid ? 'ok' : 'remove' }}"></span></h4>
</td>
</tr>
</tbody>
</table>
<a href="{{ route('layoutpurchases.index') }}" class="btn btn-danger">Back</a>
@endsection | mit |
abiosoft/caddy-git | github_hook.go | 3696 | package git
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
// GithubHook is webhook for Github.com.
type GithubHook struct{}
type ghRelease struct {
Action string `json:"action"`
Release struct {
TagName string `json:"tag_name"`
Name interface{} `json:"name"`
} `json:"release"`
}
type ghPush struct {
Ref string `json:"ref"`
}
// DoesHandle satisfies hookHandler.
func (g GithubHook) DoesHandle(h http.Header) bool {
userAgent := h.Get("User-Agent")
// GitHub always uses a user-agent like "GitHub-Hookshot/<id>"
if userAgent != "" && strings.HasPrefix(userAgent, "GitHub-Hookshot") {
return true
}
return false
}
// Handle satisfies hookHandler.
func (g GithubHook) Handle(w http.ResponseWriter, r *http.Request, repo *Repo) (int, error) {
if r.Method != "POST" {
return http.StatusMethodNotAllowed, errors.New("the request had an invalid method")
}
// read full body - required for signature
body, err := ioutil.ReadAll(r.Body)
err = g.handleSignature(r, body, repo.Hook.Secret)
if err != nil {
return http.StatusBadRequest, err
}
event := r.Header.Get("X-Github-Event")
if event == "" {
return http.StatusBadRequest, errors.New("the 'X-Github-Event' header is required but was missing")
}
switch event {
case "ping":
w.Write([]byte("pong"))
case "push":
err = g.handlePush(body, repo)
if !hookIgnored(err) && err != nil {
return http.StatusBadRequest, err
}
case "release":
err = g.handleRelease(body, repo)
if err != nil {
return http.StatusBadRequest, err
}
// return 400 if we do not handle the event type.
// This is to visually show the user a configuration error in the GH ui.
default:
return http.StatusBadRequest, nil
}
return http.StatusOK, err
}
// Check for an optional signature in the request
// if it is signed, verify the signature.
func (g GithubHook) handleSignature(r *http.Request, body []byte, secret string) error {
signature := r.Header.Get("X-Hub-Signature")
if signature != "" {
if secret == "" {
Logger().Print("Unable to verify request signature. Secret not set in caddyfile!\n")
} else {
mac := hmac.New(sha1.New, []byte(secret))
mac.Write(body)
expectedMac := hex.EncodeToString(mac.Sum(nil))
if signature[5:] != expectedMac {
return errors.New("could not verify request signature. The signature is invalid")
}
}
}
return nil
}
func (g GithubHook) handlePush(body []byte, repo *Repo) error {
var push ghPush
err := json.Unmarshal(body, &push)
if err != nil {
return err
}
// extract the branch being pushed from the ref string
// and if it matches with our locally tracked one, pull.
refSlice := strings.Split(push.Ref, "/")
if len(refSlice) != 3 {
return errors.New("the push request contained an invalid reference string")
}
branch := refSlice[2]
if branch != repo.Branch {
return hookIgnoredError{hookType: hookName(g), err: fmt.Errorf("found different branch %v", branch)}
}
Logger().Println("Received pull notification for the tracking branch, updating...")
repo.Pull()
return nil
}
func (g GithubHook) handleRelease(body []byte, repo *Repo) error {
var release ghRelease
err := json.Unmarshal(body, &release)
if err != nil {
return err
}
if release.Release.TagName == "" {
return errors.New("the release request contained an invalid TagName")
}
Logger().Printf("Received new release '%s'. -> Updating local repository to this release.\n", release.Release.Name)
// Update the local branch to the release tag name
// this will pull the release tag.
repo.Branch = release.Release.TagName
repo.Pull()
return nil
}
| mit |
cairn-software/jornet | src/server/server.js | 544 | import express from 'express';
import path from 'path';
import setupMiddleware from './middleware';
import logger from './logger';
const app = express();
setupMiddleware(app, {
outputPath: path.resolve(__dirname, '../../dist'),
publicPath: '/',
});
const PORT = process.env.PORT || 7347;
const HOST = process.env.HOST || null;
const prettyHost = HOST || 'localhost';
/* eslint consistent-return:0 */
app.listen(PORT, HOST, error => {
if (error) {
return logger.error(error.message);
}
logger.appStarted(PORT, prettyHost);
});
| mit |
Eleonore9/Elle-est-au-nord | elleestaunord/site.py | 764 | #!/env/bin/python
import os, sys
from flask import Flask, render_template, url_for
port = int(os.environ.get('PORT', 33507))
#heroku config:add PORT=33507
app = Flask(__name__)
app.config.update(
DEBUG = False,
)
# Simple site: just 3 routes for the Hone page and 2 pages
@app.route("/", methods=["GET"])
def index():
return render_template("index.html")
@app.route("/hireme", methods=["GET"])
def hireme():
return render_template("hireme.html")
@app.route("/aboutme", methods=["GET"])
def aboutme():
return render_template("aboutme.html")
@app.route("/projects", methods=["GET"])
def projects():
return render_template("projects.html")
if __name__ == "__main__":
# port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| mit |
xcjs/fetlife-oss | app/src/main/java/net/goldenspiral/fetlifeoss/cookie/SerializableHttpCookie.java | 6452 | package net.goldenspiral.fetlifeoss.cookie;
/*
* Copyright (c) 2011 James Smith <[email protected]>
* Copyright (c) 2015 Fran Montiel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Based on the code from this stackoverflow answer http://stackoverflow.com/a/25462286/980387 by janoliver
* Modifications in the structure of the class and addition of serialization of httpOnly attribute
*/
// MODIFIED FROM https://gist.github.com/franmontiel/ed12a2295566b7076161
import android.util.Log;
import net.goldenspiral.fetlifeoss.FetLife;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.net.HttpCookie;
public class SerializableHttpCookie implements Serializable {
private static final long serialVersionUID = 6374381323722046732L;
private transient HttpCookie cookie;
// Workaround httpOnly: The httpOnly attribute is not accessible so when we
// serialize and deserialize the cookie it not preserve the same value. We
// need to access it using reflection
private Field fieldHttpOnly;
public SerializableHttpCookie() {
}
public String encode(HttpCookie cookie) {
this.cookie = cookie;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(this);
} catch (IOException e) {
Log.d(FetLife.TAG, "IOException in encodeCookie", e);
return null;
}
return byteArrayToHexString(os.toByteArray());
}
public HttpCookie decode(String encodedCookie) {
byte[] bytes = hexStringToByteArray(encodedCookie);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
bytes);
HttpCookie cookie = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(
byteArrayInputStream);
cookie = ((SerializableHttpCookie) objectInputStream.readObject()).cookie;
} catch (IOException e) {
Log.d(FetLife.TAG, "IOException in decodeCookie", e);
} catch (ClassNotFoundException e) {
Log.d(FetLife.TAG, "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
// Workaround httpOnly (getter)
private boolean getHttpOnly() {
try {
initFieldHttpOnly();
return (boolean) fieldHttpOnly.get(cookie);
} catch (Exception e) {
// NoSuchFieldException || IllegalAccessException ||
// IllegalArgumentException
Log.w(FetLife.TAG, e);
}
return false;
}
// Workaround httpOnly (setter)
private void setHttpOnly(boolean httpOnly) {
try {
initFieldHttpOnly();
fieldHttpOnly.set(cookie, httpOnly);
} catch (Exception e) {
// NoSuchFieldException || IllegalAccessException ||
// IllegalArgumentException
Log.w(FetLife.TAG, e);
}
}
private void initFieldHttpOnly() throws NoSuchFieldException {
fieldHttpOnly = cookie.getClass().getDeclaredField("httpOnly");
fieldHttpOnly.setAccessible(true);
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookie.getName());
out.writeObject(cookie.getValue());
out.writeObject(cookie.getComment());
out.writeObject(cookie.getCommentURL());
out.writeObject(cookie.getDomain());
out.writeLong(cookie.getMaxAge());
out.writeObject(cookie.getPath());
out.writeObject(cookie.getPortlist());
out.writeInt(cookie.getVersion());
out.writeBoolean(cookie.getSecure());
out.writeBoolean(cookie.getDiscard());
out.writeBoolean(getHttpOnly());
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
cookie = new HttpCookie(name, value);
cookie.setComment((String) in.readObject());
cookie.setCommentURL((String) in.readObject());
cookie.setDomain((String) in.readObject());
cookie.setMaxAge(in.readLong());
cookie.setPath((String) in.readObject());
cookie.setPortlist((String) in.readObject());
cookie.setVersion(in.readInt());
cookie.setSecure(in.readBoolean());
cookie.setDiscard(in.readBoolean());
setHttpOnly(in.readBoolean());
}
/**
* Using some super basic byte array <-> hex conversions so we don't
* have to rely on any large Base64 libraries. Can be overridden if you
* like!
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
private String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes) {
int v = element & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString();
}
/**
* Converts hex values from strings to byte array
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
private byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
.digit(hexString.charAt(i + 1), 16));
}
return data;
}
} | mit |
gorelikov/testcontainers-java | core/src/main/java/org/testcontainers/images/builder/ImageFromDockerfile.java | 5941 | package org.testcontainers.images.builder;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.BuildImageCmd;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.model.BuildResponseItem;
import com.github.dockerjava.core.command.BuildImageResultCallback;
import com.google.common.collect.Sets;
import lombok.Cleanup;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.profiler.Profiler;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.images.builder.traits.*;
import org.testcontainers.utility.Base58;
import org.testcontainers.utility.DockerLoggerFactory;
import org.testcontainers.utility.LazyFuture;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPOutputStream;
@Slf4j
@Getter
public class ImageFromDockerfile extends LazyFuture<String> implements
BuildContextBuilderTrait<ImageFromDockerfile>,
ClasspathTrait<ImageFromDockerfile>,
FilesTrait<ImageFromDockerfile>,
StringsTrait<ImageFromDockerfile>,
DockerfileTrait<ImageFromDockerfile> {
private static final Set<String> imagesToDelete = Sets.newConcurrentHashSet();
static {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
DockerClient dockerClientForCleaning = DockerClientFactory.instance().client();
try {
for (String dockerImageName : imagesToDelete) {
log.info("Removing image tagged {}", dockerImageName);
try {
dockerClientForCleaning.removeImageCmd(dockerImageName).withForce(true).exec();
} catch (Throwable e) {
log.warn("Unable to delete image " + dockerImageName, e);
}
}
} catch (DockerClientException e) {
throw new RuntimeException(e);
}
}));
}
private final String dockerImageName;
private boolean deleteOnExit = true;
private final Map<String, Transferable> transferables = new HashMap<>();
public ImageFromDockerfile() {
this("testcontainers/" + Base58.randomString(16).toLowerCase());
}
public ImageFromDockerfile(String dockerImageName) {
this(dockerImageName, true);
}
public ImageFromDockerfile(String dockerImageName, boolean deleteOnExit) {
this.dockerImageName = dockerImageName;
this.deleteOnExit = deleteOnExit;
}
@Override
public ImageFromDockerfile withFileFromTransferable(String path, Transferable transferable) {
Transferable oldValue = transferables.put(path, transferable);
if (oldValue != null) {
log.warn("overriding previous mapping for '{}'", path);
}
return this;
}
@Override
protected final String resolve() {
Logger logger = DockerLoggerFactory.getLogger(dockerImageName);
Profiler profiler = new Profiler("Rule creation - build image");
profiler.setLogger(logger);
DockerClient dockerClient = DockerClientFactory.instance().client();
try {
if (deleteOnExit) {
imagesToDelete.add(dockerImageName);
}
BuildImageResultCallback resultCallback = new BuildImageResultCallback() {
@Override
public void onNext(BuildResponseItem item) {
super.onNext(item);
if (item.isErrorIndicated()) {
logger.error(item.getErrorDetail().getMessage());
} else {
logger.debug(StringUtils.chomp(item.getStream(), "\n"));
}
}
};
// We have to use pipes to avoid high memory consumption since users might want to build really big images
@Cleanup PipedInputStream in = new PipedInputStream();
@Cleanup PipedOutputStream out = new PipedOutputStream(in);
profiler.start("Configure image");
BuildImageCmd buildImageCmd = dockerClient.buildImageCmd(in);
configure(buildImageCmd);
profiler.start("Build image");
BuildImageResultCallback exec = buildImageCmd.exec(resultCallback);
// To build an image, we have to send the context to Docker in TAR archive format
profiler.start("Send context as TAR");
try (TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(new GZIPOutputStream(out))) {
for (Map.Entry<String, Transferable> entry : transferables.entrySet()) {
TarArchiveEntry tarEntry = new TarArchiveEntry(entry.getKey());
Transferable transferable = entry.getValue();
tarEntry.setSize(transferable.getSize());
tarEntry.setMode(transferable.getFileMode());
tarArchive.putArchiveEntry(tarEntry);
transferable.transferTo(tarArchive);
tarArchive.closeArchiveEntry();
}
tarArchive.finish();
}
profiler.start("Wait for an image id");
exec.awaitImageId();
return dockerImageName;
} catch(IOException e) {
throw new RuntimeException("Can't close DockerClient", e);
} finally {
profiler.stop().log();
}
}
protected void configure(BuildImageCmd buildImageCmd) {
buildImageCmd.withTag(this.getDockerImageName());
}
}
| mit |
handcraftsman/QIFGet | src/QIFGet/MvbaCore/CodeQuery/MemberInfoExtensions.cs | 935 | // * **************************************************************************
// * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace QIFGet.MvbaCore.CodeQuery
{
internal static class MemberInfoExtensions
{
internal static IEnumerable<T> CustomAttributesOfType<T>(this MemberInfo input) where T : Attribute
{
return input.GetCustomAttributes(typeof(T), true).Cast<T>();
}
}
} | mit |
HlebForms/SchoolSystemProject | SchoolSystem/SchoolSystem.Data/Contracts/IUnitOfWork.cs | 142 | using System;
namespace SchoolSystem.Data.Contracts
{
public interface IUnitOfWork : IDisposable
{
bool Commit();
}
}
| mit |
juanleal/perfilResolve | app/Http/Controllers/EventosController.php | 3491 | <?php
namespace Camp\Http\Controllers;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Camp\Http\Requests;
use Camp\Eventos;
use Tymon\JWTAuth\JWTAuth;
use Camp\Http\Controllers\Crypt;
use Hash;
class EventosController extends Controller {
private $req;
private $eventos;
private $jwtAuth;
function __construct(Request $request, Eventos $eventos, ResponseFactory $responseFactory, JWTAuth $jwtAuth) {
$this->req = $request;
$this->eventos = $eventos;
$this->res = $responseFactory;
$this->jwtAuth = $jwtAuth;
$this->middleware('jwtauth');
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index() {
//
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create() {
//
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store() {
$reqFoto = $this->req->all();
$user = new Eventos($reqFoto);
if (!$user->save()) {
abort(500, 'Could not save evento.');
}
$user['token'] = $this->jwtAuth->fromUser($user);
return $user;
}
/**
* Display the specified resource.
*
* @param int $user_id
* @return Response
*/
public function show($user_id) {
$fotos = Eventos::where('user_id', '=', $user_id)->get();
/* $arrFotos = [];
for ($i = 0; $i < count($fotos); $i++) {
$arrFotos[$i]['imagen'] = $fotos[$i]->imagen;
} */
return json_encode($fotos);
}
/*
* Consulta los próximos eventos de un usuario
*/
public function proximos() {
$user_id = $this->req->input('userId');
$proximos = Eventos::where('user_id', '=', $user_id)->where('start', '>=', date('Y-m-d'))->get();
return json_encode($proximos);
}
/*
* Verifica cuantos eventos ha asistido un usuario
*/
public function asistidos() {
$user_id = $this->req->input('userId');
$fechaFinal = date('Y-m-d');
$fechaInicial = date('Y-m-d', strtotime('-1 month', strtotime($fechaFinal)));
$asistidos = Eventos::where('user_id', '=', $user_id)
->where('asistio', '=', true)
->where(function($query) use ($fechaInicial, $fechaFinal) {
$query->where('start', '>=', $fechaInicial)
->where('start', '<', $fechaFinal);
})
->get();
return json_encode($asistidos);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id) {
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update() {
$id = $this->req->input('id');
$post = Eventos::find((int) $id);
$post->asistio = $this->req->input('asistio');
if (!$post->save()) {
abort(500, "Saving failed");
}
return $post;
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id) {
return Eventos::destroy($id);
}
}
| mit |
fmdjs/fmd.js | test/specs/remote/f2.js | 88 | define( 'specs/remote/f2', ['specs/remote/f21'], function( F21 ){ return F21+'f2'; } );
| mit |
ISKU/Algorithm | BOJ/7569/Main.java | 2168 | /*
* Author: Minho Kim (ISKU)
* Date: January 22, 2018
* E-mail: [email protected]
*
* https://github.com/ISKU/Algorithm
* https://www.acmicpc.net/problem/7569
*/
import java.util.*;
public class Main {
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
int X = sc.nextInt();
int Y = sc.nextInt();
int Z = sc.nextInt();
Queue<Tomato> queue = new LinkedList<Tomato>();
int[][][] map = new int[Z][Y][X];
int count = 0, empty = 0;
for (int z = 0; z < Z; z++) {
for (int y = 0; y < Y; y++) {
for (int x = 0; x < X; x++) {
map[z][y][x] = sc.nextInt();
if (map[z][y][x] == 1) {
queue.add(new Tomato(z, y, x, 0));
count++;
}
if (map[z][y][x] == -1)
empty++;
}
}
}
if (count == Z * Y * X - empty) {
System.out.print(0);
System.exit(0);
}
while (!queue.isEmpty()) {
Tomato tomato = queue.poll();
int z = tomato.z;
int y = tomato.y;
int x = tomato.x;
int step = tomato.step;
if (x - 1 >= 0 && map[z][y][x - 1] == 0) {
map[z][y][x - 1] = 1;
queue.add(new Tomato(z, y, x - 1, step + 1));
count++;
}
if (x + 1 < X && map[z][y][x + 1] == 0) {
map[z][y][x + 1] = 1;
queue.add(new Tomato(z, y, x + 1, step + 1));
count++;
}
if (y - 1 >= 0 && map[z][y - 1][x] == 0) {
map[z][y - 1][x] = 1;
queue.add(new Tomato(z, y - 1, x, step + 1));
count++;
}
if (y + 1 < Y && map[z][y + 1][x] == 0) {
map[z][y + 1][x] = 1;
queue.add(new Tomato(z, y + 1, x, step + 1));
count++;
}
if (z - 1 >= 0 && map[z - 1][y][x] == 0) {
map[z - 1][y][x] = 1;
queue.add(new Tomato(z - 1, y, x, step + 1));
count++;
}
if (z + 1 < Z && map[z + 1][y][x] == 0) {
map[z + 1][y][x] = 1;
queue.add(new Tomato(z + 1, y, x, step + 1));
count++;
}
if (count == Z * Y * X - empty) {
System.out.print(step + 1);
System.exit(0);
}
}
System.out.print(-1);
}
private static class Tomato {
public int z, y, x;
public int step;
public Tomato(int z, int y, int x, int step) {
this.z = z;
this.y = y;
this.x = x;
this.step = step;
}
}
} | mit |
camsys/transam_core | app/jobs/asset_schedule_disposition_update_job.rb | 700 | # --------------------------------
# # DEPRECATED see TTPLAT-1832 or https://wiki.camsys.com/pages/viewpage.action?pageId=51183790
# --------------------------------
#------------------------------------------------------------------------------
#
# AssetScheduleDispositionUpdateJob
#
# Updates an assets scheduled disposition
#
#------------------------------------------------------------------------------
class AssetScheduleDispositionUpdateJob < AbstractAssetUpdateJob
def execute_job(asset)
asset.update_scheduled_disposition
end
def prepare
Rails.logger.debug "Executing AssetScheduleDispositionUpdateJob at #{Time.now.to_s} for Asset #{object_key}"
end
end | mit |
misshie/bioruby-ucsc-api | lib/bio-ucsc/mm9/chainrn4.rb | 3076 | # Copyright::
# Copyright (C) 2011 MISHIMA, Hiroyuki <missy at be.to / hmishima at nagasaki-u.ac.jp>
# License:: The Ruby licence (Ryby's / GPLv2 dual)
#
# In the hg18 database, this table is actually separated
# into "chr1_*", "chr2_*", etc. This class dynamically
# define *::Chr1_*, *::Chr2_*, etc. The
# Rmsk.find_by_interval calls an appropreate class automatically.
module Bio
module Ucsc
module Mm9
class ChainRn4
KLASS = "ChainRn4"
KLASS_S = "chainRn4"
Bio::Ucsc::Mm9::CHROMS.each do |chr|
class_eval %!
class #{chr[0..0].upcase + chr[1..-1]}_#{KLASS} < DBConnection
self.table_name = "#{chr[0..0].downcase + chr[1..-1]}_#{KLASS_S}"
self.primary_key = nil
self.inheritance_column = nil
def self.find_by_interval(interval, opt = {:partial => true}); interval = Bio::Ucsc::Gi.wrap(interval)
find_first_or_all_by_interval(interval, :first, opt)
end
def self.find_all_by_interval(interval, opt = {:partial => true}); interval = Bio::Ucsc::Gi.wrap(interval)
find_first_or_all_by_interval(interval, :all, opt)
end
def self.find_first_or_all_by_interval(interval, first_all, opt); interval = Bio::Ucsc::Gi.wrap(interval)
zstart = interval.zero_start
zend = interval.zero_end
if opt[:partial] == true
where = <<-SQL
tName = :chrom
AND bin in (:bins)
AND ((tStart BETWEEN :zstart AND :zend)
OR (tEnd BETWEEN :zstart AND :zend)
OR (tStart <= :zstart AND tEnd >= :zend))
SQL
else
where = <<-SQL
tName = :chrom
AND bin in (:bins)
AND ((tStart BETWEEN :zstart AND :zend)
AND (tEnd BETWEEN :zstart AND :zend))
SQL
end
cond = {
:chrom => interval.chrom,
:bins => Bio::Ucsc::UcscBin.bin_all(zstart, zend),
:zstart => zstart,
:zend => zend,
}
self.find(first_all,
{ :select => "*",
:conditions => [where, cond], })
end
end
!
end # each chromosome
def self.find_by_interval(interval, opt = {:partial => true}); interval = Bio::Ucsc::Gi.wrap(interval)
chrom = interval.chrom[0..0].upcase + interval.chrom[1..-1]
chr_klass = self.const_get("#{chrom}_#{KLASS}")
chr_klass.__send__(:find_by_interval, interval, opt)
end
def self.find_all_by_interval(interval, opt = {:partial => true}); interval = Bio::Ucsc::Gi.wrap(interval)
chrom = interval.chrom[0..0].upcase + interval.chrom[1..-1]
chr_klass = self.const_get("#{chrom}_#{KLASS}")
chr_klass.__send__(:find_all_by_interval, interval, opt)
end
end # class
end # module Hg18
end # module Ucsc
end # module Bio
| mit |
koobonil/Boss2D | Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/rtp_rtcp/source/rtcp_packet/bye.cc | 4803 | /*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/rtp_rtcp/source/rtcp_packet/bye.h"
#include <utility>
#include "modules/rtp_rtcp/source/byte_io.h"
#include "modules/rtp_rtcp/source/rtcp_packet/common_header.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h"
namespace webrtc {
namespace rtcp {
constexpr uint8_t Bye::kPacketType;
// Bye packet (BYE) (RFC 3550).
//
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |V=2|P| SC | PT=BYE=203 | length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | SSRC/CSRC |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// : ... :
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
// (opt) | length | reason for leaving ...
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Bye::Bye() : sender_ssrc_(0) {}
Bye::~Bye() = default;
bool Bye::Parse(const CommonHeader& packet) {
RTC_DCHECK_EQ(packet.type(), kPacketType);
const uint8_t src_count = packet.count();
// Validate packet.
if (packet.payload_size_bytes() < 4u * src_count) {
RTC_LOG(LS_WARNING)
<< "Packet is too small to contain CSRCs it promise to have.";
return false;
}
const uint8_t* const payload = packet.payload();
bool has_reason = packet.payload_size_bytes() > 4u * src_count;
uint8_t reason_length = 0;
if (has_reason) {
reason_length = payload[4u * src_count];
if (packet.payload_size_bytes() - 4u * src_count < 1u + reason_length) {
RTC_LOG(LS_WARNING) << "Invalid reason length: " << reason_length;
return false;
}
}
// Once sure packet is valid, copy values.
if (src_count == 0) { // A count value of zero is valid, but useless.
sender_ssrc_ = 0;
csrcs_.clear();
} else {
sender_ssrc_ = ByteReader<uint32_t>::ReadBigEndian(payload);
csrcs_.resize(src_count - 1);
for (size_t i = 1; i < src_count; ++i)
csrcs_[i - 1] = ByteReader<uint32_t>::ReadBigEndian(&payload[4 * i]);
}
if (has_reason) {
reason_.assign(reinterpret_cast<const char*>(&payload[4u * src_count + 1]),
reason_length);
} else {
reason_.clear();
}
return true;
}
bool Bye::Create(uint8_t* packet,
size_t* index,
size_t max_length,
PacketReadyCallback callback) const {
while (*index + BlockLength() > max_length) {
if (!OnBufferFull(packet, index, callback))
return false;
}
const size_t index_end = *index + BlockLength();
CreateHeader(1 + csrcs_.size(), kPacketType, HeaderLength(), packet, index);
// Store srcs of the leaving clients.
ByteWriter<uint32_t>::WriteBigEndian(&packet[*index], sender_ssrc_);
*index += sizeof(uint32_t);
for (uint32_t csrc : csrcs_) {
ByteWriter<uint32_t>::WriteBigEndian(&packet[*index], csrc);
*index += sizeof(uint32_t);
}
// Store the reason to leave.
if (!reason_.empty()) {
uint8_t reason_length = static_cast<uint8_t>(reason_.size());
packet[(*index)++] = reason_length;
memcpy(&packet[*index], reason_.data(), reason_length);
*index += reason_length;
// Add padding bytes if needed.
size_t bytes_to_pad = index_end - *index;
RTC_DCHECK_LE(bytes_to_pad, 3);
if (bytes_to_pad > 0) {
memset(&packet[*index], 0, bytes_to_pad);
*index += bytes_to_pad;
}
}
RTC_DCHECK_EQ(index_end, *index);
return true;
}
bool Bye::SetCsrcs(std::vector<uint32_t> csrcs) {
if (csrcs.size() > kMaxNumberOfCsrcs) {
RTC_LOG(LS_WARNING) << "Too many CSRCs for Bye packet.";
return false;
}
csrcs_ = std::move(csrcs);
return true;
}
void Bye::SetReason(std::string reason) {
RTC_DCHECK_LE(reason.size(), 0xffu);
reason_ = std::move(reason);
}
size_t Bye::BlockLength() const {
size_t src_count = (1 + csrcs_.size());
size_t reason_size_in_32bits = reason_.empty() ? 0 : (reason_.size() / 4 + 1);
return kHeaderLength + 4 * (src_count + reason_size_in_32bits);
}
} // namespace rtcp
} // namespace webrtc
| mit |
goldenratio/youtube-to-XBMC | src/js/background_scripts/sites/default.js | 1896 | ;(function(player)
{
class DefaultSite extends AbstractSite
{
constructor(player)
{
super(player);
console.log("DefaultSite");
let customExtensions = [
"/videoplayback?"
];
let videoExtensions = [
"mp4",
"mov",
"webm",
"3gp",
"flv",
"avi",
"ogv",
"wmv",
"asf",
"mkv",
"m4v"
];
let audioExtensions = [
"mp3",
"ogg",
"midi",
"wav",
"aiff",
"aac",
"flac",
"ape",
"wma",
"m4a",
"mka"
];
let validExtensions = [... videoExtensions, ... audioExtensions];
let contextMenuFilterList = [];
let browserActionFilterList = [];
for (let extension of validExtensions) {
let contextItem = "*://*/*." + extension + "*";
contextMenuFilterList.push(contextItem);
let actionItem = ".*\\." + extension + ".*";
browserActionFilterList.push(actionItem);
}
for (let extension of customExtensions) {
let actionItem = ".*" + extension + ".*";
browserActionFilterList.push(actionItem);
}
contextMenu.addSite("default", this, contextMenuFilterList);
browserAction.addSite("default", this, browserActionFilterList);
}
getFileFromUrl(url)
{
return new Promise((resolve, reject) => {
resolve(url);
});
}
}
new DefaultSite(player)
})(player); | mit |
ruslana-net/ai-gallery | src/Ai/GalleryBundle/Resources/assets/components/fineuploader-dist/dist/azure.fine-uploader.js | 411723 | /*!
* Fine Uploader
*
* Copyright 2015, Widen Enterprises, Inc. [email protected]
*
* Version: 5.1.3
*
* Homepage: http://fineuploader.com
*
* Repository: git://github.com/Widen/fine-uploader.git
*
* Licensed only under the Widen Commercial License (http://fineuploader.com/licensing).
*/
/*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob, Storage, ActiveXObject */
/* jshint -W079 */
var qq = function(element) {
"use strict";
return {
hide: function() {
element.style.display = "none";
return this;
},
/** Returns the function which detaches attached event */
attach: function(type, fn) {
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, fn);
}
return function() {
qq(element).detach(type, fn);
};
},
detach: function(type, fn) {
if (element.removeEventListener) {
element.removeEventListener(type, fn, false);
} else if (element.attachEvent) {
element.detachEvent("on" + type, fn);
}
return this;
},
contains: function(descendant) {
// The [W3C spec](http://www.w3.org/TR/domcore/#dom-node-contains)
// says a `null` (or ostensibly `undefined`) parameter
// passed into `Node.contains` should result in a false return value.
// IE7 throws an exception if the parameter is `undefined` though.
if (!descendant) {
return false;
}
// compareposition returns false in this case
if (element === descendant) {
return true;
}
if (element.contains) {
return element.contains(descendant);
} else {
/*jslint bitwise: true*/
return !!(descendant.compareDocumentPosition(element) & 8);
}
},
/**
* Insert this element before elementB.
*/
insertBefore: function(elementB) {
elementB.parentNode.insertBefore(element, elementB);
return this;
},
remove: function() {
element.parentNode.removeChild(element);
return this;
},
/**
* Sets styles for an element.
* Fixes opacity in IE6-8.
*/
css: function(styles) {
/*jshint eqnull: true*/
if (element.style == null) {
throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!");
}
/*jshint -W116*/
if (styles.opacity != null) {
if (typeof element.style.opacity !== "string" && typeof (element.filters) !== "undefined") {
styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")";
}
}
qq.extend(element.style, styles);
return this;
},
hasClass: function(name) {
var re = new RegExp("(^| )" + name + "( |$)");
return re.test(element.className);
},
addClass: function(name) {
if (!qq(element).hasClass(name)) {
element.className += " " + name;
}
return this;
},
removeClass: function(name) {
var re = new RegExp("(^| )" + name + "( |$)");
element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, "");
return this;
},
getByClass: function(className) {
var candidates,
result = [];
if (element.querySelectorAll) {
return element.querySelectorAll("." + className);
}
candidates = element.getElementsByTagName("*");
qq.each(candidates, function(idx, val) {
if (qq(val).hasClass(className)) {
result.push(val);
}
});
return result;
},
children: function() {
var children = [],
child = element.firstChild;
while (child) {
if (child.nodeType === 1) {
children.push(child);
}
child = child.nextSibling;
}
return children;
},
setText: function(text) {
element.innerText = text;
element.textContent = text;
return this;
},
clearText: function() {
return qq(element).setText("");
},
// Returns true if the attribute exists on the element
// AND the value of the attribute is NOT "false" (case-insensitive)
hasAttribute: function(attrName) {
var attrVal;
if (element.hasAttribute) {
if (!element.hasAttribute(attrName)) {
return false;
}
/*jshint -W116*/
return (/^false$/i).exec(element.getAttribute(attrName)) == null;
}
else {
attrVal = element[attrName];
if (attrVal === undefined) {
return false;
}
/*jshint -W116*/
return (/^false$/i).exec(attrVal) == null;
}
}
};
};
(function() {
"use strict";
qq.canvasToBlob = function(canvas, mime, quality) {
return qq.dataUriToBlob(canvas.toDataURL(mime, quality));
};
qq.dataUriToBlob = function(dataUri) {
var arrayBuffer, byteString,
createBlob = function(data, mime) {
var BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder,
blobBuilder = BlobBuilder && new BlobBuilder();
if (blobBuilder) {
blobBuilder.append(data);
return blobBuilder.getBlob(mime);
}
else {
return new Blob([data], {type: mime});
}
},
intArray, mimeString;
// convert base64 to raw binary data held in a string
if (dataUri.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataUri.split(",")[1]);
}
else {
byteString = decodeURI(dataUri.split(",")[1]);
}
// extract the MIME
mimeString = dataUri.split(",")[0]
.split(":")[1]
.split(";")[0];
// write the bytes of the binary string to an ArrayBuffer
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
qq.each(byteString, function(idx, character) {
intArray[idx] = character.charCodeAt(0);
});
return createBlob(arrayBuffer, mimeString);
};
qq.log = function(message, level) {
if (window.console) {
if (!level || level === "info") {
window.console.log(message);
}
else
{
if (window.console[level]) {
window.console[level](message);
}
else {
window.console.log("<" + level + "> " + message);
}
}
}
};
qq.isObject = function(variable) {
return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]";
};
qq.isFunction = function(variable) {
return typeof (variable) === "function";
};
/**
* Check the type of a value. Is it an "array"?
*
* @param value value to test.
* @returns true if the value is an array or associated with an `ArrayBuffer`
*/
qq.isArray = function(value) {
return Object.prototype.toString.call(value) === "[object Array]" ||
(value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer);
};
// Looks for an object on a `DataTransfer` object that is associated with drop events when utilizing the Filesystem API.
qq.isItemList = function(maybeItemList) {
return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]";
};
// Looks for an object on a `NodeList` or an `HTMLCollection`|`HTMLFormElement`|`HTMLSelectElement`
// object that is associated with collections of Nodes.
qq.isNodeList = function(maybeNodeList) {
return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" ||
// If `HTMLCollection` is the actual type of the object, we must determine this
// by checking for expected properties/methods on the object
(maybeNodeList.item && maybeNodeList.namedItem);
};
qq.isString = function(maybeString) {
return Object.prototype.toString.call(maybeString) === "[object String]";
};
qq.trimStr = function(string) {
if (String.prototype.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g, "");
};
/**
* @param str String to format.
* @returns {string} A string, swapping argument values with the associated occurrence of {} in the passed string.
*/
qq.format = function(str) {
var args = Array.prototype.slice.call(arguments, 1),
newStr = str,
nextIdxToReplace = newStr.indexOf("{}");
qq.each(args, function(idx, val) {
var strBefore = newStr.substring(0, nextIdxToReplace),
strAfter = newStr.substring(nextIdxToReplace + 2);
newStr = strBefore + val + strAfter;
nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length);
// End the loop if we have run out of tokens (when the arguments exceed the # of tokens)
if (nextIdxToReplace < 0) {
return false;
}
});
return newStr;
};
qq.isFile = function(maybeFile) {
return window.File && Object.prototype.toString.call(maybeFile) === "[object File]";
};
qq.isFileList = function(maybeFileList) {
return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]";
};
qq.isFileOrInput = function(maybeFileOrInput) {
return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput);
};
qq.isInput = function(maybeInput, notFile) {
var evaluateType = function(type) {
var normalizedType = type.toLowerCase();
if (notFile) {
return normalizedType !== "file";
}
return normalizedType === "file";
};
if (window.HTMLInputElement) {
if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") {
if (maybeInput.type && evaluateType(maybeInput.type)) {
return true;
}
}
}
if (maybeInput.tagName) {
if (maybeInput.tagName.toLowerCase() === "input") {
if (maybeInput.type && evaluateType(maybeInput.type)) {
return true;
}
}
}
return false;
};
qq.isBlob = function(maybeBlob) {
if (window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]") {
return true;
}
};
qq.isXhrUploadSupported = function() {
var input = document.createElement("input");
input.type = "file";
return (
input.multiple !== undefined &&
typeof File !== "undefined" &&
typeof FormData !== "undefined" &&
typeof (qq.createXhrInstance()).upload !== "undefined");
};
// Fall back to ActiveX is native XHR is disabled (possible in any version of IE).
qq.createXhrInstance = function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (error) {
qq.log("Neither XHR or ActiveX are supported!", "error");
return null;
}
};
qq.isFolderDropSupported = function(dataTransfer) {
return dataTransfer.items &&
dataTransfer.items.length > 0 &&
dataTransfer.items[0].webkitGetAsEntry;
};
qq.isFileChunkingSupported = function() {
return !qq.androidStock() && //Android's stock browser cannot upload Blobs correctly
qq.isXhrUploadSupported() &&
(File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined);
};
qq.sliceBlob = function(fileOrBlob, start, end) {
var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice;
return slicer.call(fileOrBlob, start, end);
};
qq.arrayBufferToHex = function(buffer) {
var bytesAsHex = "",
bytes = new Uint8Array(buffer);
qq.each(bytes, function(idx, byt) {
var byteAsHexStr = byt.toString(16);
if (byteAsHexStr.length < 2) {
byteAsHexStr = "0" + byteAsHexStr;
}
bytesAsHex += byteAsHexStr;
});
return bytesAsHex;
};
qq.readBlobToHex = function(blob, startOffset, length) {
var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length),
fileReader = new FileReader(),
promise = new qq.Promise();
fileReader.onload = function() {
promise.success(qq.arrayBufferToHex(fileReader.result));
};
fileReader.onerror = promise.failure;
fileReader.readAsArrayBuffer(initialBlob);
return promise;
};
qq.extend = function(first, second, extendNested) {
qq.each(second, function(prop, val) {
if (extendNested && qq.isObject(val)) {
if (first[prop] === undefined) {
first[prop] = {};
}
qq.extend(first[prop], val, true);
}
else {
first[prop] = val;
}
});
return first;
};
/**
* Allow properties in one object to override properties in another,
* keeping track of the original values from the target object.
*
* Album that the pre-overriden properties to be overriden by the source will be passed into the `sourceFn` when it is invoked.
*
* @param target Update properties in this object from some source
* @param sourceFn A function that, when invoked, will return properties that will replace properties with the same name in the target.
* @returns {object} The target object
*/
qq.override = function(target, sourceFn) {
var super_ = {},
source = sourceFn(super_);
qq.each(source, function(srcPropName, srcPropVal) {
if (target[srcPropName] !== undefined) {
super_[srcPropName] = target[srcPropName];
}
target[srcPropName] = srcPropVal;
});
return target;
};
/**
* Searches for a given element in the array, returns -1 if it is not present.
* @param {Number} [from] The index at which to begin the search
*/
qq.indexOf = function(arr, elt, from) {
if (arr.indexOf) {
return arr.indexOf(elt, from);
}
from = from || 0;
var len = arr.length;
if (from < 0) {
from += len;
}
for (; from < len; from += 1) {
if (arr.hasOwnProperty(from) && arr[from] === elt) {
return from;
}
}
return -1;
};
//this is a version 4 UUID
qq.getUniqueId = function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
/*jslint eqeq: true, bitwise: true*/
var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
//
// Browsers and platforms detection
qq.ie = function() {
return navigator.userAgent.indexOf("MSIE") !== -1 ||
navigator.userAgent.indexOf("Trident") !== -1;
};
qq.ie7 = function() {
return navigator.userAgent.indexOf("MSIE 7") !== -1;
};
qq.ie8 = function() {
return navigator.userAgent.indexOf("MSIE 8") !== -1;
};
qq.ie10 = function() {
return navigator.userAgent.indexOf("MSIE 10") !== -1;
};
qq.ie11 = function() {
return qq.ie() && navigator.userAgent.indexOf("rv:11") !== -1;
};
qq.safari = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1;
};
qq.chrome = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1;
};
qq.opera = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1;
};
qq.firefox = function() {
return (!qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === "");
};
qq.windows = function() {
return navigator.platform === "Win32";
};
qq.android = function() {
return navigator.userAgent.toLowerCase().indexOf("android") !== -1;
};
// We need to identify the Android stock browser via the UA string to work around various bugs in this browser,
// such as the one that prevents a `Blob` from being uploaded.
qq.androidStock = function() {
return qq.android() && navigator.userAgent.toLowerCase().indexOf("chrome") < 0;
};
qq.ios6 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 6_") !== -1;
};
qq.ios7 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1;
};
qq.ios8 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 8_") !== -1;
};
// iOS 8.0.0
qq.ios800 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 8_0 ") !== -1;
};
qq.ios = function() {
/*jshint -W014 */
return navigator.userAgent.indexOf("iPad") !== -1
|| navigator.userAgent.indexOf("iPod") !== -1
|| navigator.userAgent.indexOf("iPhone") !== -1;
};
qq.iosChrome = function() {
return qq.ios() && navigator.userAgent.indexOf("CriOS") !== -1;
};
qq.iosSafari = function() {
return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf("Safari") !== -1;
};
qq.iosSafariWebView = function() {
return qq.ios() && !qq.iosChrome() && !qq.iosSafari();
};
//
// Events
qq.preventDefault = function(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
};
/**
* Creates and returns element from html string
* Uses innerHTML to create an element
*/
qq.toElement = (function() {
var div = document.createElement("div");
return function(html) {
div.innerHTML = html;
var element = div.firstChild;
div.removeChild(element);
return element;
};
}());
//key and value are passed to callback for each entry in the iterable item
qq.each = function(iterableItem, callback) {
var keyOrIndex, retVal;
if (iterableItem) {
// Iterate through [`Storage`](http://www.w3.org/TR/webstorage/#the-storage-interface) items
if (window.Storage && iterableItem.constructor === window.Storage) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex)));
if (retVal === false) {
break;
}
}
}
// `DataTransferItemList` & `NodeList` objects are array-like and should be treated as arrays
// when iterating over items inside the object.
else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
if (retVal === false) {
break;
}
}
}
else if (qq.isString(iterableItem)) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex));
if (retVal === false) {
break;
}
}
}
else {
for (keyOrIndex in iterableItem) {
if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) {
retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
if (retVal === false) {
break;
}
}
}
}
}
};
//include any args that should be passed to the new function after the context arg
qq.bind = function(oldFunc, context) {
if (qq.isFunction(oldFunc)) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
var newArgs = qq.extend([], args);
if (arguments.length) {
newArgs = newArgs.concat(Array.prototype.slice.call(arguments));
}
return oldFunc.apply(context, newArgs);
};
}
throw new Error("first parameter must be a function!");
};
/**
* obj2url() takes a json-object as argument and generates
* a querystring. pretty much like jQuery.param()
*
* how to use:
*
* `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
*
* will result in:
*
* `http://any.url/upload?otherParam=value&a=b&c=d`
*
* @param Object JSON-Object
* @param String current querystring-part
* @return String encoded querystring
*/
qq.obj2url = function(obj, temp, prefixDone) {
/*jshint laxbreak: true*/
var uristrings = [],
prefix = "&",
add = function(nextObj, i) {
var nextTemp = temp
? (/\[\]$/.test(temp)) // prevent double-encoding
? temp
: temp + "[" + i + "]"
: i;
if ((nextTemp !== "undefined") && (i !== "undefined")) {
uristrings.push(
(typeof nextObj === "object")
? qq.obj2url(nextObj, nextTemp, true)
: (Object.prototype.toString.call(nextObj) === "[object Function]")
? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj())
: encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj)
);
}
};
if (!prefixDone && temp) {
prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? "" : "&" : "?";
uristrings.push(temp);
uristrings.push(qq.obj2url(obj));
} else if ((Object.prototype.toString.call(obj) === "[object Array]") && (typeof obj !== "undefined")) {
qq.each(obj, function(idx, val) {
add(val, idx);
});
} else if ((typeof obj !== "undefined") && (obj !== null) && (typeof obj === "object")) {
qq.each(obj, function(prop, val) {
add(val, prop);
});
} else {
uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj));
}
if (temp) {
return uristrings.join(prefix);
} else {
return uristrings.join(prefix)
.replace(/^&/, "")
.replace(/%20/g, "+");
}
};
qq.obj2FormData = function(obj, formData, arrayKeyName) {
if (!formData) {
formData = new FormData();
}
qq.each(obj, function(key, val) {
key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key;
if (qq.isObject(val)) {
qq.obj2FormData(val, formData, key);
}
else if (qq.isFunction(val)) {
formData.append(key, val());
}
else {
formData.append(key, val);
}
});
return formData;
};
qq.obj2Inputs = function(obj, form) {
var input;
if (!form) {
form = document.createElement("form");
}
qq.obj2FormData(obj, {
append: function(key, val) {
input = document.createElement("input");
input.setAttribute("name", key);
input.setAttribute("value", val);
form.appendChild(input);
}
});
return form;
};
/**
* Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not
* implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js.
*/
qq.parseJson = function(json) {
/*jshint evil: true*/
if (window.JSON && qq.isFunction(JSON.parse)) {
return JSON.parse(json);
} else {
return eval("(" + json + ")");
}
};
/**
* Retrieve the extension of a file, if it exists.
*
* @param filename
* @returns {string || undefined}
*/
qq.getExtension = function(filename) {
var extIdx = filename.lastIndexOf(".") + 1;
if (extIdx > 0) {
return filename.substr(extIdx, filename.length - extIdx);
}
};
qq.getFilename = function(blobOrFileInput) {
/*jslint regexp: true*/
if (qq.isInput(blobOrFileInput)) {
// get input value and remove path to normalize
return blobOrFileInput.value.replace(/.*(\/|\\)/, "");
}
else if (qq.isFile(blobOrFileInput)) {
if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) {
return blobOrFileInput.fileName;
}
}
return blobOrFileInput.name;
};
/**
* A generic module which supports object disposing in dispose() method.
* */
qq.DisposeSupport = function() {
var disposers = [];
return {
/** Run all registered disposers */
dispose: function() {
var disposer;
do {
disposer = disposers.shift();
if (disposer) {
disposer();
}
}
while (disposer);
},
/** Attach event handler and register de-attacher as a disposer */
attach: function() {
var args = arguments;
/*jslint undef:true*/
this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));
},
/** Add disposer to the collection */
addDisposer: function(disposeFunction) {
disposers.push(disposeFunction);
}
};
};
}());
/* globals qq */
/**
* Fine Uploader top-level Error container. Inherits from `Error`.
*/
(function() {
"use strict";
qq.Error = function(message) {
this.message = "[Fine Uploader " + qq.version + "] " + message;
};
qq.Error.prototype = new Error();
}());
/*global qq */
qq.version = "5.1.3";
/* globals qq */
qq.supportedFeatures = (function() {
"use strict";
var supportsUploading,
supportsUploadingBlobs,
supportsAjaxFileUploading,
supportsFolderDrop,
supportsChunking,
supportsResume,
supportsUploadViaPaste,
supportsUploadCors,
supportsDeleteFileXdr,
supportsDeleteFileCorsXhr,
supportsDeleteFileCors,
supportsFolderSelection,
supportsImagePreviews,
supportsUploadProgress;
function testSupportsFileInputElement() {
var supported = true,
tempInput;
try {
tempInput = document.createElement("input");
tempInput.type = "file";
qq(tempInput).hide();
if (tempInput.disabled) {
supported = false;
}
}
catch (ex) {
supported = false;
}
return supported;
}
//only way to test for Filesystem API support since webkit does not expose the DataTransfer interface
function isChrome21OrHigher() {
return (qq.chrome() || qq.opera()) &&
navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined;
}
//only way to test for complete Clipboard API support at this time
function isChrome14OrHigher() {
return (qq.chrome() || qq.opera()) &&
navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined;
}
//Ensure we can send cross-origin `XMLHttpRequest`s
function isCrossOriginXhrSupported() {
if (window.XMLHttpRequest) {
var xhr = qq.createXhrInstance();
//Commonly accepted test for XHR CORS support.
return xhr.withCredentials !== undefined;
}
return false;
}
//Test for (terrible) cross-origin ajax transport fallback for IE9 and IE8
function isXdrSupported() {
return window.XDomainRequest !== undefined;
}
// CORS Ajax requests are supported if it is either possible to send credentialed `XMLHttpRequest`s,
// or if `XDomainRequest` is an available alternative.
function isCrossOriginAjaxSupported() {
if (isCrossOriginXhrSupported()) {
return true;
}
return isXdrSupported();
}
function isFolderSelectionSupported() {
// We know that folder selection is only supported in Chrome via this proprietary attribute for now
return document.createElement("input").webkitdirectory !== undefined;
}
function isLocalStorageSupported() {
try {
return !!window.localStorage;
}
catch (error) {
// probably caught a security exception, so no localStorage for you
return false;
}
}
supportsUploading = testSupportsFileInputElement();
supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported();
supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock();
supportsFolderDrop = supportsAjaxFileUploading && isChrome21OrHigher();
supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported();
supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported();
supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher();
supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading);
supportsDeleteFileCorsXhr = isCrossOriginXhrSupported();
supportsDeleteFileXdr = isXdrSupported();
supportsDeleteFileCors = isCrossOriginAjaxSupported();
supportsFolderSelection = isFolderSelectionSupported();
supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined;
supportsUploadProgress = (function() {
if (supportsAjaxFileUploading) {
return !qq.androidStock() && !qq.iosChrome();
}
return false;
}());
return {
ajaxUploading: supportsAjaxFileUploading,
blobUploading: supportsUploadingBlobs,
canDetermineSize: supportsAjaxFileUploading,
chunking: supportsChunking,
deleteFileCors: supportsDeleteFileCors,
deleteFileCorsXdr: supportsDeleteFileXdr, //NOTE: will also return true in IE10, where XDR is also supported
deleteFileCorsXhr: supportsDeleteFileCorsXhr,
fileDrop: supportsAjaxFileUploading, //NOTE: will also return true for touch-only devices. It's not currently possible to accurately test for touch-only devices
folderDrop: supportsFolderDrop,
folderSelection: supportsFolderSelection,
imagePreviews: supportsImagePreviews,
imageValidation: supportsImagePreviews,
itemSizeValidation: supportsAjaxFileUploading,
pause: supportsChunking,
progressBar: supportsUploadProgress,
resume: supportsResume,
scaling: supportsImagePreviews && supportsUploadingBlobs,
tiffPreviews: qq.safari(), // Not the best solution, but simple and probably accurate enough (for now)
unlimitedScaledImageSize: !qq.ios(), // false simply indicates that there is some known limit
uploading: supportsUploading,
uploadCors: supportsUploadCors,
uploadCustomHeaders: supportsAjaxFileUploading,
uploadNonMultipart: supportsAjaxFileUploading,
uploadViaPaste: supportsUploadViaPaste
};
}());
/*globals qq*/
// Is the passed object a promise instance?
qq.isGenericPromise = function(maybePromise) {
"use strict";
return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then));
};
qq.Promise = function() {
"use strict";
var successArgs, failureArgs,
successCallbacks = [],
failureCallbacks = [],
doneCallbacks = [],
state = 0;
qq.extend(this, {
then: function(onSuccess, onFailure) {
if (state === 0) {
if (onSuccess) {
successCallbacks.push(onSuccess);
}
if (onFailure) {
failureCallbacks.push(onFailure);
}
}
else if (state === -1) {
onFailure && onFailure.apply(null, failureArgs);
}
else if (onSuccess) {
onSuccess.apply(null, successArgs);
}
return this;
},
done: function(callback) {
if (state === 0) {
doneCallbacks.push(callback);
}
else {
callback.apply(null, failureArgs === undefined ? successArgs : failureArgs);
}
return this;
},
success: function() {
state = 1;
successArgs = arguments;
if (successCallbacks.length) {
qq.each(successCallbacks, function(idx, callback) {
callback.apply(null, successArgs);
});
}
if (doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback.apply(null, successArgs);
});
}
return this;
},
failure: function() {
state = -1;
failureArgs = arguments;
if (failureCallbacks.length) {
qq.each(failureCallbacks, function(idx, callback) {
callback.apply(null, failureArgs);
});
}
if (doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback.apply(null, failureArgs);
});
}
return this;
}
});
};
/* globals qq */
/**
* Placeholder for a Blob that will be generated on-demand.
*
* @param referenceBlob Parent of the generated blob
* @param onCreate Function to invoke when the blob must be created. Must be promissory.
* @constructor
*/
qq.BlobProxy = function(referenceBlob, onCreate) {
"use strict";
qq.extend(this, {
referenceBlob: referenceBlob,
create: function() {
return onCreate(referenceBlob);
}
});
};
/*globals qq*/
/**
* This module represents an upload or "Select File(s)" button. It's job is to embed an opaque `<input type="file">`
* element as a child of a provided "container" element. This "container" element (`options.element`) is used to provide
* a custom style for the `<input type="file">` element. The ability to change the style of the container element is also
* provided here by adding CSS classes to the container on hover/focus.
*
* TODO Eliminate the mouseover and mouseout event handlers since the :hover CSS pseudo-class should now be
* available on all supported browsers.
*
* @param o Options to override the default values
*/
qq.UploadButton = function(o) {
"use strict";
var self = this,
disposeSupport = new qq.DisposeSupport(),
options = {
// "Container" element
element: null,
// If true adds `multiple` attribute to `<input type="file">`
multiple: false,
// Corresponds to the `accept` attribute on the associated `<input type="file">`
acceptFiles: null,
// A true value allows folders to be selected, if supported by the UA
folders: false,
// `name` attribute of `<input type="file">`
name: "qqfile",
// Called when the browser invokes the onchange handler on the `<input type="file">`
onChange: function(input) {},
ios8BrowserCrashWorkaround: true,
// **This option will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers
hoverClass: "qq-upload-button-hover",
focusClass: "qq-upload-button-focus"
},
input, buttonId;
// Overrides any of the default option values with any option values passed in during construction.
qq.extend(options, o);
buttonId = qq.getUniqueId();
// Embed an opaque `<input type="file">` element as a child of `options.element`.
function createInput() {
var input = document.createElement("input");
input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId);
self.setMultiple(options.multiple, input);
if (options.folders && qq.supportedFeatures.folderSelection) {
// selecting directories is only possible in Chrome now, via a vendor-specific prefixed attribute
input.setAttribute("webkitdirectory", "");
}
if (options.acceptFiles) {
input.setAttribute("accept", options.acceptFiles);
}
input.setAttribute("type", "file");
input.setAttribute("name", options.name);
qq(input).css({
position: "absolute",
// in Opera only 'browse' button
// is clickable and it is located at
// the right side of the input
right: 0,
top: 0,
fontFamily: "Arial",
// It's especially important to make this an arbitrarily large value
// to ensure the rendered input button in IE takes up the entire
// space of the container element. Otherwise, the left side of the
// button will require a double-click to invoke the file chooser.
// In other browsers, this might cause other issues, so a large font-size
// is only used in IE. There is a bug in IE8 where the opacity style is ignored
// in some cases when the font-size is large. So, this workaround is not applied
// to IE8.
fontSize: qq.ie() && !qq.ie8() ? "3500px" : "118px",
margin: 0,
padding: 0,
cursor: "pointer",
opacity: 0
});
// Setting the file input's height to 100% in IE7 causes
// most of the visible button to be unclickable.
!qq.ie7() && qq(input).css({height: "100%"});
options.element.appendChild(input);
disposeSupport.attach(input, "change", function() {
options.onChange(input);
});
// **These event handlers will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers
disposeSupport.attach(input, "mouseover", function() {
qq(options.element).addClass(options.hoverClass);
});
disposeSupport.attach(input, "mouseout", function() {
qq(options.element).removeClass(options.hoverClass);
});
disposeSupport.attach(input, "focus", function() {
qq(options.element).addClass(options.focusClass);
});
disposeSupport.attach(input, "blur", function() {
qq(options.element).removeClass(options.focusClass);
});
// IE and Opera, unfortunately have 2 tab stops on file input
// which is unacceptable in our case, disable keyboard access
if (window.attachEvent) {
// it is IE or Opera
input.setAttribute("tabIndex", "-1");
}
return input;
}
// Make button suitable container for input
qq(options.element).css({
position: "relative",
overflow: "hidden",
// Make sure browse button is in the right side in Internet Explorer
direction: "ltr"
});
// Exposed API
qq.extend(this, {
getInput: function() {
return input;
},
getButtonId: function() {
return buttonId;
},
setMultiple: function(isMultiple, optInput) {
var input = optInput || this.getInput();
// Temporary workaround for bug in in iOS8 UIWebView that causes the browser to crash
// before the file chooser appears if the file input doesn't contain a multiple attribute.
// See #1283.
if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) {
input.setAttribute("multiple", "");
}
else {
if (isMultiple) {
input.setAttribute("multiple", "");
}
else {
input.removeAttribute("multiple");
}
}
},
setAcceptFiles: function(acceptFiles) {
if (acceptFiles !== options.acceptFiles) {
input.setAttribute("accept", acceptFiles);
}
},
reset: function() {
if (input.parentNode) {
qq(input).remove();
}
qq(options.element).removeClass(options.focusClass);
input = null;
input = createInput();
}
});
input = createInput();
};
qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id";
/*globals qq */
qq.UploadData = function(uploaderProxy) {
"use strict";
var data = [],
byUuid = {},
byStatus = {},
byProxyGroupId = {},
byBatchId = {};
function getDataByIds(idOrIds) {
if (qq.isArray(idOrIds)) {
var entries = [];
qq.each(idOrIds, function(idx, id) {
entries.push(data[id]);
});
return entries;
}
return data[idOrIds];
}
function getDataByUuids(uuids) {
if (qq.isArray(uuids)) {
var entries = [];
qq.each(uuids, function(idx, uuid) {
entries.push(data[byUuid[uuid]]);
});
return entries;
}
return data[byUuid[uuids]];
}
function getDataByStatus(status) {
var statusResults = [],
statuses = [].concat(status);
qq.each(statuses, function(index, statusEnum) {
var statusResultIndexes = byStatus[statusEnum];
if (statusResultIndexes !== undefined) {
qq.each(statusResultIndexes, function(i, dataIndex) {
statusResults.push(data[dataIndex]);
});
}
});
return statusResults;
}
qq.extend(this, {
/**
* Adds a new file to the data cache for tracking purposes.
*
* @param spec Data that describes this file. Possible properties are:
*
* - uuid: Initial UUID for this file.
* - name: Initial name of this file.
* - size: Size of this file, omit if this cannot be determined
* - status: Initial `qq.status` for this file. Omit for `qq.status.SUBMITTING`.
* - batchId: ID of the batch this file belongs to
* - proxyGroupId: ID of the proxy group associated with this file
*
* @returns {number} Internal ID for this file.
*/
addFile: function(spec) {
var status = spec.status || qq.status.SUBMITTING,
id = data.push({
name: spec.name,
originalName: spec.name,
uuid: spec.uuid,
size: spec.size || -1,
status: status
}) - 1;
if (spec.batchId) {
data[id].batchId = spec.batchId;
if (byBatchId[spec.batchId] === undefined) {
byBatchId[spec.batchId] = [];
}
byBatchId[spec.batchId].push(id);
}
if (spec.proxyGroupId) {
data[id].proxyGroupId = spec.proxyGroupId;
if (byProxyGroupId[spec.proxyGroupId] === undefined) {
byProxyGroupId[spec.proxyGroupId] = [];
}
byProxyGroupId[spec.proxyGroupId].push(id);
}
data[id].id = id;
byUuid[spec.uuid] = id;
if (byStatus[status] === undefined) {
byStatus[status] = [];
}
byStatus[status].push(id);
uploaderProxy.onStatusChange(id, null, status);
return id;
},
retrieve: function(optionalFilter) {
if (qq.isObject(optionalFilter) && data.length) {
if (optionalFilter.id !== undefined) {
return getDataByIds(optionalFilter.id);
}
else if (optionalFilter.uuid !== undefined) {
return getDataByUuids(optionalFilter.uuid);
}
else if (optionalFilter.status) {
return getDataByStatus(optionalFilter.status);
}
}
else {
return qq.extend([], data, true);
}
},
reset: function() {
data = [];
byUuid = {};
byStatus = {};
byBatchId = {};
},
setStatus: function(id, newStatus) {
var oldStatus = data[id].status,
byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id);
byStatus[oldStatus].splice(byStatusOldStatusIndex, 1);
data[id].status = newStatus;
if (byStatus[newStatus] === undefined) {
byStatus[newStatus] = [];
}
byStatus[newStatus].push(id);
uploaderProxy.onStatusChange(id, oldStatus, newStatus);
},
uuidChanged: function(id, newUuid) {
var oldUuid = data[id].uuid;
data[id].uuid = newUuid;
byUuid[newUuid] = id;
delete byUuid[oldUuid];
},
updateName: function(id, newName) {
data[id].name = newName;
},
updateSize: function(id, newSize) {
data[id].size = newSize;
},
// Only applicable if this file has a parent that we may want to reference later.
setParentId: function(targetId, parentId) {
data[targetId].parentId = parentId;
},
getIdsInProxyGroup: function(id) {
var proxyGroupId = data[id].proxyGroupId;
if (proxyGroupId) {
return byProxyGroupId[proxyGroupId];
}
return [];
},
getIdsInBatch: function(id) {
var batchId = data[id].batchId;
return byBatchId[batchId];
}
});
};
qq.status = {
SUBMITTING: "submitting",
SUBMITTED: "submitted",
REJECTED: "rejected",
QUEUED: "queued",
CANCELED: "canceled",
PAUSED: "paused",
UPLOADING: "uploading",
UPLOAD_RETRYING: "retrying upload",
UPLOAD_SUCCESSFUL: "upload successful",
UPLOAD_FAILED: "upload failed",
DELETE_FAILED: "delete failed",
DELETING: "deleting",
DELETED: "deleted"
};
/*globals qq*/
/**
* Defines the public API for FineUploaderBasic mode.
*/
(function() {
"use strict";
qq.basePublicApi = {
// DEPRECATED - TODO REMOVE IN NEXT MAJOR RELEASE (replaced by addFiles)
addBlobs: function(blobDataOrArray, params, endpoint) {
this.addFiles(blobDataOrArray, params, endpoint);
},
addFiles: function(data, params, endpoint) {
this._maybeHandleIos8SafariWorkaround();
var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId,
processBlob = qq.bind(function(blob) {
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName
}, batchId, verifiedFiles);
}, this),
processBlobData = qq.bind(function(blobData) {
this._handleNewFile(blobData, batchId, verifiedFiles);
}, this),
processCanvas = qq.bind(function(canvas) {
var blob = qq.canvasToBlob(canvas);
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName + ".png"
}, batchId, verifiedFiles);
}, this),
processCanvasData = qq.bind(function(canvasData) {
var normalizedQuality = canvasData.quality && canvasData.quality / 100,
blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality);
this._handleNewFile({
blob: blob,
name: canvasData.name
}, batchId, verifiedFiles);
}, this),
processFileOrInput = qq.bind(function(fileOrInput) {
if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {
var files = Array.prototype.slice.call(fileOrInput.files);
qq.each(files, function(idx, file) {
this._handleNewFile(file, batchId, verifiedFiles);
});
}
else {
this._handleNewFile(fileOrInput, batchId, verifiedFiles);
}
}, this),
normalizeData = function() {
if (qq.isFileList(data)) {
data = Array.prototype.slice.call(data);
}
data = [].concat(data);
},
self = this,
verifiedFiles = [];
this._currentBatchId = batchId;
if (data) {
normalizeData();
qq.each(data, function(idx, fileContainer) {
if (qq.isFileOrInput(fileContainer)) {
processFileOrInput(fileContainer);
}
else if (qq.isBlob(fileContainer)) {
processBlob(fileContainer);
}
else if (qq.isObject(fileContainer)) {
if (fileContainer.blob && fileContainer.name) {
processBlobData(fileContainer);
}
else if (fileContainer.canvas && fileContainer.name) {
processCanvasData(fileContainer);
}
}
else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") {
processCanvas(fileContainer);
}
else {
self.log(fileContainer + " is not a valid file container! Ignoring!", "warn");
}
});
this.log("Received " + verifiedFiles.length + " files.");
this._prepareItemsForUpload(verifiedFiles, params, endpoint);
}
},
cancel: function(id) {
this._handler.cancel(id);
},
cancelAll: function() {
var storedIdsCopy = [],
self = this;
qq.extend(storedIdsCopy, this._storedIds);
qq.each(storedIdsCopy, function(idx, storedFileId) {
self.cancel(storedFileId);
});
this._handler.cancelAll();
},
clearStoredFiles: function() {
this._storedIds = [];
},
continueUpload: function(id) {
var uploadData = this._uploadData.retrieve({id: id});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
if (uploadData.status === qq.status.PAUSED) {
this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id)));
this._uploadFile(id);
return true;
}
else {
this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error");
}
return false;
},
deleteFile: function(id) {
return this._onSubmitDelete(id);
},
// TODO document?
doesExist: function(fileOrBlobId) {
return this._handler.isValid(fileOrBlobId);
},
// Generate a variable size thumbnail on an img or canvas,
// returning a promise that is fulfilled when the attempt completes.
// Thumbnail can either be based off of a URL for an image returned
// by the server in the upload response, or the associated `Blob`.
drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer) {
var promiseToReturn = new qq.Promise(),
fileOrUrl, options;
if (this._imageGenerator) {
fileOrUrl = this._thumbnailUrls[fileId];
options = {
scale: maxSize > 0,
maxSize: maxSize > 0 ? maxSize : null
};
// If client-side preview generation is possible
// and we are not specifically looking for the image URl returned by the server...
if (!fromServer && qq.supportedFeatures.imagePreviews) {
fileOrUrl = this.getFile(fileId);
}
/* jshint eqeqeq:false,eqnull:true */
if (fileOrUrl == null) {
promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."});
}
else {
this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(
function success(modifiedContainer) {
promiseToReturn.success(modifiedContainer);
},
function failure(container, reason) {
promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"});
}
);
}
}
else {
promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"});
}
return promiseToReturn;
},
getButton: function(fileId) {
return this._getButton(this._buttonIdsForFileIds[fileId]);
},
getEndpoint: function(fileId) {
return this._endpointStore.get(fileId);
},
getFile: function(fileOrBlobId) {
return this._handler.getFile(fileOrBlobId) || null;
},
getInProgress: function() {
return this._uploadData.retrieve({
status: [
qq.status.UPLOADING,
qq.status.UPLOAD_RETRYING,
qq.status.QUEUED
]
}).length;
},
getName: function(id) {
return this._uploadData.retrieve({id: id}).name;
},
// Parent ID for a specific file, or null if this is the parent, or if it has no parent.
getParentId: function(id) {
var uploadDataEntry = this.getUploads({id: id}),
parentId = null;
if (uploadDataEntry) {
if (uploadDataEntry.parentId !== undefined) {
parentId = uploadDataEntry.parentId;
}
}
return parentId;
},
getResumableFilesData: function() {
return this._handler.getResumableFilesData();
},
getSize: function(id) {
return this._uploadData.retrieve({id: id}).size;
},
getNetUploads: function() {
return this._netUploaded;
},
getRemainingAllowedItems: function() {
var allowedItems = this._currentItemLimit;
if (allowedItems > 0) {
return allowedItems - this._netUploadedOrQueued;
}
return null;
},
getUploads: function(optionalFilter) {
return this._uploadData.retrieve(optionalFilter);
},
getUuid: function(id) {
return this._uploadData.retrieve({id: id}).uuid;
},
log: function(str, level) {
if (this._options.debug && (!level || level === "info")) {
qq.log("[Fine Uploader " + qq.version + "] " + str);
}
else if (level && level !== "info") {
qq.log("[Fine Uploader " + qq.version + "] " + str, level);
}
},
pauseUpload: function(id) {
var uploadData = this._uploadData.retrieve({id: id});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
// Pause only really makes sense if the file is uploading or retrying
if (qq.indexOf([qq.status.UPLOADING, qq.status.UPLOAD_RETRYING], uploadData.status) >= 0) {
if (this._handler.pause(id)) {
this._uploadData.setStatus(id, qq.status.PAUSED);
return true;
}
else {
this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error");
}
}
else {
this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error");
}
return false;
},
reset: function() {
this.log("Resetting uploader...");
this._handler.reset();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
qq.each(this._buttons, function(idx, button) {
button.reset();
});
this._paramsStore.reset();
this._endpointStore.reset();
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData.reset();
this._buttonIdsForFileIds = [];
this._pasteHandler && this._pasteHandler.reset();
this._options.session.refreshOnReset && this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._totalProgress && this._totalProgress.reset();
},
retry: function(id) {
return this._manualRetry(id);
},
scaleImage: function(id, specs) {
var self = this;
return qq.Scaler.prototype.scaleImage(id, specs, {
log: qq.bind(self.log, self),
getFile: qq.bind(self.getFile, self),
uploadData: self._uploadData
});
},
setCustomHeaders: function(headers, id) {
this._customHeadersStore.set(headers, id);
},
setDeleteFileCustomHeaders: function(headers, id) {
this._deleteFileCustomHeadersStore.set(headers, id);
},
setDeleteFileEndpoint: function(endpoint, id) {
this._deleteFileEndpointStore.set(endpoint, id);
},
setDeleteFileParams: function(params, id) {
this._deleteFileParamsStore.set(params, id);
},
// Re-sets the default endpoint, an endpoint for a specific file, or an endpoint for a specific button
setEndpoint: function(endpoint, id) {
this._endpointStore.set(endpoint, id);
},
setItemLimit: function(newItemLimit) {
this._currentItemLimit = newItemLimit;
},
setName: function(id, newName) {
this._uploadData.updateName(id, newName);
},
setParams: function(params, id) {
this._paramsStore.set(params, id);
},
setUuid: function(id, newUuid) {
return this._uploadData.uuidChanged(id, newUuid);
},
uploadStoredFiles: function() {
var idToUpload;
if (this._storedIds.length === 0) {
this._itemError("noFilesError");
}
else {
while (this._storedIds.length) {
idToUpload = this._storedIds.shift();
this._uploadFile(idToUpload);
}
}
}
};
/**
* Defines the private (internal) API for FineUploaderBasic mode.
*/
qq.basePrivateApi = {
// Updates internal state with a file record (not backed by a live file). Returns the assigned ID.
_addCannedFile: function(sessionData) {
var id = this._uploadData.addFile({
uuid: sessionData.uuid,
name: sessionData.name,
size: sessionData.size,
status: qq.status.UPLOAD_SUCCESSFUL
});
sessionData.deleteFileEndpoint && this.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id);
sessionData.deleteFileParams && this.setDeleteFileParams(sessionData.deleteFileParams, id);
if (sessionData.thumbnailUrl) {
this._thumbnailUrls[id] = sessionData.thumbnailUrl;
}
this._netUploaded++;
this._netUploadedOrQueued++;
return id;
},
_annotateWithButtonId: function(file, associatedInput) {
if (qq.isFile(file)) {
file.qqButtonId = this._getButtonId(associatedInput);
}
},
_batchError: function(message) {
this._options.callbacks.onError(null, null, message, undefined);
},
_createDeleteHandler: function() {
var self = this;
return new qq.DeleteFileAjaxRequester({
method: this._options.deleteFile.method.toUpperCase(),
maxConnections: this._options.maxConnections,
uuidParamName: this._options.request.uuidName,
customHeaders: this._deleteFileCustomHeadersStore,
paramsStore: this._deleteFileParamsStore,
endpointStore: this._deleteFileEndpointStore,
demoMode: this._options.demoMode,
cors: this._options.cors,
log: qq.bind(self.log, self),
onDelete: function(id) {
self._onDelete(id);
self._options.callbacks.onDelete(id);
},
onDeleteComplete: function(id, xhrOrXdr, isError) {
self._onDeleteComplete(id, xhrOrXdr, isError);
self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
}
});
},
_createPasteHandler: function() {
var self = this;
return new qq.PasteSupport({
targetElement: this._options.paste.targetElement,
callbacks: {
log: qq.bind(self.log, self),
pasteReceived: function(blob) {
self._handleCheckedCallback({
name: "onPasteReceived",
callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),
onSuccess: qq.bind(self._handlePasteSuccess, self, blob),
identifier: "pasted image"
});
}
}
});
},
_createStore: function(initialValue, readOnlyValues) {
var store = {},
catchall = initialValue,
perIdReadOnlyValues = {},
copy = function(orig) {
if (qq.isObject(orig)) {
return qq.extend({}, orig);
}
return orig;
},
getReadOnlyValues = function() {
if (qq.isFunction(readOnlyValues)) {
return readOnlyValues();
}
return readOnlyValues;
},
includeReadOnlyValues = function(id, existing) {
if (readOnlyValues && qq.isObject(existing)) {
qq.extend(existing, getReadOnlyValues());
}
if (perIdReadOnlyValues[id]) {
qq.extend(existing, perIdReadOnlyValues[id]);
}
};
return {
set: function(val, id) {
/*jshint eqeqeq: true, eqnull: true*/
if (id == null) {
store = {};
catchall = copy(val);
}
else {
store[id] = copy(val);
}
},
get: function(id) {
var values;
/*jshint eqeqeq: true, eqnull: true*/
if (id != null && store[id]) {
values = store[id];
}
else {
values = copy(catchall);
}
includeReadOnlyValues(id, values);
return copy(values);
},
addReadOnly: function(id, values) {
// Only applicable to Object stores
if (qq.isObject(store)) {
perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {};
qq.extend(perIdReadOnlyValues[id], values);
}
},
remove: function(fileId) {
return delete store[fileId];
},
reset: function() {
store = {};
perIdReadOnlyValues = {};
catchall = initialValue;
}
};
},
_createUploadDataTracker: function() {
var self = this;
return new qq.UploadData({
getName: function(id) {
return self.getName(id);
},
getUuid: function(id) {
return self.getUuid(id);
},
getSize: function(id) {
return self.getSize(id);
},
onStatusChange: function(id, oldStatus, newStatus) {
self._onUploadStatusChange(id, oldStatus, newStatus);
self._options.callbacks.onStatusChange(id, oldStatus, newStatus);
self._maybeAllComplete(id, newStatus);
if (self._totalProgress) {
setTimeout(function() {
self._totalProgress.onStatusChange(id, oldStatus, newStatus);
}, 0);
}
}
});
},
/**
* Generate a tracked upload button.
*
* @param spec Object containing a required `element` property
* along with optional `multiple`, `accept`, and `folders`.
* @returns {qq.UploadButton}
* @private
*/
_createUploadButton: function(spec) {
var self = this,
acceptFiles = spec.accept || this._options.validation.acceptFiles,
allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions,
button;
function allowMultiple() {
if (qq.supportedFeatures.ajaxUploading) {
// Workaround for bug in iOS7+ (see #1039)
if (self._options.workarounds.iosEmptyVideos &&
qq.ios() &&
!qq.ios6() &&
self._isAllowedExtension(allowedExtensions, ".mov")) {
return false;
}
if (spec.multiple === undefined) {
return self._options.multiple;
}
return spec.multiple;
}
return false;
}
button = new qq.UploadButton({
element: spec.element,
folders: spec.folders,
name: this._options.request.inputName,
multiple: allowMultiple(),
acceptFiles: acceptFiles,
onChange: function(input) {
self._onInputChange(input);
},
hoverClass: this._options.classes.buttonHover,
focusClass: this._options.classes.buttonFocus,
ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash
});
this._disposeSupport.addDisposer(function() {
button.dispose();
});
self._buttons.push(button);
return button;
},
_createUploadHandler: function(additionalOptions, namespace) {
var self = this,
lastOnProgress = {},
options = {
debug: this._options.debug,
maxConnections: this._options.maxConnections,
cors: this._options.cors,
demoMode: this._options.demoMode,
paramsStore: this._paramsStore,
endpointStore: this._endpointStore,
chunking: this._options.chunking,
resume: this._options.resume,
blobs: this._options.blobs,
log: qq.bind(self.log, self),
preventRetryParam: this._options.retry.preventRetryResponseProperty,
onProgress: function(id, name, loaded, total) {
if (loaded < 0 || total < 0) {
return;
}
if (lastOnProgress[id]) {
if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
}
else {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
lastOnProgress[id] = {loaded: loaded, total: total};
},
onComplete: function(id, name, result, xhr) {
delete lastOnProgress[id];
var status = self.getUploads({id: id}).status,
retVal;
// This is to deal with some observed cases where the XHR readyStateChange handler is
// invoked by the browser multiple times for the same XHR instance with the same state
// readyState value. Higher level: don't invoke complete-related code if we've already
// done this.
if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) {
return;
}
retVal = self._onComplete(id, name, result, xhr);
// If the internal `_onComplete` handler returns a promise, don't invoke the `onComplete` callback
// until the promise has been fulfilled.
if (retVal instanceof qq.Promise) {
retVal.done(function() {
self._options.callbacks.onComplete(id, name, result, xhr);
});
}
else {
self._options.callbacks.onComplete(id, name, result, xhr);
}
},
onCancel: function(id, name, cancelFinalizationEffort) {
var promise = new qq.Promise();
self._handleCheckedCallback({
name: "onCancel",
callback: qq.bind(self._options.callbacks.onCancel, self, id, name),
onFailure: promise.failure,
onSuccess: function() {
cancelFinalizationEffort.then(function() {
self._onCancel(id, name);
});
promise.success();
},
identifier: id
});
return promise;
},
onUploadPrep: qq.bind(this._onUploadPrep, this),
onUpload: function(id, name) {
self._onUpload(id, name);
self._options.callbacks.onUpload(id, name);
},
onUploadChunk: function(id, name, chunkData) {
self._onUploadChunk(id, chunkData);
self._options.callbacks.onUploadChunk(id, name, chunkData);
},
onUploadChunkSuccess: function(id, chunkData, result, xhr) {
self._options.callbacks.onUploadChunkSuccess.apply(self, arguments);
},
onResume: function(id, name, chunkData) {
return self._options.callbacks.onResume(id, name, chunkData);
},
onAutoRetry: function(id, name, responseJSON, xhr) {
return self._onAutoRetry.apply(self, arguments);
},
onUuidChanged: function(id, newUuid) {
self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'");
self.setUuid(id, newUuid);
},
getName: qq.bind(self.getName, self),
getUuid: qq.bind(self.getUuid, self),
getSize: qq.bind(self.getSize, self),
setSize: qq.bind(self._setSize, self),
getDataByUuid: function(uuid) {
return self.getUploads({uuid: uuid});
},
isQueued: function(id) {
var status = self.getUploads({id: id}).status;
return status === qq.status.QUEUED ||
status === qq.status.SUBMITTED ||
status === qq.status.UPLOAD_RETRYING ||
status === qq.status.PAUSED;
},
getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup,
getIdsInBatch: self._uploadData.getIdsInBatch
};
qq.each(this._options.request, function(prop, val) {
options[prop] = val;
});
options.customHeaders = this._customHeadersStore;
if (additionalOptions) {
qq.each(additionalOptions, function(key, val) {
options[key] = val;
});
}
return new qq.UploadHandlerController(options, namespace);
},
_fileOrBlobRejected: function(id) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.REJECTED);
},
_formatSize: function(bytes) {
var i = -1;
do {
bytes = bytes / 1000;
i++;
} while (bytes > 999);
return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i];
},
// Creates an internal object that tracks various properties of each extra button,
// and then actually creates the extra button.
_generateExtraButtonSpecs: function() {
var self = this;
this._extraButtonSpecs = {};
qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) {
var multiple = extraButtonOptionEntry.multiple,
validation = qq.extend({}, self._options.validation, true),
extraButtonSpec = qq.extend({}, extraButtonOptionEntry);
if (multiple === undefined) {
multiple = self._options.multiple;
}
if (extraButtonSpec.validation) {
qq.extend(validation, extraButtonOptionEntry.validation, true);
}
qq.extend(extraButtonSpec, {
multiple: multiple,
validation: validation
}, true);
self._initExtraButton(extraButtonSpec);
});
},
_getButton: function(buttonId) {
var extraButtonsSpec = this._extraButtonSpecs[buttonId];
if (extraButtonsSpec) {
return extraButtonsSpec.element;
}
else if (buttonId === this._defaultButtonId) {
return this._options.button;
}
},
/**
* Gets the internally used tracking ID for a button.
*
* @param buttonOrFileInputOrFile `File`, `<input type="file">`, or a button container element
* @returns {*} The button's ID, or undefined if no ID is recoverable
* @private
*/
_getButtonId: function(buttonOrFileInputOrFile) {
var inputs, fileInput,
fileBlobOrInput = buttonOrFileInputOrFile;
// We want the reference file/blob here if this is a proxy (a file that will be generated on-demand later)
if (fileBlobOrInput instanceof qq.BlobProxy) {
fileBlobOrInput = fileBlobOrInput.referenceBlob;
}
// If the item is a `Blob` it will never be associated with a button or drop zone.
if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) {
if (qq.isFile(fileBlobOrInput)) {
return fileBlobOrInput.qqButtonId;
}
else if (fileBlobOrInput.tagName.toLowerCase() === "input" &&
fileBlobOrInput.type.toLowerCase() === "file") {
return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
inputs = fileBlobOrInput.getElementsByTagName("input");
qq.each(inputs, function(idx, input) {
if (input.getAttribute("type") === "file") {
fileInput = input;
return false;
}
});
if (fileInput) {
return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
}
},
_getNotFinished: function() {
return this._uploadData.retrieve({
status: [
qq.status.UPLOADING,
qq.status.UPLOAD_RETRYING,
qq.status.QUEUED,
qq.status.SUBMITTING,
qq.status.SUBMITTED,
qq.status.PAUSED
]
}).length;
},
// Get the validation options for this button. Could be the default validation option
// or a specific one assigned to this particular button.
_getValidationBase: function(buttonId) {
var extraButtonSpec = this._extraButtonSpecs[buttonId];
return extraButtonSpec ? extraButtonSpec.validation : this._options.validation;
},
_getValidationDescriptor: function(fileWrapper) {
if (fileWrapper.file instanceof qq.BlobProxy) {
return {
name: qq.getFilename(fileWrapper.file.referenceBlob),
size: fileWrapper.file.referenceBlob.size
};
}
return {
name: this.getUploads({id: fileWrapper.id}).name,
size: this.getUploads({id: fileWrapper.id}).size
};
},
_getValidationDescriptors: function(fileWrappers) {
var self = this,
fileDescriptors = [];
qq.each(fileWrappers, function(idx, fileWrapper) {
fileDescriptors.push(self._getValidationDescriptor(fileWrapper));
});
return fileDescriptors;
},
// Allows camera access on either the default or an extra button for iOS devices.
_handleCameraAccess: function() {
if (this._options.camera.ios && qq.ios()) {
var acceptIosCamera = "image/*;capture=camera",
button = this._options.camera.button,
buttonId = button ? this._getButtonId(button) : this._defaultButtonId,
optionRoot = this._options;
// If we are not targeting the default button, it is an "extra" button
if (buttonId && buttonId !== this._defaultButtonId) {
optionRoot = this._extraButtonSpecs[buttonId];
}
// Camera access won't work in iOS if the `multiple` attribute is present on the file input
optionRoot.multiple = false;
// update the options
if (optionRoot.validation.acceptFiles === null) {
optionRoot.validation.acceptFiles = acceptIosCamera;
}
else {
optionRoot.validation.acceptFiles += "," + acceptIosCamera;
}
// update the already-created button
qq.each(this._buttons, function(idx, button) {
if (button.getButtonId() === buttonId) {
button.setMultiple(optionRoot.multiple);
button.setAcceptFiles(optionRoot.acceptFiles);
return false;
}
});
}
},
_handleCheckedCallback: function(details) {
var self = this,
callbackRetVal = details.callback();
if (qq.isGenericPromise(callbackRetVal)) {
this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier);
return callbackRetVal.then(
function(successParam) {
self.log(details.name + " promise success for " + details.identifier);
details.onSuccess(successParam);
},
function() {
if (details.onFailure) {
self.log(details.name + " promise failure for " + details.identifier);
details.onFailure();
}
else {
self.log(details.name + " promise failure for " + details.identifier);
}
});
}
if (callbackRetVal !== false) {
details.onSuccess(callbackRetVal);
}
else {
if (details.onFailure) {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback.");
details.onFailure();
}
else {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed.");
}
}
return callbackRetVal;
},
// Updates internal state when a new file has been received, and adds it along with its ID to a passed array.
_handleNewFile: function(file, batchId, newFileWrapperList) {
var self = this,
uuid = qq.getUniqueId(),
size = -1,
name = qq.getFilename(file),
actualFile = file.blob || file,
handler = this._customNewFileHandler ?
this._customNewFileHandler :
qq.bind(self._handleNewFileGeneric, self);
if (!qq.isInput(actualFile) && actualFile.size >= 0) {
size = actualFile.size;
}
handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, {
uploadData: self._uploadData,
paramsStore: self._paramsStore,
addFileToHandler: function(id, file) {
self._handler.add(id, file);
self._netUploadedOrQueued++;
self._trackButton(id);
}
});
},
_handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) {
var id = this._uploadData.addFile({uuid: uuid, name: name, size: size, batchId: batchId});
this._handler.add(id, file);
this._trackButton(id);
this._netUploadedOrQueued++;
fileList.push({id: id, file: file});
},
_handlePasteSuccess: function(blob, extSuppliedName) {
var extension = blob.type.split("/")[1],
name = extSuppliedName;
/*jshint eqeqeq: true, eqnull: true*/
if (name == null) {
name = this._options.paste.defaultName;
}
name += "." + extension;
this.addFiles({
name: name,
blob: blob
});
},
// Creates an extra button element
_initExtraButton: function(spec) {
var button = this._createUploadButton({
element: spec.element,
multiple: spec.multiple,
accept: spec.validation.acceptFiles,
folders: spec.folders,
allowedExtensions: spec.validation.allowedExtensions
});
this._extraButtonSpecs[button.getButtonId()] = spec;
},
_initFormSupportAndParams: function() {
this._formSupport = qq.FormSupport && new qq.FormSupport(
this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this)
);
if (this._formSupport && this._formSupport.attachedToForm) {
this._paramsStore = this._createStore(
this._options.request.params, this._formSupport.getFormInputsAsObject
);
this._options.autoUpload = this._formSupport.newAutoUpload;
if (this._formSupport.newEndpoint) {
this._options.request.endpoint = this._formSupport.newEndpoint;
}
}
else {
this._paramsStore = this._createStore(this._options.request.params);
}
},
_isDeletePossible: function() {
if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) {
return false;
}
if (this._options.cors.expected) {
if (qq.supportedFeatures.deleteFileCorsXhr) {
return true;
}
if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) {
return true;
}
return false;
}
return true;
},
_isAllowedExtension: function(allowed, fileName) {
var valid = false;
if (!allowed.length) {
return true;
}
qq.each(allowed, function(idx, allowedExt) {
/**
* If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the
* `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details.
*/
if (qq.isString(allowedExt)) {
/*jshint eqeqeq: true, eqnull: true*/
var extRegex = new RegExp("\\." + allowedExt + "$", "i");
if (fileName.match(extRegex) != null) {
valid = true;
return false;
}
}
});
return valid;
},
/**
* Constructs and returns a message that describes an item/file error. Also calls `onError` callback.
*
* @param code REQUIRED - a code that corresponds to a stock message describing this type of error
* @param maybeNameOrNames names of the items that have failed, if applicable
* @param item `File`, `Blob`, or `<input type="file">`
* @private
*/
_itemError: function(code, maybeNameOrNames, item) {
var message = this._options.messages[code],
allowedExtensions = [],
names = [].concat(maybeNameOrNames),
name = names[0],
buttonId = this._getButtonId(item),
validationBase = this._getValidationBase(buttonId),
extensionsForMessage, placeholderMatch;
function r(name, replacement) { message = message.replace(name, replacement); }
qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) {
/**
* If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the
* `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details.
*/
if (qq.isString(allowedExtension)) {
allowedExtensions.push(allowedExtension);
}
});
extensionsForMessage = allowedExtensions.join(", ").toLowerCase();
r("{file}", this._options.formatFileName(name));
r("{extensions}", extensionsForMessage);
r("{sizeLimit}", this._formatSize(validationBase.sizeLimit));
r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit));
placeholderMatch = message.match(/(\{\w+\})/g);
if (placeholderMatch !== null) {
qq.each(placeholderMatch, function(idx, placeholder) {
r(placeholder, names[idx]);
});
}
this._options.callbacks.onError(null, name, message, undefined);
return message;
},
/**
* Conditionally orders a manual retry of a failed upload.
*
* @param id File ID of the failed upload
* @param callback Optional callback to invoke if a retry is prudent.
* In lieu of asking the upload handler to retry.
* @returns {boolean} true if a manual retry will occur
* @private
*/
_manualRetry: function(id, callback) {
if (this._onBeforeManualRetry(id)) {
this._netUploadedOrQueued++;
this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
if (callback) {
callback(id);
}
else {
this._handler.retry(id);
}
return true;
}
},
_maybeAllComplete: function(id, status) {
var self = this,
notFinished = this._getNotFinished();
if (status === qq.status.UPLOAD_SUCCESSFUL) {
this._succeededSinceLastAllComplete.push(id);
}
else if (status === qq.status.UPLOAD_FAILED) {
this._failedSinceLastAllComplete.push(id);
}
if (notFinished === 0 &&
(this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) {
// Attempt to ensure onAllComplete is not invoked before other callbacks, such as onCancel & onComplete
setTimeout(function() {
self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete);
}, 0);
}
},
_maybeHandleIos8SafariWorkaround: function() {
var self = this;
if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
setTimeout(function() {
window.alert(self._options.messages.unsupportedBrowserIos8Safari);
}, 0);
throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari);
}
},
_maybeParseAndSendUploadError: function(id, name, response, xhr) {
// Assuming no one will actually set the response code to something other than 200
// and still set 'success' to true...
if (!response.success) {
if (xhr && xhr.status !== 200 && !response.error) {
this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr);
}
else {
var errorReason = response.error ? response.error : this._options.text.defaultResponseError;
this._options.callbacks.onError(id, name, errorReason, xhr);
}
}
},
_maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) {
var self = this;
if (items.length > index) {
if (validItem || !this._options.validation.stopOnFirstInvalidFile) {
//use setTimeout to prevent a stack overflow with a large number of files in the batch & non-promissory callbacks
setTimeout(function() {
var validationDescriptor = self._getValidationDescriptor(items[index]),
buttonId = self._getButtonId(items[index].file),
button = self._getButton(buttonId);
self._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button),
onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint),
onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint),
identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size
});
}, 0);
}
else if (!validItem) {
for (; index < items.length; index++) {
self._fileOrBlobRejected(items[index].id);
}
}
}
},
_onAllComplete: function(successful, failed) {
this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries);
this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed));
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
},
/**
* Attempt to automatically retry a failed upload.
*
* @param id The file ID of the failed upload
* @param name The name of the file associated with the failed upload
* @param responseJSON Response from the server, parsed into a javascript object
* @param xhr Ajax transport used to send the failed request
* @param callback Optional callback to be invoked if a retry is prudent.
* Invoked in lieu of asking the upload handler to retry.
* @returns {boolean} true if an auto-retry will occur
* @private
*/
_onAutoRetry: function(id, name, responseJSON, xhr, callback) {
var self = this;
self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty];
if (self._shouldAutoRetry(id, name, responseJSON)) {
self._maybeParseAndSendUploadError.apply(self, arguments);
self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]);
self._onBeforeAutoRetry(id, name);
self._retryTimeouts[id] = setTimeout(function() {
self.log("Retrying " + name + "...");
self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
if (callback) {
callback(id);
}
else {
self._handler.retry(id);
}
}, self._options.retry.autoAttemptDelay * 1000);
return true;
}
},
_onBeforeAutoRetry: function(id, name) {
this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "...");
},
//return false if we should not attempt the requested retry
_onBeforeManualRetry: function(id) {
var itemLimit = this._currentItemLimit,
fileName;
if (this._preventRetries[id]) {
this.log("Retries are forbidden for id " + id, "warn");
return false;
}
else if (this._handler.isValid(id)) {
fileName = this.getName(id);
if (this._options.callbacks.onManualRetry(id, fileName) === false) {
return false;
}
if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) {
this._itemError("retryFailTooManyItems");
return false;
}
this.log("Retrying upload for '" + fileName + "' (id: " + id + ")...");
return true;
}
else {
this.log("'" + id + "' is not a valid file ID", "error");
return false;
}
},
_onCancel: function(id, name) {
this._netUploadedOrQueued--;
clearTimeout(this._retryTimeouts[id]);
var storedItemIndex = qq.indexOf(this._storedIds, id);
if (!this._options.autoUpload && storedItemIndex >= 0) {
this._storedIds.splice(storedItemIndex, 1);
}
this._uploadData.setStatus(id, qq.status.CANCELED);
},
_onComplete: function(id, name, result, xhr) {
if (!result.success) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED);
if (result[this._options.retry.preventRetryResponseProperty] === true) {
this._preventRetries[id] = true;
}
}
else {
if (result.thumbnailUrl) {
this._thumbnailUrls[id] = result.thumbnailUrl;
}
this._netUploaded++;
this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL);
}
this._maybeParseAndSendUploadError(id, name, result, xhr);
return result.success ? true : false;
},
_onDelete: function(id) {
this._uploadData.setStatus(id, qq.status.DELETING);
},
_onDeleteComplete: function(id, xhrOrXdr, isError) {
var name = this.getName(id);
if (isError) {
this._uploadData.setStatus(id, qq.status.DELETE_FAILED);
this.log("Delete request for '" + name + "' has failed.", "error");
// For error reporing, we only have accesss to the response status if this is not
// an `XDomainRequest`.
if (xhrOrXdr.withCredentials === undefined) {
this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr);
}
else {
this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr);
}
}
else {
this._netUploadedOrQueued--;
this._netUploaded--;
this._handler.expunge(id);
this._uploadData.setStatus(id, qq.status.DELETED);
this.log("Delete request for '" + name + "' has succeeded.");
}
},
_onInputChange: function(input) {
var fileIndex;
if (qq.supportedFeatures.ajaxUploading) {
for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) {
this._annotateWithButtonId(input.files[fileIndex], input);
}
this.addFiles(input.files);
}
// Android 2.3.x will fire `onchange` even if no file has been selected
else if (input.value.length > 0) {
this.addFiles(input);
}
qq.each(this._buttons, function(idx, button) {
button.reset();
});
},
_onProgress: function(id, name, loaded, total) {
this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total);
},
_onSubmit: function(id, name) {
//nothing to do yet in core uploader
},
_onSubmitCallbackSuccess: function(id, name) {
this._onSubmit.apply(this, arguments);
this._uploadData.setStatus(id, qq.status.SUBMITTED);
this._onSubmitted.apply(this, arguments);
this._options.callbacks.onSubmitted.apply(this, arguments);
if (this._options.autoUpload) {
this._uploadFile(id);
}
else {
this._storeForLater(id);
}
},
_onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) {
var uuid = this.getUuid(id),
adjustedOnSuccessCallback;
if (onSuccessCallback) {
adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams);
}
if (this._isDeletePossible()) {
this._handleCheckedCallback({
name: "onSubmitDelete",
callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id),
onSuccess: adjustedOnSuccessCallback ||
qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams),
identifier: id
});
return true;
}
else {
this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " +
"due to CORS on a user agent that does not support pre-flighting.", "warn");
return false;
}
},
_onSubmitted: function(id) {
//nothing to do in the base uploader
},
_onTotalProgress: function(loaded, total) {
this._options.callbacks.onTotalProgress(loaded, total);
},
_onUploadPrep: function(id) {
// nothing to do in the core uploader for now
},
_onUpload: function(id, name) {
this._uploadData.setStatus(id, qq.status.UPLOADING);
},
_onUploadChunk: function(id, chunkData) {
//nothing to do in the base uploader
},
_onUploadStatusChange: function(id, oldStatus, newStatus) {
// Make sure a "queued" retry attempt is canceled if the upload has been paused
if (newStatus === qq.status.PAUSED) {
clearTimeout(this._retryTimeouts[id]);
}
},
_onValidateBatchCallbackFailure: function(fileWrappers) {
var self = this;
qq.each(fileWrappers, function(idx, fileWrapper) {
self._fileOrBlobRejected(fileWrapper.id);
});
},
_onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) {
var errorMessage,
itemLimit = this._currentItemLimit,
proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued;
if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) {
if (items.length > 0) {
this._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button),
onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint),
onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint),
identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size
});
}
else {
this._itemError("noFilesError");
}
}
else {
this._onValidateBatchCallbackFailure(items);
errorMessage = this._options.messages.tooManyItemsError
.replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued)
.replace(/\{itemLimit\}/g, itemLimit);
this._batchError(errorMessage);
}
},
_onValidateCallbackFailure: function(items, index, params, endpoint) {
var nextIndex = index + 1;
this._fileOrBlobRejected(items[index].id, items[index].file.name);
this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
},
_onValidateCallbackSuccess: function(items, index, params, endpoint) {
var self = this,
nextIndex = index + 1,
validationDescriptor = this._getValidationDescriptor(items[index]);
this._validateFileOrBlobData(items[index], validationDescriptor)
.then(
function() {
self._upload(items[index].id, params, endpoint);
self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint);
},
function() {
self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
}
);
},
_prepareItemsForUpload: function(items, params, endpoint) {
if (items.length === 0) {
this._itemError("noFilesError");
return;
}
var validationDescriptors = this._getValidationDescriptors(items),
buttonId = this._getButtonId(items[0].file),
button = this._getButton(buttonId);
this._handleCheckedCallback({
name: "onValidateBatch",
callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button),
onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button),
onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items),
identifier: "batch validation"
});
},
_preventLeaveInProgress: function() {
var self = this;
this._disposeSupport.attach(window, "beforeunload", function(e) {
if (self.getInProgress()) {
e = e || window.event;
// for ie, ff
e.returnValue = self._options.messages.onLeave;
// for webkit
return self._options.messages.onLeave;
}
});
},
// Attempts to refresh session data only if the `qq.Session` module exists
// and a session endpoint has been specified. The `onSessionRequestComplete`
// callback will be invoked once the refresh is complete.
_refreshSessionData: function() {
var self = this,
options = this._options.session;
/* jshint eqnull:true */
if (qq.Session && this._options.session.endpoint != null) {
if (!this._session) {
qq.extend(options, this._options.cors);
options.log = qq.bind(this.log, this);
options.addFileRecord = qq.bind(this._addCannedFile, this);
this._session = new qq.Session(options);
}
setTimeout(function() {
self._session.refresh().then(function(response, xhrOrXdr) {
self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr);
}, function(response, xhrOrXdr) {
self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr);
});
}, 0);
}
},
_setSize: function(id, newSize) {
this._uploadData.updateSize(id, newSize);
this._totalProgress && this._totalProgress.onNewSize(id);
},
_shouldAutoRetry: function(id, name, responseJSON) {
var uploadData = this._uploadData.retrieve({id: id});
/*jshint laxbreak: true */
if (!this._preventRetries[id]
&& this._options.retry.enableAuto
&& uploadData.status !== qq.status.PAUSED) {
if (this._autoRetries[id] === undefined) {
this._autoRetries[id] = 0;
}
if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) {
this._autoRetries[id] += 1;
return true;
}
}
return false;
},
_storeForLater: function(id) {
this._storedIds.push(id);
},
// Maps a file with the button that was used to select it.
_trackButton: function(id) {
var buttonId;
if (qq.supportedFeatures.ajaxUploading) {
buttonId = this._handler.getFile(id).qqButtonId;
}
else {
buttonId = this._getButtonId(this._handler.getInput(id));
}
if (buttonId) {
this._buttonIdsForFileIds[id] = buttonId;
}
},
_upload: function(id, params, endpoint) {
var name = this.getName(id);
if (params) {
this.setParams(params, id);
}
if (endpoint) {
this.setEndpoint(endpoint, id);
}
this._handleCheckedCallback({
name: "onSubmit",
callback: qq.bind(this._options.callbacks.onSubmit, this, id, name),
onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name),
onFailure: qq.bind(this._fileOrBlobRejected, this, id, name),
identifier: id
});
},
_uploadFile: function(id) {
if (!this._handler.upload(id)) {
this._uploadData.setStatus(id, qq.status.QUEUED);
}
},
/**
* Performs some internal validation checks on an item, defined in the `validation` option.
*
* @param fileWrapper Wrapper containing a `file` along with an `id`
* @param validationDescriptor Normalized information about the item (`size`, `name`).
* @returns qq.Promise with appropriate callbacks invoked depending on the validity of the file
* @private
*/
_validateFileOrBlobData: function(fileWrapper, validationDescriptor) {
var self = this,
file = (function() {
if (fileWrapper.file instanceof qq.BlobProxy) {
return fileWrapper.file.referenceBlob;
}
return fileWrapper.file;
}()),
name = validationDescriptor.name,
size = validationDescriptor.size,
buttonId = this._getButtonId(fileWrapper.file),
validationBase = this._getValidationBase(buttonId),
validityChecker = new qq.Promise();
validityChecker.then(
function() {},
function() {
self._fileOrBlobRejected(fileWrapper.id, name);
});
if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) {
this._itemError("typeError", name, file);
return validityChecker.failure();
}
if (size === 0) {
this._itemError("emptyError", name, file);
return validityChecker.failure();
}
if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) {
this._itemError("sizeError", name, file);
return validityChecker.failure();
}
if (size > 0 && size < validationBase.minSizeLimit) {
this._itemError("minSizeError", name, file);
return validityChecker.failure();
}
if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) {
new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then(
validityChecker.success,
function(errorCode) {
self._itemError(errorCode + "ImageError", name, file);
validityChecker.failure();
}
);
}
else {
validityChecker.success();
}
return validityChecker;
},
_wrapCallbacks: function() {
var self, safeCallback, prop;
self = this;
safeCallback = function(name, callback, args) {
var errorMsg;
try {
return callback.apply(self, args);
}
catch (exception) {
errorMsg = exception.message || exception.toString();
self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error");
}
};
/* jshint forin: false, loopfunc: true */
for (prop in this._options.callbacks) {
(function() {
var callbackName, callbackFunc;
callbackName = prop;
callbackFunc = self._options.callbacks[callbackName];
self._options.callbacks[callbackName] = function() {
return safeCallback(callbackName, callbackFunc, arguments);
};
}());
}
}
};
}());
/*globals qq*/
(function() {
"use strict";
qq.FineUploaderBasic = function(o) {
var self = this;
// These options define FineUploaderBasic mode.
this._options = {
debug: false,
button: null,
multiple: true,
maxConnections: 3,
disableCancelForFormUploads: false,
autoUpload: true,
request: {
endpoint: "/server/upload",
params: {},
paramsInBody: true,
customHeaders: {},
forceMultipart: true,
inputName: "qqfile",
uuidName: "qquuid",
totalFileSizeName: "qqtotalfilesize",
filenameParam: "qqfilename"
},
validation: {
allowedExtensions: [],
sizeLimit: 0,
minSizeLimit: 0,
itemLimit: 0,
stopOnFirstInvalidFile: true,
acceptFiles: null,
image: {
maxHeight: 0,
maxWidth: 0,
minHeight: 0,
minWidth: 0
}
},
callbacks: {
onSubmit: function(id, name) {},
onSubmitted: function(id, name) {},
onComplete: function(id, name, responseJSON, maybeXhr) {},
onAllComplete: function(successful, failed) {},
onCancel: function(id, name) {},
onUpload: function(id, name) {},
onUploadChunk: function(id, name, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {},
onResume: function(id, fileName, chunkData) {},
onProgress: function(id, name, loaded, total) {},
onTotalProgress: function(loaded, total) {},
onError: function(id, name, reason, maybeXhrOrXdr) {},
onAutoRetry: function(id, name, attemptNumber) {},
onManualRetry: function(id, name) {},
onValidateBatch: function(fileOrBlobData) {},
onValidate: function(fileOrBlobData) {},
onSubmitDelete: function(id) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {},
onPasteReceived: function(blob) {},
onStatusChange: function(id, oldStatus, newStatus) {},
onSessionRequestComplete: function(response, success, xhrOrXdr) {}
},
messages: {
typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
noFilesError: "No files to upload.",
tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
maxHeightImageError: "Image is too tall.",
maxWidthImageError: "Image is too wide.",
minHeightImageError: "Image is not tall enough.",
minWidthImageError: "Image is not wide enough.",
retryFailTooManyItems: "Retry failed - you have reached your file limit.",
onLeave: "The files are being uploaded, if you leave now the upload will be canceled.",
unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues."
},
retry: {
enableAuto: false,
maxAutoAttempts: 3,
autoAttemptDelay: 5,
preventRetryResponseProperty: "preventRetry"
},
classes: {
buttonHover: "qq-upload-button-hover",
buttonFocus: "qq-upload-button-focus"
},
chunking: {
enabled: false,
concurrent: {
enabled: false
},
mandatory: false,
paramNames: {
partIndex: "qqpartindex",
partByteOffset: "qqpartbyteoffset",
chunkSize: "qqchunksize",
totalFileSize: "qqtotalfilesize",
totalParts: "qqtotalparts"
},
partSize: 2000000,
// only relevant for traditional endpoints, only required when concurrent.enabled === true
success: {
endpoint: null
}
},
resume: {
enabled: false,
recordsExpireIn: 7, //days
paramNames: {
resuming: "qqresume"
}
},
formatFileName: function(fileOrBlobName) {
if (fileOrBlobName !== undefined && fileOrBlobName.length > 33) {
fileOrBlobName = fileOrBlobName.slice(0, 19) + "..." + fileOrBlobName.slice(-14);
}
return fileOrBlobName;
},
text: {
defaultResponseError: "Upload failure reason unknown",
sizeSymbols: ["kB", "MB", "GB", "TB", "PB", "EB"]
},
deleteFile: {
enabled: false,
method: "DELETE",
endpoint: "/server/upload",
customHeaders: {},
params: {}
},
cors: {
expected: false,
sendCredentials: false,
allowXdr: false
},
blobs: {
defaultName: "misc_data"
},
paste: {
targetElement: null,
defaultName: "pasted_image"
},
camera: {
ios: false,
// if ios is true: button is null means target the default button, otherwise target the button specified
button: null
},
// This refers to additional upload buttons to be handled by Fine Uploader.
// Each element is an object, containing `element` as the only required
// property. The `element` must be a container that will ultimately
// contain an invisible `<input type="file">` created by Fine Uploader.
// Optional properties of each object include `multiple`, `validation`,
// and `folders`.
extraButtons: [],
// Depends on the session module. Used to query the server for an initial file list
// during initialization and optionally after a `reset`.
session: {
endpoint: null,
params: {},
customHeaders: {},
refreshOnReset: true
},
// Send parameters associated with an existing form along with the files
form: {
// Element ID, HTMLElement, or null
element: "qq-form",
// Overrides the base `autoUpload`, unless `element` is null.
autoUpload: false,
// true = upload files on form submission (and squelch submit event)
interceptSubmit: true
},
// scale images client side, upload a new file for each scaled version
scaling: {
// send the original file as well
sendOriginal: true,
// fox orientation for scaled images
orient: true,
// If null, scaled image type will match reference image type. This value will be referred to
// for any size record that does not specific a type.
defaultType: null,
defaultQuality: 80,
failureText: "Failed to scale",
includeExif: false,
// metadata about each requested scaled version
sizes: []
},
workarounds: {
iosEmptyVideos: true,
ios8SafariUploads: true,
ios8BrowserCrash: true
}
};
// Replace any default options with user defined ones
qq.extend(this._options, o, true);
this._buttons = [];
this._extraButtonSpecs = {};
this._buttonIdsForFileIds = [];
this._wrapCallbacks();
this._disposeSupport = new qq.DisposeSupport();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData = this._createUploadDataTracker();
this._initFormSupportAndParams();
this._customHeadersStore = this._createStore(this._options.request.customHeaders);
this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders);
this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params);
this._endpointStore = this._createStore(this._options.request.endpoint);
this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint);
this._handler = this._createUploadHandler();
this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler();
if (this._options.button) {
this._defaultButtonId = this._createUploadButton({element: this._options.button}).getButtonId();
}
this._generateExtraButtonSpecs();
this._handleCameraAccess();
if (this._options.paste.targetElement) {
if (qq.PasteSupport) {
this._pasteHandler = this._createPasteHandler();
}
else {
this.log("Paste support module not found", "error");
}
}
this._preventLeaveInProgress();
this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this));
this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._scaler = (qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this))) || {};
if (this._scaler.enabled) {
this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler);
}
if (qq.TotalProgress && qq.supportedFeatures.progressBar) {
this._totalProgress = new qq.TotalProgress(
qq.bind(this._onTotalProgress, this),
function(id) {
var entry = self._uploadData.retrieve({id: id});
return (entry && entry.size) || 0;
}
);
}
this._currentItemLimit = this._options.validation.itemLimit;
};
// Define the private & public API methods.
qq.FineUploaderBasic.prototype = qq.basePublicApi;
qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi);
}());
/*globals qq, XDomainRequest*/
/** Generic class for sending non-upload ajax requests and handling the associated responses **/
qq.AjaxRequester = function(o) {
"use strict";
var log, shouldParamsBeInQueryString,
queue = [],
requestData = {},
options = {
acceptHeader: null,
validMethods: ["POST"],
method: "POST",
contentType: "application/x-www-form-urlencoded",
maxConnections: 3,
customHeaders: {},
endpointStore: {},
paramsStore: {},
mandatedParams: {},
allowXRequestedWithAndCacheControl: true,
successfulResponseCodes: {
DELETE: [200, 202, 204],
POST: [200, 204],
GET: [200]
},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onSend: function(id) {},
onComplete: function(id, xhrOrXdr, isError) {},
onProgress: null
};
qq.extend(options, o);
log = options.log;
if (qq.indexOf(options.validMethods, options.method) < 0) {
throw new Error("'" + options.method + "' is not a supported method for this type of request!");
}
// [Simple methods](http://www.w3.org/TR/cors/#simple-method)
// are defined by the W3C in the CORS spec as a list of methods that, in part,
// make a CORS request eligible to be exempt from preflighting.
function isSimpleMethod() {
return qq.indexOf(["GET", "POST", "HEAD"], options.method) >= 0;
}
// [Simple headers](http://www.w3.org/TR/cors/#simple-header)
// are defined by the W3C in the CORS spec as a list of headers that, in part,
// make a CORS request eligible to be exempt from preflighting.
function containsNonSimpleHeaders(headers) {
var containsNonSimple = false;
qq.each(containsNonSimple, function(idx, header) {
if (qq.indexOf(["Accept", "Accept-Language", "Content-Language", "Content-Type"], header) < 0) {
containsNonSimple = true;
return false;
}
});
return containsNonSimple;
}
function isXdr(xhr) {
//The `withCredentials` test is a commonly accepted way to determine if XHR supports CORS.
return options.cors.expected && xhr.withCredentials === undefined;
}
// Returns either a new `XMLHttpRequest` or `XDomainRequest` instance.
function getCorsAjaxTransport() {
var xhrOrXdr;
if (window.XMLHttpRequest || window.ActiveXObject) {
xhrOrXdr = qq.createXhrInstance();
if (xhrOrXdr.withCredentials === undefined) {
xhrOrXdr = new XDomainRequest();
}
}
return xhrOrXdr;
}
// Returns either a new XHR/XDR instance, or an existing one for the associated `File` or `Blob`.
function getXhrOrXdr(id, suppliedXhr) {
var xhrOrXdr = requestData[id].xhr;
if (!xhrOrXdr) {
if (suppliedXhr) {
xhrOrXdr = suppliedXhr;
}
else {
if (options.cors.expected) {
xhrOrXdr = getCorsAjaxTransport();
}
else {
xhrOrXdr = qq.createXhrInstance();
}
}
requestData[id].xhr = xhrOrXdr;
}
return xhrOrXdr;
}
// Removes element from queue, sends next request
function dequeue(id) {
var i = qq.indexOf(queue, id),
max = options.maxConnections,
nextId;
delete requestData[id];
queue.splice(i, 1);
if (queue.length >= max && i < max) {
nextId = queue[max - 1];
sendRequest(nextId);
}
}
function onComplete(id, xdrError) {
var xhr = getXhrOrXdr(id),
method = options.method,
isError = xdrError === true;
dequeue(id);
if (isError) {
log(method + " request for " + id + " has failed", "error");
}
else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) {
isError = true;
log(method + " request for " + id + " has failed - response code " + xhr.status, "error");
}
options.onComplete(id, xhr, isError);
}
function getParams(id) {
var onDemandParams = requestData[id].additionalParams,
mandatedParams = options.mandatedParams,
params;
if (options.paramsStore.get) {
params = options.paramsStore.get(id);
}
if (onDemandParams) {
qq.each(onDemandParams, function(name, val) {
params = params || {};
params[name] = val;
});
}
if (mandatedParams) {
qq.each(mandatedParams, function(name, val) {
params = params || {};
params[name] = val;
});
}
return params;
}
function sendRequest(id, optXhr) {
var xhr = getXhrOrXdr(id, optXhr),
method = options.method,
params = getParams(id),
payload = requestData[id].payload,
url;
options.onSend(id);
url = createUrl(id, params);
// XDR and XHR status detection APIs differ a bit.
if (isXdr(xhr)) {
xhr.onload = getXdrLoadHandler(id);
xhr.onerror = getXdrErrorHandler(id);
}
else {
xhr.onreadystatechange = getXhrReadyStateChangeHandler(id);
}
registerForUploadProgress(id);
// The last parameter is assumed to be ignored if we are actually using `XDomainRequest`.
xhr.open(method, url, true);
// Instruct the transport to send cookies along with the CORS request,
// unless we are using `XDomainRequest`, which is not capable of this.
if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) {
xhr.withCredentials = true;
}
setHeaders(id);
log("Sending " + method + " request for " + id);
if (payload) {
xhr.send(payload);
}
else if (shouldParamsBeInQueryString || !params) {
xhr.send();
}
else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) {
xhr.send(qq.obj2url(params, ""));
}
else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) {
xhr.send(JSON.stringify(params));
}
else {
xhr.send(params);
}
return xhr;
}
function createUrl(id, params) {
var endpoint = options.endpointStore.get(id),
addToPath = requestData[id].addToPath;
/*jshint -W116,-W041 */
if (addToPath != undefined) {
endpoint += "/" + addToPath;
}
if (shouldParamsBeInQueryString && params) {
return qq.obj2url(params, endpoint);
}
else {
return endpoint;
}
}
// Invoked by the UA to indicate a number of possible states that describe
// a live `XMLHttpRequest` transport.
function getXhrReadyStateChangeHandler(id) {
return function() {
if (getXhrOrXdr(id).readyState === 4) {
onComplete(id);
}
};
}
function registerForUploadProgress(id) {
var onProgress = options.onProgress;
if (onProgress) {
getXhrOrXdr(id).upload.onprogress = function(e) {
if (e.lengthComputable) {
onProgress(id, e.loaded, e.total);
}
};
}
}
// This will be called by IE to indicate **success** for an associated
// `XDomainRequest` transported request.
function getXdrLoadHandler(id) {
return function() {
onComplete(id);
};
}
// This will be called by IE to indicate **failure** for an associated
// `XDomainRequest` transported request.
function getXdrErrorHandler(id) {
return function() {
onComplete(id, true);
};
}
function setHeaders(id) {
var xhr = getXhrOrXdr(id),
customHeaders = options.customHeaders,
onDemandHeaders = requestData[id].additionalHeaders || {},
method = options.method,
allHeaders = {};
// If XDomainRequest is being used, we can't set headers, so just ignore this block.
if (!isXdr(xhr)) {
options.acceptHeader && xhr.setRequestHeader("Accept", options.acceptHeader);
// Only attempt to add X-Requested-With & Cache-Control if permitted
if (options.allowXRequestedWithAndCacheControl) {
// Do not add X-Requested-With & Cache-Control if this is a cross-origin request
// OR the cross-origin request contains a non-simple method or header.
// This is done to ensure a preflight is not triggered exclusively based on the
// addition of these 2 non-simple headers.
if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Cache-Control", "no-cache");
}
}
if (options.contentType && (method === "POST" || method === "PUT")) {
xhr.setRequestHeader("Content-Type", options.contentType);
}
qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders);
qq.extend(allHeaders, onDemandHeaders);
qq.each(allHeaders, function(name, val) {
xhr.setRequestHeader(name, val);
});
}
}
function isResponseSuccessful(responseCode) {
return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0;
}
function prepareToSend(id, optXhr, addToPath, additionalParams, additionalHeaders, payload) {
requestData[id] = {
addToPath: addToPath,
additionalParams: additionalParams,
additionalHeaders: additionalHeaders,
payload: payload
};
var len = queue.push(id);
// if too many active connections, wait...
if (len <= options.maxConnections) {
return sendRequest(id, optXhr);
}
}
shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE";
qq.extend(this, {
// Start the process of sending the request. The ID refers to the file associated with the request.
initTransport: function(id) {
var path, params, headers, payload, cacheBuster;
return {
// Optionally specify the end of the endpoint path for the request.
withPath: function(appendToPath) {
path = appendToPath;
return this;
},
// Optionally specify additional parameters to send along with the request.
// These will be added to the query string for GET/DELETE requests or the payload
// for POST/PUT requests. The Content-Type of the request will be used to determine
// how these parameters should be formatted as well.
withParams: function(additionalParams) {
params = additionalParams;
return this;
},
// Optionally specify additional headers to send along with the request.
withHeaders: function(additionalHeaders) {
headers = additionalHeaders;
return this;
},
// Optionally specify a payload/body for the request.
withPayload: function(thePayload) {
payload = thePayload;
return this;
},
// Appends a cache buster (timestamp) to the request URL as a query parameter (only if GET or DELETE)
withCacheBuster: function() {
cacheBuster = true;
return this;
},
// Send the constructed request.
send: function(optXhr) {
if (cacheBuster && qq.indexOf(["GET", "DELETE"], options.method) >= 0) {
params.qqtimestamp = new Date().getTime();
}
return prepareToSend(id, optXhr, path, params, headers, payload);
}
};
},
canceled: function(id) {
dequeue(id);
}
});
};
/* globals qq */
/**
* Common upload handler functions.
*
* @constructor
*/
qq.UploadHandler = function(spec) {
"use strict";
var proxy = spec.proxy,
fileState = {},
onCancel = proxy.onCancel,
getName = proxy.getName;
qq.extend(this, {
add: function(id, fileItem) {
fileState[id] = fileItem;
fileState[id].temp = {};
},
cancel: function(id) {
var self = this,
cancelFinalizationEffort = new qq.Promise(),
onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort);
onCancelRetVal.then(function() {
if (self.isValid(id)) {
fileState[id].canceled = true;
self.expunge(id);
}
cancelFinalizationEffort.success();
});
},
expunge: function(id) {
delete fileState[id];
},
getThirdPartyFileId: function(id) {
return fileState[id].key;
},
isValid: function(id) {
return fileState[id] !== undefined;
},
reset: function() {
fileState = {};
},
_getFileState: function(id) {
return fileState[id];
},
_setThirdPartyFileId: function(id, thirdPartyFileId) {
fileState[id].key = thirdPartyFileId;
},
_wasCanceled: function(id) {
return !!fileState[id].canceled;
}
});
};
/*globals qq*/
/**
* Base upload handler module. Controls more specific handlers.
*
* @param o Options. Passed along to the specific handler submodule as well.
* @param namespace [optional] Namespace for the specific handler.
*/
qq.UploadHandlerController = function(o, namespace) {
"use strict";
var controller = this,
chunkingPossible = false,
concurrentChunkingPossible = false,
chunking, preventRetryResponse, log, handler,
options = {
paramsStore: {},
maxConnections: 3, // maximum number of concurrent uploads
chunking: {
enabled: false,
multiple: {
enabled: false
}
},
log: function(str, level) {},
onProgress: function(id, fileName, loaded, total) {},
onComplete: function(id, fileName, response, xhr) {},
onCancel: function(id, fileName) {},
onUploadPrep: function(id) {}, // Called if non-trivial operations will be performed before onUpload
onUpload: function(id, fileName) {},
onUploadChunk: function(id, fileName, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, response, xhr) {},
onAutoRetry: function(id, fileName, response, xhr) {},
onResume: function(id, fileName, chunkData) {},
onUuidChanged: function(id, newUuid) {},
getName: function(id) {},
setSize: function(id, newSize) {},
isQueued: function(id) {},
getIdsInProxyGroup: function(id) {},
getIdsInBatch: function(id) {}
},
chunked = {
// Called when each chunk has uploaded successfully
done: function(id, chunkIdx, response, xhr) {
var chunkData = handler._getChunkData(id, chunkIdx);
handler._getFileState(id).attemptingResume = false;
delete handler._getFileState(id).temp.chunkProgress[chunkIdx];
handler._getFileState(id).loaded += chunkData.size;
options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr);
},
// Called when all chunks have been successfully uploaded and we want to ask the handler to perform any
// logic associated with closing out the file, such as combining the chunks.
finalize: function(id) {
var size = options.getSize(id),
name = options.getName(id);
log("All chunks have been uploaded for " + id + " - finalizing....");
handler.finalizeChunks(id).then(
function(response, xhr) {
log("Finalize successful for " + id);
var normaizedResponse = upload.normalizeResponse(response, true);
options.onProgress(id, name, size, size);
handler._maybeDeletePersistedChunkData(id);
upload.cleanup(id, normaizedResponse, xhr);
},
function(response, xhr) {
var normaizedResponse = upload.normalizeResponse(response, false);
log("Problem finalizing chunks for file ID " + id + " - " + normaizedResponse.error, "error");
if (normaizedResponse.reset) {
chunked.reset(id);
}
if (!options.onAutoRetry(id, name, normaizedResponse, xhr)) {
upload.cleanup(id, normaizedResponse, xhr);
}
}
);
},
hasMoreParts: function(id) {
return !!handler._getFileState(id).chunking.remaining.length;
},
nextPart: function(id) {
var nextIdx = handler._getFileState(id).chunking.remaining.shift();
if (nextIdx >= handler._getTotalChunks(id)) {
nextIdx = null;
}
return nextIdx;
},
reset: function(id) {
log("Server or callback has ordered chunking effort to be restarted on next attempt for item ID " + id, "error");
handler._maybeDeletePersistedChunkData(id);
handler.reevaluateChunking(id);
handler._getFileState(id).loaded = 0;
},
sendNext: function(id) {
var size = options.getSize(id),
name = options.getName(id),
chunkIdx = chunked.nextPart(id),
chunkData = handler._getChunkData(id, chunkIdx),
resuming = handler._getFileState(id).attemptingResume,
inProgressChunks = handler._getFileState(id).chunking.inProgress || [];
if (handler._getFileState(id).loaded == null) {
handler._getFileState(id).loaded = 0;
}
// Don't follow-through with the resume attempt if the integrator returns false from onResume
if (resuming && options.onResume(id, name, chunkData) === false) {
chunked.reset(id);
chunkIdx = chunked.nextPart(id);
chunkData = handler._getChunkData(id, chunkIdx);
resuming = false;
}
// If all chunks have already uploaded successfully, we must be re-attempting the finalize step.
if (chunkIdx == null && inProgressChunks.length === 0) {
chunked.finalize(id);
}
// Send the next chunk
else {
log("Sending chunked upload request for item " + id + ": bytes " + (chunkData.start + 1) + "-" + chunkData.end + " of " + size);
options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData));
inProgressChunks.push(chunkIdx);
handler._getFileState(id).chunking.inProgress = inProgressChunks;
if (concurrentChunkingPossible) {
connectionManager.open(id, chunkIdx);
}
if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) {
chunked.sendNext(id);
}
handler.uploadChunk(id, chunkIdx, resuming).then(
// upload chunk success
function success(response, xhr) {
log("Chunked upload request succeeded for " + id + ", chunk " + chunkIdx);
handler.clearCachedChunk(id, chunkIdx);
var inProgressChunks = handler._getFileState(id).chunking.inProgress || [],
responseToReport = upload.normalizeResponse(response, true),
inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx);
log(qq.format("Chunk {} for file {} uploaded successfully.", chunkIdx, id));
chunked.done(id, chunkIdx, responseToReport, xhr);
if (inProgressChunkIdx >= 0) {
inProgressChunks.splice(inProgressChunkIdx, 1);
}
handler._maybePersistChunkedState(id);
if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) {
chunked.finalize(id);
}
else if (chunked.hasMoreParts(id)) {
chunked.sendNext(id);
}
},
// upload chunk failure
function failure(response, xhr) {
log("Chunked upload request failed for " + id + ", chunk " + chunkIdx);
handler.clearCachedChunk(id, chunkIdx);
var responseToReport = upload.normalizeResponse(response, false),
inProgressIdx;
if (responseToReport.reset) {
chunked.reset(id);
}
else {
inProgressIdx = qq.indexOf(handler._getFileState(id).chunking.inProgress, chunkIdx);
if (inProgressIdx >= 0) {
handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1);
handler._getFileState(id).chunking.remaining.unshift(chunkIdx);
}
}
// We may have aborted all other in-progress chunks for this file due to a failure.
// If so, ignore the failures associated with those aborts.
if (!handler._getFileState(id).temp.ignoreFailure) {
// If this chunk has failed, we want to ignore all other failures of currently in-progress
// chunks since they will be explicitly aborted
if (concurrentChunkingPossible) {
handler._getFileState(id).temp.ignoreFailure = true;
qq.each(handler._getXhrs(id), function(ckid, ckXhr) {
ckXhr.abort();
});
// We must indicate that all aborted chunks are no longer in progress
handler.moveInProgressToRemaining(id);
// Free up any connections used by these chunks, but don't allow any
// other files to take up the connections (until we have exhausted all auto-retries)
connectionManager.free(id, true);
}
if (!options.onAutoRetry(id, name, responseToReport, xhr)) {
// If one chunk fails, abort all of the others to avoid odd race conditions that occur
// if a chunk succeeds immediately after one fails before we have determined if the upload
// is a failure or not.
upload.cleanup(id, responseToReport, xhr);
}
}
}
)
.done(function() {
handler.clearXhr(id, chunkIdx);
}) ;
}
}
},
connectionManager = {
_open: [],
_openChunks: {},
_waiting: [],
available: function() {
var max = options.maxConnections,
openChunkEntriesCount = 0,
openChunksCount = 0;
qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) {
openChunkEntriesCount++;
openChunksCount += openChunkIndexes.length;
});
return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount);
},
/**
* Removes element from queue, starts upload of next
*/
free: function(id, dontAllowNext) {
var allowNext = !dontAllowNext,
waitingIndex = qq.indexOf(connectionManager._waiting, id),
connectionsIndex = qq.indexOf(connectionManager._open, id),
nextId;
delete connectionManager._openChunks[id];
if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) {
log("Generated blob upload has ended for " + id + ", disposing generated blob.");
delete handler._getFileState(id).file;
}
// If this file was not consuming a connection, it was just waiting, so remove it from the waiting array
if (waitingIndex >= 0) {
connectionManager._waiting.splice(waitingIndex, 1);
}
// If this file was consuming a connection, allow the next file to be uploaded
else if (allowNext && connectionsIndex >= 0) {
connectionManager._open.splice(connectionsIndex, 1);
nextId = connectionManager._waiting.shift();
if (nextId >= 0) {
connectionManager._open.push(nextId);
upload.start(nextId);
}
}
},
getWaitingOrConnected: function() {
var waitingOrConnected = [];
// Chunked files may have multiple connections open per chunk (if concurrent chunking is enabled)
// We need to grab the file ID of any file that has at least one chunk consuming a connection.
qq.each(connectionManager._openChunks, function(fileId, chunks) {
if (chunks && chunks.length) {
waitingOrConnected.push(parseInt(fileId));
}
});
// For non-chunked files, only one connection will be consumed per file.
// This is where we aggregate those file IDs.
qq.each(connectionManager._open, function(idx, fileId) {
if (!connectionManager._openChunks[fileId]) {
waitingOrConnected.push(parseInt(fileId));
}
});
// There may be files waiting for a connection.
waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting);
return waitingOrConnected;
},
isUsingConnection: function(id) {
return qq.indexOf(connectionManager._open, id) >= 0;
},
open: function(id, chunkIdx) {
if (chunkIdx == null) {
connectionManager._waiting.push(id);
}
if (connectionManager.available()) {
if (chunkIdx == null) {
connectionManager._waiting.pop();
connectionManager._open.push(id);
}
else {
(function() {
var openChunksEntry = connectionManager._openChunks[id] || [];
openChunksEntry.push(chunkIdx);
connectionManager._openChunks[id] = openChunksEntry;
}());
}
return true;
}
return false;
},
reset: function() {
connectionManager._waiting = [];
connectionManager._open = [];
}
},
simple = {
send: function(id, name) {
handler._getFileState(id).loaded = 0;
log("Sending simple upload request for " + id);
handler.uploadFile(id).then(
function(response, optXhr) {
log("Simple upload request succeeded for " + id);
var responseToReport = upload.normalizeResponse(response, true),
size = options.getSize(id);
options.onProgress(id, name, size, size);
upload.maybeNewUuid(id, responseToReport);
upload.cleanup(id, responseToReport, optXhr);
},
function(response, optXhr) {
log("Simple upload request failed for " + id);
var responseToReport = upload.normalizeResponse(response, false);
if (!options.onAutoRetry(id, name, responseToReport, optXhr)) {
upload.cleanup(id, responseToReport, optXhr);
}
}
);
}
},
upload = {
cancel: function(id) {
log("Cancelling " + id);
options.paramsStore.remove(id);
connectionManager.free(id);
},
cleanup: function(id, response, optXhr) {
var name = options.getName(id);
options.onComplete(id, name, response, optXhr);
if (handler._getFileState(id)) {
handler._clearXhrs && handler._clearXhrs(id);
}
connectionManager.free(id);
},
// Returns a qq.BlobProxy, or an actual File/Blob if no proxy is involved, or undefined
// if none of these are available for the ID
getProxyOrBlob: function(id) {
return (handler.getProxy && handler.getProxy(id)) ||
(handler.getFile && handler.getFile(id));
},
initHandler: function() {
var handlerType = namespace ? qq[namespace] : qq.traditional,
handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form";
handler = new handlerType[handlerModuleSubtype + "UploadHandler"](
options,
{
getDataByUuid: options.getDataByUuid,
getName: options.getName,
getSize: options.getSize,
getUuid: options.getUuid,
log: log,
onCancel: options.onCancel,
onProgress: options.onProgress,
onUuidChanged: options.onUuidChanged
}
);
if (handler._removeExpiredChunkingRecords) {
handler._removeExpiredChunkingRecords();
}
},
isDeferredEligibleForUpload: function(id) {
return options.isQueued(id);
},
// For Blobs that are part of a group of generated images, along with a reference image,
// this will ensure the blobs in the group are uploaded in the order they were triggered,
// even if some async processing must be completed on one or more Blobs first.
maybeDefer: function(id, blob) {
// If we don't have a file/blob yet & no file/blob exists for this item, request it,
// and then submit the upload to the specific handler once the blob is available.
// ASSUMPTION: This condition will only ever be true if XHR uploading is supported.
if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) {
// Blob creation may take some time, so the caller may want to update the
// UI to indicate that an operation is in progress, even before the actual
// upload begins and an onUpload callback is invoked.
options.onUploadPrep(id);
log("Attempting to generate a blob on-demand for " + id);
blob.create().then(function(generatedBlob) {
log("Generated an on-demand blob for " + id);
// Update record associated with this file by providing the generated Blob
handler.updateBlob(id, generatedBlob);
// Propagate the size for this generated Blob
options.setSize(id, generatedBlob.size);
// Order handler to recalculate chunking possibility, if applicable
handler.reevaluateChunking(id);
upload.maybeSendDeferredFiles(id);
},
// Blob could not be generated. Fail the upload & attempt to prevent retries. Also bubble error message.
function(errorMessage) {
var errorResponse = {};
if (errorMessage) {
errorResponse.error = errorMessage;
}
log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error");
options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null);
upload.maybeSendDeferredFiles(id);
connectionManager.free(id);
});
}
else {
return upload.maybeSendDeferredFiles(id);
}
return false;
},
// Upload any grouped blobs, in the proper order, that are ready to be uploaded
maybeSendDeferredFiles: function(id) {
var idsInGroup = options.getIdsInProxyGroup(id),
uploadedThisId = false;
if (idsInGroup && idsInGroup.length) {
log("Maybe ready to upload proxy group file " + id);
qq.each(idsInGroup, function(idx, idInGroup) {
if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) {
uploadedThisId = idInGroup === id;
upload.now(idInGroup);
}
else if (upload.isDeferredEligibleForUpload(idInGroup)) {
return false;
}
});
}
else {
uploadedThisId = true;
upload.now(id);
}
return uploadedThisId;
},
maybeNewUuid: function(id, response) {
if (response.newUuid !== undefined) {
options.onUuidChanged(id, response.newUuid);
}
},
// The response coming from handler implementations may be in various formats.
// Instead of hoping a promise nested 5 levels deep will always return an object
// as its first param, let's just normalize the response here.
normalizeResponse: function(originalResponse, successful) {
var response = originalResponse;
// The passed "response" param may not be a response at all.
// It could be a string, detailing the error, for example.
if (!qq.isObject(originalResponse)) {
response = {};
if (qq.isString(originalResponse) && !successful) {
response.error = originalResponse;
}
}
response.success = successful;
return response;
},
now: function(id) {
var name = options.getName(id);
if (!controller.isValid(id)) {
throw new qq.Error(id + " is not a valid file ID to upload!");
}
options.onUpload(id, name);
if (chunkingPossible && handler._shouldChunkThisFile(id)) {
chunked.sendNext(id);
}
else {
simple.send(id, name);
}
},
start: function(id) {
var blobToUpload = upload.getProxyOrBlob(id);
if (blobToUpload) {
return upload.maybeDefer(id, blobToUpload);
}
else {
upload.now(id);
return true;
}
}
};
qq.extend(this, {
/**
* Adds file or file input to the queue
**/
add: function(id, file) {
handler.add.apply(this, arguments);
},
/**
* Sends the file identified by id
*/
upload: function(id) {
if (connectionManager.open(id)) {
return upload.start(id);
}
return false;
},
retry: function(id) {
// On retry, if concurrent chunking has been enabled, we may have aborted all other in-progress chunks
// for a file when encountering a failed chunk upload. We then signaled the controller to ignore
// all failures associated with these aborts. We are now retrying, so we don't want to ignore
// any more failures at this point.
if (concurrentChunkingPossible) {
handler._getFileState(id).temp.ignoreFailure = false;
}
// If we are attempting to retry a file that is already consuming a connection, this is likely an auto-retry.
// Just go ahead and ask the handler to upload again.
if (connectionManager.isUsingConnection(id)) {
return upload.start(id);
}
// If we are attempting to retry a file that is not currently consuming a connection,
// this is likely a manual retry attempt. We will need to ensure a connection is available
// before the retry commences.
else {
return controller.upload(id);
}
},
/**
* Cancels file upload by id
*/
cancel: function(id) {
var cancelRetVal = handler.cancel(id);
if (qq.isGenericPromise(cancelRetVal)) {
cancelRetVal.then(function() {
upload.cancel(id);
});
}
else if (cancelRetVal !== false) {
upload.cancel(id);
}
},
/**
* Cancels all queued or in-progress uploads
*/
cancelAll: function() {
var waitingOrConnected = connectionManager.getWaitingOrConnected(),
i;
// ensure files are cancelled in reverse order which they were added
// to avoid a flash of time where a queued file begins to upload before it is canceled
if (waitingOrConnected.length) {
for (i = waitingOrConnected.length - 1; i >= 0; i--) {
controller.cancel(waitingOrConnected[i]);
}
}
connectionManager.reset();
},
// Returns a File, Blob, or the Blob/File for the reference/parent file if the targeted blob is a proxy.
// Undefined if no file record is available.
getFile: function(id) {
if (handler.getProxy && handler.getProxy(id)) {
return handler.getProxy(id).referenceBlob;
}
return handler.getFile && handler.getFile(id);
},
// Returns true if the Blob associated with the ID is related to a proxy s
isProxied: function(id) {
return !!(handler.getProxy && handler.getProxy(id));
},
getInput: function(id) {
if (handler.getInput) {
return handler.getInput(id);
}
},
reset: function() {
log("Resetting upload handler");
controller.cancelAll();
connectionManager.reset();
handler.reset();
},
expunge: function(id) {
if (controller.isValid(id)) {
return handler.expunge(id);
}
},
/**
* Determine if the file exists.
*/
isValid: function(id) {
return handler.isValid(id);
},
getResumableFilesData: function() {
if (handler.getResumableFilesData) {
return handler.getResumableFilesData();
}
return [];
},
/**
* This may or may not be implemented, depending on the handler. For handlers where a third-party ID is
* available (such as the "key" for Amazon S3), this will return that value. Otherwise, the return value
* will be undefined.
*
* @param id Internal file ID
* @returns {*} Some identifier used by a 3rd-party service involved in the upload process
*/
getThirdPartyFileId: function(id) {
if (controller.isValid(id)) {
return handler.getThirdPartyFileId(id);
}
},
/**
* Attempts to pause the associated upload if the specific handler supports this and the file is "valid".
* @param id ID of the upload/file to pause
* @returns {boolean} true if the upload was paused
*/
pause: function(id) {
if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) {
connectionManager.free(id);
handler.moveInProgressToRemaining(id);
return true;
}
return false;
},
// True if the file is eligible for pause/resume.
isResumable: function(id) {
return !!handler.isResumable && handler.isResumable(id);
}
});
qq.extend(options, o);
log = options.log;
chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking;
concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled;
preventRetryResponse = (function() {
var response = {};
response[options.preventRetryParam] = true;
return response;
}());
upload.initHandler();
};
/* globals qq */
/**
* Common APIs exposed to creators of upload via form/iframe handlers. This is reused and possibly overridden
* in some cases by specific form upload handlers.
*
* @constructor
*/
qq.FormUploadHandler = function(spec) {
"use strict";
var options = spec.options,
handler = this,
proxy = spec.proxy,
formHandlerInstanceId = qq.getUniqueId(),
onloadCallbacks = {},
detachLoadEvents = {},
postMessageCallbackTimers = {},
isCors = options.isCors,
inputName = options.inputName,
getUuid = proxy.getUuid,
log = proxy.log,
corsMessageReceiver = new qq.WindowReceiveMessage({log: log});
/**
* Remove any trace of the file from the handler.
*
* @param id ID of the associated file
*/
function expungeFile(id) {
delete detachLoadEvents[id];
// If we are dealing with CORS, we might still be waiting for a response from a loaded iframe.
// In that case, terminate the timer waiting for a message from the loaded iframe
// and stop listening for any more messages coming from this iframe.
if (isCors) {
clearTimeout(postMessageCallbackTimers[id]);
delete postMessageCallbackTimers[id];
corsMessageReceiver.stopReceivingMessages(id);
}
var iframe = document.getElementById(handler._getIframeName(id));
if (iframe) {
// To cancel request set src to something else. We use src="javascript:false;"
// because it doesn't trigger ie6 prompt on https
/* jshint scripturl:true */
iframe.setAttribute("src", "javascript:false;");
qq(iframe).remove();
}
}
/**
* @param iframeName `document`-unique Name of the associated iframe
* @returns {*} ID of the associated file
*/
function getFileIdForIframeName(iframeName) {
return iframeName.split("_")[0];
}
/**
* Generates an iframe to be used as a target for upload-related form submits. This also adds the iframe
* to the current `document`. Album that the iframe is hidden from view.
*
* @param name Name of the iframe.
* @returns {HTMLIFrameElement} The created iframe
*/
function initIframeForUpload(name) {
var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />");
iframe.setAttribute("id", name);
iframe.style.display = "none";
document.body.appendChild(iframe);
return iframe;
}
/**
* If we are in CORS mode, we must listen for messages (containing the server response) from the associated
* iframe, since we cannot directly parse the content of the iframe due to cross-origin restrictions.
*
* @param iframe Listen for messages on this iframe.
* @param callback Invoke this callback with the message from the iframe.
*/
function registerPostMessageCallback(iframe, callback) {
var iframeName = iframe.id,
fileId = getFileIdForIframeName(iframeName),
uuid = getUuid(fileId);
onloadCallbacks[uuid] = callback;
// When the iframe has loaded (after the server responds to an upload request)
// declare the attempt a failure if we don't receive a valid message shortly after the response comes in.
detachLoadEvents[fileId] = qq(iframe).attach("load", function() {
if (handler.getInput(fileId)) {
log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")");
postMessageCallbackTimers[iframeName] = setTimeout(function() {
var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName;
log(errorMessage, "error");
callback({
error: errorMessage
});
}, 1000);
}
});
// Listen for messages coming from this iframe. When a message has been received, cancel the timer
// that declares the upload a failure if a message is not received within a reasonable amount of time.
corsMessageReceiver.receiveMessage(iframeName, function(message) {
log("Received the following window message: '" + message + "'");
var fileId = getFileIdForIframeName(iframeName),
response = handler._parseJsonResponse(message),
uuid = response.uuid,
onloadCallback;
if (uuid && onloadCallbacks[uuid]) {
log("Handling response for iframe name " + iframeName);
clearTimeout(postMessageCallbackTimers[iframeName]);
delete postMessageCallbackTimers[iframeName];
handler._detachLoadEvent(iframeName);
onloadCallback = onloadCallbacks[uuid];
delete onloadCallbacks[uuid];
corsMessageReceiver.stopReceivingMessages(iframeName);
onloadCallback(response);
}
else if (!uuid) {
log("'" + message + "' does not contain a UUID - ignoring.");
}
});
}
qq.extend(this, new qq.UploadHandler(spec));
qq.override(this, function(super_) {
return {
/**
* Adds File or Blob to the queue
**/
add: function(id, fileInput) {
super_.add(id, {input: fileInput});
fileInput.setAttribute("name", inputName);
// remove file input from DOM
if (fileInput.parentNode) {
qq(fileInput).remove();
}
},
expunge: function(id) {
expungeFile(id);
super_.expunge(id);
},
isValid: function(id) {
return super_.isValid(id) &&
handler._getFileState(id).input !== undefined;
}
};
});
qq.extend(this, {
getInput: function(id) {
return handler._getFileState(id).input;
},
/**
* This function either delegates to a more specific message handler if CORS is involved,
* or simply registers a callback when the iframe has been loaded that invokes the passed callback
* after determining if the content of the iframe is accessible.
*
* @param iframe Associated iframe
* @param callback Callback to invoke after we have determined if the iframe content is accessible.
*/
_attachLoadEvent: function(iframe, callback) {
/*jslint eqeq: true*/
var responseDescriptor;
if (isCors) {
registerPostMessageCallback(iframe, callback);
}
else {
detachLoadEvents[iframe.id] = qq(iframe).attach("load", function() {
log("Received response for " + iframe.id);
// when we remove iframe from dom
// the request stops, but in IE load
// event fires
if (!iframe.parentNode) {
return;
}
try {
// fixing Opera 10.53
if (iframe.contentDocument &&
iframe.contentDocument.body &&
iframe.contentDocument.body.innerHTML == "false") {
// In Opera event is fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
// when we upload file with iframe
return;
}
}
catch (error) {
//IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases
log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error");
responseDescriptor = {success: false};
}
callback(responseDescriptor);
});
}
},
/**
* Creates an iframe with a specific document-unique name.
*
* @param id ID of the associated file
* @returns {HTMLIFrameElement}
*/
_createIframe: function(id) {
var iframeName = handler._getIframeName(id);
return initIframeForUpload(iframeName);
},
/**
* Called when we are no longer interested in being notified when an iframe has loaded.
*
* @param id Associated file ID
*/
_detachLoadEvent: function(id) {
if (detachLoadEvents[id] !== undefined) {
detachLoadEvents[id]();
delete detachLoadEvents[id];
}
},
/**
* @param fileId ID of the associated file
* @returns {string} The `document`-unique name of the iframe
*/
_getIframeName: function(fileId) {
return fileId + "_" + formHandlerInstanceId;
},
/**
* Generates a form element and appends it to the `document`. When the form is submitted, a specific iframe is targeted.
* The name of the iframe is passed in as a property of the spec parameter, and must be unique in the `document`. Album
* that the form is hidden from view.
*
* @param spec An object containing various properties to be used when constructing the form. Required properties are
* currently: `method`, `endpoint`, `params`, `paramsInBody`, and `targetName`.
* @returns {HTMLFormElement} The created form
*/
_initFormForUpload: function(spec) {
var method = spec.method,
endpoint = spec.endpoint,
params = spec.params,
paramsInBody = spec.paramsInBody,
targetName = spec.targetName,
form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"),
url = endpoint;
if (paramsInBody) {
qq.obj2Inputs(params, form);
}
else {
url = qq.obj2url(params, endpoint);
}
form.setAttribute("action", url);
form.setAttribute("target", targetName);
form.style.display = "none";
document.body.appendChild(form);
return form;
},
/**
* @param innerHtmlOrMessage JSON message
* @returns {*} The parsed response, or an empty object if the response could not be parsed
*/
_parseJsonResponse: function(innerHtmlOrMessage) {
var response = {};
try {
response = qq.parseJson(innerHtmlOrMessage);
}
catch (error) {
log("Error when attempting to parse iframe upload response (" + error.message + ")", "error");
}
return response;
}
});
};
/* globals qq */
/**
* Common API exposed to creators of XHR handlers. This is reused and possibly overriding in some cases by specific
* XHR upload handlers.
*
* @constructor
*/
qq.XhrUploadHandler = function(spec) {
"use strict";
var handler = this,
namespace = spec.options.namespace,
proxy = spec.proxy,
chunking = spec.options.chunking,
resume = spec.options.resume,
chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking,
resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume,
getName = proxy.getName,
getSize = proxy.getSize,
getUuid = proxy.getUuid,
getEndpoint = proxy.getEndpoint,
getDataByUuid = proxy.getDataByUuid,
onUuidChanged = proxy.onUuidChanged,
onProgress = proxy.onProgress,
log = proxy.log;
function abort(id) {
qq.each(handler._getXhrs(id), function(xhrId, xhr) {
var ajaxRequester = handler._getAjaxRequester(id, xhrId);
xhr.onreadystatechange = null;
xhr.upload.onprogress = null;
xhr.abort();
ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id);
});
}
qq.extend(this, new qq.UploadHandler(spec));
qq.override(this, function(super_) {
return {
/**
* Adds File or Blob to the queue
**/
add: function(id, blobOrProxy) {
if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) {
super_.add(id, {file: blobOrProxy});
}
else if (blobOrProxy instanceof qq.BlobProxy) {
super_.add(id, {proxy: blobOrProxy});
}
else {
throw new Error("Passed obj is not a File, Blob, or proxy");
}
handler._initTempState(id);
resumeEnabled && handler._maybePrepareForResume(id);
},
expunge: function(id) {
abort(id);
handler._maybeDeletePersistedChunkData(id);
handler._clearXhrs(id);
super_.expunge(id);
}
};
});
qq.extend(this, {
// Clear the cached chunk `Blob` after we are done with it, just in case the `Blob` bytes are stored in memory.
clearCachedChunk: function(id, chunkIdx) {
delete handler._getFileState(id).temp.cachedChunks[chunkIdx];
},
clearXhr: function(id, chunkIdx) {
var tempState = handler._getFileState(id).temp;
if (tempState.xhrs) {
delete tempState.xhrs[chunkIdx];
}
if (tempState.ajaxRequesters) {
delete tempState.ajaxRequesters[chunkIdx];
}
},
// Called when all chunks have been successfully uploaded. Expected promissory return type.
// This defines the default behavior if nothing further is required when all chunks have been uploaded.
finalizeChunks: function(id, responseParser) {
var lastChunkIdx = handler._getTotalChunks(id) - 1,
xhr = handler._getXhr(id, lastChunkIdx);
if (responseParser) {
return new qq.Promise().success(responseParser(xhr), xhr);
}
return new qq.Promise().success({}, xhr);
},
getFile: function(id) {
return handler.isValid(id) && handler._getFileState(id).file;
},
getProxy: function(id) {
return handler.isValid(id) && handler._getFileState(id).proxy;
},
/**
* @returns {Array} Array of objects containing properties useful to integrators
* when it is important to determine which files are potentially resumable.
*/
getResumableFilesData: function() {
var resumableFilesData = [];
handler._iterateResumeRecords(function(key, uploadData) {
handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining);
var data = {
name: uploadData.name,
remaining: uploadData.chunking.remaining,
size: uploadData.size,
uuid: uploadData.uuid
};
if (uploadData.key) {
data.key = uploadData.key;
}
resumableFilesData.push(data);
});
return resumableFilesData;
},
isResumable: function(id) {
return !!chunking && handler.isValid(id) && !handler._getFileState(id).notResumable;
},
moveInProgressToRemaining: function(id, optInProgress, optRemaining) {
var inProgress = optInProgress || handler._getFileState(id).chunking.inProgress,
remaining = optRemaining || handler._getFileState(id).chunking.remaining;
if (inProgress) {
inProgress.reverse();
qq.each(inProgress, function(idx, chunkIdx) {
remaining.unshift(chunkIdx);
});
inProgress.length = 0;
}
},
pause: function(id) {
if (handler.isValid(id)) {
log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id)));
handler._getFileState(id).paused = true;
abort(id);
return true;
}
},
reevaluateChunking: function(id) {
if (chunking && handler.isValid(id)) {
var state = handler._getFileState(id),
totalChunks,
i;
delete state.chunking;
state.chunking = {};
totalChunks = handler._getTotalChunks(id);
if (totalChunks > 1 || chunking.mandatory) {
state.chunking.enabled = true;
state.chunking.parts = totalChunks;
state.chunking.remaining = [];
for (i = 0; i < totalChunks; i++) {
state.chunking.remaining.push(i);
}
handler._initTempState(id);
}
else {
state.chunking.enabled = false;
}
}
},
updateBlob: function(id, newBlob) {
if (handler.isValid(id)) {
handler._getFileState(id).file = newBlob;
}
},
_clearXhrs: function(id) {
var tempState = handler._getFileState(id).temp;
qq.each(tempState.ajaxRequesters, function(chunkId) {
delete tempState.ajaxRequesters[chunkId];
});
qq.each(tempState.xhrs, function(chunkId) {
delete tempState.xhrs[chunkId];
});
},
/**
* Creates an XHR instance for this file and stores it in the fileState.
*
* @param id File ID
* @param optChunkIdx The chunk index associated with this XHR, if applicable
* @returns {XMLHttpRequest}
*/
_createXhr: function(id, optChunkIdx) {
return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance());
},
_getAjaxRequester: function(id, optChunkIdx) {
var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
return handler._getFileState(id).temp.ajaxRequesters[chunkIdx];
},
_getChunkData: function(id, chunkIndex) {
var chunkSize = chunking.partSize,
fileSize = getSize(id),
fileOrBlob = handler.getFile(id),
startBytes = chunkSize * chunkIndex,
endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize,
totalChunks = handler._getTotalChunks(id),
cachedChunks = this._getFileState(id).temp.cachedChunks,
// To work around a Webkit GC bug, we must keep each chunk `Blob` in scope until we are done with it.
// See https://github.com/Widen/fine-uploader/issues/937#issuecomment-41418760
blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes);
cachedChunks[chunkIndex] = blob;
return {
part: chunkIndex,
start: startBytes,
end: endBytes,
count: totalChunks,
blob: blob,
size: endBytes - startBytes
};
},
_getChunkDataForCallback: function(chunkData) {
return {
partIndex: chunkData.part,
startByte: chunkData.start + 1,
endByte: chunkData.end,
totalParts: chunkData.count
};
},
/**
* @param id File ID
* @returns {string} Identifier for this item that may appear in the browser's local storage
*/
_getLocalStorageId: function(id) {
var formatVersion = "5.0",
name = getName(id),
size = getSize(id),
chunkSize = chunking.partSize,
endpoint = getEndpoint(id);
return qq.format("qq{}resume{}-{}-{}-{}-{}", namespace, formatVersion, name, size, chunkSize, endpoint);
},
_getMimeType: function(id) {
return handler.getFile(id).type;
},
_getPersistableData: function(id) {
return handler._getFileState(id).chunking;
},
/**
* @param id ID of the associated file
* @returns {number} Number of parts this file can be divided into, or undefined if chunking is not supported in this UA
*/
_getTotalChunks: function(id) {
if (chunking) {
var fileSize = getSize(id),
chunkSize = chunking.partSize;
return Math.ceil(fileSize / chunkSize);
}
},
_getXhr: function(id, optChunkIdx) {
var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
return handler._getFileState(id).temp.xhrs[chunkIdx];
},
_getXhrs: function(id) {
return handler._getFileState(id).temp.xhrs;
},
// Iterates through all XHR handler-created resume records (in local storage),
// invoking the passed callback and passing in the key and value of each local storage record.
_iterateResumeRecords: function(callback) {
if (resumeEnabled) {
qq.each(localStorage, function(key, item) {
if (key.indexOf(qq.format("qq{}resume-", namespace)) === 0) {
var uploadData = JSON.parse(item);
callback(key, uploadData);
}
});
}
},
_initTempState: function(id) {
handler._getFileState(id).temp = {
ajaxRequesters: {},
chunkProgress: {},
xhrs: {},
cachedChunks: {}
};
},
_markNotResumable: function(id) {
handler._getFileState(id).notResumable = true;
},
// Removes a chunked upload record from local storage, if possible.
// Returns true if the item was removed, false otherwise.
_maybeDeletePersistedChunkData: function(id) {
var localStorageId;
if (resumeEnabled && handler.isResumable(id)) {
localStorageId = handler._getLocalStorageId(id);
if (localStorageId && localStorage.getItem(localStorageId)) {
localStorage.removeItem(localStorageId);
return true;
}
}
return false;
},
// If this is a resumable upload, grab the relevant data from storage and items in memory that track this upload
// so we can pick up from where we left off.
_maybePrepareForResume: function(id) {
var state = handler._getFileState(id),
localStorageId, persistedData;
// Resume is enabled and possible and this is the first time we've tried to upload this file in this session,
// so prepare for a resume attempt.
if (resumeEnabled && state.key === undefined) {
localStorageId = handler._getLocalStorageId(id);
persistedData = localStorage.getItem(localStorageId);
// If we found this item in local storage, maybe we should resume it.
if (persistedData) {
persistedData = JSON.parse(persistedData);
// If we found a resume record but we have already handled this file in this session,
// don't try to resume it & ensure we don't persist future check data
if (getDataByUuid(persistedData.uuid)) {
handler._markNotResumable(id);
}
else {
log(qq.format("Identified file with ID {} and name of {} as resumable.", id, getName(id)));
onUuidChanged(id, persistedData.uuid);
state.key = persistedData.key;
state.chunking = persistedData.chunking;
state.loaded = persistedData.loaded;
state.attemptingResume = true;
handler.moveInProgressToRemaining(id);
}
}
}
},
// Persist any data needed to resume this upload in a new session.
_maybePersistChunkedState: function(id) {
var state = handler._getFileState(id),
localStorageId, persistedData;
// If local storage isn't supported by the browser, or if resume isn't enabled or possible, give up
if (resumeEnabled && handler.isResumable(id)) {
localStorageId = handler._getLocalStorageId(id);
persistedData = {
name: getName(id),
size: getSize(id),
uuid: getUuid(id),
key: state.key,
chunking: state.chunking,
loaded: state.loaded,
lastUpdated: Date.now()
};
localStorage.setItem(localStorageId, JSON.stringify(persistedData));
}
},
_registerProgressHandler: function(id, chunkIdx, chunkSize) {
var xhr = handler._getXhr(id, chunkIdx),
name = getName(id),
progressCalculator = {
simple: function(loaded, total) {
var fileSize = getSize(id);
if (loaded === total) {
onProgress(id, name, fileSize, fileSize);
}
else {
onProgress(id, name, (loaded >= fileSize ? fileSize - 1 : loaded), fileSize);
}
},
chunked: function(loaded, total) {
var chunkProgress = handler._getFileState(id).temp.chunkProgress,
totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded,
loadedForRequest = loaded,
totalForRequest = total,
totalFileSize = getSize(id),
estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize),
totalLoadedForFile = totalSuccessfullyLoadedForFile;
chunkProgress[chunkIdx] = estActualChunkLoaded;
qq.each(chunkProgress, function(chunkIdx, chunkLoaded) {
totalLoadedForFile += chunkLoaded;
});
onProgress(id, name, totalLoadedForFile, totalFileSize);
}
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
/* jshint eqnull: true */
var type = chunkSize == null ? "simple" : "chunked";
progressCalculator[type](e.loaded, e.total);
}
};
},
/**
* Registers an XHR transport instance created elsewhere.
*
* @param id ID of the associated file
* @param optChunkIdx The chunk index associated with this XHR, if applicable
* @param xhr XMLHttpRequest object instance
* @param optAjaxRequester `qq.AjaxRequester` associated with this request, if applicable.
* @returns {XMLHttpRequest}
*/
_registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) {
var xhrsId = optChunkIdx == null ? -1 : optChunkIdx,
tempState = handler._getFileState(id).temp;
tempState.xhrs = tempState.xhrs || {};
tempState.ajaxRequesters = tempState.ajaxRequesters || {};
tempState.xhrs[xhrsId] = xhr;
if (optAjaxRequester) {
tempState.ajaxRequesters[xhrsId] = optAjaxRequester;
}
return xhr;
},
// Deletes any local storage records that are "expired".
_removeExpiredChunkingRecords: function() {
var expirationDays = resume.recordsExpireIn;
handler._iterateResumeRecords(function(key, uploadData) {
var expirationDate = new Date(uploadData.lastUpdated);
// transform updated date into expiration date
expirationDate.setDate(expirationDate.getDate() + expirationDays);
if (expirationDate.getTime() <= Date.now()) {
log("Removing expired resume record with key " + key);
localStorage.removeItem(key);
}
});
},
/**
* Determine if the associated file should be chunked.
*
* @param id ID of the associated file
* @returns {*} true if chunking is enabled, possible, and the file can be split into more than 1 part
*/
_shouldChunkThisFile: function(id) {
var state = handler._getFileState(id);
if (!state.chunking) {
handler.reevaluateChunking(id);
}
return state.chunking.enabled;
}
});
};
/*globals qq */
/*jshint -W117 */
qq.WindowReceiveMessage = function(o) {
"use strict";
var options = {
log: function(message, level) {}
},
callbackWrapperDetachers = {};
qq.extend(options, o);
qq.extend(this, {
receiveMessage: function(id, callback) {
var onMessageCallbackWrapper = function(event) {
callback(event.data);
};
if (window.postMessage) {
callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper);
}
else {
log("iframe message passing not supported in this browser!", "error");
}
},
stopReceivingMessages: function(id) {
if (window.postMessage) {
var detacher = callbackWrapperDetachers[id];
if (detacher) {
detacher();
}
}
}
});
};
/*globals qq */
/**
* Defines the public API for FineUploader mode.
*/
(function() {
"use strict";
qq.uiPublicApi = {
clearStoredFiles: function() {
this._parent.prototype.clearStoredFiles.apply(this, arguments);
this._templating.clearFiles();
},
addExtraDropzone: function(element) {
this._dnd && this._dnd.setupExtraDropzone(element);
},
removeExtraDropzone: function(element) {
if (this._dnd) {
return this._dnd.removeDropzone(element);
}
},
getItemByFileId: function(id) {
return this._templating.getFileContainer(id);
},
reset: function() {
this._parent.prototype.reset.apply(this, arguments);
this._templating.reset();
if (!this._options.button && this._templating.getButton()) {
this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId();
}
if (this._dnd) {
this._dnd.dispose();
this._dnd = this._setupDragAndDrop();
}
this._totalFilesInBatch = 0;
this._filesInBatchAddedToUi = 0;
this._setupClickAndEditEventHandlers();
},
setName: function(id, newName) {
var formattedFilename = this._options.formatFileName(newName);
this._parent.prototype.setName.apply(this, arguments);
this._templating.updateFilename(id, formattedFilename);
},
pauseUpload: function(id) {
var paused = this._parent.prototype.pauseUpload.apply(this, arguments);
paused && this._templating.uploadPaused(id);
return paused;
},
continueUpload: function(id) {
var continued = this._parent.prototype.continueUpload.apply(this, arguments);
continued && this._templating.uploadContinued(id);
return continued;
},
getId: function(fileContainerOrChildEl) {
return this._templating.getFileId(fileContainerOrChildEl);
},
getDropTarget: function(fileId) {
var file = this.getFile(fileId);
return file.qqDropTarget;
}
};
/**
* Defines the private (internal) API for FineUploader mode.
*/
qq.uiPrivateApi = {
_getButton: function(buttonId) {
var button = this._parent.prototype._getButton.apply(this, arguments);
if (!button) {
if (buttonId === this._defaultButtonId) {
button = this._templating.getButton();
}
}
return button;
},
_removeFileItem: function(fileId) {
this._templating.removeFile(fileId);
},
_setupClickAndEditEventHandlers: function() {
this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent();
// A better approach would be to check specifically for focusin event support by querying the DOM API,
// but the DOMFocusIn event is not exposed as a property, so we have to resort to UA string sniffing.
this._focusinEventSupported = !qq.firefox();
if (this._isEditFilenameEnabled())
{
this._filenameClickHandler = this._bindFilenameClickEvent();
this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent();
this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent();
}
},
_setupDragAndDrop: function() {
var self = this,
dropZoneElements = this._options.dragAndDrop.extraDropzones,
templating = this._templating,
defaultDropZone = templating.getDropZone();
defaultDropZone && dropZoneElements.push(defaultDropZone);
return new qq.DragAndDrop({
dropZoneElements: dropZoneElements,
allowMultipleItems: this._options.multiple,
classes: {
dropActive: this._options.classes.dropActive
},
callbacks: {
processingDroppedFiles: function() {
templating.showDropProcessing();
},
processingDroppedFilesComplete: function(files, targetEl) {
templating.hideDropProcessing();
qq.each(files, function(idx, file) {
file.qqDropTarget = targetEl;
});
if (files.length) {
self.addFiles(files, null, null);
}
},
dropError: function(code, errorData) {
self._itemError(code, errorData);
},
dropLog: function(message, level) {
self.log(message, level);
}
}
});
},
_bindFileButtonsClickEvent: function() {
var self = this;
return new qq.FileButtonsClickHandler({
templating: this._templating,
log: function(message, lvl) {
self.log(message, lvl);
},
onDeleteFile: function(fileId) {
self.deleteFile(fileId);
},
onCancel: function(fileId) {
self.cancel(fileId);
},
onRetry: function(fileId) {
qq(self._templating.getFileContainer(fileId)).removeClass(self._classes.retryable);
self._templating.hideRetry(fileId);
self.retry(fileId);
},
onPause: function(fileId) {
self.pauseUpload(fileId);
},
onContinue: function(fileId) {
self.continueUpload(fileId);
},
onGetName: function(fileId) {
return self.getName(fileId);
}
});
},
_isEditFilenameEnabled: function() {
/*jshint -W014 */
return this._templating.isEditFilenamePossible()
&& !this._options.autoUpload
&& qq.FilenameClickHandler
&& qq.FilenameInputFocusHandler
&& qq.FilenameInputFocusHandler;
},
_filenameEditHandler: function() {
var self = this,
templating = this._templating;
return {
templating: templating,
log: function(message, lvl) {
self.log(message, lvl);
},
onGetUploadStatus: function(fileId) {
return self.getUploads({id: fileId}).status;
},
onGetName: function(fileId) {
return self.getName(fileId);
},
onSetName: function(id, newName) {
self.setName(id, newName);
},
onEditingStatusChange: function(id, isEditing) {
var qqInput = qq(templating.getEditInput(id)),
qqFileContainer = qq(templating.getFileContainer(id));
if (isEditing) {
qqInput.addClass("qq-editing");
templating.hideFilename(id);
templating.hideEditIcon(id);
}
else {
qqInput.removeClass("qq-editing");
templating.showFilename(id);
templating.showEditIcon(id);
}
// Force IE8 and older to repaint
qqFileContainer.addClass("qq-temp").removeClass("qq-temp");
}
};
},
_onUploadStatusChange: function(id, oldStatus, newStatus) {
this._parent.prototype._onUploadStatusChange.apply(this, arguments);
if (this._isEditFilenameEnabled()) {
// Status for a file exists before it has been added to the DOM, so we must be careful here.
if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) {
this._templating.markFilenameEditable(id);
this._templating.hideEditIcon(id);
}
}
},
_bindFilenameInputFocusInEvent: function() {
var spec = qq.extend({}, this._filenameEditHandler());
return new qq.FilenameInputFocusInHandler(spec);
},
_bindFilenameInputFocusEvent: function() {
var spec = qq.extend({}, this._filenameEditHandler());
return new qq.FilenameInputFocusHandler(spec);
},
_bindFilenameClickEvent: function() {
var spec = qq.extend({}, this._filenameEditHandler());
return new qq.FilenameClickHandler(spec);
},
_storeForLater: function(id) {
this._parent.prototype._storeForLater.apply(this, arguments);
this._templating.hideSpinner(id);
},
_onAllComplete: function(successful, failed) {
this._parent.prototype._onAllComplete.apply(this, arguments);
this._templating.resetTotalProgress();
},
_onSubmit: function(id, name) {
var file = this.getFile(id);
if (file && file.qqPath && this._options.dragAndDrop.reportDirectoryPaths) {
this._paramsStore.addReadOnly(id, {
qqpath: file.qqPath
});
}
this._parent.prototype._onSubmit.apply(this, arguments);
this._addToList(id, name);
},
// The file item has been added to the DOM.
_onSubmitted: function(id) {
// If the edit filename feature is enabled, mark the filename element as "editable" and the associated edit icon
if (this._isEditFilenameEnabled()) {
this._templating.markFilenameEditable(id);
this._templating.showEditIcon(id);
// If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input
if (!this._focusinEventSupported) {
this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id));
}
}
},
// Update the progress bar & percentage as the file is uploaded
_onProgress: function(id, name, loaded, total) {
this._parent.prototype._onProgress.apply(this, arguments);
this._templating.updateProgress(id, loaded, total);
if (Math.round(loaded / total * 100) === 100) {
this._templating.hideCancel(id);
this._templating.hidePause(id);
this._templating.hideProgress(id);
this._templating.setStatusText(id, this._options.text.waitingForResponse);
// If ~last byte was sent, display total file size
this._displayFileSize(id);
}
else {
// If still uploading, display percentage - total size is actually the total request(s) size
this._displayFileSize(id, loaded, total);
}
},
_onTotalProgress: function(loaded, total) {
this._parent.prototype._onTotalProgress.apply(this, arguments);
this._templating.updateTotalProgress(loaded, total);
},
_onComplete: function(id, name, result, xhr) {
var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments),
templating = this._templating,
fileContainer = templating.getFileContainer(id),
self = this;
function completeUpload(result) {
// If this file is not represented in the templating module, perhaps it was hidden intentionally.
// If so, don't perform any UI-related tasks related to this file.
if (!fileContainer) {
return;
}
templating.setStatusText(id);
qq(fileContainer).removeClass(self._classes.retrying);
templating.hideProgress(id);
if (!self._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) {
templating.hideCancel(id);
}
templating.hideSpinner(id);
if (result.success) {
self._markFileAsSuccessful(id);
}
else {
qq(fileContainer).addClass(self._classes.fail);
if (templating.isRetryPossible() && !self._preventRetries[id]) {
qq(fileContainer).addClass(self._classes.retryable);
templating.showRetry(id);
}
self._controlFailureTextDisplay(id, result);
}
}
// The parent may need to perform some async operation before we can accurately determine the status of the upload.
if (parentRetVal instanceof qq.Promise) {
parentRetVal.done(function(newResult) {
completeUpload(newResult);
});
}
else {
completeUpload(result);
}
return parentRetVal;
},
_markFileAsSuccessful: function(id) {
var templating = this._templating;
if (this._isDeletePossible()) {
templating.showDeleteButton(id);
}
qq(templating.getFileContainer(id)).addClass(this._classes.success);
this._maybeUpdateThumbnail(id);
},
_onUploadPrep: function(id) {
this._parent.prototype._onUploadPrep.apply(this, arguments);
this._templating.showSpinner(id);
},
_onUpload: function(id, name) {
var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments);
this._templating.showSpinner(id);
return parentRetVal;
},
_onUploadChunk: function(id, chunkData) {
this._parent.prototype._onUploadChunk.apply(this, arguments);
// Only display the pause button if we have finished uploading at least one chunk
// & this file can be resumed
if (chunkData.partIndex > 0 && this._handler.isResumable(id)) {
this._templating.allowPause(id);
}
},
_onCancel: function(id, name) {
this._parent.prototype._onCancel.apply(this, arguments);
this._removeFileItem(id);
if (this._getNotFinished() === 0) {
this._templating.resetTotalProgress();
}
},
_onBeforeAutoRetry: function(id) {
var retryNumForDisplay, maxAuto, retryAlbum;
this._parent.prototype._onBeforeAutoRetry.apply(this, arguments);
this._showCancelLink(id);
if (this._options.retry.showAutoRetryAlbum) {
retryNumForDisplay = this._autoRetries[id];
maxAuto = this._options.retry.maxAutoAttempts;
retryAlbum = this._options.retry.autoRetryAlbum.replace(/\{retryNum\}/g, retryNumForDisplay);
retryAlbum = retryAlbum.replace(/\{maxAuto\}/g, maxAuto);
this._templating.setStatusText(id, retryAlbum);
qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying);
}
},
//return false if we should not attempt the requested retry
_onBeforeManualRetry: function(id) {
if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) {
this._templating.resetProgress(id);
qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail);
this._templating.setStatusText(id);
this._templating.showSpinner(id);
this._showCancelLink(id);
return true;
}
else {
qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable);
this._templating.showRetry(id);
return false;
}
},
_onSubmitDelete: function(id) {
var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this);
this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback);
},
_onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) {
if (this._options.deleteFile.forceConfirm) {
this._showDeleteConfirm.apply(this, arguments);
}
else {
this._sendDeleteRequest.apply(this, arguments);
}
},
_onDeleteComplete: function(id, xhr, isError) {
this._parent.prototype._onDeleteComplete.apply(this, arguments);
this._templating.hideSpinner(id);
if (isError) {
this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText);
this._templating.showDeleteButton(id);
}
else {
this._removeFileItem(id);
}
},
_sendDeleteRequest: function(id, uuid, additionalMandatedParams) {
this._templating.hideDeleteButton(id);
this._templating.showSpinner(id);
this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText);
this._deleteHandler.sendDelete.apply(this, arguments);
},
_showDeleteConfirm: function(id, uuid, mandatedParams) {
/*jshint -W004 */
var fileName = this.getName(id),
confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName),
uuid = this.getUuid(id),
deleteRequestArgs = arguments,
self = this,
retVal;
retVal = this._options.showConfirm(confirmMessage);
if (qq.isGenericPromise(retVal)) {
retVal.then(function() {
self._sendDeleteRequest.apply(self, deleteRequestArgs);
});
}
else if (retVal !== false) {
self._sendDeleteRequest.apply(self, deleteRequestArgs);
}
},
_addToList: function(id, name, canned) {
var prependData,
prependIndex = 0,
dontDisplay = this._handler.isProxied(id) && this._options.scaling.hideScaled,
record;
// If we don't want this file to appear in the UI, skip all of this UI-related logic.
if (dontDisplay) {
return;
}
if (this._options.display.prependFiles) {
if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) {
prependIndex = this._filesInBatchAddedToUi - 1;
}
prependData = {
index: prependIndex
};
}
if (!canned) {
if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) {
this._templating.disableCancel();
}
// Cancel all existing (previous) files and clear the list if this file is not part of
// a scaled file group that has already been accepted, or if this file is not part of
// a scaled file group at all.
if (!this._options.multiple) {
record = this.getUploads({id: id});
this._handledProxyGroup = this._handledProxyGroup || record.proxyGroupId;
if (record.proxyGroupId !== this._handledProxyGroup || !record.proxyGroupId) {
this._handler.cancelAll();
this._clearList();
this._handledProxyGroup = null;
}
}
}
this._templating.addFile(id, this._options.formatFileName(name), prependData);
if (canned) {
this._thumbnailUrls[id] && this._templating.updateThumbnail(id, this._thumbnailUrls[id], true);
}
else {
this._templating.generatePreview(id, this.getFile(id));
}
this._filesInBatchAddedToUi += 1;
if (canned ||
(this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading)) {
this._displayFileSize(id);
}
},
_clearList: function() {
this._templating.clearFiles();
this.clearStoredFiles();
},
_displayFileSize: function(id, loadedSize, totalSize) {
var size = this.getSize(id),
sizeForDisplay = this._formatSize(size);
if (size >= 0) {
if (loadedSize !== undefined && totalSize !== undefined) {
sizeForDisplay = this._formatProgress(loadedSize, totalSize);
}
this._templating.updateSize(id, sizeForDisplay);
}
},
_formatProgress: function(uploadedSize, totalSize) {
var message = this._options.text.formatProgress;
function r(name, replacement) { message = message.replace(name, replacement); }
r("{percent}", Math.round(uploadedSize / totalSize * 100));
r("{total_size}", this._formatSize(totalSize));
return message;
},
_controlFailureTextDisplay: function(id, response) {
var mode, maxChars, responseProperty, failureReason, shortFailureReason;
mode = this._options.failedUploadTextDisplay.mode;
maxChars = this._options.failedUploadTextDisplay.maxChars;
responseProperty = this._options.failedUploadTextDisplay.responseProperty;
if (mode === "custom") {
failureReason = response[responseProperty];
if (failureReason) {
if (failureReason.length > maxChars) {
shortFailureReason = failureReason.substring(0, maxChars) + "...";
}
}
else {
failureReason = this._options.text.failUpload;
}
this._templating.setStatusText(id, shortFailureReason || failureReason);
if (this._options.failedUploadTextDisplay.enableTooltip) {
this._showTooltip(id, failureReason);
}
}
else if (mode === "default") {
this._templating.setStatusText(id, this._options.text.failUpload);
}
else if (mode !== "none") {
this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", "warn");
}
},
_showTooltip: function(id, text) {
this._templating.getFileContainer(id).title = text;
},
_showCancelLink: function(id) {
if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) {
this._templating.showCancel(id);
}
},
_itemError: function(code, name, item) {
var message = this._parent.prototype._itemError.apply(this, arguments);
this._options.showMessage(message);
},
_batchError: function(message) {
this._parent.prototype._batchError.apply(this, arguments);
this._options.showMessage(message);
},
_setupPastePrompt: function() {
var self = this;
this._options.callbacks.onPasteReceived = function() {
var message = self._options.paste.namePromptMessage,
defaultVal = self._options.paste.defaultName;
return self._options.showPrompt(message, defaultVal);
};
},
_fileOrBlobRejected: function(id, name) {
this._totalFilesInBatch -= 1;
this._parent.prototype._fileOrBlobRejected.apply(this, arguments);
},
_prepareItemsForUpload: function(items, params, endpoint) {
this._totalFilesInBatch = items.length;
this._filesInBatchAddedToUi = 0;
this._parent.prototype._prepareItemsForUpload.apply(this, arguments);
},
_maybeUpdateThumbnail: function(fileId) {
var thumbnailUrl = this._thumbnailUrls[fileId];
this._templating.updateThumbnail(fileId, thumbnailUrl);
},
_addCannedFile: function(sessionData) {
var id = this._parent.prototype._addCannedFile.apply(this, arguments);
this._addToList(id, this.getName(id), true);
this._templating.hideSpinner(id);
this._templating.hideCancel(id);
this._markFileAsSuccessful(id);
return id;
},
_setSize: function(id, newSize) {
this._parent.prototype._setSize.apply(this, arguments);
this._templating.updateSize(id, this._formatSize(newSize));
}
};
}());
/*globals qq */
/**
* This defines FineUploader mode, which is a default UI w/ drag & drop uploading.
*/
qq.FineUploader = function(o, namespace) {
"use strict";
// By default this should inherit instance data from FineUploaderBasic, but this can be overridden
// if the (internal) caller defines a different parent. The parent is also used by
// the private and public API functions that need to delegate to a parent function.
this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic;
this._parent.apply(this, arguments);
// Options provided by FineUploader mode
qq.extend(this._options, {
element: null,
button: null,
listElement: null,
dragAndDrop: {
extraDropzones: [],
reportDirectoryPaths: false
},
text: {
formatProgress: "{percent}% of {total_size}",
failUpload: "Upload failed",
waitingForResponse: "Processing...",
paused: "Paused"
},
template: "qq-template",
classes: {
retrying: "qq-upload-retrying",
retryable: "qq-upload-retryable",
success: "qq-upload-success",
fail: "qq-upload-fail",
editable: "qq-editable",
hide: "qq-hide",
dropActive: "qq-upload-drop-area-active"
},
failedUploadTextDisplay: {
mode: "default", //default, custom, or none
maxChars: 50,
responseProperty: "error",
enableTooltip: true
},
messages: {
tooManyFilesError: "You may only drop one file",
unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind."
},
retry: {
showAutoRetryAlbum: true,
autoRetryAlbum: "Retrying {retryNum}/{maxAuto}..."
},
deleteFile: {
forceConfirm: false,
confirmMessage: "Are you sure you want to delete {filename}?",
deletingStatusText: "Deleting...",
deletingFailedText: "Delete failed"
},
display: {
fileSizeOnSubmit: false,
prependFiles: false
},
paste: {
promptForName: false,
namePromptMessage: "Please name this image"
},
thumbnails: {
maxCount: 0,
placeholders: {
waitUntilResponse: false,
notAvailablePath: null,
waitingPath: null
},
timeBetweenThumbs: 750
},
scaling: {
hideScaled: false
},
showMessage: function(message) {
setTimeout(function() {
window.alert(message);
}, 0);
},
showConfirm: function(message) {
return window.confirm(message);
},
showPrompt: function(message, defaultValue) {
return window.prompt(message, defaultValue);
}
}, true);
// Replace any default options with user defined ones
qq.extend(this._options, o, true);
this._templating = new qq.Templating({
log: qq.bind(this.log, this),
templateIdOrEl: this._options.template,
containerEl: this._options.element,
fileContainerEl: this._options.listElement,
button: this._options.button,
imageGenerator: this._imageGenerator,
classes: {
hide: this._options.classes.hide,
editable: this._options.classes.editable
},
limits: {
maxThumbs: this._options.thumbnails.maxCount,
timeBetweenThumbs: this._options.thumbnails.timeBetweenThumbs
},
placeholders: {
waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse,
thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath,
waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath
},
text: this._options.text
});
if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
this._templating.renderFailure(this._options.messages.unsupportedBrowserIos8Safari);
}
else if (!qq.supportedFeatures.uploading || (this._options.cors.expected && !qq.supportedFeatures.uploadCors)) {
this._templating.renderFailure(this._options.messages.unsupportedBrowser);
}
else {
this._wrapCallbacks();
this._templating.render();
this._classes = this._options.classes;
if (!this._options.button && this._templating.getButton()) {
this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId();
}
this._setupClickAndEditEventHandlers();
if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) {
this._dnd = this._setupDragAndDrop();
}
if (this._options.paste.targetElement && this._options.paste.promptForName) {
if (qq.PasteSupport) {
this._setupPastePrompt();
}
else {
this.log("Paste support module not found.", "error");
}
}
this._totalFilesInBatch = 0;
this._filesInBatchAddedToUi = 0;
}
};
// Inherit the base public & private API methods
qq.extend(qq.FineUploader.prototype, qq.basePublicApi);
qq.extend(qq.FineUploader.prototype, qq.basePrivateApi);
// Add the FineUploader/default UI public & private UI methods, which may override some base methods.
qq.extend(qq.FineUploader.prototype, qq.uiPublicApi);
qq.extend(qq.FineUploader.prototype, qq.uiPrivateApi);
/* globals qq */
/* jshint -W065 */
/**
* Module responsible for rendering all Fine Uploader UI templates. This module also asserts at least
* a limited amount of control over the template elements after they are added to the DOM.
* Wherever possible, this module asserts total control over template elements present in the DOM.
*
* @param spec Specification object used to control various templating behaviors
* @constructor
*/
qq.Templating = function(spec) {
"use strict";
var FILE_ID_ATTR = "qq-file-id",
FILE_CLASS_PREFIX = "qq-file-id-",
THUMBNAIL_MAX_SIZE_ATTR = "qq-max-size",
THUMBNAIL_SERVER_SCALE_ATTR = "qq-server-scale",
// This variable is duplicated in the DnD module since it can function as a standalone as well
HIDE_DROPZONE_ATTR = "qq-hide-dropzone",
isCancelDisabled = false,
generatedThumbnails = 0,
thumbnailQueueMonitorRunning = false,
thumbGenerationQueue = [],
thumbnailMaxSize = -1,
options = {
log: null,
limits: {
maxThumbs: 0,
timeBetweenThumbs: 750
},
templateIdOrEl: "qq-template",
containerEl: null,
fileContainerEl: null,
button: null,
imageGenerator: null,
classes: {
hide: "qq-hide",
editable: "qq-editable"
},
placeholders: {
waitUntilUpdate: false,
thumbnailNotAvailable: null,
waitingForThumbnail: null
},
text: {
paused: "Paused"
}
},
selectorClasses = {
button: "qq-upload-button-selector",
drop: "qq-upload-drop-area-selector",
list: "qq-upload-list-selector",
progressBarContainer: "qq-progress-bar-container-selector",
progressBar: "qq-progress-bar-selector",
totalProgressBarContainer: "qq-total-progress-bar-container-selector",
totalProgressBar: "qq-total-progress-bar-selector",
file: "qq-upload-file-selector",
spinner: "qq-upload-spinner-selector",
size: "qq-upload-size-selector",
cancel: "qq-upload-cancel-selector",
pause: "qq-upload-pause-selector",
continueButton: "qq-upload-continue-selector",
deleteButton: "qq-upload-delete-selector",
retry: "qq-upload-retry-selector",
statusText: "qq-upload-status-text-selector",
editFilenameInput: "qq-edit-filename-selector",
editNameIcon: "qq-edit-filename-icon-selector",
dropProcessing: "qq-drop-processing-selector",
dropProcessingSpinner: "qq-drop-processing-spinner-selector",
thumbnail: "qq-thumbnail-selector"
},
previewGeneration = {},
cachedThumbnailNotAvailableImg = new qq.Promise(),
cachedWaitingForThumbnailImg = new qq.Promise(),
log,
isEditElementsExist,
isRetryElementExist,
templateHtml,
container,
fileList,
showThumbnails,
serverScale,
// During initialization of the templating module we should cache any
// placeholder images so we can quickly swap them into the file list on demand.
// Any placeholder images that cannot be loaded/found are simply ignored.
cacheThumbnailPlaceholders = function() {
var notAvailableUrl = options.placeholders.thumbnailNotAvailable,
waitingUrl = options.placeholders.waitingForThumbnail,
spec = {
maxSize: thumbnailMaxSize,
scale: serverScale
};
if (showThumbnails) {
if (notAvailableUrl) {
options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then(
function(updatedImg) {
cachedThumbnailNotAvailableImg.success(updatedImg);
},
function() {
cachedThumbnailNotAvailableImg.failure();
log("Problem loading 'not available' placeholder image at " + notAvailableUrl, "error");
}
);
}
else {
cachedThumbnailNotAvailableImg.failure();
}
if (waitingUrl) {
options.imageGenerator.generate(waitingUrl, new Image(), spec).then(
function(updatedImg) {
cachedWaitingForThumbnailImg.success(updatedImg);
},
function() {
cachedWaitingForThumbnailImg.failure();
log("Problem loading 'waiting for thumbnail' placeholder image at " + waitingUrl, "error");
}
);
}
else {
cachedWaitingForThumbnailImg.failure();
}
}
},
// Displays a "waiting for thumbnail" type placeholder image
// iff we were able to load it during initialization of the templating module.
displayWaitingImg = function(thumbnail) {
var waitingImgPlacement = new qq.Promise();
cachedWaitingForThumbnailImg.then(function(img) {
maybeScalePlaceholderViaCss(img, thumbnail);
/* jshint eqnull:true */
if (!thumbnail.src) {
thumbnail.src = img.src;
thumbnail.onload = function() {
thumbnail.onload = null;
show(thumbnail);
waitingImgPlacement.success();
};
}
else {
waitingImgPlacement.success();
}
}, function() {
// In some browsers (such as IE9 and older) an img w/out a src attribute
// are displayed as "broken" images, so we should just hide the img tag
// if we aren't going to display the "waiting" placeholder.
hide(thumbnail);
waitingImgPlacement.success();
});
return waitingImgPlacement;
},
generateNewPreview = function(id, blob, spec) {
var thumbnail = getThumbnail(id);
log("Generating new thumbnail for " + id);
blob.qqThumbnailId = id;
return options.imageGenerator.generate(blob, thumbnail, spec).then(
function() {
generatedThumbnails++;
show(thumbnail);
previewGeneration[id].success();
},
function() {
previewGeneration[id].failure();
// Display the "not available" placeholder img only if we are
// not expecting a thumbnail at a later point, such as in a server response.
if (!options.placeholders.waitUntilUpdate) {
maybeSetDisplayNotAvailableImg(id, thumbnail);
}
});
},
generateNextQueuedPreview = function() {
if (thumbGenerationQueue.length) {
thumbnailQueueMonitorRunning = true;
var queuedThumbRequest = thumbGenerationQueue.shift();
if (queuedThumbRequest.update) {
processUpdateQueuedPreviewRequest(queuedThumbRequest);
}
else {
processNewQueuedPreviewRequest(queuedThumbRequest);
}
}
else {
thumbnailQueueMonitorRunning = false;
}
},
getCancel = function(id) {
return getTemplateEl(getFile(id), selectorClasses.cancel);
},
getContinue = function(id) {
return getTemplateEl(getFile(id), selectorClasses.continueButton);
},
getDelete = function(id) {
return getTemplateEl(getFile(id), selectorClasses.deleteButton);
},
getDropProcessing = function() {
return getTemplateEl(container, selectorClasses.dropProcessing);
},
getEditIcon = function(id) {
return getTemplateEl(getFile(id), selectorClasses.editNameIcon);
},
getFile = function(id) {
return qq(fileList).getByClass(FILE_CLASS_PREFIX + id)[0];
},
getFilename = function(id) {
return getTemplateEl(getFile(id), selectorClasses.file);
},
getPause = function(id) {
return getTemplateEl(getFile(id), selectorClasses.pause);
},
getProgress = function(id) {
/* jshint eqnull:true */
// Total progress bar
if (id == null) {
return getTemplateEl(container, selectorClasses.totalProgressBarContainer) ||
getTemplateEl(container, selectorClasses.totalProgressBar);
}
// Per-file progress bar
return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) ||
getTemplateEl(getFile(id), selectorClasses.progressBar);
},
getRetry = function(id) {
return getTemplateEl(getFile(id), selectorClasses.retry);
},
getSize = function(id) {
return getTemplateEl(getFile(id), selectorClasses.size);
},
getSpinner = function(id) {
return getTemplateEl(getFile(id), selectorClasses.spinner);
},
getTemplateEl = function(context, cssClass) {
return context && qq(context).getByClass(cssClass)[0];
},
getThumbnail = function(id) {
return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail);
},
hide = function(el) {
el && qq(el).addClass(options.classes.hide);
},
// Ensures a placeholder image does not exceed any max size specified
// via `style` attribute properties iff <canvas> was not used to scale
// the placeholder AND the target <img> doesn't already have these `style` attribute properties set.
maybeScalePlaceholderViaCss = function(placeholder, thumbnail) {
var maxWidth = placeholder.style.maxWidth,
maxHeight = placeholder.style.maxHeight;
if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) {
qq(thumbnail).css({
maxWidth: maxWidth,
maxHeight: maxHeight
});
}
},
// Displays a "thumbnail not available" type placeholder image
// iff we were able to load this placeholder during initialization
// of the templating module or after preview generation has failed.
maybeSetDisplayNotAvailableImg = function(id, thumbnail) {
var previewing = previewGeneration[id] || new qq.Promise().failure(),
notAvailableImgPlacement = new qq.Promise();
cachedThumbnailNotAvailableImg.then(function(img) {
previewing.then(
function() {
notAvailableImgPlacement.success();
},
function() {
maybeScalePlaceholderViaCss(img, thumbnail);
thumbnail.onload = function() {
thumbnail.onload = null;
notAvailableImgPlacement.success();
};
thumbnail.src = img.src;
show(thumbnail);
}
);
});
return notAvailableImgPlacement;
},
/**
* Grabs the HTML from the script tag holding the template markup. This function will also adjust
* some internally-tracked state variables based on the contents of the template.
* The template is filtered so that irrelevant elements (such as the drop zone if DnD is not supported)
* are omitted from the DOM. Useful errors will be thrown if the template cannot be parsed.
*
* @returns {{template: *, fileTemplate: *}} HTML for the top-level file items templates
*/
parseAndGetTemplate = function() {
var scriptEl,
scriptHtml,
fileListNode,
tempTemplateEl,
fileListHtml,
defaultButton,
dropArea,
thumbnail,
dropProcessing;
log("Parsing template");
/*jshint -W116*/
if (options.templateIdOrEl == null) {
throw new Error("You MUST specify either a template element or ID!");
}
// Grab the contents of the script tag holding the template.
if (qq.isString(options.templateIdOrEl)) {
scriptEl = document.getElementById(options.templateIdOrEl);
if (scriptEl === null) {
throw new Error(qq.format("Cannot find template script at ID '{}'!", options.templateIdOrEl));
}
scriptHtml = scriptEl.innerHTML;
}
else {
if (options.templateIdOrEl.innerHTML === undefined) {
throw new Error("You have specified an invalid value for the template option! " +
"It must be an ID or an Element.");
}
scriptHtml = options.templateIdOrEl.innerHTML;
}
scriptHtml = qq.trimStr(scriptHtml);
tempTemplateEl = document.createElement("div");
tempTemplateEl.appendChild(qq.toElement(scriptHtml));
// Don't include the default template button in the DOM
// if an alternate button container has been specified.
if (options.button) {
defaultButton = qq(tempTemplateEl).getByClass(selectorClasses.button)[0];
if (defaultButton) {
qq(defaultButton).remove();
}
}
// Omit the drop processing element from the DOM if DnD is not supported by the UA,
// or the drag and drop module is not found.
// NOTE: We are consciously not removing the drop zone if the UA doesn't support DnD
// to support layouts where the drop zone is also a container for visible elements,
// such as the file list.
if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) {
dropProcessing = qq(tempTemplateEl).getByClass(selectorClasses.dropProcessing)[0];
if (dropProcessing) {
qq(dropProcessing).remove();
}
}
dropArea = qq(tempTemplateEl).getByClass(selectorClasses.drop)[0];
// If DnD is not available then remove
// it from the DOM as well.
if (dropArea && !qq.DragAndDrop) {
log("DnD module unavailable.", "info");
qq(dropArea).remove();
}
// If there is a drop area defined in the template, and the current UA doesn't support DnD,
// and the drop area is marked as "hide before enter", ensure it is hidden as the DnD module
// will not do this (since we will not be loading the DnD module)
if (dropArea && !qq.supportedFeatures.fileDrop &&
qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) {
qq(dropArea).css({
display: "none"
});
}
// Ensure the `showThumbnails` flag is only set if the thumbnail element
// is present in the template AND the current UA is capable of generating client-side previews.
thumbnail = qq(tempTemplateEl).getByClass(selectorClasses.thumbnail)[0];
if (!showThumbnails) {
thumbnail && qq(thumbnail).remove();
}
else if (thumbnail) {
thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR));
// Only enforce max size if the attr value is non-zero
thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null;
serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR);
}
showThumbnails = showThumbnails && thumbnail;
isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0;
isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0;
fileListNode = qq(tempTemplateEl).getByClass(selectorClasses.list)[0];
/*jshint -W116*/
if (fileListNode == null) {
throw new Error("Could not find the file list container in the template!");
}
fileListHtml = fileListNode.innerHTML;
fileListNode.innerHTML = "";
log("Template parsing complete");
return {
template: qq.trimStr(tempTemplateEl.innerHTML),
fileTemplate: qq.trimStr(fileListHtml)
};
},
prependFile = function(el, index) {
var parentEl = fileList,
beforeEl = parentEl.firstChild;
if (index > 0) {
beforeEl = qq(parentEl).children()[index].nextSibling;
}
parentEl.insertBefore(el, beforeEl);
},
processNewQueuedPreviewRequest = function(queuedThumbRequest) {
var id = queuedThumbRequest.id,
optFileOrBlob = queuedThumbRequest.optFileOrBlob,
relatedThumbnailId = optFileOrBlob && optFileOrBlob.qqThumbnailId,
thumbnail = getThumbnail(id),
spec = {
maxSize: thumbnailMaxSize,
scale: true,
orient: true
};
if (qq.supportedFeatures.imagePreviews) {
if (thumbnail) {
if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {
maybeSetDisplayNotAvailableImg(id, thumbnail);
generateNextQueuedPreview();
}
else {
displayWaitingImg(thumbnail).done(function() {
previewGeneration[id] = new qq.Promise();
previewGeneration[id].done(function() {
setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
});
/* jshint eqnull: true */
// If we've already generated an <img> for this file, use the one that exists,
// don't waste resources generating a new one.
if (relatedThumbnailId != null) {
useCachedPreview(id, relatedThumbnailId);
}
else {
generateNewPreview(id, optFileOrBlob, spec);
}
});
}
}
}
else if (thumbnail) {
displayWaitingImg(thumbnail);
generateNextQueuedPreview();
}
},
processUpdateQueuedPreviewRequest = function(queuedThumbRequest) {
var id = queuedThumbRequest.id,
thumbnailUrl = queuedThumbRequest.thumbnailUrl,
showWaitingImg = queuedThumbRequest.showWaitingImg,
thumbnail = getThumbnail(id),
spec = {
maxSize: thumbnailMaxSize,
scale: serverScale
};
if (thumbnail) {
if (thumbnailUrl) {
if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {
maybeSetDisplayNotAvailableImg(id, thumbnail);
generateNextQueuedPreview();
}
else {
if (showWaitingImg) {
displayWaitingImg(thumbnail);
}
return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then(
function() {
show(thumbnail);
generatedThumbnails++;
setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
},
function() {
maybeSetDisplayNotAvailableImg(id, thumbnail);
setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
}
);
}
}
else {
maybeSetDisplayNotAvailableImg(id, thumbnail);
generateNextQueuedPreview();
}
}
},
setProgressBarWidth = function(id, percent) {
var bar = getProgress(id),
/* jshint eqnull:true */
progressBarSelector = id == null ? selectorClasses.totalProgressBar : selectorClasses.progressBar;
if (bar && !qq(bar).hasClass(progressBarSelector)) {
bar = qq(bar).getByClass(progressBarSelector)[0];
}
bar && qq(bar).css({width: percent + "%"});
},
show = function(el) {
el && qq(el).removeClass(options.classes.hide);
},
useCachedPreview = function(targetThumbnailId, cachedThumbnailId) {
var targetThumnail = getThumbnail(targetThumbnailId),
cachedThumbnail = getThumbnail(cachedThumbnailId);
log(qq.format("ID {} is the same file as ID {}. Will use generated thumbnail from ID {} instead.", targetThumbnailId, cachedThumbnailId, cachedThumbnailId));
// Generation of the related thumbnail may still be in progress, so, wait until it is done.
previewGeneration[cachedThumbnailId].then(function() {
generatedThumbnails++;
previewGeneration[targetThumbnailId].success();
log(qq.format("Now using previously generated thumbnail created for ID {} on ID {}.", cachedThumbnailId, targetThumbnailId));
targetThumnail.src = cachedThumbnail.src;
show(targetThumnail);
},
function() {
previewGeneration[targetThumbnailId].failure();
if (!options.placeholders.waitUntilUpdate) {
maybeSetDisplayNotAvailableImg(targetThumbnailId, targetThumnail);
}
});
};
qq.extend(options, spec);
log = options.log;
// No need to worry about conserving CPU or memory on older browsers,
// since there is no ability to preview, and thumbnail display is primitive and quick.
if (!qq.supportedFeatures.imagePreviews) {
options.limits.timeBetweenThumbs = 0;
options.limits.maxThumbs = 0;
}
container = options.containerEl;
showThumbnails = options.imageGenerator !== undefined;
templateHtml = parseAndGetTemplate();
cacheThumbnailPlaceholders();
qq.extend(this, {
render: function() {
log("Rendering template in DOM.");
generatedThumbnails = 0;
container.innerHTML = templateHtml.template;
hide(getDropProcessing());
this.hideTotalProgress();
fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list);
log("Template rendering complete");
},
renderFailure: function(message) {
var cantRenderEl = qq.toElement(message);
container.innerHTML = "";
container.appendChild(cantRenderEl);
},
reset: function() {
this.render();
},
clearFiles: function() {
fileList.innerHTML = "";
},
disableCancel: function() {
isCancelDisabled = true;
},
addFile: function(id, name, prependInfo) {
var fileEl = qq.toElement(templateHtml.fileTemplate),
fileNameEl = getTemplateEl(fileEl, selectorClasses.file),
thumb;
qq(fileEl).addClass(FILE_CLASS_PREFIX + id);
fileNameEl && qq(fileNameEl).setText(name);
fileEl.setAttribute(FILE_ID_ATTR, id);
if (prependInfo) {
prependFile(fileEl, prependInfo.index);
}
else {
fileList.appendChild(fileEl);
}
hide(getProgress(id));
hide(getSize(id));
hide(getDelete(id));
hide(getRetry(id));
hide(getPause(id));
hide(getContinue(id));
if (isCancelDisabled) {
this.hideCancel(id);
}
thumb = getThumbnail(id);
if (thumb && !thumb.src) {
cachedWaitingForThumbnailImg.then(function(waitingImg) {
thumb.src = waitingImg.src;
if (waitingImg.style.maxHeight && waitingImg.style.maxWidth) {
qq(thumb).css({
maxHeight: waitingImg.style.maxHeight,
maxWidth: waitingImg.style.maxWidth
});
}
show(thumb);
});
}
},
removeFile: function(id) {
qq(getFile(id)).remove();
},
getFileId: function(el) {
var currentNode = el;
if (currentNode) {
/*jshint -W116*/
while (currentNode.getAttribute(FILE_ID_ATTR) == null) {
currentNode = currentNode.parentNode;
}
return parseInt(currentNode.getAttribute(FILE_ID_ATTR));
}
},
getFileList: function() {
return fileList;
},
markFilenameEditable: function(id) {
var filename = getFilename(id);
filename && qq(filename).addClass(options.classes.editable);
},
updateFilename: function(id, name) {
var filename = getFilename(id);
filename && qq(filename).setText(name);
},
hideFilename: function(id) {
hide(getFilename(id));
},
showFilename: function(id) {
show(getFilename(id));
},
isFileName: function(el) {
return qq(el).hasClass(selectorClasses.file);
},
getButton: function() {
return options.button || getTemplateEl(container, selectorClasses.button);
},
hideDropProcessing: function() {
hide(getDropProcessing());
},
showDropProcessing: function() {
show(getDropProcessing());
},
getDropZone: function() {
return getTemplateEl(container, selectorClasses.drop);
},
isEditFilenamePossible: function() {
return isEditElementsExist;
},
hideRetry: function(id) {
hide(getRetry(id));
},
isRetryPossible: function() {
return isRetryElementExist;
},
showRetry: function(id) {
show(getRetry(id));
},
getFileContainer: function(id) {
return getFile(id);
},
showEditIcon: function(id) {
var icon = getEditIcon(id);
icon && qq(icon).addClass(options.classes.editable);
},
hideEditIcon: function(id) {
var icon = getEditIcon(id);
icon && qq(icon).removeClass(options.classes.editable);
},
isEditIcon: function(el) {
return qq(el).hasClass(selectorClasses.editNameIcon);
},
getEditInput: function(id) {
return getTemplateEl(getFile(id), selectorClasses.editFilenameInput);
},
isEditInput: function(el) {
return qq(el).hasClass(selectorClasses.editFilenameInput);
},
updateProgress: function(id, loaded, total) {
var bar = getProgress(id),
percent;
if (bar && total > 0) {
percent = Math.round(loaded / total * 100);
if (percent === 100) {
hide(bar);
}
else {
show(bar);
}
setProgressBarWidth(id, percent);
}
},
updateTotalProgress: function(loaded, total) {
this.updateProgress(null, loaded, total);
},
hideProgress: function(id) {
var bar = getProgress(id);
bar && hide(bar);
},
hideTotalProgress: function() {
this.hideProgress();
},
resetProgress: function(id) {
setProgressBarWidth(id, 0);
this.hideTotalProgress(id);
},
resetTotalProgress: function() {
this.resetProgress();
},
showCancel: function(id) {
if (!isCancelDisabled) {
var cancel = getCancel(id);
cancel && qq(cancel).removeClass(options.classes.hide);
}
},
hideCancel: function(id) {
hide(getCancel(id));
},
isCancel: function(el) {
return qq(el).hasClass(selectorClasses.cancel);
},
allowPause: function(id) {
show(getPause(id));
hide(getContinue(id));
},
uploadPaused: function(id) {
this.setStatusText(id, options.text.paused);
this.allowContinueButton(id);
hide(getSpinner(id));
},
hidePause: function(id) {
hide(getPause(id));
},
isPause: function(el) {
return qq(el).hasClass(selectorClasses.pause);
},
isContinueButton: function(el) {
return qq(el).hasClass(selectorClasses.continueButton);
},
allowContinueButton: function(id) {
show(getContinue(id));
hide(getPause(id));
},
uploadContinued: function(id) {
this.setStatusText(id, "");
this.allowPause(id);
show(getSpinner(id));
},
showDeleteButton: function(id) {
show(getDelete(id));
},
hideDeleteButton: function(id) {
hide(getDelete(id));
},
isDeleteButton: function(el) {
return qq(el).hasClass(selectorClasses.deleteButton);
},
isRetry: function(el) {
return qq(el).hasClass(selectorClasses.retry);
},
updateSize: function(id, text) {
var size = getSize(id);
if (size) {
show(size);
qq(size).setText(text);
}
},
setStatusText: function(id, text) {
var textEl = getTemplateEl(getFile(id), selectorClasses.statusText);
if (textEl) {
/*jshint -W116*/
if (text == null) {
qq(textEl).clearText();
}
else {
qq(textEl).setText(text);
}
}
},
hideSpinner: function(id) {
hide(getSpinner(id));
},
showSpinner: function(id) {
show(getSpinner(id));
},
generatePreview: function(id, optFileOrBlob) {
thumbGenerationQueue.push({id: id, optFileOrBlob: optFileOrBlob});
!thumbnailQueueMonitorRunning && generateNextQueuedPreview();
},
updateThumbnail: function(id, thumbnailUrl, showWaitingImg) {
thumbGenerationQueue.push({update: true, id: id, thumbnailUrl: thumbnailUrl, showWaitingImg: showWaitingImg});
!thumbnailQueueMonitorRunning && generateNextQueuedPreview();
}
});
};
/*globals qq */
qq.azure = qq.azure || {};
qq.azure.util = qq.azure.util || (function() {
"use strict";
return {
AZURE_PARAM_PREFIX: "x-ms-meta-",
getParamsAsHeaders: function(params) {
var headers = {};
qq.each(params, function(name, val) {
var headerName = qq.azure.util.AZURE_PARAM_PREFIX + name;
if (qq.isFunction(val)) {
headers[headerName] = encodeURIComponent(String(val()));
}
else if (qq.isObject(val)) {
qq.extend(headers, qq.azure.util.getParamsAsHeaders(val));
}
else {
headers[headerName] = encodeURIComponent(String(val));
}
});
return headers;
},
parseAzureError: function(responseText, log) {
var domParser = new DOMParser(),
responseDoc = domParser.parseFromString(responseText, "application/xml"),
errorTag = responseDoc.getElementsByTagName("Error")[0],
errorDetails = {},
codeTag, messageTag;
log("Received error response: " + responseText, "error");
if (errorTag) {
messageTag = errorTag.getElementsByTagName("Message")[0];
if (messageTag) {
errorDetails.message = messageTag.textContent;
}
codeTag = errorTag.getElementsByTagName("Code")[0];
if (codeTag) {
errorDetails.code = codeTag.textContent;
}
log("Parsed Azure error: " + JSON.stringify(errorDetails), "error");
return errorDetails;
}
}
};
}());
/*globals qq*/
/**
* Defines the public API for non-traditional FineUploaderBasic mode.
*/
(function() {
"use strict";
qq.nonTraditionalBasePublicApi = {
setUploadSuccessParams: function(params, id) {
this._uploadSuccessParamsStore.set(params, id);
},
setUploadSuccessEndpoint: function(endpoint, id) {
this._uploadSuccessEndpointStore.set(endpoint, id);
}
};
qq.nonTraditionalBasePrivateApi = {
/**
* When the upload has completed, if it is successful, send a request to the `successEndpoint` (if defined).
* This will hold up the call to the `onComplete` callback until we have determined success of the upload
* according to the local server, if a `successEndpoint` has been defined by the integrator.
*
* @param id ID of the completed upload
* @param name Name of the associated item
* @param result Object created from the server's parsed JSON response.
* @param xhr Associated XmlHttpRequest, if this was used to send the request.
* @returns {boolean || qq.Promise} true/false if success can be determined immediately, otherwise a `qq.Promise`
* if we need to ask the server.
* @private
*/
_onComplete: function(id, name, result, xhr) {
var success = result.success ? true : false,
self = this,
onCompleteArgs = arguments,
successEndpoint = this._uploadSuccessEndpointStore.get(id),
successCustomHeaders = this._options.uploadSuccess.customHeaders,
cors = this._options.cors,
promise = new qq.Promise(),
uploadSuccessParams = this._uploadSuccessParamsStore.get(id),
fileParams = this._paramsStore.get(id),
// If we are waiting for confirmation from the local server, and have received it,
// include properties from the local server response in the `response` parameter
// sent to the `onComplete` callback, delegate to the parent `_onComplete`, and
// fulfill the associated promise.
onSuccessFromServer = function(successRequestResult) {
delete self._failedSuccessRequestCallbacks[id];
qq.extend(result, successRequestResult);
qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs);
promise.success(successRequestResult);
},
// If the upload success request fails, attempt to re-send the success request (via the core retry code).
// The entire upload may be restarted if the server returns a "reset" property with a value of true as well.
onFailureFromServer = function(successRequestResult) {
var callback = submitSuccessRequest;
qq.extend(result, successRequestResult);
if (result && result.reset) {
callback = null;
}
if (!callback) {
delete self._failedSuccessRequestCallbacks[id];
}
else {
self._failedSuccessRequestCallbacks[id] = callback;
}
if (!self._onAutoRetry(id, name, result, xhr, callback)) {
qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs);
promise.failure(successRequestResult);
}
},
submitSuccessRequest,
successAjaxRequester;
// Ask the local server if the file sent is ok.
if (success && successEndpoint) {
successAjaxRequester = new qq.UploadSuccessAjaxRequester({
endpoint: successEndpoint,
customHeaders: successCustomHeaders,
cors: cors,
log: qq.bind(this.log, this)
});
// combine custom params and default params
qq.extend(uploadSuccessParams, self._getEndpointSpecificParams(id, result, xhr), true);
// include any params associated with the file
fileParams && qq.extend(uploadSuccessParams, fileParams, true);
submitSuccessRequest = qq.bind(function() {
successAjaxRequester.sendSuccessRequest(id, uploadSuccessParams)
.then(onSuccessFromServer, onFailureFromServer);
}, self);
submitSuccessRequest();
return promise;
}
// If we are not asking the local server about the file, just delegate to the parent `_onComplete`.
return qq.FineUploaderBasic.prototype._onComplete.apply(this, arguments);
},
// If the failure occurred on an upload success request (and a reset was not ordered), try to resend that instead.
_manualRetry: function(id) {
var successRequestCallback = this._failedSuccessRequestCallbacks[id];
return qq.FineUploaderBasic.prototype._manualRetry.call(this, id, successRequestCallback);
}
};
}());
/*globals qq */
/**
* This defines FineUploaderBasic mode w/ support for uploading to Azure, which provides all the basic
* functionality of Fine Uploader Basic as well as code to handle uploads directly to Azure.
* Some inherited options and API methods have a special meaning in the context of the Azure uploader.
*/
(function() {
"use strict";
qq.azure.FineUploaderBasic = function(o) {
if (!qq.supportedFeatures.ajaxUploading) {
throw new qq.Error("Uploading directly to Azure is not possible in this browser.");
}
var options = {
signature: {
endpoint: null,
customHeaders: {}
},
// 'uuid', 'filename', or a function which may be promissory
blobProperties: {
name: "uuid"
},
uploadSuccess: {
endpoint: null,
// In addition to the default params sent by Fine Uploader
params: {},
customHeaders: {}
},
chunking: {
// If this is increased, Azure may respond with a 413
partSize: 4000000,
// Don't chunk files less than this size
minFileSize: 4000001
}
};
// Replace any default options with user defined ones
qq.extend(options, o, true);
// Call base module
qq.FineUploaderBasic.call(this, options);
this._uploadSuccessParamsStore = this._createStore(this._options.uploadSuccess.params);
this._uploadSuccessEndpointStore = this._createStore(this._options.uploadSuccess.endpoint);
// This will hold callbacks for failed uploadSuccess requests that will be invoked on retry.
// Indexed by file ID.
this._failedSuccessRequestCallbacks = {};
// Holds blob names for file representations constructed from a session request.
this._cannedBlobNames = {};
};
// Inherit basic public & private API methods.
qq.extend(qq.azure.FineUploaderBasic.prototype, qq.basePublicApi);
qq.extend(qq.azure.FineUploaderBasic.prototype, qq.basePrivateApi);
qq.extend(qq.azure.FineUploaderBasic.prototype, qq.nonTraditionalBasePublicApi);
qq.extend(qq.azure.FineUploaderBasic.prototype, qq.nonTraditionalBasePrivateApi);
// Define public & private API methods for this module.
qq.extend(qq.azure.FineUploaderBasic.prototype, {
getBlobName: function(id) {
/* jshint eqnull:true */
if (this._cannedBlobNames[id] == null) {
return this._handler.getThirdPartyFileId(id);
}
return this._cannedBlobNames[id];
},
_getEndpointSpecificParams: function(id) {
return {
blob: this.getBlobName(id),
uuid: this.getUuid(id),
name: this.getName(id),
container: this._endpointStore.get(id)
};
},
_createUploadHandler: function() {
return qq.FineUploaderBasic.prototype._createUploadHandler.call(this,
{
signature: this._options.signature,
onGetBlobName: qq.bind(this._determineBlobName, this),
deleteBlob: qq.bind(this._deleteBlob, this, true)
},
"azure");
},
_determineBlobName: function(id) {
var self = this,
blobNameOptionValue = this._options.blobProperties.name,
uuid = this.getUuid(id),
filename = this.getName(id),
fileExtension = qq.getExtension(filename);
if (qq.isString(blobNameOptionValue)) {
switch (blobNameOptionValue) {
case "uuid":
return new qq.Promise().success(uuid + "." + fileExtension);
case "filename":
return new qq.Promise().success(filename);
default:
return new qq.Promise.failure("Invalid blobName option value - " + blobNameOptionValue);
}
}
else {
return blobNameOptionValue.call(this, id);
}
},
_addCannedFile: function(sessionData) {
var id;
/* jshint eqnull:true */
if (sessionData.blobName == null) {
throw new qq.Error("Did not find blob name property in server session response. This is required!");
}
else {
id = qq.FineUploaderBasic.prototype._addCannedFile.apply(this, arguments);
this._cannedBlobNames[id] = sessionData.blobName;
}
return id;
},
_deleteBlob: function(relatedToCancel, id) {
var self = this,
deleteBlobSasUri = {},
blobUriStore = {
get: function(id) {
return self._endpointStore.get(id) + "/" + self.getBlobName(id);
}
},
deleteFileEndpointStore = {
get: function(id) {
return deleteBlobSasUri[id];
}
},
getSasSuccess = function(id, sasUri) {
deleteBlobSasUri[id] = sasUri;
deleteBlob.send(id);
},
getSasFailure = function(id, reason, xhr) {
if (relatedToCancel) {
self.log("Will cancel upload, but cannot remove uncommitted parts from Azure due to issue retrieving SAS", "error");
qq.FineUploaderBasic.prototype._onCancel.call(self, id, self.getName(id));
}
else {
self._onDeleteComplete(id, xhr, true);
self._options.callbacks.onDeleteComplete(id, xhr, true);
}
},
deleteBlob = new qq.azure.DeleteBlob({
endpointStore: deleteFileEndpointStore,
log: qq.bind(self.log, self),
onDelete: function(id) {
self._onDelete(id);
self._options.callbacks.onDelete(id);
},
onDeleteComplete: function(id, xhrOrXdr, isError) {
delete deleteBlobSasUri[id];
if (isError) {
if (relatedToCancel) {
self.log("Will cancel upload, but failed to remove uncommitted parts from Azure.", "error");
}
else {
qq.azure.util.parseAzureError(xhrOrXdr.responseText, qq.bind(self.log, self));
}
}
if (relatedToCancel) {
qq.FineUploaderBasic.prototype._onCancel.call(self, id, self.getName(id));
self.log("Deleted uncommitted blob chunks for " + id);
}
else {
self._onDeleteComplete(id, xhrOrXdr, isError);
self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
}
}
}),
getSas = new qq.azure.GetSas({
cors: this._options.cors,
endpointStore: {
get: function() {
return self._options.signature.endpoint;
}
},
restRequestVerb: deleteBlob.method,
log: qq.bind(self.log, self)
});
getSas.request(id, blobUriStore.get(id)).then(
qq.bind(getSasSuccess, self, id),
qq.bind(getSasFailure, self, id));
},
_createDeleteHandler: function() {
var self = this;
return {
sendDelete: function(id, uuid) {
self._deleteBlob(false, id);
}
};
}
});
}());
/*globals qq */
/**
* Upload handler used by the upload to Azure module that depends on File API support, and, therefore, makes use of
* `XMLHttpRequest` level 2 to upload `File`s and `Blob`s directly to Azure Blob Storage containers via the
* associated Azure API.
*
* @param spec Options passed from the base handler
* @param proxy Callbacks & methods used to query for or push out data/changes
*/
// TODO l18n for error messages returned to UI
qq.azure.XhrUploadHandler = function(spec, proxy) {
"use strict";
var handler = this,
log = proxy.log,
cors = spec.cors,
endpointStore = spec.endpointStore,
paramsStore = spec.paramsStore,
signature = spec.signature,
filenameParam = spec.filenameParam,
minFileSizeForChunking = spec.chunking.minFileSize,
deleteBlob = spec.deleteBlob,
onGetBlobName = spec.onGetBlobName,
getName = proxy.getName,
getSize = proxy.getSize,
getBlobMetadata = function(id) {
var params = paramsStore.get(id);
params[filenameParam] = getName(id);
return params;
},
api = {
putBlob: new qq.azure.PutBlob({
getBlobMetadata: getBlobMetadata,
log: log
}),
putBlock: new qq.azure.PutBlock({
log: log
}),
putBlockList: new qq.azure.PutBlockList({
getBlobMetadata: getBlobMetadata,
log: log
}),
getSasForPutBlobOrBlock: new qq.azure.GetSas({
cors: cors,
customHeaders: signature.customHeaders,
endpointStore: {
get: function() {
return signature.endpoint;
}
},
log: log,
restRequestVerb: "PUT"
})
};
function combineChunks(id) {
var promise = new qq.Promise();
getSignedUrl(id).then(function(sasUri) {
var mimeType = handler._getMimeType(id),
blockIdEntries = handler._getPersistableData(id).blockIdEntries;
api.putBlockList.send(id, sasUri, blockIdEntries, mimeType, function(xhr) {
handler._registerXhr(id, null, xhr, api.putBlockList);
})
.then(function(xhr) {
log("Success combining chunks for id " + id);
promise.success({}, xhr);
}, function(xhr) {
log("Attempt to combine chunks failed for id " + id, "error");
handleFailure(xhr, promise);
});
},
promise.failure);
return promise;
}
function determineBlobUrl(id) {
var containerUrl = endpointStore.get(id),
promise = new qq.Promise(),
getBlobNameSuccess = function(blobName) {
handler._setThirdPartyFileId(id, blobName);
promise.success(containerUrl + "/" + blobName);
},
getBlobNameFailure = function(reason) {
promise.failure(reason);
};
onGetBlobName(id).then(getBlobNameSuccess, getBlobNameFailure);
return promise;
}
function getSignedUrl(id, optChunkIdx) {
// We may have multiple SAS requests in progress for the same file, so we must include the chunk idx
// as part of the ID when communicating with the SAS ajax requester to avoid collisions.
var getSasId = optChunkIdx == null ? id : id + "." + optChunkIdx,
promise = new qq.Promise(),
getSasSuccess = function(sasUri) {
log("GET SAS request succeeded.");
promise.success(sasUri);
},
getSasFailure = function(reason, getSasXhr) {
log("GET SAS request failed: " + reason, "error");
promise.failure({error: "Problem communicating with local server"}, getSasXhr);
},
determineBlobUrlSuccess = function(blobUrl) {
api.getSasForPutBlobOrBlock.request(getSasId, blobUrl).then(
getSasSuccess,
getSasFailure
);
},
determineBlobUrlFailure = function(reason) {
log(qq.format("Failed to determine blob name for ID {} - {}", id, reason), "error");
promise.failure({error: reason});
};
determineBlobUrl(id).then(determineBlobUrlSuccess, determineBlobUrlFailure);
return promise;
}
function handleFailure(xhr, promise) {
var azureError = qq.azure.util.parseAzureError(xhr.responseText, log),
errorMsg = "Problem sending file to Azure";
promise.failure({error: errorMsg,
azureError: azureError && azureError.message,
reset: xhr.status === 403
});
}
qq.extend(this, {
uploadChunk: function(id, chunkIdx) {
var promise = new qq.Promise();
getSignedUrl(id, chunkIdx).then(
function(sasUri) {
var xhr = handler._createXhr(id, chunkIdx),
chunkData = handler._getChunkData(id, chunkIdx);
handler._registerProgressHandler(id, chunkIdx, chunkData.size);
handler._registerXhr(id, chunkIdx, xhr, api.putBlock);
// We may have multiple put block requests in progress for the same file, so we must include the chunk idx
// as part of the ID when communicating with the put block ajax requester to avoid collisions.
api.putBlock.upload(id + "." + chunkIdx, xhr, sasUri, chunkIdx, chunkData.blob).then(
function(blockIdEntry) {
if (!handler._getPersistableData(id).blockIdEntries) {
handler._getPersistableData(id).blockIdEntries = [];
}
handler._getPersistableData(id).blockIdEntries.push(blockIdEntry);
log("Put Block call succeeded for " + id);
promise.success({}, xhr);
},
function() {
log(qq.format("Put Block call failed for ID {} on part {}", id, chunkIdx), "error");
handleFailure(xhr, promise);
}
);
},
promise.failure
);
return promise;
},
uploadFile: function(id) {
var promise = new qq.Promise(),
fileOrBlob = handler.getFile(id);
getSignedUrl(id).then(function(sasUri) {
var xhr = handler._createXhr(id);
handler._registerProgressHandler(id);
api.putBlob.upload(id, xhr, sasUri, fileOrBlob).then(
function() {
log("Put Blob call succeeded for " + id);
promise.success({}, xhr);
},
function() {
log("Put Blob call failed for " + id, "error");
handleFailure(xhr, promise);
}
);
},
promise.failure);
return promise;
}
});
qq.extend(this,
new qq.XhrUploadHandler({
options: qq.extend({namespace: "azure"}, spec),
proxy: qq.extend({getEndpoint: spec.endpointStore.get}, proxy)
}
));
qq.override(this, function(super_) {
return {
expunge: function(id) {
var relatedToCancel = handler._wasCanceled(id),
chunkingData = handler._getPersistableData(id),
blockIdEntries = (chunkingData && chunkingData.blockIdEntries) || [];
if (relatedToCancel && blockIdEntries.length > 0) {
deleteBlob(id);
}
super_.expunge(id);
},
finalizeChunks: function(id) {
return combineChunks(id);
},
_shouldChunkThisFile: function(id) {
var maybePossible = super_._shouldChunkThisFile(id);
return maybePossible && getSize(id) >= minFileSizeForChunking;
}
};
});
};
/* globals qq */
/**
* Sends a GET request to the integrator's server, which should return a Shared Access Signature URI used to
* make a specific request on a Blob via the Azure REST API.
*/
qq.azure.GetSas = function(o) {
"use strict";
var requester,
options = {
cors: {
expected: false,
sendCredentials: false
},
customHeaders: {},
restRequestVerb: "PUT",
endpointStore: null,
log: function(str, level) {}
},
requestPromises = {};
qq.extend(options, o);
function sasResponseReceived(id, xhr, isError) {
var promise = requestPromises[id];
if (isError) {
promise.failure("Received response code " + xhr.status, xhr);
}
else {
if (xhr.responseText.length) {
promise.success(xhr.responseText);
}
else {
promise.failure("Empty response.", xhr);
}
}
delete requestPromises[id];
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: ["GET"],
method: "GET",
successfulResponseCodes: {
GET: [200]
},
contentType: null,
customHeaders: options.customHeaders,
endpointStore: options.endpointStore,
cors: options.cors,
log: options.log,
onComplete: sasResponseReceived
}));
qq.extend(this, {
request: function(id, blobUri) {
var requestPromise = new qq.Promise(),
restVerb = options.restRequestVerb;
options.log(qq.format("Submitting GET SAS request for a {} REST request related to file ID {}.", restVerb, id));
requestPromises[id] = requestPromise;
requester.initTransport(id)
.withParams({
bloburi: blobUri,
_method: restVerb
})
.withCacheBuster()
.send();
return requestPromise;
}
});
};
/*globals qq, XMLHttpRequest*/
/**
* Sends a POST request to the server to notify it of a successful upload to an endpoint. The server is expected to indicate success
* or failure via the response status. Specific information about the failure can be passed from the server via an `error`
* property (by default) in an "application/json" response.
*
* @param o Options associated with all requests.
* @constructor
*/
qq.UploadSuccessAjaxRequester = function(o) {
"use strict";
var requester,
pendingRequests = [],
options = {
method: "POST",
endpoint: null,
maxConnections: 3,
customHeaders: {},
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {}
};
qq.extend(options, o);
function handleSuccessResponse(id, xhrOrXdr, isError) {
var promise = pendingRequests[id],
responseJson = xhrOrXdr.responseText,
successIndicator = {success: true},
failureIndicator = {success: false},
parsedResponse;
delete pendingRequests[id];
options.log(qq.format("Received the following response body to an upload success request for id {}: {}", id, responseJson));
try {
parsedResponse = qq.parseJson(responseJson);
// If this is a cross-origin request, the server may return a 200 response w/ error or success properties
// in order to ensure any specific error message is picked up by Fine Uploader for all browsers,
// since XDomainRequest (used in IE9 and IE8) doesn't give you access to the
// response body for an "error" response.
if (isError || (parsedResponse && (parsedResponse.error || parsedResponse.success === false))) {
options.log("Upload success request was rejected by the server.", "error");
promise.failure(qq.extend(parsedResponse, failureIndicator));
}
else {
options.log("Upload success was acknowledged by the server.");
promise.success(qq.extend(parsedResponse, successIndicator));
}
}
catch (error) {
// This will be executed if a JSON response is not present. This is not mandatory, so account for this properly.
if (isError) {
options.log(qq.format("Your server indicated failure in its upload success request response for id {}!", id), "error");
promise.failure(failureIndicator);
}
else {
options.log("Upload success was acknowledged by the server.");
promise.success(successIndicator);
}
}
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
method: options.method,
endpointStore: {
get: function() {
return options.endpoint;
}
},
paramsStore: options.paramsStore,
maxConnections: options.maxConnections,
customHeaders: options.customHeaders,
log: options.log,
onComplete: handleSuccessResponse,
cors: options.cors,
successfulResponseCodes: {
POST: [200]
}
}));
qq.extend(this, {
/**
* Sends a request to the server, notifying it that a recently submitted file was successfully sent.
*
* @param id ID of the associated file
* @param spec `Object` with the properties that correspond to important values that we want to
* send to the server with this request.
* @returns {qq.Promise} A promise to be fulfilled when the response has been received and parsed. The parsed
* payload of the response will be passed into the `failure` or `success` promise method.
*/
sendSuccessRequest: function(id, spec) {
var promise = new qq.Promise();
options.log("Submitting upload success request/notification for " + id);
requester.initTransport(id)
.withParams(spec)
.send();
pendingRequests[id] = promise;
return promise;
}
});
};
/* globals qq */
/**
* Implements the Delete Blob Azure REST API call. http://msdn.microsoft.com/en-us/library/windowsazure/dd179413.aspx.
*/
qq.azure.DeleteBlob = function(o) {
"use strict";
var requester,
method = "DELETE",
options = {
endpointStore: {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhr, isError) {},
log: function(str, level) {}
};
qq.extend(options, o);
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [method],
method: method,
successfulResponseCodes: (function() {
var codes = {};
codes[method] = [202];
return codes;
}()),
contentType: null,
endpointStore: options.endpointStore,
allowXRequestedWithAndCacheControl: false,
cors: {
expected: true
},
log: options.log,
onSend: options.onDelete,
onComplete: options.onDeleteComplete
}));
qq.extend(this, {
method: method,
send: function(id) {
options.log("Submitting Delete Blob request for " + id);
return requester.initTransport(id)
.send();
}
});
};
/* globals qq */
/**
* Implements the Put Blob Azure REST API call. http://msdn.microsoft.com/en-us/library/windowsazure/dd179451.aspx.
*/
qq.azure.PutBlob = function(o) {
"use strict";
var requester,
method = "PUT",
options = {
getBlobMetadata: function(id) {},
log: function(str, level) {}
},
endpoints = {},
promises = {},
endpointHandler = {
get: function(id) {
return endpoints[id];
}
};
qq.extend(options, o);
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [method],
method: method,
successfulResponseCodes: (function() {
var codes = {};
codes[method] = [201];
return codes;
}()),
contentType: null,
customHeaders: function(id) {
var params = options.getBlobMetadata(id),
headers = qq.azure.util.getParamsAsHeaders(params);
headers["x-ms-blob-type"] = "BlockBlob";
return headers;
},
endpointStore: endpointHandler,
allowXRequestedWithAndCacheControl: false,
cors: {
expected: true
},
log: options.log,
onComplete: function(id, xhr, isError) {
var promise = promises[id];
delete endpoints[id];
delete promises[id];
if (isError) {
promise.failure();
}
else {
promise.success();
}
}
}));
qq.extend(this, {
method: method,
upload: function(id, xhr, url, file) {
var promise = new qq.Promise();
options.log("Submitting Put Blob request for " + id);
promises[id] = promise;
endpoints[id] = url;
requester.initTransport(id)
.withPayload(file)
.withHeaders({"Content-Type": file.type})
.send(xhr);
return promise;
}
});
};
/* globals qq */
/**
* Implements the Put Block List Azure REST API call. http://msdn.microsoft.com/en-us/library/windowsazure/dd179467.aspx.
*/
qq.azure.PutBlockList = function(o) {
"use strict";
var requester,
method = "PUT",
promises = {},
options = {
getBlobMetadata: function(id) {},
log: function(str, level) {}
},
endpoints = {},
endpointHandler = {
get: function(id) {
return endpoints[id];
}
};
qq.extend(options, o);
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [method],
method: method,
successfulResponseCodes: (function() {
var codes = {};
codes[method] = [201];
return codes;
}()),
customHeaders: function(id) {
var params = options.getBlobMetadata(id);
return qq.azure.util.getParamsAsHeaders(params);
},
contentType: "text/plain",
endpointStore: endpointHandler,
allowXRequestedWithAndCacheControl: false,
cors: {
expected: true
},
log: options.log,
onSend: function() {},
onComplete: function(id, xhr, isError) {
var promise = promises[id];
delete endpoints[id];
delete promises[id];
if (isError) {
promise.failure(xhr);
}
else {
promise.success(xhr);
}
}
}));
function createRequestBody(blockIdEntries) {
var doc = document.implementation.createDocument(null, "BlockList", null);
// If we don't sort the block ID entries by part number, the file will be combined incorrectly by Azure
blockIdEntries.sort(function(a, b) {
return a.part - b.part;
});
// Construct an XML document for each pair of etag/part values that correspond to part uploads.
qq.each(blockIdEntries, function(idx, blockIdEntry) {
var latestEl = doc.createElement("Latest"),
latestTextEl = doc.createTextNode(blockIdEntry.id);
latestEl.appendChild(latestTextEl);
qq(doc).children()[0].appendChild(latestEl);
});
// Turn the resulting XML document into a string fit for transport.
return new XMLSerializer().serializeToString(doc);
}
qq.extend(this, {
method: method,
send: function(id, sasUri, blockIdEntries, fileMimeType, registerXhrCallback) {
var promise = new qq.Promise(),
blockIdsXml = createRequestBody(blockIdEntries),
xhr;
promises[id] = promise;
options.log(qq.format("Submitting Put Block List request for {}", id));
endpoints[id] = qq.format("{}&comp=blocklist", sasUri);
xhr = requester.initTransport(id)
.withPayload(blockIdsXml)
.withHeaders({"x-ms-blob-content-type": fileMimeType})
.send();
registerXhrCallback(xhr);
return promise;
}
});
};
/* globals qq */
/**
* Implements the Put Block Azure REST API call. http://msdn.microsoft.com/en-us/library/windowsazure/dd135726.aspx.
*/
qq.azure.PutBlock = function(o) {
"use strict";
var requester,
method = "PUT",
blockIdEntries = {},
promises = {},
options = {
log: function(str, level) {}
},
endpoints = {},
endpointHandler = {
get: function(id) {
return endpoints[id];
}
};
qq.extend(options, o);
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [method],
method: method,
successfulResponseCodes: (function() {
var codes = {};
codes[method] = [201];
return codes;
}()),
contentType: null,
endpointStore: endpointHandler,
allowXRequestedWithAndCacheControl: false,
cors: {
expected: true
},
log: options.log,
onComplete: function(id, xhr, isError) {
var promise = promises[id],
blockIdEntry = blockIdEntries[id];
delete endpoints[id];
delete promises[id];
delete blockIdEntries[id];
if (isError) {
promise.failure();
}
else {
promise.success(blockIdEntry);
}
}
}));
function createBlockId(partNum) {
var digits = 5,
zeros = new Array(digits + 1).join("0"),
paddedPartNum = (zeros + partNum).slice(-digits);
return btoa(paddedPartNum);
}
qq.extend(this, {
method: method,
upload: function(id, xhr, sasUri, partNum, blob) {
var promise = new qq.Promise(),
blockId = createBlockId(partNum);
promises[id] = promise;
options.log(qq.format("Submitting Put Block request for {} = part {}", id, partNum));
endpoints[id] = qq.format("{}&comp=block&blockid={}", sasUri, encodeURIComponent(blockId));
blockIdEntries[id] = {part: partNum, id: blockId};
requester.initTransport(id)
.withPayload(blob)
.send(xhr);
return promise;
}
});
};
/*globals qq */
/**
* This defines FineUploader mode w/ support for uploading to Azure, which provides all the basic
* functionality of Fine Uploader as well as code to handle uploads directly to Azure.
* This module inherits all logic from UI & core mode and adds some UI-related logic
* specific to the upload-to-Azure workflow. Some inherited options and API methods have a special meaning
* in the context of the Azure uploader.
*/
(function() {
"use strict";
qq.azure.FineUploader = function(o) {
var options = {
failedUploadTextDisplay: {
mode: "custom"
}
};
// Replace any default options with user defined ones
qq.extend(options, o, true);
// Inherit instance data from FineUploader, which should in turn inherit from azure.FineUploaderBasic.
qq.FineUploader.call(this, options, "azure");
};
// Inherit the API methods from FineUploaderBasicS3
qq.extend(qq.azure.FineUploader.prototype, qq.azure.FineUploaderBasic.prototype);
// Inherit public and private API methods related to UI
qq.extend(qq.azure.FineUploader.prototype, qq.uiPublicApi);
qq.extend(qq.azure.FineUploader.prototype, qq.uiPrivateApi);
// Define public & private API methods for this module.
qq.extend(qq.azure.FineUploader.prototype, {
});
}());
/*globals qq*/
qq.PasteSupport = function(o) {
"use strict";
var options, detachPasteHandler;
options = {
targetElement: null,
callbacks: {
log: function(message, level) {},
pasteReceived: function(blob) {}
}
};
function isImage(item) {
return item.type &&
item.type.indexOf("image/") === 0;
}
function registerPasteHandler() {
detachPasteHandler = qq(options.targetElement).attach("paste", function(event) {
var clipboardData = event.clipboardData;
if (clipboardData) {
qq.each(clipboardData.items, function(idx, item) {
if (isImage(item)) {
var blob = item.getAsFile();
options.callbacks.pasteReceived(blob);
}
});
}
});
}
function unregisterPasteHandler() {
if (detachPasteHandler) {
detachPasteHandler();
}
}
qq.extend(options, o);
registerPasteHandler();
qq.extend(this, {
reset: function() {
unregisterPasteHandler();
}
});
};
/*globals qq, document, CustomEvent*/
qq.DragAndDrop = function(o) {
"use strict";
var options,
HIDE_ZONES_EVENT_NAME = "qq-hidezones",
HIDE_BEFORE_ENTER_ATTR = "qq-hide-dropzone",
uploadDropZones = [],
droppedFiles = [],
disposeSupport = new qq.DisposeSupport();
options = {
dropZoneElements: [],
allowMultipleItems: true,
classes: {
dropActive: null
},
callbacks: new qq.DragAndDrop.callbacks()
};
qq.extend(options, o, true);
function uploadDroppedFiles(files, uploadDropZone) {
// We need to convert the `FileList` to an actual `Array` to avoid iteration issues
var filesAsArray = Array.prototype.slice.call(files);
options.callbacks.dropLog("Grabbed " + files.length + " dropped files.");
uploadDropZone.dropDisabled(false);
options.callbacks.processingDroppedFilesComplete(filesAsArray, uploadDropZone.getElement());
}
function traverseFileTree(entry) {
var parseEntryPromise = new qq.Promise();
if (entry.isFile) {
entry.file(function(file) {
var name = entry.name,
fullPath = entry.fullPath,
indexOfNameInFullPath = fullPath.indexOf(name);
// remove file name from full path string
fullPath = fullPath.substr(0, indexOfNameInFullPath);
// remove leading slash in full path string
if (fullPath.charAt(0) === "/") {
fullPath = fullPath.substr(1);
}
file.qqPath = fullPath;
droppedFiles.push(file);
parseEntryPromise.success();
},
function(fileError) {
options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error");
parseEntryPromise.failure();
});
}
else if (entry.isDirectory) {
getFilesInDirectory(entry).then(
function allEntriesRead(entries) {
var entriesLeft = entries.length;
qq.each(entries, function(idx, entry) {
traverseFileTree(entry).done(function() {
entriesLeft -= 1;
if (entriesLeft === 0) {
parseEntryPromise.success();
}
});
});
if (!entries.length) {
parseEntryPromise.success();
}
},
function readFailure(fileError) {
options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error");
parseEntryPromise.failure();
}
);
}
return parseEntryPromise;
}
// Promissory. Guaranteed to read all files in the root of the passed directory.
function getFilesInDirectory(entry, reader, accumEntries, existingPromise) {
var promise = existingPromise || new qq.Promise(),
dirReader = reader || entry.createReader();
dirReader.readEntries(
function readSuccess(entries) {
var newEntries = accumEntries ? accumEntries.concat(entries) : entries;
if (entries.length) {
setTimeout(function() { // prevent stack oveflow, however unlikely
getFilesInDirectory(entry, dirReader, newEntries, promise);
}, 0);
}
else {
promise.success(newEntries);
}
},
promise.failure
);
return promise;
}
function handleDataTransfer(dataTransfer, uploadDropZone) {
var pendingFolderPromises = [],
handleDataTransferPromise = new qq.Promise();
options.callbacks.processingDroppedFiles();
uploadDropZone.dropDisabled(true);
if (dataTransfer.files.length > 1 && !options.allowMultipleItems) {
options.callbacks.processingDroppedFilesComplete([]);
options.callbacks.dropError("tooManyFilesError", "");
uploadDropZone.dropDisabled(false);
handleDataTransferPromise.failure();
}
else {
droppedFiles = [];
if (qq.isFolderDropSupported(dataTransfer)) {
qq.each(dataTransfer.items, function(idx, item) {
var entry = item.webkitGetAsEntry();
if (entry) {
//due to a bug in Chrome's File System API impl - #149735
if (entry.isFile) {
droppedFiles.push(item.getAsFile());
}
else {
pendingFolderPromises.push(traverseFileTree(entry).done(function() {
pendingFolderPromises.pop();
if (pendingFolderPromises.length === 0) {
handleDataTransferPromise.success();
}
}));
}
}
});
}
else {
droppedFiles = dataTransfer.files;
}
if (pendingFolderPromises.length === 0) {
handleDataTransferPromise.success();
}
}
return handleDataTransferPromise;
}
function setupDropzone(dropArea) {
var dropZone = new qq.UploadDropZone({
HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME,
element: dropArea,
onEnter: function(e) {
qq(dropArea).addClass(options.classes.dropActive);
e.stopPropagation();
},
onLeaveNotDescendants: function(e) {
qq(dropArea).removeClass(options.classes.dropActive);
},
onDrop: function(e) {
handleDataTransfer(e.dataTransfer, dropZone).then(
function() {
uploadDroppedFiles(droppedFiles, dropZone);
},
function() {
options.callbacks.dropLog("Drop event DataTransfer parsing failed. No files will be uploaded.", "error");
}
);
}
});
disposeSupport.addDisposer(function() {
dropZone.dispose();
});
qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide();
uploadDropZones.push(dropZone);
return dropZone;
}
function isFileDrag(dragEvent) {
var fileDrag;
qq.each(dragEvent.dataTransfer.types, function(key, val) {
if (val === "Files") {
fileDrag = true;
return false;
}
});
return fileDrag;
}
// Attempt to determine when the file has left the document. It is not always possible to detect this
// in all cases, but it is generally possible in all browsers, with a few exceptions.
//
// Exceptions:
// * IE10+ & Safari: We can't detect a file leaving the document if the Explorer window housing the file
// overlays the browser window.
// * IE10+: If the file is dragged out of the window too quickly, IE does not set the expected values of the
// event's X & Y properties.
function leavingDocumentOut(e) {
if (qq.firefox()) {
return !e.relatedTarget;
}
if (qq.safari()) {
return e.x < 0 || e.y < 0;
}
return e.x === 0 && e.y === 0;
}
function setupDragDrop() {
var dropZones = options.dropZoneElements,
maybeHideDropZones = function() {
setTimeout(function() {
qq.each(dropZones, function(idx, dropZone) {
qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide();
qq(dropZone).removeClass(options.classes.dropActive);
});
}, 10);
};
qq.each(dropZones, function(idx, dropZone) {
var uploadDropZone = setupDropzone(dropZone);
// IE <= 9 does not support the File API used for drag+drop uploads
if (dropZones.length && qq.supportedFeatures.fileDrop) {
disposeSupport.attach(document, "dragenter", function(e) {
if (!uploadDropZone.dropDisabled() && isFileDrag(e)) {
qq.each(dropZones, function(idx, dropZone) {
// We can't apply styles to non-HTMLElements, since they lack the `style` property.
// Also, if the drop zone isn't initially hidden, let's not mess with `style.display`.
if (dropZone instanceof HTMLElement &&
qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR)) {
qq(dropZone).css({display: "block"});
}
});
}
});
}
});
disposeSupport.attach(document, "dragleave", function(e) {
if (leavingDocumentOut(e)) {
maybeHideDropZones();
}
});
// Just in case we were not able to detect when a dragged file has left the document,
// hide all relevant drop zones the next time the mouse enters the document.
// Album that mouse events such as this one are not fired during drag operations.
disposeSupport.attach(qq(document).children()[0], "mouseenter", function(e) {
maybeHideDropZones();
});
disposeSupport.attach(document, "drop", function(e) {
e.preventDefault();
maybeHideDropZones();
});
disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, maybeHideDropZones);
}
setupDragDrop();
qq.extend(this, {
setupExtraDropzone: function(element) {
options.dropZoneElements.push(element);
setupDropzone(element);
},
removeDropzone: function(element) {
var i,
dzs = options.dropZoneElements;
for (i in dzs) {
if (dzs[i] === element) {
return dzs.splice(i, 1);
}
}
},
dispose: function() {
disposeSupport.dispose();
qq.each(uploadDropZones, function(idx, dropZone) {
dropZone.dispose();
});
}
});
};
qq.DragAndDrop.callbacks = function() {
"use strict";
return {
processingDroppedFiles: function() {},
processingDroppedFilesComplete: function(files, targetEl) {},
dropError: function(code, errorSpecifics) {
qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error");
},
dropLog: function(message, level) {
qq.log(message, level);
}
};
};
qq.UploadDropZone = function(o) {
"use strict";
var disposeSupport = new qq.DisposeSupport(),
options, element, preventDrop, dropOutsideDisabled;
options = {
element: null,
onEnter: function(e) {},
onLeave: function(e) {},
// is not fired when leaving element by hovering descendants
onLeaveNotDescendants: function(e) {},
onDrop: function(e) {}
};
qq.extend(options, o);
element = options.element;
function dragoverShouldBeCanceled() {
return qq.safari() || (qq.firefox() && qq.windows());
}
function disableDropOutside(e) {
// run only once for all instances
if (!dropOutsideDisabled) {
// for these cases we need to catch onDrop to reset dropArea
if (dragoverShouldBeCanceled) {
disposeSupport.attach(document, "dragover", function(e) {
e.preventDefault();
});
} else {
disposeSupport.attach(document, "dragover", function(e) {
if (e.dataTransfer) {
e.dataTransfer.dropEffect = "none";
e.preventDefault();
}
});
}
dropOutsideDisabled = true;
}
}
function isValidFileDrag(e) {
// e.dataTransfer currently causing IE errors
// IE9 does NOT support file API, so drag-and-drop is not possible
if (!qq.supportedFeatures.fileDrop) {
return false;
}
var effectTest, dt = e.dataTransfer,
// do not check dt.types.contains in webkit, because it crashes safari 4
isSafari = qq.safari();
// dt.effectAllowed is none in Safari 5
// dt.types.contains check is for firefox
// dt.effectAllowed crashes IE 11 & 10 when files have been dragged from
// the filesystem
effectTest = qq.ie() && qq.supportedFeatures.fileDrop ? true : dt.effectAllowed !== "none";
return dt && effectTest && (dt.files || (!isSafari && dt.types.contains && dt.types.contains("Files")));
}
function isOrSetDropDisabled(isDisabled) {
if (isDisabled !== undefined) {
preventDrop = isDisabled;
}
return preventDrop;
}
function triggerHidezonesEvent() {
var hideZonesEvent;
function triggerUsingOldApi() {
hideZonesEvent = document.createEvent("Event");
hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true);
}
if (window.CustomEvent) {
try {
hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME);
}
catch (err) {
triggerUsingOldApi();
}
}
else {
triggerUsingOldApi();
}
document.dispatchEvent(hideZonesEvent);
}
function attachEvents() {
disposeSupport.attach(element, "dragover", function(e) {
if (!isValidFileDrag(e)) {
return;
}
// dt.effectAllowed crashes IE 11 & 10 when files have been dragged from
// the filesystem
var effect = qq.ie() && qq.supportedFeatures.fileDrop ? null : e.dataTransfer.effectAllowed;
if (effect === "move" || effect === "linkMove") {
e.dataTransfer.dropEffect = "move"; // for FF (only move allowed)
} else {
e.dataTransfer.dropEffect = "copy"; // for Chrome
}
e.stopPropagation();
e.preventDefault();
});
disposeSupport.attach(element, "dragenter", function(e) {
if (!isOrSetDropDisabled()) {
if (!isValidFileDrag(e)) {
return;
}
options.onEnter(e);
}
});
disposeSupport.attach(element, "dragleave", function(e) {
if (!isValidFileDrag(e)) {
return;
}
options.onLeave(e);
var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
// do not fire when moving a mouse over a descendant
if (qq(this).contains(relatedTarget)) {
return;
}
options.onLeaveNotDescendants(e);
});
disposeSupport.attach(element, "drop", function(e) {
if (!isOrSetDropDisabled()) {
if (!isValidFileDrag(e)) {
return;
}
e.preventDefault();
e.stopPropagation();
options.onDrop(e);
triggerHidezonesEvent();
}
});
}
disableDropOutside();
attachEvents();
qq.extend(this, {
dropDisabled: function(isDisabled) {
return isOrSetDropDisabled(isDisabled);
},
dispose: function() {
disposeSupport.dispose();
},
getElement: function() {
return element;
}
});
};
/*globals qq, XMLHttpRequest*/
qq.DeleteFileAjaxRequester = function(o) {
"use strict";
var requester,
options = {
method: "DELETE",
uuidParamName: "qquuid",
endpointStore: {},
maxConnections: 3,
customHeaders: function(id) {return {};},
paramsStore: {},
demoMode: false,
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {}
};
qq.extend(options, o);
function getMandatedParams() {
if (options.method.toUpperCase() === "POST") {
return {
_method: "DELETE"
};
}
return {};
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: ["POST", "DELETE"],
method: options.method,
endpointStore: options.endpointStore,
paramsStore: options.paramsStore,
mandatedParams: getMandatedParams(),
maxConnections: options.maxConnections,
customHeaders: function(id) {
return options.customHeaders.get(id);
},
demoMode: options.demoMode,
log: options.log,
onSend: options.onDelete,
onComplete: options.onDeleteComplete,
cors: options.cors
}));
qq.extend(this, {
sendDelete: function(id, uuid, additionalMandatedParams) {
var additionalOptions = additionalMandatedParams || {};
options.log("Submitting delete file request for " + id);
if (options.method === "DELETE") {
requester.initTransport(id)
.withPath(uuid)
.withParams(additionalOptions)
.send();
}
else {
additionalOptions[options.uuidParamName] = uuid;
requester.initTransport(id)
.withParams(additionalOptions)
.send();
}
}
});
};
/*global qq, define */
/*jshint strict:false,bitwise:false,nonew:false,asi:true,-W064,-W116,-W089 */
/**
* Mega pixel image rendering library for iOS6+
*
* Fixes iOS6+'s image file rendering issue for large size image (over mega-pixel),
* which causes unexpected subsampling when drawing it in canvas.
* By using this library, you can safely render the image with proper stretching.
*
* Copyright (c) 2012 Shinichi Tomita <[email protected]>
* Released under the MIT license
*
* Heavily modified by Widen for Fine Uploader
*/
(function() {
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be subsampled in rendering.
*/
function detectSubsampling(img) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas = document.createElement("canvas"),
ctx;
if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image
canvas.width = canvas.height = 1;
ctx = canvas.getContext("2d");
ctx.drawImage(img, -iw + 1, 0);
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering edge pixel or not.
// if alpha value is 0 image is not covering, hence subsampled.
return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
} else {
return false;
}
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into canvas for some images.
*/
function detectVerticalSquash(img, iw, ih) {
var canvas = document.createElement("canvas"),
sy = 0,
ey = ih,
py = ih,
ctx, data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
data = ctx.getImageData(0, 0, 1, ih).data;
// search image edge pixel position in case it is squashed vertically.
while (py > sy) {
alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
/**
* Rendering image element (with resizing) and get its data URL
*/
function renderImageToDataURL(img, options, doSquash) {
var canvas = document.createElement("canvas"),
mime = options.mime || "image/jpeg";
renderImageToCanvas(img, canvas, options, doSquash);
return canvas.toDataURL(mime, options.quality || 0.8);
}
function maybeCalculateDownsampledDimensions(spec) {
var maxPixels = 5241000; //iOS specific value
if (!qq.ios()) {
throw new qq.Error("Downsampled dimensions can only be reliably calculated for iOS!");
}
if (spec.origHeight * spec.origWidth > maxPixels) {
return {
newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))),
newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight)))
}
}
}
/**
* Rendering image element (with resizing) into the canvas element
*/
function renderImageToCanvas(img, canvas, options, doSquash) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
width = options.width,
height = options.height,
ctx = canvas.getContext("2d"),
modifiedDimensions;
ctx.save();
if (!qq.supportedFeatures.unlimitedScaledImageSize) {
modifiedDimensions = maybeCalculateDownsampledDimensions({
origWidth: width,
origHeight: height
});
if (modifiedDimensions) {
qq.log(qq.format("Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h",
width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight),
"warn");
width = modifiedDimensions.newWidth;
height = modifiedDimensions.newHeight;
}
}
transformCoordinate(canvas, width, height, options.orientation);
// Fine Uploader specific: Save some CPU cycles if not using iOS
// Assumption: This logic is only needed to overcome iOS image sampling issues
if (qq.ios()) {
(function() {
if (detectSubsampling(img)) {
iw /= 2;
ih /= 2;
}
var d = 1024, // size of tiling canvas
tmpCanvas = document.createElement("canvas"),
vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1,
dw = Math.ceil(d * width / iw),
dh = Math.ceil(d * height / ih / vertSquashRatio),
sy = 0,
dy = 0,
tmpCtx, sx, dx;
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext("2d");
while (sy < ih) {
sx = 0,
dx = 0;
while (sx < iw) {
tmpCtx.clearRect(0, 0, d, d);
tmpCtx.drawImage(img, -sx, -sy);
ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
}())
}
else {
ctx.drawImage(img, 0, 0, width, height);
}
canvas.qqImageRendered && canvas.qqImageRendered();
}
/**
* Transform canvas coordination according to specified frame size and orientation
* Orientation value is from EXIF tag
*/
function transformCoordinate(canvas, width, height, orientation) {
switch (orientation) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
default:
canvas.width = width;
canvas.height = height;
}
var ctx = canvas.getContext("2d");
switch (orientation) {
case 2:
// horizontal flip
ctx.translate(width, 0);
ctx.scale(-1, 1);
break;
case 3:
// 180 rotate left
ctx.translate(width, height);
ctx.rotate(Math.PI);
break;
case 4:
// vertical flip
ctx.translate(0, height);
ctx.scale(1, -1);
break;
case 5:
// vertical flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
// 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(0, -height);
break;
case 7:
// horizontal flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(width, -height);
ctx.scale(-1, 1);
break;
case 8:
// 90 rotate left
ctx.rotate(-0.5 * Math.PI);
ctx.translate(-width, 0);
break;
default:
break;
}
}
/**
* MegaPixImage class
*/
function MegaPixImage(srcImage, errorCallback) {
var self = this;
if (window.Blob && srcImage instanceof Blob) {
(function() {
var img = new Image(),
URL = window.URL && window.URL.createObjectURL ? window.URL :
window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
if (!URL) { throw Error("No createObjectURL function found to create blob url"); }
img.src = URL.createObjectURL(srcImage);
self.blob = srcImage;
srcImage = img;
}());
}
if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
srcImage.onload = function() {
var listeners = self.imageLoadListeners;
if (listeners) {
self.imageLoadListeners = null;
// IE11 doesn't reliably report actual image dimensions immediately after onload for small files,
// so let's push this to the end of the UI thread queue.
setTimeout(function() {
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i]();
}
}, 0);
}
};
srcImage.onerror = errorCallback;
this.imageLoadListeners = [];
}
this.srcImage = srcImage;
}
/**
* Rendering megapix image into specified target element
*/
MegaPixImage.prototype.render = function(target, options) {
options = options || {};
var self = this,
imgWidth = this.srcImage.naturalWidth,
imgHeight = this.srcImage.naturalHeight,
width = options.width,
height = options.height,
maxWidth = options.maxWidth,
maxHeight = options.maxHeight,
doSquash = !this.blob || this.blob.type === "image/jpeg",
tagName = target.tagName.toLowerCase(),
opt;
if (this.imageLoadListeners) {
this.imageLoadListeners.push(function() { self.render(target, options) });
return;
}
if (width && !height) {
height = (imgHeight * width / imgWidth) << 0;
} else if (height && !width) {
width = (imgWidth * height / imgHeight) << 0;
} else {
width = imgWidth;
height = imgHeight;
}
if (maxWidth && width > maxWidth) {
width = maxWidth;
height = (imgHeight * width / imgWidth) << 0;
}
if (maxHeight && height > maxHeight) {
height = maxHeight;
width = (imgWidth * height / imgHeight) << 0;
}
opt = { width: width, height: height },
qq.each(options, function(optionsKey, optionsValue) {
opt[optionsKey] = optionsValue;
});
if (tagName === "img") {
(function() {
var oldTargetSrc = target.src;
target.src = renderImageToDataURL(self.srcImage, opt, doSquash);
oldTargetSrc === target.src && target.onload();
}())
} else if (tagName === "canvas") {
renderImageToCanvas(this.srcImage, target, opt, doSquash);
}
if (typeof this.onrender === "function") {
this.onrender(target);
}
};
qq.MegaPixImage = MegaPixImage;
})();
/*globals qq */
/**
* Draws a thumbnail of a Blob/File/URL onto an <img> or <canvas>.
*
* @constructor
*/
qq.ImageGenerator = function(log) {
"use strict";
function isImg(el) {
return el.tagName.toLowerCase() === "img";
}
function isCanvas(el) {
return el.tagName.toLowerCase() === "canvas";
}
function isImgCorsSupported() {
return new Image().crossOrigin !== undefined;
}
function isCanvasSupported() {
var canvas = document.createElement("canvas");
return canvas.getContext && canvas.getContext("2d");
}
// This is only meant to determine the MIME type of a renderable image file.
// It is used to ensure images drawn from a URL that have transparent backgrounds
// are rendered correctly, among other things.
function determineMimeOfFileName(nameWithPath) {
/*jshint -W015 */
var pathSegments = nameWithPath.split("/"),
name = pathSegments[pathSegments.length - 1],
extension = qq.getExtension(name);
extension = extension && extension.toLowerCase();
switch (extension) {
case "jpeg":
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "bmp":
return "image/bmp";
case "gif":
return "image/gif";
case "tiff":
case "tif":
return "image/tiff";
}
}
// This will likely not work correctly in IE8 and older.
// It's only used as part of a formula to determine
// if a canvas can be used to scale a server-hosted thumbnail.
// If canvas isn't supported by the UA (IE8 and older)
// this method should not even be called.
function isCrossOrigin(url) {
var targetAnchor = document.createElement("a"),
targetProtocol, targetHostname, targetPort;
targetAnchor.href = url;
targetProtocol = targetAnchor.protocol;
targetPort = targetAnchor.port;
targetHostname = targetAnchor.hostname;
if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) {
return true;
}
if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) {
return true;
}
// IE doesn't take ports into consideration when determining if two endpoints are same origin.
if (targetPort !== window.location.port && !qq.ie()) {
return true;
}
return false;
}
function registerImgLoadListeners(img, promise) {
img.onload = function() {
img.onload = null;
img.onerror = null;
promise.success(img);
};
img.onerror = function() {
img.onload = null;
img.onerror = null;
log("Problem drawing thumbnail!", "error");
promise.failure(img, "Problem drawing thumbnail!");
};
}
function registerCanvasDrawImageListener(canvas, promise) {
// The image is drawn on the canvas by a third-party library,
// and we want to know when this is completed. Since the library
// may invoke drawImage many times in a loop, we need to be called
// back when the image is fully rendered. So, we are expecting the
// code that draws this image to follow a convention that involves a
// function attached to the canvas instance be invoked when it is done.
canvas.qqImageRendered = function() {
promise.success(canvas);
};
}
// Fulfills a `qq.Promise` when an image has been drawn onto the target,
// whether that is a <canvas> or an <img>. The attempt is considered a
// failure if the target is not an <img> or a <canvas>, or if the drawing
// attempt was not successful.
function registerThumbnailRenderedListener(imgOrCanvas, promise) {
var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas);
if (isImg(imgOrCanvas)) {
registerImgLoadListeners(imgOrCanvas, promise);
}
else if (isCanvas(imgOrCanvas)) {
registerCanvasDrawImageListener(imgOrCanvas, promise);
}
else {
promise.failure(imgOrCanvas);
log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error");
}
return registered;
}
// Draw a preview iff the current UA can natively display it.
// Also rotate the image if necessary.
function draw(fileOrBlob, container, options) {
var drawPreview = new qq.Promise(),
identifier = new qq.Identify(fileOrBlob, log),
maxSize = options.maxSize,
// jshint eqnull:true
orient = options.orient == null ? true : options.orient,
megapixErrorHandler = function() {
container.onerror = null;
container.onload = null;
log("Could not render preview, file may be too large!", "error");
drawPreview.failure(container, "Browser cannot render image!");
};
identifier.isPreviewable().then(
function(mime) {
// If options explicitly specify that Orientation is not desired,
// replace the orient task with a dummy promise that "succeeds" immediately.
var dummyExif = {
parse: function() {
return new qq.Promise().success();
}
},
exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif,
mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler);
if (registerThumbnailRenderedListener(container, drawPreview)) {
exif.parse().then(
function(exif) {
var orientation = exif && exif.Orientation;
mpImg.render(container, {
maxWidth: maxSize,
maxHeight: maxSize,
orientation: orientation,
mime: mime
});
},
function(failureMsg) {
log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg));
mpImg.render(container, {
maxWidth: maxSize,
maxHeight: maxSize,
mime: mime
});
}
);
}
},
function() {
log("Not previewable");
drawPreview.failure(container, "Not previewable");
}
);
return drawPreview;
}
function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize) {
var tempImg = new Image(),
tempImgRender = new qq.Promise();
registerThumbnailRenderedListener(tempImg, tempImgRender);
if (isCrossOrigin(url)) {
tempImg.crossOrigin = "anonymous";
}
tempImg.src = url;
tempImgRender.then(
function rendered() {
registerThumbnailRenderedListener(canvasOrImg, draw);
var mpImg = new qq.MegaPixImage(tempImg);
mpImg.render(canvasOrImg, {
maxWidth: maxSize,
maxHeight: maxSize,
mime: determineMimeOfFileName(url)
});
},
draw.failure
);
}
function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) {
registerThumbnailRenderedListener(img, draw);
// NOTE: The fact that maxWidth/height is set on the thumbnail for scaled images
// that must drop back to CSS is known and exploited by the templating module.
// In this module, we pre-render "waiting" thumbs for all files immediately after they
// are submitted, and we must be sure to pass any style associated with the "waiting" preview.
qq(img).css({
maxWidth: maxSize + "px",
maxHeight: maxSize + "px"
});
img.src = url;
}
// Draw a (server-hosted) thumbnail given a URL.
// This will optionally scale the thumbnail as well.
// It attempts to use <canvas> to scale, but will fall back
// to max-width and max-height style properties if the UA
// doesn't support canvas or if the images is cross-domain and
// the UA doesn't support the crossorigin attribute on img tags,
// which is required to scale a cross-origin image using <canvas> &
// then export it back to an <img>.
function drawFromUrl(url, container, options) {
var draw = new qq.Promise(),
scale = options.scale,
maxSize = scale ? options.maxSize : null;
// container is an img, scaling needed
if (scale && isImg(container)) {
// Iff canvas is available in this UA, try to use it for scaling.
// Otherwise, fall back to CSS scaling
if (isCanvasSupported()) {
// Attempt to use <canvas> for image scaling,
// but we must fall back to scaling via CSS/styles
// if this is a cross-origin image and the UA doesn't support <img> CORS.
if (isCrossOrigin(url) && !isImgCorsSupported()) {
drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
}
else {
drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
}
}
else {
drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
}
}
// container is a canvas, scaling optional
else if (isCanvas(container)) {
drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
}
// container is an img & no scaling: just set the src attr to the passed url
else if (registerThumbnailRenderedListener(container, draw)) {
container.src = url;
}
return draw;
}
qq.extend(this, {
/**
* Generate a thumbnail. Depending on the arguments, this may either result in
* a client-side rendering of an image (if a `Blob` is supplied) or a server-generated
* image that may optionally be scaled client-side using <canvas> or CSS/styles (as a fallback).
*
* @param fileBlobOrUrl a `File`, `Blob`, or a URL pointing to the image
* @param container <img> or <canvas> to contain the preview
* @param options possible properties include `maxSize` (int), `orient` (bool - default true), and `resize` (bool - default true)
* @returns qq.Promise fulfilled when the preview has been drawn, or the attempt has failed
*/
generate: function(fileBlobOrUrl, container, options) {
if (qq.isString(fileBlobOrUrl)) {
log("Attempting to update thumbnail based on server response.");
return drawFromUrl(fileBlobOrUrl, container, options || {});
}
else {
log("Attempting to draw client-side image preview.");
return draw(fileBlobOrUrl, container, options || {});
}
}
});
};
/*globals qq */
/**
* EXIF image data parser. Currently only parses the Orientation tag value,
* but this may be expanded to other tags in the future.
*
* @param fileOrBlob Attempt to parse EXIF data in this `Blob`
* @constructor
*/
qq.Exif = function(fileOrBlob, log) {
"use strict";
// Orientation is the only tag parsed here at this time.
var TAG_IDS = [274],
TAG_INFO = {
274: {
name: "Orientation",
bytes: 2
}
};
// Convert a little endian (hex string) to big endian (decimal).
function parseLittleEndian(hex) {
var result = 0,
pow = 0;
while (hex.length > 0) {
result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);
hex = hex.substring(2, hex.length);
pow += 8;
}
return result;
}
// Find the byte offset, of Application Segment 1 (EXIF).
// External callers need not supply any arguments.
function seekToApp1(offset, promise) {
var theOffset = offset,
thePromise = promise;
if (theOffset === undefined) {
theOffset = 2;
thePromise = new qq.Promise();
}
qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) {
var match = /^ffe([0-9])/.exec(hex),
segmentLength;
if (match) {
if (match[1] !== "1") {
segmentLength = parseInt(hex.slice(4, 8), 16);
seekToApp1(theOffset + segmentLength + 2, thePromise);
}
else {
thePromise.success(theOffset);
}
}
else {
thePromise.failure("No EXIF header to be found!");
}
});
return thePromise;
}
// Find the byte offset of Application Segment 1 (EXIF) for valid JPEGs only.
function getApp1Offset() {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) {
if (hex.indexOf("ffd8") !== 0) {
promise.failure("Not a valid JPEG!");
}
else {
seekToApp1().then(function(offset) {
promise.success(offset);
},
function(error) {
promise.failure(error);
});
}
});
return promise;
}
// Determine the byte ordering of the EXIF header.
function isLittleEndian(app1Start) {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) {
promise.success(hex === "4949");
});
return promise;
}
// Determine the number of directory entries in the EXIF header.
function getDirEntryCount(app1Start, littleEndian) {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) {
if (littleEndian) {
return promise.success(parseLittleEndian(hex));
}
else {
promise.success(parseInt(hex, 16));
}
});
return promise;
}
// Get the IFD portion of the EXIF header as a hex string.
function getIfd(app1Start, dirEntries) {
var offset = app1Start + 20,
bytes = dirEntries * 12;
return qq.readBlobToHex(fileOrBlob, offset, bytes);
}
// Obtain an array of all directory entries (as hex strings) in the EXIF header.
function getDirEntries(ifdHex) {
var entries = [],
offset = 0;
while (offset + 24 <= ifdHex.length) {
entries.push(ifdHex.slice(offset, offset + 24));
offset += 24;
}
return entries;
}
// Obtain values for all relevant tags and return them.
function getTagValues(littleEndian, dirEntries) {
var TAG_VAL_OFFSET = 16,
tagsToFind = qq.extend([], TAG_IDS),
vals = {};
qq.each(dirEntries, function(idx, entry) {
var idHex = entry.slice(0, 4),
id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16),
tagsToFindIdx = tagsToFind.indexOf(id),
tagValHex, tagName, tagValLength;
if (tagsToFindIdx >= 0) {
tagName = TAG_INFO[id].name;
tagValLength = TAG_INFO[id].bytes;
tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + (tagValLength * 2));
vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16);
tagsToFind.splice(tagsToFindIdx, 1);
}
if (tagsToFind.length === 0) {
return false;
}
});
return vals;
}
qq.extend(this, {
/**
* Attempt to parse the EXIF header for the `Blob` associated with this instance.
*
* @returns {qq.Promise} To be fulfilled when the parsing is complete.
* If successful, the parsed EXIF header as an object will be included.
*/
parse: function() {
var parser = new qq.Promise(),
onParseFailure = function(message) {
log(qq.format("EXIF header parse failed: '{}' ", message));
parser.failure(message);
};
getApp1Offset().then(function(app1Offset) {
log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name));
isLittleEndian(app1Offset).then(function(littleEndian) {
log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big"));
getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) {
log(qq.format("Found {} APP1 directory entries", dirEntryCount));
getIfd(app1Offset, dirEntryCount).then(function(ifdHex) {
var dirEntries = getDirEntries(ifdHex),
tagValues = getTagValues(littleEndian, dirEntries);
log("Successfully parsed some EXIF tags");
parser.success(tagValues);
}, onParseFailure);
}, onParseFailure);
}, onParseFailure);
}, onParseFailure);
return parser;
}
});
};
/*globals qq */
qq.Identify = function(fileOrBlob, log) {
"use strict";
function isIdentifiable(magicBytes, questionableBytes) {
var identifiable = false,
magicBytesEntries = [].concat(magicBytes);
qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {
if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {
identifiable = true;
return false;
}
});
return identifiable;
}
qq.extend(this, {
/**
* Determines if a Blob can be displayed natively in the current browser. This is done by reading magic
* bytes in the beginning of the file, so this is an asynchronous operation. Before we attempt to read the
* file, we will examine the blob's type attribute to save CPU cycles.
*
* @returns {qq.Promise} Promise that is fulfilled when identification is complete.
* If successful, the MIME string is passed to the success handler.
*/
isPreviewable: function() {
var self = this,
idenitifer = new qq.Promise(),
previewable = false,
name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
log(qq.format("Attempting to determine if {} can be rendered in this browser", name));
log("First pass: check type attribute of blob object.");
if (this.isPreviewableSync()) {
log("Second pass: check for magic bytes in file header.");
qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {
qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {
if (isIdentifiable(bytes, hex)) {
// Safari is the only supported browser that can deal with TIFFs natively,
// so, if this is a TIFF and the UA isn't Safari, declare this file "non-previewable".
if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) {
previewable = true;
idenitifer.success(mime);
}
return false;
}
});
log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT"));
if (!previewable) {
idenitifer.failure();
}
},
function() {
log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser.");
idenitifer.failure();
});
}
else {
idenitifer.failure();
}
return idenitifer;
},
/**
* Determines if a Blob can be displayed natively in the current browser. This is done by checking the
* blob's type attribute. This is a synchronous operation, useful for situations where an asynchronous operation
* would be challenging to support. Album that the blob's type property is not as accurate as reading the
* file's magic bytes.
*
* @returns {Boolean} true if the blob can be rendered in the current browser
*/
isPreviewableSync: function() {
var fileMime = fileOrBlob.type,
// Assumption: This will only ever be executed in browsers that support `Object.keys`.
isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0,
previewable = false,
name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
if (isRecognizedImage) {
if (fileMime === "image/tiff") {
previewable = qq.supportedFeatures.tiffPreviews;
}
else {
previewable = true;
}
}
!previewable && log(name + " is not previewable in this browser per the blob's type attr");
return previewable;
}
});
};
qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {
"image/jpeg": "ffd8ff",
"image/gif": "474946",
"image/png": "89504e",
"image/bmp": "424d",
"image/tiff": ["49492a00", "4d4d002a"]
};
/*globals qq*/
/**
* Attempts to validate an image, wherever possible.
*
* @param blob File or Blob representing a user-selecting image.
* @param log Uses this to post log messages to the console.
* @constructor
*/
qq.ImageValidation = function(blob, log) {
"use strict";
/**
* @param limits Object with possible image-related limits to enforce.
* @returns {boolean} true if at least one of the limits has a non-zero value
*/
function hasNonZeroLimits(limits) {
var atLeastOne = false;
qq.each(limits, function(limit, value) {
if (value > 0) {
atLeastOne = true;
return false;
}
});
return atLeastOne;
}
/**
* @returns {qq.Promise} The promise is a failure if we can't obtain the width & height.
* Otherwise, `success` is called on the returned promise with an object containing
* `width` and `height` properties.
*/
function getWidthHeight() {
var sizeDetermination = new qq.Promise();
new qq.Identify(blob, log).isPreviewable().then(function() {
var image = new Image(),
url = window.URL && window.URL.createObjectURL ? window.URL :
window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL :
null;
if (url) {
image.onerror = function() {
log("Cannot determine dimensions for image. May be too large.", "error");
sizeDetermination.failure();
};
image.onload = function() {
sizeDetermination.success({
width: this.width,
height: this.height
});
};
image.src = url.createObjectURL(blob);
}
else {
log("No createObjectURL function available to generate image URL!", "error");
sizeDetermination.failure();
}
}, sizeDetermination.failure);
return sizeDetermination;
}
/**
*
* @param limits Object with possible image-related limits to enforce.
* @param dimensions Object containing `width` & `height` properties for the image to test.
* @returns {String || undefined} The name of the failing limit. Undefined if no failing limits.
*/
function getFailingLimit(limits, dimensions) {
var failingLimit;
qq.each(limits, function(limitName, limitValue) {
if (limitValue > 0) {
var limitMatcher = /(max|min)(Width|Height)/.exec(limitName),
dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1),
actualValue = dimensions[dimensionPropName];
/*jshint -W015*/
switch (limitMatcher[1]) {
case "min":
if (actualValue < limitValue) {
failingLimit = limitName;
return false;
}
break;
case "max":
if (actualValue > limitValue) {
failingLimit = limitName;
return false;
}
break;
}
}
});
return failingLimit;
}
/**
* Validate the associated blob.
*
* @param limits
* @returns {qq.Promise} `success` is called on the promise is the image is valid or
* if the blob is not an image, or if the image is not verifiable.
* Otherwise, `failure` with the name of the failing limit.
*/
this.validate = function(limits) {
var validationEffort = new qq.Promise();
log("Attempting to validate image.");
if (hasNonZeroLimits(limits)) {
getWidthHeight().then(function(dimensions) {
var failingLimit = getFailingLimit(limits, dimensions);
if (failingLimit) {
validationEffort.failure(failingLimit);
}
else {
validationEffort.success();
}
}, validationEffort.success);
}
else {
validationEffort.success();
}
return validationEffort;
};
};
/* globals qq */
/**
* Module used to control populating the initial list of files.
*
* @constructor
*/
qq.Session = function(spec) {
"use strict";
var options = {
endpoint: null,
params: {},
customHeaders: {},
cors: {},
addFileRecord: function(sessionData) {},
log: function(message, level) {}
};
qq.extend(options, spec, true);
function isJsonResponseValid(response) {
if (qq.isArray(response)) {
return true;
}
options.log("Session response is not an array.", "error");
}
function handleFileItems(fileItems, success, xhrOrXdr, promise) {
var someItemsIgnored = false;
success = success && isJsonResponseValid(fileItems);
if (success) {
qq.each(fileItems, function(idx, fileItem) {
/* jshint eqnull:true */
if (fileItem.uuid == null) {
someItemsIgnored = true;
options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error");
}
else if (fileItem.name == null) {
someItemsIgnored = true;
options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error");
}
else {
try {
options.addFileRecord(fileItem);
return true;
}
catch (err) {
someItemsIgnored = true;
options.log(err.message, "error");
}
}
return false;
});
}
promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr);
}
// Initiate a call to the server that will be used to populate the initial file list.
// Returns a `qq.Promise`.
this.refresh = function() {
/*jshint indent:false */
var refreshEffort = new qq.Promise(),
refreshCompleteCallback = function(response, success, xhrOrXdr) {
handleFileItems(response, success, xhrOrXdr, refreshEffort);
},
requsterOptions = qq.extend({}, options),
requester = new qq.SessionAjaxRequester(
qq.extend(requsterOptions, {onComplete: refreshCompleteCallback})
);
requester.queryServer();
return refreshEffort;
};
};
/*globals qq, XMLHttpRequest*/
/**
* Thin module used to send GET requests to the server, expecting information about session
* data used to initialize an uploader instance.
*
* @param spec Various options used to influence the associated request.
* @constructor
*/
qq.SessionAjaxRequester = function(spec) {
"use strict";
var requester,
options = {
endpoint: null,
customHeaders: {},
params: {},
cors: {
expected: false,
sendCredentials: false
},
onComplete: function(response, success, xhrOrXdr) {},
log: function(str, level) {}
};
qq.extend(options, spec);
function onComplete(id, xhrOrXdr, isError) {
var response = null;
/* jshint eqnull:true */
if (xhrOrXdr.responseText != null) {
try {
response = qq.parseJson(xhrOrXdr.responseText);
}
catch (err) {
options.log("Problem parsing session response: " + err.message, "error");
isError = true;
}
}
options.onComplete(response, !isError, xhrOrXdr);
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: ["GET"],
method: "GET",
endpointStore: {
get: function() {
return options.endpoint;
}
},
customHeaders: options.customHeaders,
log: options.log,
onComplete: onComplete,
cors: options.cors
}));
qq.extend(this, {
queryServer: function() {
var params = qq.extend({}, options.params);
options.log("Session query request.");
requester.initTransport("sessionRefresh")
.withParams(params)
.withCacheBuster()
.send();
}
});
};
/* globals qq */
/**
* Module that handles support for existing forms.
*
* @param options Options passed from the integrator-supplied options related to form support.
* @param startUpload Callback to invoke when files "stored" should be uploaded.
* @param log Proxy for the logger
* @constructor
*/
qq.FormSupport = function(options, startUpload, log) {
"use strict";
var self = this,
interceptSubmit = options.interceptSubmit,
formEl = options.element,
autoUpload = options.autoUpload;
// Available on the public API associated with this module.
qq.extend(this, {
// To be used by the caller to determine if the endpoint will be determined by some processing
// that occurs in this module, such as if the form has an action attribute.
// Ignore if `attachToForm === false`.
newEndpoint: null,
// To be used by the caller to determine if auto uploading should be allowed.
// Ignore if `attachToForm === false`.
newAutoUpload: autoUpload,
// true if a form was detected and is being tracked by this module
attachedToForm: false,
// Returns an object with names and values for all valid form elements associated with the attached form.
getFormInputsAsObject: function() {
/* jshint eqnull:true */
if (formEl == null) {
return null;
}
return self._form2Obj(formEl);
}
});
// If the form contains an action attribute, this should be the new upload endpoint.
function determineNewEndpoint(formEl) {
if (formEl.getAttribute("action")) {
self.newEndpoint = formEl.getAttribute("action");
}
}
// Return true only if the form is valid, or if we cannot make this determination.
// If the form is invalid, ensure invalid field(s) are highlighted in the UI.
function validateForm(formEl, nativeSubmit) {
if (formEl.checkValidity && !formEl.checkValidity()) {
log("Form did not pass validation checks - will not upload.", "error");
nativeSubmit();
}
else {
return true;
}
}
// Intercept form submit attempts, unless the integrator has told us not to do this.
function maybeUploadOnSubmit(formEl) {
var nativeSubmit = formEl.submit;
// Intercept and squelch submit events.
qq(formEl).attach("submit", function(event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
validateForm(formEl, nativeSubmit) && startUpload();
});
// The form's `submit()` function may be called instead (i.e. via jQuery.submit()).
// Intercept that too.
formEl.submit = function() {
validateForm(formEl, nativeSubmit) && startUpload();
};
}
// If the element value passed from the uploader is a string, assume it is an element ID - select it.
// The rest of the code in this module depends on this being an HTMLElement.
function determineFormEl(formEl) {
if (formEl) {
if (qq.isString(formEl)) {
formEl = document.getElementById(formEl);
}
if (formEl) {
log("Attaching to form element.");
determineNewEndpoint(formEl);
interceptSubmit && maybeUploadOnSubmit(formEl);
}
}
return formEl;
}
formEl = determineFormEl(formEl);
this.attachedToForm = !!formEl;
};
qq.extend(qq.FormSupport.prototype, {
// Converts all relevant form fields to key/value pairs. This is meant to mimic the data a browser will
// construct from a given form when the form is submitted.
_form2Obj: function(form) {
"use strict";
var obj = {},
notIrrelevantType = function(type) {
var irrelevantTypes = [
"button",
"image",
"reset",
"submit"
];
return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0;
},
radioOrCheckbox = function(type) {
return qq.indexOf(["checkbox", "radio"], type.toLowerCase()) >= 0;
},
ignoreValue = function(el) {
if (radioOrCheckbox(el.type) && !el.checked) {
return true;
}
return el.disabled && el.type.toLowerCase() !== "hidden";
},
selectValue = function(select) {
var value = null;
qq.each(qq(select).children(), function(idx, child) {
if (child.tagName.toLowerCase() === "option" && child.selected) {
value = child.value;
return false;
}
});
return value;
};
qq.each(form.elements, function(idx, el) {
if ((qq.isInput(el, true) || el.tagName.toLowerCase() === "textarea") &&
notIrrelevantType(el.type) &&
!ignoreValue(el)) {
obj[el.name] = el.value;
}
else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) {
var value = selectValue(el);
if (value !== null) {
obj[el.name] = value;
}
}
});
return obj;
}
});
/* globals qq, ExifRestorer */
/**
* Controls generation of scaled images based on a reference image encapsulated in a `File` or `Blob`.
* Scaled images are generated and converted to blobs on-demand.
* Multiple scaled images per reference image with varying sizes and other properties are supported.
*
* @param spec Information about the scaled images to generate.
* @param log Logger instance
* @constructor
*/
qq.Scaler = function(spec, log) {
"use strict";
var self = this,
includeReference = spec.sendOriginal,
orient = spec.orient,
defaultType = spec.defaultType,
defaultQuality = spec.defaultQuality / 100,
failedToScaleText = spec.failureText,
includeExif = spec.includeExif,
sizes = this._getSortedSizes(spec.sizes);
// Revealed API for instances of this module
qq.extend(this, {
// If no targeted sizes have been declared or if this browser doesn't support
// client-side image preview generation, there is no scaling to do.
enabled: qq.supportedFeatures.scaling && sizes.length > 0,
getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {
var self = this,
records = [],
originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData,
idenitifier = new qq.Identify(originalBlob, log);
// If the reference file cannot be rendered natively, we can't create scaled versions.
if (idenitifier.isPreviewableSync()) {
// Create records for each scaled version & add them to the records array, smallest first.
qq.each(sizes, function(idx, sizeRecord) {
var outputType = self._determineOutputType({
defaultType: defaultType,
requestedType: sizeRecord.type,
refType: originalBlob.type
});
records.push({
uuid: qq.getUniqueId(),
name: self._getName(originalFileName, {
name: sizeRecord.name,
type: outputType,
refType: originalBlob.type
}),
blob: new qq.BlobProxy(originalBlob,
qq.bind(self._generateScaledImage, self, {
maxSize: sizeRecord.maxSize,
orient: orient,
type: outputType,
quality: defaultQuality,
failedText: failedToScaleText,
includeExif: includeExif,
log: log
}))
});
});
includeReference && records.push({
uuid: originalFileUuid,
name: originalFileName,
blob: originalBlob
});
}
else {
records.push({
uuid: originalFileUuid,
name: originalFileName,
blob: originalBlob
});
}
return records;
},
handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) {
var self = this,
buttonId = file.qqButtonId || (file.blob && file.blob.qqButtonId),
scaledIds = [],
originalId = null,
addFileToHandler = api.addFileToHandler,
uploadData = api.uploadData,
paramsStore = api.paramsStore,
proxyGroupId = qq.getUniqueId();
qq.each(self.getFileRecords(uuid, name, file), function(idx, record) {
var relatedBlob = file,
relatedSize = size,
id;
if (record.blob instanceof qq.BlobProxy) {
relatedBlob = record.blob;
relatedSize = -1;
}
id = uploadData.addFile({
uuid: record.uuid,
name: record.name,
size: relatedSize,
batchId: batchId,
proxyGroupId: proxyGroupId
});
if (record.blob instanceof qq.BlobProxy) {
scaledIds.push(id);
}
else {
originalId = id;
}
addFileToHandler(id, relatedBlob);
fileList.push({id: id, file: relatedBlob});
});
// If we are potentially uploading an original file and some scaled versions,
// ensure the scaled versions include reference's to the parent's UUID and size
// in their associated upload requests.
if (originalId !== null) {
qq.each(scaledIds, function(idx, scaledId) {
var params = {
qqparentuuid: uploadData.retrieve({id: originalId}).uuid,
qqparentsize: uploadData.retrieve({id: originalId}).size
};
// Make SURE the UUID for each scaled image is sent with the upload request,
// to be consistent (since we need to ensure it is sent for the original file as well).
params[uuidParamName] = uploadData.retrieve({id: scaledId}).uuid;
uploadData.setParentId(scaledId, originalId);
paramsStore.addReadOnly(scaledId, params);
});
// If any scaled images are tied to this parent image, be SURE we send its UUID as an upload request
// parameter as well.
if (scaledIds.length) {
(function() {
var param = {};
param[uuidParamName] = uploadData.retrieve({id: originalId}).uuid;
paramsStore.addReadOnly(originalId, param);
}());
}
}
}
});
};
qq.extend(qq.Scaler.prototype, {
scaleImage: function(id, specs, api) {
"use strict";
if (!qq.supportedFeatures.scaling) {
throw new qq.Error("Scaling is not supported in this browser!");
}
var scalingEffort = new qq.Promise(),
log = api.log,
file = api.getFile(id),
uploadData = api.uploadData.retrieve({id: id}),
name = uploadData && uploadData.name,
uuid = uploadData && uploadData.uuid,
scalingOptions = {
sendOriginal: false,
orient: specs.orient,
defaultType: specs.type || null,
defaultQuality: specs.quality,
failedToScaleText: "Unable to scale",
sizes: [{name: "", maxSize: specs.maxSize}]
},
scaler = new qq.Scaler(scalingOptions, log);
if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) {
scalingEffort.failure();
log("Could not generate requested scaled image for " + id + ". " +
"Scaling is either not possible in this browser, or the file could not be located.", "error");
}
else {
(qq.bind(function() {
// Assumption: There will never be more than one record
var record = scaler.getFileRecords(uuid, name, file)[0];
if (record && record.blob instanceof qq.BlobProxy) {
record.blob.create().then(scalingEffort.success, scalingEffort.failure);
}
else {
log(id + " is not a scalable image!", "error");
scalingEffort.failure();
}
}, this)());
}
return scalingEffort;
},
// NOTE: We cannot reliably determine at this time if the UA supports a specific MIME type for the target format.
// image/jpeg and image/png are the only safe choices at this time.
_determineOutputType: function(spec) {
"use strict";
var requestedType = spec.requestedType,
defaultType = spec.defaultType,
referenceType = spec.refType;
// If a default type and requested type have not been specified, this should be a
// JPEG if the original type is a JPEG, otherwise, a PNG.
if (!defaultType && !requestedType) {
if (referenceType !== "image/jpeg") {
return "image/png";
}
return referenceType;
}
// A specified default type is used when a requested type is not specified.
if (!requestedType) {
return defaultType;
}
// If requested type is specified, use it, as long as this recognized type is supported by the current UA
if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {
if (requestedType === "image/tiff") {
return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;
}
return requestedType;
}
return defaultType;
},
// Get a file name for a generated scaled file record, based on the provided scaled image description
_getName: function(originalName, scaledVersionProperties) {
"use strict";
var startOfExt = originalName.lastIndexOf("."),
versionType = scaledVersionProperties.type || "image/png",
referenceType = scaledVersionProperties.refType,
scaledName = "",
scaledExt = qq.getExtension(originalName),
nameAppendage = "";
if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) {
nameAppendage = " (" + scaledVersionProperties.name + ")";
}
if (startOfExt >= 0) {
scaledName = originalName.substr(0, startOfExt);
if (referenceType !== versionType) {
scaledExt = versionType.split("/")[1];
}
scaledName += nameAppendage + "." + scaledExt;
}
else {
scaledName = originalName + nameAppendage;
}
return scaledName;
},
// We want the smallest scaled file to be uploaded first
_getSortedSizes: function(sizes) {
"use strict";
sizes = qq.extend([], sizes);
return sizes.sort(function(a, b) {
if (a.maxSize > b.maxSize) {
return 1;
}
if (a.maxSize < b.maxSize) {
return -1;
}
return 0;
});
},
_generateScaledImage: function(spec, sourceFile) {
"use strict";
var self = this,
log = spec.log,
maxSize = spec.maxSize,
orient = spec.orient,
type = spec.type,
quality = spec.quality,
failedText = spec.failedText,
includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg",
scalingEffort = new qq.Promise(),
imageGenerator = new qq.ImageGenerator(log),
canvas = document.createElement("canvas");
log("Attempting to generate scaled version for " + sourceFile.name);
imageGenerator.generate(sourceFile, canvas, {maxSize: maxSize, orient: orient}).then(function() {
var scaledImageDataUri = canvas.toDataURL(type, quality),
signalSuccess = function() {
log("Success generating scaled version for " + sourceFile.name);
var blob = qq.dataUriToBlob(scaledImageDataUri);
scalingEffort.success(blob);
};
if (includeExif) {
self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) {
scaledImageDataUri = scaledImageDataUriWithExif;
signalSuccess();
},
function() {
log("Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.", "error");
signalSuccess();
});
}
else {
signalSuccess();
}
}, function() {
log("Failed attempt to generate scaled version for " + sourceFile.name, "error");
scalingEffort.failure(failedText);
});
return scalingEffort;
},
// Attempt to insert the original image's EXIF header into a scaled version.
_insertExifHeader: function(originalImage, scaledImageDataUri, log) {
"use strict";
var reader = new FileReader(),
insertionEffort = new qq.Promise(),
originalImageDataUri = "";
reader.onload = function() {
originalImageDataUri = reader.result;
insertionEffort.success(ExifRestorer.restore(originalImageDataUri, scaledImageDataUri));
};
reader.onerror = function() {
log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error");
insertionEffort.failure();
};
reader.readAsDataURL(originalImage);
return insertionEffort;
},
_dataUriToBlob: function(dataUri) {
"use strict";
var byteString, mimeString, arrayBuffer, intArray;
// convert base64 to raw binary data held in a string
if (dataUri.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataUri.split(",")[1]);
}
else {
byteString = decodeURI(dataUri.split(",")[1]);
}
// extract the MIME
mimeString = dataUri.split(",")[0]
.split(":")[1]
.split(";")[0];
// write the bytes of the binary string to an ArrayBuffer
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
qq.each(byteString, function(idx, character) {
intArray[idx] = character.charCodeAt(0);
});
return this._createBlob(arrayBuffer, mimeString);
},
_createBlob: function(data, mime) {
"use strict";
var BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder,
blobBuilder = BlobBuilder && new BlobBuilder();
if (blobBuilder) {
blobBuilder.append(data);
return blobBuilder.getBlob(mime);
}
else {
return new Blob([data], {type: mime});
}
}
});
//Based on MinifyJpeg
//http://elicon.blog57.fc2.com/blog-entry-206.html
var ExifRestorer = (function()
{
var ExifRestorer = {};
ExifRestorer.KEY_STR = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";
ExifRestorer.encode64 = function(input)
{
var output = "",
chr1, chr2, chr3 = "",
enc1, enc2, enc3, enc4 = "",
i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this.KEY_STR.charAt(enc1) +
this.KEY_STR.charAt(enc2) +
this.KEY_STR.charAt(enc3) +
this.KEY_STR.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
};
ExifRestorer.restore = function(origFileBase64, resizedFileBase64)
{
var expectedBase64Header = "data:image/jpeg;base64,";
if (!origFileBase64.match(expectedBase64Header))
{
return resizedFileBase64;
}
var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, ""));
var segments = this.slice2Segments(rawImage);
var image = this.exifManipulation(resizedFileBase64, segments);
return expectedBase64Header + this.encode64(image);
};
ExifRestorer.exifManipulation = function(resizedFileBase64, segments)
{
var exifArray = this.getExifArray(segments),
newImageArray = this.insertExif(resizedFileBase64, exifArray),
aBuffer = new Uint8Array(newImageArray);
return aBuffer;
};
ExifRestorer.getExifArray = function(segments)
{
var seg;
for (var x = 0; x < segments.length; x++)
{
seg = segments[x];
if (seg[0] == 255 & seg[1] == 225) //(ff e1)
{
return seg;
}
}
return [];
};
ExifRestorer.insertExif = function(resizedFileBase64, exifArray)
{
var imageData = resizedFileBase64.replace("data:image/jpeg;base64,", ""),
buf = this.decode64(imageData),
separatePoint = buf.indexOf(255,3),
mae = buf.slice(0, separatePoint),
ato = buf.slice(separatePoint),
array = mae;
array = array.concat(exifArray);
array = array.concat(ato);
return array;
};
ExifRestorer.slice2Segments = function(rawImageArray)
{
var head = 0,
segments = [];
while (1)
{
if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218){break;}
if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216)
{
head += 2;
}
else
{
var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3],
endPoint = head + length + 2,
seg = rawImageArray.slice(head, endPoint);
segments.push(seg);
head = endPoint;
}
if (head > rawImageArray.length){break;}
}
return segments;
};
ExifRestorer.decode64 = function(input)
{
var output = "",
chr1, chr2, chr3 = "",
enc1, enc2, enc3, enc4 = "",
i = 0,
buf = [];
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
throw new Error("There were invalid base64 characters in the input text. " +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = this.KEY_STR.indexOf(input.charAt(i++));
enc2 = this.KEY_STR.indexOf(input.charAt(i++));
enc3 = this.KEY_STR.indexOf(input.charAt(i++));
enc4 = this.KEY_STR.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
buf.push(chr1);
if (enc3 != 64) {
buf.push(chr2);
}
if (enc4 != 64) {
buf.push(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return buf;
};
return ExifRestorer;
})();
/* globals qq */
/**
* Keeps a running tally of total upload progress for a batch of files.
*
* @param callback Invoked when total progress changes, passing calculated total loaded & total size values.
* @param getSize Function that returns the size of a file given its ID
* @constructor
*/
qq.TotalProgress = function(callback, getSize) {
"use strict";
var perFileProgress = {},
totalLoaded = 0,
totalSize = 0,
lastLoadedSent = -1,
lastTotalSent = -1,
callbackProxy = function(loaded, total) {
if (loaded !== lastLoadedSent || total !== lastTotalSent) {
callback(loaded, total);
}
lastLoadedSent = loaded;
lastTotalSent = total;
},
/**
* @param failed Array of file IDs that have failed
* @param retryable Array of file IDs that are retryable
* @returns true if none of the failed files are eligible for retry
*/
noRetryableFiles = function(failed, retryable) {
var none = true;
qq.each(failed, function(idx, failedId) {
if (qq.indexOf(retryable, failedId) >= 0) {
none = false;
return false;
}
});
return none;
},
onCancel = function(id) {
updateTotalProgress(id, -1, -1);
delete perFileProgress[id];
},
onAllComplete = function(successful, failed, retryable) {
if (failed.length === 0 || noRetryableFiles(failed, retryable)) {
callbackProxy(totalSize, totalSize);
this.reset();
}
},
onNew = function(id) {
var size = getSize(id);
// We might not know the size yet, such as for blob proxies
if (size > 0) {
updateTotalProgress(id, 0, size);
perFileProgress[id] = {loaded: 0, total: size};
}
},
/**
* Invokes the callback with the current total progress of all files in the batch. Called whenever it may
* be appropriate to re-calculate and dissemenate this data.
*
* @param id ID of a file that has changed in some important way
* @param newLoaded New loaded value for this file. -1 if this value should no longer be part of calculations
* @param newTotal New total size of the file. -1 if this value should no longer be part of calculations
*/
updateTotalProgress = function(id, newLoaded, newTotal) {
var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0,
oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0;
if (newLoaded === -1 && newTotal === -1) {
totalLoaded -= oldLoaded;
totalSize -= oldTotal;
}
else {
if (newLoaded) {
totalLoaded += newLoaded - oldLoaded;
}
if (newTotal) {
totalSize += newTotal - oldTotal;
}
}
callbackProxy(totalLoaded, totalSize);
};
qq.extend(this, {
// Called when a batch of files has completed uploading.
onAllComplete: onAllComplete,
// Called when the status of a file has changed.
onStatusChange: function(id, oldStatus, newStatus) {
if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) {
onCancel(id);
}
else if (newStatus === qq.status.SUBMITTING) {
onNew(id);
}
},
// Called whenever the upload progress of an individual file has changed.
onIndividualProgress: function(id, loaded, total) {
updateTotalProgress(id, loaded, total);
perFileProgress[id] = {loaded: loaded, total: total};
},
// Called whenever the total size of a file has changed, such as when the size of a generated blob is known.
onNewSize: function(id) {
onNew(id);
},
reset: function() {
perFileProgress = {};
totalLoaded = 0;
totalSize = 0;
}
});
};
/*globals qq */
// Base handler for UI (FineUploader mode) events.
// Some more specific handlers inherit from this one.
qq.UiEventHandler = function(s, protectedApi) {
"use strict";
var disposer = new qq.DisposeSupport(),
spec = {
eventType: "click",
attachTo: null,
onHandled: function(target, event) {}
};
// This makes up the "public" API methods that will be accessible
// to instances constructing a base or child handler
qq.extend(this, {
addHandler: function(element) {
addHandler(element);
},
dispose: function() {
disposer.dispose();
}
});
function addHandler(element) {
disposer.attach(element, spec.eventType, function(event) {
// Only in IE: the `event` is a property of the `window`.
event = event || window.event;
// On older browsers, we must check the `srcElement` instead of the `target`.
var target = event.target || event.srcElement;
spec.onHandled(target, event);
});
}
// These make up the "protected" API methods that children of this base handler will utilize.
qq.extend(protectedApi, {
getFileIdFromItem: function(item) {
return item.qqFileId;
},
getDisposeSupport: function() {
return disposer;
}
});
qq.extend(spec, s);
if (spec.attachTo) {
addHandler(spec.attachTo);
}
};
/* global qq */
qq.FileButtonsClickHandler = function(s) {
"use strict";
var inheritedInternalApi = {},
spec = {
templating: null,
log: function(message, lvl) {},
onDeleteFile: function(fileId) {},
onCancel: function(fileId) {},
onRetry: function(fileId) {},
onPause: function(fileId) {},
onContinue: function(fileId) {},
onGetName: function(fileId) {}
},
buttonHandlers = {
cancel: function(id) { spec.onCancel(id); },
retry: function(id) { spec.onRetry(id); },
deleteButton: function(id) { spec.onDeleteFile(id); },
pause: function(id) { spec.onPause(id); },
continueButton: function(id) { spec.onContinue(id); }
};
function examineEvent(target, event) {
qq.each(buttonHandlers, function(buttonType, handler) {
var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1),
fileId;
if (spec.templating["is" + firstLetterCapButtonType](target)) {
fileId = spec.templating.getFileId(target);
qq.preventDefault(event);
spec.log(qq.format("Detected valid file button click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
handler(fileId);
return false;
}
});
}
qq.extend(spec, s);
spec.eventType = "click";
spec.onHandled = examineEvent;
spec.attachTo = spec.templating.getFileList();
qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));
};
/*globals qq */
// Child of FilenameEditHandler. Used to detect click events on filename display elements.
qq.FilenameClickHandler = function(s) {
"use strict";
var inheritedInternalApi = {},
spec = {
templating: null,
log: function(message, lvl) {},
classes: {
file: "qq-upload-file",
editNameIcon: "qq-edit-filename-icon"
},
onGetUploadStatus: function(fileId) {},
onGetName: function(fileId) {}
};
qq.extend(spec, s);
// This will be called by the parent handler when a `click` event is received on the list element.
function examineEvent(target, event) {
if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) {
var fileId = spec.templating.getFileId(target),
status = spec.onGetUploadStatus(fileId);
// We only allow users to change filenames of files that have been submitted but not yet uploaded.
if (status === qq.status.SUBMITTED) {
spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
qq.preventDefault(event);
inheritedInternalApi.handleFilenameEdit(fileId, target, true);
}
}
}
spec.eventType = "click";
spec.onHandled = examineEvent;
qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));
};
/*globals qq */
// Child of FilenameEditHandler. Used to detect focusin events on file edit input elements.
qq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) {
"use strict";
var spec = {
templating: null,
onGetUploadStatus: function(fileId) {},
log: function(message, lvl) {}
};
if (!inheritedInternalApi) {
inheritedInternalApi = {};
}
// This will be called by the parent handler when a `focusin` event is received on the list element.
function handleInputFocus(target, event) {
if (spec.templating.isEditInput(target)) {
var fileId = spec.templating.getFileId(target),
status = spec.onGetUploadStatus(fileId);
if (status === qq.status.SUBMITTED) {
spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
inheritedInternalApi.handleFilenameEdit(fileId, target);
}
}
}
spec.eventType = "focusin";
spec.onHandled = handleInputFocus;
qq.extend(spec, s);
qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));
};
/*globals qq */
/**
* Child of FilenameInputFocusInHandler. Used to detect focus events on file edit input elements. This child module is only
* needed for UAs that do not support the focusin event. Currently, only Firefox lacks this event.
*
* @param spec Overrides for default specifications
*/
qq.FilenameInputFocusHandler = function(spec) {
"use strict";
spec.eventType = "focus";
spec.attachTo = null;
qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {}));
};
/*globals qq */
// Handles edit-related events on a file item (FineUploader mode). This is meant to be a parent handler.
// Children will delegate to this handler when specific edit-related actions are detected.
qq.FilenameEditHandler = function(s, inheritedInternalApi) {
"use strict";
var spec = {
templating: null,
log: function(message, lvl) {},
onGetUploadStatus: function(fileId) {},
onGetName: function(fileId) {},
onSetName: function(fileId, newName) {},
onEditingStatusChange: function(fileId, isEditing) {}
};
function getFilenameSansExtension(fileId) {
var filenameSansExt = spec.onGetName(fileId),
extIdx = filenameSansExt.lastIndexOf(".");
if (extIdx > 0) {
filenameSansExt = filenameSansExt.substr(0, extIdx);
}
return filenameSansExt;
}
function getOriginalExtension(fileId) {
var origName = spec.onGetName(fileId);
return qq.getExtension(origName);
}
// Callback iff the name has been changed
function handleNameUpdate(newFilenameInputEl, fileId) {
var newName = newFilenameInputEl.value,
origExtension;
if (newName !== undefined && qq.trimStr(newName).length > 0) {
origExtension = getOriginalExtension(fileId);
if (origExtension !== undefined) {
newName = newName + "." + origExtension;
}
spec.onSetName(fileId, newName);
}
spec.onEditingStatusChange(fileId, false);
}
// The name has been updated if the filename edit input loses focus.
function registerInputBlurHandler(inputEl, fileId) {
inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() {
handleNameUpdate(inputEl, fileId);
});
}
// The name has been updated if the user presses enter.
function registerInputEnterKeyHandler(inputEl, fileId) {
inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) {
var code = event.keyCode || event.which;
if (code === 13) {
handleNameUpdate(inputEl, fileId);
}
});
}
qq.extend(spec, s);
spec.attachTo = spec.templating.getFileList();
qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));
qq.extend(inheritedInternalApi, {
handleFilenameEdit: function(id, target, focusInput) {
var newFilenameInputEl = spec.templating.getEditInput(id);
spec.onEditingStatusChange(id, true);
newFilenameInputEl.value = getFilenameSansExtension(id);
if (focusInput) {
newFilenameInputEl.focus();
}
registerInputBlurHandler(newFilenameInputEl, id);
registerInputEnterKeyHandler(newFilenameInputEl, id);
}
});
};
/*! 2015-04-02 */
| mit |
MiniverCheevy/voodoo | Voodoo.Patterns/ModelHelper.cs | 2687 | using System;
using System.Linq;
using System.Text;
using Voodoo.Logging;
namespace Voodoo
{
public static class ModelHelper
{
public static string ExtractUserNameFromDomainNameOrEmailAddress(string name)
{
if (string.IsNullOrWhiteSpace(name))
return string.Empty;
var slashPosition = name.IndexOf('\\');
var atPosition = name.IndexOf('@');
if (slashPosition > -1)
name = name.Substring(slashPosition + 1);
if (atPosition > -1)
name = name.Substring(0, atPosition);
return name;
}
public static string Truncate(this string s, int maxLength)
{
if (s == null)
return string.Empty;
return (s.Length > maxLength) ? s.Remove(maxLength) : s;
}
public static string FormatPhone(string phone)
{
if (string.IsNullOrWhiteSpace(phone) || phone.Length != 10)
return phone.To<string>();
return $"({phone.Substring(0, 3)}) {phone.Substring(3, 3)}-{phone.Substring(6, 4)}";
}
public static string UnformatPhone(string phone)
{
return new string(phone.To<string>().ToArray<char>().Where(char.IsDigit).ToArray());
}
public static T GetAttributeFromEnumMember<T>(object enumMember)
where T : Attribute
{
try
{
var attributeType = typeof(T);
var enumType = enumMember.GetType();
var memberInfos = enumType.GetMember(enumMember.To<string>());
if (memberInfos.Any())
{
var attribute = memberInfos.First()
.GetCustomAttributes(true)
.FirstOrDefault(c => c.GetType() == attributeType);
if (attribute == null)
return null;
return attribute.To<T>();
}
}
catch (Exception ex)
{
LogManager.Log(ex);
}
return null;
}
public static string RemoveSpecialCharacters(string value)
{
var sb = new StringBuilder();
foreach (var c in value)
if (c >= '0' && c <= '9' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')
sb.Append(c);
return sb.ToString();
}
public static string[] SplitStringIntoLines(string value)
{
return value.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
}
}
} | mit |
idle-code/ContextControl | tests/Expression.cpp | 2177 | #include "Expression.hpp"
#include "gtest/gtest.h"
using namespace ContextControl;
class ExpressionTest : public ::testing::Test {
protected:
TreeNode root_node;
virtual void SetUp(void)
{
ASSERT_EQ(0, root_node.Size());
root_node.Create(NodeKind::Integer, "int_node");
root_node["int_node"].SetValueTo(3);
root_node.Create(NodeKind::String, "string_node");
root_node["string_node"].SetValueTo("Test");
root_node.Create("branch");
root_node["branch"].Create(NodeKind::Integer, "seven");
root_node["branch.seven"].SetValueTo(7);
root_node["branch"].Create(NodeKind::Boolean, "true");
root_node["branch.true"].SetValueTo(true);
ASSERT_EQ(3, root_node.Size());
}
virtual void TearDown(void)
{
root_node.Clear();
}
};
/** ----------------------------------------------------------------------- **/
TEST_F(ExpressionTest, ExpressionContext)
{
String commant_text = "int_node: get"; // "int_node" alone should also parse
Expression parsed_expression = Expression::Parse(root_node, commant_text);
TreeNode &context = parsed_expression.Context();
EXPECT_EQ(root_node["int_node"], context);
}
TEST_F(ExpressionTest, ExpressionCommand)
{
String commant_text = "int_node: get"; // "int_node" alone should also parse
Expression parsed_expression = Expression::Parse(root_node, commant_text);
TreeNode &command = parsed_expression.Command();
EXPECT_EQ(NodeKind::String, command.Type());
EXPECT_EQ("get", command.GetValueAs<String>());
}
TEST_F(ExpressionTest, EvaluateScalar)
{
String commant_text = "int_node: get"; // "int_node" alone should also parse
Expression parsed_expression = Expression::Parse(root_node, commant_text);
TreeNode result = parsed_expression.Evaluate();
EXPECT_EQ(NodeKind::Integer, result.Type());
EXPECT_EQ(3, result.GetValueAs<int>());
}
/*
* .: {int_node: get} -> 3
* .int_node: {get} -> 3
* .: {int_node} -> 3
* {int_node get} -> error: No "int_node" command in context .
* .network.eth0.ip get
* .network.eth0.ip: get
* {.: list}: sort.descending.by.name | ${{size} - 1}
* {int_node: get} + 2 -> 5
* {int_node} + 2 -> 5
* int_node + 2 -> 5
*/
| mit |
rednaxelafx/jvm.go | jvmgo/jvm/rtda/class/descriptor_parser.go | 2611 | package class
import (
"strings"
)
type MemberDescriptorParser struct {
descriptor string
offset int
md *MethodDescriptor
}
func (self *MemberDescriptorParser) parse() *MethodDescriptor {
self.md = &MethodDescriptor{}
self.md.d = self.descriptor
self.startParams()
self.parseParamTypes()
self.endParams()
self.parseReturnType()
self.finish()
return self.md
}
func (self *MemberDescriptorParser) startParams() {
if self.readUint8() != '(' {
self.causePanic()
}
}
func (self *MemberDescriptorParser) endParams() {
if self.readUint8() != ')' {
self.causePanic()
}
}
func (self *MemberDescriptorParser) finish() {
if self.offset != len(self.descriptor) {
self.causePanic()
}
}
func (self *MemberDescriptorParser) causePanic() {
panic("BAD descriptor: " + self.descriptor)
}
func (self *MemberDescriptorParser) readUint8() uint8 {
b := self.descriptor[self.offset]
self.offset++
return b
}
func (self *MemberDescriptorParser) unreadUint8() {
self.offset--
}
func (self *MemberDescriptorParser) parseParamTypes() {
for {
t := self.parseFieldType()
if t != nil {
self.md.addParameterType(t)
} else {
break
}
}
}
func (self *MemberDescriptorParser) parseReturnType() {
t := self.parseFieldType()
if t != nil {
self.md.returnType = t
} else {
self.causePanic()
}
}
func (self *MemberDescriptorParser) parseFieldType() *FieldType {
switch self.readUint8() {
case 'B':
return baseTypeB
case 'C':
return baseTypeC
case 'D':
return baseTypeD
case 'F':
return baseTypeF
case 'I':
return baseTypeI
case 'J':
return baseTypeJ
case 'S':
return baseTypeS
case 'Z':
return baseTypeZ
case 'V':
return baseTypeV
case 'L':
return self.parseObjectType()
case '[':
return self.parseArrayType()
default:
self.unreadUint8()
return nil
}
}
func (self *MemberDescriptorParser) parseObjectType() *FieldType {
unread := self.descriptor[self.offset:]
semicolonIndex := strings.IndexRune(unread, ';')
if semicolonIndex == -1 {
self.causePanic()
return nil
} else {
objStart := self.offset - 1
objEnd := self.offset + semicolonIndex + 1
self.offset = objEnd
descriptor := self.descriptor[objStart:objEnd]
return &FieldType{descriptor}
}
}
func (self *MemberDescriptorParser) parseArrayType() *FieldType {
arrStart := self.offset - 1
self.parseFieldType()
arrEnd := self.offset
descriptor := self.descriptor[arrStart:arrEnd]
return &FieldType{descriptor}
}
func parseMethodDescriptor(descriptor string) *MethodDescriptor {
parser := &MemberDescriptorParser{descriptor: descriptor}
return parser.parse()
}
| mit |
ngocson8b/6jar | fuel/app/config/config.php | 8654 | <?php
/**
* Part of the Fuel framework.
*
* @package Fuel
* @version 1.8
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2016 Fuel Development Team
* @link http://fuelphp.com
*/
return array(
/**
* base_url - The base URL of the application.
* MUST contain a trailing slash (/)
*
* You can set this to a full or relative URL:
*
* 'base_url' => '/foo/',
* 'base_url' => 'http://foo.com/'
*
* Set this to null to have it automatically detected.
*/
// 'base_url' => null,
/**
* url_suffix - Any suffix that needs to be added to
* URL's generated by Fuel. If the suffix is an extension,
* make sure to include the dot
*
* 'url_suffix' => '.html',
*
* Set this to an empty string if no suffix is used
*/
// 'url_suffix' => '',
/**
* index_file - The name of the main bootstrap file.
*
* Set this to 'index.php if you don't use URL rewriting
*/
// 'index_file' => false,
// 'profiling' => false,
/**
* Default location for the file cache
*/
// 'cache_dir' => APPPATH.'cache/',
/**
* Settings for the file finder cache (the Cache class has it's own config!)
*/
// 'caching' => false,
// 'cache_lifetime' => 3600, // In Seconds
/**
* Callback to use with ob_start(), set this to 'ob_gzhandler' for gzip encoding of output
*/
// 'ob_callback' => null,
// 'errors' => array(
// Which errors should we show, but continue execution? You can add the following:
// E_NOTICE, E_WARNING, E_DEPRECATED, E_STRICT to mimic PHP's default behaviour
// (which is to continue on non-fatal errors). We consider this bad practice.
// 'continue_on' => array(),
// How many errors should we show before we stop showing them? (prevents out-of-memory errors)
// 'throttle' => 10,
// Should notices from Error::notice() be shown?
// 'notices' => true,
// Render previous contents or show it as HTML?
// 'render_prior' => false,
// ),
/**
* Localization & internationalization settings
*/
// 'language' => 'en', // Default language
// 'language_fallback' => 'en', // Fallback language when file isn't available for default language
// 'locale' => 'en_US', // PHP set_locale() setting, null to not set
/**
* Internal string encoding charset
*/
// 'encoding' => 'UTF-8',
/**
* DateTime settings
*
* server_gmt_offset in seconds the server offset from gmt timestamp when time() is used
* default_timezone optional, if you want to change the server's default timezone
*/
// 'server_gmt_offset' => 0,
// 'default_timezone' => null,
/**
* Logging Threshold. Can be set to any of the following:
*
* Fuel::L_NONE
* Fuel::L_ERROR
* Fuel::L_WARNING
* Fuel::L_DEBUG
* Fuel::L_INFO
* Fuel::L_ALL
*/
// 'log_threshold' => Fuel::L_WARNING,
// 'log_path' => APPPATH.'logs/',
// 'log_date_format' => 'Y-m-d H:i:s',
/**
* Security settings
*/
'security' => array(
// 'csrf_autoload' => false,
// 'csrf_autoload_methods' => array('post', 'put', 'delete'),
// 'csrf_bad_request_on_fail' => false,
// 'csrf_auto_token' => false,
// 'csrf_token_key' => 'fuel_csrf_token',
// 'csrf_expiration' => 0,
/**
* A salt to make sure the generated security tokens are not predictable
*/
// 'token_salt' => 'put your salt value here to make the token more secure',
/**
* Allow the Input class to use X headers when present
*
* Examples of these are HTTP_X_FORWARDED_FOR and HTTP_X_FORWARDED_PROTO, which
* can be faked which could have security implications
*/
// 'allow_x_headers' => false,
/**
* This input filter can be any normal PHP function as well as 'xss_clean'
*
* WARNING: Using xss_clean will cause a performance hit.
* How much is dependant on how much input data there is.
*/
'uri_filter' => array('htmlentities'),
/**
* This input filter can be any normal PHP function as well as 'xss_clean'
*
* WARNING: Using xss_clean will cause a performance hit.
* How much is dependant on how much input data there is.
*/
// 'input_filter' => array(),
/**
* This output filter can be any normal PHP function as well as 'xss_clean'
*
* WARNING: Using xss_clean will cause a performance hit.
* How much is dependant on how much input data there is.
*/
'output_filter' => array('Security::htmlentities'),
/**
* Encoding mechanism to use on htmlentities()
*/
// 'htmlentities_flags' => ENT_QUOTES,
/**
* Whether to encode HTML entities as well
*/
// 'htmlentities_double_encode' => false,
/**
* Whether to automatically filter view data
*/
// 'auto_filter_output' => true,
/**
* With output encoding switched on all objects passed will be converted to strings or
* throw exceptions unless they are instances of the classes in this array.
*/
'whitelisted_classes' => array(
'Fuel\\Core\\Presenter',
'Fuel\\Core\\Response',
'Fuel\\Core\\View',
'Fuel\\Core\\ViewModel',
'Closure',
),
),
/**
* Cookie settings
*/
// 'cookie' => array(
// Number of seconds before the cookie expires
// 'expiration' => 0,
// Restrict the path that the cookie is available to
// 'path' => '/',
// Restrict the domain that the cookie is available to
// 'domain' => null,
// Only transmit cookies over secure connections
// 'secure' => false,
// Only transmit cookies over HTTP, disabling Javascript access
// 'http_only' => false,
// ),
/**
* Validation settings
*/
// 'validation' => array(
/**
* Whether to fallback to global when a value is not found in the input array.
*/
// 'global_input_fallback' => true,
// ),
/**
* Controller class prefix
*/
// 'controller_prefix' => 'Controller_',
/**
* Routing settings
*/
// 'routing' => array(
/**
* Whether URI routing is case sensitive or not
*/
// 'case_sensitive' => true,
/**
* Whether to strip the extension
*/
// 'strip_extension' => true,
// ),
/**
* To enable you to split up your application into modules which can be
* routed by the first uri segment you have to define their basepaths
* here. By default empty, but to use them you can add something
* like this:
* array(APPPATH.'modules'.DS)
*
* Paths MUST end with a directory separator (the DS constant)!
*/
// 'module_paths' => array(
// //APPPATH.'modules'.DS
// ),
/**
* To enable you to split up your additions to the framework, packages are
* used. You can define the basepaths for your packages here. By default
* empty, but to use them you can add something like this:
* array(APPPATH.'modules'.DS)
*
* Paths MUST end with a directory separator (the DS constant)!
*/
'package_paths' => array(
PKGPATH,
),
/**************************************************************************/
/* Always Load */
/**************************************************************************/
'always_load' => array(
/**
* These packages are loaded on Fuel's startup.
* You can specify them in the following manner:
*
* array('auth'); // This will assume the packages are in PKGPATH
*
* // Use this format to specify the path to the package explicitly
* array(
* array('auth' => PKGPATH.'auth/')
* );
*/
'packages' => array(
'orm',
'auth',
),
),
/**
* These modules are always loaded on Fuel's startup. You can specify them
* in the following manner:
*
* array('module_name');
*
* A path must be set in module_paths for this to work.
*/
// 'modules' => array(),
/**
* Classes to autoload & initialize even when not used
*/
// 'classes' => array(),
/**
* Configs to autoload
*
* Examples: if you want to load 'session' config into a group 'session' you only have to
* add 'session'. If you want to add it to another group (example: 'auth') you have to
* add it like 'session' => 'auth'.
* If you don't want the config in a group use null as groupname.
*/
// 'config' => array(),
/**
* Language files to autoload
*
* Examples: if you want to load 'validation' lang into a group 'validation' you only have to
* add 'validation'. If you want to add it to another group (example: 'forms') you have to
* add it like 'validation' => 'forms'.
* If you don't want the lang in a group use null as groupname.
*/
// 'language' => array(),
// ),
);
| mit |